diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000000..63d88b10f38 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,54 @@ +--- +name: Bug report +about: Please fill in the bug report carefully +title: '' +labels: '' +assignees: '' + +--- + +Make your question, not a Statement, inclusive. Include all pertinent information: + +What you are trying to do? +Describe your system( Hardware, computer, O/S, core version, environment). +Describe what is failing. +Show the shortest possible code that will duplicate the error. +Show the EXACT error message(it doesn't work is not enough). +All of this work on your part shows us that you have worked to solve YOUR problem. The more complete your issue posting is, the more likely someone will volunteer their time to help you. + +If you have a Guru Meditation Error or Backtrace, ***please decode it***: +https://github.com/me-no-dev/EspExceptionDecoder + +----------------------------- Remove above ----------------------------- + + +### Hardware: +Board: ?ESP32 Dev Module? ?node32? ?ttgo_lora? +Core Installation version: ?1.0.0? ?1.0.1-rc4? ?1.0.1? ?1.0.1-git? ?1.0.2? ?1.0.3? +IDE name: ?Arduino IDE? ?Platform.io? ?IDF component? +Flash Frequency: ?40Mhz? +PSRAM enabled: ?no? ?yes? +Upload Speed: ?115200? +Computer OS: ?Windows 10? ?Mac OSX? ?Ubuntu? + +### Description: +Describe your problem here + + +### Sketch: (leave the backquotes for [code formatting](https://help.github.com/articles/creating-and-highlighting-code-blocks/)) +```cpp + +//Change the code below by your sketch +#include + +void setup() { +} + +void loop() { +} +``` + +### Debug Messages: +``` +Enable Core debug level: Debug on tools menu of Arduino IDE, then put the serial output here +``` diff --git a/.github/scripts/check-cmakelists.sh b/.github/scripts/check-cmakelists.sh new file mode 100755 index 00000000000..88eb3dfbc4b --- /dev/null +++ b/.github/scripts/check-cmakelists.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# +# This script is for Travis. It checks all non-examples source files in libraries/ and cores/ are listed in +# CMakeLists.txt for the cmake-based IDF component +# +# If you see an error running this script, edit CMakeLists.txt and add any new source files into your PR +# + +set -e + +# pull all submodules +git submodule update --init --recursive + +# find all source files in repo +REPO_SRCS=`find cores/esp32/ libraries/ -name 'examples' -prune -o -name '*.c' -print -o -name '*.cpp' -print | sort` + +# find all source files named in CMakeLists.txt COMPONENT_SRCS +CMAKE_SRCS=`cmake --trace-expand -C CMakeLists.txt 2>&1 | grep COMPONENT_SRCS | sed 's/.\+COMPONENT_SRCS //' | sed 's/ )//' | tr ' ;' '\n' | sort` + +if ! diff -u0 --label "Repo Files" --label "COMPONENT_SRCS" <(echo "$REPO_SRCS") <(echo "$CMAKE_SRCS"); then + echo "Source files in repo (-) and source files in CMakeLists.txt (+) don't match" + echo "Edit CMakeLists.txt as appropriate to add/remove source files from COMPONENT_SRCS" + exit 1 +fi + +echo "CMakeLists.txt and repo source files match" +exit 0 diff --git a/.github/scripts/install-arduino-core-esp32.sh b/.github/scripts/install-arduino-core-esp32.sh new file mode 100755 index 00000000000..cf1026d6a71 --- /dev/null +++ b/.github/scripts/install-arduino-core-esp32.sh @@ -0,0 +1,36 @@ +#!/bin/bash + +export ARDUINO_ESP32_PATH="$ARDUINO_USR_PATH/hardware/espressif/esp32" +if [ ! -d "$ARDUINO_ESP32_PATH" ]; then + echo "Installing ESP32 Arduino Core ..." + script_init_path="$PWD" + mkdir -p "$ARDUINO_USR_PATH/hardware/espressif" + cd "$ARDUINO_USR_PATH/hardware/espressif" + + echo "Installing Python Serial ..." + pip install pyserial > /dev/null + + if [ "$OS_IS_WINDOWS" == "1" ]; then + echo "Installing Python Requests ..." + pip install requests > /dev/null + fi + + if [ "$GITHUB_REPOSITORY" == "espressif/arduino-esp32" ]; then + echo "Linking Core..." + ln -s $GITHUB_WORKSPACE esp32 + else + echo "Cloning Core Repository..." + git clone https://github.com/espressif/arduino-esp32.git esp32 > /dev/null 2>&1 + fi + + echo "Updating Submodules ..." + cd esp32 + git submodule update --init --recursive > /dev/null 2>&1 + + echo "Installing Platform Tools ..." + cd tools && python get.py + cd $script_init_path + + echo "ESP32 Arduino has been installed in '$ARDUINO_ESP32_PATH'" + echo "" +fi diff --git a/.github/scripts/install-arduino-ide.sh b/.github/scripts/install-arduino-ide.sh new file mode 100755 index 00000000000..7e268b1ff7e --- /dev/null +++ b/.github/scripts/install-arduino-ide.sh @@ -0,0 +1,220 @@ +#!/bin/bash + +#OSTYPE: 'linux-gnu', ARCH: 'x86_64' => linux64 +#OSTYPE: 'msys', ARCH: 'x86_64' => win32 +#OSTYPE: 'darwin18', ARCH: 'i386' => macos + +OSBITS=`arch` +if [[ "$OSTYPE" == "linux"* ]]; then + export OS_IS_LINUX="1" + ARCHIVE_FORMAT="tar.xz" + if [[ "$OSBITS" == "i686" ]]; then + OS_NAME="linux32" + elif [[ "$OSBITS" == "x86_64" ]]; then + OS_NAME="linux64" + elif [[ "$OSBITS" == "armv7l" || "$OSBITS" == "aarch64" ]]; then + OS_NAME="linuxarm" + else + OS_NAME="$OSTYPE-$OSBITS" + echo "Unknown OS '$OS_NAME'" + exit 1 + fi +elif [[ "$OSTYPE" == "darwin"* ]]; then + export OS_IS_MACOS="1" + ARCHIVE_FORMAT="zip" + OS_NAME="macosx" +elif [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then + export OS_IS_WINDOWS="1" + ARCHIVE_FORMAT="zip" + OS_NAME="windows" +else + OS_NAME="$OSTYPE-$OSBITS" + echo "Unknown OS '$OS_NAME'" + exit 1 +fi +export OS_NAME + +ARDUINO_BUILD_DIR="$HOME/.arduino/build.tmp" +ARDUINO_CACHE_DIR="$HOME/.arduino/cache.tmp" + +if [ "$OS_IS_MACOS" == "1" ]; then + export ARDUINO_IDE_PATH="/Applications/Arduino.app/Contents/Java" + export ARDUINO_USR_PATH="$HOME/Documents/Arduino" +elif [ "$OS_IS_WINDOWS" == "1" ]; then + export ARDUINO_IDE_PATH="$HOME/arduino_ide" + export ARDUINO_USR_PATH="$HOME/Documents/Arduino" +else + export ARDUINO_IDE_PATH="$HOME/arduino_ide" + export ARDUINO_USR_PATH="$HOME/Arduino" +fi + +if [ ! -d "$ARDUINO_IDE_PATH" ]; then + echo "Installing Arduino IDE on $OS_NAME ..." + echo "Downloading 'arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT' to 'arduino.$ARCHIVE_FORMAT' ..." + if [ "$OS_IS_LINUX" == "1" ]; then + wget -O "arduino.$ARCHIVE_FORMAT" "https://www.arduino.cc/download.php?f=/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1 + echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..." + tar xf "arduino.$ARCHIVE_FORMAT" > /dev/null + mv arduino-nightly "$ARDUINO_IDE_PATH" + else + curl -o "arduino.$ARCHIVE_FORMAT" -L "https://www.arduino.cc/download.php?f=/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1 + echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..." + unzip "arduino.$ARCHIVE_FORMAT" > /dev/null + if [ "$OS_IS_MACOS" == "1" ]; then + mv "Arduino.app" "/Applications/Arduino.app" + else + mv arduino-nightly "$ARDUINO_IDE_PATH" + fi + fi + rm -rf "arduino.$ARCHIVE_FORMAT" + + mkdir -p "$ARDUINO_USR_PATH/libraries" + mkdir -p "$ARDUINO_USR_PATH/hardware" + + echo "Arduino IDE Installed in '$ARDUINO_IDE_PATH'" + echo "" +fi + +function build_sketch(){ # build_sketch [extra-options] + if [ "$#" -lt 2 ]; then + echo "ERROR: Illegal number of parameters" + echo "USAGE: build_sketch [extra-options]" + return 1 + fi + + local fqbn="$1" + local sketch="$2" + local xtra_opts="$3" + local win_opts="" + if [ "$OS_IS_WINDOWS" == "1" ]; then + local ctags_version=`ls "$ARDUINO_IDE_PATH/tools-builder/ctags/"` + local preprocessor_version=`ls "$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/"` + win_opts="-prefs=runtime.tools.ctags.path=$ARDUINO_IDE_PATH/tools-builder/ctags/$ctags_version -prefs=runtime.tools.arduino-preprocessor.path=$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/$preprocessor_version" + fi + + echo "" + echo "Compiling '"$(basename "$sketch")"' ..." + mkdir -p "$ARDUINO_BUILD_DIR" + mkdir -p "$ARDUINO_CACHE_DIR" + $ARDUINO_IDE_PATH/arduino-builder -compile -logger=human -core-api-version=10810 \ + -fqbn=$fqbn \ + -warnings="all" \ + -tools "$ARDUINO_IDE_PATH/tools-builder" \ + -tools "$ARDUINO_IDE_PATH/tools" \ + -built-in-libraries "$ARDUINO_IDE_PATH/libraries" \ + -hardware "$ARDUINO_IDE_PATH/hardware" \ + -hardware "$ARDUINO_USR_PATH/hardware" \ + -libraries "$ARDUINO_USR_PATH/libraries" \ + -build-cache "$ARDUINO_CACHE_DIR" \ + -build-path "$ARDUINO_BUILD_DIR" \ + $win_opts $xtra_opts "$sketch" +} + +function count_sketches() # count_sketches +{ + local examples="$1" + rm -rf sketches.txt + if [ ! -d "$examples" ]; then + touch sketches.txt + return 0 + fi + local sketches=$(find $examples -name *.ino) + local sketchnum=0 + for sketch in $sketches; do + local sketchdir=$(dirname $sketch) + local sketchdirname=$(basename $sketchdir) + local sketchname=$(basename $sketch) + if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then + continue + fi; + if [[ -f "$sketchdir/.test.skip" ]]; then + continue + fi + echo $sketch >> sketches.txt + sketchnum=$(($sketchnum + 1)) + done + return $sketchnum +} + +function build_sketches() # build_sketches [extra-options] +{ + local fqbn=$1 + local examples=$2 + local chunk_idex=$3 + local chunks_num=$4 + local xtra_opts=$5 + + if [ "$#" -lt 2 ]; then + echo "ERROR: Illegal number of parameters" + echo "USAGE: build_sketches [ ] [extra-options]" + return 1 + fi + + if [ "$#" -lt 4 ]; then + chunk_idex="0" + chunks_num="1" + xtra_opts=$3 + fi + + if [ "$chunks_num" -le 0 ]; then + echo "ERROR: Chunks count must be positive number" + return 1 + fi + if [ "$chunk_idex" -ge "$chunks_num" ]; then + echo "ERROR: Chunk index must be less than chunks count" + return 1 + fi + + set +e + count_sketches "$examples" + local sketchcount=$? + set -e + local sketches=$(cat sketches.txt) + rm -rf sketches.txt + + local chunk_size=$(( $sketchcount / $chunks_num )) + local all_chunks=$(( $chunks_num * $chunk_size )) + if [ "$all_chunks" -lt "$sketchcount" ]; then + chunk_size=$(( $chunk_size + 1 )) + fi + + local start_index=$(( $chunk_idex * $chunk_size )) + if [ "$sketchcount" -le "$start_index" ]; then + echo "Skipping job" + return 0 + fi + + local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size )) + if [ "$end_index" -gt "$sketchcount" ]; then + end_index=$sketchcount + fi + + local start_num=$(( $start_index + 1 )) + echo "Found $sketchcount Sketches"; + echo "Chunk Count : $chunks_num" + echo "Chunk Size : $chunk_size" + echo "Start Sketch: $start_num" + echo "End Sketch : $end_index" + + local sketchnum=0 + for sketch in $sketches; do + local sketchdir=$(dirname $sketch) + local sketchdirname=$(basename $sketchdir) + local sketchname=$(basename $sketch) + if [ "${sketchdirname}.ino" != "$sketchname" ] \ + || [ -f "$sketchdir/.test.skip" ]; then + continue + fi + sketchnum=$(($sketchnum + 1)) + if [ "$sketchnum" -le "$start_index" ] \ + || [ "$sketchnum" -gt "$end_index" ]; then + continue + fi + build_sketch "$fqbn" "$sketch" "$xtra_opts" + local result=$? + if [ $result -ne 0 ]; then + return $result + fi + done + return 0 +} diff --git a/.github/scripts/install-platformio-esp32.sh b/.github/scripts/install-platformio-esp32.sh new file mode 100755 index 00000000000..ce6de4a2ef4 --- /dev/null +++ b/.github/scripts/install-platformio-esp32.sh @@ -0,0 +1,153 @@ +#!/bin/bash + +export PLATFORMIO_ESP32_PATH="$HOME/.platformio/packages/framework-arduinoespressif32" + +echo "Installing Python Wheel ..." +pip install wheel > /dev/null 2>&1 + +echo "Installing PlatformIO ..." +pip install -U https://github.com/platformio/platformio/archive/develop.zip > /dev/null 2>&1 + +echo "Installing Platform ESP32 ..." +python -m platformio platform install https://github.com/platformio/platform-espressif32.git#feature/stage > /dev/null 2>&1 + +echo "Replacing the framework version ..." +if [[ "$OSTYPE" == "darwin"* ]]; then + sed 's/https:\/\/github\.com\/espressif\/arduino-esp32\.git/*/' "$HOME/.platformio/platforms/espressif32/platform.json" > "platform.json" + mv -f "platform.json" "$HOME/.platformio/platforms/espressif32/platform.json" +else + sed -i 's/https:\/\/github\.com\/espressif\/arduino-esp32\.git/*/' "$HOME/.platformio/platforms/espressif32/platform.json" +fi + +if [ "$GITHUB_REPOSITORY" == "espressif/arduino-esp32" ]; then + echo "Linking Core..." + ln -s $GITHUB_WORKSPACE "$PLATFORMIO_ESP32_PATH" +else + echo "Cloning Core Repository ..." + git clone https://github.com/espressif/arduino-esp32.git "$PLATFORMIO_ESP32_PATH" > /dev/null 2>&1 +fi + +echo "PlatformIO for ESP32 has been installed" +echo "" + +function build_pio_sketch(){ # build_pio_sketch + if [ "$#" -lt 2 ]; then + echo "ERROR: Illegal number of parameters" + echo "USAGE: build_pio_sketch " + return 1 + fi + + local board="$1" + local sketch="$2" + local sketch_dir=$(dirname "$sketch") + echo "" + echo "Compiling '"$(basename "$sketch")"' ..." + python -m platformio ci --board "$board" "$sketch_dir" --project-option="board_build.partitions = huge_app.csv" +} + +function count_sketches() # count_sketches +{ + local examples="$1" + rm -rf sketches.txt + if [ ! -d "$examples" ]; then + touch sketches.txt + return 0 + fi + local sketches=$(find $examples -name *.ino) + local sketchnum=0 + for sketch in $sketches; do + local sketchdir=$(dirname $sketch) + local sketchdirname=$(basename $sketchdir) + local sketchname=$(basename $sketch) + if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then + continue + fi; + if [[ -f "$sketchdir/.test.skip" ]]; then + continue + fi + echo $sketch >> sketches.txt + sketchnum=$(($sketchnum + 1)) + done + return $sketchnum +} + +function build_pio_sketches() # build_pio_sketches +{ + if [ "$#" -lt 2 ]; then + echo "ERROR: Illegal number of parameters" + echo "USAGE: build_pio_sketches [ ]" + return 1 + fi + + local board=$1 + local examples=$2 + local chunk_idex=$3 + local chunks_num=$4 + + if [ "$#" -lt 4 ]; then + chunk_idex="0" + chunks_num="1" + fi + + if [ "$chunks_num" -le 0 ]; then + echo "ERROR: Chunks count must be positive number" + return 1 + fi + if [ "$chunk_idex" -ge "$chunks_num" ]; then + echo "ERROR: Chunk index must be less than chunks count" + return 1 + fi + + set +e + count_sketches "$examples" + local sketchcount=$? + set -e + local sketches=$(cat sketches.txt) + rm -rf sketches.txt + + local chunk_size=$(( $sketchcount / $chunks_num )) + local all_chunks=$(( $chunks_num * $chunk_size )) + if [ "$all_chunks" -lt "$sketchcount" ]; then + chunk_size=$(( $chunk_size + 1 )) + fi + + local start_index=$(( $chunk_idex * $chunk_size )) + if [ "$sketchcount" -le "$start_index" ]; then + echo "Skipping job" + return 0 + fi + + local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size )) + if [ "$end_index" -gt "$sketchcount" ]; then + end_index=$sketchcount + fi + + local start_num=$(( $start_index + 1 )) + echo "Found $sketchcount Sketches"; + echo "Chunk Count : $chunks_num" + echo "Chunk Size : $chunk_size" + echo "Start Sketch: $start_num" + echo "End Sketch : $end_index" + + local sketchnum=0 + for sketch in $sketches; do + local sketchdir=$(dirname $sketch) + local sketchdirname=$(basename $sketchdir) + local sketchname=$(basename $sketch) + if [ "${sketchdirname}.ino" != "$sketchname" ] \ + || [ -f "$sketchdir/.test.skip" ]; then + continue + fi + sketchnum=$(($sketchnum + 1)) + if [ "$sketchnum" -le "$start_index" ] \ + || [ "$sketchnum" -gt "$end_index" ]; then + continue + fi + build_pio_sketch "$board" "$sketch" + local result=$? + if [ $result -ne 0 ]; then + return $result + fi + done + return 0 +} diff --git a/.github/scripts/merge_packages.py b/.github/scripts/merge_packages.py new file mode 100755 index 00000000000..53fbbd9b0a9 --- /dev/null +++ b/.github/scripts/merge_packages.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# This script merges two Arduino Board Manager package json files. +# Usage: +# python merge_packages.py package_esp8266com_index.json version/new/package_esp8266com_index.json +# Written by Ivan Grokhotkov, 2015 +# +from __future__ import print_function +from distutils.version import LooseVersion +import re +import json +import sys + +def load_package(filename): + pkg = json.load(open(filename))['packages'][0] + print("Loaded package {0} from {1}".format(pkg['name'], filename), file=sys.stderr) + print("{0} platform(s), {1} tools".format(len(pkg['platforms']), len(pkg['tools'])), file=sys.stderr) + return pkg + +def merge_objects(versions, obj): + for o in obj: + name = o['name'].encode('ascii') + ver = o['version'].encode('ascii') + if not name in versions: + print("found new object, {0}".format(name), file=sys.stderr) + versions[name] = {} + if not ver in versions[name]: + print("found new version {0} for object {1}".format(ver, name), file=sys.stderr) + versions[name][ver] = o + return versions + +# Normalize ESP release version string (x.x.x) by adding '-rc' (x.x.x-rc9223372036854775807) to ensure having REL above any RC +# Dummy approach, functional anyway for current ESP package versioning (unlike NormalizedVersion/LooseVersion/StrictVersion & similar crap) +def pkgVersionNormalized(versionString): + + verStr = str(versionString) + verParts = re.split('\.|-rc', verStr, flags=re.IGNORECASE) + + if len(verParts) == 3: + if (sys.version_info > (3, 0)): # Python 3 + verStr = str(versionString) + '-rc' + str(sys.maxsize) + else: # Python 2 + verStr = str(versionString) + '-rc' + str(sys.maxint) + + elif len(verParts) != 4: + print("pkgVersionNormalized WARNING: unexpected version format: {0})".format(verStr), file=sys.stderr) + + return verStr + + +def main(args): + if len(args) < 3: + print("Usage: {0} ".format(args[0]), file=sys.stderr) + return 1 + + tools = {} + platforms = {} + pkg1 = load_package(args[1]) + tools = merge_objects(tools, pkg1['tools']); + platforms = merge_objects(platforms, pkg1['platforms']); + pkg2 = load_package(args[2]) + tools = merge_objects(tools, pkg2['tools']); + platforms = merge_objects(platforms, pkg2['platforms']); + + pkg1['tools'] = [] + pkg1['platforms'] = [] + + for name in tools: + for version in tools[name]: + print("Adding tool {0}-{1}".format(name, version), file=sys.stderr) + pkg1['tools'].append(tools[name][version]) + + for name in platforms: + for version in platforms[name]: + print("Adding platform {0}-{1}".format(name, version), file=sys.stderr) + pkg1['platforms'].append(platforms[name][version]) + + pkg1['platforms'] = sorted(pkg1['platforms'], key=lambda k: LooseVersion(pkgVersionNormalized(k['version'])), reverse=True) + + json.dump({'packages':[pkg1]}, sys.stdout, indent=2) + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/.github/scripts/on-pages.sh b/.github/scripts/on-pages.sh new file mode 100644 index 00000000000..1b265f91adb --- /dev/null +++ b/.github/scripts/on-pages.sh @@ -0,0 +1,131 @@ +#/bin/bash +set -e + +function get_file_size(){ + local file="$1" + if [[ "$OSTYPE" == "darwin"* ]]; then + eval `stat -s "$file"` + local res="$?" + echo "$st_size" + return $res + else + stat --printf="%s" "$file" + return $? + fi +} + +#git_remove_from_pages +function git_remove_from_pages(){ + local path=$1 + local info=`curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.object+json" -X GET "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path?ref=gh-pages"` + local type=`echo "$info" | jq -r '.type'` + if [ ! $type == "file" ]; then + if [ ! $type == "null" ]; then + echo "Wrong type '$type'" + else + echo "File is not on Pages" + fi + return 0 + fi + local sha=`echo "$info" | jq -r '.sha'` + local message="Deleting "$(basename $path) + local json="{\"branch\":\"gh-pages\",\"message\":\"$message\",\"sha\":\"$sha\"}" + echo "$json" | curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.raw+json" -X DELETE --data @- "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path" +} + +function git_upload_to_pages(){ + local path=$1 + local src=$2 + + if [ ! -f "$src" ]; then + >&2 echo "Input is not a file! Aborting..." + return 1 + fi + + local info=`curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.object+json" -X GET "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path?ref=gh-pages"` + local type=`echo "$info" | jq -r '.type'` + local message=$(basename $path) + local sha="" + local content="" + + if [ $type == "file" ]; then + sha=`echo "$info" | jq -r '.sha'` + sha=",\"sha\":\"$sha\"" + message="Updating $message" + elif [ ! $type == "null" ]; then + >&2 echo "Wrong type '$type'" + return 1 + else + message="Creating $message" + fi + + content=`base64 -i "$src"` + data="{\"branch\":\"gh-pages\",\"message\":\"$message\",\"content\":\"$content\"$sha}" + + echo "$data" | curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.raw+json" -X PUT --data @- "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path" +} + +function git_safe_upload_to_pages(){ + local path=$1 + local file="$2" + local name=$(basename "$file") + local size=`get_file_size "$file"` + local upload_res=`git_upload_to_pages "$path" "$file"` + if [ $? -ne 0 ]; then + >&2 echo "ERROR: Failed to upload '$name' ($?)" + return 1 + fi + up_size=`echo "$upload_res" | jq -r '.content.size'` + if [ $up_size -ne $size ]; then + >&2 echo "ERROR: Uploaded size does not match! $up_size != $size" + #git_delete_asset + return 1 + fi + echo "$upload_res" | jq -r '.content.download_url' + return $? +} + +EVENT_JSON=`cat $GITHUB_EVENT_PATH` + +pages_added=`echo "$EVENT_JSON" | jq -r '.commits[].added[]'` +pages_modified=`echo "$EVENT_JSON" | jq -r '.commits[].modified[]'` +pages_removed=`echo "$EVENT_JSON" | jq -r '.commits[].removed[]'` + +for page in $pages_added; do + if [[ $page != "README.md" && $page != "docs/"* ]]; then + continue + fi + echo "Adding '$page' to pages ..." + if [[ $page == "README.md" ]]; then + git_safe_upload_to_pages "index.md" "README.md" + else + git_safe_upload_to_pages "$page" "$page" + fi +done + +for page in $pages_modified; do + if [[ $page != "README.md" && $page != "docs/"* ]]; then + continue + fi + echo "Modifying '$page' ..." + if [[ $page == "README.md" ]]; then + git_safe_upload_to_pages "index.md" "README.md" + else + git_safe_upload_to_pages "$page" "$page" + fi +done + +for page in $pages_removed; do + if [[ $page != "README.md" && $page != "docs/"* ]]; then + continue + fi + echo "Removing '$page' from pages ..." + if [[ $page == "README.md" ]]; then + git_remove_from_pages "README.md" > /dev/null + else + git_remove_from_pages "$page" > /dev/null + fi +done + +echo +echo "DONE!" diff --git a/.github/scripts/on-push.sh b/.github/scripts/on-push.sh new file mode 100755 index 00000000000..e0e14ec2b26 --- /dev/null +++ b/.github/scripts/on-push.sh @@ -0,0 +1,71 @@ +#!/bin/bash + +set -e + +if [ ! -z "$TRAVIS_TAG" ]; then + echo "Skipping Test: Tagged build" + exit 0 +fi + +if [ ! -z "$GITHUB_WORKSPACE" ]; then + export TRAVIS_BUILD_DIR="$GITHUB_WORKSPACE" + export TRAVIS_REPO_SLUG="$GITHUB_REPOSITORY" +elif [ ! -z "$TRAVIS_BUILD_DIR" ]; then + export GITHUB_WORKSPACE="$TRAVIS_BUILD_DIR" + export GITHUB_REPOSITORY="$TRAVIS_REPO_SLUG" +else + export GITHUB_WORKSPACE="$PWD" + export GITHUB_REPOSITORY="espressif/arduino-esp32" +fi + +CHUNK_INDEX=$1 +CHUNKS_CNT=$2 +BUILD_PIO=0 +if [ "$#" -lt 2 ] || [ "$CHUNKS_CNT" -le 0 ]; then + CHUNK_INDEX=0 + CHUNKS_CNT=1 +elif [ "$CHUNK_INDEX" -gt "$CHUNKS_CNT" ]; then + CHUNK_INDEX=$CHUNKS_CNT +elif [ "$CHUNK_INDEX" -eq "$CHUNKS_CNT" ]; then + BUILD_PIO=1 +fi + +echo "Updating submodules ..." +git -C "$GITHUB_WORKSPACE" submodule update --init --recursive > /dev/null 2>&1 + +if [ "$BUILD_PIO" -eq 0 ]; then + # ArduinoIDE Test + FQBN="espressif:esp32:esp32:PSRAM=enabled,PartitionScheme=huge_app" + source ./.github/scripts/install-arduino-ide.sh + source ./.github/scripts/install-arduino-core-esp32.sh + if [ "$OS_IS_WINDOWS" == "1" ]; then + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/BLE/examples/BLE_server/BLE_server.ino" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/AzureIoT/examples/GetStarted/GetStarted.ino" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.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" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/BLE/examples/BLE_server/BLE_server.ino" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/AzureIoT/examples/GetStarted/GetStarted.ino" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino" + else + # CMake Test + if [ "$CHUNK_INDEX" -eq 0 ]; then + bash "$ARDUINO_ESP32_PATH/.github/scripts/check-cmakelists.sh" + fi + build_sketches "$FQBN" "$ARDUINO_ESP32_PATH/libraries" "$CHUNK_INDEX" "$CHUNKS_CNT" + fi +else + # PlatformIO Test + source ./.github/scripts/install-platformio-esp32.sh + BOARD="esp32dev" + build_pio_sketch "$BOARD" "$PLATFORMIO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \ + build_pio_sketch "$BOARD" "$PLATFORMIO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino" && \ + build_pio_sketch "$BOARD" "$PLATFORMIO_ESP32_PATH/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino" && \ + build_pio_sketch "$BOARD" "$PLATFORMIO_ESP32_PATH/libraries/BLE/examples/BLE_server/BLE_server.ino" && \ + build_pio_sketch "$BOARD" "$PLATFORMIO_ESP32_PATH/libraries/AzureIoT/examples/GetStarted/GetStarted.ino" && \ + build_pio_sketch "$BOARD" "$PLATFORMIO_ESP32_PATH/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino" + #build_pio_sketches esp32dev "$PLATFORMIO_ESP32_PATH/libraries" +fi diff --git a/.github/scripts/on-release.sh b/.github/scripts/on-release.sh new file mode 100755 index 00000000000..e5e320099dd --- /dev/null +++ b/.github/scripts/on-release.sh @@ -0,0 +1,380 @@ +#!/bin/bash + +if [ ! $GITHUB_EVENT_NAME == "release" ]; then + echo "Wrong event '$GITHUB_EVENT_NAME'!" + exit 1 +fi + +EVENT_JSON=`cat $GITHUB_EVENT_PATH` + +action=`echo $EVENT_JSON | jq -r '.action'` +if [ ! $action == "published" ]; then + echo "Wrong action '$action'. Exiting now..." + exit 0 +fi + +draft=`echo $EVENT_JSON | jq -r '.release.draft'` +if [ $draft == "true" ]; then + echo "It's a draft release. Exiting now..." + exit 0 +fi + +RELEASE_PRE=`echo $EVENT_JSON | jq -r '.release.prerelease'` +RELEASE_TAG=`echo $EVENT_JSON | jq -r '.release.tag_name'` +RELEASE_BRANCH=`echo $EVENT_JSON | jq -r '.release.target_commitish'` +RELEASE_ID=`echo $EVENT_JSON | jq -r '.release.id'` +RELEASE_BODY=`echo $EVENT_JSON | jq -r '.release.body'` + +OUTPUT_DIR="$GITHUB_WORKSPACE/build" +PACKAGE_NAME="esp32-$RELEASE_TAG" +PACKAGE_JSON_MERGE="$GITHUB_WORKSPACE/.github/scripts/merge_packages.py" +PACKAGE_JSON_TEMPLATE="$GITHUB_WORKSPACE/package/package_esp32_index.template.json" +PACKAGE_JSON_DEV="package_esp32_dev_index.json" +PACKAGE_JSON_REL="package_esp32_index.json" + +echo "Event: $GITHUB_EVENT_NAME, Repo: $GITHUB_REPOSITORY, Path: $GITHUB_WORKSPACE, Ref: $GITHUB_REF" +echo "Action: $action, Branch: $RELEASE_BRANCH, ID: $RELEASE_ID" +echo "Tag: $RELEASE_TAG, Draft: $draft, Pre-Release: $RELEASE_PRE" + +function get_file_size(){ + local file="$1" + if [[ "$OSTYPE" == "darwin"* ]]; then + eval `stat -s "$file"` + local res="$?" + echo "$st_size" + return $res + else + stat --printf="%s" "$file" + return $? + fi +} + +function git_upload_asset(){ + local name=$(basename "$1") + # local mime=$(file -b --mime-type "$1") + curl -k -X POST -sH "Authorization: token $GITHUB_TOKEN" -H "Content-Type: application/octet-stream" --data-binary @"$1" "https://uploads.github.com/repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID/assets?name=$name" +} + +function git_safe_upload_asset(){ + local file="$1" + local name=$(basename "$file") + local size=`get_file_size "$file"` + local upload_res=`git_upload_asset "$file"` + if [ $? -ne 0 ]; then + >&2 echo "ERROR: Failed to upload '$name' ($?)" + return 1 + fi + up_size=`echo "$upload_res" | jq -r '.size'` + if [ $up_size -ne $size ]; then + >&2 echo "ERROR: Uploaded size does not match! $up_size != $size" + #git_delete_asset + return 1 + fi + echo "$upload_res" | jq -r '.browser_download_url' + return $? +} + +function git_upload_to_pages(){ + local path=$1 + local src=$2 + + if [ ! -f "$src" ]; then + >&2 echo "Input is not a file! Aborting..." + return 1 + fi + + local info=`curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.object+json" -X GET "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path?ref=gh-pages"` + local type=`echo "$info" | jq -r '.type'` + local message=$(basename $path) + local sha="" + local content="" + + if [ $type == "file" ]; then + sha=`echo "$info" | jq -r '.sha'` + sha=",\"sha\":\"$sha\"" + message="Updating $message" + elif [ ! $type == "null" ]; then + >&2 echo "Wrong type '$type'" + return 1 + else + message="Creating $message" + fi + + content=`base64 -i "$src"` + data="{\"branch\":\"gh-pages\",\"message\":\"$message\",\"content\":\"$content\"$sha}" + + echo "$data" | curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.raw+json" -X PUT --data @- "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path" +} + +function git_safe_upload_to_pages(){ + local path=$1 + local file="$2" + local name=$(basename "$file") + local size=`get_file_size "$file"` + local upload_res=`git_upload_to_pages "$path" "$file"` + if [ $? -ne 0 ]; then + >&2 echo "ERROR: Failed to upload '$name' ($?)" + return 1 + fi + up_size=`echo "$upload_res" | jq -r '.content.size'` + if [ $up_size -ne $size ]; then + >&2 echo "ERROR: Uploaded size does not match! $up_size != $size" + #git_delete_asset + return 1 + fi + echo "$upload_res" | jq -r '.content.download_url' + return $? +} + +function merge_package_json(){ + local jsonLink=$1 + local jsonOut=$2 + local old_json=$OUTPUT_DIR/oldJson.json + local merged_json=$OUTPUT_DIR/mergedJson.json + + echo "Downloading previous JSON $jsonLink ..." + curl -L -o "$old_json" "https://github.com/$GITHUB_REPOSITORY/releases/download/$jsonLink?access_token=$GITHUB_TOKEN" 2>/dev/null + if [ $? -ne 0 ]; then echo "ERROR: Download Failed! $?"; exit 1; fi + + echo "Creating new JSON ..." + set +e + stdbuf -oL python "$PACKAGE_JSON_MERGE" "$jsonOut" "$old_json" > "$merged_json" + set -e + + set -v + if [ ! -s $merged_json ]; then + rm -f "$merged_json" + echo "Nothing to merge" + else + rm -f "$jsonOut" + mv "$merged_json" "$jsonOut" + echo "JSON data successfully merged" + fi + rm -f "$old_json" + set +v +} + +set -e + +## +## PACKAGE ZIP +## + +mkdir -p "$OUTPUT_DIR" +PKG_DIR="$OUTPUT_DIR/$PACKAGE_NAME" +PACKAGE_ZIP="$PACKAGE_NAME.zip" + +echo "Updating submodules ..." +git -C "$GITHUB_WORKSPACE" submodule update --init --recursive > /dev/null 2>&1 + +mkdir -p "$PKG_DIR/tools" + +# Copy all core files to the package folder +echo "Copying files for packaging ..." +cp -f "$GITHUB_WORKSPACE/boards.txt" "$PKG_DIR/" +cp -f "$GITHUB_WORKSPACE/programmers.txt" "$PKG_DIR/" +cp -Rf "$GITHUB_WORKSPACE/cores" "$PKG_DIR/" +cp -Rf "$GITHUB_WORKSPACE/libraries" "$PKG_DIR/" +cp -Rf "$GITHUB_WORKSPACE/variants" "$PKG_DIR/" +cp -f "$GITHUB_WORKSPACE/tools/espota.exe" "$PKG_DIR/tools/" +cp -f "$GITHUB_WORKSPACE/tools/espota.py" "$PKG_DIR/tools/" +cp -f "$GITHUB_WORKSPACE/tools/esptool.py" "$PKG_DIR/tools/" +cp -f "$GITHUB_WORKSPACE/tools/gen_esp32part.py" "$PKG_DIR/tools/" +cp -f "$GITHUB_WORKSPACE/tools/gen_esp32part.exe" "$PKG_DIR/tools/" +cp -Rf "$GITHUB_WORKSPACE/tools/partitions" "$PKG_DIR/tools/" +cp -Rf "$GITHUB_WORKSPACE/tools/sdk" "$PKG_DIR/tools/" + +# Remove unnecessary files in the package folder +echo "Cleaning up folders ..." +find "$PKG_DIR" -name '*.DS_Store' -exec rm -f {} \; +find "$PKG_DIR" -name '*.git*' -type f -delete + +# Replace tools locations in platform.txt +echo "Generating platform.txt..." +cat "$GITHUB_WORKSPACE/platform.txt" | \ +sed "s/version=.*/version=$ver$extent/g" | \ +sed 's/runtime.tools.xtensa-esp32-elf-gcc.path={runtime.platform.path}\/tools\/xtensa-esp32-elf//g' | \ +sed 's/tools.esptool_py.path={runtime.platform.path}\/tools\/esptool/tools.esptool_py.path=\{runtime.tools.esptool_py.path\}/g' \ + > "$PKG_DIR/platform.txt" + +# Add header with version information +echo "Generating core_version.h ..." +ver_define=`echo $RELEASE_TAG | tr "[:lower:].\055" "[:upper:]_"` +ver_hex=`git -C "$GITHUB_WORKSPACE" rev-parse --short=8 HEAD 2>/dev/null` +echo \#define ARDUINO_ESP32_GIT_VER 0x$ver_hex > "$PKG_DIR/cores/esp32/core_version.h" +echo \#define ARDUINO_ESP32_GIT_DESC `git -C "$GITHUB_WORKSPACE" describe --tags 2>/dev/null` >> "$PKG_DIR/cores/esp32/core_version.h" +echo \#define ARDUINO_ESP32_RELEASE_$ver_define >> "$PKG_DIR/cores/esp32/core_version.h" +echo \#define ARDUINO_ESP32_RELEASE \"$ver_define\" >> "$PKG_DIR/cores/esp32/core_version.h" + +# Compress package folder +echo "Creating ZIP ..." +pushd "$OUTPUT_DIR" >/dev/null +zip -qr "$PACKAGE_ZIP" "$PACKAGE_NAME" +if [ $? -ne 0 ]; then echo "ERROR: Failed to create $PACKAGE_ZIP ($?)"; exit 1; fi + +# Calculate SHA-256 +echo "Calculating SHA sum ..." +PACKAGE_PATH="$OUTPUT_DIR/$PACKAGE_ZIP" +PACKAGE_SHA=`shasum -a 256 "$PACKAGE_ZIP" | cut -f 1 -d ' '` +PACKAGE_SIZE=`get_file_size "$PACKAGE_ZIP"` +popd >/dev/null +rm -rf "$PKG_DIR" +echo "'$PACKAGE_ZIP' Created! Size: $PACKAGE_SIZE, SHA-256: $PACKAGE_SHA" +echo + +# Upload package to release page +echo "Uploading package to release page ..." +PACKAGE_URL=`git_safe_upload_asset "$PACKAGE_PATH"` +echo "Package Uploaded" +echo "Download URL: $PACKAGE_URL" +echo + +## +## PACKAGE JSON +## + +# Construct JQ argument with package data +jq_arg=".packages[0].platforms[0].version = \"$RELEASE_TAG\" | \ + .packages[0].platforms[0].url = \"$PACKAGE_URL\" |\ + .packages[0].platforms[0].archiveFileName = \"$PACKAGE_ZIP\" |\ + .packages[0].platforms[0].size = \"$PACKAGE_SIZE\" |\ + .packages[0].platforms[0].checksum = \"SHA-256:$PACKAGE_SHA\"" + +# Generate package JSONs +echo "Genarating $PACKAGE_JSON_DEV ..." +cat "$PACKAGE_JSON_TEMPLATE" | jq "$jq_arg" > "$OUTPUT_DIR/$PACKAGE_JSON_DEV" +if [ "$RELEASE_PRE" == "false" ]; then + echo "Genarating $PACKAGE_JSON_REL ..." + cat "$PACKAGE_JSON_TEMPLATE" | jq "$jq_arg" > "$OUTPUT_DIR/$PACKAGE_JSON_REL" +fi + +# Figure out the last release or pre-release +echo "Getting previous releases ..." +releasesJson=`curl -sH "Authorization: token $GITHUB_TOKEN" "https://api.github.com/repos/$GITHUB_REPOSITORY/releases" 2>/dev/null` +if [ $? -ne 0 ]; then echo "ERROR: Get Releases Failed! ($?)"; exit 1; fi + +set +e +prev_release=$(echo "$releasesJson" | jq -e -r '. | map(select(.draft == false and .prerelease == false)) | sort_by(.created_at | - fromdateiso8601) | .[0].tag_name') +prev_any_release=$(echo "$releasesJson" | jq -e -r '. | map(select(.draft == false)) | sort_by(.created_at | - fromdateiso8601) | .[0].tag_name') +shopt -s nocasematch +if [ "$prev_any_release" == "$RELEASE_TAG" ]; then + prev_release=$(echo "$releasesJson" | jq -e -r '. | map(select(.draft == false and .prerelease == false)) | sort_by(.created_at | - fromdateiso8601) | .[1].tag_name') + prev_any_release=$(echo "$releasesJson" | jq -e -r '. | map(select(.draft == false)) | sort_by(.created_at | - fromdateiso8601) | .[1].tag_name') +fi +COMMITS_SINCE_RELEASE="$prev_any_release" +shopt -u nocasematch +set -e + +# Merge package JSONs with previous releases +if [ ! -z "$prev_any_release" ] && [ "$prev_any_release" != "null" ]; then + echo "Merging with JSON from $prev_any_release ..." + merge_package_json "$prev_any_release/$PACKAGE_JSON_DEV" "$OUTPUT_DIR/$PACKAGE_JSON_DEV" +fi + +if [ "$RELEASE_PRE" == "false" ]; then + COMMITS_SINCE_RELEASE="$prev_release" + if [ ! -z "$prev_release" ] && [ "$prev_release" != "null" ]; then + echo "Merging with JSON from $prev_release ..." + merge_package_json "$prev_release/$PACKAGE_JSON_REL" "$OUTPUT_DIR/$PACKAGE_JSON_REL" + fi +fi + +echo "Previous Release: $prev_release" +echo "Previous (any)release: $prev_any_release" +echo + +# Upload package JSONs +echo "Uploading $PACKAGE_JSON_DEV ..." +echo "Download URL: "`git_safe_upload_asset "$OUTPUT_DIR/$PACKAGE_JSON_DEV"` +echo "Pages URL: "`git_safe_upload_to_pages "$PACKAGE_JSON_DEV" "$OUTPUT_DIR/$PACKAGE_JSON_DEV"` +echo +if [ "$RELEASE_PRE" == "false" ]; then + echo "Uploading $PACKAGE_JSON_REL ..." + echo "Download URL: "`git_safe_upload_asset "$OUTPUT_DIR/$PACKAGE_JSON_REL"` + echo "Pages URL: "`git_safe_upload_to_pages "$PACKAGE_JSON_REL" "$OUTPUT_DIR/$PACKAGE_JSON_REL"` + echo +fi + +## +## RELEASE NOTES +## + +# Create release notes +echo "Preparing release notes ..." +releaseNotes="" + +# Process annotated tags +relNotesRaw=`git -C "$GITHUB_WORKSPACE" show -s --format=%b $RELEASE_TAG` +readarray -t msgArray <<<"$relNotesRaw" +arrLen=${#msgArray[@]} +if [ $arrLen > 3 ] && [ "${msgArray[0]:0:3}" == "tag" ]; then + ind=3 + while [ $ind -lt $arrLen ]; do + if [ $ind -eq 3 ]; then + releaseNotes="#### ${msgArray[ind]}" + releaseNotes+=$'\r\n' + else + oneLine="$(echo -e "${msgArray[ind]}" | sed -e 's/^[[:space:]]*//')" + if [ ${#oneLine} -gt 0 ]; then + if [ "${oneLine:0:2}" == "* " ]; then oneLine=$(echo ${oneLine/\*/-}); fi + if [ "${oneLine:0:2}" != "- " ]; then releaseNotes+="- "; fi + releaseNotes+="$oneLine" + releaseNotes+=$'\r\n' + fi + fi + let ind=$ind+1 + done +fi + +# Append Commit Messages +if [ ! -z "$COMMITS_SINCE_RELEASE" ] && [ "$COMMITS_SINCE_RELEASE" != "null" ]; then + echo "Getting commits since $COMMITS_SINCE_RELEASE ..." + commitFile=$OUTPUT_DIR/commits.txt + git -C "$GITHUB_WORKSPACE" log --oneline $COMMITS_SINCE_RELEASE.. > "$OUTPUT_DIR/commits.txt" + releaseNotes+=$'\r\n##### Commits\r\n' + IFS=$'\n' + for next in `cat $commitFile` + do + IFS=' ' read -r commitId commitMsg <<< "$next" + commitLine="- [$commitId](https://github.com/$GITHUB_REPOSITORY/commit/$commitId) $commitMsg" + releaseNotes+="$commitLine" + releaseNotes+=$'\r\n' + done + rm -f $commitFile +fi + +# Prepend the original release body +if [ "${RELEASE_BODY: -1}" == $'\r' ]; then + RELEASE_BODY="${RELEASE_BODY:0:-1}" +else + RELEASE_BODY="$RELEASE_BODY" +fi +RELEASE_BODY+=$'\r\n' +releaseNotes="$RELEASE_BODY$releaseNotes" + +# Update release page +echo "Updating release notes ..." +releaseNotes=$(printf '%s' "$releaseNotes" | python -c 'import json,sys; print(json.dumps(sys.stdin.read()))') +releaseNotes=${releaseNotes:1:-1} +curlData="{\"body\": \"$releaseNotes\"}" +releaseData=`curl --data "$curlData" "https://api.github.com/repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID?access_token=$GITHUB_TOKEN" 2>/dev/null` +if [ $? -ne 0 ]; then echo "ERROR: Updating Release Failed: $?"; exit 1; fi +echo "Release notes successfully updated" +echo + +## +## SUBMODULE VERSIONS +## + +# Upload submodules versions +echo "Generating submodules.txt ..." +git -C "$GITHUB_WORKSPACE" submodule status > "$OUTPUT_DIR/submodules.txt" +echo "Uploading submodules.txt ..." +echo "Download URL: "`git_safe_upload_asset "$OUTPUT_DIR/submodules.txt"` +echo "" +set +e + +## +## DONE +## +echo "DONE!" diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 00000000000..e969fcba5b1 --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,64 @@ +# Configuration for probot-stale - https://github.com/probot/stale + +# Number of days of inactivity before an Issue or Pull Request becomes stale +daysUntilStale: 60 + +# Number of days of inactivity before an Issue or Pull Request with the stale label is closed. +# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale. +daysUntilClose: 14 + +# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled) +onlyLabels: [] + +# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable +exemptLabels: + - pinned + - security + - "to be implemented" + - "for reference" + - "move to PR" + - "enhancement" + +# Set to true to ignore issues in a project (defaults to false) +exemptProjects: false + +# Set to true to ignore issues in a milestone (defaults to false) +exemptMilestones: false + +# Set to true to ignore issues with an assignee (defaults to false) +exemptAssignees: false + +# Label to use when marking as stale +staleLabel: stale + +# Comment to post when marking as stale. Set to `false` to disable +markComment: > + [STALE_SET] This issue has been automatically marked as stale because it has not had + recent activity. It will be closed in 14 days if no further activity occurs. Thank you + for your contributions. + +# Comment to post when removing the stale label. +unmarkComment: > + [STALE_CLR] This issue has been removed from the stale queue. Please ensure activity to keep it openin the future. + +# Comment to post when closing a stale Issue or Pull Request. +closeComment: > + [STALE_DEL] This stale issue has been automatically closed. Thank you for your contributions. + +# Limit the number of actions per hour, from 1-30. Default is 30 +limitPerRun: 30 + +# Limit to only `issues` or `pulls` +only: issues + +# Optionally, specify configuration settings that are specific to just 'issues' or 'pulls': +# pulls: +# daysUntilStale: 30 +# markComment: > +# This pull request has been automatically marked as stale because it has not had +# recent activity. It will be closed if no further activity occurs. Thank you +# for your contributions. + +# issues: +# exemptLabels: +# - confirmed diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml new file mode 100644 index 00000000000..f111f3aa254 --- /dev/null +++ b/.github/workflows/gh-pages.yml @@ -0,0 +1,21 @@ +name: GitHub Pages CI + +on: + push: + branches: + - master + paths: + - 'README.md' + - 'docs/**' + +jobs: + + build-pages: + name: Build GitHub Pages + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Copy Files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: bash ./.github/scripts/on-pages.sh diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml new file mode 100644 index 00000000000..42d4735f106 --- /dev/null +++ b/.github/workflows/push.yml @@ -0,0 +1,49 @@ +name: ESP32 Arduino CI + +on: + push: + branches: + - master + - release/* + pull_request: + +jobs: + + # Ubuntu + build-arduino-linux: + name: Arduino ${{ matrix.chunk }} on ubuntu-latest + runs-on: ubuntu-latest + strategy: + matrix: + chunk: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + + steps: + - uses: actions/checkout@v1 + - name: Build Sketches + run: bash ./.github/scripts/on-push.sh ${{ matrix.chunk }} 15 + + # Windows and MacOS + build-arduino-win-mac: + name: Arduino on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [windows-latest, macOS-latest] + + steps: + - uses: actions/checkout@v1 + - name: Build Sketches + run: bash ./.github/scripts/on-push.sh + + # PlatformIO on Windows, Ubuntu and Mac + build-platformio: + name: PlatformIO on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + + steps: + - uses: actions/checkout@v1 + - name: Build Sketches + run: bash ./.github/scripts/on-push.sh 1 1 #equal and non-zero to trigger PIO diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000000..83b625164f7 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,17 @@ +name: ESP32 Arduino Release + +on: + release: + types: published + +jobs: + build: + name: Publish Release + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@master + - name: Build Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: bash ./.github/scripts/on-release.sh diff --git a/.gitignore b/.gitignore index a5dd41c7f3c..a09a7a0d6b9 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,11 @@ tools/esptool tools/esptool.exe tools/mkspiffs/mkspiffs tools/mkspiffs/mkspiffs.exe -.DS_Store +.DS_Store + +#Ignore files built by Visual Studio/Visual Micro +[Dd]ebug*/ +[Rr]elease*/ +.vs/ +__vm/ +*.vcxproj* diff --git a/.gitmodules b/.gitmodules index 1ca8b1312f5..c9e5e6fd92e 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ -[submodule "libraries/BLE"] - path = libraries/BLE - url = https://github.com/nkolban/ESP32_BLE_Arduino.git +[submodule "libraries/AzureIoT"] + path = libraries/AzureIoT + url = https://github.com/VSChina/ESP32_AzureIoT_Arduino diff --git a/.travis.yml b/.travis.yml index 3929a491e89..2fb1dc44dc9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,50 +1,47 @@ sudo: false language: python -python: - - "2.7" os: - linux -script: - #- set -e - - echo -e "travis_fold:start:sketch_test_env_prepare" - - pip install pyserial - - wget -O arduino.tar.xz https://www.arduino.cc/download.php?f=/arduino-nightly-linux64.tar.xz - - tar xf arduino.tar.xz - - mv arduino-nightly $HOME/arduino_ide - - mkdir -p $HOME/Arduino/libraries - - cd $HOME/arduino_ide/hardware - - mkdir espressif - - cd espressif - - ln -s $TRAVIS_BUILD_DIR esp32 - - cd esp32 +git: + depth: false + +before_install: - git submodule update --init --recursive - - cd tools - - python get.py - - export PATH="$HOME/arduino_ide:$TRAVIS_BUILD_DIR/tools/xtensa-esp32-elf/bin:$PATH" - - which arduino - - cd $TRAVIS_BUILD_DIR - - source tools/common.sh - - echo -e "travis_fold:end:sketch_test_env_prepare" - - echo -e "travis_fold:start:sketch_test" - - build_sketches $HOME/arduino_ide $TRAVIS_BUILD_DIR/libraries "-l $HOME/Arduino/libraries" - - echo -e "travis_fold:end:sketch_test" - - echo -e "travis_fold:start:size_report" - - cat size.log - - echo -e "travis_fold:end:size_report" - - # test library examples with PlatformIO - - echo -e "travis_fold:start:platformio_test_env_prepare" - - pip install -U https://github.com/platformio/platformio/archive/develop.zip - - platformio platform install https://github.com/platformio/platform-espressif32.git#feature/stage - - sed -i 's/https:\/\/github\.com\/espressif\/arduino-esp32\.git/*/' ~/.platformio/platforms/espressif32/platform.json - - ln -s $TRAVIS_BUILD_DIR ~/.platformio/packages/framework-arduinoespressif32 - - echo -e "travis_fold:end:platformio_test_env_prepare" - - echo -e "travis_fold:start:platformio_test" - - "python -c \"import glob,os,subprocess,sys; map(lambda p: (sys.stdout.write('Library example: %s\\n' % p), subprocess.call(['pio', 'ci', p, '--board', 'esp32dev'])), set([os.path.dirname(p) for p in glob.glob('libraries/*/examples/*/*.ino') + glob.glob('libraries/*/examples/*/*/*.ino')]))\"" - - echo -e "travis_fold:end:platformio_test" + +stages: + - build + - deploy + +jobs: + include: + + - name: "Build Arduino 0" + if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) + stage: build + script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 0 10 + + - name: "Build Arduino 1" + if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) + stage: build + script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 1 10 + + - name: "Build Arduino 2" + if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) + stage: build + script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 2 10 + + - name: "Build Arduino 3" + if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) + stage: build + script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 3 10 + + - name: "Build PlatformIO" + if: tag IS blank AND (type = pull_request OR (type = push AND branch = master)) + stage: build + script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 1 1 notifications: email: @@ -52,7 +49,7 @@ notifications: on_failure: change webhooks: urls: - - https://webhooks.gitter.im/e/cb057279c430d91a47a8 + - https://webhooks.gitter.im/e/cb057279c430d91a47a8 on_success: change # options: [always|never|change] default: always on_failure: always # options: [always|never|change] default: always - on_start: false # default: false + on_start: never # options: [always|never|change] default: always \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000000..32979ad4acf --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,216 @@ +set(CORE_SRCS + cores/esp32/base64.cpp + cores/esp32/cbuf.cpp + cores/esp32/esp32-hal-adc.c + cores/esp32/esp32-hal-bt.c + cores/esp32/esp32-hal-cpu.c + cores/esp32/esp32-hal-dac.c + cores/esp32/esp32-hal-gpio.c + cores/esp32/esp32-hal-i2c.c + cores/esp32/esp32-hal-ledc.c + cores/esp32/esp32-hal-matrix.c + cores/esp32/esp32-hal-misc.c + cores/esp32/esp32-hal-psram.c + cores/esp32/esp32-hal-sigmadelta.c + cores/esp32/esp32-hal-spi.c + cores/esp32/esp32-hal-time.c + cores/esp32/esp32-hal-timer.c + cores/esp32/esp32-hal-touch.c + cores/esp32/esp32-hal-uart.c + cores/esp32/esp32-hal-rmt.c + cores/esp32/Esp.cpp + cores/esp32/FunctionalInterrupt.cpp + cores/esp32/HardwareSerial.cpp + cores/esp32/IPAddress.cpp + cores/esp32/IPv6Address.cpp + cores/esp32/libb64/cdecode.c + cores/esp32/libb64/cencode.c + cores/esp32/main.cpp + cores/esp32/MD5Builder.cpp + cores/esp32/Print.cpp + cores/esp32/stdlib_noniso.c + cores/esp32/Stream.cpp + cores/esp32/StreamString.cpp + cores/esp32/wiring_pulse.c + cores/esp32/wiring_shift.c + cores/esp32/WMath.cpp + cores/esp32/WString.cpp + ) + +set(LIBRARY_SRCS + libraries/ArduinoOTA/src/ArduinoOTA.cpp + libraries/AsyncUDP/src/AsyncUDP.cpp + libraries/BluetoothSerial/src/BluetoothSerial.cpp + libraries/DNSServer/src/DNSServer.cpp + libraries/EEPROM/src/EEPROM.cpp + libraries/ESPmDNS/src/ESPmDNS.cpp + libraries/FFat/src/FFat.cpp + libraries/FS/src/FS.cpp + libraries/FS/src/vfs_api.cpp + libraries/HTTPClient/src/HTTPClient.cpp + libraries/HTTPUpdate/src/HTTPUpdate.cpp + libraries/NetBIOS/src/NetBIOS.cpp + libraries/Preferences/src/Preferences.cpp + libraries/SD_MMC/src/SD_MMC.cpp + libraries/SD/src/SD.cpp + libraries/SD/src/sd_diskio.cpp + libraries/SD/src/sd_diskio_crc.c + libraries/SimpleBLE/src/SimpleBLE.cpp + libraries/SPIFFS/src/SPIFFS.cpp + libraries/SPI/src/SPI.cpp + libraries/Ticker/src/Ticker.cpp + libraries/Update/src/Updater.cpp + libraries/WebServer/src/WebServer.cpp + libraries/WebServer/src/Parsing.cpp + libraries/WebServer/src/detail/mimetable.cpp + libraries/WiFiClientSecure/src/ssl_client.cpp + libraries/WiFiClientSecure/src/WiFiClientSecure.cpp + libraries/WiFi/src/ETH.cpp + libraries/WiFi/src/WiFiAP.cpp + libraries/WiFi/src/WiFiClient.cpp + libraries/WiFi/src/WiFi.cpp + libraries/WiFi/src/WiFiGeneric.cpp + libraries/WiFi/src/WiFiMulti.cpp + libraries/WiFi/src/WiFiScan.cpp + libraries/WiFi/src/WiFiServer.cpp + libraries/WiFi/src/WiFiSTA.cpp + libraries/WiFi/src/WiFiUdp.cpp + libraries/Wire/src/Wire.cpp + ) + +set(AZURE_SRCS + libraries/AzureIoT/src/az_iot/azureiotcerts.c + libraries/AzureIoT/src/az_iot/c-utility/pal/agenttime.c + libraries/AzureIoT/src/az_iot/c-utility/pal/dns_async.c + libraries/AzureIoT/src/az_iot/c-utility/pal/freertos/lock.c + libraries/AzureIoT/src/az_iot/c-utility/pal/freertos/threadapi.c + libraries/AzureIoT/src/az_iot/c-utility/pal/freertos/tickcounter.c + libraries/AzureIoT/src/az_iot/c-utility/pal/lwip/sntp_lwip.c + libraries/AzureIoT/src/az_iot/c-utility/pal/socket_async.c + libraries/AzureIoT/src/az_iot/c-utility/pal/src/platform_openssl_compact.c + libraries/AzureIoT/src/az_iot/c-utility/pal/src/tlsio_openssl_compact.c + libraries/AzureIoT/src/az_iot/c-utility/pal/tlsio_options.c + libraries/AzureIoT/src/az_iot/c-utility/src/base64.c + libraries/AzureIoT/src/az_iot/c-utility/src/buffer.c + libraries/AzureIoT/src/az_iot/c-utility/src/connection_string_parser.c + libraries/AzureIoT/src/az_iot/c-utility/src/consolelogger.c + libraries/AzureIoT/src/az_iot/c-utility/src/constbuffer.c + libraries/AzureIoT/src/az_iot/c-utility/src/constmap.c + libraries/AzureIoT/src/az_iot/c-utility/src/crt_abstractions.c + libraries/AzureIoT/src/az_iot/c-utility/src/doublylinkedlist.c + libraries/AzureIoT/src/az_iot/c-utility/src/gballoc.c + libraries/AzureIoT/src/az_iot/c-utility/src/gb_stdio.c + libraries/AzureIoT/src/az_iot/c-utility/src/gb_time.c + libraries/AzureIoT/src/az_iot/c-utility/src/hmac.c + libraries/AzureIoT/src/az_iot/c-utility/src/hmacsha256.c + libraries/AzureIoT/src/az_iot/c-utility/src/httpapiex.c + libraries/AzureIoT/src/az_iot/c-utility/src/httpapiexsas.c + libraries/AzureIoT/src/az_iot/c-utility/src/httpheaders.c + libraries/AzureIoT/src/az_iot/c-utility/src/http_proxy_io.c + libraries/AzureIoT/src/az_iot/c-utility/src/map.c + libraries/AzureIoT/src/az_iot/c-utility/src/optionhandler.c + libraries/AzureIoT/src/az_iot/c-utility/src/sastoken.c + libraries/AzureIoT/src/az_iot/c-utility/src/sha1.c + libraries/AzureIoT/src/az_iot/c-utility/src/sha224.c + libraries/AzureIoT/src/az_iot/c-utility/src/sha384-512.c + libraries/AzureIoT/src/az_iot/c-utility/src/singlylinkedlist.c + libraries/AzureIoT/src/az_iot/c-utility/src/strings.c + libraries/AzureIoT/src/az_iot/c-utility/src/string_tokenizer.c + libraries/AzureIoT/src/az_iot/c-utility/src/urlencode.c + libraries/AzureIoT/src/az_iot/c-utility/src/usha.c + libraries/AzureIoT/src/az_iot/c-utility/src/vector.c + libraries/AzureIoT/src/az_iot/c-utility/src/xio.c + libraries/AzureIoT/src/az_iot/c-utility/src/xlogging.c + libraries/AzureIoT/src/az_iot/iothub_client/src/blob.c + libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_client_authorization.c + libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_client.c + libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_client_ll.c + libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_client_retry_control.c + libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_message.c + libraries/AzureIoT/src/az_iot/iothub_client/src/iothubtransport.c + libraries/AzureIoT/src/az_iot/iothub_client/src/iothubtransportmqtt.c + libraries/AzureIoT/src/az_iot/iothub_client/src/iothubtransport_mqtt_common.c + libraries/AzureIoT/src/az_iot/iothub_client/src/version.c + libraries/AzureIoT/src/az_iot/umqtt/src/mqtt_client.c + libraries/AzureIoT/src/az_iot/umqtt/src/mqtt_codec.c + libraries/AzureIoT/src/az_iot/umqtt/src/mqtt_message.c + libraries/AzureIoT/src/AzureIotHub.cpp + libraries/AzureIoT/src/Esp32MQTTClient.cpp + ) + +set(BLE_SRCS + libraries/BLE/src/BLE2902.cpp + libraries/BLE/src/BLE2904.cpp + libraries/BLE/src/BLEAddress.cpp + libraries/BLE/src/BLEAdvertisedDevice.cpp + libraries/BLE/src/BLEAdvertising.cpp + libraries/BLE/src/BLEBeacon.cpp + libraries/BLE/src/BLECharacteristic.cpp + libraries/BLE/src/BLECharacteristicMap.cpp + libraries/BLE/src/BLEClient.cpp + libraries/BLE/src/BLEDescriptor.cpp + libraries/BLE/src/BLEDescriptorMap.cpp + libraries/BLE/src/BLEDevice.cpp + libraries/BLE/src/BLEEddystoneTLM.cpp + libraries/BLE/src/BLEEddystoneURL.cpp + libraries/BLE/src/BLEExceptions.cpp + libraries/BLE/src/BLEHIDDevice.cpp + libraries/BLE/src/BLERemoteCharacteristic.cpp + libraries/BLE/src/BLERemoteDescriptor.cpp + libraries/BLE/src/BLERemoteService.cpp + libraries/BLE/src/BLEScan.cpp + libraries/BLE/src/BLESecurity.cpp + libraries/BLE/src/BLEServer.cpp + libraries/BLE/src/BLEService.cpp + libraries/BLE/src/BLEServiceMap.cpp + libraries/BLE/src/BLEUtils.cpp + libraries/BLE/src/BLEUUID.cpp + libraries/BLE/src/BLEValue.cpp + libraries/BLE/src/FreeRTOS.cpp + libraries/BLE/src/GeneralUtils.cpp + ) + +set(COMPONENT_SRCS ${CORE_SRCS} ${LIBRARY_SRCS} ${AZURE_SRCS} ${BLE_SRCS}) + +set(COMPONENT_ADD_INCLUDEDIRS + variants/esp32/ + cores/esp32/ + libraries/ArduinoOTA/src + libraries/AsyncUDP/src + libraries/AzureIoT/src + libraries/BLE/src + libraries/BluetoothSerial/src + libraries/DNSServer/src + libraries/EEPROM/src + libraries/ESP32/src + libraries/ESPmDNS/src + libraries/FFat/src + libraries/FS/src + libraries/HTTPClient/src + libraries/HTTPUpdate/src + libraries/NetBIOS/src + libraries/Preferences/src + libraries/SD_MMC/src + libraries/SD/src + libraries/SimpleBLE/src + libraries/SPIFFS/src + libraries/SPI/src + libraries/Ticker/src + libraries/Update/src + libraries/WebServer/src + libraries/WiFiClientSecure/src + libraries/WiFi/src + libraries/Wire/src + ) + +set(COMPONENT_PRIV_INCLUDEDIRS cores/esp32/libb64) + +set(COMPONENT_REQUIRES spi_flash mbedtls mdns ethernet) +set(COMPONENT_PRIV_REQUIRES fatfs nvs_flash app_update spiffs bootloader_support openssl bt) + +register_component() + +set_source_files_properties(libraries/AzureIoT/src/az_iot/iothub_client/src/iothubtransport_mqtt_common.c + PROPERTIES COMPILE_FLAGS + -Wno-maybe-uninitialized +) diff --git a/Kconfig.projbuild b/Kconfig.projbuild index 9e131b040c2..10bbf25181e 100644 --- a/Kconfig.projbuild +++ b/Kconfig.projbuild @@ -19,6 +19,70 @@ config AUTOSTART_ARDUINO If disabled, you can call initArduino() to run any preparations required by the framework +choice ARDUINO_RUNNING_CORE + bool "Core on which Arduino's setup() and loop() are running" + default ARDUINO_RUN_CORE1 + help + Select on which core Arduino's setup() and loop() functions run + + config ARDUINO_RUN_CORE0 + bool "CORE 0" + config ARDUINO_RUN_CORE1 + bool "CORE 1" + config ARDUINO_RUN_NO_AFFINITY + bool "BOTH" + +endchoice + +config ARDUINO_RUNNING_CORE + int + default 0 if ARDUINO_RUN_CORE0 + default 1 if ARDUINO_RUN_CORE1 + default -1 if ARDUINO_RUN_NO_AFFINITY + +choice ARDUINO_EVENT_RUNNING_CORE + bool "Core on which Arduino's event handler is running" + default ARDUINO_EVENT_RUN_CORE1 + help + Select on which core Arduino's WiFi.onEvent() run + + config ARDUINO_EVENT_RUN_CORE0 + bool "CORE 0" + config ARDUINO_EVENT_RUN_CORE1 + bool "CORE 1" + config ARDUINO_EVENT_RUN_NO_AFFINITY + bool "BOTH" + +endchoice + +config ARDUINO_EVENT_RUNNING_CORE + int + default 0 if ARDUINO_EVENT_RUN_CORE0 + default 1 if ARDUINO_EVENT_RUN_CORE1 + default -1 if ARDUINO_EVENT_RUN_NO_AFFINITY + +choice ARDUINO_UDP_RUNNING_CORE + bool "Core on which Arduino's UDP is running" + default ARDUINO_UDP_RUN_CORE1 + help + Select on which core Arduino's UDP run + + config ARDUINO_UDP_RUN_CORE0 + bool "CORE 0" + config ARDUINO_UDP_RUN_CORE1 + bool "CORE 1" + config ARDUINO_UDP_RUN_NO_AFFINITY + bool "BOTH" + +endchoice + +config ARDUINO_UDP_RUNNING_CORE + int + default 0 if ARDUINO_UDP_RUN_CORE0 + default 1 if ARDUINO_UDP_RUN_CORE1 + default -1 if ARDUINO_UDP_RUN_NO_AFFINITY + + config DISABLE_HAL_LOCKS bool "Disable mutex locks for HAL" default "n" @@ -90,6 +154,8 @@ config ARDUHAL_PARTITION_SCHEME_MINIMAL bool "Minimal (for 2MB FLASH)" config ARDUHAL_PARTITION_SCHEME_NO_OTA bool "No OTA (for large apps)" +config ARDUHAL_PARTITION_SCHEME_HUGE_APP + bool "Huge App (for very large apps)" config ARDUHAL_PARTITION_SCHEME_MIN_SPIFFS bool "Minimal SPIFFS (for large apps with OTA)" endchoice @@ -99,6 +165,7 @@ config ARDUHAL_PARTITION_SCHEME default "default" if ARDUHAL_PARTITION_SCHEME_DEFAULT default "minimal" if ARDUHAL_PARTITION_SCHEME_MINIMAL default "no_ota" if ARDUHAL_PARTITION_SCHEME_NO_OTA + default "huge_app" if ARDUHAL_PARTITION_SCHEME_HUGE_APP default "min_spiffs" if ARDUHAL_PARTITION_SCHEME_MIN_SPIFFS @@ -106,8 +173,153 @@ config AUTOCONNECT_WIFI bool "Autoconnect WiFi on boot" default "n" depends on AUTOSTART_ARDUINO + select ARDUINO_SELECTIVE_WiFi help If enabled, WiFi will connect to the last used SSID (if station was enabled), else connection will be started only after calling WiFi.begin(ssid, password) +config ARDUINO_SELECTIVE_COMPILATION + bool "Include only specific Arduino libraries" + default n + +config ARDUINO_SELECTIVE_ArduinoOTA + bool "Enable ArduinoOTA" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_WiFi + select ARDUINO_SELECTIVE_ESPmDNS + default y + +config ARDUINO_SELECTIVE_AsyncUDP + bool "Enable AsyncUDP" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_AzureIoT + bool "Enable AzureIoT" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_HTTPClient + default y + +config ARDUINO_SELECTIVE_BLE + bool "Enable BLE" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_BluetoothSerial + bool "Enable BluetoothSerial" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_DNSServer + bool "Enable DNSServer" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_WiFi + default y + +config ARDUINO_SELECTIVE_EEPROM + bool "Enable EEPROM" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_ESP32 + bool "Enable ESP32" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_ESPmDNS + bool "Enable ESPmDNS" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_WiFi + default y + +config ARDUINO_SELECTIVE_FFat + bool "Enable FFat" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_FS + default y + +config ARDUINO_SELECTIVE_FS + bool "Enable FS" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_HTTPClient + bool "Enable HTTPClient" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_WiFi + select ARDUINO_SELECTIVE_WiFiClientSecure + default y + +config ARDUINO_SELECTIVE_NetBIOS + bool "Enable NetBIOS" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_WiFi + default y + +config ARDUINO_SELECTIVE_Preferences + bool "Enable Preferences" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_SD + bool "Enable SD" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_FS + default y + +config ARDUINO_SELECTIVE_SD_MMC + bool "Enable SD_MMC" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_FS + default y + +config ARDUINO_SELECTIVE_SimpleBLE + bool "Enable SimpleBLE" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_SPI + bool "Enable SPI" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_SPIFFS + bool "Enable SPIFFS" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_FS + default y + +config ARDUINO_SELECTIVE_Ticker + bool "Enable Ticker" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_Update + bool "Enable Update" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_WebServer + bool "Enable WebServer" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + select ARDUINO_SELECTIVE_FS + +config ARDUINO_SELECTIVE_WiFi + bool "Enable WiFi" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + +config ARDUINO_SELECTIVE_WiFiClientSecure + bool "Enable WiFiClientSecure" + depends on ARDUINO_SELECTIVE_COMPILATION + select ARDUINO_SELECTIVE_WiFi + default y + +config ARDUINO_SELECTIVE_Wire + bool "Enable Wire" + depends on ARDUINO_SELECTIVE_COMPILATION + default y + + endmenu diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000000..d55f6088e5e --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,503 @@ +### GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + [This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + +### Preamble + +The licenses for most software are designed to take away your freedom +to share and change it. By contrast, the GNU General Public Licenses +are intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations +below. + +When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + +To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there +is no warranty for the free library. Also, if the library is modified +by someone else and passed on, the recipients should know that what +they have is not the original version, so that the original author's +reputation will not be affected by problems that might be introduced +by others. + +Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + +When a program is linked with a library, whether statically or using a +shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + +We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + +For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it +becomes a de-facto standard. To achieve this, non-free programs must +be allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + +Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + +### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +**0.** This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). Each +licensee is addressed as "you". + +A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control +compilation and installation of the library. + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does and +what the program that uses the Library does. + +**1.** You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a +fee. + +**2.** You may modify your copy or copies of the Library or any +portion of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + +- **a)** The modified work must itself be a software library. +- **b)** You must cause the files modified to carry prominent + notices stating that you changed the files and the date of + any change. +- **c)** You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. +- **d)** If a facility in the modified Library refers to a function + or a table of data to be supplied by an application program that + uses the facility, other than as an argument passed when the + facility is invoked, then you must make a good faith effort to + ensure that, in the event an application does not supply such + function or table, the facility still operates, and performs + whatever part of its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of + the application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + +**3.** You may opt to apply the terms of the ordinary GNU General +Public License instead of this License to a given copy of the Library. +To do this, you must alter all the notices that refer to this License, +so that they refer to the ordinary GNU General Public License, version +2, instead of to this License. (If a newer version than version 2 of +the ordinary GNU General Public License has appeared, then you can +specify that version instead if you wish.) Do not make any other +change in these notices. + +Once this change is made in a given copy, it is irreversible for that +copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the +Library into a program that is not a library. + +**4.** You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from +a designated place, then offering equivalent access to copy the source +code from the same place satisfies the requirement to distribute the +source code, even though third parties are not compelled to copy the +source along with the object code. + +**5.** A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a work, +in isolation, is not a derivative work of the Library, and therefore +falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. Section +6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure +layouts and accessors, and small macros and small inline functions +(ten lines or less in length), then the use of the object file is +unrestricted, regardless of whether it is legally a derivative work. +(Executables containing this object code plus portions of the Library +will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + +**6.** As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a work +containing portions of the Library, and distribute that work under +terms of your choice, provided that the terms permit modification of +the work for the customer's own use and reverse engineering for +debugging such modifications. + +You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + +- **a)** Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood that + the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) +- **b)** Use a suitable shared library mechanism for linking with + the Library. A suitable mechanism is one that (1) uses at run time + a copy of the library already present on the user's computer + system, rather than copying library functions into the executable, + and (2) will operate properly with a modified version of the + library, if the user installs one, as long as the modified version + is interface-compatible with the version that the work was + made with. +- **c)** Accompany the work with a written offer, valid for at least + three years, to give the same user the materials specified in + Subsection 6a, above, for a charge no more than the cost of + performing this distribution. +- **d)** If distribution of the work is made by offering access to + copy from a designated place, offer equivalent access to copy the + above specified materials from the same place. +- **e)** Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + +It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + +**7.** You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + +- **a)** Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other + library facilities. This must be distributed under the terms of + the Sections above. +- **b)** Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + +**8.** You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + +**9.** You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + +**10.** Each time you redistribute the Library (or any work based on +the Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + +**11.** If, as a consequence of a court judgment or allegation of +patent infringement or for any other reason (not limited to patent +issues), conditions are imposed on you (whether by court order, +agreement or otherwise) that contradict the conditions of this +License, they do not excuse you from the conditions of this License. +If you cannot distribute so as to satisfy simultaneously your +obligations under this License and any other pertinent obligations, +then as a consequence you may not distribute the Library at all. For +example, if a patent license would not permit royalty-free +redistribution of the Library by all those who receive copies directly +or indirectly through you, then the only way you could satisfy both it +and this License would be to refrain entirely from distribution of the +Library. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply, and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + +**12.** If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + +**13.** The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. Such +new versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + +**14.** If you wish to incorporate parts of the Library into other +free programs whose distribution conditions are incompatible with +these, write to the author to ask for permission. For software which +is copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + +**NO WARRANTY** + +**15.** BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +**16.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + +### END OF TERMS AND CONDITIONS + +### How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms +of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It +is safest to attach them to the start of each source file to most +effectively convey the exclusion of warranty; and each file should +have at least the "copyright" line and a pointer to where the full +notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper +mail. + +You should also get your employer (if you work as a programmer) or +your school, if any, to sign a "copyright disclaimer" for the library, +if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in + the library `Frob' (a library for tweaking knobs) written + by James Random Hacker. + + signature of Ty Coon, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! \ No newline at end of file diff --git a/Makefile.projbuild b/Makefile.projbuild index e21d4c77b93..26b43787a6f 100644 --- a/Makefile.projbuild +++ b/Makefile.projbuild @@ -1,17 +1,7 @@ -BOOT_APP_BIN_OFFSET := 0xe000 BOOT_APP_BIN_ROOT := $(call dequote,$(COMPONENT_PATH)) -BOOT_APP_BIN_PATH := $(call dequote,$(abspath $(BOOT_APP_BIN_ROOT)/$(subst $(quote),,tools/partitions/boot_app0.bin))) ifndef CONFIG_PARTITION_TABLE_CUSTOM PARTITION_TABLE_CSV_PATH = $(call dequote,$(abspath $(BOOT_APP_BIN_ROOT)/$(subst $(quote),,tools/partitions/$(CONFIG_ARDUHAL_PARTITION_SCHEME).csv))) endif -BOOT_APP_BIN_FLASH_CMD = $(ESPTOOLPY_SERIAL) write_flash $(BOOT_APP_BIN_OFFSET) $(BOOT_APP_BIN_PATH) -ESPTOOL_ALL_FLASH_ARGS += $(BOOT_APP_BIN_OFFSET) $(BOOT_APP_BIN_PATH) - -CPPFLAGS += -DARDUINO=10800 -DESP32=1 -DARDUINO_ARCH_ESP32=1 - -boot-app0: - @echo "Rebooting to APP0" - $(BOOT_APP_BIN_FLASH_CMD) - +CPPFLAGS += -DARDUINO=10800 -DESP32=1 -DARDUINO_ARCH_ESP32=1 -DBOARD_HAS_PSRAM diff --git a/README.md b/README.md index 4c0c046e5a8..27f18c077cc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ -# Arduino core for ESP32 WiFi chip - -[![Build Status](https://travis-ci.org/espressif/arduino-esp32.svg?branch=master)](https://travis-ci.org/espressif/arduino-esp32) +# Arduino core for the ESP32 +[![Build Status](https://travis-ci.org/espressif/arduino-esp32.svg?branch=master)](https://travis-ci.org/espressif/arduino-esp32) ![](https://github.com/espressif/arduino-esp32/workflows/ESP32%20Arduino%20CI/badge.svg) ### Need help or have a question? Join the chat at [![https://gitter.im/espressif/arduino-esp32](https://badges.gitter.im/espressif/arduino-esp32.svg)](https://gitter.im/espressif/arduino-esp32?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -11,15 +10,15 @@ - [Issue/Bug report template](#issuebug-report-template) - [ESP32Dev Board PINMAP](#esp32dev-board-pinmap) -## Development Status -Most of the framework is implemented. Most noticable is the missing analogWrite. While analogWrite is on it's way, there are a few other options that you can use: -- 16 channels [LEDC](cores/esp32/esp32-hal-ledc.h) which is PWM -- 8 channels [SigmaDelta](cores/esp32/esp32-hal-sigmadelta.h) which uses SigmaDelta modulation -- 2 channels [DAC](cores/esp32/esp32-hal-dac.h) which gives real analog output +### Development Status +[Latest stable release ![Release Version](https://img.shields.io/github/release/espressif/arduino-esp32.svg?style=plastic) ![Release Date](https://img.shields.io/github/release-date/espressif/arduino-esp32.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/) ![Downloads](https://img.shields.io/github/downloads/espressif/arduino-esp32/latest/total.svg?style=plastic) -## Installation Instructions +[Latest development release ![Development Version](https://img.shields.io/github/release/espressif/arduino-esp32/all.svg?style=plastic) ![Development Date](https://img.shields.io/github/release-date-pre/espressif/arduino-esp32.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/) ![Downloads](https://img.shields.io/github/downloads-pre/espressif/arduino-esp32/latest/total.svg?style=plastic) -- Using Arduino IDE +### Installation Instructions +- Using Arduino IDE Boards Manager (preferred) + + [Instructions for Boards Manager](docs/arduino-ide/boards_manager.md) +- Using Arduino IDE with the development repository + [Instructions for Windows](docs/arduino-ide/windows.md) + [Instructions for Mac](docs/arduino-ide/mac.md) + [Instructions for Debian/Ubuntu Linux](docs/arduino-ide/debian_ubuntu.md) @@ -28,21 +27,21 @@ Most of the framework is implemented. Most noticable is the missing analogWrite. - [Using PlatformIO](docs/platformio.md) - [Building with make](docs/make.md) - [Using as ESP-IDF component](docs/esp-idf_component.md) +- [Using OTAWebUpdater](docs/OTAWebUpdate/OTAWebUpdate.md) -#### Decoding exceptions +### Decoding exceptions You can use [EspExceptionDecoder](https://github.com/me-no-dev/EspExceptionDecoder) to get meaningful call trace. -#### Issue/Bug report template +### Issue/Bug report template Before reporting an issue, make sure you've searched for similar one that was already created. Also make sure to go through all the issues labelled as [for reference](https://github.com/espressif/arduino-esp32/issues?utf8=%E2%9C%93&q=is%3Aissue%20label%3A%22for%20reference%22%20). -Finally, if you're sure no one else had the issue, follow the [ISSUE_TEMPLATE](docs/ISSUE_TEMPLATE.md) while reporting any issue. - +Finally, if you are sure no one else had the issue, follow the [ISSUE_TEMPLATE](docs/ISSUE_TEMPLATE.md) while reporting any issue. -## ESP32Dev Board PINMAP +### ESP32Dev Board PINMAP ![Pin Functions](docs/esp32_pinmap.png) -## Hint +### Tip Sometimes to program ESP32 via serial you must keep GPIO0 LOW during the programming process diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 62bdcce8883..00000000000 --- a/appveyor.yml +++ /dev/null @@ -1,19 +0,0 @@ -build: off -environment: - - matrix: - - PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiClient" - - PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiClientBasic" - - PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiClientEvents" - - PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiIPv6" - - PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiScan" - - PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiSmartConfig" - -install: - - cmd: git submodule update --init --recursive - - cmd: SET PATH=%PATH%;C:\Python27\Scripts - - cmd: pip install -U https://github.com/platformio/platformio/archive/develop.zip - - cmd: platformio platform install https://github.com/platformio/platform-espressif32.git#feature/stage - -test_script: - - cmd: platformio ci -b esp32dev -b nano32 -b node32s diff --git a/boards.txt b/boards.txt index 6a78f4e26c9..9c821ef4e35 100644 --- a/boards.txt +++ b/boards.txt @@ -1,17 +1,22 @@ menu.UploadSpeed=Upload Speed +menu.CPUFreq=CPU Frequency menu.FlashFreq=Flash Frequency menu.FlashMode=Flash Mode menu.FlashSize=Flash Size menu.PartitionScheme=Partition Scheme menu.DebugLevel=Core Debug Level +menu.PSRAM=PSRAM +menu.Revision=Board Revision +############################################################## +### DO NOT PUT BOARDS ABOVE THE OFFICIAL ESPRESSIF BOARDS! ### ############################################################## esp32.name=ESP32 Dev Module -esp32.upload.tool=esptool +esp32.upload.tool=esptool_py esp32.upload.maximum_size=1310720 -esp32.upload.maximum_data_size=294912 +esp32.upload.maximum_data_size=327680 esp32.upload.wait_for_upload_port=true esp32.serial.disableDTR=true @@ -28,15 +33,63 @@ esp32.build.flash_freq=40m esp32.build.flash_mode=dio esp32.build.boot=dio esp32.build.partitions=default +esp32.build.defines= + +esp32.menu.PSRAM.disabled=Disabled +esp32.menu.PSRAM.disabled.build.defines= +esp32.menu.PSRAM.enabled=Enabled +esp32.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue -esp32.menu.PartitionScheme.default=Default +esp32.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS) esp32.menu.PartitionScheme.default.build.partitions=default -esp32.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +esp32.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS) +esp32.menu.PartitionScheme.defaultffat.build.partitions=default_ffat +esp32.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT) +esp32.menu.PartitionScheme.default_8MB.build.partitions=default_8MB +esp32.menu.PartitionScheme.default_8MB.upload.maximum_size=3342336 +esp32.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS) esp32.menu.PartitionScheme.minimal.build.partitions=minimal -esp32.menu.PartitionScheme.no_ota=No OTA (Large APP) +esp32.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS) esp32.menu.PartitionScheme.no_ota.build.partitions=no_ota -esp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +esp32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS) +esp32.menu.PartitionScheme.noota_3g.build.partitions=noota_3g +esp32.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576 +esp32.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS) +esp32.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat +esp32.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152 +esp32.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS) +esp32.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat +esp32.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576 +esp32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS) +esp32.menu.PartitionScheme.huge_app.build.partitions=huge_app +esp32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +esp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS) esp32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +esp32.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT) +esp32.menu.PartitionScheme.fatflash.build.partitions=ffat +esp32.menu.PartitionScheme.fatflash.upload.maximum_size=2097152 +esp32.menu.PartitionScheme.app3M_fat9M_16MB=16M Flash (3MB APP/9MB FATFS) +esp32.menu.PartitionScheme.app3M_fat9M_16MB.build.partitions=app3M_fat9M_16MB +esp32.menu.PartitionScheme.app3M_fat9M_16MB.upload.maximum_size=3145728 + +esp32.menu.CPUFreq.240=240MHz (WiFi/BT) +esp32.menu.CPUFreq.240.build.f_cpu=240000000L +esp32.menu.CPUFreq.160=160MHz (WiFi/BT) +esp32.menu.CPUFreq.160.build.f_cpu=160000000L +esp32.menu.CPUFreq.80=80MHz (WiFi/BT) +esp32.menu.CPUFreq.80.build.f_cpu=80000000L +esp32.menu.CPUFreq.40=40MHz (40MHz XTAL) +esp32.menu.CPUFreq.40.build.f_cpu=40000000L +esp32.menu.CPUFreq.26=26MHz (26MHz XTAL) +esp32.menu.CPUFreq.26.build.f_cpu=26000000L +esp32.menu.CPUFreq.20=20MHz (40MHz XTAL) +esp32.menu.CPUFreq.20.build.f_cpu=20000000L +esp32.menu.CPUFreq.13=13MHz (26MHz XTAL) +esp32.menu.CPUFreq.13.build.f_cpu=13000000L +esp32.menu.CPUFreq.10=10MHz (40MHz XTAL) +esp32.menu.CPUFreq.10.build.f_cpu=10000000L esp32.menu.FlashMode.qio=QIO esp32.menu.FlashMode.qio.build.flash_mode=dio @@ -58,9 +111,14 @@ esp32.menu.FlashFreq.40.build.flash_freq=40m esp32.menu.FlashSize.4M=4MB (32Mb) esp32.menu.FlashSize.4M.build.flash_size=4MB +esp32.menu.FlashSize.8M=8MB (64Mb) +esp32.menu.FlashSize.8M.build.flash_size=8MB +esp32.menu.FlashSize.8M.build.partitions=default_8MB esp32.menu.FlashSize.2M=2MB (16Mb) esp32.menu.FlashSize.2M.build.flash_size=2MB esp32.menu.FlashSize.2M.build.partitions=minimal +esp32.menu.FlashSize.16M=16MB (128Mb) +esp32.menu.FlashSize.16M.build.flash_size=16MB esp32.menu.UploadSpeed.921600=921600 esp32.menu.UploadSpeed.921600.upload.speed=921600 @@ -92,11 +150,110 @@ esp32.menu.DebugLevel.verbose.build.code_debug=5 ############################################################## +esp32wrover.name=ESP32 Wrover Module + +esp32wrover.upload.tool=esptool_py +esp32wrover.upload.maximum_size=1310720 +esp32wrover.upload.maximum_data_size=327680 +esp32wrover.upload.wait_for_upload_port=true + +esp32wrover.serial.disableDTR=true +esp32wrover.serial.disableRTS=true + +esp32wrover.build.mcu=esp32 +esp32wrover.build.core=esp32 +esp32wrover.build.variant=esp32 +esp32wrover.build.board=ESP32_DEV + +esp32wrover.build.f_cpu=240000000L +esp32wrover.build.flash_size=4MB +esp32wrover.build.flash_freq=40m +esp32wrover.build.flash_mode=dio +esp32wrover.build.boot=dio +esp32wrover.build.partitions=default +esp32wrover.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +esp32wrover.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS) +esp32wrover.menu.PartitionScheme.default.build.partitions=default +esp32wrover.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS) +esp32wrover.menu.PartitionScheme.defaultffat.build.partitions=default_ffat +esp32wrover.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT) +esp32wrover.menu.PartitionScheme.default_8MB.build.partitions=default_8MB +esp32wrover.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS) +esp32wrover.menu.PartitionScheme.minimal.build.partitions=minimal +esp32wrover.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS) +esp32wrover.menu.PartitionScheme.no_ota.build.partitions=no_ota +esp32wrover.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32wrover.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS) +esp32wrover.menu.PartitionScheme.noota_3g.build.partitions=noota_3g +esp32wrover.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576 +esp32wrover.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS) +esp32wrover.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat +esp32wrover.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152 +esp32wrover.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS) +esp32wrover.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat +esp32wrover.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576 +esp32wrover.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS) +esp32wrover.menu.PartitionScheme.huge_app.build.partitions=huge_app +esp32wrover.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +esp32wrover.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS) +esp32wrover.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32wrover.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +esp32wrover.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT) +esp32wrover.menu.PartitionScheme.fatflash.build.partitions=ffat + +esp32wrover.menu.FlashMode.qio=QIO +esp32wrover.menu.FlashMode.qio.build.flash_mode=dio +esp32wrover.menu.FlashMode.qio.build.boot=qio +esp32wrover.menu.FlashMode.dio=DIO +esp32wrover.menu.FlashMode.dio.build.flash_mode=dio +esp32wrover.menu.FlashMode.dio.build.boot=dio +esp32wrover.menu.FlashMode.qout=QOUT +esp32wrover.menu.FlashMode.qout.build.flash_mode=dout +esp32wrover.menu.FlashMode.qout.build.boot=qout +esp32wrover.menu.FlashMode.dout=DOUT +esp32wrover.menu.FlashMode.dout.build.flash_mode=dout +esp32wrover.menu.FlashMode.dout.build.boot=dout + +esp32wrover.menu.FlashFreq.80=80MHz +esp32wrover.menu.FlashFreq.80.build.flash_freq=80m +esp32wrover.menu.FlashFreq.40=40MHz +esp32wrover.menu.FlashFreq.40.build.flash_freq=40m + +esp32wrover.menu.UploadSpeed.921600=921600 +esp32wrover.menu.UploadSpeed.921600.upload.speed=921600 +esp32wrover.menu.UploadSpeed.115200=115200 +esp32wrover.menu.UploadSpeed.115200.upload.speed=115200 +esp32wrover.menu.UploadSpeed.256000.windows=256000 +esp32wrover.menu.UploadSpeed.256000.upload.speed=256000 +esp32wrover.menu.UploadSpeed.230400.windows.upload.speed=256000 +esp32wrover.menu.UploadSpeed.230400=230400 +esp32wrover.menu.UploadSpeed.230400.upload.speed=230400 +esp32wrover.menu.UploadSpeed.460800.linux=460800 +esp32wrover.menu.UploadSpeed.460800.macosx=460800 +esp32wrover.menu.UploadSpeed.460800.upload.speed=460800 +esp32wrover.menu.UploadSpeed.512000.windows=512000 +esp32wrover.menu.UploadSpeed.512000.upload.speed=512000 + +esp32wrover.menu.DebugLevel.none=None +esp32wrover.menu.DebugLevel.none.build.code_debug=0 +esp32wrover.menu.DebugLevel.error=Error +esp32wrover.menu.DebugLevel.error.build.code_debug=1 +esp32wrover.menu.DebugLevel.warn=Warn +esp32wrover.menu.DebugLevel.warn.build.code_debug=2 +esp32wrover.menu.DebugLevel.info=Info +esp32wrover.menu.DebugLevel.info.build.code_debug=3 +esp32wrover.menu.DebugLevel.debug=Debug +esp32wrover.menu.DebugLevel.debug.build.code_debug=4 +esp32wrover.menu.DebugLevel.verbose=Verbose +esp32wrover.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## pico32.name=ESP32 Pico Kit -pico32.upload.tool=esptool +pico32.upload.tool=esptool_py pico32.upload.maximum_size=1310720 -pico32.upload.maximum_data_size=294912 +pico32.upload.maximum_data_size=327680 pico32.upload.wait_for_upload_port=true pico32.serial.disableDTR=true @@ -113,6 +270,16 @@ pico32.build.flash_freq=80m pico32.build.flash_mode=dio pico32.build.boot=dio pico32.build.partitions=default +pico32.build.defines= + +pico32.menu.PartitionScheme.default=Default +pico32.menu.PartitionScheme.default.build.partitions=default +pico32.menu.PartitionScheme.no_ota=No OTA (Large APP) +pico32.menu.PartitionScheme.no_ota.build.partitions=no_ota +pico32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +pico32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +pico32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +pico32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 pico32.menu.UploadSpeed.921600=921600 pico32.menu.UploadSpeed.921600.upload.speed=921600 @@ -144,11 +311,421 @@ pico32.menu.DebugLevel.verbose.build.code_debug=5 ############################################################## +tinypico.name=TinyPICO + +tinypico.upload.tool=esptool_py +tinypico.upload.maximum_size=1310720 +tinypico.upload.maximum_data_size=327680 +tinypico.upload.wait_for_upload_port=true + +tinypico.serial.disableDTR=true +tinypico.serial.disableRTS=true + +tinypico.build.mcu=esp32 +tinypico.build.core=esp32 +tinypico.build.variant=pico32 +tinypico.build.board=ESP32_PICO + +tinypico.build.f_cpu=240000000L +tinypico.build.flash_size=4MB +tinypico.build.flash_freq=80m +tinypico.build.flash_mode=dio +tinypico.build.boot=dio +tinypico.build.partitions=default +tinypico.build.defines= + +tinypico.menu.PartitionScheme.default=Default +tinypico.menu.PartitionScheme.default.build.partitions=default +tinypico.menu.PartitionScheme.no_ota=No OTA (Large APP) +tinypico.menu.PartitionScheme.no_ota.build.partitions=no_ota +tinypico.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +tinypico.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +tinypico.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +tinypico.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +tinypico.menu.UploadSpeed.921600=921600 +tinypico.menu.UploadSpeed.921600.upload.speed=921600 +tinypico.menu.UploadSpeed.115200=115200 +tinypico.menu.UploadSpeed.115200.upload.speed=115200 +tinypico.menu.UploadSpeed.256000.windows=256000 +tinypico.menu.UploadSpeed.256000.upload.speed=256000 +tinypico.menu.UploadSpeed.230400.windows.upload.speed=256000 +tinypico.menu.UploadSpeed.230400=230400 +tinypico.menu.UploadSpeed.230400.upload.speed=230400 +tinypico.menu.UploadSpeed.460800.linux=460800 +tinypico.menu.UploadSpeed.460800.macosx=460800 +tinypico.menu.UploadSpeed.460800.upload.speed=460800 +tinypico.menu.UploadSpeed.512000.windows=512000 +tinypico.menu.UploadSpeed.512000.upload.speed=512000 + +tinypico.menu.FlashMode.qio=QIO +tinypico.menu.FlashMode.qio.build.flash_mode=dio +tinypico.menu.FlashMode.qio.build.boot=qio +tinypico.menu.FlashMode.dio=DIO +tinypico.menu.FlashMode.dio.build.flash_mode=dio +tinypico.menu.FlashMode.dio.build.boot=dio + +tinypico.menu.FlashFreq.80=80MHz +tinypico.menu.FlashFreq.80.build.flash_freq=80m +tinypico.menu.FlashFreq.40=40MHz +tinypico.menu.FlashFreq.40.build.flash_freq=40m + +tinypico.menu.PSRAM.enabled=Enabled +tinypico.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue +tinypico.menu.PSRAM.disabled=Disabled +tinypico.menu.PSRAM.disabled.build.defines= + +tinypico.menu.DebugLevel.none=None +tinypico.menu.DebugLevel.none.build.code_debug=0 +tinypico.menu.DebugLevel.error=Error +tinypico.menu.DebugLevel.error.build.code_debug=1 +tinypico.menu.DebugLevel.warn=Warn +tinypico.menu.DebugLevel.warn.build.code_debug=2 +tinypico.menu.DebugLevel.info=Info +tinypico.menu.DebugLevel.info.build.code_debug=3 +tinypico.menu.DebugLevel.debug=Debug +tinypico.menu.DebugLevel.debug.build.code_debug=4 +tinypico.menu.DebugLevel.verbose=Verbose +tinypico.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## +magicbit.name=MagicBit + +magicbit.upload.tool=esptool_py +magicbit.upload.maximum_size=1310720 +magicbit.upload.maximum_data_size=327680 +magicbit.upload.wait_for_upload_port=true + +magicbit.serial.disableDTR=true +magicbit.serial.disableRTS=true + +magicbit.build.mcu=esp32 +magicbit.build.core=esp32 +magicbit.build.variant=magicbit +magicbit.build.board=ESP32_DEV + +magicbit.build.f_cpu=240000000L +magicbit.build.flash_size=4MB +magicbit.build.flash_freq=40m +magicbit.build.flash_mode=dio +magicbit.build.boot=dio +magicbit.build.partitions=default + +magicbit.menu.CPUFreq.240=240MHz (WiFi/BT) +magicbit.menu.CPUFreq.240.build.f_cpu=240000000L +magicbit.menu.CPUFreq.160=160MHz (WiFi/BT) +magicbit.menu.CPUFreq.160.build.f_cpu=160000000L +magicbit.menu.CPUFreq.80=80MHz (WiFi/BT) +magicbit.menu.CPUFreq.80.build.f_cpu=80000000L +magicbit.menu.CPUFreq.40=40MHz (40MHz XTAL) + +magicbit.menu.UploadSpeed.921600=921600 +magicbit.menu.UploadSpeed.921600.upload.speed=921600 +magicbit.menu.UploadSpeed.115200=115200 +magicbit.menu.UploadSpeed.115200.upload.speed=115200 +############################################################## +turta_iot_node.name=Turta IoT Node + +turta_iot_node.upload.tool=esptool_py +turta_iot_node.upload.maximum_size=1310720 +turta_iot_node.upload.maximum_data_size=327680 +turta_iot_node.upload.wait_for_upload_port=true + +turta_iot_node.serial.disableDTR=true +turta_iot_node.serial.disableRTS=true + +turta_iot_node.build.mcu=esp32 +turta_iot_node.build.core=esp32 +turta_iot_node.build.variant=pico32 +turta_iot_node.build.board=ESP32_PICO + +turta_iot_node.build.f_cpu=240000000L +turta_iot_node.build.flash_size=4MB +turta_iot_node.build.flash_freq=80m +turta_iot_node.build.flash_mode=dio +turta_iot_node.build.boot=dio +turta_iot_node.build.partitions=default +turta_iot_node.build.defines= + +turta_iot_node.menu.UploadSpeed.921600=921600 +turta_iot_node.menu.UploadSpeed.921600.upload.speed=921600 +turta_iot_node.menu.UploadSpeed.115200=115200 +turta_iot_node.menu.UploadSpeed.115200.upload.speed=115200 + +turta_iot_node.menu.DebugLevel.none=None +turta_iot_node.menu.DebugLevel.none.build.code_debug=0 +turta_iot_node.menu.DebugLevel.error=Error +turta_iot_node.menu.DebugLevel.error.build.code_debug=1 +turta_iot_node.menu.DebugLevel.warn=Warn +turta_iot_node.menu.DebugLevel.warn.build.code_debug=2 +turta_iot_node.menu.DebugLevel.info=Info +turta_iot_node.menu.DebugLevel.info.build.code_debug=3 +turta_iot_node.menu.DebugLevel.debug=Debug +turta_iot_node.menu.DebugLevel.debug.build.code_debug=4 +turta_iot_node.menu.DebugLevel.verbose=Verbose +turta_iot_node.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +ttgo-lora32-v1.name=TTGO LoRa32-OLED V1 + +ttgo-lora32-v1.upload.tool=esptool_py +ttgo-lora32-v1.upload.maximum_size=1310720 +ttgo-lora32-v1.upload.maximum_data_size=294912 +ttgo-lora32-v1.upload.wait_for_upload_port=true + +ttgo-lora32-v1.serial.disableDTR=true +ttgo-lora32-v1.serial.disableRTS=true + +ttgo-lora32-v1.build.mcu=esp32 +ttgo-lora32-v1.build.core=esp32 +ttgo-lora32-v1.build.variant=ttgo-lora32-v1 +ttgo-lora32-v1.build.board=TTGO_LoRa32_V1 + +ttgo-lora32-v1.build.f_cpu=240000000L +ttgo-lora32-v1.build.flash_mode=dio +ttgo-lora32-v1.build.flash_size=4MB +ttgo-lora32-v1.build.boot=dio +ttgo-lora32-v1.build.partitions=default + +ttgo-lora32-v1.menu.FlashFreq.80=80MHz +ttgo-lora32-v1.menu.FlashFreq.80.build.flash_freq=80m +ttgo-lora32-v1.menu.FlashFreq.40=40MHz +ttgo-lora32-v1.menu.FlashFreq.40.build.flash_freq=40m + +ttgo-lora32-v1.menu.UploadSpeed.921600=921600 +ttgo-lora32-v1.menu.UploadSpeed.921600.upload.speed=921600 +ttgo-lora32-v1.menu.UploadSpeed.115200=115200 +ttgo-lora32-v1.menu.UploadSpeed.115200.upload.speed=115200 +ttgo-lora32-v1.menu.UploadSpeed.256000.windows=256000 +ttgo-lora32-v1.menu.UploadSpeed.256000.upload.speed=256000 +ttgo-lora32-v1.menu.UploadSpeed.230400.windows.upload.speed=256000 +ttgo-lora32-v1.menu.UploadSpeed.230400=230400 +ttgo-lora32-v1.menu.UploadSpeed.230400.upload.speed=230400 +ttgo-lora32-v1.menu.UploadSpeed.460800.linux=460800 +ttgo-lora32-v1.menu.UploadSpeed.460800.macosx=460800 +ttgo-lora32-v1.menu.UploadSpeed.460800.upload.speed=460800 +ttgo-lora32-v1.menu.UploadSpeed.512000.windows=512000 +ttgo-lora32-v1.menu.UploadSpeed.512000.upload.speed=512000 + +ttgo-lora32-v1.menu.DebugLevel.none=None +ttgo-lora32-v1.menu.DebugLevel.none.build.code_debug=0 +ttgo-lora32-v1.menu.DebugLevel.error=Error +ttgo-lora32-v1.menu.DebugLevel.error.build.code_debug=1 +ttgo-lora32-v1.menu.DebugLevel.warn=Warn +ttgo-lora32-v1.menu.DebugLevel.warn.build.code_debug=2 +ttgo-lora32-v1.menu.DebugLevel.info=Info +ttgo-lora32-v1.menu.DebugLevel.info.build.code_debug=3 +ttgo-lora32-v1.menu.DebugLevel.debug=Debug +ttgo-lora32-v1.menu.DebugLevel.debug.build.code_debug=4 +ttgo-lora32-v1.menu.DebugLevel.verbose=Verbose +ttgo-lora32-v1.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +ttgo-t1.name=TTGO T1 + +ttgo-t1.upload.tool=esptool_py +ttgo-t1.upload.maximum_size=1310720 +ttgo-t1.upload.maximum_data_size=327680 +ttgo-t1.upload.wait_for_upload_port=true + +ttgo-t1.serial.disableDTR=true +ttgo-t1.serial.disableRTS=true + +ttgo-t1.build.mcu=esp32 +ttgo-t1.build.core=esp32 +ttgo-t1.build.variant=ttgo-t1 +ttgo-t1.build.board=TTGO_T1 + +ttgo-t1.build.f_cpu=240000000L +ttgo-t1.build.flash_size=4MB +ttgo-t1.build.flash_freq=40m +ttgo-t1.build.flash_mode=dio +ttgo-t1.build.boot=dio +ttgo-t1.build.partitions=default +ttgo-t1.build.defines= + +ttgo-t1.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS) +ttgo-t1.menu.PartitionScheme.default.build.partitions=default +ttgo-t1.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS) +ttgo-t1.menu.PartitionScheme.defaultffat.build.partitions=default_ffat +ttgo-t1.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS) +ttgo-t1.menu.PartitionScheme.minimal.build.partitions=minimal +ttgo-t1.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS) +ttgo-t1.menu.PartitionScheme.no_ota.build.partitions=no_ota +ttgo-t1.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +ttgo-t1.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS) +ttgo-t1.menu.PartitionScheme.noota_3g.build.partitions=noota_3g +ttgo-t1.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576 +ttgo-t1.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS) +ttgo-t1.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat +ttgo-t1.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152 +ttgo-t1.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS) +ttgo-t1.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat +ttgo-t1.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576 +ttgo-t1.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS) +ttgo-t1.menu.PartitionScheme.huge_app.build.partitions=huge_app +ttgo-t1.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +ttgo-t1.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS) +ttgo-t1.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +ttgo-t1.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +ttgo-t1.menu.CPUFreq.240=240MHz (WiFi/BT) +ttgo-t1.menu.CPUFreq.240.build.f_cpu=240000000L +ttgo-t1.menu.CPUFreq.160=160MHz (WiFi/BT) +ttgo-t1.menu.CPUFreq.160.build.f_cpu=160000000L +ttgo-t1.menu.CPUFreq.80=80MHz (WiFi/BT) +ttgo-t1.menu.CPUFreq.80.build.f_cpu=80000000L +ttgo-t1.menu.CPUFreq.40=40MHz (40MHz XTAL) +ttgo-t1.menu.CPUFreq.40.build.f_cpu=40000000L +ttgo-t1.menu.CPUFreq.26=26MHz (26MHz XTAL) +ttgo-t1.menu.CPUFreq.26.build.f_cpu=26000000L +ttgo-t1.menu.CPUFreq.20=20MHz (40MHz XTAL) +ttgo-t1.menu.CPUFreq.20.build.f_cpu=20000000L +ttgo-t1.menu.CPUFreq.13=13MHz (26MHz XTAL) +ttgo-t1.menu.CPUFreq.13.build.f_cpu=13000000L +ttgo-t1.menu.CPUFreq.10=10MHz (40MHz XTAL) +ttgo-t1.menu.CPUFreq.10.build.f_cpu=10000000L + +ttgo-t1.menu.FlashMode.qio=QIO +ttgo-t1.menu.FlashMode.qio.build.flash_mode=dio +ttgo-t1.menu.FlashMode.qio.build.boot=qio +ttgo-t1.menu.FlashMode.dio=DIO +ttgo-t1.menu.FlashMode.dio.build.flash_mode=dio +ttgo-t1.menu.FlashMode.dio.build.boot=dio +ttgo-t1.menu.FlashMode.qout=QOUT +ttgo-t1.menu.FlashMode.qout.build.flash_mode=dout +ttgo-t1.menu.FlashMode.qout.build.boot=qout +ttgo-t1.menu.FlashMode.dout=DOUT +ttgo-t1.menu.FlashMode.dout.build.flash_mode=dout +ttgo-t1.menu.FlashMode.dout.build.boot=dout + +ttgo-t1.menu.FlashFreq.80=80MHz +ttgo-t1.menu.FlashFreq.80.build.flash_freq=80m +ttgo-t1.menu.FlashFreq.40=40MHz +ttgo-t1.menu.FlashFreq.40.build.flash_freq=40m + +ttgo-t1.menu.FlashSize.4M=4MB (32Mb) +ttgo-t1.menu.FlashSize.4M.build.flash_size=4MB +ttgo-t1.menu.FlashSize.2M=2MB (16Mb) +ttgo-t1.menu.FlashSize.2M.build.flash_size=2MB +ttgo-t1.menu.FlashSize.2M.build.partitions=minimal +ttgo-t1.menu.FlashSize.16M=16MB (128Mb) +ttgo-t1.menu.FlashSize.16M.build.flash_size=16MB +ttgo-t1.menu.FlashSize.16M.build.partitions=ffat + +ttgo-t1.menu.UploadSpeed.921600=921600 +ttgo-t1.menu.UploadSpeed.921600.upload.speed=921600 +ttgo-t1.menu.UploadSpeed.115200=115200 +ttgo-t1.menu.UploadSpeed.115200.upload.speed=115200 +ttgo-t1.menu.UploadSpeed.256000.windows=256000 +ttgo-t1.menu.UploadSpeed.256000.upload.speed=256000 +ttgo-t1.menu.UploadSpeed.230400.windows.upload.speed=256000 +ttgo-t1.menu.UploadSpeed.230400=230400 +ttgo-t1.menu.UploadSpeed.230400.upload.speed=230400 +ttgo-t1.menu.UploadSpeed.460800.linux=460800 +ttgo-t1.menu.UploadSpeed.460800.macosx=460800 +ttgo-t1.menu.UploadSpeed.460800.upload.speed=460800 +ttgo-t1.menu.UploadSpeed.512000.windows=512000 +ttgo-t1.menu.UploadSpeed.512000.upload.speed=512000 + +ttgo-t1.menu.DebugLevel.none=None +ttgo-t1.menu.DebugLevel.none.build.code_debug=0 +ttgo-t1.menu.DebugLevel.error=Error +ttgo-t1.menu.DebugLevel.error.build.code_debug=1 +ttgo-t1.menu.DebugLevel.warn=Warn +ttgo-t1.menu.DebugLevel.warn.build.code_debug=2 +ttgo-t1.menu.DebugLevel.info=Info +ttgo-t1.menu.DebugLevel.info.build.code_debug=3 +ttgo-t1.menu.DebugLevel.debug=Debug +ttgo-t1.menu.DebugLevel.debug.build.code_debug=4 +ttgo-t1.menu.DebugLevel.verbose=Verbose +ttgo-t1.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +cw02.name=XinaBox CW02 + +cw02.upload.tool=esptool_py +cw02.upload.maximum_size=1310720 +cw02.upload.maximum_data_size=294912 +cw02.upload.wait_for_upload_port=true + +cw02.serial.disableDTR=true +cw02.serial.disableRTS=true + +cw02.build.mcu=esp32 +cw02.build.core=esp32 +cw02.build.variant=xinabox +cw02.build.board=ESP32_DEV + +cw02.build.f_cpu=240000000L +cw02.build.flash_size=4MB +cw02.build.flash_freq=40m +cw02.build.flash_mode=dio +cw02.build.boot=dio +cw02.build.partitions=default + +cw02.menu.FlashMode.qio=QIO +cw02.menu.FlashMode.qio.build.flash_mode=dio +cw02.menu.FlashMode.qio.build.boot=qio +cw02.menu.FlashMode.dio=DIO +cw02.menu.FlashMode.dio.build.flash_mode=dio +cw02.menu.FlashMode.dio.build.boot=dio +cw02.menu.FlashMode.qout=QOUT +cw02.menu.FlashMode.qout.build.flash_mode=dout +cw02.menu.FlashMode.qout.build.boot=qout +cw02.menu.FlashMode.dout=DOUT +cw02.menu.FlashMode.dout.build.flash_mode=dout +cw02.menu.FlashMode.dout.build.boot=dout + +cw02.menu.FlashFreq.80=80MHz +cw02.menu.FlashFreq.80.build.flash_freq=80m +cw02.menu.FlashFreq.40=40MHz +cw02.menu.FlashFreq.40.build.flash_freq=40m + +cw02.menu.FlashSize.4M=4MB (32Mb) +cw02.menu.FlashSize.4M.build.flash_size=4MB +cw02.menu.FlashSize.2M=2MB (16Mb) +cw02.menu.FlashSize.2M.build.flash_size=2MB +cw02.menu.FlashSize.2M.build.partitions=minimal + +cw02.menu.UploadSpeed.921600=921600 +cw02.menu.UploadSpeed.921600.upload.speed=921600 +cw02.menu.UploadSpeed.115200=115200 +cw02.menu.UploadSpeed.115200.upload.speed=115200 +cw02.menu.UploadSpeed.256000.windows=256000 +cw02.menu.UploadSpeed.256000.upload.speed=256000 +cw02.menu.UploadSpeed.230400.windows.upload.speed=256000 +cw02.menu.UploadSpeed.230400=230400 +cw02.menu.UploadSpeed.230400.upload.speed=230400 +cw02.menu.UploadSpeed.460800.linux=460800 +cw02.menu.UploadSpeed.460800.macosx=460800 +cw02.menu.UploadSpeed.460800.upload.speed=460800 +cw02.menu.UploadSpeed.512000.windows=512000 +cw02.menu.UploadSpeed.512000.upload.speed=512000 + +cw02.menu.DebugLevel.none=None +cw02.menu.DebugLevel.none.build.code_debug=0 +cw02.menu.DebugLevel.error=Error +cw02.menu.DebugLevel.error.build.code_debug=1 +cw02.menu.DebugLevel.warn=Warn +cw02.menu.DebugLevel.warn.build.code_debug=2 +cw02.menu.DebugLevel.info=Info +cw02.menu.DebugLevel.info.build.code_debug=3 +cw02.menu.DebugLevel.debug=Debug +cw02.menu.DebugLevel.debug.build.code_debug=4 +cw02.menu.DebugLevel.verbose=Verbose +cw02.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + esp32thing.name=SparkFun ESP32 Thing -esp32thing.upload.tool=esptool +esp32thing.upload.tool=esptool_py esp32thing.upload.maximum_size=1310720 -esp32thing.upload.maximum_data_size=294912 +esp32thing.upload.maximum_data_size=327680 esp32thing.upload.wait_for_upload_port=true esp32thing.serial.disableDTR=true @@ -164,12 +741,22 @@ esp32thing.build.flash_mode=dio esp32thing.build.flash_size=4MB esp32thing.build.boot=dio esp32thing.build.partitions=default +esp32thing.build.defines= esp32thing.menu.FlashFreq.80=80MHz esp32thing.menu.FlashFreq.80.build.flash_freq=80m esp32thing.menu.FlashFreq.40=40MHz esp32thing.menu.FlashFreq.40.build.flash_freq=40m +esp32thing.menu.PartitionScheme.default=Default +esp32thing.menu.PartitionScheme.default.build.partitions=default +esp32thing.menu.PartitionScheme.no_ota=No OTA (Large APP) +esp32thing.menu.PartitionScheme.no_ota.build.partitions=no_ota +esp32thing.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32thing.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +esp32thing.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32thing.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + esp32thing.menu.UploadSpeed.921600=921600 esp32thing.menu.UploadSpeed.921600.upload.speed=921600 esp32thing.menu.UploadSpeed.115200=115200 @@ -185,13 +772,27 @@ esp32thing.menu.UploadSpeed.460800.upload.speed=460800 esp32thing.menu.UploadSpeed.512000.windows=512000 esp32thing.menu.UploadSpeed.512000.upload.speed=512000 +esp32thing.menu.DebugLevel.none=None +esp32thing.menu.DebugLevel.none.build.code_debug=0 +esp32thing.menu.DebugLevel.error=Error +esp32thing.menu.DebugLevel.error.build.code_debug=1 +esp32thing.menu.DebugLevel.warn=Warn +esp32thing.menu.DebugLevel.warn.build.code_debug=2 +esp32thing.menu.DebugLevel.info=Info +esp32thing.menu.DebugLevel.info.build.code_debug=3 +esp32thing.menu.DebugLevel.debug=Debug +esp32thing.menu.DebugLevel.debug.build.code_debug=4 +esp32thing.menu.DebugLevel.verbose=Verbose +esp32thing.menu.DebugLevel.verbose.build.code_debug=5 + + ############################################################## nina_w10.name=u-blox NINA-W10 series (ESP32) -nina_w10.upload.tool=esptool +nina_w10.upload.tool=esptool_py nina_w10.upload.maximum_size=1310720 -nina_w10.upload.maximum_data_size=294912 +nina_w10.upload.maximum_data_size=327680 nina_w10.upload.wait_for_upload_port=true nina_w10.serial.disableDTR=true @@ -207,6 +808,7 @@ nina_w10.build.partitions=minimal nina_w10.build.flash_mode=dio nina_w10.build.flash_size=2MB nina_w10.build.flash_freq=40m +nina_w10.build.defines= nina_w10.menu.UploadSpeed.921600=921600 nina_w10.menu.UploadSpeed.921600.upload.speed=921600 @@ -227,9 +829,9 @@ nina_w10.menu.UploadSpeed.512000.upload.speed=512000 widora-air.name=Widora AIR -widora-air.upload.tool=esptool +widora-air.upload.tool=esptool_py widora-air.upload.maximum_size=1310720 -widora-air.upload.maximum_data_size=294912 +widora-air.upload.maximum_data_size=327680 widora-air.upload.wait_for_upload_port=true widora-air.serial.disableDTR=true @@ -245,6 +847,7 @@ widora-air.build.flash_mode=dio widora-air.build.flash_size=16MB widora-air.build.boot=dio widora-air.build.partitions=default +widora-air.build.defines= widora-air.menu.FlashFreq.80=80MHz widora-air.menu.FlashFreq.80.build.flash_freq=80m @@ -270,9 +873,9 @@ widora-air.menu.UploadSpeed.512000.upload.speed=512000 esp320.name=Electronic SweetPeas - ESP320 -esp320.upload.tool=esptool +esp320.upload.tool=esptool_py esp320.upload.maximum_size=1310720 -esp320.upload.maximum_data_size=294912 +esp320.upload.maximum_data_size=327680 esp320.upload.wait_for_upload_port=true esp320.serial.disableDTR=true @@ -288,6 +891,7 @@ esp320.build.flash_mode=qio esp320.build.flash_size=4MB esp320.build.boot=dio esp320.build.partitions=default +esp320.build.defines= esp320.menu.FlashFreq.80=80MHz esp320.menu.FlashFreq.80.build.flash_freq=80m @@ -313,9 +917,9 @@ esp320.menu.UploadSpeed.512000.upload.speed=512000 nano32.name=Nano32 -nano32.upload.tool=esptool +nano32.upload.tool=esptool_py nano32.upload.maximum_size=1310720 -nano32.upload.maximum_data_size=294912 +nano32.upload.maximum_data_size=327680 nano32.upload.wait_for_upload_port=true nano32.serial.disableDTR=true @@ -331,6 +935,7 @@ nano32.build.flash_mode=dio nano32.build.flash_size=4MB nano32.build.boot=dio nano32.build.partitions=default +nano32.build.defines= nano32.menu.FlashFreq.80=80MHz nano32.menu.FlashFreq.80.build.flash_freq=80m @@ -354,11 +959,162 @@ nano32.menu.UploadSpeed.512000.upload.speed=512000 ############################################################## +d32.name=LOLIN D32 + +d32.upload.tool=esptool_py +d32.upload.maximum_size=1310720 +d32.upload.maximum_data_size=327680 +d32.upload.wait_for_upload_port=true + +d32.serial.disableDTR=true +d32.serial.disableRTS=true + +d32.build.mcu=esp32 +d32.build.core=esp32 +d32.build.variant=d32 +d32.build.board=LOLIN_D32 + +d32.build.f_cpu=240000000L +d32.build.flash_size=4MB +d32.build.flash_freq=40m +d32.build.flash_mode=dio +d32.build.boot=dio +d32.build.partitions=default +d32.build.defines= + +d32.menu.PartitionScheme.default=Default +d32.menu.PartitionScheme.default.build.partitions=default +d32.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +d32.menu.PartitionScheme.minimal.build.partitions=minimal +d32.menu.PartitionScheme.no_ota=No OTA (Large APP) +d32.menu.PartitionScheme.no_ota.build.partitions=no_ota +d32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +d32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +d32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +d32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + + + +d32.menu.FlashFreq.80=80MHz +d32.menu.FlashFreq.80.build.flash_freq=80m +d32.menu.FlashFreq.40=40MHz +d32.menu.FlashFreq.40.build.flash_freq=40m + + + +d32.menu.UploadSpeed.921600=921600 +d32.menu.UploadSpeed.921600.upload.speed=921600 +d32.menu.UploadSpeed.115200=115200 +d32.menu.UploadSpeed.115200.upload.speed=115200 +d32.menu.UploadSpeed.256000.windows=256000 +d32.menu.UploadSpeed.256000.upload.speed=256000 +d32.menu.UploadSpeed.230400.windows.upload.speed=256000 +d32.menu.UploadSpeed.230400=230400 +d32.menu.UploadSpeed.230400.upload.speed=230400 +d32.menu.UploadSpeed.460800.linux=460800 +d32.menu.UploadSpeed.460800.macosx=460800 +d32.menu.UploadSpeed.460800.upload.speed=460800 +d32.menu.UploadSpeed.512000.windows=512000 +d32.menu.UploadSpeed.512000.upload.speed=512000 + +d32.menu.DebugLevel.none=None +d32.menu.DebugLevel.none.build.code_debug=0 +d32.menu.DebugLevel.error=Error +d32.menu.DebugLevel.error.build.code_debug=1 +d32.menu.DebugLevel.warn=Warn +d32.menu.DebugLevel.warn.build.code_debug=2 +d32.menu.DebugLevel.info=Info +d32.menu.DebugLevel.info.build.code_debug=3 +d32.menu.DebugLevel.debug=Debug +d32.menu.DebugLevel.debug.build.code_debug=4 +d32.menu.DebugLevel.verbose=Verbose +d32.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +d32_pro.name=LOLIN D32 PRO + +d32_pro.upload.tool=esptool_py +d32_pro.upload.maximum_size=1310720 +d32_pro.upload.maximum_data_size=327680 +d32_pro.upload.wait_for_upload_port=true + +d32_pro.serial.disableDTR=true +d32_pro.serial.disableRTS=true + +d32_pro.build.mcu=esp32 +d32_pro.build.core=esp32 +d32_pro.build.variant=d32_pro +d32_pro.build.board=LOLIN_D32_PRO + +d32_pro.build.f_cpu=240000000L +d32_pro.build.flash_size=4MB +d32_pro.build.flash_freq=40m +d32_pro.build.flash_mode=dio +d32_pro.build.boot=dio +d32_pro.build.partitions=default +d32_pro.build.defines= + +d32_pro.menu.PSRAM.disabled=Disabled +d32_pro.menu.PSRAM.disabled.build.defines= +d32_pro.menu.PSRAM.enabled=Enabled +d32_pro.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +d32_pro.menu.PartitionScheme.default=Default +d32_pro.menu.PartitionScheme.default.build.partitions=default +d32_pro.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +d32_pro.menu.PartitionScheme.minimal.build.partitions=minimal +d32_pro.menu.PartitionScheme.no_ota=No OTA (Large APP) +d32_pro.menu.PartitionScheme.no_ota.build.partitions=no_ota +d32_pro.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +d32_pro.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +d32_pro.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +d32_pro.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + + + +d32_pro.menu.FlashFreq.80=80MHz +d32_pro.menu.FlashFreq.80.build.flash_freq=80m +d32_pro.menu.FlashFreq.40=40MHz +d32_pro.menu.FlashFreq.40.build.flash_freq=40m + + + +d32_pro.menu.UploadSpeed.921600=921600 +d32_pro.menu.UploadSpeed.921600.upload.speed=921600 +d32_pro.menu.UploadSpeed.115200=115200 +d32_pro.menu.UploadSpeed.115200.upload.speed=115200 +d32_pro.menu.UploadSpeed.256000.windows=256000 +d32_pro.menu.UploadSpeed.256000.upload.speed=256000 +d32_pro.menu.UploadSpeed.230400.windows.upload.speed=256000 +d32_pro.menu.UploadSpeed.230400=230400 +d32_pro.menu.UploadSpeed.230400.upload.speed=230400 +d32_pro.menu.UploadSpeed.460800.linux=460800 +d32_pro.menu.UploadSpeed.460800.macosx=460800 +d32_pro.menu.UploadSpeed.460800.upload.speed=460800 +d32_pro.menu.UploadSpeed.512000.windows=512000 +d32_pro.menu.UploadSpeed.512000.upload.speed=512000 + +d32_pro.menu.DebugLevel.none=None +d32_pro.menu.DebugLevel.none.build.code_debug=0 +d32_pro.menu.DebugLevel.error=Error +d32_pro.menu.DebugLevel.error.build.code_debug=1 +d32_pro.menu.DebugLevel.warn=Warn +d32_pro.menu.DebugLevel.warn.build.code_debug=2 +d32_pro.menu.DebugLevel.info=Info +d32_pro.menu.DebugLevel.info.build.code_debug=3 +d32_pro.menu.DebugLevel.debug=Debug +d32_pro.menu.DebugLevel.debug.build.code_debug=4 +d32_pro.menu.DebugLevel.verbose=Verbose +d32_pro.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + lolin32.name=WEMOS LOLIN32 -lolin32.upload.tool=esptool +lolin32.upload.tool=esptool_py lolin32.upload.maximum_size=1310720 -lolin32.upload.maximum_data_size=294912 +lolin32.upload.maximum_data_size=327680 lolin32.upload.wait_for_upload_port=true lolin32.serial.disableDTR=true @@ -374,12 +1130,39 @@ lolin32.build.flash_mode=dio lolin32.build.flash_size=4MB lolin32.build.boot=dio lolin32.build.partitions=default +lolin32.build.defines= lolin32.menu.FlashFreq.80=80MHz lolin32.menu.FlashFreq.80.build.flash_freq=80m lolin32.menu.FlashFreq.40=40MHz lolin32.menu.FlashFreq.40.build.flash_freq=40m +lolin32.menu.PartitionScheme.default=Default +lolin32.menu.PartitionScheme.default.build.partitions=default +lolin32.menu.PartitionScheme.no_ota=No OTA (Large APP) +lolin32.menu.PartitionScheme.no_ota.build.partitions=no_ota +lolin32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +lolin32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +lolin32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +lolin32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +lolin32.menu.CPUFreq.240=240MHz (WiFi/BT) +lolin32.menu.CPUFreq.240.build.f_cpu=240000000L +lolin32.menu.CPUFreq.160=160MHz (WiFi/BT) +lolin32.menu.CPUFreq.160.build.f_cpu=160000000L +lolin32.menu.CPUFreq.80=80MHz (WiFi/BT) +lolin32.menu.CPUFreq.80.build.f_cpu=80000000L +lolin32.menu.CPUFreq.40=40MHz (40MHz XTAL) +lolin32.menu.CPUFreq.40.build.f_cpu=40000000L +lolin32.menu.CPUFreq.26=26MHz (26MHz XTAL) +lolin32.menu.CPUFreq.26.build.f_cpu=26000000L +lolin32.menu.CPUFreq.20=20MHz (40MHz XTAL) +lolin32.menu.CPUFreq.20.build.f_cpu=20000000L +lolin32.menu.CPUFreq.13=13MHz (26MHz XTAL) +lolin32.menu.CPUFreq.13.build.f_cpu=13000000L +lolin32.menu.CPUFreq.10=10MHz (40MHz XTAL) +lolin32.menu.CPUFreq.10.build.f_cpu=10000000L + lolin32.menu.UploadSpeed.921600=921600 lolin32.menu.UploadSpeed.921600.upload.speed=921600 lolin32.menu.UploadSpeed.115200=115200 @@ -399,9 +1182,9 @@ lolin32.menu.UploadSpeed.512000.upload.speed=512000 pocket_32.name=Dongsen Tech Pocket 32 -pocket_32.upload.tool=esptool +pocket_32.upload.tool=esptool_py pocket_32.upload.maximum_size=1310720 -pocket_32.upload.maximum_data_size=294912 +pocket_32.upload.maximum_data_size=327680 pocket_32.upload.wait_for_upload_port=true pocket_32.serial.disableDTR=true @@ -417,6 +1200,7 @@ pocket_32.build.flash_mode=dio pocket_32.build.flash_size=4MB pocket_32.build.boot=dio pocket_32.build.partitions=default +pocket_32.build.defines= pocket_32.menu.FlashFreq.80=80MHz pocket_32.menu.FlashFreq.80.build.flash_freq=80m @@ -440,11 +1224,11 @@ pocket_32.menu.UploadSpeed.512000.upload.speed=512000 ############################################################## -WeMosBat.name="WeMos" WiFi&Bluetooth Battery +WeMosBat.name=WeMos WiFi&Bluetooth Battery -WeMosBat.upload.tool=esptool +WeMosBat.upload.tool=esptool_py WeMosBat.upload.maximum_size=1310720 -WeMosBat.upload.maximum_data_size=294912 +WeMosBat.upload.maximum_data_size=327680 WeMosBat.upload.wait_for_upload_port=true WeMosBat.serial.disableDTR=true @@ -460,6 +1244,7 @@ WeMosBat.build.flash_mode=dio WeMosBat.build.flash_size=4MB WeMosBat.build.boot=dio WeMosBat.build.partitions=default +WeMosBat.build.defines= WeMosBat.menu.FlashFreq.80=80MHz WeMosBat.menu.FlashFreq.80.build.flash_freq=80m @@ -498,9 +1283,9 @@ WeMosBat.menu.DebugLevel.verbose.build.code_debug=5 espea32.name=ESPea32 -espea32.upload.tool=esptool +espea32.upload.tool=esptool_py espea32.upload.maximum_size=1310720 -espea32.upload.maximum_data_size=294912 +espea32.upload.maximum_data_size=327680 espea32.upload.wait_for_upload_port=true espea32.serial.disableDTR=true @@ -516,6 +1301,7 @@ espea32.build.flash_mode=dio espea32.build.flash_size=4MB espea32.build.boot=dio espea32.build.partitions=default +espea32.build.defines= espea32.menu.FlashFreq.80=80MHz espea32.menu.FlashFreq.80.build.flash_freq=80m @@ -541,9 +1327,9 @@ espea32.menu.UploadSpeed.512000.upload.speed=512000 quantum.name=Noduino Quantum -quantum.upload.tool=esptool +quantum.upload.tool=esptool_py quantum.upload.maximum_size=1310720 -quantum.upload.maximum_data_size=294912 +quantum.upload.maximum_data_size=327680 quantum.upload.wait_for_upload_port=true quantum.serial.disableDTR=true @@ -559,6 +1345,7 @@ quantum.build.flash_mode=qio quantum.build.flash_size=16MB quantum.build.boot=dio quantum.build.partitions=default +quantum.build.defines= quantum.menu.FlashFreq.80=80MHz quantum.menu.FlashFreq.80.build.flash_freq=80m @@ -584,9 +1371,9 @@ quantum.menu.UploadSpeed.512000.upload.speed=512000 node32s.name=Node32s -node32s.upload.tool=esptool +node32s.upload.tool=esptool_py node32s.upload.maximum_size=1310720 -node32s.upload.maximum_data_size=294912 +node32s.upload.maximum_data_size=327680 node32s.upload.wait_for_upload_port=true node32s.serial.disableDTR=true @@ -602,6 +1389,16 @@ node32s.build.flash_mode=dio node32s.build.flash_size=4MB node32s.build.boot=dio node32s.build.partitions=default +node32s.build.defines= + +node32s.menu.PartitionScheme.default=Default +node32s.menu.PartitionScheme.default.build.partitions=default +node32s.menu.PartitionScheme.no_ota=No OTA (Large APP) +node32s.menu.PartitionScheme.no_ota.build.partitions=no_ota +node32s.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +node32s.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +node32s.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +node32s.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 node32s.menu.FlashFreq.80=80MHz node32s.menu.FlashFreq.80.build.flash_freq=80m @@ -623,13 +1420,26 @@ node32s.menu.UploadSpeed.460800.upload.speed=460800 node32s.menu.UploadSpeed.512000.windows=512000 node32s.menu.UploadSpeed.512000.upload.speed=512000 +node32s.menu.DebugLevel.none=None +node32s.menu.DebugLevel.none.build.code_debug=0 +node32s.menu.DebugLevel.error=Error +node32s.menu.DebugLevel.error.build.code_debug=1 +node32s.menu.DebugLevel.warn=Warn +node32s.menu.DebugLevel.warn.build.code_debug=2 +node32s.menu.DebugLevel.info=Info +node32s.menu.DebugLevel.info.build.code_debug=3 +node32s.menu.DebugLevel.debug=Debug +node32s.menu.DebugLevel.debug.build.code_debug=4 +node32s.menu.DebugLevel.verbose=Verbose +node32s.menu.DebugLevel.verbose.build.code_debug=5 + ############################################################## hornbill32dev.name=Hornbill ESP32 Dev -hornbill32dev.upload.tool=esptool +hornbill32dev.upload.tool=esptool_py hornbill32dev.upload.maximum_size=1310720 -hornbill32dev.upload.maximum_data_size=294912 +hornbill32dev.upload.maximum_data_size=327680 hornbill32dev.upload.wait_for_upload_port=true hornbill32dev.serial.disableDTR=true @@ -645,6 +1455,7 @@ hornbill32dev.build.flash_mode=dio hornbill32dev.build.flash_size=4MB hornbill32dev.build.boot=dio hornbill32dev.build.partitions=default +hornbill32dev.build.defines= hornbill32dev.menu.FlashFreq.80=80MHz hornbill32dev.menu.FlashFreq.80.build.flash_freq=80m @@ -670,9 +1481,9 @@ hornbill32dev.menu.UploadSpeed.512000.upload.speed=512000 hornbill32minima.name=Hornbill ESP32 Minima -hornbill32minima.upload.tool=esptool +hornbill32minima.upload.tool=esptool_py hornbill32minima.upload.maximum_size=1310720 -hornbill32minima.upload.maximum_data_size=294912 +hornbill32minima.upload.maximum_data_size=327680 hornbill32minima.upload.wait_for_upload_port=true hornbill32minima.serial.disableDTR=true @@ -687,6 +1498,7 @@ hornbill32minima.build.flash_mode=dio hornbill32minima.build.flash_size=4MB hornbill32minima.build.boot=dio hornbill32minima.build.partitions=default +hornbill32minima.build.defines= hornbill32minima.menu.FlashFreq.80=80MHz hornbill32minima.menu.FlashFreq.80.build.flash_freq=80m @@ -712,9 +1524,9 @@ hornbill32minima.menu.UploadSpeed.512000.upload.speed=512000 firebeetle32.name=FireBeetle-ESP32 -firebeetle32.upload.tool=esptool +firebeetle32.upload.tool=esptool_py firebeetle32.upload.maximum_size=1310720 -firebeetle32.upload.maximum_data_size=294912 +firebeetle32.upload.maximum_data_size=327680 firebeetle32.upload.wait_for_upload_port=true firebeetle32.serial.disableDTR=true @@ -730,6 +1542,7 @@ firebeetle32.build.flash_mode=dio firebeetle32.build.flash_size=4MB firebeetle32.build.boot=dio firebeetle32.build.partitions=default +firebeetle32.build.defines= firebeetle32.menu.FlashFreq.80=80MHz firebeetle32.menu.FlashFreq.80.build.flash_freq=80m @@ -755,9 +1568,9 @@ firebeetle32.menu.UploadSpeed.512000.upload.speed=512000 intorobot-fig.name=IntoRobot Fig -intorobot-fig.upload.tool=esptool +intorobot-fig.upload.tool=esptool_py intorobot-fig.upload.maximum_size=1310720 -intorobot-fig.upload.maximum_data_size=294912 +intorobot-fig.upload.maximum_data_size=327680 intorobot-fig.upload.wait_for_upload_port=true intorobot-fig.serial.disableDTR=true @@ -773,6 +1586,7 @@ intorobot-fig.build.flash_mode=dio intorobot-fig.build.flash_size=4MB intorobot-fig.build.boot=dio intorobot-fig.build.partitions=default +intorobot-fig.build.defines= intorobot-fig.menu.FlashFreq.80=80MHz intorobot-fig.menu.FlashFreq.80.build.flash_freq=80m @@ -798,9 +1612,9 @@ intorobot-fig.menu.UploadSpeed.512000.upload.speed=512000 onehorse32dev.name=Onehorse ESP32 Dev Module -onehorse32dev.upload.tool=esptool +onehorse32dev.upload.tool=esptool_py onehorse32dev.upload.maximum_size=1310720 -onehorse32dev.upload.maximum_data_size=294912 +onehorse32dev.upload.maximum_data_size=327680 onehorse32dev.upload.wait_for_upload_port=true onehorse32dev.serial.disableDTR=true @@ -816,6 +1630,7 @@ onehorse32dev.build.flash_mode=dout onehorse32dev.build.flash_size=4MB onehorse32dev.build.boot=dio onehorse32dev.build.partitions=default +onehorse32dev.build.defines= onehorse32dev.menu.FlashFreq.80=80MHz onehorse32dev.menu.FlashFreq.80.build.flash_freq=80m @@ -841,9 +1656,9 @@ onehorse32dev.menu.UploadSpeed.512000.upload.speed=512000 featheresp32.name=Adafruit ESP32 Feather -featheresp32.upload.tool=esptool +featheresp32.upload.tool=esptool_py featheresp32.upload.maximum_size=1310720 -featheresp32.upload.maximum_data_size=294912 +featheresp32.upload.maximum_data_size=327680 featheresp32.upload.wait_for_upload_port=true featheresp32.serial.disableDTR=true @@ -859,6 +1674,7 @@ featheresp32.build.flash_mode=dio featheresp32.build.flash_size=4MB featheresp32.build.boot=dio featheresp32.build.partitions=default +featheresp32.build.defines= featheresp32.menu.FlashFreq.80=80MHz featheresp32.menu.FlashFreq.80.build.flash_freq=80m @@ -893,13 +1709,22 @@ featheresp32.menu.DebugLevel.debug.build.code_debug=4 featheresp32.menu.DebugLevel.verbose=Verbose featheresp32.menu.DebugLevel.verbose.build.code_debug=5 +featheresp32.menu.PartitionScheme.default=Default +featheresp32.menu.PartitionScheme.default.build.partitions=default +featheresp32.menu.PartitionScheme.no_ota=No OTA (Large APP) +featheresp32.menu.PartitionScheme.no_ota.build.partitions=no_ota +featheresp32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +featheresp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +featheresp32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +featheresp32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + ############################################################## nodemcu-32s.name=NodeMCU-32S -nodemcu-32s.upload.tool=esptool +nodemcu-32s.upload.tool=esptool_py nodemcu-32s.upload.maximum_size=1310720 -nodemcu-32s.upload.maximum_data_size=294912 +nodemcu-32s.upload.maximum_data_size=327680 nodemcu-32s.upload.wait_for_upload_port=true nodemcu-32s.serial.disableDTR=true @@ -915,6 +1740,7 @@ nodemcu-32s.build.flash_mode=dio nodemcu-32s.build.flash_size=4MB nodemcu-32s.build.boot=dio nodemcu-32s.build.partitions=default +nodemcu-32s.build.defines= nodemcu-32s.menu.FlashFreq.80=80MHz nodemcu-32s.menu.FlashFreq.80.build.flash_freq=80m @@ -940,9 +1766,9 @@ nodemcu-32s.menu.UploadSpeed.512000.upload.speed=512000 mhetesp32devkit.name=MH ET LIVE ESP32DevKIT -mhetesp32devkit.upload.tool=esptool +mhetesp32devkit.upload.tool=esptool_py mhetesp32devkit.upload.maximum_size=1310720 -mhetesp32devkit.upload.maximum_data_size=294912 +mhetesp32devkit.upload.maximum_data_size=327680 mhetesp32devkit.upload.wait_for_upload_port=true mhetesp32devkit.serial.disableDTR=true @@ -958,12 +1784,22 @@ mhetesp32devkit.build.flash_mode=dio mhetesp32devkit.build.flash_size=4MB mhetesp32devkit.build.boot=dio mhetesp32devkit.build.partitions=default +mhetesp32devkit.build.defines= mhetesp32devkit.menu.FlashFreq.80=80MHz mhetesp32devkit.menu.FlashFreq.80.build.flash_freq=80m mhetesp32devkit.menu.FlashFreq.40=40MHz mhetesp32devkit.menu.FlashFreq.40.build.flash_freq=40m +mhetesp32devkit.menu.PartitionScheme.default=Default +mhetesp32devkit.menu.PartitionScheme.default.build.partitions=default +mhetesp32devkit.menu.PartitionScheme.no_ota=No OTA (Large APP) +mhetesp32devkit.menu.PartitionScheme.no_ota.build.partitions=no_ota +mhetesp32devkit.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +mhetesp32devkit.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +mhetesp32devkit.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +mhetesp32devkit.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + mhetesp32devkit.menu.UploadSpeed.921600=921600 mhetesp32devkit.menu.UploadSpeed.921600.upload.speed=921600 mhetesp32devkit.menu.UploadSpeed.115200=115200 @@ -979,13 +1815,26 @@ mhetesp32devkit.menu.UploadSpeed.460800.upload.speed=460800 mhetesp32devkit.menu.UploadSpeed.512000.windows=512000 mhetesp32devkit.menu.UploadSpeed.512000.upload.speed=512000 +mhetesp32devkit.menu.DebugLevel.none=None +mhetesp32devkit.menu.DebugLevel.none.build.code_debug=0 +mhetesp32devkit.menu.DebugLevel.error=Error +mhetesp32devkit.menu.DebugLevel.error.build.code_debug=1 +mhetesp32devkit.menu.DebugLevel.warn=Warn +mhetesp32devkit.menu.DebugLevel.warn.build.code_debug=2 +mhetesp32devkit.menu.DebugLevel.info=Info +mhetesp32devkit.menu.DebugLevel.info.build.code_debug=3 +mhetesp32devkit.menu.DebugLevel.debug=Debug +mhetesp32devkit.menu.DebugLevel.debug.build.code_debug=4 +mhetesp32devkit.menu.DebugLevel.verbose=Verbose +mhetesp32devkit.menu.DebugLevel.verbose.build.code_debug=5 + ############################################################## mhetesp32minikit.name=MH ET LIVE ESP32MiniKit -mhetesp32minikit.upload.tool=esptool +mhetesp32minikit.upload.tool=esptool_py mhetesp32minikit.upload.maximum_size=1310720 -mhetesp32minikit.upload.maximum_data_size=294912 +mhetesp32minikit.upload.maximum_data_size=327680 mhetesp32minikit.upload.wait_for_upload_port=true mhetesp32minikit.serial.disableDTR=true @@ -1001,12 +1850,24 @@ mhetesp32minikit.build.flash_mode=dio mhetesp32minikit.build.flash_size=4MB mhetesp32minikit.build.boot=dio mhetesp32minikit.build.partitions=default +mhetesp32minikit.build.defines= mhetesp32minikit.menu.FlashFreq.80=80MHz mhetesp32minikit.menu.FlashFreq.80.build.flash_freq=80m mhetesp32minikit.menu.FlashFreq.40=40MHz mhetesp32minikit.menu.FlashFreq.40.build.flash_freq=40m +mhetesp32minikit.menu.PartitionScheme.default=Default with spiffs +mhetesp32minikit.menu.PartitionScheme.default.build.partitions=default +mhetesp32minikit.menu.PartitionScheme.defaultffat=Default with ffat +mhetesp32minikit.menu.PartitionScheme.defaultffat.build.partitions=default_ffat +mhetesp32minikit.menu.PartitionScheme.no_ota=No OTA (Large APP) +mhetesp32minikit.menu.PartitionScheme.no_ota.build.partitions=no_ota +mhetesp32minikit.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +mhetesp32minikit.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +mhetesp32minikit.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +mhetesp32minikit.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + mhetesp32minikit.menu.UploadSpeed.921600=921600 mhetesp32minikit.menu.UploadSpeed.921600.upload.speed=921600 mhetesp32minikit.menu.UploadSpeed.115200=115200 @@ -1022,13 +1883,26 @@ mhetesp32minikit.menu.UploadSpeed.460800.upload.speed=460800 mhetesp32minikit.menu.UploadSpeed.512000.windows=512000 mhetesp32minikit.menu.UploadSpeed.512000.upload.speed=512000 +mhetesp32minikit.menu.DebugLevel.none=None +mhetesp32minikit.menu.DebugLevel.none.build.code_debug=0 +mhetesp32minikit.menu.DebugLevel.error=Error +mhetesp32minikit.menu.DebugLevel.error.build.code_debug=1 +mhetesp32minikit.menu.DebugLevel.warn=Warn +mhetesp32minikit.menu.DebugLevel.warn.build.code_debug=2 +mhetesp32minikit.menu.DebugLevel.info=Info +mhetesp32minikit.menu.DebugLevel.info.build.code_debug=3 +mhetesp32minikit.menu.DebugLevel.debug=Debug +mhetesp32minikit.menu.DebugLevel.debug.build.code_debug=4 +mhetesp32minikit.menu.DebugLevel.verbose=Verbose +mhetesp32minikit.menu.DebugLevel.verbose.build.code_debug=5 + ################################################################# esp32vn-iot-uno.name=ESP32vn IoT Uno -esp32vn-iot-uno.upload.tool=esptool +esp32vn-iot-uno.upload.tool=esptool_py esp32vn-iot-uno.upload.maximum_size=1310720 -esp32vn-iot-uno.upload.maximum_data_size=294912 +esp32vn-iot-uno.upload.maximum_data_size=327680 esp32vn-iot-uno.upload.wait_for_upload_port=true esp32vn-iot-uno.serial.disableDTR=true @@ -1037,13 +1911,14 @@ esp32vn-iot-uno.serial.disableRTS=true esp32vn-iot-uno.build.mcu=esp32 esp32vn-iot-uno.build.core=esp32 esp32vn-iot-uno.build.variant=esp32vn-iot-uno -esp32vn-iot-uno.build.board=esp32vn-iot-uno +esp32vn-iot-uno.build.board=esp32vn_iot_uno esp32vn-iot-uno.build.f_cpu=240000000L esp32vn-iot-uno.build.flash_mode=dio esp32vn-iot-uno.build.flash_size=4MB esp32vn-iot-uno.build.boot=dio esp32vn-iot-uno.build.partitions=default +esp32vn-iot-uno.build.defines= esp32vn-iot-uno.menu.FlashFreq.80=80MHz esp32vn-iot-uno.menu.FlashFreq.80.build.flash_freq=80m @@ -1069,9 +1944,9 @@ esp32vn-iot-uno.menu.UploadSpeed.512000.upload.speed=512000 esp32doit-devkit-v1.name=DOIT ESP32 DEVKIT V1 -esp32doit-devkit-v1.upload.tool=esptool +esp32doit-devkit-v1.upload.tool=esptool_py esp32doit-devkit-v1.upload.maximum_size=1310720 -esp32doit-devkit-v1.upload.maximum_data_size=294912 +esp32doit-devkit-v1.upload.maximum_data_size=327680 esp32doit-devkit-v1.upload.wait_for_upload_port=true esp32doit-devkit-v1.serial.disableDTR=true @@ -1087,6 +1962,7 @@ esp32doit-devkit-v1.build.flash_mode=dio esp32doit-devkit-v1.build.flash_size=4MB esp32doit-devkit-v1.build.boot=dio esp32doit-devkit-v1.build.partitions=default +esp32doit-devkit-v1.build.defines= esp32doit-devkit-v1.menu.FlashFreq.80=80MHz esp32doit-devkit-v1.menu.FlashFreq.80.build.flash_freq=80m @@ -1123,9 +1999,9 @@ esp32doit-devkit-v1.menu.DebugLevel.debug.build.code_debug=4 esp32-evb.name=OLIMEX ESP32-EVB -esp32-evb.upload.tool=esptool +esp32-evb.upload.tool=esptool_py esp32-evb.upload.maximum_size=1310720 -esp32-evb.upload.maximum_data_size=294912 +esp32-evb.upload.maximum_data_size=327680 esp32-evb.upload.wait_for_upload_port=true esp32-evb.serial.disableDTR=true @@ -1134,13 +2010,14 @@ esp32-evb.serial.disableRTS=true esp32-evb.build.mcu=esp32 esp32-evb.build.core=esp32 esp32-evb.build.variant=esp32-evb -esp32-evb.build.board=ESP32-EVB +esp32-evb.build.board=ESP32_EVB esp32-evb.build.f_cpu=240000000L esp32-evb.build.flash_mode=dio esp32-evb.build.flash_size=4MB esp32-evb.build.boot=dio esp32-evb.build.partitions=default +esp32-evb.build.defines= esp32-evb.menu.FlashFreq.80=80MHz esp32-evb.menu.FlashFreq.80.build.flash_freq=80m @@ -1151,13 +2028,22 @@ esp32-evb.menu.FlashFreq.40.build.flash_freq=40m esp32-evb.menu.UploadSpeed.115200=115200 esp32-evb.menu.UploadSpeed.115200.upload.speed=115200 +esp32-evb.menu.PartitionScheme.default=Default +esp32-evb.menu.PartitionScheme.default.build.partitions=default +esp32-evb.menu.PartitionScheme.no_ota=No OTA (Large APP) +esp32-evb.menu.PartitionScheme.no_ota.build.partitions=no_ota +esp32-evb.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32-evb.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +esp32-evb.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32-evb.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + ############################################################## esp32-gateway.name=OLIMEX ESP32-GATEWAY -esp32-gateway.upload.tool=esptool +esp32-gateway.upload.tool=esptool_py esp32-gateway.upload.maximum_size=1310720 -esp32-gateway.upload.maximum_data_size=294912 +esp32-gateway.upload.maximum_data_size=327680 esp32-gateway.upload.wait_for_upload_port=true esp32-gateway.serial.disableDTR=true @@ -1166,13 +2052,20 @@ esp32-gateway.serial.disableRTS=true esp32-gateway.build.mcu=esp32 esp32-gateway.build.core=esp32 esp32-gateway.build.variant=esp32-gateway -esp32-gateway.build.board=ESP32-GATEWAY +esp32-gateway.build.board=ESP32_GATEWAY +esp32-gateway.menu.Revision.RevC=Revision C or older +esp32-gateway.menu.Revision.RevC.build.board=ESP32_GATEWAY='C' +esp32-gateway.menu.Revision.RevE=Revision E +esp32-gateway.menu.Revision.RevE.build.board=ESP32_GATEWAY='E' +esp32-gateway.menu.Revision.RevF=Revision F +esp32-gateway.menu.Revision.RevF.build.board=ESP32_GATEWAY='F' esp32-gateway.build.f_cpu=240000000L esp32-gateway.build.flash_mode=dio esp32-gateway.build.flash_size=4MB esp32-gateway.build.boot=dio esp32-gateway.build.partitions=default +esp32-gateway.build.defines= esp32-gateway.menu.FlashFreq.80=80MHz esp32-gateway.menu.FlashFreq.80.build.flash_freq=80m @@ -1183,13 +2076,179 @@ esp32-gateway.menu.FlashFreq.40.build.flash_freq=40m esp32-gateway.menu.UploadSpeed.115200=115200 esp32-gateway.menu.UploadSpeed.115200.upload.speed=115200 +esp32-gateway.menu.PartitionScheme.default=Default +esp32-gateway.menu.PartitionScheme.default.build.partitions=default +esp32-gateway.menu.PartitionScheme.no_ota=No OTA (Large APP) +esp32-gateway.menu.PartitionScheme.no_ota.build.partitions=no_ota +esp32-gateway.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32-gateway.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +esp32-gateway.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32-gateway.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +############################################################## + +esp32-poe.name=OLIMEX ESP32-PoE + +esp32-poe.upload.tool=esptool_py +esp32-poe.upload.maximum_size=1310720 +esp32-poe.upload.maximum_data_size=327680 +esp32-poe.upload.wait_for_upload_port=true + +esp32-poe.serial.disableDTR=true +esp32-poe.serial.disableRTS=true + +esp32-poe.build.mcu=esp32 +esp32-poe.build.core=esp32 +esp32-poe.build.variant=esp32-poe +esp32-poe.build.board=ESP32_POE + +esp32-poe.build.f_cpu=240000000L +esp32-poe.build.flash_mode=dio +esp32-poe.build.flash_size=4MB +esp32-poe.build.boot=dio +esp32-poe.build.partitions=default +esp32-poe.build.defines= + +esp32-poe.menu.FlashFreq.80=80MHz +esp32-poe.menu.FlashFreq.80.build.flash_freq=80m +esp32-poe.menu.FlashFreq.40=40MHz +esp32-poe.menu.FlashFreq.40.build.flash_freq=40m + + +esp32-poe.menu.UploadSpeed.115200=115200 +esp32-poe.menu.UploadSpeed.115200.upload.speed=115200 + +esp32-poe.menu.PartitionScheme.default=Default +esp32-poe.menu.PartitionScheme.default.build.partitions=default +esp32-poe.menu.PartitionScheme.no_ota=No OTA (Large APP) +esp32-poe.menu.PartitionScheme.no_ota.build.partitions=no_ota +esp32-poe.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32-poe.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +esp32-poe.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32-poe.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +############################################################## + +esp32-poe-iso.name=OLIMEX ESP32-PoE-ISO + +esp32-poe-iso.upload.tool=esptool_py +esp32-poe-iso.upload.maximum_size=1310720 +esp32-poe-iso.upload.maximum_data_size=327680 +esp32-poe-iso.upload.wait_for_upload_port=true + +esp32-poe-iso.serial.disableDTR=true +esp32-poe-iso.serial.disableRTS=true + +esp32-poe-iso.build.mcu=esp32 +esp32-poe-iso.build.core=esp32 +esp32-poe-iso.build.variant=esp32-poe-iso +esp32-poe-iso.build.board=ESP32_POE_ISO + +esp32-poe-iso.build.f_cpu=240000000L +esp32-poe-iso.build.flash_mode=dio +esp32-poe-iso.build.flash_size=4MB +esp32-poe-iso.build.boot=dio +esp32-poe-iso.build.partitions=default +esp32-poe-iso.build.defines= + +esp32-poe-iso.menu.FlashFreq.80=80MHz +esp32-poe-iso.menu.FlashFreq.80.build.flash_freq=80m +esp32-poe-iso.menu.FlashFreq.40=40MHz +esp32-poe-iso.menu.FlashFreq.40.build.flash_freq=40m + + +esp32-poe-iso.menu.UploadSpeed.115200=115200 +esp32-poe-iso.menu.UploadSpeed.115200.upload.speed=115200 + +esp32-poe-iso.menu.PartitionScheme.default=Default +esp32-poe-iso.menu.PartitionScheme.default.build.partitions=default +esp32-poe-iso.menu.PartitionScheme.no_ota=No OTA (Large APP) +esp32-poe-iso.menu.PartitionScheme.no_ota.build.partitions=no_ota +esp32-poe-iso.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32-poe-iso.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +esp32-poe-iso.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32-poe-iso.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +############################################################## + +esp32-DevKitLipo.name=OLIMEX ESP32-DevKit-LiPo + +esp32-DevKitLipo.upload.tool=esptool_py +esp32-DevKitLipo.upload.maximum_size=1310720 +esp32-DevKitLipo.upload.maximum_data_size=327680 +esp32-DevKitLipo.upload.wait_for_upload_port=true + +esp32-DevKitLipo.serial.disableDTR=true +esp32-DevKitLipo.serial.disableRTS=true + +esp32-DevKitLipo.build.mcu=esp32 +esp32-DevKitLipo.build.core=esp32 +esp32-DevKitLipo.build.variant=esp32-devkit-lipo +esp32-DevKitLipo.build.board=ESP32_DEVKIT_LIPO + +esp32-DevKitLipo.build.f_cpu=240000000L +esp32-DevKitLipo.build.flash_size=4MB +esp32-DevKitLipo.build.flash_freq=40m +esp32-DevKitLipo.build.flash_mode=dio +esp32-DevKitLipo.build.boot=dio +esp32-DevKitLipo.build.partitions=default +esp32-DevKitLipo.build.defines= + +esp32-DevKitLipo.menu.PartitionScheme.default=Default +esp32-DevKitLipo.menu.PartitionScheme.default.build.partitions=default +esp32-DevKitLipo.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +esp32-DevKitLipo.menu.PartitionScheme.minimal.build.partitions=minimal +esp32-DevKitLipo.menu.PartitionScheme.no_ota=No OTA (Large APP) +esp32-DevKitLipo.menu.PartitionScheme.no_ota.build.partitions=no_ota +esp32-DevKitLipo.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32-DevKitLipo.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA) +esp32-DevKitLipo.menu.PartitionScheme.huge_app.build.partitions=huge_app +esp32-DevKitLipo.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +esp32-DevKitLipo.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +esp32-DevKitLipo.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32-DevKitLipo.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +esp32-DevKitLipo.menu.PartitionScheme.fatflash=16M Fat +esp32-DevKitLipo.menu.PartitionScheme.fatflash.build.partitions=ffat + +esp32-DevKitLipo.menu.FlashMode.qio=QIO +esp32-DevKitLipo.menu.FlashMode.qio.build.flash_mode=dio +esp32-DevKitLipo.menu.FlashMode.qio.build.boot=qio +esp32-DevKitLipo.menu.FlashMode.dio=DIO +esp32-DevKitLipo.menu.FlashMode.dio.build.flash_mode=dio +esp32-DevKitLipo.menu.FlashMode.dio.build.boot=dio +esp32-DevKitLipo.menu.FlashMode.qout=QOUT +esp32-DevKitLipo.menu.FlashMode.qout.build.flash_mode=dout +esp32-DevKitLipo.menu.FlashMode.qout.build.boot=qout +esp32-DevKitLipo.menu.FlashMode.dout=DOUT +esp32-DevKitLipo.menu.FlashMode.dout.build.flash_mode=dout +esp32-DevKitLipo.menu.FlashMode.dout.build.boot=dout + +esp32-DevKitLipo.menu.FlashFreq.80=80MHz +esp32-DevKitLipo.menu.FlashFreq.80.build.flash_freq=80m +esp32-DevKitLipo.menu.FlashFreq.40=40MHz +esp32-DevKitLipo.menu.FlashFreq.40.build.flash_freq=40m + +esp32-DevKitLipo.menu.UploadSpeed.921600=921600 +esp32-DevKitLipo.menu.UploadSpeed.921600.upload.speed=921600 +esp32-DevKitLipo.menu.UploadSpeed.115200=115200 +esp32-DevKitLipo.menu.UploadSpeed.115200.upload.speed=115200 +esp32-DevKitLipo.menu.UploadSpeed.256000.windows=256000 +esp32-DevKitLipo.menu.UploadSpeed.256000.upload.speed=256000 +esp32-DevKitLipo.menu.UploadSpeed.230400.windows.upload.speed=256000 +esp32-DevKitLipo.menu.UploadSpeed.230400=230400 +esp32-DevKitLipo.menu.UploadSpeed.230400.upload.speed=230400 +esp32-DevKitLipo.menu.UploadSpeed.460800.linux=460800 +esp32-DevKitLipo.menu.UploadSpeed.460800.macosx=460800 +esp32-DevKitLipo.menu.UploadSpeed.460800.upload.speed=460800 +esp32-DevKitLipo.menu.UploadSpeed.512000.windows=512000 +esp32-DevKitLipo.menu.UploadSpeed.512000.upload.speed=512000 ############################################################## espino32.name=ThaiEasyElec's ESPino32 -espino32.upload.tool=esptool +espino32.upload.tool=esptool_py espino32.upload.maximum_size=1310720 -espino32.upload.maximum_data_size=294912 +espino32.upload.maximum_data_size=327680 espino32.upload.wait_for_upload_port=true espino32.serial.disableDTR=true @@ -1205,6 +2264,7 @@ espino32.build.flash_mode=dio espino32.build.flash_size=4MB espino32.build.boot=dio espino32.build.partitions=default +espino32.build.defines= espino32.menu.FlashFreq.80=80MHz espino32.menu.FlashFreq.80.build.flash_freq=80m @@ -1230,9 +2290,9 @@ espino32.menu.UploadSpeed.512000.upload.speed=512000 m5stack-core-esp32.name=M5Stack-Core-ESP32 -m5stack-core-esp32.upload.tool=esptool +m5stack-core-esp32.upload.tool=esptool_py m5stack-core-esp32.upload.maximum_size=1310720 -m5stack-core-esp32.upload.maximum_data_size=294912 +m5stack-core-esp32.upload.maximum_data_size=327680 m5stack-core-esp32.upload.wait_for_upload_port=true m5stack-core-esp32.serial.disableDTR=true @@ -1248,6 +2308,7 @@ m5stack-core-esp32.build.flash_size=4MB m5stack-core-esp32.build.flash_mode=dio m5stack-core-esp32.build.boot=dio m5stack-core-esp32.build.partitions=default +m5stack-core-esp32.build.defines= m5stack-core-esp32.menu.FlashMode.qio=QIO m5stack-core-esp32.menu.FlashMode.qio.build.flash_mode=dio @@ -1267,6 +2328,15 @@ m5stack-core-esp32.menu.FlashFreq.80.build.flash_freq=80m m5stack-core-esp32.menu.FlashFreq.40=40MHz m5stack-core-esp32.menu.FlashFreq.40.build.flash_freq=40m +m5stack-core-esp32.menu.PartitionScheme.default=Default +m5stack-core-esp32.menu.PartitionScheme.default.build.partitions=default +m5stack-core-esp32.menu.PartitionScheme.no_ota=No OTA (Large APP) +m5stack-core-esp32.menu.PartitionScheme.no_ota.build.partitions=no_ota +m5stack-core-esp32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +m5stack-core-esp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +m5stack-core-esp32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +m5stack-core-esp32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + m5stack-core-esp32.menu.UploadSpeed.921600=921600 m5stack-core-esp32.menu.UploadSpeed.921600.upload.speed=921600 m5stack-core-esp32.menu.UploadSpeed.115200=115200 @@ -1297,11 +2367,217 @@ m5stack-core-esp32.menu.DebugLevel.verbose.build.code_debug=5 ############################################################## -heltec_wifi_kit_32.name=Heltec_WIFI_Kit_32 +m5stack-fire.name=M5Stack-FIRE + +m5stack-fire.upload.tool=esptool_py +m5stack-fire.upload.maximum_size=6553600 +m5stack-fire.upload.maximum_data_size=4521984 +m5stack-fire.upload.wait_for_upload_port=true + +m5stack-fire.serial.disableDTR=true +m5stack-fire.serial.disableRTS=true + +m5stack-fire.build.mcu=esp32 +m5stack-fire.build.core=esp32 +m5stack-fire.build.variant=m5stack_fire +m5stack-fire.build.board=M5STACK_FIRE + +m5stack-fire.build.f_cpu=240000000L +m5stack-fire.build.flash_size=16MB +m5stack-fire.build.flash_freq=80m +m5stack-fire.build.flash_mode=dio +m5stack-fire.build.boot=dio +m5stack-fire.build.partitions=default_16MB +m5stack-fire.build.defines= + +m5stack-fire.menu.PSRAM.enabled=Enabled +m5stack-fire.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue +m5stack-fire.menu.PSRAM.disabled=Disabled +m5stack-fire.menu.PSRAM.disabled.build.defines= + +m5stack-fire.menu.PartitionScheme.default=Default (2 x 6.5 MB app, 3.6 MB SPIFFS) +m5stack-fire.menu.PartitionScheme.default.build.partitions=default_16MB +m5stack-fire.menu.PartitionScheme.default.upload.maximum_size=6553600 +m5stack-fire.menu.PartitionScheme.large_spiffs=Large SPIFFS (7 MB) +m5stack-fire.menu.PartitionScheme.large_spiffs.build.partitions=large_spiffs_16MB +m5stack-fire.menu.PartitionScheme.large_spiffs.upload.maximum_size=4685824 + +m5stack-fire.menu.UploadSpeed.921600=921600 +m5stack-fire.menu.UploadSpeed.921600.upload.speed=921600 +m5stack-fire.menu.UploadSpeed.115200=115200 +m5stack-fire.menu.UploadSpeed.115200.upload.speed=115200 +m5stack-fire.menu.UploadSpeed.256000.windows=256000 +m5stack-fire.menu.UploadSpeed.256000.upload.speed=256000 +m5stack-fire.menu.UploadSpeed.230400.windows.upload.speed=256000 +m5stack-fire.menu.UploadSpeed.230400=230400 +m5stack-fire.menu.UploadSpeed.230400.upload.speed=230400 +m5stack-fire.menu.UploadSpeed.460800.linux=460800 +m5stack-fire.menu.UploadSpeed.460800.macosx=460800 +m5stack-fire.menu.UploadSpeed.460800.upload.speed=460800 +m5stack-fire.menu.UploadSpeed.512000.windows=512000 +m5stack-fire.menu.UploadSpeed.512000.upload.speed=512000 + +m5stack-fire.menu.DebugLevel.none=None +m5stack-fire.menu.DebugLevel.none.build.code_debug=0 +m5stack-fire.menu.DebugLevel.error=Error +m5stack-fire.menu.DebugLevel.error.build.code_debug=1 +m5stack-fire.menu.DebugLevel.warn=Warn +m5stack-fire.menu.DebugLevel.warn.build.code_debug=2 +m5stack-fire.menu.DebugLevel.info=Info +m5stack-fire.menu.DebugLevel.info.build.code_debug=3 +m5stack-fire.menu.DebugLevel.debug=Debug +m5stack-fire.menu.DebugLevel.debug.build.code_debug=4 +m5stack-fire.menu.DebugLevel.verbose=Verbose +m5stack-fire.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +m5stick-c.name=M5Stick-C + +m5stick-c.upload.tool=esptool_py +m5stick-c.upload.maximum_size=1310720 +m5stick-c.upload.maximum_data_size=327680 +m5stick-c.upload.wait_for_upload_port=true + +m5stick-c.serial.disableDTR=true +m5stick-c.serial.disableRTS=true + +m5stick-c.build.mcu=esp32 +m5stick-c.build.core=esp32 +m5stick-c.build.variant=m5stick_c +m5stick-c.build.board=M5Stick_C + +m5stick-c.build.f_cpu=240000000L +m5stick-c.build.flash_size=4MB +m5stick-c.build.flash_freq=80m +m5stick-c.build.flash_mode=dio +m5stick-c.build.boot=dio +m5stick-c.build.partitions=default +m5stick-c.build.defines= + +m5stick-c.menu.PartitionScheme.default=Default +m5stick-c.menu.PartitionScheme.default.build.partitions=default +m5stick-c.menu.PartitionScheme.no_ota=No OTA (Large APP) +m5stick-c.menu.PartitionScheme.no_ota.build.partitions=no_ota +m5stick-c.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +m5stick-c.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +m5stick-c.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +m5stick-c.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + + +m5stick-c.menu.UploadSpeed.1500000=1500000 +m5stick-c.menu.UploadSpeed.1500000.upload.speed=1500000 +m5stick-c.menu.UploadSpeed.750000=750000 +m5stick-c.menu.UploadSpeed.750000.upload.speed=750000 +m5stick-c.menu.UploadSpeed.500000=500000 +m5stick-c.menu.UploadSpeed.500000.upload.speed=500000 +m5stick-c.menu.UploadSpeed.250000=250000 +m5stick-c.menu.UploadSpeed.250000.upload.speed=250000 +m5stick-c.menu.UploadSpeed.115200=115200 +m5stick-c.menu.UploadSpeed.115200.upload.speed=115200 + + + +m5stick-c.menu.DebugLevel.none=None +m5stick-c.menu.DebugLevel.none.build.code_debug=0 +m5stick-c.menu.DebugLevel.error=Error +m5stick-c.menu.DebugLevel.error.build.code_debug=1 +m5stick-c.menu.DebugLevel.warn=Warn +m5stick-c.menu.DebugLevel.warn.build.code_debug=2 +m5stick-c.menu.DebugLevel.info=Info +m5stick-c.menu.DebugLevel.info.build.code_debug=3 +m5stick-c.menu.DebugLevel.debug=Debug +m5stick-c.menu.DebugLevel.debug.build.code_debug=4 +m5stick-c.menu.DebugLevel.verbose=Verbose +m5stick-c.menu.DebugLevel.verbose.build.code_debug=5 + -heltec_wifi_kit_32.upload.tool=esptool +############################################################## + +odroid_esp32.name=ODROID ESP32 + +odroid_esp32.upload.tool=esptool_py +odroid_esp32.upload.maximum_size=1310720 +odroid_esp32.upload.maximum_data_size=327680 +odroid_esp32.upload.wait_for_upload_port=true + +odroid_esp32.serial.disableDTR=true +odroid_esp32.serial.disableRTS=true + +odroid_esp32.build.mcu=esp32 +odroid_esp32.build.core=esp32 +odroid_esp32.build.variant=odroid_esp32 +odroid_esp32.build.board=ODROID_ESP32 + +odroid_esp32.build.f_cpu=240000000L +odroid_esp32.build.flash_size=16MB +odroid_esp32.build.flash_mode=dio +odroid_esp32.build.boot=dio +odroid_esp32.build.partitions=default +odroid_esp32.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +odroid_esp32.menu.FlashMode.qio=QIO +odroid_esp32.menu.FlashMode.qio.build.flash_mode=dio +odroid_esp32.menu.FlashMode.qio.build.boot=qio +odroid_esp32.menu.FlashMode.dio=DIO +odroid_esp32.menu.FlashMode.dio.build.flash_mode=dio +odroid_esp32.menu.FlashMode.dio.build.boot=dio +odroid_esp32.menu.FlashMode.qout=QOUT +odroid_esp32.menu.FlashMode.qout.build.flash_mode=dout +odroid_esp32.menu.FlashMode.qout.build.boot=qout +odroid_esp32.menu.FlashMode.dout=DOUT +odroid_esp32.menu.FlashMode.dout.build.flash_mode=dout +odroid_esp32.menu.FlashMode.dout.build.boot=dout + +odroid_esp32.menu.FlashFreq.80=80MHz +odroid_esp32.menu.FlashFreq.80.build.flash_freq=80m +odroid_esp32.menu.FlashFreq.40=40MHz +odroid_esp32.menu.FlashFreq.40.build.flash_freq=40m + +odroid_esp32.menu.PartitionScheme.default=Default +odroid_esp32.menu.PartitionScheme.default.build.partitions=default +odroid_esp32.menu.PartitionScheme.no_ota=No OTA (Large APP) +odroid_esp32.menu.PartitionScheme.no_ota.build.partitions=no_ota +odroid_esp32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +odroid_esp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +odroid_esp32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +odroid_esp32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +odroid_esp32.menu.UploadSpeed.921600=921600 +odroid_esp32.menu.UploadSpeed.921600.upload.speed=921600 +odroid_esp32.menu.UploadSpeed.115200=115200 +odroid_esp32.menu.UploadSpeed.115200.upload.speed=115200 +odroid_esp32.menu.UploadSpeed.256000.windows=256000 +odroid_esp32.menu.UploadSpeed.256000.upload.speed=256000 +odroid_esp32.menu.UploadSpeed.230400.windows.upload.speed=256000 +odroid_esp32.menu.UploadSpeed.230400=230400 +odroid_esp32.menu.UploadSpeed.230400.upload.speed=230400 +odroid_esp32.menu.UploadSpeed.460800.linux=460800 +odroid_esp32.menu.UploadSpeed.460800.macosx=460800 +odroid_esp32.menu.UploadSpeed.460800.upload.speed=460800 +odroid_esp32.menu.UploadSpeed.512000.windows=512000 +odroid_esp32.menu.UploadSpeed.512000.upload.speed=512000 + +odroid_esp32.menu.DebugLevel.none=None +odroid_esp32.menu.DebugLevel.none.build.code_debug=0 +odroid_esp32.menu.DebugLevel.error=Error +odroid_esp32.menu.DebugLevel.error.build.code_debug=1 +odroid_esp32.menu.DebugLevel.warn=Warn +odroid_esp32.menu.DebugLevel.warn.build.code_debug=2 +odroid_esp32.menu.DebugLevel.info=Info +odroid_esp32.menu.DebugLevel.info.build.code_debug=3 +odroid_esp32.menu.DebugLevel.debug=Debug +odroid_esp32.menu.DebugLevel.debug.build.code_debug=4 +odroid_esp32.menu.DebugLevel.verbose=Verbose +odroid_esp32.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +heltec_wifi_kit_32.name=Heltec WiFi Kit 32 + +heltec_wifi_kit_32.upload.tool=esptool_py heltec_wifi_kit_32.upload.maximum_size=1310720 -heltec_wifi_kit_32.upload.maximum_data_size=294912 +heltec_wifi_kit_32.upload.maximum_data_size=327680 heltec_wifi_kit_32.upload.wait_for_upload_port=true heltec_wifi_kit_32.serial.disableDTR=true @@ -1310,18 +2586,74 @@ heltec_wifi_kit_32.serial.disableRTS=true heltec_wifi_kit_32.build.mcu=esp32 heltec_wifi_kit_32.build.core=esp32 heltec_wifi_kit_32.build.variant=heltec_wifi_kit_32 -heltec_wifi_kit_32.build.board=Heltec_WIFI_Kit_32 +heltec_wifi_kit_32.build.board=HELTEC_WIFI_KIT_32 heltec_wifi_kit_32.build.f_cpu=240000000L -heltec_wifi_kit_32.build.flash_mode=dio heltec_wifi_kit_32.build.flash_size=4MB +heltec_wifi_kit_32.build.flash_freq=40m +heltec_wifi_kit_32.build.flash_mode=dio heltec_wifi_kit_32.build.boot=dio heltec_wifi_kit_32.build.partitions=default +heltec_wifi_kit_32.build.defines= + +heltec_wifi_kit_32.menu.PSRAM.disabled=Disabled +heltec_wifi_kit_32.menu.PSRAM.disabled.build.defines= +heltec_wifi_kit_32.menu.PSRAM.enabled=Enabled +heltec_wifi_kit_32.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +heltec_wifi_kit_32.menu.PartitionScheme.default=Default +heltec_wifi_kit_32.menu.PartitionScheme.default.build.partitions=default +heltec_wifi_kit_32.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +heltec_wifi_kit_32.menu.PartitionScheme.minimal.build.partitions=minimal +heltec_wifi_kit_32.menu.PartitionScheme.no_ota=No OTA (Large APP) +heltec_wifi_kit_32.menu.PartitionScheme.no_ota.build.partitions=no_ota +heltec_wifi_kit_32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +heltec_wifi_kit_32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA) +heltec_wifi_kit_32.menu.PartitionScheme.huge_app.build.partitions=huge_app +heltec_wifi_kit_32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +heltec_wifi_kit_32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +heltec_wifi_kit_32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +heltec_wifi_kit_32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +heltec_wifi_kit_32.menu.PartitionScheme.fatflash=16M Fat +heltec_wifi_kit_32.menu.PartitionScheme.fatflash.build.partitions=ffat + +heltec_wifi_kit_32.menu.CPUFreq.240=240MHz (WiFi/BT) +heltec_wifi_kit_32.menu.CPUFreq.240.build.f_cpu=240000000L +heltec_wifi_kit_32.menu.CPUFreq.160=160MHz (WiFi/BT) +heltec_wifi_kit_32.menu.CPUFreq.160.build.f_cpu=160000000L +heltec_wifi_kit_32.menu.CPUFreq.80=80MHz (WiFi/BT) +heltec_wifi_kit_32.menu.CPUFreq.80.build.f_cpu=80000000L +heltec_wifi_kit_32.menu.CPUFreq.26=26MHz (26MHz XTAL) +heltec_wifi_kit_32.menu.CPUFreq.26.build.f_cpu=26000000L +heltec_wifi_kit_32.menu.CPUFreq.13=13MHz (26MHz XTAL) +heltec_wifi_kit_32.menu.CPUFreq.13.build.f_cpu=13000000L + +heltec_wifi_kit_32.menu.FlashMode.qio=QIO +heltec_wifi_kit_32.menu.FlashMode.qio.build.flash_mode=dio +heltec_wifi_kit_32.menu.FlashMode.qio.build.boot=qio +heltec_wifi_kit_32.menu.FlashMode.dio=DIO +heltec_wifi_kit_32.menu.FlashMode.dio.build.flash_mode=dio +heltec_wifi_kit_32.menu.FlashMode.dio.build.boot=dio +heltec_wifi_kit_32.menu.FlashMode.qout=QOUT +heltec_wifi_kit_32.menu.FlashMode.qout.build.flash_mode=dout +heltec_wifi_kit_32.menu.FlashMode.qout.build.boot=qout +heltec_wifi_kit_32.menu.FlashMode.dout=DOUT +heltec_wifi_kit_32.menu.FlashMode.dout.build.flash_mode=dout +heltec_wifi_kit_32.menu.FlashMode.dout.build.boot=dout -heltec_wifi_kit_32.menu.FlashFreq.80=80MHz -heltec_wifi_kit_32.menu.FlashFreq.80.build.flash_freq=80m heltec_wifi_kit_32.menu.FlashFreq.40=40MHz heltec_wifi_kit_32.menu.FlashFreq.40.build.flash_freq=40m +heltec_wifi_kit_32.menu.FlashFreq.80=80MHz +heltec_wifi_kit_32.menu.FlashFreq.80.build.flash_freq=80m + +heltec_wifi_kit_32.menu.FlashSize.4M=4MB (32Mb) +heltec_wifi_kit_32.menu.FlashSize.4M.build.flash_size=4MB +heltec_wifi_kit_32.menu.FlashSize.2M=2MB (16Mb) +heltec_wifi_kit_32.menu.FlashSize.2M.build.flash_size=2MB +heltec_wifi_kit_32.menu.FlashSize.2M.build.partitions=minimal +heltec_wifi_kit_32.menu.FlashSize.16M=16MB (128Mb) +heltec_wifi_kit_32.menu.FlashSize.16M.build.flash_size=16MB +heltec_wifi_kit_32.menu.FlashSize.16M.build.partitions=ffat heltec_wifi_kit_32.menu.UploadSpeed.921600=921600 heltec_wifi_kit_32.menu.UploadSpeed.921600.upload.speed=921600 @@ -1338,13 +2670,26 @@ heltec_wifi_kit_32.menu.UploadSpeed.460800.upload.speed=460800 heltec_wifi_kit_32.menu.UploadSpeed.512000.windows=512000 heltec_wifi_kit_32.menu.UploadSpeed.512000.upload.speed=512000 +heltec_wifi_kit_32.menu.DebugLevel.none=None +heltec_wifi_kit_32.menu.DebugLevel.none.build.code_debug=0 +heltec_wifi_kit_32.menu.DebugLevel.error=Error +heltec_wifi_kit_32.menu.DebugLevel.error.build.code_debug=1 +heltec_wifi_kit_32.menu.DebugLevel.warn=Warn +heltec_wifi_kit_32.menu.DebugLevel.warn.build.code_debug=2 +heltec_wifi_kit_32.menu.DebugLevel.info=Info +heltec_wifi_kit_32.menu.DebugLevel.info.build.code_debug=3 +heltec_wifi_kit_32.menu.DebugLevel.debug=Debug +heltec_wifi_kit_32.menu.DebugLevel.debug.build.code_debug=4 +heltec_wifi_kit_32.menu.DebugLevel.verbose=Verbose +heltec_wifi_kit_32.menu.DebugLevel.verbose.build.code_debug=5 + ############################################################## -heltec_wifi_lora_32.name=Heltec_WIFI_LoRa_32 +heltec_wifi_lora_32.name=Heltec WiFi LoRa 32 -heltec_wifi_lora_32.upload.tool=esptool +heltec_wifi_lora_32.upload.tool=esptool_py heltec_wifi_lora_32.upload.maximum_size=1310720 -heltec_wifi_lora_32.upload.maximum_data_size=294912 +heltec_wifi_lora_32.upload.maximum_data_size=327680 heltec_wifi_lora_32.upload.wait_for_upload_port=true heltec_wifi_lora_32.serial.disableDTR=true @@ -1353,18 +2698,74 @@ heltec_wifi_lora_32.serial.disableRTS=true heltec_wifi_lora_32.build.mcu=esp32 heltec_wifi_lora_32.build.core=esp32 heltec_wifi_lora_32.build.variant=heltec_wifi_lora_32 -heltec_wifi_lora_32.build.board=Heltec_WIFI_LoRa_32 +heltec_wifi_lora_32.build.board=HELTEC_WIFI_LORA_32 heltec_wifi_lora_32.build.f_cpu=240000000L -heltec_wifi_lora_32.build.flash_mode=dio heltec_wifi_lora_32.build.flash_size=4MB +heltec_wifi_lora_32.build.flash_freq=40m +heltec_wifi_lora_32.build.flash_mode=dio heltec_wifi_lora_32.build.boot=dio heltec_wifi_lora_32.build.partitions=default +heltec_wifi_lora_32.build.defines= + +heltec_wifi_lora_32.menu.PSRAM.disabled=Disabled +heltec_wifi_lora_32.menu.PSRAM.disabled.build.defines= +heltec_wifi_lora_32.menu.PSRAM.enabled=Enabled +heltec_wifi_lora_32.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +heltec_wifi_lora_32.menu.PartitionScheme.default=Default +heltec_wifi_lora_32.menu.PartitionScheme.default.build.partitions=default +heltec_wifi_lora_32.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +heltec_wifi_lora_32.menu.PartitionScheme.minimal.build.partitions=minimal +heltec_wifi_lora_32.menu.PartitionScheme.no_ota=No OTA (Large APP) +heltec_wifi_lora_32.menu.PartitionScheme.no_ota.build.partitions=no_ota +heltec_wifi_lora_32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +heltec_wifi_lora_32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA) +heltec_wifi_lora_32.menu.PartitionScheme.huge_app.build.partitions=huge_app +heltec_wifi_lora_32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +heltec_wifi_lora_32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +heltec_wifi_lora_32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +heltec_wifi_lora_32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +heltec_wifi_lora_32.menu.PartitionScheme.fatflash=16M Fat +heltec_wifi_lora_32.menu.PartitionScheme.fatflash.build.partitions=ffat + +heltec_wifi_lora_32.menu.CPUFreq.240=240MHz (WiFi/BT) +heltec_wifi_lora_32.menu.CPUFreq.240.build.f_cpu=240000000L +heltec_wifi_lora_32.menu.CPUFreq.160=160MHz (WiFi/BT) +heltec_wifi_lora_32.menu.CPUFreq.160.build.f_cpu=160000000L +heltec_wifi_lora_32.menu.CPUFreq.80=80MHz (WiFi/BT) +heltec_wifi_lora_32.menu.CPUFreq.80.build.f_cpu=80000000L +heltec_wifi_lora_32.menu.CPUFreq.26=26MHz (26MHz XTAL) +heltec_wifi_lora_32.menu.CPUFreq.26.build.f_cpu=26000000L +heltec_wifi_lora_32.menu.CPUFreq.13=13MHz (26MHz XTAL) +heltec_wifi_lora_32.menu.CPUFreq.13.build.f_cpu=13000000L + +heltec_wifi_lora_32.menu.FlashMode.qio=QIO +heltec_wifi_lora_32.menu.FlashMode.qio.build.flash_mode=dio +heltec_wifi_lora_32.menu.FlashMode.qio.build.boot=qio +heltec_wifi_lora_32.menu.FlashMode.dio=DIO +heltec_wifi_lora_32.menu.FlashMode.dio.build.flash_mode=dio +heltec_wifi_lora_32.menu.FlashMode.dio.build.boot=dio +heltec_wifi_lora_32.menu.FlashMode.qout=QOUT +heltec_wifi_lora_32.menu.FlashMode.qout.build.flash_mode=dout +heltec_wifi_lora_32.menu.FlashMode.qout.build.boot=qout +heltec_wifi_lora_32.menu.FlashMode.dout=DOUT +heltec_wifi_lora_32.menu.FlashMode.dout.build.flash_mode=dout +heltec_wifi_lora_32.menu.FlashMode.dout.build.boot=dout -heltec_wifi_lora_32.menu.FlashFreq.80=80MHz -heltec_wifi_lora_32.menu.FlashFreq.80.build.flash_freq=80m heltec_wifi_lora_32.menu.FlashFreq.40=40MHz heltec_wifi_lora_32.menu.FlashFreq.40.build.flash_freq=40m +heltec_wifi_lora_32.menu.FlashFreq.80=80MHz +heltec_wifi_lora_32.menu.FlashFreq.80.build.flash_freq=80m + +heltec_wifi_lora_32.menu.FlashSize.4M=4MB (32Mb) +heltec_wifi_lora_32.menu.FlashSize.4M.build.flash_size=4MB +heltec_wifi_lora_32.menu.FlashSize.2M=2MB (16Mb) +heltec_wifi_lora_32.menu.FlashSize.2M.build.flash_size=2MB +heltec_wifi_lora_32.menu.FlashSize.2M.build.partitions=minimal +heltec_wifi_lora_32.menu.FlashSize.16M=16MB (128Mb) +heltec_wifi_lora_32.menu.FlashSize.16M.build.flash_size=16MB +heltec_wifi_lora_32.menu.FlashSize.16M.build.partitions=ffat heltec_wifi_lora_32.menu.UploadSpeed.921600=921600 heltec_wifi_lora_32.menu.UploadSpeed.921600.upload.speed=921600 @@ -1381,13 +2782,262 @@ heltec_wifi_lora_32.menu.UploadSpeed.460800.upload.speed=460800 heltec_wifi_lora_32.menu.UploadSpeed.512000.windows=512000 heltec_wifi_lora_32.menu.UploadSpeed.512000.upload.speed=512000 +heltec_wifi_lora_32.menu.DebugLevel.none=None +heltec_wifi_lora_32.menu.DebugLevel.none.build.code_debug=0 +heltec_wifi_lora_32.menu.DebugLevel.error=Error +heltec_wifi_lora_32.menu.DebugLevel.error.build.code_debug=1 +heltec_wifi_lora_32.menu.DebugLevel.warn=Warn +heltec_wifi_lora_32.menu.DebugLevel.warn.build.code_debug=2 +heltec_wifi_lora_32.menu.DebugLevel.info=Info +heltec_wifi_lora_32.menu.DebugLevel.info.build.code_debug=3 +heltec_wifi_lora_32.menu.DebugLevel.debug=Debug +heltec_wifi_lora_32.menu.DebugLevel.debug.build.code_debug=4 +heltec_wifi_lora_32.menu.DebugLevel.verbose=Verbose +heltec_wifi_lora_32.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +heltec_wifi_lora_32_V2.name=Heltec WiFi LoRa 32(V2) + +heltec_wifi_lora_32_V2.upload.tool=esptool_py +heltec_wifi_lora_32_V2.upload.maximum_size=1310720 +heltec_wifi_lora_32_V2.upload.maximum_data_size=327680 +heltec_wifi_lora_32_V2.upload.wait_for_upload_port=true + +heltec_wifi_lora_32_V2.serial.disableDTR=true +heltec_wifi_lora_32_V2.serial.disableRTS=true + +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 +heltec_wifi_lora_32_V2.build.board=HELTEC_WIFI_LORA_32_V2 + +heltec_wifi_lora_32_V2.build.f_cpu=240000000L +heltec_wifi_lora_32_V2.build.flash_size=8MB +heltec_wifi_lora_32_V2.build.flash_freq=40m +heltec_wifi_lora_32_V2.build.flash_mode=dio +heltec_wifi_lora_32_V2.build.boot=dio +heltec_wifi_lora_32_V2.build.partitions=default_8MB +heltec_wifi_lora_32_V2.build.defines= + +heltec_wifi_lora_32_V2.menu.PSRAM.disabled=Disabled +heltec_wifi_lora_32_V2.menu.PSRAM.disabled.build.defines= +heltec_wifi_lora_32_V2.menu.PSRAM.enabled=Enabled +heltec_wifi_lora_32_V2.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +heltec_wifi_lora_32_V2.menu.PartitionScheme.default=default_8MB +heltec_wifi_lora_32_V2.menu.PartitionScheme.default.build.partitions=default_8MB +heltec_wifi_lora_32_V2.menu.PartitionScheme.default.upload.maximum_size=3342336 +heltec_wifi_lora_32_V2.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +heltec_wifi_lora_32_V2.menu.PartitionScheme.minimal.build.partitions=minimal +heltec_wifi_lora_32_V2.menu.PartitionScheme.no_ota=No OTA (Large APP) +heltec_wifi_lora_32_V2.menu.PartitionScheme.no_ota.build.partitions=no_ota +heltec_wifi_lora_32_V2.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +heltec_wifi_lora_32_V2.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA) +heltec_wifi_lora_32_V2.menu.PartitionScheme.huge_app.build.partitions=huge_app +heltec_wifi_lora_32_V2.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +heltec_wifi_lora_32_V2.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +heltec_wifi_lora_32_V2.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +heltec_wifi_lora_32_V2.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +heltec_wifi_lora_32_V2.menu.PartitionScheme.fatflash=16M Fat +heltec_wifi_lora_32_V2.menu.PartitionScheme.fatflash.build.partitions=ffat + +heltec_wifi_lora_32_V2.menu.CPUFreq.240=240MHz (WiFi/BT) +heltec_wifi_lora_32_V2.menu.CPUFreq.240.build.f_cpu=240000000L +heltec_wifi_lora_32_V2.menu.CPUFreq.160=160MHz (WiFi/BT) +heltec_wifi_lora_32_V2.menu.CPUFreq.160.build.f_cpu=160000000L +heltec_wifi_lora_32_V2.menu.CPUFreq.80=80MHz (WiFi/BT) +heltec_wifi_lora_32_V2.menu.CPUFreq.80.build.f_cpu=80000000L +heltec_wifi_lora_32_V2.menu.CPUFreq.40=40MHz (40MHz XTAL) +heltec_wifi_lora_32_V2.menu.CPUFreq.40.build.f_cpu=40000000L +heltec_wifi_lora_32_V2.menu.CPUFreq.20=20MHz (40MHz XTAL) +heltec_wifi_lora_32_V2.menu.CPUFreq.20.build.f_cpu=20000000L +heltec_wifi_lora_32_V2.menu.CPUFreq.10=10MHz (40MHz XTAL) +heltec_wifi_lora_32_V2.menu.CPUFreq.10.build.f_cpu=10000000L + +heltec_wifi_lora_32_V2.menu.FlashMode.qio=QIO +heltec_wifi_lora_32_V2.menu.FlashMode.qio.build.flash_mode=dio +heltec_wifi_lora_32_V2.menu.FlashMode.qio.build.boot=qio +heltec_wifi_lora_32_V2.menu.FlashMode.dio=DIO +heltec_wifi_lora_32_V2.menu.FlashMode.dio.build.flash_mode=dio +heltec_wifi_lora_32_V2.menu.FlashMode.dio.build.boot=dio +heltec_wifi_lora_32_V2.menu.FlashMode.qout=QOUT +heltec_wifi_lora_32_V2.menu.FlashMode.qout.build.flash_mode=dout +heltec_wifi_lora_32_V2.menu.FlashMode.qout.build.boot=qout +heltec_wifi_lora_32_V2.menu.FlashMode.dout=DOUT +heltec_wifi_lora_32_V2.menu.FlashMode.dout.build.flash_mode=dout +heltec_wifi_lora_32_V2.menu.FlashMode.dout.build.boot=dout + +heltec_wifi_lora_32_V2.menu.FlashFreq.80=80MHz +heltec_wifi_lora_32_V2.menu.FlashFreq.80.build.flash_freq=80m +heltec_wifi_lora_32_V2.menu.FlashFreq.40=40MHz +heltec_wifi_lora_32_V2.menu.FlashFreq.40.build.flash_freq=40m + +heltec_wifi_lora_32_V2.menu.FlashSize.8M=8MB (64Mb) +heltec_wifi_lora_32_V2.menu.FlashSize.8M.build.flash_size=8MB +heltec_wifi_lora_32_V2.menu.FlashSize.8M.build.partitions=default_8MB +heltec_wifi_lora_32_V2.menu.FlashSize.4M=4MB (32Mb) +heltec_wifi_lora_32_V2.menu.FlashSize.4M.build.flash_size=4MB +heltec_wifi_lora_32_V2.menu.FlashSize.2M=2MB (16Mb) +heltec_wifi_lora_32_V2.menu.FlashSize.2M.build.flash_size=2MB +heltec_wifi_lora_32_V2.menu.FlashSize.2M.build.partitions=minimal +heltec_wifi_lora_32_V2.menu.FlashSize.16M=16MB (128Mb) +heltec_wifi_lora_32_V2.menu.FlashSize.16M.build.flash_size=16MB +heltec_wifi_lora_32_V2.menu.FlashSize.16M.build.partitions=ffat + +heltec_wifi_lora_32_V2.menu.UploadSpeed.921600=921600 +heltec_wifi_lora_32_V2.menu.UploadSpeed.921600.upload.speed=921600 +heltec_wifi_lora_32_V2.menu.UploadSpeed.115200=115200 +heltec_wifi_lora_32_V2.menu.UploadSpeed.115200.upload.speed=115200 +heltec_wifi_lora_32_V2.menu.UploadSpeed.256000.windows=256000 +heltec_wifi_lora_32_V2.menu.UploadSpeed.256000.upload.speed=256000 +heltec_wifi_lora_32_V2.menu.UploadSpeed.230400.windows.upload.speed=256000 +heltec_wifi_lora_32_V2.menu.UploadSpeed.230400=230400 +heltec_wifi_lora_32_V2.menu.UploadSpeed.230400.upload.speed=230400 +heltec_wifi_lora_32_V2.menu.UploadSpeed.460800.linux=460800 +heltec_wifi_lora_32_V2.menu.UploadSpeed.460800.macosx=460800 +heltec_wifi_lora_32_V2.menu.UploadSpeed.460800.upload.speed=460800 +heltec_wifi_lora_32_V2.menu.UploadSpeed.512000.windows=512000 +heltec_wifi_lora_32_V2.menu.UploadSpeed.512000.upload.speed=512000 + +heltec_wifi_lora_32_V2.menu.DebugLevel.none=None +heltec_wifi_lora_32_V2.menu.DebugLevel.none.build.code_debug=0 +heltec_wifi_lora_32_V2.menu.DebugLevel.error=Error +heltec_wifi_lora_32_V2.menu.DebugLevel.error.build.code_debug=1 +heltec_wifi_lora_32_V2.menu.DebugLevel.warn=Warn +heltec_wifi_lora_32_V2.menu.DebugLevel.warn.build.code_debug=2 +heltec_wifi_lora_32_V2.menu.DebugLevel.info=Info +heltec_wifi_lora_32_V2.menu.DebugLevel.info.build.code_debug=3 +heltec_wifi_lora_32_V2.menu.DebugLevel.debug=Debug +heltec_wifi_lora_32_V2.menu.DebugLevel.debug.build.code_debug=4 +heltec_wifi_lora_32_V2.menu.DebugLevel.verbose=Verbose +heltec_wifi_lora_32_V2.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +heltec_wireless_stick.name=Heltec Wireless Stick + +heltec_wireless_stick.upload.tool=esptool_py +heltec_wireless_stick.upload.maximum_size=1310720 +heltec_wireless_stick.upload.maximum_data_size=327680 +heltec_wireless_stick.upload.wait_for_upload_port=true + +heltec_wireless_stick.serial.disableDTR=true +heltec_wireless_stick.serial.disableRTS=true + +heltec_wireless_stick.build.mcu=esp32 +heltec_wireless_stick.build.core=esp32 +heltec_wireless_stick.build.variant=heltec_wireless_stick +heltec_wireless_stick.build.board=HELTEC_WIRELESS_STICK + +heltec_wireless_stick.build.f_cpu=240000000L +heltec_wireless_stick.build.flash_size=8MB +heltec_wireless_stick.build.flash_freq=40m +heltec_wireless_stick.build.flash_mode=dio +heltec_wireless_stick.build.boot=dio +heltec_wireless_stick.build.partitions=default_8MB +heltec_wireless_stick.build.defines= + +heltec_wireless_stick.menu.PSRAM.disabled=Disabled +heltec_wireless_stick.menu.PSRAM.disabled.build.defines= +heltec_wireless_stick.menu.PSRAM.enabled=Enabled +heltec_wireless_stick.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +heltec_wireless_stick.menu.PartitionScheme.default=default_8MB +heltec_wireless_stick.menu.PartitionScheme.default.build.partitions=default_8MB +heltec_wireless_stick.menu.PartitionScheme.default.upload.maximum_size=3342336 +heltec_wireless_stick.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +heltec_wireless_stick.menu.PartitionScheme.minimal.build.partitions=minimal +heltec_wireless_stick.menu.PartitionScheme.no_ota=No OTA (Large APP) +heltec_wireless_stick.menu.PartitionScheme.no_ota.build.partitions=no_ota +heltec_wireless_stick.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +heltec_wireless_stick.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA) +heltec_wireless_stick.menu.PartitionScheme.huge_app.build.partitions=huge_app +heltec_wireless_stick.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +heltec_wireless_stick.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +heltec_wireless_stick.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +heltec_wireless_stick.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +heltec_wireless_stick.menu.PartitionScheme.fatflash=16M Fat +heltec_wireless_stick.menu.PartitionScheme.fatflash.build.partitions=ffat + +heltec_wireless_stick.menu.CPUFreq.240=240MHz (WiFi/BT) +heltec_wireless_stick.menu.CPUFreq.240.build.f_cpu=240000000L +heltec_wireless_stick.menu.CPUFreq.160=160MHz (WiFi/BT) +heltec_wireless_stick.menu.CPUFreq.160.build.f_cpu=160000000L +heltec_wireless_stick.menu.CPUFreq.80=80MHz (WiFi/BT) +heltec_wireless_stick.menu.CPUFreq.80.build.f_cpu=80000000L +heltec_wireless_stick.menu.CPUFreq.40=40MHz (40MHz XTAL) +heltec_wireless_stick.menu.CPUFreq.40.build.f_cpu=40000000L +heltec_wireless_stick.menu.CPUFreq.20=20MHz (40MHz XTAL) +heltec_wireless_stick.menu.CPUFreq.20.build.f_cpu=20000000L +heltec_wireless_stick.menu.CPUFreq.10=10MHz (40MHz XTAL) +heltec_wireless_stick.menu.CPUFreq.10.build.f_cpu=10000000L + +heltec_wireless_stick.menu.FlashMode.qio=QIO +heltec_wireless_stick.menu.FlashMode.qio.build.flash_mode=dio +heltec_wireless_stick.menu.FlashMode.qio.build.boot=qio +heltec_wireless_stick.menu.FlashMode.dio=DIO +heltec_wireless_stick.menu.FlashMode.dio.build.flash_mode=dio +heltec_wireless_stick.menu.FlashMode.dio.build.boot=dio +heltec_wireless_stick.menu.FlashMode.qout=QOUT +heltec_wireless_stick.menu.FlashMode.qout.build.flash_mode=dout +heltec_wireless_stick.menu.FlashMode.qout.build.boot=qout +heltec_wireless_stick.menu.FlashMode.dout=DOUT +heltec_wireless_stick.menu.FlashMode.dout.build.flash_mode=dout +heltec_wireless_stick.menu.FlashMode.dout.build.boot=dout + +heltec_wireless_stick.menu.FlashFreq.80=80MHz +heltec_wireless_stick.menu.FlashFreq.80.build.flash_freq=80m +heltec_wireless_stick.menu.FlashFreq.40=40MHz +heltec_wireless_stick.menu.FlashFreq.40.build.flash_freq=40m + +heltec_wireless_stick.menu.FlashSize.8M=8MB (64Mb) +heltec_wireless_stick.menu.FlashSize.8M.build.flash_size=8MB +heltec_wireless_stick.menu.FlashSize.2M.build.partitions=default_8MB +heltec_wireless_stick.menu.FlashSize.4M=4MB (32Mb) +heltec_wireless_stick.menu.FlashSize.4M.build.flash_size=4MB +heltec_wireless_stick.menu.FlashSize.2M=2MB (16Mb) +heltec_wireless_stick.menu.FlashSize.2M.build.flash_size=2MB +heltec_wireless_stick.menu.FlashSize.2M.build.partitions=minimal +heltec_wireless_stick.menu.FlashSize.16M=16MB (128Mb) +heltec_wireless_stick.menu.FlashSize.16M.build.flash_size=16MB +heltec_wireless_stick.menu.FlashSize.16M.build.partitions=ffat + +heltec_wireless_stick.menu.UploadSpeed.921600=921600 +heltec_wireless_stick.menu.UploadSpeed.921600.upload.speed=921600 +heltec_wireless_stick.menu.UploadSpeed.115200=115200 +heltec_wireless_stick.menu.UploadSpeed.115200.upload.speed=115200 +heltec_wireless_stick.menu.UploadSpeed.256000.windows=256000 +heltec_wireless_stick.menu.UploadSpeed.256000.upload.speed=256000 +heltec_wireless_stick.menu.UploadSpeed.230400.windows.upload.speed=256000 +heltec_wireless_stick.menu.UploadSpeed.230400=230400 +heltec_wireless_stick.menu.UploadSpeed.230400.upload.speed=230400 +heltec_wireless_stick.menu.UploadSpeed.460800.linux=460800 +heltec_wireless_stick.menu.UploadSpeed.460800.macosx=460800 +heltec_wireless_stick.menu.UploadSpeed.460800.upload.speed=460800 +heltec_wireless_stick.menu.UploadSpeed.512000.windows=512000 +heltec_wireless_stick.menu.UploadSpeed.512000.upload.speed=512000 + +heltec_wireless_stick.menu.DebugLevel.none=None +heltec_wireless_stick.menu.DebugLevel.none.build.code_debug=0 +heltec_wireless_stick.menu.DebugLevel.error=Error +heltec_wireless_stick.menu.DebugLevel.error.build.code_debug=1 +heltec_wireless_stick.menu.DebugLevel.warn=Warn +heltec_wireless_stick.menu.DebugLevel.warn.build.code_debug=2 +heltec_wireless_stick.menu.DebugLevel.info=Info +heltec_wireless_stick.menu.DebugLevel.info.build.code_debug=3 +heltec_wireless_stick.menu.DebugLevel.debug=Debug +heltec_wireless_stick.menu.DebugLevel.debug.build.code_debug=4 +heltec_wireless_stick.menu.DebugLevel.verbose=Verbose +heltec_wireless_stick.menu.DebugLevel.verbose.build.code_debug=5 + ############################################################## espectro32.name=ESPectro32 -espectro32.upload.tool=esptool +espectro32.upload.tool=esptool_py espectro32.upload.maximum_size=1310720 -espectro32.upload.maximum_data_size=294912 +espectro32.upload.maximum_data_size=327680 espectro32.upload.wait_for_upload_port=true espectro32.serial.disableDTR=true @@ -1403,6 +3053,7 @@ espectro32.build.flash_size=4MB espectro32.build.flash_mode=dio espectro32.build.boot=dio espectro32.build.partitions=default +espectro32.build.defines= espectro32.menu.FlashMode.qio=QIO espectro32.menu.FlashMode.qio.build.flash_mode=dio @@ -1460,9 +3111,9 @@ espectro32.menu.DebugLevel.verbose.build.code_debug=5 ############################################################## CoreESP32.name=Microduino-CoreESP32 -CoreESP32.upload.tool=esptool +CoreESP32.upload.tool=esptool_py CoreESP32.upload.maximum_size=1310720 -CoreESP32.upload.maximum_data_size=294912 +CoreESP32.upload.maximum_data_size=327680 CoreESP32.upload.wait_for_upload_port=true CoreESP32.serial.disableDTR=true @@ -1478,6 +3129,7 @@ CoreESP32.build.flash_mode=dio CoreESP32.build.flash_size=4MB CoreESP32.build.boot=dio CoreESP32.build.partitions=default +CoreESP32.build.defines= CoreESP32.menu.FlashFreq.80=80MHz CoreESP32.menu.FlashFreq.80.build.flash_freq=80m @@ -1498,3 +3150,1101 @@ CoreESP32.menu.UploadSpeed.460800.macosx=460800 CoreESP32.menu.UploadSpeed.460800.upload.speed=460800 CoreESP32.menu.UploadSpeed.512000.windows=512000 CoreESP32.menu.UploadSpeed.512000.upload.speed=512000 + +############################################################## + + +alksesp32.name=ALKS ESP32 + +alksesp32.upload.tool=esptool_py +alksesp32.upload.maximum_size=1310720 +alksesp32.upload.maximum_data_size=327680 +alksesp32.upload.wait_for_upload_port=true + +alksesp32.serial.disableDTR=true +alksesp32.serial.disableRTS=true + +alksesp32.build.mcu=esp32 +alksesp32.build.core=esp32 +alksesp32.build.variant=alksesp32 +alksesp32.build.board=ALKS + +alksesp32.build.f_cpu=240000000L +alksesp32.build.flash_size=4MB +alksesp32.build.flash_freq=40m +alksesp32.build.flash_mode=dio +alksesp32.build.boot=dio +alksesp32.build.partitions=default +alksesp32.build.defines= + +alksesp32.menu.PSRAM.disabled=Disabled +alksesp32.menu.PSRAM.disabled.build.defines= +alksesp32.menu.PSRAM.enabled=Enabled +alksesp32.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +alksesp32.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS) +alksesp32.menu.PartitionScheme.default.build.partitions=default +alksesp32.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS) +alksesp32.menu.PartitionScheme.defaultffat.build.partitions=default_ffat +alksesp32.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS) +alksesp32.menu.PartitionScheme.minimal.build.partitions=minimal +alksesp32.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS) +alksesp32.menu.PartitionScheme.no_ota.build.partitions=no_ota +alksesp32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +alksesp32.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS) +alksesp32.menu.PartitionScheme.noota_3g.build.partitions=noota_3g +alksesp32.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576 +alksesp32.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS) +alksesp32.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat +alksesp32.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152 +alksesp32.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS) +alksesp32.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat +alksesp32.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576 +alksesp32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS) +alksesp32.menu.PartitionScheme.huge_app.build.partitions=huge_app +alksesp32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +alksesp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS) +alksesp32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +alksesp32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +alksesp32.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT) +alksesp32.menu.PartitionScheme.fatflash.build.partitions=ffat + +alksesp32.menu.CPUFreq.240=240MHz (WiFi/BT) +alksesp32.menu.CPUFreq.240.build.f_cpu=240000000L +alksesp32.menu.CPUFreq.160=160MHz (WiFi/BT) +alksesp32.menu.CPUFreq.160.build.f_cpu=160000000L +alksesp32.menu.CPUFreq.80=80MHz (WiFi/BT) +alksesp32.menu.CPUFreq.80.build.f_cpu=80000000L +alksesp32.menu.CPUFreq.40=40MHz (40MHz XTAL) +alksesp32.menu.CPUFreq.40.build.f_cpu=40000000L +alksesp32.menu.CPUFreq.26=26MHz (26MHz XTAL) +alksesp32.menu.CPUFreq.26.build.f_cpu=26000000L +alksesp32.menu.CPUFreq.20=20MHz (40MHz XTAL) +alksesp32.menu.CPUFreq.20.build.f_cpu=20000000L +alksesp32.menu.CPUFreq.13=13MHz (26MHz XTAL) +alksesp32.menu.CPUFreq.13.build.f_cpu=13000000L +alksesp32.menu.CPUFreq.10=10MHz (40MHz XTAL) +alksesp32.menu.CPUFreq.10.build.f_cpu=10000000L + +alksesp32.menu.FlashMode.qio=QIO +alksesp32.menu.FlashMode.qio.build.flash_mode=dio +alksesp32.menu.FlashMode.qio.build.boot=qio +alksesp32.menu.FlashMode.dio=DIO +alksesp32.menu.FlashMode.dio.build.flash_mode=dio +alksesp32.menu.FlashMode.dio.build.boot=dio +alksesp32.menu.FlashMode.qout=QOUT +alksesp32.menu.FlashMode.qout.build.flash_mode=dout +alksesp32.menu.FlashMode.qout.build.boot=qout +alksesp32.menu.FlashMode.dout=DOUT +alksesp32.menu.FlashMode.dout.build.flash_mode=dout +alksesp32.menu.FlashMode.dout.build.boot=dout + +alksesp32.menu.FlashFreq.80=80MHz +alksesp32.menu.FlashFreq.80.build.flash_freq=80m +alksesp32.menu.FlashFreq.40=40MHz +alksesp32.menu.FlashFreq.40.build.flash_freq=40m + +alksesp32.menu.FlashSize.4M=4MB (32Mb) +alksesp32.menu.FlashSize.4M.build.flash_size=4MB +alksesp32.menu.FlashSize.2M=2MB (16Mb) +alksesp32.menu.FlashSize.2M.build.flash_size=2MB +alksesp32.menu.FlashSize.2M.build.partitions=minimal +alksesp32.menu.FlashSize.16M=16MB (128Mb) +alksesp32.menu.FlashSize.16M.build.flash_size=16MB +alksesp32.menu.FlashSize.16M.build.partitions=ffat + +alksesp32.menu.UploadSpeed.921600=921600 +alksesp32.menu.UploadSpeed.921600.upload.speed=921600 +alksesp32.menu.UploadSpeed.115200=115200 +alksesp32.menu.UploadSpeed.115200.upload.speed=115200 +alksesp32.menu.UploadSpeed.256000.windows=256000 +alksesp32.menu.UploadSpeed.256000.upload.speed=256000 +alksesp32.menu.UploadSpeed.230400.windows.upload.speed=256000 +alksesp32.menu.UploadSpeed.230400=230400 +alksesp32.menu.UploadSpeed.230400.upload.speed=230400 +alksesp32.menu.UploadSpeed.460800.linux=460800 +alksesp32.menu.UploadSpeed.460800.macosx=460800 +alksesp32.menu.UploadSpeed.460800.upload.speed=460800 +alksesp32.menu.UploadSpeed.512000.windows=512000 +alksesp32.menu.UploadSpeed.512000.upload.speed=512000 + +alksesp32.menu.DebugLevel.none=None +alksesp32.menu.DebugLevel.none.build.code_debug=0 +alksesp32.menu.DebugLevel.error=Error +alksesp32.menu.DebugLevel.error.build.code_debug=1 +alksesp32.menu.DebugLevel.warn=Warn +alksesp32.menu.DebugLevel.warn.build.code_debug=2 +alksesp32.menu.DebugLevel.info=Info +alksesp32.menu.DebugLevel.info.build.code_debug=3 +alksesp32.menu.DebugLevel.debug=Debug +alksesp32.menu.DebugLevel.debug.build.code_debug=4 +alksesp32.menu.DebugLevel.verbose=Verbose +alksesp32.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + + +wipy3.name=WiPy 3.0 + +wipy3.upload.tool=esptool_py +wipy3.upload.maximum_size=1310720 +wipy3.upload.maximum_data_size=294912 +wipy3.upload.wait_for_upload_port=true + +wipy3.serial.disableDTR=true +wipy3.serial.disableRTS=true + +wipy3.build.mcu=esp32 +wipy3.build.core=esp32 +wipy3.build.variant=wipy3 +wipy3.build.board=WIPY3 + +wipy3.build.f_cpu=240000000L +wipy3.build.flash_mode=dio +wipy3.build.flash_size=8MB +wipy3.build.boot=dio +wipy3.build.partitions=default +wipy3.build.defines= + +wipy3.menu.FlashFreq.80=80MHz +wipy3.menu.FlashFreq.80.build.flash_freq=80m +wipy3.menu.FlashFreq.40=40MHz +wipy3.menu.FlashFreq.40.build.flash_freq=40m + +wipy3.menu.UploadSpeed.921600=921600 +wipy3.menu.UploadSpeed.921600.upload.speed=921600 +wipy3.menu.UploadSpeed.115200=115200 +wipy3.menu.UploadSpeed.115200.upload.speed=115200 +wipy3.menu.UploadSpeed.256000.windows=256000 +wipy3.menu.UploadSpeed.256000.upload.speed=256000 +wipy3.menu.UploadSpeed.230400.windows.upload.speed=256000 +wipy3.menu.UploadSpeed.230400=230400 +wipy3.menu.UploadSpeed.230400.upload.speed=230400 +wipy3.menu.UploadSpeed.460800.linux=460800 +wipy3.menu.UploadSpeed.460800.macosx=460800 +wipy3.menu.UploadSpeed.460800.upload.speed=460800 +wipy3.menu.UploadSpeed.512000.windows=512000 +wipy3.menu.UploadSpeed.512000.upload.speed=512000 + +wipy3.menu.DebugLevel.none=None +wipy3.menu.DebugLevel.none.build.code_debug=0 +wipy3.menu.DebugLevel.error=Error +wipy3.menu.DebugLevel.error.build.code_debug=1 +wipy3.menu.DebugLevel.warn=Warn +wipy3.menu.DebugLevel.warn.build.code_debug=2 +wipy3.menu.DebugLevel.info=Info +wipy3.menu.DebugLevel.info.build.code_debug=3 +wipy3.menu.DebugLevel.debug=Debug +wipy3.menu.DebugLevel.debug.build.code_debug=4 +wipy3.menu.DebugLevel.verbose=Verbose +wipy3.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +bpi-bit.name=BPI-BIT + +bpi-bit.upload.tool=esptool_py +bpi-bit.upload.maximum_size=1310720 +bpi-bit.upload.maximum_data_size=294912 +bpi-bit.upload.wait_for_upload_port=true + +bpi-bit.serial.disableDTR=true +bpi-bit.serial.disableRTS=true + +bpi-bit.build.mcu=esp32 +bpi-bit.build.core=esp32 +bpi-bit.build.variant=bpi-bit +bpi-bit.build.board=BPI-BIT + +bpi-bit.build.f_cpu=160000000L +bpi-bit.build.flash_mode=dio +bpi-bit.build.flash_size=4MB +bpi-bit.build.boot=dio +bpi-bit.build.partitions=default + +bpi-bit.menu.FlashFreq.80=80MHz +bpi-bit.menu.FlashFreq.80.build.flash_freq=80m +bpi-bit.menu.FlashFreq.40=40MHz +bpi-bit.menu.FlashFreq.40.build.flash_freq=40m + +bpi-bit.menu.UploadSpeed.921600=921600 +bpi-bit.menu.UploadSpeed.921600.upload.speed=921600 +bpi-bit.menu.UploadSpeed.115200=115200 +bpi-bit.menu.UploadSpeed.115200.upload.speed=115200 +bpi-bit.menu.UploadSpeed.256000.windows=256000 +bpi-bit.menu.UploadSpeed.256000.upload.speed=256000 +bpi-bit.menu.UploadSpeed.230400.windows.upload.speed=256000 +bpi-bit.menu.UploadSpeed.230400=230400 +bpi-bit.menu.UploadSpeed.230400.upload.speed=230400 +bpi-bit.menu.UploadSpeed.460800.linux=460800 +bpi-bit.menu.UploadSpeed.460800.macosx=460800 +bpi-bit.menu.UploadSpeed.460800.upload.speed=460800 +bpi-bit.menu.UploadSpeed.512000.windows=512000 +bpi-bit.menu.UploadSpeed.512000.upload.speed=512000 + +############################################################## + +wesp32.name=Silicognition wESP32 + +wesp32.upload.tool=esptool_py +wesp32.upload.maximum_size=1310720 +wesp32.upload.maximum_data_size=327680 +wesp32.upload.wait_for_upload_port=true + +wesp32.serial.disableDTR=true +wesp32.serial.disableRTS=true + +wesp32.build.mcu=esp32 +wesp32.build.core=esp32 +wesp32.build.variant=wesp32 +wesp32.build.board=WESP32 + +wesp32.build.f_cpu=240000000L +wesp32.build.flash_mode=dio +wesp32.build.flash_size=4MB +wesp32.build.boot=dio +wesp32.build.partitions=default +wesp32.build.defines= + +wesp32.menu.FlashFreq.80=80MHz +wesp32.menu.FlashFreq.80.build.flash_freq=80m +wesp32.menu.FlashFreq.40=40MHz +wesp32.menu.FlashFreq.40.build.flash_freq=40m + +wesp32.menu.UploadSpeed.921600=921600 +wesp32.menu.UploadSpeed.921600.upload.speed=921600 +wesp32.menu.UploadSpeed.115200=115200 +wesp32.menu.UploadSpeed.115200.upload.speed=115200 +wesp32.menu.UploadSpeed.256000.windows=256000 +wesp32.menu.UploadSpeed.256000.upload.speed=256000 +wesp32.menu.UploadSpeed.230400.windows.upload.speed=256000 +wesp32.menu.UploadSpeed.230400=230400 +wesp32.menu.UploadSpeed.230400.upload.speed=230400 +wesp32.menu.UploadSpeed.460800.linux=460800 +wesp32.menu.UploadSpeed.460800.macosx=460800 +wesp32.menu.UploadSpeed.460800.upload.speed=460800 +wesp32.menu.UploadSpeed.512000.windows=512000 +wesp32.menu.UploadSpeed.512000.upload.speed=512000 + +wesp32.menu.DebugLevel.none=None +wesp32.menu.DebugLevel.none.build.code_debug=0 +wesp32.menu.DebugLevel.error=Error +wesp32.menu.DebugLevel.error.build.code_debug=1 +wesp32.menu.DebugLevel.warn=Warn +wesp32.menu.DebugLevel.warn.build.code_debug=2 +wesp32.menu.DebugLevel.info=Info +wesp32.menu.DebugLevel.info.build.code_debug=3 +wesp32.menu.DebugLevel.debug=Debug +wesp32.menu.DebugLevel.debug.build.code_debug=4 +wesp32.menu.DebugLevel.verbose=Verbose +wesp32.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +t-beam.name=T-Beam + +t-beam.upload.tool=esptool_py +t-beam.upload.maximum_size=1310720 +t-beam.upload.maximum_data_size=327680 +t-beam.upload.wait_for_upload_port=true + +t-beam.serial.disableDTR=true +t-beam.serial.disableRTS=true + +t-beam.build.mcu=esp32 +t-beam.build.core=esp32 +t-beam.build.variant=t-beam +t-beam.build.board=T-Beam + +t-beam.build.f_cpu=240000000L +t-beam.build.flash_mode=dio +t-beam.build.flash_size=4MB +t-beam.build.boot=dio +t-beam.build.partitions=default + +t-beam.menu.PSRAM.disabled=Disabled +t-beam.menu.PSRAM.disabled.build.defines= +t-beam.menu.PSRAM.enabled=Enabled +t-beam.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +t-beam.menu.FlashFreq.80=80MHz +t-beam.menu.FlashFreq.80.build.flash_freq=80m +t-beam.menu.FlashFreq.40=40MHz +t-beam.menu.FlashFreq.40.build.flash_freq=40m + +t-beam.menu.UploadSpeed.921600=921600 +t-beam.menu.UploadSpeed.921600.upload.speed=921600 +t-beam.menu.UploadSpeed.115200=115200 +t-beam.menu.UploadSpeed.115200.upload.speed=115200 +t-beam.menu.UploadSpeed.256000.windows=256000 +t-beam.menu.UploadSpeed.256000.upload.speed=256000 +t-beam.menu.UploadSpeed.230400.windows.upload.speed=256000 +t-beam.menu.UploadSpeed.230400=230400 +t-beam.menu.UploadSpeed.230400.upload.speed=230400 +t-beam.menu.UploadSpeed.460800.linux=460800 +t-beam.menu.UploadSpeed.460800.macosx=460800 +t-beam.menu.UploadSpeed.460800.upload.speed=460800 +t-beam.menu.UploadSpeed.512000.windows=512000 +t-beam.menu.UploadSpeed.512000.upload.speed=512000 + +t-beam.menu.DebugLevel.none=None +t-beam.menu.DebugLevel.none.build.code_debug=0 +t-beam.menu.DebugLevel.error=Error +t-beam.menu.DebugLevel.error.build.code_debug=1 +t-beam.menu.DebugLevel.warn=Warn +t-beam.menu.DebugLevel.warn.build.code_debug=2 +t-beam.menu.DebugLevel.info=Info +t-beam.menu.DebugLevel.info.build.code_debug=3 +t-beam.menu.DebugLevel.debug=Debug +t-beam.menu.DebugLevel.debug.build.code_debug=4 +t-beam.menu.DebugLevel.verbose=Verbose +t-beam.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +d-duino-32.name=D-duino-32 + +d-duino-32.upload.tool=esptool_py +d-duino-32.upload.maximum_size=1310720 +d-duino-32.upload.maximum_data_size=327680 +d-duino-32.upload.wait_for_upload_port=true + +d-duino-32.serial.disableDTR=true +d-duino-32.serial.disableRTS=true + +d-duino-32.build.mcu=esp32 +d-duino-32.build.core=esp32 +d-duino-32.build.variant=d-duino-32 +d-duino-32.build.board=D-duino-32 + +d-duino-32.build.f_cpu=240000000L +d-duino-32.build.flash_size=4MB +d-duino-32.build.flash_freq=40m +d-duino-32.build.flash_mode=dio +d-duino-32.build.boot=dio +d-duino-32.build.partitions=default +d-duino-32.build.defines= + +d-duino-32.menu.PartitionScheme.default=Default +d-duino-32.menu.PartitionScheme.default.build.partitions=default +d-duino-32.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +d-duino-32.menu.PartitionScheme.minimal.build.partitions=minimal +d-duino-32.menu.PartitionScheme.no_ota=No OTA (Large APP) +d-duino-32.menu.PartitionScheme.no_ota.build.partitions=no_ota +d-duino-32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +d-duino-32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +d-duino-32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +d-duino-32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +d-duino-32.menu.PartitionScheme.fatflash=16M Fat +d-duino-32.menu.PartitionScheme.fatflash.build.partitions=ffat + +d-duino-32.menu.FlashFreq.80=80MHz +d-duino-32.menu.FlashFreq.80.build.flash_freq=80m +d-duino-32.menu.FlashFreq.40=40MHz +d-duino-32.menu.FlashFreq.40.build.flash_freq=40m + +d-duino-32.menu.UploadSpeed.921600=921600 +d-duino-32.menu.UploadSpeed.921600.upload.speed=921600 +d-duino-32.menu.UploadSpeed.115200=115200 +d-duino-32.menu.UploadSpeed.115200.upload.speed=115200 +d-duino-32.menu.UploadSpeed.256000.windows=256000 +d-duino-32.menu.UploadSpeed.256000.upload.speed=256000 +d-duino-32.menu.UploadSpeed.230400.windows.upload.speed=256000 +d-duino-32.menu.UploadSpeed.230400=230400 +d-duino-32.menu.UploadSpeed.230400.upload.speed=230400 +d-duino-32.menu.UploadSpeed.460800.linux=460800 +d-duino-32.menu.UploadSpeed.460800.macosx=460800 +d-duino-32.menu.UploadSpeed.460800.upload.speed=460800 +d-duino-32.menu.UploadSpeed.512000.windows=512000 +d-duino-32.menu.UploadSpeed.512000.upload.speed=512000 + +d-duino-32.menu.DebugLevel.none=None +d-duino-32.menu.DebugLevel.none.build.code_debug=0 +d-duino-32.menu.DebugLevel.error=Error +d-duino-32.menu.DebugLevel.error.build.code_debug=1 +d-duino-32.menu.DebugLevel.warn=Warn +d-duino-32.menu.DebugLevel.warn.build.code_debug=2 +d-duino-32.menu.DebugLevel.info=Info +d-duino-32.menu.DebugLevel.info.build.code_debug=3 +d-duino-32.menu.DebugLevel.debug=Debug +d-duino-32.menu.DebugLevel.debug.build.code_debug=4 +d-duino-32.menu.DebugLevel.verbose=Verbose +d-duino-32.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +lopy.name=LoPy + +lopy.upload.tool=esptool_py +lopy.upload.maximum_size=1310720 +lopy.upload.maximum_data_size=327680 +lopy.upload.wait_for_upload_port=true + +lopy.serial.disableDTR=true +lopy.serial.disableRTS=true + +lopy.build.mcu=esp32 +lopy.build.core=esp32 +lopy.build.variant=lopy +lopy.build.board=LoPy + +lopy.build.f_cpu=240000000L +lopy.build.flash_mode=dio +lopy.build.flash_size=4MB +lopy.build.boot=dio +lopy.build.partitions=default + +lopy.menu.FlashFreq.80=80MHz +lopy.menu.FlashFreq.80.build.flash_freq=80m +lopy.menu.FlashFreq.40=40MHz +lopy.menu.FlashFreq.40.build.flash_freq=40m + +lopy.menu.UploadSpeed.921600=921600 +lopy.menu.UploadSpeed.921600.upload.speed=921600 +lopy.menu.UploadSpeed.115200=115200 +lopy.menu.UploadSpeed.115200.upload.speed=115200 +lopy.menu.UploadSpeed.256000.windows=256000 +lopy.menu.UploadSpeed.256000.upload.speed=256000 +lopy.menu.UploadSpeed.230400.windows.upload.speed=256000 +lopy.menu.UploadSpeed.230400=230400 +lopy.menu.UploadSpeed.230400.upload.speed=230400 +lopy.menu.UploadSpeed.460800.linux=460800 +lopy.menu.UploadSpeed.460800.macosx=460800 +lopy.menu.UploadSpeed.460800.upload.speed=460800 +lopy.menu.UploadSpeed.512000.windows=512000 +lopy.menu.UploadSpeed.512000.upload.speed=512000 + +lopy.menu.DebugLevel.none=None +lopy.menu.DebugLevel.none.build.code_debug=0 +lopy.menu.DebugLevel.error=Error +lopy.menu.DebugLevel.error.build.code_debug=1 +lopy.menu.DebugLevel.warn=Warn +lopy.menu.DebugLevel.warn.build.code_debug=2 +lopy.menu.DebugLevel.info=Info +lopy.menu.DebugLevel.info.build.code_debug=3 +lopy.menu.DebugLevel.debug=Debug +lopy.menu.DebugLevel.debug.build.code_debug=4 +lopy.menu.DebugLevel.verbose=Verbose +lopy.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +lopy4.name=LoPy4 + +lopy4.upload.tool=esptool_py +lopy4.upload.maximum_size=1310720 +lopy4.upload.maximum_data_size=327680 +lopy4.upload.wait_for_upload_port=true + +lopy4.serial.disableDTR=true +lopy4.serial.disableRTS=true + +lopy4.build.mcu=esp32 +lopy4.build.core=esp32 +lopy4.build.variant=lopy4 +lopy4.build.board=LoPy4 + +lopy4.build.f_cpu=240000000L +lopy4.build.flash_mode=dio +lopy4.build.flash_size=4MB +lopy4.build.boot=dio +lopy4.build.partitions=default + +lopy4.menu.PSRAM.disabled=Disabled +lopy4.menu.PSRAM.disabled.build.defines= +lopy4.menu.PSRAM.enabled=Enabled +lopy4.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +lopy4.menu.FlashFreq.80=80MHz +lopy4.menu.FlashFreq.80.build.flash_freq=80m +lopy4.menu.FlashFreq.40=40MHz +lopy4.menu.FlashFreq.40.build.flash_freq=40m + +lopy4.menu.UploadSpeed.921600=921600 +lopy4.menu.UploadSpeed.921600.upload.speed=921600 +lopy4.menu.UploadSpeed.115200=115200 +lopy4.menu.UploadSpeed.115200.upload.speed=115200 +lopy4.menu.UploadSpeed.256000.windows=256000 +lopy4.menu.UploadSpeed.256000.upload.speed=256000 +lopy4.menu.UploadSpeed.230400.windows.upload.speed=256000 +lopy4.menu.UploadSpeed.230400=230400 +lopy4.menu.UploadSpeed.230400.upload.speed=230400 +lopy4.menu.UploadSpeed.460800.linux=460800 +lopy4.menu.UploadSpeed.460800.macosx=460800 +lopy4.menu.UploadSpeed.460800.upload.speed=460800 +lopy4.menu.UploadSpeed.512000.windows=512000 +lopy4.menu.UploadSpeed.512000.upload.speed=512000 + +lopy4.menu.DebugLevel.none=None +lopy4.menu.DebugLevel.none.build.code_debug=0 +lopy4.menu.DebugLevel.error=Error +lopy4.menu.DebugLevel.error.build.code_debug=1 +lopy4.menu.DebugLevel.warn=Warn +lopy4.menu.DebugLevel.warn.build.code_debug=2 +lopy4.menu.DebugLevel.info=Info +lopy4.menu.DebugLevel.info.build.code_debug=3 +lopy4.menu.DebugLevel.debug=Debug +lopy4.menu.DebugLevel.debug.build.code_debug=4 +lopy4.menu.DebugLevel.verbose=Verbose +lopy4.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +oroca_edubot.name=OROCA EduBot + +oroca_edubot.upload.tool=esptool_py +oroca_edubot.upload.maximum_size=3145728 +oroca_edubot.upload.maximum_data_size=327680 +oroca_edubot.upload.wait_for_upload_port=true + +oroca_edubot.serial.disableDTR=true +oroca_edubot.serial.disableRTS=true + +oroca_edubot.build.mcu=esp32 +oroca_edubot.build.core=esp32 +oroca_edubot.build.variant=oroca_edubot +oroca_edubot.build.board=OROCA_EDUBOT + +oroca_edubot.build.f_cpu=240000000L +oroca_edubot.build.flash_mode=dio +oroca_edubot.build.flash_size=4MB +oroca_edubot.build.boot=dio +oroca_edubot.build.partitions=huge_app +oroca_edubot.build.defines= + +oroca_edubot.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA) +oroca_edubot.menu.PartitionScheme.huge_app.build.partitions=huge_app +oroca_edubot.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +oroca_edubot.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +oroca_edubot.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +oroca_edubot.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +oroca_edubot.menu.FlashFreq.80=80MHz +oroca_edubot.menu.FlashFreq.80.build.flash_freq=80m +oroca_edubot.menu.FlashFreq.40=40MHz +oroca_edubot.menu.FlashFreq.40.build.flash_freq=40m + +oroca_edubot.menu.UploadSpeed.921600=921600 +oroca_edubot.menu.UploadSpeed.921600.upload.speed=921600 +oroca_edubot.menu.UploadSpeed.115200=115200 +oroca_edubot.menu.UploadSpeed.115200.upload.speed=115200 +oroca_edubot.menu.UploadSpeed.256000.windows=256000 +oroca_edubot.menu.UploadSpeed.256000.upload.speed=256000 +oroca_edubot.menu.UploadSpeed.230400.windows.upload.speed=256000 +oroca_edubot.menu.UploadSpeed.230400=230400 +oroca_edubot.menu.UploadSpeed.230400.upload.speed=230400 +oroca_edubot.menu.UploadSpeed.460800.linux=460800 +oroca_edubot.menu.UploadSpeed.460800.macosx=460800 +oroca_edubot.menu.UploadSpeed.460800.upload.speed=460800 +oroca_edubot.menu.UploadSpeed.512000.windows=512000 +oroca_edubot.menu.UploadSpeed.512000.upload.speed=512000 + +oroca_edubot.menu.DebugLevel.none=None +oroca_edubot.menu.DebugLevel.none.build.code_debug=0 +oroca_edubot.menu.DebugLevel.error=Error +oroca_edubot.menu.DebugLevel.error.build.code_debug=1 +oroca_edubot.menu.DebugLevel.warn=Warn +oroca_edubot.menu.DebugLevel.warn.build.code_debug=2 +oroca_edubot.menu.DebugLevel.info=Info +oroca_edubot.menu.DebugLevel.info.build.code_debug=3 +oroca_edubot.menu.DebugLevel.debug=Debug +oroca_edubot.menu.DebugLevel.debug.build.code_debug=4 +oroca_edubot.menu.DebugLevel.verbose=Verbose +oroca_edubot.menu.DebugLevel.verbose.build.code_debug=5 + + + +############################################################## + +fm-devkit.name=ESP32 FM DevKit + +fm-devkit.upload.tool=esptool +fm-devkit.upload.maximum_size=1310720 +fm-devkit.upload.maximum_data_size=327680 +fm-devkit.upload.wait_for_upload_port=true + +fm-devkit.serial.disableDTR=true +fm-devkit.serial.disableRTS=true + +fm-devkit.build.mcu=esp32 +fm-devkit.build.core=esp32 +fm-devkit.build.variant=fm-devkit +fm-devkit.build.board=fm-devkit + +fm-devkit.build.f_cpu=240000000L +fm-devkit.build.flash_size=4MB +fm-devkit.build.flash_freq=80m +fm-devkit.build.flash_mode=dio +fm-devkit.build.boot=dio +fm-devkit.build.partitions=default +fm-devkit.build.defines= + +fm-devkit.menu.UploadSpeed.921600=921600 +fm-devkit.menu.UploadSpeed.921600.upload.speed=921600 +fm-devkit.menu.UploadSpeed.115200=115200 +fm-devkit.menu.UploadSpeed.115200.upload.speed=115200 +fm-devkit.menu.UploadSpeed.256000.windows=256000 +fm-devkit.menu.UploadSpeed.256000.upload.speed=256000 +fm-devkit.menu.UploadSpeed.230400.windows.upload.speed=256000 +fm-devkit.menu.UploadSpeed.230400=230400 +fm-devkit.menu.UploadSpeed.230400.upload.speed=230400 +fm-devkit.menu.UploadSpeed.460800.linux=460800 +fm-devkit.menu.UploadSpeed.460800.macosx=460800 +fm-devkit.menu.UploadSpeed.460800.upload.speed=460800 +fm-devkit.menu.UploadSpeed.512000.windows=512000 +fm-devkit.menu.UploadSpeed.512000.upload.speed=512000 + +fm-devkit.menu.DebugLevel.none=None +fm-devkit.menu.DebugLevel.none.build.code_debug=0 +fm-devkit.menu.DebugLevel.error=Error +fm-devkit.menu.DebugLevel.error.build.code_debug=1 +fm-devkit.menu.DebugLevel.warn=Warn +fm-devkit.menu.DebugLevel.warn.build.code_debug=2 +fm-devkit.menu.DebugLevel.info=Info +fm-devkit.menu.DebugLevel.info.build.code_debug=3 +fm-devkit.menu.DebugLevel.debug=Debug +fm-devkit.menu.DebugLevel.debug.build.code_debug=4 +fm-devkit.menu.DebugLevel.verbose=Verbose +fm-devkit.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +frogboard.name=Frog Board ESP32 + +frogboard.upload.tool=esptool_py +frogboard.upload.maximum_size=1310720 +frogboard.upload.maximum_data_size=327680 +frogboard.upload.wait_for_upload_port=true + +frogboard.serial.disableDTR=true +frogboard.serial.disableRTS=true + +frogboard.build.mcu=esp32 +frogboard.build.core=esp32 +frogboard.build.variant=frog32 +frogboard.build.board=FROG_ESP32 +frogboard.build.f_cpu=240000000L +frogboard.build.flash_size=4MB +frogboard.build.flash_freq=40m +frogboard.build.flash_mode=dio +frogboard.build.boot=dio +frogboard.build.partitions=default +frogboard.build.defines= + +frogboard.menu.PSRAM.disabled=Disabled +frogboard.menu.PSRAM.disabled.build.defines= +frogboard.menu.PSRAM.enabled=Enabled +frogboard.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue + +frogboard.menu.PartitionScheme.default=Default +frogboard.menu.PartitionScheme.default.build.partitions=default +frogboard.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +frogboard.menu.PartitionScheme.minimal.build.partitions=minimal +frogboard.menu.PartitionScheme.no_ota=No OTA (Large APP) +frogboard.menu.PartitionScheme.no_ota.build.partitions=no_ota +frogboard.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +frogboard.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +frogboard.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +frogboard.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +frogboard.menu.FlashMode.qio=QIO +frogboard.menu.FlashMode.qio.build.flash_mode=dio +frogboard.menu.FlashMode.qio.build.boot=qio +frogboard.menu.FlashMode.dio=DIO +frogboard.menu.FlashMode.dio.build.flash_mode=dio +frogboard.menu.FlashMode.dio.build.boot=dio +frogboard.menu.FlashMode.qout=QOUT +frogboard.menu.FlashMode.qout.build.flash_mode=dout +frogboard.menu.FlashMode.qout.build.boot=qout +frogboard.menu.FlashMode.dout=DOUT +frogboard.menu.FlashMode.dout.build.flash_mode=dout +frogboard.menu.FlashMode.dout.build.boot=dout +frogboard.menu.FlashFreq.80=80MHz +frogboard.menu.FlashFreq.80.build.flash_freq=80m +frogboard.menu.FlashFreq.40=40MHz +frogboard.menu.FlashFreq.40.build.flash_freq=40m +frogboard.menu.FlashSize.4M=4MB (32Mb) +frogboard.menu.FlashSize.4M.build.flash_size=4MB +frogboard.menu.FlashSize.2M=2MB (16Mb) +frogboard.menu.FlashSize.2M.build.flash_size=2MB +frogboard.menu.FlashSize.2M.build.partitions=minimal + +frogboard.menu.UploadSpeed.921600=921600 +frogboard.menu.UploadSpeed.921600.upload.speed=921600 +frogboard.menu.UploadSpeed.115200=115200 +frogboard.menu.UploadSpeed.115200.upload.speed=115200 +frogboard.menu.UploadSpeed.256000.windows=256000 +frogboard.menu.UploadSpeed.256000.upload.speed=256000 +frogboard.menu.UploadSpeed.230400.windows.upload.speed=256000 +frogboard.menu.UploadSpeed.230400=230400 +frogboard.menu.UploadSpeed.230400.upload.speed=230400 +frogboard.menu.UploadSpeed.460800.linux=460800 +frogboard.menu.UploadSpeed.460800.macosx=460800 +frogboard.menu.UploadSpeed.460800.upload.speed=460800 +frogboard.menu.UploadSpeed.512000.windows=512000 +frogboard.menu.UploadSpeed.512000.upload.speed=512000 + +frogboard.menu.DebugLevel.none=None +frogboard.menu.DebugLevel.none.build.code_debug=0 +frogboard.menu.DebugLevel.error=Error +frogboard.menu.DebugLevel.error.build.code_debug=1 +frogboard.menu.DebugLevel.warn=Warn +frogboard.menu.DebugLevel.warn.build.code_debug=2 +frogboard.menu.DebugLevel.info=Info +frogboard.menu.DebugLevel.info.build.code_debug=3 +frogboard.menu.DebugLevel.debug=Debug +frogboard.menu.DebugLevel.debug.build.code_debug=4 +frogboard.menu.DebugLevel.verbose=Verbose +frogboard.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +esp32cam.name=AI Thinker ESP32-CAM + +esp32cam.upload.tool=esptool_py +esp32cam.upload.maximum_size=3145728 +esp32cam.upload.maximum_data_size=327680 +esp32cam.upload.wait_for_upload_port=true +esp32cam.upload.speed=460800 + +esp32cam.serial.disableDTR=true +esp32cam.serial.disableRTS=true + +esp32cam.build.mcu=esp32 +esp32cam.build.core=esp32 +esp32cam.build.variant=esp32 +esp32cam.build.board=ESP32_DEV +esp32cam.build.f_cpu=240000000L +esp32cam.build.flash_size=4MB +esp32cam.build.flash_freq=80m +esp32cam.build.flash_mode=dio +esp32cam.build.boot=qio +esp32cam.build.partitions=huge_app +esp32cam.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue +esp32cam.build.code_debug=0 + +############################################################## + +sparkfun_lora_gateway_1-channel.name=SparkFun LoRa Gateway 1-Channel + +sparkfun_lora_gateway_1-channel.upload.tool=esptool_py +sparkfun_lora_gateway_1-channel.upload.maximum_size=1310720 +sparkfun_lora_gateway_1-channel.upload.maximum_data_size=294912 +sparkfun_lora_gateway_1-channel.upload.wait_for_upload_port=true + +sparkfun_lora_gateway_1-channel.serial.disableDTR=true +sparkfun_lora_gateway_1-channel.serial.disableRTS=true + +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 +sparkfun_lora_gateway_1-channel.build.board=ESP32_DEV + +sparkfun_lora_gateway_1-channel.build.f_cpu=240000000L +sparkfun_lora_gateway_1-channel.build.flash_size=4MB +sparkfun_lora_gateway_1-channel.build.flash_freq=40m +sparkfun_lora_gateway_1-channel.build.flash_mode=dio +sparkfun_lora_gateway_1-channel.build.boot=dio +sparkfun_lora_gateway_1-channel.build.partitions=default + +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.default=Default +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.default.build.partitions=default +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.minimal=Minimal (2MB FLASH) +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.minimal.build.partitions=minimal +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.no_ota=No OTA (Large APP) +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.no_ota.build.partitions=no_ota +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +sparkfun_lora_gateway_1-channel.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +sparkfun_lora_gateway_1-channel.menu.FlashMode.qio=QIO +sparkfun_lora_gateway_1-channel.menu.FlashMode.qio.build.flash_mode=dio +sparkfun_lora_gateway_1-channel.menu.FlashMode.qio.build.boot=qio +sparkfun_lora_gateway_1-channel.menu.FlashMode.dio=DIO +sparkfun_lora_gateway_1-channel.menu.FlashMode.dio.build.flash_mode=dio +sparkfun_lora_gateway_1-channel.menu.FlashMode.dio.build.boot=dio +sparkfun_lora_gateway_1-channel.menu.FlashMode.qout=QOUT +sparkfun_lora_gateway_1-channel.menu.FlashMode.qout.build.flash_mode=dout +sparkfun_lora_gateway_1-channel.menu.FlashMode.qout.build.boot=qout +sparkfun_lora_gateway_1-channel.menu.FlashMode.dout=DOUT +sparkfun_lora_gateway_1-channel.menu.FlashMode.dout.build.flash_mode=dout +sparkfun_lora_gateway_1-channel.menu.FlashMode.dout.build.boot=dout + +sparkfun_lora_gateway_1-channel.menu.FlashFreq.80=80MHz +sparkfun_lora_gateway_1-channel.menu.FlashFreq.80.build.flash_freq=80m +sparkfun_lora_gateway_1-channel.menu.FlashFreq.40=40MHz +sparkfun_lora_gateway_1-channel.menu.FlashFreq.40.build.flash_freq=40m + +sparkfun_lora_gateway_1-channel.menu.FlashSize.4M=4MB (32Mb) +sparkfun_lora_gateway_1-channel.menu.FlashSize.4M.build.flash_size=4MB + +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.921600=921600 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.921600.upload.speed=921600 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.115200=115200 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.115200.upload.speed=115200 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.256000.windows=256000 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.256000.upload.speed=256000 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.230400.windows.upload.speed=256000 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.230400=230400 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.230400.upload.speed=230400 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.460800.linux=460800 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.460800.macosx=460800 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.460800.upload.speed=460800 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.512000.windows=512000 +sparkfun_lora_gateway_1-channel.menu.UploadSpeed.512000.upload.speed=512000 + +############################################################## + +ttgo-t-watch.name=TTGO T-Watch + +ttgo-t-watch.upload.tool=esptool_py +ttgo-t-watch.upload.maximum_size=6553600 +ttgo-t-watch.upload.maximum_data_size=4521984 +ttgo-t-watch.upload.wait_for_upload_port=true + +ttgo-t-watch.serial.disableDTR=true +ttgo-t-watch.serial.disableRTS=true + +ttgo-t-watch.build.mcu=esp32 +ttgo-t-watch.build.core=esp32 +ttgo-t-watch.build.variant=twatch +ttgo-t-watch.build.board=T-Watch + +ttgo-t-watch.build.f_cpu=240000000L +ttgo-t-watch.build.flash_size=16MB +ttgo-t-watch.build.flash_freq=80m +ttgo-t-watch.build.flash_mode=dio +ttgo-t-watch.build.boot=dio +ttgo-t-watch.build.partitions=default_16MB +ttgo-t-watch.build.defines= + +ttgo-t-watch.menu.PSRAM.enabled=Enabled +ttgo-t-watch.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue +ttgo-t-watch.menu.PSRAM.disabled=Disabled +ttgo-t-watch.menu.PSRAM.disabled.build.defines= + +ttgo-t-watch.menu.PartitionScheme.default=Default (2 x 6.5 MB app, 3.6 MB SPIFFS) +ttgo-t-watch.menu.PartitionScheme.default.build.partitions=default_16MB +ttgo-t-watch.menu.PartitionScheme.default.upload.maximum_size=6553600 +ttgo-t-watch.menu.PartitionScheme.large_spiffs=Large SPIFFS (7 MB) +ttgo-t-watch.menu.PartitionScheme.large_spiffs.build.partitions=large_spiffs_16MB +ttgo-t-watch.menu.PartitionScheme.large_spiffs.upload.maximum_size=4685824 + +ttgo-t-watch.menu.UploadSpeed.2000000=2000000 +ttgo-t-watch.menu.UploadSpeed.2000000.upload.speed=2000000 +ttgo-t-watch.menu.UploadSpeed.1152000=1152000 +ttgo-t-watch.menu.UploadSpeed.1152000.upload.speed=1152000 +ttgo-t-watch.menu.UploadSpeed.921600=921600 +ttgo-t-watch.menu.UploadSpeed.921600.upload.speed=921600 +ttgo-t-watch.menu.UploadSpeed.115200=115200 +ttgo-t-watch.menu.UploadSpeed.115200.upload.speed=115200 +ttgo-t-watch.menu.UploadSpeed.256000.windows=256000 +ttgo-t-watch.menu.UploadSpeed.256000.upload.speed=256000 +ttgo-t-watch.menu.UploadSpeed.230400.windows.upload.speed=256000 +ttgo-t-watch.menu.UploadSpeed.230400=230400 +ttgo-t-watch.menu.UploadSpeed.230400.upload.speed=230400 +ttgo-t-watch.menu.UploadSpeed.460800.linux=460800 +ttgo-t-watch.menu.UploadSpeed.460800.macosx=460800 +ttgo-t-watch.menu.UploadSpeed.460800.upload.speed=460800 +ttgo-t-watch.menu.UploadSpeed.512000.windows=512000 +ttgo-t-watch.menu.UploadSpeed.512000.upload.speed=512000 + +ttgo-t-watch.menu.DebugLevel.none=None +ttgo-t-watch.menu.DebugLevel.none.build.code_debug=0 +ttgo-t-watch.menu.DebugLevel.error=Error +ttgo-t-watch.menu.DebugLevel.error.build.code_debug=1 +ttgo-t-watch.menu.DebugLevel.warn=Warn +ttgo-t-watch.menu.DebugLevel.warn.build.code_debug=2 +ttgo-t-watch.menu.DebugLevel.info=Info +ttgo-t-watch.menu.DebugLevel.info.build.code_debug=3 +ttgo-t-watch.menu.DebugLevel.debug=Debug +ttgo-t-watch.menu.DebugLevel.debug.build.code_debug=4 +ttgo-t-watch.menu.DebugLevel.verbose=Verbose +ttgo-t-watch.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +d1_mini32.name=WEMOS D1 MINI ESP32 + +d1_mini32.upload.tool=esptool_py +d1_mini32.upload.maximum_size=1310720 +d1_mini32.upload.maximum_data_size=327680 +d1_mini32.upload.wait_for_upload_port=true + +d1_mini32.serial.disableDTR=true +d1_mini32.serial.disableRTS=true + +d1_mini32.build.mcu=esp32 +d1_mini32.build.core=esp32 +d1_mini32.build.variant=d1_mini32 +d1_mini32.build.board=D1_MINI32 + +d1_mini32.build.f_cpu=240000000L +d1_mini32.build.flash_mode=dio +d1_mini32.build.flash_size=4MB +d1_mini32.build.boot=dio +d1_mini32.build.partitions=default +d1_mini32.build.defines= + +d1_mini32.menu.FlashFreq.80=80MHz +d1_mini32.menu.FlashFreq.80.build.flash_freq=80m +d1_mini32.menu.FlashFreq.40=40MHz +d1_mini32.menu.FlashFreq.40.build.flash_freq=40m + +d1_mini32.menu.PartitionScheme.default=Default +d1_mini32.menu.PartitionScheme.default.build.partitions=default +d1_mini32.menu.PartitionScheme.no_ota=No OTA (Large APP) +d1_mini32.menu.PartitionScheme.no_ota.build.partitions=no_ota +d1_mini32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +d1_mini32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA) +d1_mini32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +d1_mini32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 + +d1_mini32.menu.CPUFreq.240=240MHz (WiFi/BT) +d1_mini32.menu.CPUFreq.240.build.f_cpu=240000000L +d1_mini32.menu.CPUFreq.160=160MHz (WiFi/BT) +d1_mini32.menu.CPUFreq.160.build.f_cpu=160000000L +d1_mini32.menu.CPUFreq.80=80MHz (WiFi/BT) +d1_mini32.menu.CPUFreq.80.build.f_cpu=80000000L +d1_mini32.menu.CPUFreq.40=40MHz (40MHz XTAL) +d1_mini32.menu.CPUFreq.40.build.f_cpu=40000000L +d1_mini32.menu.CPUFreq.26=26MHz (26MHz XTAL) +d1_mini32.menu.CPUFreq.26.build.f_cpu=26000000L +d1_mini32.menu.CPUFreq.20=20MHz (40MHz XTAL) +d1_mini32.menu.CPUFreq.20.build.f_cpu=20000000L +d1_mini32.menu.CPUFreq.13=13MHz (26MHz XTAL) +d1_mini32.menu.CPUFreq.13.build.f_cpu=13000000L +d1_mini32.menu.CPUFreq.10=10MHz (40MHz XTAL) +d1_mini32.menu.CPUFreq.10.build.f_cpu=10000000L + +d1_mini32.menu.UploadSpeed.921600=921600 +d1_mini32.menu.UploadSpeed.921600.upload.speed=921600 +d1_mini32.menu.UploadSpeed.115200=115200 +d1_mini32.menu.UploadSpeed.115200.upload.speed=115200 +d1_mini32.menu.UploadSpeed.256000.windows=256000 +d1_mini32.menu.UploadSpeed.256000.upload.speed=256000 +d1_mini32.menu.UploadSpeed.230400.windows.upload.speed=256000 +d1_mini32.menu.UploadSpeed.230400=230400 +d1_mini32.menu.UploadSpeed.230400.upload.speed=230400 +d1_mini32.menu.UploadSpeed.460800.linux=460800 +d1_mini32.menu.UploadSpeed.460800.macosx=460800 +d1_mini32.menu.UploadSpeed.460800.upload.speed=460800 +d1_mini32.menu.UploadSpeed.512000.windows=512000 +d1_mini32.menu.UploadSpeed.512000.upload.speed=512000 + +############################################################## + +gpy.name=Pycom GPy + +gpy.upload.tool=esptool_py +gpy.upload.maximum_size=1310720 +gpy.upload.maximum_data_size=327680 +gpy.upload.wait_for_upload_port=true + +gpy.serial.disableDTR=true +gpy.serial.disableRTS=true + +gpy.build.mcu=esp32 +gpy.build.core=esp32 +gpy.build.variant=gpy +gpy.build.board=PYCOM_GPY + +gpy.build.f_cpu=240000000L +gpy.build.flash_mode=dio +gpy.build.flash_size=8MB +gpy.build.boot=dio +gpy.build.partitions=default + +gpy.menu.FlashFreq.80=80MHz +gpy.menu.FlashFreq.80.build.flash_freq=80m +gpy.menu.FlashFreq.40=40MHz +gpy.menu.FlashFreq.40.build.flash_freq=40m + +gpy.menu.UploadSpeed.921600=921600 +gpy.menu.UploadSpeed.921600.upload.speed=921600 +gpy.menu.UploadSpeed.115200=115200 +gpy.menu.UploadSpeed.115200.upload.speed=115200 +gpy.menu.UploadSpeed.256000.windows=256000 +gpy.menu.UploadSpeed.256000.upload.speed=256000 +gpy.menu.UploadSpeed.230400.windows.upload.speed=256000 +gpy.menu.UploadSpeed.230400=230400 +gpy.menu.UploadSpeed.230400.upload.speed=230400 +gpy.menu.UploadSpeed.460800.linux=460800 +gpy.menu.UploadSpeed.460800.macosx=460800 +gpy.menu.UploadSpeed.460800.upload.speed=460800 +gpy.menu.UploadSpeed.512000.windows=512000 +gpy.menu.UploadSpeed.512000.upload.speed=512000 + +gpy.menu.DebugLevel.none=None +gpy.menu.DebugLevel.none.build.code_debug=0 +gpy.menu.DebugLevel.error=Error +gpy.menu.DebugLevel.error.build.code_debug=1 +gpy.menu.DebugLevel.warn=Warn +gpy.menu.DebugLevel.warn.build.code_debug=2 +gpy.menu.DebugLevel.info=Info +gpy.menu.DebugLevel.info.build.code_debug=3 +gpy.menu.DebugLevel.debug=Debug +gpy.menu.DebugLevel.debug.build.code_debug=4 +gpy.menu.DebugLevel.verbose=Verbose +gpy.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + +vintlabs-devkit-v1.name=VintLabs ESP32 Devkit + +vintlabs-devkit-v1.upload.tool=esptool_py +vintlabs-devkit-v1.upload.maximum_size=1310720 +vintlabs-devkit-v1.upload.maximum_data_size=327680 +vintlabs-devkit-v1.upload.wait_for_upload_port=true + +vintlabs-devkit-v1.serial.disableDTR=true +vintlabs-devkit-v1.serial.disableRTS=true + +vintlabs-devkit-v1.build.mcu=esp32 +vintlabs-devkit-v1.build.core=esp32 +vintlabs-devkit-v1.build.variant=vintlabsdevkitv1 +vintlabs-devkit-v1.build.board=ESP32_DEV + +vintlabs-devkit-v1.build.f_cpu=240000000L +vintlabs-devkit-v1.build.flash_mode=dio +vintlabs-devkit-v1.build.flash_size=4MB +vintlabs-devkit-v1.build.boot=dio +vintlabs-devkit-v1.build.partitions=default +vintlabs-devkit-v1.build.defines= + +vintlabs-devkit-v1.menu.FlashFreq.80=80MHz +vintlabs-devkit-v1.menu.FlashFreq.80.build.flash_freq=80m +vintlabs-devkit-v1.menu.FlashFreq.40=40MHz +vintlabs-devkit-v1.menu.FlashFreq.40.build.flash_freq=40m + +vintlabs-devkit-v1.menu.UploadSpeed.2000000=2000000 +vintlabs-devkit-v1.menu.UploadSpeed.2000000.upload.speed=2000000 +vintlabs-devkit-v1.menu.UploadSpeed.921600=921600 +vintlabs-devkit-v1.menu.UploadSpeed.921600.upload.speed=921600 +vintlabs-devkit-v1.menu.UploadSpeed.115200=115200 +vintlabs-devkit-v1.menu.UploadSpeed.115200.upload.speed=115200 +vintlabs-devkit-v1.menu.UploadSpeed.256000.windows=256000 +vintlabs-devkit-v1.menu.UploadSpeed.256000.upload.speed=256000 +vintlabs-devkit-v1.menu.UploadSpeed.230400.windows.upload.speed=256000 +vintlabs-devkit-v1.menu.UploadSpeed.230400=230400 +vintlabs-devkit-v1.menu.UploadSpeed.230400.upload.speed=230400 +vintlabs-devkit-v1.menu.UploadSpeed.460800.linux=460800 +vintlabs-devkit-v1.menu.UploadSpeed.460800.macosx=460800 +vintlabs-devkit-v1.menu.UploadSpeed.460800.upload.speed=460800 +vintlabs-devkit-v1.menu.UploadSpeed.512000.windows=512000 +vintlabs-devkit-v1.menu.UploadSpeed.512000.upload.speed=512000 + +vintlabs-devkit-v1.menu.DebugLevel.none=None +vintlabs-devkit-v1.menu.DebugLevel.none.build.code_debug=0 +vintlabs-devkit-v1.menu.DebugLevel.error=Error +vintlabs-devkit-v1.menu.DebugLevel.error.build.code_debug=1 +vintlabs-devkit-v1.menu.DebugLevel.warn=Warn +vintlabs-devkit-v1.menu.DebugLevel.warn.build.code_debug=2 +vintlabs-devkit-v1.menu.DebugLevel.info=Info +vintlabs-devkit-v1.menu.DebugLevel.info.build.code_debug=3 +vintlabs-devkit-v1.menu.DebugLevel.debug=Debug +vintlabs-devkit-v1.menu.DebugLevel.debug.build.code_debug=4 + +############################################################## + diff --git a/component.mk b/component.mk index 15d50c00626..4b85ee4f217 100644 --- a/component.mk +++ b/component.mk @@ -1,6 +1,36 @@ -ARDUINO_CORE_LIBS := $(patsubst $(COMPONENT_PATH)/%,%,$(sort $(dir $(wildcard $(COMPONENT_PATH)/libraries/*/*/)))) +ARDUINO_ALL_LIBRARIES := $(patsubst $(COMPONENT_PATH)/libraries/%,%,$(wildcard $(COMPONENT_PATH)/libraries/*)) -COMPONENT_ADD_INCLUDEDIRS := cores/esp32 variants/esp32 $(ARDUINO_CORE_LIBS) +# Macro returns non-empty if Arduino library $(1) should be included in the build +# (either because selective compilation is of, or this library is enabled +define ARDUINO_LIBRARY_ENABLED +$(if $(CONFIG_ARDUINO_SELECTIVE_COMPILATION),$(CONFIG_ARDUINO_SELECTIVE_$(1)),y) +endef + +ARDUINO_ENABLED_LIBRARIES := $(foreach LIBRARY,$(sort $(ARDUINO_ALL_LIBRARIES)),$(if $(call ARDUINO_LIBRARY_ENABLED,$(LIBRARY)),$(LIBRARY))) + +$(info Arduino libraries in build: $(ARDUINO_ENABLED_LIBRARIES)) + +# Expand all subdirs under $(1) +define EXPAND_SUBDIRS +$(sort $(dir $(wildcard $(1)/* $(1)/*/* $(1)/*/*/* $(1)/*/*/*/* $(1)/*/*/*/*/*))) +endef + +# Macro returns SRCDIRS for library +define ARDUINO_LIBRARY_GET_SRCDIRS + $(if $(wildcard $(COMPONENT_PATH)/libraries/$(1)/src/.), \ + $(call EXPAND_SUBDIRS,$(COMPONENT_PATH)/libraries/$(1)/src), \ + $(filter-out $(call EXPAND_SUBDIRS,$(COMPONENT_PATH)/libraries/$(1)/examples), \ + $(call EXPAND_SUBDIRS,$(COMPONENT_PATH)/libraries/$(1)) \ + ) \ + ) +endef + +# Make a list of all srcdirs in enabled libraries +ARDUINO_LIBRARY_SRCDIRS := $(patsubst $(COMPONENT_PATH)/%,%,$(foreach LIBRARY,$(ARDUINO_ENABLED_LIBRARIES),$(call ARDUINO_LIBRARY_GET_SRCDIRS,$(LIBRARY)))) + +#$(info Arduino libraries src dirs: $(ARDUINO_LIBRARY_SRCDIRS)) + +COMPONENT_ADD_INCLUDEDIRS := cores/esp32 variants/esp32 $(ARDUINO_LIBRARY_SRCDIRS) COMPONENT_PRIV_INCLUDEDIRS := cores/esp32/libb64 -COMPONENT_SRCDIRS := cores/esp32/libb64 cores/esp32 variants/esp32 $(ARDUINO_CORE_LIBS) +COMPONENT_SRCDIRS := cores/esp32/libb64 cores/esp32 variants/esp32 $(ARDUINO_LIBRARY_SRCDIRS) CXXFLAGS += -fno-rtti diff --git a/cores/esp32/Arduino.h b/cores/esp32/Arduino.h index d60d3fe0828..645b407034f 100644 --- a/cores/esp32/Arduino.h +++ b/cores/esp32/Arduino.h @@ -68,14 +68,7 @@ #define __STRINGIFY(a) #a #endif -// undefine stdlib's abs if encountered -#ifdef abs -#undef abs -#endif - -#define abs(x) ((x)>0?(x):-(x)) #define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt))) -#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5)) #define radians(deg) ((deg)*DEG_TO_RAD) #define degrees(rad) ((rad)*RAD_TO_DEG) #define sq(x) ((x)*(x)) @@ -146,6 +139,9 @@ void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val); #ifdef __cplusplus } +#include +#include + #include "WCharacter.h" #include "WString.h" #include "Stream.h" @@ -158,6 +154,13 @@ void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val); #include "HardwareSerial.h" #include "Esp.h" +using std::abs; +using std::isinf; +using std::isnan; +using std::max; +using std::min; +using ::round; + uint16_t makeWord(uint16_t w); uint16_t makeWord(byte h, byte l); @@ -176,12 +179,6 @@ extern "C" void configTzTime(const char* tz, long random(long); #endif /* __cplusplus */ -#ifndef _GLIBCXX_VECTOR -// arduino is not compatible with std::vector -#define min(a,b) ((a)<(b)?(a):(b)) -#define max(a,b) ((a)>(b)?(a):(b)) -#endif - #define _min(a,b) ((a)<(b)?(a):(b)) #define _max(a,b) ((a)>(b)?(a):(b)) diff --git a/cores/esp32/Esp.cpp b/cores/esp32/Esp.cpp index d9f1da0cda9..54451127ef3 100644 --- a/cores/esp32/Esp.cpp +++ b/cores/esp32/Esp.cpp @@ -25,20 +25,12 @@ #include #include #include - -/* Main header of binary image */ -typedef struct { - uint8_t magic; - uint8_t segment_count; - 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; - uint8_t encrypt_flag; /* encrypt flag */ - uint8_t extra_header[15]; /* ESP32 additional header, unused by second bootloader */ -} esp_image_header_t; - -#define ESP_IMAGE_HEADER_MAGIC 0xE9 +#include +extern "C" { +#include "esp_ota_ops.h" +#include "esp_image_format.h" +} +#include /** * User-defined Literals @@ -100,21 +92,123 @@ void EspClass::deepSleep(uint32_t time_us) esp_deep_sleep(time_us); } -uint32_t EspClass::getCycleCount() +void EspClass::restart(void) { - uint32_t ccount; - __asm__ __volatile__("esync; rsr %0,ccount":"=a" (ccount)); - return ccount; + esp_restart(); } -void EspClass::restart(void) +uint32_t EspClass::getHeapSize(void) { - esp_restart(); + multi_heap_info_t info; + heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); + return info.total_free_bytes + info.total_allocated_bytes; } uint32_t EspClass::getFreeHeap(void) { - return esp_get_free_heap_size(); + return heap_caps_get_free_size(MALLOC_CAP_INTERNAL); +} + +uint32_t EspClass::getMinFreeHeap(void) +{ + return heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL); +} + +uint32_t EspClass::getMaxAllocHeap(void) +{ + return heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL); +} + +uint32_t EspClass::getPsramSize(void) +{ + multi_heap_info_t info; + heap_caps_get_info(&info, MALLOC_CAP_SPIRAM); + return info.total_free_bytes + info.total_allocated_bytes; +} + +uint32_t EspClass::getFreePsram(void) +{ + return heap_caps_get_free_size(MALLOC_CAP_SPIRAM); +} + +uint32_t EspClass::getMinFreePsram(void) +{ + return heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM); +} + +uint32_t EspClass::getMaxAllocPsram(void) +{ + return heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM); +} + +static uint32_t sketchSize(sketchSize_t response) { + esp_image_metadata_t data; + const esp_partition_t *running = esp_ota_get_running_partition(); + if (!running) return 0; + const esp_partition_pos_t running_pos = { + .offset = running->address, + .size = running->size, + }; + data.start_addr = running_pos.offset; + esp_image_verify(ESP_IMAGE_VERIFY, &running_pos, &data); + if (response) { + return running_pos.size - data.image_len; + } else { + return data.image_len; + } +} + +uint32_t EspClass::getSketchSize () { + return sketchSize(SKETCH_SIZE_TOTAL); +} + +String EspClass::getSketchMD5() +{ + static String result; + if (result.length()) { + return result; + } + uint32_t lengthLeft = getSketchSize(); + + const esp_partition_t *running = esp_ota_get_running_partition(); + if (!running) { + log_e("Partition could not be found"); + + return String(); + } + const size_t bufSize = SPI_FLASH_SEC_SIZE; + std::unique_ptr buf(new uint8_t[bufSize]); + uint32_t offset = 0; + if(!buf.get()) { + log_e("Not enough memory to allocate buffer"); + + return String(); + } + MD5Builder md5; + md5.begin(); + while( lengthLeft > 0) { + size_t readBytes = (lengthLeft < bufSize) ? lengthLeft : bufSize; + if (!ESP.flashRead(running->address + offset, reinterpret_cast(buf.get()), (readBytes + 3) & ~3)) { + log_e("Could not read buffer from flash"); + + return String(); + } + md5.add(buf.get(), readBytes); + lengthLeft -= readBytes; + offset += readBytes; + } + md5.calculate(); + result = md5.toString(); + return result; +} + +uint32_t EspClass::getFreeSketchSpace () { + const esp_partition_t* _partition = esp_ota_get_next_update_partition(NULL); + if(!_partition){ + return 0; + } + + return _partition->size; } uint8_t EspClass::getChipRevision(void) diff --git a/cores/esp32/Esp.h b/cores/esp32/Esp.h index 80e995a6e16..2580eecf65b 100644 --- a/cores/esp32/Esp.h +++ b/cores/esp32/Esp.h @@ -50,16 +50,33 @@ typedef enum { FM_UNKNOWN = 0xff } FlashMode_t; +typedef enum { + SKETCH_SIZE_TOTAL = 0, + SKETCH_SIZE_FREE = 1 +} sketchSize_t; + class EspClass { public: EspClass() {} ~EspClass() {} void restart(); - uint32_t getFreeHeap(); + + //Internal RAM + uint32_t getHeapSize(); //total heap size + uint32_t getFreeHeap(); //available heap + uint32_t getMinFreeHeap(); //lowest level of free heap since boot + uint32_t getMaxAllocHeap(); //largest block of heap that can be allocated at once + + //SPI RAM + uint32_t getPsramSize(); + uint32_t getFreePsram(); + uint32_t getMinFreePsram(); + uint32_t getMaxAllocPsram(); + uint8_t getChipRevision(); - uint8_t getCpuFreqMHz(){ return CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ; } - uint32_t getCycleCount(); + uint32_t getCpuFreqMHz(){ return getCpuFrequencyMhz(); } + inline uint32_t getCycleCount() __attribute__((always_inline)); const char * getSdkVersion(); void deepSleep(uint32_t time_us); @@ -72,6 +89,10 @@ class EspClass uint32_t magicFlashChipSpeed(uint8_t byte); FlashMode_t magicFlashChipMode(uint8_t byte); + uint32_t getSketchSize(); + String getSketchMD5(); + uint32_t getFreeSketchSpace(); + bool flashEraseSector(uint32_t sector); bool flashWrite(uint32_t offset, uint32_t *data, size_t size); bool flashRead(uint32_t offset, uint32_t *data, size_t size); @@ -80,6 +101,13 @@ class EspClass }; +uint32_t IRAM_ATTR EspClass::getCycleCount() +{ + uint32_t ccount; + __asm__ __volatile__("esync; rsr %0,ccount":"=a" (ccount)); + return ccount; +} + extern EspClass ESP; #endif //ESP_H diff --git a/cores/esp32/FunctionalInterrupt.cpp b/cores/esp32/FunctionalInterrupt.cpp new file mode 100644 index 00000000000..d2e6dfd4236 --- /dev/null +++ b/cores/esp32/FunctionalInterrupt.cpp @@ -0,0 +1,44 @@ +/* + * FunctionalInterrupt.cpp + * + * Created on: 8 jul. 2018 + * Author: Herman + */ + +#include "FunctionalInterrupt.h" +#include "Arduino.h" + +typedef void (*voidFuncPtr)(void); +typedef void (*voidFuncPtrArg)(void*); + +extern "C" +{ + extern void __attachInterruptFunctionalArg(uint8_t pin, voidFuncPtrArg userFunc, void * arg, int intr_type, bool functional); +} + +void IRAM_ATTR interruptFunctional(void* arg) +{ + InterruptArgStructure* localArg = (InterruptArgStructure*)arg; + if (localArg->interruptFunction) + { + localArg->interruptFunction(); + } +} + +void attachInterrupt(uint8_t pin, std::function intRoutine, int mode) +{ + // use the local interrupt routine which takes the ArgStructure as argument + __attachInterruptFunctionalArg (pin, (voidFuncPtrArg)interruptFunctional, new InterruptArgStructure{intRoutine}, mode, true); +} + +extern "C" +{ + void cleanupFunctional(void* arg) + { + delete (InterruptArgStructure*)arg; + } +} + + + + diff --git a/cores/esp32/FunctionalInterrupt.h b/cores/esp32/FunctionalInterrupt.h new file mode 100644 index 00000000000..b5e3181f986 --- /dev/null +++ b/cores/esp32/FunctionalInterrupt.h @@ -0,0 +1,20 @@ +/* + * FunctionalInterrupt.h + * + * Created on: 8 jul. 2018 + * Author: Herman + */ + +#ifndef CORE_CORE_FUNCTIONALINTERRUPT_H_ +#define CORE_CORE_FUNCTIONALINTERRUPT_H_ + +#include + +struct InterruptArgStructure { + std::function interruptFunction; +}; + +void attachInterrupt(uint8_t pin, std::function intRoutine, int mode); + + +#endif /* CORE_CORE_FUNCTIONALINTERRUPT_H_ */ diff --git a/cores/esp32/HardwareSerial.cpp b/cores/esp32/HardwareSerial.cpp index c449b1640e7..860c2c0f604 100644 --- a/cores/esp32/HardwareSerial.cpp +++ b/cores/esp32/HardwareSerial.cpp @@ -1,110 +1,163 @@ -#include -#include -#include -#include - -#include "HardwareSerial.h" - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL) -HardwareSerial Serial(0); -#endif - -HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _uart(NULL) {} - -void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert) -{ - if(0 > _uart_nr || _uart_nr > 2) { - log_e("Serial number is invalid, please use 0, 1 or 2"); - return; - } - if(_uart) { - end(); - } - if(_uart_nr == 0 && rxPin < 0 && txPin < 0) { - rxPin = 3; - txPin = 1; - } - if(_uart_nr == 1 && rxPin < 0 && txPin < 0) { - rxPin = 9; - txPin = 10; - } - if(_uart_nr == 2 && rxPin < 0 && txPin < 0) { - rxPin = 16; - txPin = 17; - } - _uart = uartBegin(_uart_nr, baud, config, rxPin, txPin, 256, invert); -} - -void HardwareSerial::end() -{ - if(uartGetDebug() == _uart_nr) { - uartSetDebug(0); - } - uartEnd(_uart); - _uart = 0; -} - -void HardwareSerial::setDebugOutput(bool en) -{ - if(_uart == 0) { - return; - } - if(en) { - uartSetDebug(_uart); - } else { - if(uartGetDebug() == _uart_nr) { - uartSetDebug(0); - } - } -} - -int HardwareSerial::available(void) -{ - return uartAvailable(_uart); -} -int HardwareSerial::availableForWrite(void) -{ - return uartAvailableForWrite(_uart); -} - -int HardwareSerial::peek(void) -{ - if (available()) { - return uartPeek(_uart); - } - return -1; -} - -int HardwareSerial::read(void) -{ - if(available()) { - return uartRead(_uart); - } - return -1; -} - -void HardwareSerial::flush() -{ - uartFlush(_uart); -} - -size_t HardwareSerial::write(uint8_t c) -{ - uartWrite(_uart, c); - return 1; -} - -size_t HardwareSerial::write(const uint8_t *buffer, size_t size) -{ - uartWriteBuf(_uart, buffer, size); - return size; -} -uint32_t HardwareSerial::baudRate() - -{ - return uartGetBaudRate(_uart); -} -HardwareSerial::operator bool() const -{ - return true; -} +#include +#include +#include +#include + +#include "pins_arduino.h" +#include "HardwareSerial.h" + +#ifndef RX1 +#define RX1 9 +#endif + +#ifndef TX1 +#define TX1 10 +#endif + +#ifndef RX2 +#define RX2 16 +#endif + +#ifndef TX2 +#define TX2 17 +#endif + +#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL) +HardwareSerial Serial(0); +HardwareSerial Serial1(1); +HardwareSerial Serial2(2); +#endif + +HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _uart(NULL) {} + +void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert, unsigned long timeout_ms) +{ + if(0 > _uart_nr || _uart_nr > 2) { + log_e("Serial number is invalid, please use 0, 1 or 2"); + return; + } + if(_uart) { + end(); + } + if(_uart_nr == 0 && rxPin < 0 && txPin < 0) { + rxPin = 3; + txPin = 1; + } + if(_uart_nr == 1 && rxPin < 0 && txPin < 0) { + rxPin = RX1; + txPin = TX1; + } + if(_uart_nr == 2 && rxPin < 0 && txPin < 0) { + rxPin = RX2; + txPin = TX2; + } + + _uart = uartBegin(_uart_nr, baud ? baud : 9600, config, rxPin, txPin, 256, invert); + + if(!baud) { + uartStartDetectBaudrate(_uart); + time_t startMillis = millis(); + unsigned long detectedBaudRate = 0; + while(millis() - startMillis < timeout_ms && !(detectedBaudRate = uartDetectBaudrate(_uart))) { + yield(); + } + + end(); + + if(detectedBaudRate) { + delay(100); // Give some time... + _uart = uartBegin(_uart_nr, detectedBaudRate, config, rxPin, txPin, 256, invert); + } else { + log_e("Could not detect baudrate. Serial data at the port must be present within the timeout for detection to be possible"); + _uart = NULL; + } + } +} + +void HardwareSerial::updateBaudRate(unsigned long baud) +{ + uartSetBaudRate(_uart, baud); +} + +void HardwareSerial::end() +{ + if(uartGetDebug() == _uart_nr) { + uartSetDebug(0); + } + uartEnd(_uart); + _uart = 0; +} + +size_t HardwareSerial::setRxBufferSize(size_t new_size) { + return uartResizeRxBuffer(_uart, new_size); +} + +void HardwareSerial::setDebugOutput(bool en) +{ + if(_uart == 0) { + return; + } + if(en) { + uartSetDebug(_uart); + } else { + if(uartGetDebug() == _uart_nr) { + uartSetDebug(0); + } + } +} + +int HardwareSerial::available(void) +{ + return uartAvailable(_uart); +} +int HardwareSerial::availableForWrite(void) +{ + return uartAvailableForWrite(_uart); +} + +int HardwareSerial::peek(void) +{ + if (available()) { + return uartPeek(_uart); + } + return -1; +} + +int HardwareSerial::read(void) +{ + if(available()) { + return uartRead(_uart); + } + return -1; +} + +void HardwareSerial::flush(void) +{ + uartFlush(_uart); +} + +void HardwareSerial::flush(bool txOnly) +{ + uartFlushTxOnly(_uart, txOnly); +} + +size_t HardwareSerial::write(uint8_t c) +{ + uartWrite(_uart, c); + return 1; +} + +size_t HardwareSerial::write(const uint8_t *buffer, size_t size) +{ + uartWriteBuf(_uart, buffer, size); + return size; +} +uint32_t HardwareSerial::baudRate() + +{ + return uartGetBaudRate(_uart); +} +HardwareSerial::operator bool() const +{ + return true; +} diff --git a/cores/esp32/HardwareSerial.h b/cores/esp32/HardwareSerial.h index c0e00ec2e23..7d9f26d2fae 100644 --- a/cores/esp32/HardwareSerial.h +++ b/cores/esp32/HardwareSerial.h @@ -22,6 +22,24 @@ Modified 18 December 2014 by Ivan Grokhotkov (esp8266 platform support) Modified 31 March 2015 by Markus Sattler (rewrite the code for UART0 + UART1 support in ESP8266) Modified 25 April 2015 by Thomas Flayols (add configuration different from 8N1 in ESP8266) + Modified 13 October 2018 by Jeroen Döll (add baudrate detection) + Baudrate detection example usage (detection on Serial1): + void setup() { + Serial.begin(115200); + delay(100); + Serial.println(); + + Serial1.begin(0, SERIAL_8N1, -1, -1, true, 11000UL); // Passing 0 for baudrate to detect it, the last parameter is a timeout in ms + + unsigned long detectedBaudRate = Serial1.baudRate(); + if(detectedBaudRate) { + Serial.printf("Detected baudrate is %lu\n", detectedBaudRate); + } else { + Serial.println("No baudrate detected, Serial1 will not work!"); + } + } + + Pay attention: the baudrate returned by baudRate() may be rounded, eg 115200 returns 115201 */ #ifndef HardwareSerial_h @@ -37,13 +55,15 @@ class HardwareSerial: public Stream public: HardwareSerial(int uart_nr); - void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1, bool invert=false); + void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1, bool invert=false, unsigned long timeout_ms = 20000UL); void end(); + void updateBaudRate(unsigned long baud); int available(void); int availableForWrite(void); int peek(void); int read(void); void flush(void); + void flush( bool txOnly); size_t write(uint8_t); size_t write(const uint8_t *buffer, size_t size); @@ -70,6 +90,7 @@ class HardwareSerial: public Stream uint32_t baudRate(); operator bool() const; + size_t setRxBufferSize(size_t); void setDebugOutput(bool); protected: @@ -77,8 +98,12 @@ class HardwareSerial: public Stream uart_t* _uart; }; +extern void serialEventRun(void) __attribute__((weak)); + #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL) extern HardwareSerial Serial; +extern HardwareSerial Serial1; +extern HardwareSerial Serial2; #endif -#endif +#endif // HardwareSerial_h diff --git a/cores/esp32/Print.cpp b/cores/esp32/Print.cpp index a0c7a4a8441..60964703306 100644 --- a/cores/esp32/Print.cpp +++ b/cores/esp32/Print.cpp @@ -52,19 +52,24 @@ size_t Print::printf(const char *format, ...) va_list copy; va_start(arg, format); va_copy(copy, arg); - size_t len = vsnprintf(NULL, 0, format, arg); + int len = vsnprintf(temp, sizeof(loc_buf), format, copy); va_end(copy); + if(len < 0) { + va_end(arg); + return 0; + }; if(len >= sizeof(loc_buf)){ - temp = new char[len+1]; + temp = (char*) malloc(len+1); if(temp == NULL) { + va_end(arg); return 0; } + len = vsnprintf(temp, len+1, format, arg); } - len = vsnprintf(temp, len+1, format, arg); - write((uint8_t*)temp, len); va_end(arg); - if(len > 64){ - delete[] temp; + len = write((uint8_t*)temp, len); + if(temp != loc_buf){ + free(temp); } return len; } @@ -154,8 +159,10 @@ size_t Print::print(struct tm * timeinfo, const char * format) } char buf[64]; size_t written = strftime(buf, 64, f, timeinfo); - print(buf); - return written; + if(written == 0){ + return written; + } + return print(buf); } size_t Print::println(void) diff --git a/cores/esp32/Server.h b/cores/esp32/Server.h index 1be91873082..6a940a0b5fa 100644 --- a/cores/esp32/Server.h +++ b/cores/esp32/Server.h @@ -25,7 +25,7 @@ class Server: public Print { public: - virtual void begin() =0; + virtual void begin(uint16_t port=0) =0; }; #endif diff --git a/cores/esp32/Stream.cpp b/cores/esp32/Stream.cpp index 59b0bafeb55..5c090791968 100644 --- a/cores/esp32/Stream.cpp +++ b/cores/esp32/Stream.cpp @@ -82,6 +82,9 @@ void Stream::setTimeout(unsigned long timeout) // sets the maximum number of mi { _timeout = timeout; } +unsigned long Stream::getTimeout(void) { + return _timeout; +} // find returns true if the target string is found bool Stream::find(const char *target) diff --git a/cores/esp32/Stream.h b/cores/esp32/Stream.h index e5f4f6cc4c7..4ce31955acd 100644 --- a/cores/esp32/Stream.h +++ b/cores/esp32/Stream.h @@ -59,7 +59,7 @@ class Stream: public Print // parsing methods void setTimeout(unsigned long timeout); // sets maximum milliseconds to wait for stream data, default is 1 second - + unsigned long getTimeout(void); bool find(const char *target); // reads data from the stream until the target string is found bool find(uint8_t *target) { @@ -97,8 +97,8 @@ class Stream: public Print float parseFloat(); // float version of parseInt - size_t readBytes(char *buffer, size_t length); // read chars from stream into buffer - size_t readBytes(uint8_t *buffer, size_t length) + virtual size_t readBytes(char *buffer, size_t length); // read chars from stream into buffer + virtual size_t readBytes(uint8_t *buffer, size_t length) { return readBytes((char *) buffer, length); } @@ -114,7 +114,7 @@ class Stream: public Print // returns the number of characters placed in the buffer (0 means no valid data found) // Arduino String functions to be added here - String readString(); + virtual String readString(); String readStringUntil(char terminator); protected: diff --git a/cores/esp32/StreamString.cpp b/cores/esp32/StreamString.cpp index 80b2aff00c3..f50b6825b55 100644 --- a/cores/esp32/StreamString.cpp +++ b/cores/esp32/StreamString.cpp @@ -1,71 +1,67 @@ -/** - StreamString.cpp - - Copyright (c) 2015 Markus Sattler. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - */ - -#include -#include "StreamString.h" - -size_t StreamString::write(const uint8_t *data, size_t size) -{ - if(size && data) { - if(reserve(length() + size + 1)) { - memcpy((void *) (buffer + len), (const void *) data, size); - len += size; - *(buffer + len) = 0x00; // add null for string end - return size; - } - } - return 0; -} - -size_t StreamString::write(uint8_t data) -{ - return concat((char) data); -} - -int StreamString::available() -{ - return length(); -} - -int StreamString::read() -{ - if(length()) { - char c = charAt(0); - remove(0, 1); - return c; - - } - return -1; -} - -int StreamString::peek() -{ - if(length()) { - char c = charAt(0); - return c; - } - return -1; -} - -void StreamString::flush() -{ -} - +/** + StreamString.cpp + + Copyright (c) 2015 Markus Sattler. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + */ + +#include +#include "StreamString.h" + +size_t StreamString::write(const uint8_t *data, size_t size) { + if(size && data) { + const unsigned int newlen = length() + size; + if(reserve(newlen + 1)) { + memcpy((void *) (wbuffer() + len()), (const void *) data, size); + setLen(newlen); + *(wbuffer() + newlen) = 0x00; // add null for string end + return size; + } + } + return 0; +} + +size_t StreamString::write(uint8_t data) { + return concat((char) data); +} + +int StreamString::available() { + return length(); +} + +int StreamString::read() { + if(length()) { + char c = charAt(0); + remove(0, 1); + return c; + + } + return -1; +} + +int StreamString::peek() { + if(length()) { + char c = charAt(0); + return c; + } + return -1; +} + +void StreamString::flush() { +} + diff --git a/cores/esp32/StreamString.h b/cores/esp32/StreamString.h index a1983d8895f..dbdf3fb0097 100644 --- a/cores/esp32/StreamString.h +++ b/cores/esp32/StreamString.h @@ -1,39 +1,39 @@ -/** - StreamString.h - - Copyright (c) 2015 Markus Sattler. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef STREAMSTRING_H_ -#define STREAMSTRING_H_ - - -class StreamString: public Stream, public String -{ -public: - size_t write(const uint8_t *buffer, size_t size) override; - size_t write(uint8_t data) override; - - int available() override; - int read() override; - int peek() override; - void flush() override; -}; - - -#endif /* STREAMSTRING_H_ */ +/** + StreamString.h + + Copyright (c) 2015 Markus Sattler. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +*/ + +#ifndef STREAMSTRING_H_ +#define STREAMSTRING_H_ + + +class StreamString: public Stream, public String +{ +public: + size_t write(const uint8_t *buffer, size_t size) override; + size_t write(uint8_t data) override; + + int available() override; + int read() override; + int peek() override; + void flush() override; +}; + + +#endif /* STREAMSTRING_H_ */ diff --git a/cores/esp32/WMath.cpp b/cores/esp32/WMath.cpp index b1099b67e66..abec110b04c 100644 --- a/cores/esp32/WMath.cpp +++ b/cores/esp32/WMath.cpp @@ -37,10 +37,23 @@ void randomSeed(unsigned long seed) long random(long howbig) { - if(howbig == 0) { - return 0; + uint32_t x = esp_random(); + uint64_t m = uint64_t(x) * uint64_t(howbig); + uint32_t l = uint32_t(m); + if (l < howbig) { + uint32_t t = -howbig; + if (t >= howbig) { + t -= howbig; + if (t >= howbig) + t %= howbig; + } + while (l < t) { + x = esp_random(); + m = uint64_t(x) * uint64_t(howbig); + l = uint32_t(m); + } } - return esp_random() % howbig; + return m >> 32; } long random(long howsmall, long howbig) @@ -52,9 +65,12 @@ long random(long howsmall, long howbig) return random(diff) + howsmall; } -long map(long x, long in_min, long in_max, long out_min, long out_max) -{ - return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; +long map(long x, long in_min, long in_max, long out_min, long out_max) { + long divisor = (in_max - in_min); + if(divisor == 0){ + return -1; //AVR returns -1, SAM returns 0 + } + return (x - in_min) * (out_max - out_min) / divisor + out_min; } unsigned int makeWord(unsigned int w) diff --git a/cores/esp32/WString.cpp b/cores/esp32/WString.cpp index 124b9753d53..aee4b1c94bd 100644 --- a/cores/esp32/WString.cpp +++ b/cores/esp32/WString.cpp @@ -3,8 +3,8 @@ ...mostly rewritten by Paul Stoffregen... Copyright (c) 2009-10 Hernando Barragan. All rights reserved. Copyright 2011, Paul Stoffregen, paul@pjrc.com - Modified by Ivan Grokhotkov, 2014 - ESP31B support - Modified by Michael C. Miller, 2015 - ESP31B progmem support + Modified by Ivan Grokhotkov, 2014 - esp8266 support + Modified by Michael C. Miller, 2015 - esp8266 progmem support This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -21,47 +21,43 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ +#include #include "WString.h" #include "stdlib_noniso.h" -#include "esp32-hal-log.h" -//extern "C" { -//#include "esp_common.h" -//} /*********************************************/ /* Constructors */ /*********************************************/ -String::String(const char *cstr) -{ +String::String(const char *cstr) { init(); - if(cstr) { + if (cstr) copy(cstr, strlen(cstr)); - } } -String::String(const String &value) -{ +String::String(const String &value) { init(); *this = value; } +String::String(const __FlashStringHelper *pstr) { + init(); + *this = pstr; // see operator = +} + #ifdef __GXX_EXPERIMENTAL_CXX0X__ -String::String(String &&rval) -{ +String::String(String &&rval) { init(); move(rval); } -String::String(StringSumHelper &&rval) -{ +String::String(StringSumHelper &&rval) { init(); move(rval); } #endif -String::String(char c) -{ +String::String(char c) { init(); char buf[2]; buf[0] = c; @@ -69,120 +65,138 @@ String::String(char c) *this = buf; } -String::String(unsigned char value, unsigned char base) -{ +String::String(unsigned char value, unsigned char base) { init(); char buf[1 + 8 * sizeof(unsigned char)]; utoa(value, buf, base); *this = buf; } -String::String(int value, unsigned char base) -{ +String::String(int value, unsigned char base) { init(); char buf[2 + 8 * sizeof(int)]; - itoa(value, buf, base); + if (base == 10) { + sprintf(buf, "%d", value); + } else { + itoa(value, buf, base); + } *this = buf; } -String::String(unsigned int value, unsigned char base) -{ +String::String(unsigned int value, unsigned char base) { init(); char buf[1 + 8 * sizeof(unsigned int)]; utoa(value, buf, base); *this = buf; } -String::String(long value, unsigned char base) -{ +String::String(long value, unsigned char base) { init(); char buf[2 + 8 * sizeof(long)]; - ltoa(value, buf, base); + if (base==10) { + sprintf(buf, "%ld", value); + } else { + ltoa(value, buf, base); + } *this = buf; } -String::String(unsigned long value, unsigned char base) -{ +String::String(unsigned long value, unsigned char base) { init(); char buf[1 + 8 * sizeof(unsigned long)]; ultoa(value, buf, base); *this = buf; } -String::String(float value, unsigned char decimalPlaces) -{ +String::String(float value, unsigned char decimalPlaces) { init(); char buf[33]; *this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf); } -String::String(double value, unsigned char decimalPlaces) -{ +String::String(double value, unsigned char decimalPlaces) { init(); char buf[33]; *this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf); } -String::~String() -{ - if(buffer) { - free(buffer); - } - init(); +String::~String() { + invalidate(); } // /*********************************************/ // /* Memory Management */ // /*********************************************/ -inline void String::init(void) -{ - buffer = NULL; - capacity = 0; - len = 0; +inline void String::init(void) { + setSSO(false); + setCapacity(0); + setLen(0); + setBuffer(nullptr); } -void String::invalidate(void) -{ - if(buffer) { - free(buffer); - } +void String::invalidate(void) { + if(!isSSO() && wbuffer()) + free(wbuffer()); init(); } -unsigned char String::reserve(unsigned int size) -{ - if(buffer && capacity >= size) { +unsigned char String::reserve(unsigned int size) { + if(buffer() && capacity() >= size) return 1; - } if(changeBuffer(size)) { - if(len == 0) { - buffer[0] = 0; - } + if(len() == 0) + wbuffer()[0] = 0; return 1; } return 0; } -unsigned char String::changeBuffer(unsigned int maxStrLen) -{ - size_t newSize = ((maxStrLen + 16) & (~0xf)) - 1; - char *newbuffer = (char *) realloc(buffer, newSize+1); - if(newbuffer) { - if(newSize > len){ - if(newSize > capacity){ - memset(newbuffer+capacity, 0, newSize-capacity); - } - } else { - //new buffer can not fit the old len - newbuffer[newSize] = 0; - len = newSize; +unsigned char String::changeBuffer(unsigned int maxStrLen) { + // Can we use SSO here to avoid allocation? + if (maxStrLen < sizeof(sso.buff) - 1) { + if (isSSO() || !buffer()) { + // Already using SSO, nothing to do + uint16_t oldLen = len(); + setSSO(true); + setLen(oldLen); + return 1; + } else { // if bufptr && !isSSO() + // Using bufptr, need to shrink into sso.buff + char temp[sizeof(sso.buff)]; + memcpy(temp, buffer(), maxStrLen); + free(wbuffer()); + uint16_t oldLen = len(); + setSSO(true); + setLen(oldLen); + memcpy(wbuffer(), temp, maxStrLen); + return 1; + } + } + // Fallthrough to normal allocator + size_t newSize = (maxStrLen + 16) & (~0xf); + // Make sure we can fit newsize in the buffer + if (newSize > CAPACITY_MAX) { + return false; + } + uint16_t oldLen = len(); + char *newbuffer = (char *) realloc(isSSO() ? nullptr : wbuffer(), newSize); + if (newbuffer) { + size_t oldSize = capacity() + 1; // include NULL. + if (isSSO()) { + // Copy the SSO buffer into allocated space + memmove(newbuffer, sso.buff, sizeof(sso.buff)); + } + if (newSize > oldSize) + { + memset(newbuffer + oldSize, 0, newSize - oldSize); } - capacity = newSize; - buffer = newbuffer; + setSSO(false); + setCapacity(newSize - 1); + setLen(oldLen); // Needed in case of SSO where len() never existed + setBuffer(newbuffer); return 1; } - log_e("realloc failed! Buffer unchanged"); return 0; } @@ -190,84 +204,88 @@ unsigned char String::changeBuffer(unsigned int maxStrLen) // /* Copy and Move */ // /*********************************************/ -String & String::copy(const char *cstr, unsigned int length) -{ +String & String::copy(const char *cstr, unsigned int length) { if(!reserve(length)) { invalidate(); return *this; } - len = length; - strcpy(buffer, cstr); + setLen(length); + memmove(wbuffer(), cstr, length + 1); return *this; } -String & String::copy(const __FlashStringHelper *pstr, unsigned int length) -{ - return copy(reinterpret_cast(pstr), length); +String & String::copy(const __FlashStringHelper *pstr, unsigned int length) { + if (!reserve(length)) { + invalidate(); + return *this; + } + setLen(length); + memcpy_P(wbuffer(), (PGM_P)pstr, length + 1); // We know wbuffer() cannot ever be in PROGMEM, so memcpy safe here + return *this; } #ifdef __GXX_EXPERIMENTAL_CXX0X__ -void String::move(String &rhs) -{ - if(buffer) { - if(capacity >= rhs.len) { - strcpy(buffer, rhs.buffer); - len = rhs.len; - rhs.len = 0; +void String::move(String &rhs) { + if(buffer()) { + if(capacity() >= rhs.len()) { + memmove(wbuffer(), rhs.buffer(), rhs.length() + 1); + setLen(rhs.len()); + rhs.invalidate(); return; } else { - free(buffer); + if (!isSSO()) { + free(wbuffer()); + setBuffer(nullptr); + } } } - buffer = rhs.buffer; - capacity = rhs.capacity; - len = rhs.len; - rhs.buffer = NULL; - rhs.capacity = 0; - rhs.len = 0; + if (rhs.isSSO()) { + setSSO(true); + memmove(sso.buff, rhs.sso.buff, sizeof(sso.buff)); + } else { + setSSO(false); + setBuffer(rhs.wbuffer()); + } + setCapacity(rhs.capacity()); + setLen(rhs.len()); + rhs.setSSO(false); + rhs.setCapacity(0); + rhs.setLen(0); + rhs.setBuffer(nullptr); } #endif -String & String::operator =(const String &rhs) -{ - if(this == &rhs) { +String & String::operator =(const String &rhs) { + if(this == &rhs) return *this; - } - if(rhs.buffer) { - copy(rhs.buffer, rhs.len); - } else { + if(rhs.buffer()) + copy(rhs.buffer(), rhs.len()); + else invalidate(); - } return *this; } #ifdef __GXX_EXPERIMENTAL_CXX0X__ -String & String::operator =(String &&rval) -{ - if(this != &rval) { +String & String::operator =(String &&rval) { + if(this != &rval) move(rval); - } return *this; } -String & String::operator =(StringSumHelper &&rval) -{ - if(this != &rval) { +String & String::operator =(StringSumHelper &&rval) { + if(this != &rval) move(rval); - } return *this; } #endif -String & String::operator =(const char *cstr) -{ - if(cstr) { +String & String::operator =(const char *cstr) { + if(cstr) copy(cstr, strlen(cstr)); - } else { + else invalidate(); - } return *this; } @@ -284,196 +302,189 @@ String & String::operator = (const __FlashStringHelper *pstr) // /* concat */ // /*********************************************/ -unsigned char String::concat(const String &s) -{ - return concat(s.buffer, s.len); +unsigned char String::concat(const String &s) { + // Special case if we're concatting ourself (s += s;) since we may end up + // realloc'ing the buffer and moving s.buffer in the method called + if (&s == this) { + unsigned int newlen = 2 * len(); + if (!s.buffer()) + return 0; + if (s.len() == 0) + return 1; + if (!reserve(newlen)) + return 0; + memmove(wbuffer() + len(), buffer(), len()); + setLen(newlen); + wbuffer()[len()] = 0; + return 1; + } else { + return concat(s.buffer(), s.len()); + } } -unsigned char String::concat(const char *cstr, unsigned int length) -{ - unsigned int newlen = len + length; - if(!cstr) { +unsigned char String::concat(const char *cstr, unsigned int length) { + unsigned int newlen = len() + length; + if(!cstr) return 0; - } - if(length == 0) { + if(length == 0) return 1; - } - if(!reserve(newlen)) { + if(!reserve(newlen)) return 0; - } - strcpy(buffer + len, cstr); - len = newlen; + if (cstr >= wbuffer() && cstr < wbuffer() + len()) + // compatible with SSO in ram #6155 (case "x += x.c_str()") + memmove(wbuffer() + len(), cstr, length + 1); + else + // compatible with source in flash #6367 + memcpy_P(wbuffer() + len(), cstr, length + 1); + setLen(newlen); return 1; } -unsigned char String::concat(const char *cstr) -{ - if(!cstr) { +unsigned char String::concat(const char *cstr) { + if(!cstr) return 0; - } return concat(cstr, strlen(cstr)); } -unsigned char String::concat(char c) -{ +unsigned char String::concat(char c) { char buf[2]; buf[0] = c; buf[1] = 0; return concat(buf, 1); } -unsigned char String::concat(unsigned char num) -{ +unsigned char String::concat(unsigned char num) { char buf[1 + 3 * sizeof(unsigned char)]; - itoa(num, buf, 10); + sprintf(buf, "%d", num); return concat(buf, strlen(buf)); } -unsigned char String::concat(int num) -{ +unsigned char String::concat(int num) { char buf[2 + 3 * sizeof(int)]; - itoa(num, buf, 10); + sprintf(buf, "%d", num); return concat(buf, strlen(buf)); } -unsigned char String::concat(unsigned int num) -{ +unsigned char String::concat(unsigned int num) { char buf[1 + 3 * sizeof(unsigned int)]; utoa(num, buf, 10); return concat(buf, strlen(buf)); } -unsigned char String::concat(long num) -{ +unsigned char String::concat(long num) { char buf[2 + 3 * sizeof(long)]; - ltoa(num, buf, 10); + sprintf(buf, "%ld", num); return concat(buf, strlen(buf)); } -unsigned char String::concat(unsigned long num) -{ +unsigned char String::concat(unsigned long num) { char buf[1 + 3 * sizeof(unsigned long)]; ultoa(num, buf, 10); return concat(buf, strlen(buf)); } -unsigned char String::concat(float num) -{ +unsigned char String::concat(float num) { char buf[20]; char* string = dtostrf(num, 4, 2, buf); return concat(string, strlen(string)); } -unsigned char String::concat(double num) -{ +unsigned char String::concat(double num) { char buf[20]; char* string = dtostrf(num, 4, 2, buf); return concat(string, strlen(string)); } -unsigned char String::concat(const __FlashStringHelper * str) -{ - return concat(reinterpret_cast(str)); +unsigned char String::concat(const __FlashStringHelper * str) { + if (!str) return 0; + int length = strlen_P((PGM_P)str); + if (length == 0) return 1; + unsigned int newlen = len() + length; + if (!reserve(newlen)) return 0; + memcpy_P(wbuffer() + len(), (PGM_P)str, length + 1); + setLen(newlen); + return 1; } /*********************************************/ /* Concatenate */ /*********************************************/ -StringSumHelper & operator +(const StringSumHelper &lhs, const String &rhs) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, const String &rhs) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(rhs.buffer, rhs.len)) { + if(!a.concat(rhs.buffer(), rhs.len())) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, const char *cstr) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, const char *cstr) { StringSumHelper &a = const_cast(lhs); - if(!cstr || !a.concat(cstr, strlen(cstr))) { + if(!cstr || !a.concat(cstr, strlen(cstr))) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, char c) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, char c) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(c)) { + if(!a.concat(c)) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, unsigned char num) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, unsigned char num) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(num)) { + if(!a.concat(num)) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, int num) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, int num) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(num)) { + if(!a.concat(num)) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, unsigned int num) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, unsigned int num) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(num)) { + if(!a.concat(num)) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, long num) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, long num) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(num)) { + if(!a.concat(num)) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, unsigned long num) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, unsigned long num) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(num)) { + if(!a.concat(num)) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, float num) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, float num) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(num)) { + if(!a.concat(num)) a.invalidate(); - } return a; } -StringSumHelper & operator +(const StringSumHelper &lhs, double num) -{ +StringSumHelper & operator +(const StringSumHelper &lhs, double num) { StringSumHelper &a = const_cast(lhs); - if(!a.concat(num)) { + if(!a.concat(num)) a.invalidate(); - } return a; } StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs) { StringSumHelper &a = const_cast(lhs); - if (!a.concat(rhs)) a.invalidate(); + if (!a.concat(rhs)) + a.invalidate(); return a; } @@ -481,149 +492,145 @@ StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHel // /* Comparison */ // /*********************************************/ -int String::compareTo(const String &s) const -{ - if(!buffer || !s.buffer) { - if(s.buffer && s.len > 0) { - return 0 - *(unsigned char *) s.buffer; - } - if(buffer && len > 0) { - return *(unsigned char *) buffer; - } +int String::compareTo(const String &s) const { + if(!buffer() || !s.buffer()) { + if(s.buffer() && s.len() > 0) + return 0 - *(unsigned char *) s.buffer(); + if(buffer() && len() > 0) + return *(unsigned char *) buffer(); return 0; } - return strcmp(buffer, s.buffer); + return strcmp(buffer(), s.buffer()); } -unsigned char String::equals(const String &s2) const -{ - return (len == s2.len && compareTo(s2) == 0); +unsigned char String::equals(const String &s2) const { + return (len() == s2.len() && compareTo(s2) == 0); } -unsigned char String::equals(const char *cstr) const -{ - if(len == 0) { +unsigned char String::equals(const char *cstr) const { + if(len() == 0) return (cstr == NULL || *cstr == 0); - } - if(cstr == NULL) { - return buffer[0] == 0; - } - return strcmp(buffer, cstr) == 0; + if(cstr == NULL) + return buffer()[0] == 0; + return strcmp(buffer(), cstr) == 0; } -unsigned char String::operator<(const String &rhs) const -{ +unsigned char String::operator<(const String &rhs) const { return compareTo(rhs) < 0; } -unsigned char String::operator>(const String &rhs) const -{ +unsigned char String::operator>(const String &rhs) const { return compareTo(rhs) > 0; } -unsigned char String::operator<=(const String &rhs) const -{ +unsigned char String::operator<=(const String &rhs) const { return compareTo(rhs) <= 0; } -unsigned char String::operator>=(const String &rhs) const -{ +unsigned char String::operator>=(const String &rhs) const { return compareTo(rhs) >= 0; } -unsigned char String::equalsIgnoreCase(const String &s2) const -{ - if(this == &s2) { +unsigned char String::equalsIgnoreCase(const String &s2) const { + if(this == &s2) return 1; - } - if(len != s2.len) { + if(len() != s2.len()) return 0; - } - if(len == 0) { + if(len() == 0) return 1; - } - const char *p1 = buffer; - const char *p2 = s2.buffer; + const char *p1 = buffer(); + const char *p2 = s2.buffer(); while(*p1) { - if(tolower(*p1++) != tolower(*p2++)) { + if(tolower(*p1++) != tolower(*p2++)) return 0; - } } return 1; } -unsigned char String::startsWith(const String &s2) const -{ - if(len < s2.len) { +unsigned char String::equalsConstantTime(const String &s2) const { + // To avoid possible time-based attacks present function + // compares given strings in a constant time. + if(len() != s2.len()) return 0; + //at this point lengths are the same + if(len() == 0) + return 1; + //at this point lenghts are the same and non-zero + const char *p1 = buffer(); + const char *p2 = s2.buffer(); + unsigned int equalchars = 0; + unsigned int diffchars = 0; + while(*p1) { + if(*p1 == *p2) + ++equalchars; + else + ++diffchars; + ++p1; + ++p2; } + //the following should force a constant time eval of the condition without a compiler "logical shortcut" + unsigned char equalcond = (equalchars == len()); + unsigned char diffcond = (diffchars == 0); + return (equalcond & diffcond); //bitwise AND +} + +unsigned char String::startsWith(const String &s2) const { + if(len() < s2.len()) + return 0; return startsWith(s2, 0); } -unsigned char String::startsWith(const String &s2, unsigned int offset) const -{ - if(offset > len - s2.len || !buffer || !s2.buffer) { +unsigned char String::startsWith(const String &s2, unsigned int offset) const { + if(offset > (unsigned)(len() - s2.len()) || !buffer() || !s2.buffer()) return 0; - } - return strncmp(&buffer[offset], s2.buffer, s2.len) == 0; + return strncmp(&buffer()[offset], s2.buffer(), s2.len()) == 0; } -unsigned char String::endsWith(const String &s2) const -{ - if(len < s2.len || !buffer || !s2.buffer) { +unsigned char String::endsWith(const String &s2) const { + if(len() < s2.len() || !buffer() || !s2.buffer()) return 0; - } - return strcmp(&buffer[len - s2.len], s2.buffer) == 0; + return strcmp(&buffer()[len() - s2.len()], s2.buffer()) == 0; } // /*********************************************/ // /* Character Access */ // /*********************************************/ -char String::charAt(unsigned int loc) const -{ +char String::charAt(unsigned int loc) const { return operator[](loc); } -void String::setCharAt(unsigned int loc, char c) -{ - if(loc < len) { - buffer[loc] = c; - } +void String::setCharAt(unsigned int loc, char c) { + if(loc < len()) + wbuffer()[loc] = c; } -char & String::operator[](unsigned int index) -{ +char & String::operator[](unsigned int index) { static char dummy_writable_char; - if(index >= len || !buffer) { + if(index >= len() || !buffer()) { dummy_writable_char = 0; return dummy_writable_char; } - return buffer[index]; + return wbuffer()[index]; } -char String::operator[](unsigned int index) const -{ - if(index >= len || !buffer) { +char String::operator[](unsigned int index) const { + if(index >= len() || !buffer()) return 0; - } - return buffer[index]; + return buffer()[index]; } -void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const -{ - if(!bufsize || !buf) { +void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const { + if(!bufsize || !buf) return; - } - if(index >= len) { + if(index >= len()) { buf[0] = 0; return; } unsigned int n = bufsize - 1; - if(n > len - index) { - n = len - index; - } - strncpy((char *) buf, buffer + index, n); + if(n > len() - index) + n = len() - index; + strncpy((char *) buf, buffer() + index, n); buf[n] = 0; } @@ -631,104 +638,83 @@ void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int ind // /* Search */ // /*********************************************/ -int String::indexOf(char c) const -{ +int String::indexOf(char c) const { return indexOf(c, 0); } -int String::indexOf(char ch, unsigned int fromIndex) const -{ - if(fromIndex >= len) { +int String::indexOf(char ch, unsigned int fromIndex) const { + if(fromIndex >= len()) return -1; - } - const char* temp = strchr(buffer + fromIndex, ch); - if(temp == NULL) { + const char* temp = strchr(buffer() + fromIndex, ch); + if(temp == NULL) return -1; - } - return temp - buffer; + return temp - buffer(); } -int String::indexOf(const String &s2) const -{ +int String::indexOf(const String &s2) const { return indexOf(s2, 0); } -int String::indexOf(const String &s2, unsigned int fromIndex) const -{ - if(fromIndex >= len) { +int String::indexOf(const String &s2, unsigned int fromIndex) const { + if(fromIndex >= len()) return -1; - } - const char *found = strstr(buffer + fromIndex, s2.buffer); - if(found == NULL) { + const char *found = strstr(buffer() + fromIndex, s2.buffer()); + if(found == NULL) return -1; - } - return found - buffer; + return found - buffer(); } -int String::lastIndexOf(char theChar) const -{ - return lastIndexOf(theChar, len - 1); +int String::lastIndexOf(char theChar) const { + return lastIndexOf(theChar, len() - 1); } -int String::lastIndexOf(char ch, unsigned int fromIndex) const -{ - if(fromIndex >= len) { +int String::lastIndexOf(char ch, unsigned int fromIndex) const { + if(fromIndex >= len()) return -1; - } - char tempchar = buffer[fromIndex + 1]; - buffer[fromIndex + 1] = '\0'; - char* temp = strrchr(buffer, ch); - buffer[fromIndex + 1] = tempchar; - if(temp == NULL) { + char tempchar = buffer()[fromIndex + 1]; + wbuffer()[fromIndex + 1] = '\0'; + char* temp = strrchr(wbuffer(), ch); + wbuffer()[fromIndex + 1] = tempchar; + if(temp == NULL) return -1; - } - return temp - buffer; + return temp - buffer(); } -int String::lastIndexOf(const String &s2) const -{ - return lastIndexOf(s2, len - s2.len); +int String::lastIndexOf(const String &s2) const { + return lastIndexOf(s2, len() - s2.len()); } -int String::lastIndexOf(const String &s2, unsigned int fromIndex) const -{ - if(s2.len == 0 || len == 0 || s2.len > len) { +int String::lastIndexOf(const String &s2, unsigned int fromIndex) const { + if(s2.len() == 0 || len() == 0 || s2.len() > len()) return -1; - } - if(fromIndex >= len) { - fromIndex = len - 1; - } + if(fromIndex >= len()) + fromIndex = len() - 1; int found = -1; - for(char *p = buffer; p <= buffer + fromIndex; p++) { - p = strstr(p, s2.buffer); - if(!p) { + for(char *p = wbuffer(); p <= wbuffer() + fromIndex; p++) { + p = strstr(p, s2.buffer()); + if(!p) break; - } - if((unsigned int) (p - buffer) <= fromIndex) { - found = p - buffer; - } + if((unsigned int) (p - wbuffer()) <= fromIndex) + found = p - buffer(); } return found; } -String String::substring(unsigned int left, unsigned int right) const -{ +String String::substring(unsigned int left, unsigned int right) const { if(left > right) { unsigned int temp = right; right = left; left = temp; } String out; - if(left >= len) { + if(left >= len()) return out; - } - if(right > len) { - right = len; - } - char temp = buffer[right]; // save the replaced character - buffer[right] = '\0'; - out = buffer + left; // pointer arithmetic - buffer[right] = temp; //restore character + if(right > len()) + right = len(); + char temp = buffer()[right]; // save the replaced character + wbuffer()[right] = '\0'; + out = wbuffer() + left; // pointer arithmetic + wbuffer()[right] = temp; //restore character return out; } @@ -736,148 +722,140 @@ String String::substring(unsigned int left, unsigned int right) const // /* Modification */ // /*********************************************/ -void String::replace(char find, char replace) -{ - if(!buffer) { +void String::replace(char find, char replace) { + if(!buffer()) return; - } - for(char *p = buffer; *p; p++) { - if(*p == find) { + for(char *p = wbuffer(); *p; p++) { + if(*p == find) *p = replace; - } } } -void String::replace(const String& find, const String& replace) -{ - if(len == 0 || find.len == 0) { +void String::replace(const String& find, const String& replace) { + if(len() == 0 || find.len() == 0) return; - } - int diff = replace.len - find.len; - char *readFrom = buffer; + int diff = replace.len() - find.len(); + char *readFrom = wbuffer(); char *foundAt; if(diff == 0) { - while((foundAt = strstr(readFrom, find.buffer)) != NULL) { - memcpy(foundAt, replace.buffer, replace.len); - readFrom = foundAt + replace.len; + while((foundAt = strstr(readFrom, find.buffer())) != NULL) { + memmove(foundAt, replace.buffer(), replace.len()); + readFrom = foundAt + replace.len(); } } else if(diff < 0) { - char *writeTo = buffer; - while((foundAt = strstr(readFrom, find.buffer)) != NULL) { + char *writeTo = wbuffer(); + while((foundAt = strstr(readFrom, find.buffer())) != NULL) { unsigned int n = foundAt - readFrom; - memcpy(writeTo, readFrom, n); + memmove(writeTo, readFrom, n); writeTo += n; - memcpy(writeTo, replace.buffer, replace.len); - writeTo += replace.len; - readFrom = foundAt + find.len; - len += diff; + memmove(writeTo, replace.buffer(), replace.len()); + writeTo += replace.len(); + readFrom = foundAt + find.len(); + setLen(len() + diff); } - strcpy(writeTo, readFrom); + memmove(writeTo, readFrom, strlen(readFrom)+1); } else { - unsigned int size = len; // compute size needed for result - while((foundAt = strstr(readFrom, find.buffer)) != NULL) { - readFrom = foundAt + find.len; + unsigned int size = len(); // compute size needed for result + while((foundAt = strstr(readFrom, find.buffer())) != NULL) { + readFrom = foundAt + find.len(); size += diff; } - if(size == len) { + if(size == len()) return; - } - if(size > capacity && !changeBuffer(size)) { - return; // XXX: tell user! - } - int index = len - 1; + if(size > capacity() && !changeBuffer(size)) + return; // XXX: tell user! + int index = len() - 1; while(index >= 0 && (index = lastIndexOf(find, index)) >= 0) { - readFrom = buffer + index + find.len; - memmove(readFrom + diff, readFrom, len - (readFrom - buffer)); - len += diff; - buffer[len] = 0; - memcpy(buffer + index, replace.buffer, replace.len); + readFrom = wbuffer() + index + find.len(); + memmove(readFrom + diff, readFrom, len() - (readFrom - buffer())); + int newLen = len() + diff; + memmove(wbuffer() + index, replace.buffer(), replace.len()); + setLen(newLen); + wbuffer()[newLen] = 0; index--; } } } -void String::remove(unsigned int index) -{ +void String::remove(unsigned int index) { // Pass the biggest integer as the count. The remove method // below will take care of truncating it at the end of the // string. remove(index, (unsigned int) -1); } -void String::remove(unsigned int index, unsigned int count) -{ - if(index >= len) { +void String::remove(unsigned int index, unsigned int count) { + if(index >= len()) { return; } if(count <= 0) { return; } - if(count > len - index) { - count = len - index; + if(count > len() - index) { + count = len() - index; } - char *writeTo = buffer + index; - len = len - count; - strncpy(writeTo, buffer + index + count, len - index); - buffer[len] = 0; + char *writeTo = wbuffer() + index; + unsigned int newlen = len() - count; + setLen(newlen); + memmove(writeTo, wbuffer() + index + count, newlen - index); + wbuffer()[newlen] = 0; } -void String::toLowerCase(void) -{ - if(!buffer) { +void String::toLowerCase(void) { + if(!buffer()) return; - } - for(char *p = buffer; *p; p++) { + for(char *p = wbuffer(); *p; p++) { *p = tolower(*p); } } -void String::toUpperCase(void) -{ - if(!buffer) { +void String::toUpperCase(void) { + if(!buffer()) return; - } - for(char *p = buffer; *p; p++) { + for(char *p = wbuffer(); *p; p++) { *p = toupper(*p); } } -void String::trim(void) -{ - if(!buffer || len == 0) { +void String::trim(void) { + if(!buffer() || len() == 0) return; - } - char *begin = buffer; - while(isspace(*begin)) { + char *begin = wbuffer(); + while(isspace(*begin)) begin++; - } - char *end = buffer + len - 1; - while(isspace(*end) && end >= begin) { + char *end = wbuffer() + len() - 1; + while(isspace(*end) && end >= begin) end--; - } - len = end + 1 - begin; - if(begin > buffer) { - memcpy(buffer, begin, len); - } - buffer[len] = 0; + unsigned int newlen = end + 1 - begin; + setLen(newlen); + if(begin > buffer()) + memmove(wbuffer(), begin, newlen); + wbuffer()[newlen] = 0; } // /*********************************************/ // /* Parsing / Conversion */ // /*********************************************/ -long String::toInt(void) const -{ - if(buffer) { - return atol(buffer); - } +long String::toInt(void) const { + if (buffer()) + return atol(buffer()); return 0; } -float String::toFloat(void) const -{ - if(buffer) { - return atof(buffer); - } +float String::toFloat(void) const { + if (buffer()) + return atof(buffer()); return 0; } + +double String::toDouble(void) const +{ + if (buffer()) + return atof(buffer()); + return 0.0; +} + +// global empty string to allow returning const String& with nothing + +const String emptyString; diff --git a/cores/esp32/WString.h b/cores/esp32/WString.h index 9d49377ceb5..38bd116f4ae 100644 --- a/cores/esp32/WString.h +++ b/cores/esp32/WString.h @@ -27,6 +27,7 @@ #include #include #include +#include // An inherited class for holding the result of a concatenation. These // result objects are assumed to be writable by subsequent concatenations. @@ -35,293 +36,300 @@ class StringSumHelper; // an abstract class used as a means to proide a unique pointer type // but really has no body class __FlashStringHelper; -#define F(string_literal) (reinterpret_cast(PSTR(string_literal))) +#define FPSTR(pstr_pointer) (reinterpret_cast(pstr_pointer)) +#define F(string_literal) (FPSTR(PSTR(string_literal))) // The string class -class String -{ - // use a function pointer to allow for "if (s)" without the - // complications of an operator bool(). for more information, see: - // http://www.artima.com/cppsource/safebool.html - typedef void (String::*StringIfHelperType)() const; - void StringIfHelper() const - { - } +class String { + // use a function pointer to allow for "if (s)" without the + // complications of an operator bool(). for more information, see: + // http://www.artima.com/cppsource/safebool.html + typedef void (String::*StringIfHelperType)() const; + void StringIfHelper() const { + } -public: - // constructors - // creates a copy of the initial value. - // if the initial value is null or invalid, or if memory allocation - // fails, the string will be marked as invalid (i.e. "if (s)" will - // be false). - String(const char *cstr = ""); - String(const String &str); - String(const __FlashStringHelper *str) : String(reinterpret_cast(str)) {}; + public: + // constructors + // creates a copy of the initial value. + // if the initial value is null or invalid, or if memory allocation + // fails, the string will be marked as invalid (i.e. "if (s)" will + // be false). + String(const char *cstr = ""); + String(const String &str); + String(const __FlashStringHelper *str); #ifdef __GXX_EXPERIMENTAL_CXX0X__ - String(String &&rval); - String(StringSumHelper &&rval); + String(String &&rval); + String(StringSumHelper &&rval); #endif - explicit String(char c); - explicit String(unsigned char, unsigned char base = 10); - explicit String(int, unsigned char base = 10); - explicit String(unsigned int, unsigned char base = 10); - explicit String(long, unsigned char base = 10); - explicit String(unsigned long, unsigned char base = 10); - explicit String(float, unsigned char decimalPlaces = 2); - explicit String(double, unsigned char decimalPlaces = 2); - ~String(void); + explicit String(char c); + explicit String(unsigned char, unsigned char base = 10); + explicit String(int, unsigned char base = 10); + explicit String(unsigned int, unsigned char base = 10); + explicit String(long, unsigned char base = 10); + explicit String(unsigned long, unsigned char base = 10); + explicit String(float, unsigned char decimalPlaces = 2); + explicit String(double, unsigned char decimalPlaces = 2); + ~String(void); - // memory management - // return true on success, false on failure (in which case, the string - // is left unchanged). reserve(0), if successful, will validate an - // invalid string (i.e., "if (s)" will be true afterwards) - unsigned char reserve(unsigned int size); - inline unsigned int length(void) const - { - if(buffer) { - return len; - } else { - return 0; - } - } + // memory management + // return true on success, false on failure (in which case, the string + // is left unchanged). reserve(0), if successful, will validate an + // invalid string (i.e., "if (s)" will be true afterwards) + unsigned char reserve(unsigned int size); + inline unsigned int length(void) const { + if(buffer()) { + return len(); + } else { + return 0; + } + } + inline void clear(void) { + setLen(0); + } + inline bool isEmpty(void) const { + return length() == 0; + } - // creates a copy of the assigned value. if the value is null or - // invalid, or if the memory allocation fails, the string will be - // marked as invalid ("if (s)" will be false). - String & operator =(const String &rhs); - String & operator =(const char *cstr); - String & operator = (const __FlashStringHelper *str); + // creates a copy of the assigned value. if the value is null or + // invalid, or if the memory allocation fails, the string will be + // marked as invalid ("if (s)" will be false). + String & operator =(const String &rhs); + String & operator =(const char *cstr); + String & operator = (const __FlashStringHelper *str); #ifdef __GXX_EXPERIMENTAL_CXX0X__ - String & operator =(String &&rval); - String & operator =(StringSumHelper &&rval); + String & operator =(String &&rval); + String & operator =(StringSumHelper &&rval); #endif - // concatenate (works w/ built-in types) + // concatenate (works w/ built-in types) - // returns true on success, false on failure (in which case, the string - // is left unchanged). if the argument is null or invalid, the - // concatenation is considered unsucessful. - unsigned char concat(const String &str); - unsigned char concat(const char *cstr); - unsigned char concat(char c); - unsigned char concat(unsigned char c); - unsigned char concat(int num); - unsigned char concat(unsigned int num); - unsigned char concat(long num); - unsigned char concat(unsigned long num); - unsigned char concat(float num); - unsigned char concat(double num); - unsigned char concat(const __FlashStringHelper * str); + // returns true on success, false on failure (in which case, the string + // is left unchanged). if the argument is null or invalid, the + // concatenation is considered unsuccessful. + unsigned char concat(const String &str); + unsigned char concat(const char *cstr); + unsigned char concat(char c); + unsigned char concat(unsigned char c); + unsigned char concat(int num); + unsigned char concat(unsigned int num); + unsigned char concat(long num); + unsigned char concat(unsigned long num); + unsigned char concat(float num); + unsigned char concat(double num); + unsigned char concat(const __FlashStringHelper * str); - // if there's not enough memory for the concatenated value, the string - // will be left unchanged (but this isn't signalled in any way) - String & operator +=(const String &rhs) - { - concat(rhs); - return (*this); - } - String & operator +=(const char *cstr) - { - concat(cstr); - return (*this); - } - String & operator +=(char c) - { - concat(c); - return (*this); - } - String & operator +=(unsigned char num) - { - concat(num); - return (*this); - } - String & operator +=(int num) - { - concat(num); - return (*this); - } - String & operator +=(unsigned int num) - { - concat(num); - return (*this); - } - String & operator +=(long num) - { - concat(num); - return (*this); - } - String & operator +=(unsigned long num) - { - concat(num); - return (*this); - } - String & operator +=(float num) - { - concat(num); - return (*this); - } - String & operator +=(double num) - { - concat(num); - return (*this); - } - String & operator += (const __FlashStringHelper *str) - { - concat(str); - return (*this); - } + // if there's not enough memory for the concatenated value, the string + // will be left unchanged (but this isn't signalled in any way) + String & operator +=(const String &rhs) { + concat(rhs); + return (*this); + } + String & operator +=(const char *cstr) { + concat(cstr); + return (*this); + } + String & operator +=(char c) { + concat(c); + return (*this); + } + String & operator +=(unsigned char num) { + concat(num); + return (*this); + } + String & operator +=(int num) { + concat(num); + return (*this); + } + String & operator +=(unsigned int num) { + concat(num); + return (*this); + } + String & operator +=(long num) { + concat(num); + return (*this); + } + String & operator +=(unsigned long num) { + concat(num); + return (*this); + } + String & operator +=(float num) { + concat(num); + return (*this); + } + String & operator +=(double num) { + concat(num); + return (*this); + } + String & operator += (const __FlashStringHelper *str){ + concat(str); + return (*this); + } - friend StringSumHelper & operator +(const StringSumHelper &lhs, const String &rhs); - friend StringSumHelper & operator +(const StringSumHelper &lhs, const char *cstr); - friend StringSumHelper & operator +(const StringSumHelper &lhs, char c); - friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned char num); - friend StringSumHelper & operator +(const StringSumHelper &lhs, int num); - friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned int num); - friend StringSumHelper & operator +(const StringSumHelper &lhs, long num); - friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned long num); - friend StringSumHelper & operator +(const StringSumHelper &lhs, float num); - friend StringSumHelper & operator +(const StringSumHelper &lhs, double num); - friend StringSumHelper & operator +(const StringSumHelper &lhs, const __FlashStringHelper *rhs); + friend StringSumHelper & operator +(const StringSumHelper &lhs, const String &rhs); + friend StringSumHelper & operator +(const StringSumHelper &lhs, const char *cstr); + friend StringSumHelper & operator +(const StringSumHelper &lhs, char c); + friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned char num); + friend StringSumHelper & operator +(const StringSumHelper &lhs, int num); + friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned int num); + friend StringSumHelper & operator +(const StringSumHelper &lhs, long num); + friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned long num); + friend StringSumHelper & operator +(const StringSumHelper &lhs, float num); + friend StringSumHelper & operator +(const StringSumHelper &lhs, double num); + friend StringSumHelper & operator +(const StringSumHelper &lhs, const __FlashStringHelper *rhs); + + // comparison (only works w/ Strings and "strings") + operator StringIfHelperType() const { + return buffer() ? &String::StringIfHelper : 0; + } + int compareTo(const String &s) const; + unsigned char equals(const String &s) const; + unsigned char equals(const char *cstr) const; + unsigned char operator ==(const String &rhs) const { + return equals(rhs); + } + unsigned char operator ==(const char *cstr) const { + return equals(cstr); + } + unsigned char operator !=(const String &rhs) const { + return !equals(rhs); + } + unsigned char operator !=(const char *cstr) const { + return !equals(cstr); + } + unsigned char operator <(const String &rhs) const; + unsigned char operator >(const String &rhs) const; + unsigned char operator <=(const String &rhs) const; + unsigned char operator >=(const String &rhs) const; + unsigned char equalsIgnoreCase(const String &s) const; + unsigned char equalsConstantTime(const String &s) const; + unsigned char startsWith(const String &prefix) const; + unsigned char startsWith(const String &prefix, unsigned int offset) const; + unsigned char endsWith(const String &suffix) const; - // comparison (only works w/ Strings and "strings") - operator StringIfHelperType() const - { - return buffer ? &String::StringIfHelper : 0; - } - int compareTo(const String &s) const; - unsigned char equals(const String &s) const; - unsigned char equals(const char *cstr) const; - unsigned char operator ==(const String &rhs) const - { - return equals(rhs); - } - unsigned char operator ==(const char *cstr) const - { - return equals(cstr); - } - unsigned char operator !=(const String &rhs) const - { - return !equals(rhs); - } - unsigned char operator !=(const char *cstr) const - { - return !equals(cstr); - } - unsigned char operator <(const String &rhs) const; - unsigned char operator >(const String &rhs) const; - unsigned char operator <=(const String &rhs) const; - unsigned char operator >=(const String &rhs) const; - unsigned char equalsIgnoreCase(const String &s) const; - unsigned char startsWith(const String &prefix) const; - unsigned char startsWith(const String &prefix, unsigned int offset) const; - unsigned char endsWith(const String &suffix) const; + // character access + char charAt(unsigned int index) const; + void setCharAt(unsigned int index, char c); + char operator [](unsigned int index) const; + char& operator [](unsigned int index); + void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index = 0) const; + void toCharArray(char *buf, unsigned int bufsize, unsigned int index = 0) const { + getBytes((unsigned char *) buf, bufsize, index); + } + const char* c_str() const { return buffer(); } + char* begin() { return wbuffer(); } + char* end() { return wbuffer() + length(); } + const char* begin() const { return c_str(); } + const char* end() const { return c_str() + length(); } - // character acccess - char charAt(unsigned int index) const; - void setCharAt(unsigned int index, char c); - char operator [](unsigned int index) const; - char& operator [](unsigned int index); - void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index = 0) const; - void toCharArray(char *buf, unsigned int bufsize, unsigned int index = 0) const - { - getBytes((unsigned char *) buf, bufsize, index); - } - const char * c_str() const - { - return buffer; - } + // search + int indexOf(char ch) const; + int indexOf(char ch, unsigned int fromIndex) const; + int indexOf(const String &str) const; + int indexOf(const String &str, unsigned int fromIndex) const; + int lastIndexOf(char ch) const; + int lastIndexOf(char ch, unsigned int fromIndex) const; + int lastIndexOf(const String &str) const; + int lastIndexOf(const String &str, unsigned int fromIndex) const; + String substring(unsigned int beginIndex) const { + return substring(beginIndex, len()); + } + ; + String substring(unsigned int beginIndex, unsigned int endIndex) const; - // search - int indexOf(char ch) const; - int indexOf(char ch, unsigned int fromIndex) const; - int indexOf(const String &str) const; - int indexOf(const String &str, unsigned int fromIndex) const; - int lastIndexOf(char ch) const; - int lastIndexOf(char ch, unsigned int fromIndex) const; - int lastIndexOf(const String &str) const; - int lastIndexOf(const String &str, unsigned int fromIndex) const; - String substring(unsigned int beginIndex) const - { - return substring(beginIndex, len); - } - ; - String substring(unsigned int beginIndex, unsigned int endIndex) const; + // modification + void replace(char find, char replace); + void replace(const String& find, const String& replace); + void remove(unsigned int index); + void remove(unsigned int index, unsigned int count); + void toLowerCase(void); + void toUpperCase(void); + void trim(void); - // modification - void replace(char find, char replace); - void replace(const String& find, const String& replace); - void remove(unsigned int index); - void remove(unsigned int index, unsigned int count); - void toLowerCase(void); - void toUpperCase(void); - void trim(void); + // parsing/conversion + long toInt(void) const; + float toFloat(void) const; + double toDouble(void) const; - // parsing/conversion - long toInt(void) const; - float toFloat(void) const; + protected: + // Contains the string info when we're not in SSO mode + struct _ptr { + char * buff; + uint16_t cap; + uint16_t len; + }; + // This allows strings up up to 11 (10 + \0 termination) without any extra space. + enum { SSOSIZE = sizeof(struct _ptr) + 4 - 1 }; // Characters to allocate space for SSO, must be 12 or more + struct _sso { + char buff[SSOSIZE]; + unsigned char len : 7; // Ensure only one byte is allocated by GCC for the bitfields + unsigned char isSSO : 1; + } __attribute__((packed)); // Ensure that GCC doesn't expand the flag byte to a 32-bit word for alignment issues + enum { CAPACITY_MAX = 65535 }; // If typeof(cap) changed from uint16_t, be sure to update this enum to the max value storable in the type + union { + struct _ptr ptr; + struct _sso sso; + }; + // Accessor functions + inline bool isSSO() const { return sso.isSSO; } + inline unsigned int len() const { return isSSO() ? sso.len : ptr.len; } + inline unsigned int capacity() const { return isSSO() ? (unsigned int)SSOSIZE - 1 : ptr.cap; } // Size of max string not including terminal NUL + inline void setSSO(bool set) { sso.isSSO = set; } + inline void setLen(int len) { if (isSSO()) sso.len = len; else ptr.len = len; } + inline void setCapacity(int cap) { if (!isSSO()) ptr.cap = cap; } + inline void setBuffer(char *buff) { if (!isSSO()) ptr.buff = buff; } + // Buffer accessor functions + inline const char *buffer() const { return (const char *)(isSSO() ? sso.buff : ptr.buff); } + inline char *wbuffer() const { return isSSO() ? const_cast(sso.buff) : ptr.buff; } // Writable version of buffer -protected: - char *buffer; // the actual char array - unsigned int capacity; // the array length minus one (for the '\0') - unsigned int len; // the String length (not counting the '\0') -protected: - void init(void); - void invalidate(void); - unsigned char changeBuffer(unsigned int maxStrLen); - unsigned char concat(const char *cstr, unsigned int length); + protected: + void init(void); + void invalidate(void); + unsigned char changeBuffer(unsigned int maxStrLen); + unsigned char concat(const char *cstr, unsigned int length); - // copy and move - String & copy(const char *cstr, unsigned int length); - String & copy(const __FlashStringHelper *pstr, unsigned int length); + // copy and move + String & copy(const char *cstr, unsigned int length); + String & copy(const __FlashStringHelper *pstr, unsigned int length); #ifdef __GXX_EXPERIMENTAL_CXX0X__ - void move(String &rhs); + void move(String &rhs); #endif }; -class StringSumHelper: public String -{ -public: - StringSumHelper(const String &s) : - String(s) - { - } - StringSumHelper(const char *p) : - String(p) - { - } - StringSumHelper(char c) : - String(c) - { - } - StringSumHelper(unsigned char num) : - String(num) - { - } - StringSumHelper(int num) : - String(num) - { - } - StringSumHelper(unsigned int num) : - String(num) - { - } - StringSumHelper(long num) : - String(num) - { - } - StringSumHelper(unsigned long num) : - String(num) - { - } - StringSumHelper(float num) : - String(num) - { - } - StringSumHelper(double num) : - String(num) - { - } +class StringSumHelper: public String { + public: + StringSumHelper(const String &s) : + String(s) { + } + StringSumHelper(const char *p) : + String(p) { + } + StringSumHelper(char c) : + String(c) { + } + StringSumHelper(unsigned char num) : + String(num) { + } + StringSumHelper(int num) : + String(num) { + } + StringSumHelper(unsigned int num) : + String(num) { + } + StringSumHelper(long num) : + String(num) { + } + StringSumHelper(unsigned long num) : + String(num) { + } + StringSumHelper(float num) : + String(num) { + } + StringSumHelper(double num) : + String(num) { + } }; +extern const String emptyString; + #endif // __cplusplus #endif // String_class_h diff --git a/cores/esp32/apps/sntp/sntp.h b/cores/esp32/apps/sntp/sntp.h new file mode 100644 index 00000000000..8a940f88076 --- /dev/null +++ b/cores/esp32/apps/sntp/sntp.h @@ -0,0 +1 @@ +#include "lwip/apps/sntp.h" diff --git a/cores/esp32/base64.cpp b/cores/esp32/base64.cpp index b95064ae136..1fc144e2659 100644 --- a/cores/esp32/base64.cpp +++ b/cores/esp32/base64.cpp @@ -1,65 +1,64 @@ -/** - * base64.cpp - * - * Created on: 09.12.2015 - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the ESP31B core for Arduino. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#include "Arduino.h" -extern "C" { -#include "libb64/cdecode.h" -#include "libb64/cencode.h" -} -#include "base64.h" - -/** - * convert input data to base64 - * @param data uint8_t * - * @param length size_t - * @return String - */ -String base64::encode(uint8_t * data, size_t length) -{ - // base64 needs more size then the source data - size_t size = ((length * 1.6f) + 1); - char * buffer = (char *) malloc(size); - if(buffer) { - base64_encodestate _state; - base64_init_encodestate(&_state); - int len = base64_encode_block((const char *) &data[0], length, &buffer[0], &_state); - len = base64_encode_blockend((buffer + len), &_state); - - String base64 = String(buffer); - free(buffer); - return base64; - } - return String("-FAIL-"); -} - -/** - * convert input data to base64 - * @param text String - * @return String - */ -String base64::encode(String text) -{ - return base64::encode((uint8_t *) text.c_str(), text.length()); -} - +/** + * base64.cpp + * + * Created on: 09.12.2015 + * + * Copyright (c) 2015 Markus Sattler. All rights reserved. + * This file is part of the ESP31B core for Arduino. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include "Arduino.h" +extern "C" { +#include "libb64/cdecode.h" +#include "libb64/cencode.h" +} +#include "base64.h" + +/** + * convert input data to base64 + * @param data const uint8_t * + * @param length size_t + * @return String + */ +String base64::encode(const uint8_t * data, size_t length) +{ + size_t size = base64_encode_expected_len(length) + 1; + char * buffer = (char *) malloc(size); + if(buffer) { + base64_encodestate _state; + base64_init_encodestate(&_state); + int len = base64_encode_block((const char *) &data[0], length, &buffer[0], &_state); + len = base64_encode_blockend((buffer + len), &_state); + + String base64 = String(buffer); + free(buffer); + return base64; + } + return String("-FAIL-"); +} + +/** + * convert input data to base64 + * @param text const String& + * @return String + */ +String base64::encode(const String& text) +{ + return base64::encode((uint8_t *) text.c_str(), text.length()); +} + diff --git a/cores/esp32/base64.h b/cores/esp32/base64.h index f246652198e..97095817b8f 100644 --- a/cores/esp32/base64.h +++ b/cores/esp32/base64.h @@ -1,13 +1,13 @@ -#ifndef CORE_BASE64_H_ -#define CORE_BASE64_H_ - -class base64 -{ -public: - static String encode(uint8_t * data, size_t length); - static String encode(String text); -private: -}; - - -#endif /* CORE_BASE64_H_ */ +#ifndef CORE_BASE64_H_ +#define CORE_BASE64_H_ + +class base64 +{ +public: + static String encode(const uint8_t * data, size_t length); + static String encode(const String& text); +private: +}; + + +#endif /* CORE_BASE64_H_ */ diff --git a/cores/esp32/esp32-hal-bt.c b/cores/esp32/esp32-hal-bt.c index 0591ace38af..99762243469 100644 --- a/cores/esp32/esp32-hal-bt.c +++ b/cores/esp32/esp32-hal-bt.c @@ -14,12 +14,18 @@ #include "esp32-hal-bt.h" -#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED) +#ifdef CONFIG_BT_ENABLED +bool btInUse(){ return true; } +#ifdef CONFIG_BLUEDROID_ENABLED #include "esp_bt.h" -#include "esp_bt_defs.h" -#include "esp_bt_main.h" + +#ifdef CONFIG_CLASSIC_BT_ENABLED +#define BT_MODE ESP_BT_MODE_BTDM +#else +#define BT_MODE ESP_BT_MODE_BLE +#endif bool btStarted(){ return (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED); @@ -35,7 +41,7 @@ bool btStart(){ while(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE){} } if(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED){ - if (esp_bt_controller_enable(ESP_BT_MODE_BTDM)) { + if (esp_bt_controller_enable(BT_MODE)) { log_e("BT Enable failed"); return false; } @@ -59,6 +65,14 @@ bool btStop(){ while(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED); } if(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED){ + if (esp_bt_controller_deinit()) { + log_e("BT deint failed"); + return false; + } + vTaskDelay(1); + if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_IDLE) { + return false; + } return true; } log_e("BT Stop failed"); @@ -81,4 +95,5 @@ bool btStop() return false; } #endif +#endif diff --git a/cores/esp32/esp32-hal-cpu.c b/cores/esp32/esp32-hal-cpu.c new file mode 100644 index 00000000000..1e30bcf71b1 --- /dev/null +++ b/cores/esp32/esp32-hal-cpu.c @@ -0,0 +1,219 @@ +// 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. + +#include "sdkconfig.h" +#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" +#include "soc/rtc_cntl_reg.h" +#include "rom/rtc.h" +#include "soc/apb_ctrl_reg.h" +#include "soc/efuse_reg.h" +#include "esp32-hal.h" +#include "esp32-hal-cpu.h" + +typedef struct apb_change_cb_s { + struct apb_change_cb_s * next; + void * arg; + apb_change_cb_t cb; +} apb_change_t; + +const uint32_t MHZ = 1000000; + +static apb_change_t * apb_change_callbacks = NULL; +static xSemaphoreHandle apb_change_lock = NULL; + +static void initApbChangeCallback(){ + static volatile bool initialized = false; + if(!initialized){ + initialized = true; + apb_change_lock = xSemaphoreCreateMutex(); + if(!apb_change_lock){ + initialized = false; + } + } +} + +static void triggerApbChangeCallback(apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb){ + initApbChangeCallback(); + xSemaphoreTake(apb_change_lock, portMAX_DELAY); + apb_change_t * r = apb_change_callbacks; + while(r != NULL){ + r->cb(r->arg, ev_type, old_apb, new_apb); + r=r->next; + } + xSemaphoreGive(apb_change_lock); +} + +bool addApbChangeCallback(void * arg, apb_change_cb_t cb){ + initApbChangeCallback(); + apb_change_t * c = (apb_change_t*)malloc(sizeof(apb_change_t)); + if(!c){ + log_e("Callback Object Malloc Failed"); + return false; + } + c->next = NULL; + c->arg = arg; + c->cb = cb; + xSemaphoreTake(apb_change_lock, portMAX_DELAY); + if(apb_change_callbacks == NULL){ + apb_change_callbacks = c; + } else { + apb_change_t * r = apb_change_callbacks; + if(r->cb != cb || r->arg != arg){ + while(r->next){ + r = r->next; + if(r->cb == cb && r->arg == arg){ + free(c); + goto unlock_and_exit; + } + } + r->next = c; + } + } +unlock_and_exit: + xSemaphoreGive(apb_change_lock); + return true; +} + +bool removeApbChangeCallback(void * arg, apb_change_cb_t cb){ + initApbChangeCallback(); + xSemaphoreTake(apb_change_lock, portMAX_DELAY); + apb_change_t * r = apb_change_callbacks; + if(r == NULL){ + xSemaphoreGive(apb_change_lock); + return false; + } + if(r->cb == cb && r->arg == arg){ + apb_change_callbacks = r->next; + free(r); + } else { + while(r->next && (r->next->cb != cb || r->next->arg != arg)){ + r = r->next; + } + if(r->next == NULL || r->next->cb != cb || r->next->arg != arg){ + xSemaphoreGive(apb_change_lock); + return false; + } + apb_change_t * c = r->next; + r->next = c->next; + free(c); + } + xSemaphoreGive(apb_change_lock); + return true; +} + +static uint32_t calculateApb(rtc_cpu_freq_config_t * conf){ + if(conf->freq_mhz >= 80){ + return 80 * MHZ; + } + return (conf->source_freq_mhz * MHZ) / conf->div; +} + +void esp_timer_impl_update_apb_freq(uint32_t apb_ticks_per_us); //private in IDF + +bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz){ + rtc_cpu_freq_config_t conf, cconf; + uint32_t capb, apb; + //Get XTAL Frequency and calculate min CPU MHz + rtc_xtal_freq_t xtal = rtc_clk_xtal_freq_get(); + if(xtal > RTC_XTAL_FREQ_AUTO){ + if(xtal < RTC_XTAL_FREQ_40M) { + if(cpu_freq_mhz <= xtal && cpu_freq_mhz != xtal && cpu_freq_mhz != (xtal/2)){ + log_e("Bad frequency: %u MHz! Options are: 240, 160, 80, %u and %u MHz", cpu_freq_mhz, xtal, xtal/2); + return false; + } + } else if(cpu_freq_mhz <= xtal && cpu_freq_mhz != xtal && cpu_freq_mhz != (xtal/2) && cpu_freq_mhz != (xtal/4)){ + log_e("Bad frequency: %u MHz! Options are: 240, 160, 80, %u, %u and %u MHz", cpu_freq_mhz, xtal, xtal/2, xtal/4); + return false; + } + } + if(cpu_freq_mhz > xtal && cpu_freq_mhz != 240 && cpu_freq_mhz != 160 && cpu_freq_mhz != 80){ + if(xtal >= RTC_XTAL_FREQ_40M){ + log_e("Bad frequency: %u MHz! Options are: 240, 160, 80, %u, %u and %u MHz", cpu_freq_mhz, xtal, xtal/2, xtal/4); + } else { + log_e("Bad frequency: %u MHz! Options are: 240, 160, 80, %u and %u MHz", cpu_freq_mhz, xtal, xtal/2); + } + return false; + } + //check if cpu supports the frequency + if(cpu_freq_mhz == 240){ + //Check if ESP32 is rated for a CPU frequency of 160MHz only + if (REG_GET_BIT(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_CPU_FREQ_RATED) && + REG_GET_BIT(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_CPU_FREQ_LOW)) { + log_e("Can not switch to 240 MHz! Chip CPU frequency rated for 160MHz."); + cpu_freq_mhz = 160; + } + } + //Get current CPU clock configuration + rtc_clk_cpu_freq_get_config(&cconf); + //return if frequency has not changed + if(cconf.freq_mhz == cpu_freq_mhz){ + return true; + } + //Get configuration for the new CPU frequency + if(!rtc_clk_cpu_freq_mhz_to_config(cpu_freq_mhz, &conf)){ + log_e("CPU clock could not be set to %u MHz", cpu_freq_mhz); + return false; + } + //Current APB + capb = calculateApb(&cconf); + //New APB + apb = calculateApb(&conf); + log_d("%s: %u / %u = %u Mhz, APB: %u Hz", (conf.source == RTC_CPU_FREQ_SRC_PLL)?"PLL":((conf.source == RTC_CPU_FREQ_SRC_APLL)?"APLL":((conf.source == RTC_CPU_FREQ_SRC_XTAL)?"XTAL":"8M")), conf.source_freq_mhz, conf.div, conf.freq_mhz, apb); + //Call peripheral functions before the APB change + if(apb_change_callbacks){ + triggerApbChangeCallback(APB_BEFORE_CHANGE, capb, apb); + } + //Make the frequency change + rtc_clk_cpu_freq_set_config_fast(&conf); + if(capb != apb){ + //Update REF_TICK (uncomment if REF_TICK is different than 1MHz) + //if(conf.freq_mhz < 80){ + // ESP_REG(APB_CTRL_XTAL_TICK_CONF_REG) = conf.freq_mhz / (REF_CLK_FREQ / MHZ) - 1; + //} + //Update APB Freq REG + rtc_clk_apb_freq_update(apb); + //Update esp_timer divisor + esp_timer_impl_update_apb_freq(apb / MHZ); + } + //Update FreeRTOS Tick Divisor + uint32_t fcpu = (conf.freq_mhz >= 80)?(conf.freq_mhz * MHZ):(apb); + _xt_tick_divisor = fcpu / XT_TICK_PER_SEC; + //Call peripheral functions after the APB change + if(apb_change_callbacks){ + triggerApbChangeCallback(APB_AFTER_CHANGE, capb, apb); + } + return true; +} + +uint32_t getCpuFrequencyMhz(){ + rtc_cpu_freq_config_t conf; + rtc_clk_cpu_freq_get_config(&conf); + return conf.freq_mhz; +} + +uint32_t getXtalFrequencyMhz(){ + return rtc_clk_xtal_freq_get(); +} + +uint32_t getApbFrequency(){ + rtc_cpu_freq_config_t conf; + rtc_clk_cpu_freq_get_config(&conf); + return calculateApb(&conf); +} diff --git a/cores/esp32/esp32-hal-cpu.h b/cores/esp32/esp32-hal-cpu.h new file mode 100644 index 00000000000..646b59858f5 --- /dev/null +++ b/cores/esp32/esp32-hal-cpu.h @@ -0,0 +1,48 @@ +// 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 _ESP32_HAL_CPU_H_ +#define _ESP32_HAL_CPU_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +typedef enum { APB_BEFORE_CHANGE, APB_AFTER_CHANGE } apb_change_ev_t; + +typedef void (* apb_change_cb_t)(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb); + +bool addApbChangeCallback(void * arg, apb_change_cb_t cb); +bool removeApbChangeCallback(void * arg, apb_change_cb_t cb); + +//function takes the following frequencies as valid values: +// 240, 160, 80 <<< For all XTAL types +// 40, 20, 10 <<< For 40MHz XTAL +// 26, 13 <<< For 26MHz XTAL +// 24, 12 <<< For 24MHz XTAL +bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz); + +uint32_t getCpuFrequencyMhz(); // In MHz +uint32_t getXtalFrequencyMhz(); // In MHz +uint32_t getApbFrequency(); // In Hz + +#ifdef __cplusplus +} +#endif + +#endif /* _ESP32_HAL_CPU_H_ */ diff --git a/cores/esp32/esp32-hal-dac.h b/cores/esp32/esp32-hal-dac.h index fdb21628d1c..47b2265800f 100644 --- a/cores/esp32/esp32-hal-dac.h +++ b/cores/esp32/esp32-hal-dac.h @@ -25,6 +25,7 @@ extern "C" { #endif #include "esp32-hal.h" +#include "driver/gpio.h" void dacWrite(uint8_t pin, uint8_t value); diff --git a/cores/esp32/esp32-hal-gpio.c b/cores/esp32/esp32-hal-gpio.c index 7c5e02bd47f..d22af774c81 100644 --- a/cores/esp32/esp32-hal-gpio.c +++ b/cores/esp32/esp32-hal-gpio.c @@ -70,7 +70,13 @@ const DRAM_ATTR esp32_gpioMux_t esp32_gpioMux[GPIO_PIN_COUNT]={ }; typedef void (*voidFuncPtr)(void); -static voidFuncPtr __pinInterruptHandlers[GPIO_PIN_COUNT] = {0,}; +typedef void (*voidFuncPtrArg)(void*); +typedef struct { + voidFuncPtr fn; + void* arg; + bool functional; +} InterruptHandle_t; +static InterruptHandle_t __pinInterruptHandlers[GPIO_PIN_COUNT] = {0,}; #include "driver/rtc_io.h" @@ -193,7 +199,7 @@ extern int IRAM_ATTR __digitalRead(uint8_t pin) static intr_handle_t gpio_intr_handle = NULL; -static void IRAM_ATTR __onPinInterrupt(void *arg) +static void IRAM_ATTR __onPinInterrupt() { uint32_t gpio_intr_status_l=0; uint32_t gpio_intr_status_h=0; @@ -207,8 +213,12 @@ static void IRAM_ATTR __onPinInterrupt(void *arg) if(gpio_intr_status_l) { do { if(gpio_intr_status_l & ((uint32_t)1 << pin)) { - if(__pinInterruptHandlers[pin]) { - __pinInterruptHandlers[pin](); + if(__pinInterruptHandlers[pin].fn) { + if(__pinInterruptHandlers[pin].arg){ + ((voidFuncPtrArg)__pinInterruptHandlers[pin].fn)(__pinInterruptHandlers[pin].arg); + } else { + __pinInterruptHandlers[pin].fn(); + } } } } while(++pin<32); @@ -217,23 +227,38 @@ static void IRAM_ATTR __onPinInterrupt(void *arg) pin=32; do { if(gpio_intr_status_h & ((uint32_t)1 << (pin - 32))) { - if(__pinInterruptHandlers[pin]) { - __pinInterruptHandlers[pin](); + if(__pinInterruptHandlers[pin].fn) { + if(__pinInterruptHandlers[pin].arg){ + ((voidFuncPtrArg)__pinInterruptHandlers[pin].fn)(__pinInterruptHandlers[pin].arg); + } else { + __pinInterruptHandlers[pin].fn(); + } } } } while(++pin= ARDUHAL_LOG_LEVEL_INFO) && (defined ENABLE_I2C_DEBUG_BUFFER) +#define INTBUFFMAX 64 +#define FIFOMAX 512 +static uint32_t intBuff[INTBUFFMAX][3][2]; +static uint32_t intPos[2]= {0,0}; +static uint16_t fifoBuffer[FIFOMAX]; +static uint16_t fifoPos = 0; +#endif + +// start from tools/sdk/include/soc/soc/i2c_struct.h + +typedef union { + struct { + uint32_t byte_num: 8; /*Byte_num represent the number of data need to be send or data need to be received.*/ + uint32_t ack_en: 1; /*ack_check_en ack_exp and ack value are used to control the ack bit.*/ + uint32_t ack_exp: 1; /*ack_check_en ack_exp and ack value are used to control the ack bit.*/ + uint32_t ack_val: 1; /*ack_check_en ack_exp and ack value are used to control the ack bit.*/ + uint32_t op_code: 3; /*op_code is the command 0:RSTART 1:WRITE 2:READ 3:STOP . 4:END.*/ + uint32_t reserved14: 17; + uint32_t done: 1; /*When command0 is done in I2C Master mode this bit changes to high level.*/ + }; + uint32_t val; +} I2C_COMMAND_t; + +typedef union { + struct { + uint32_t rx_fifo_full_thrhd: 5; + uint32_t tx_fifo_empty_thrhd:5; //Config tx_fifo empty threhd value when using apb fifo access * / + uint32_t nonfifo_en: 1; //Set this bit to enble apb nonfifo access. * / + uint32_t fifo_addr_cfg_en: 1; //When this bit is set to 1 then the byte after address represent the offset address of I2C Slave's ram. * / + uint32_t rx_fifo_rst: 1; //Set this bit to reset rx fifo when using apb fifo access. * / + // chuck while this bit is 1, the RX fifo is held in REST, Toggle it * / + uint32_t tx_fifo_rst: 1; //Set this bit to reset tx fifo when using apb fifo access. * / + // chuck while this bit is 1, the TX fifo is held in REST, Toggle it * / + uint32_t nonfifo_rx_thres: 6; //when I2C receives more than nonfifo_rx_thres data it will produce rx_send_full_int_raw interrupt and update the current offset address of the receiving data.* / + uint32_t nonfifo_tx_thres: 6; //when I2C sends more than nonfifo_tx_thres data it will produce tx_send_empty_int_raw interrupt and update the current offset address of the sending data. * / + uint32_t reserved26: 6; + }; + uint32_t val; +} I2C_FIFO_CONF_t; + +typedef union { + struct { + uint32_t rx_fifo_start_addr: 5; /*This is the offset address of the last receiving data as described in nonfifo_rx_thres_register.*/ + uint32_t rx_fifo_end_addr: 5; /*This is the offset address of the first receiving data as described in nonfifo_rx_thres_register.*/ + uint32_t tx_fifo_start_addr: 5; /*This is the offset address of the first sending data as described in nonfifo_tx_thres register.*/ + uint32_t tx_fifo_end_addr: 5; /*This is the offset address of the last sending data as described in nonfifo_tx_thres register.*/ + uint32_t reserved20: 12; + }; + uint32_t val; + } I2C_FIFO_ST_t; + +// end from tools/sdk/include/soc/soc/i2c_struct.h + +// sync between dispatch(i2cProcQueue) and worker(i2c_isr_handler_default) +typedef enum { + //I2C_NONE=0, + I2C_STARTUP=1, + I2C_RUNNING, + I2C_DONE +} I2C_STAGE_t; + +typedef enum { + I2C_NONE=0, + I2C_MASTER, + I2C_SLAVE, + I2C_MASTERSLAVE +} I2C_MODE_t; + +// internal Error condition +typedef enum { + // I2C_NONE=0, + I2C_OK=1, + I2C_ERROR, + I2C_ADDR_NAK, + I2C_DATA_NAK, + I2C_ARBITRATION, + I2C_TIMEOUT +} I2C_ERROR_t; + +// i2c_event bits for EVENTGROUP bits +// needed to minimize change events, FreeRTOS Daemon overload, so ISR will only set values +// on Exit. Dispatcher will set bits for each dq before/after ISR completion +#define EVENT_ERROR_NAK (BIT(0)) +#define EVENT_ERROR (BIT(1)) +#define EVENT_ERROR_BUS_BUSY (BIT(2)) +#define EVENT_RUNNING (BIT(3)) +#define EVENT_DONE (BIT(4)) +#define EVENT_IN_END (BIT(5)) +#define EVENT_ERROR_PREV (BIT(6)) +#define EVENT_ERROR_TIMEOUT (BIT(7)) +#define EVENT_ERROR_ARBITRATION (BIT(8)) +#define EVENT_ERROR_DATA_NAK (BIT(9)) +#define EVENT_MASK 0x3F + +// control record for each dq entry +typedef union { + struct { + uint32_t addr: 16; // I2C address, if 10bit must have 0x7800 mask applied, else 8bit + uint32_t mode: 1; // transaction direction 0 write, 1 read + uint32_t stop: 1; // sendStop 0 no, 1 yes + uint32_t startCmdSent: 1; // START cmd has been added to command[] + uint32_t addrCmdSent: 1; // addr WRITE cmd has been added to command[] + uint32_t dataCmdSent: 1; // all necessary DATA(READ/WRITE) cmds added to command[] + uint32_t stopCmdSent: 1; // completed all necessary commands + uint32_t addrReq: 2; // number of addr bytes need to send address + uint32_t addrSent: 2; // number of addr bytes added to FIFO + uint32_t reserved_31: 6; + }; + uint32_t val; +} I2C_DATA_CTRL_t; + +// individual dq element +typedef struct { + uint8_t *data; // data pointer for read/write buffer + uint16_t length; // size of data buffer + uint16_t position; // current position for next char in buffer (lock, portMAX_DELAY) != pdPASS) -#define I2C_MUTEX_UNLOCK() xSemaphoreGive(i2c->lock) +#define I2C_MUTEX_LOCK() do {} while (xSemaphoreTakeRecursive(i2c->lock, portMAX_DELAY) != pdPASS) +#define I2C_MUTEX_UNLOCK() xSemaphoreGiveRecursive(i2c->lock) static i2c_t _i2c_bus_array[2] = { - {(volatile i2c_dev_t *)(DR_REG_I2C_EXT_BASE_FIXED), NULL, 0}, - {(volatile i2c_dev_t *)(DR_REG_I2C1_EXT_BASE_FIXED), NULL, 1} + {(volatile i2c_dev_t *)(DR_REG_I2C_EXT_BASE_FIXED), NULL, 0, -1, -1, I2C_NONE,I2C_NONE,I2C_ERROR_OK,NULL,NULL,NULL,0,0,0,0,0,0}, + {(volatile i2c_dev_t *)(DR_REG_I2C1_EXT_BASE_FIXED), NULL, 1, -1, -1,I2C_NONE,I2C_NONE,I2C_ERROR_OK,NULL,NULL,NULL,0,0,0,0,0,0} }; #endif -i2c_err_t i2cAttachSCL(i2c_t * i2c, int8_t scl) +/* + * index - command index (0 to 15) + * op_code - is the command + * byte_num - This register is to store the amounts of data that is read and written. byte_num in RSTART, STOP, END is null. + * ack_val - Each data byte is terminated by an ACK bit used to set the bit level. + * ack_exp - This bit is to set an expected ACK value for the transmitter. + * ack_check - This bit is to decide whether the transmitter checks ACK bit. 1 means yes and 0 means no. + * */ + + +/* Stickbreaker ISR mode debug support + */ +static void IRAM_ATTR i2cDumpCmdQueue(i2c_t *i2c) { - if(i2c == NULL){ - return I2C_ERROR_DEV; +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_ERROR)&&(defined ENABLE_I2C_DEBUG_BUFFER) + static const char * const cmdName[] ={"RSTART","WRITE","READ","STOP","END"}; + uint8_t i=0; + while(i<16) { + I2C_COMMAND_t c; + c.val=i2c->dev->command[i].val; + log_e("[%2d]\t%c\t%s\tval[%d]\texp[%d]\ten[%d]\tbytes[%d]",i,(c.done?'Y':'N'), + cmdName[c.op_code], + c.ack_val, + c.ack_exp, + c.ack_en, + c.byte_num); + i++; } - pinMode(scl, OUTPUT_OPEN_DRAIN | PULLUP); - pinMatrixOutAttach(scl, I2C_SCL_IDX(i2c->num), false, false); - pinMatrixInAttach(scl, I2C_SCL_IDX(i2c->num), false); - return I2C_ERROR_OK; +#endif } -i2c_err_t i2cDetachSCL(i2c_t * i2c, int8_t scl) +/* Stickbreaker ISR mode debug support + */ +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) +static void i2cDumpDqData(i2c_t * i2c) { - if(i2c == NULL){ - return I2C_ERROR_DEV; +#if defined (ENABLE_I2C_DEBUG_BUFFER) + uint16_t a=0; + char buff[140]; + I2C_DATA_QUEUE_t *tdq; + int digits=0,lenDigits=0; + a = i2c->queueCount; + while(a>0) { + digits++; + a /= 10; } - pinMatrixOutDetach(scl, false, false); - pinMatrixInDetach(I2C_SCL_IDX(i2c->num), false, false); - pinMode(scl, INPUT); - return I2C_ERROR_OK; + while(aqueueCount) { // find maximum number of len decimal digits for formatting + if (i2c->dq[a].length > lenDigits ) lenDigits = i2c->dq[a].length; + a++; + } + a=0; + while(lenDigits>0){ + a++; + lenDigits /= 10; + } + lenDigits = a; + a = 0; + while(aqueueCount) { + tdq=&i2c->dq[a]; + char buf1[10],buf2[10]; + sprintf(buf1,"%0*d",lenDigits,tdq->length); + sprintf(buf2,"%0*d",lenDigits,tdq->position); + log_i("[%0*d] %sbit %x %c %s buf@=%p, len=%s, pos=%s, ctrl=%d%d%d%d%d",digits,a, + (tdq->ctrl.addr>0x100)?"10":"7", + (tdq->ctrl.addr>0x100)?(((tdq->ctrl.addr&0x600)>>1)|(tdq->ctrl.addr&0xff)):(tdq->ctrl.addr>>1), + (tdq->ctrl.mode)?'R':'W', + (tdq->ctrl.stop)?"STOP":"", + tdq->data, + buf1,buf2, + tdq->ctrl.startCmdSent,tdq->ctrl.addrCmdSent,tdq->ctrl.dataCmdSent,(tdq->ctrl.stop)?tdq->ctrl.stopCmdSent:0,tdq->ctrl.addrSent + ); + uint16_t offset = 0; + while(offsetlength) { + memset(buff,' ',140); + buff[139]='\0'; + uint16_t i = 0,j; + j=sprintf(buff,"0x%04x: ",offset); + while((i<32)&&(offset < tdq->length)) { + char ch = tdq->data[offset]; + sprintf((char*)&buff[(i*3)+41],"%02x ",ch); + if((ch<32)||(ch>126)) { + ch='.'; + } + j+=sprintf((char*)&buff[j],"%c",ch); + buff[j]=' '; + i++; + offset++; + } + log_i("%s",buff); + } + a++; + } +#else + log_i("Debug Buffer not Enabled"); +#endif } - -i2c_err_t i2cAttachSDA(i2c_t * i2c, int8_t sda) +#endif +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO +static void i2cDumpI2c(i2c_t * i2c) { - if(i2c == NULL){ - return I2C_ERROR_DEV; + log_e("i2c=%p",i2c); + log_i("dev=%p date=%p",i2c->dev,i2c->dev->date); +#if !CONFIG_DISABLE_HAL_LOCKS + log_i("lock=%p",i2c->lock); +#endif + log_i("num=%d",i2c->num); + log_i("mode=%d",i2c->mode); + log_i("stage=%d",i2c->stage); + log_i("error=%d",i2c->error); + log_i("event=%p bits=%x",i2c->i2c_event,(i2c->i2c_event)?xEventGroupGetBits(i2c->i2c_event):0); + log_i("intr_handle=%p",i2c->intr_handle); + log_i("dq=%p",i2c->dq); + log_i("queueCount=%d",i2c->queueCount); + log_i("queuePos=%d",i2c->queuePos); + log_i("errorByteCnt=%d",i2c->errorByteCnt); + log_i("errorQueue=%d",i2c->errorQueue); + log_i("debugFlags=0x%08X",i2c->debugFlags); + if(i2c->dq) { + i2cDumpDqData(i2c); } - pinMode(sda, OUTPUT_OPEN_DRAIN | PULLUP); - pinMatrixOutAttach(sda, I2C_SDA_IDX(i2c->num), false, false); - pinMatrixInAttach(sda, I2C_SDA_IDX(i2c->num), false); - return I2C_ERROR_OK; } +#endif -i2c_err_t i2cDetachSDA(i2c_t * i2c, int8_t sda) +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) +static void i2cDumpInts(uint8_t num) { - if(i2c == NULL){ - return I2C_ERROR_DEV; +#if defined (ENABLE_I2C_DEBUG_BUFFER) + uint32_t b; + log_i("%u row\tcount\tINTR\tTX\tRX\tTick ",num); + for(uint32_t a=1; a<=INTBUFFMAX; a++) { + b=(a+intPos[num])%INTBUFFMAX; + if(intBuff[b][0][num]!=0) { + log_i("[%02d]\t0x%04x\t0x%04x\t0x%04x\t0x%04x\t0x%08x",b,((intBuff[b][0][num]>>16)&0xFFFF),(intBuff[b][0][num]&0xFFFF),((intBuff[b][1][num]>>16)&0xFFFF),(intBuff[b][1][num]&0xFFFF),intBuff[b][2][num]); + } } - pinMatrixOutDetach(sda, false, false); - pinMatrixInDetach(I2C_SDA_IDX(i2c->num), false, false); - pinMode(sda, INPUT); - return I2C_ERROR_OK; +#else + log_i("Debug Buffer not Enabled"); +#endif } +#endif -/* - * index - command index (0 to 15) - * op_code - is the command - * byte_num - This register is to store the amounts of data that is read and written. byte_num in RSTART, STOP, END is null. - * ack_val - Each data byte is terminated by an ACK bit used to set the bit level. - * ack_exp - This bit is to set an expected ACK value for the transmitter. - * ack_check - This bit is to decide whether the transmitter checks ACK bit. 1 means yes and 0 means no. - * */ -void i2cSetCmd(i2c_t * i2c, uint8_t index, uint8_t op_code, uint8_t byte_num, bool ack_val, bool ack_exp, bool ack_check) -{ - i2c->dev->command[index].val = 0; - i2c->dev->command[index].ack_en = ack_check; - i2c->dev->command[index].ack_exp = ack_exp; - i2c->dev->command[index].ack_val = ack_val; - i2c->dev->command[index].byte_num = byte_num; - i2c->dev->command[index].op_code = op_code; +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO)&&(defined ENABLE_I2C_DEBUG_BUFFER) +static void IRAM_ATTR i2cDumpStatus(i2c_t * i2c){ + typedef union { + struct { + uint32_t ack_rec: 1; /*This register stores the value of ACK bit.*/ + uint32_t slave_rw: 1; /*when in slave mode 1:master read slave 0: master write slave.*/ + uint32_t time_out: 1; /*when I2C takes more than time_out_reg clocks to receive a data then this register changes to high level.*/ + uint32_t arb_lost: 1; /*when I2C lost control of SDA line this register changes to high level.*/ + uint32_t bus_busy: 1; /*1:I2C bus is busy transferring data. 0:I2C bus is in idle state.*/ + uint32_t slave_addressed: 1; /*when configured as i2c slave and the address send by master is equal to slave's address then this bit will be high level.*/ + uint32_t byte_trans: 1; /*This register changes to high level when one byte is transferred.*/ + uint32_t reserved7: 1; + uint32_t rx_fifo_cnt: 6; /*This register represent the amount of data need to send.*/ + uint32_t reserved14: 4; + uint32_t tx_fifo_cnt: 6; /*This register stores the amount of received data in ram.*/ + uint32_t scl_main_state_last: 3; /*This register stores the value of state machine for i2c module. 3'h0: SCL_MAIN_IDLE 3'h1: SCL_ADDRESS_SHIFT 3'h2: SCL_ACK_ADDRESS 3'h3: SCL_RX_DATA 3'h4 SCL_TX_DATA 3'h5:SCL_SEND_ACK 3'h6:SCL_WAIT_ACK*/ + uint32_t reserved27: 1; + uint32_t scl_state_last: 3; /*This register stores the value of state machine to produce SCL. 3'h0: SCL_IDLE 3'h1:SCL_START 3'h2:SCL_LOW_EDGE 3'h3: SCL_LOW 3'h4:SCL_HIGH_EDGE 3'h5:SCL_HIGH 3'h6:SCL_STOP*/ + uint32_t reserved31: 1; + }; + uint32_t val; + } status_reg; + + status_reg sr; + sr.val= i2c->dev->status_reg.val; + + log_i("ack(%d) sl_rw(%d) to(%d) arb(%d) busy(%d) sl(%d) trans(%d) rx(%d) tx(%d) sclMain(%d) scl(%d)",sr.ack_rec,sr.slave_rw,sr.time_out,sr.arb_lost,sr.bus_busy,sr.slave_addressed,sr.byte_trans, sr.rx_fifo_cnt, sr.tx_fifo_cnt,sr.scl_main_state_last, sr.scl_state_last); } +#endif -void i2cResetCmd(i2c_t * i2c) { - uint8_t i; - for(i=0;i<16;i++){ - i2c->dev->command[i].val = 0; - } +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO)&&(defined ENABLE_I2C_DEBUG_BUFFER) +static void i2cDumpFifo(i2c_t * i2c){ +char buf[64]; +uint16_t k = 0; +uint16_t i = fifoPos+1; + i %=FIFOMAX; +while((fifoBuffer[i]==0)&&(i!=fifoPos)){ + i++; + i %=FIFOMAX; } - -void i2cResetFiFo(i2c_t * i2c) { - i2c->dev->fifo_conf.tx_fifo_rst = 1; - i2c->dev->fifo_conf.tx_fifo_rst = 0; - i2c->dev->fifo_conf.rx_fifo_rst = 1; - i2c->dev->fifo_conf.rx_fifo_rst = 0; +if(i != fifoPos){// actual data + do{ + if(fifoBuffer[i] & 0x8000){ // address byte + if(fifoBuffer[i] & 0x100) { // read + if(fifoBuffer[i] & 0x1) { // valid read dev id + k+= sprintf(&buf[k],"READ 0x%02X",(fifoBuffer[i]&0xff)>>1); + } else { // invalid read dev id + k+= sprintf(&buf[k],"Bad READ 0x%02X",(fifoBuffer[i]&0xff)); + } + } else { // write + if(fifoBuffer[i] & 0x1) { // bad write dev id + k+= sprintf(&buf[k],"bad WRITE 0x%02X",(fifoBuffer[i]&0xff)); + } else { // good Write + k+= sprintf(&buf[k],"WRITE 0x%02X",(fifoBuffer[i]&0xff)>>1); + } + } + } else k += sprintf(&buf[k],"% 4X ",fifoBuffer[i]); + + i++; + i %= FIFOMAX; + bool outBuffer=false; + if( fifoBuffer[i] & 0x8000){ + outBuffer=true; + k=0; + } + if((outBuffer)||(k>50)||(i==fifoPos)) log_i("%s",buf); + outBuffer = false; + if(k>50) { + k=sprintf(buf,"-> "); + } + }while( i!= fifoPos); } +} +#endif -i2c_err_t i2cWrite(i2c_t * i2c, uint16_t address, bool addr_10bit, uint8_t * data, uint16_t len, bool sendStop) -{ - int i; - uint16_t index = 0; - uint16_t dataLen = len + (addr_10bit?2:1); - address = (address << 1); - - if(i2c == NULL){ - return I2C_ERROR_DEV; +static void IRAM_ATTR i2cTriggerDumps(i2c_t * i2c, uint8_t trigger, const char locus[]){ +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO)&&(defined ENABLE_I2C_DEBUG_BUFFER) + if( trigger ){ + log_i("%s",locus); + if(trigger & 1) i2cDumpI2c(i2c); + if(trigger & 2) i2cDumpInts(i2c->num); + if(trigger & 4) i2cDumpCmdQueue(i2c); + if(trigger & 8) i2cDumpStatus(i2c); + if(trigger & 16) i2cDumpFifo(i2c); } +#endif +} + // end of debug support routines + +/* Start of CPU Clock change Support +*/ + +static void i2cApbChangeCallback(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb){ + i2c_t* i2c = (i2c_t*) arg; // recover data + if(i2c == NULL) { // point to peripheral control block does not exits + return; + } + uint32_t oldFreq=0; + switch(ev_type){ + case APB_BEFORE_CHANGE : + if(new_apb < 3000000) {// too slow + log_e("apb speed %d too slow",new_apb); + break; + } + I2C_MUTEX_LOCK(); // lock will spin until current transaction is completed + break; + case APB_AFTER_CHANGE : + oldFreq = (i2c->dev->scl_low_period.period+i2c->dev->scl_high_period.period); //read old apbCycles + if(oldFreq>0) { // was configured with value + oldFreq = old_apb / oldFreq; + i2cSetFrequency(i2c,oldFreq); + } + I2C_MUTEX_UNLOCK(); + break; + default : + log_e("unk ev %u",ev_type); + I2C_MUTEX_UNLOCK(); + } + return; +} +/* End of CPU Clock change Support +*/ +static void IRAM_ATTR i2cSetCmd(i2c_t * i2c, uint8_t index, uint8_t op_code, uint8_t byte_num, bool ack_val, bool ack_exp, bool ack_check) +{ + I2C_COMMAND_t cmd; + cmd.val=0; + cmd.ack_en = ack_check; + cmd.ack_exp = ack_exp; + cmd.ack_val = ack_val; + cmd.byte_num = byte_num; + cmd.op_code = op_code; + i2c->dev->command[index].val = cmd.val; +} + - I2C_MUTEX_LOCK(); - - if (i2c->dev->status_reg.bus_busy == 1) - { - log_e( "Busy Timeout! Addr: %x", address >> 1 ); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_BUSY; +static void IRAM_ATTR fillCmdQueue(i2c_t * i2c, bool INTS) +{ + /* this function is called on initial i2cProcQueue() or when a I2C_END_DETECT_INT occurs + */ + uint16_t cmdIdx = 0; + uint16_t qp = i2c->queuePos; // all queues before queuePos have been completely processed, + // so look start by checking the 'current queue' so see if it needs commands added to + // hardware peripheral command list. walk through each queue entry until all queues have been + // checked + bool done; + bool needMoreCmds = false; + bool ena_rx=false; // if we add a read op, better enable Rx_Fifo IRQ + bool ena_tx=false; // if we add a Write op, better enable TX_Fifo IRQ + + while(!needMoreCmds&&(qp < i2c->queueCount)) { // check if more possible cmds + if(i2c->dq[qp].ctrl.stopCmdSent) {// marks that all required cmds[] have been added to peripheral + qp++; + } else { + needMoreCmds=true; + } } + //log_e("needMoreCmds=%d",needMoreCmds); + done=(!needMoreCmds)||(cmdIdx>14); - while(dataLen) { - uint8_t willSend = (dataLen > 32)?32:dataLen; - uint8_t dataSend = willSend; + while(!done) { // fill the command[] until either 0..14 filled or out of cmds and last cmd is STOP + //CMD START + I2C_DATA_QUEUE_t *tdq=&i2c->dq[qp]; // simpler coding - i2cResetFiFo(i2c); - i2cResetCmd(i2c); - //Clear Interrupts - i2c->dev->int_clr.val = 0xFFFFFFFF; + if((!tdq->ctrl.startCmdSent) && (cmdIdx < 14)) { // has this dq element's START command been added? + // (cmdIdx<14) because a START op cannot directly precede an END op, else a time out cascade occurs + i2cSetCmd(i2c, cmdIdx++, I2C_CMD_RSTART, 0, false, false, false); + tdq->ctrl.startCmdSent=1; + } - //CMD START - i2cSetCmd(i2c, 0, I2C_CMD_RSTART, 0, false, false, false); - - //CMD WRITE(ADDRESS + DATA) - if(!index) { - if(addr_10bit){// address is leftshifted with Read/Write bit set - i2c->dev->fifo_data.data = (((address >> 8) & 0x6) | 0xF0); // send a9:a8 plus 1111 0xxW mask - i2c->dev->fifo_data.data = ((address >> 1) & 0xFF); // send a7:a0, remove W bit (7bit address style) - dataSend -= 2; - } - else { // 7bit address - i2c->dev->fifo_data.data = address & 0xFF; - dataSend--; + //CMD WRITE ADDRESS + if((!done)&&(tdq->ctrl.startCmdSent)) { // have to leave room for continue(END), and START must have been sent! + if(!tdq->ctrl.addrCmdSent) { + i2cSetCmd(i2c, cmdIdx++, I2C_CMD_WRITE, tdq->ctrl.addrReq, false, false, true); //load address in cmdlist, validate (low) ack + tdq->ctrl.addrCmdSent=1; + done =(cmdIdx>14); + ena_tx=true; // tx Data necessary } } - i = 0; - while(idev->fifo_data.val = data[index++]; - while(i2c->dev->status_reg.tx_fifo_cnt < i); - } - i2cSetCmd(i2c, 1, I2C_CMD_WRITE, willSend, false, false, true); - dataLen -= willSend; - - //CMD STOP or CMD END if there is more data - if(dataLen || !sendStop) { - i2cSetCmd(i2c, 2, I2C_CMD_END, 0, false, false, false); - } else if(sendStop) { - i2cSetCmd(i2c, 2, I2C_CMD_STOP, 0, false, false, false); - } - - //START Transmission - i2c->dev->ctr.trans_start = 1; - - //WAIT Transmission - uint32_t startAt = millis(); - while(1) { - //have been looping for too long - if((millis() - startAt)>50){ - log_e("Timeout! Addr: %x", address >> 1); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_BUS; + + /* Can I have another Sir? + ALL CMD queues must be terminated with either END or STOP. + + If END is used, when refilling the cmd[] next time, no entries from END to [15] can be used. + AND the cmd[] must be filled starting at [0] with commands. Either fill all 15 [0]..[14] and leave the + END in [15] or include a STOP in one of the positions [0]..[14]. Any entries after a STOP are IGNORED by the StateMachine. + The END operation does not complete until ctr->trans_start=1 has been issued. + + So, only refill from [0]..[14], leave [15] for a continuation(END) if necessary. + As a corollary, once END exists in [15], you do not need to overwrite it for the + next continuation. It is never modified. But, I update it every time because it might + actually be the first time! + + 23NOV17 START cannot proceed END. if START is in[14], END cannot be in [15]. + So, if END is moved to [14], [14] and [15] can no longer be used for anything other than END. + If a START is found in [14] then a prior READ or WRITE must be expanded so that there is no START element in [14]. + */ + + if((!done)&&(tdq->ctrl.addrCmdSent)) { //room in command[] for at least One data (read/Write) cmd + uint8_t blkSize=0; // max is 255 + while(( tdq->cmdBytesNeeded > tdq->ctrl.mode )&&(!done )) { // more bytes needed and room in cmd queue, leave room for END + blkSize = (tdq->cmdBytesNeeded > 255)?255:(tdq->cmdBytesNeeded - tdq->ctrl.mode); // Last read cmd needs different ACK setting, so leave 1 byte remainder on reads + tdq->cmdBytesNeeded -= blkSize; + if(tdq->ctrl.mode==1) { //read mode + i2cSetCmd(i2c, (cmdIdx)++, I2C_CMD_READ, blkSize,false,false,false); // read cmd, this can't be the last read. + ena_rx=true; // need to enable rxFifo IRQ + } else { // write + i2cSetCmd(i2c, cmdIdx++, I2C_CMD_WRITE, blkSize, false, false, true); // check for Nak + ena_tx=true; // need to enable txFifo IRQ + } + done = cmdIdx>14; //have to leave room for END } - //Bus failed (maybe check for this while waiting? - if(i2c->dev->int_raw.arbitration_lost) { - log_e("Bus Fail! Addr: %x", address >> 1); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_BUS; + if(!done) { // buffer is not filled completely + if((tdq->ctrl.mode==1)&&(tdq->cmdBytesNeeded==1)) { //special last read byte NAK + i2cSetCmd(i2c, (cmdIdx)++, I2C_CMD_READ, 1,true,false,false); + // send NAK to mark end of read + tdq->cmdBytesNeeded=0; + done = cmdIdx > 14; + ena_rx=true; + } } - //Bus timeout - if(i2c->dev->int_raw.time_out) { - log_e("Bus Timeout! Addr: %x", address >> 1); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_TIMEOUT; + tdq->ctrl.dataCmdSent=(tdq->cmdBytesNeeded==0); // enough command[] to send all data + + if((!done)&&(tdq->ctrl.dataCmdSent)) { // possibly add stop + if(!tdq->ctrl.stopCmdSent){ + if(tdq->ctrl.stop) { //send a stop + i2cSetCmd(i2c, (cmdIdx)++,I2C_CMD_STOP,0,false,false,false); + done = cmdIdx > 14; + } + tdq->ctrl.stopCmdSent = 1; + } } + } + + if((cmdIdx==14)&&(!tdq->ctrl.startCmdSent)) { + // START would have preceded END, causes SM TIMEOUT + // need to stretch out a prior WRITE or READ to two Command[] elements + done = false; // reuse it + uint16_t i = 13; // start working back until a READ/WRITE has >1 numBytes + cmdIdx =15; + while(!done) { + i2c->dev->command[i+1].val = i2c->dev->command[i].val; // push it down + if (((i2c->dev->command[i].op_code == 1)||(i2c->dev->command[i].op_code==2))) { + /* add a dummy read/write cmd[] with num_bytes set to zero,just a place holder in the cmd[]list + */ + i2c->dev->command[i].byte_num = 0; + done = true; - //Transmission did not finish and ACK_ERR is set - if(i2c->dev->int_raw.ack_err) { - log_w("Ack Error! Addr: %x", address >> 1); - while((i2c->dev->status_reg.bus_busy) && ((millis() - startAt)<50)); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_ACK; + } else { + if(i > 0) { + i--; + } else { // unable to stretch, fatal + log_e("invalid CMD[] layout Stretch Failed"); + i2cDumpCmdQueue(i2c); + done = true; + } + } } - if((sendStop && i2c->dev->command[2].done) || !i2c->dev->status_reg.bus_busy){ - break; + } + + + if(cmdIdx==15) { //need continuation, even if STOP is in 14, it will not matter + // cmd buffer is almost full, Add END as a continuation feature + i2cSetCmd(i2c, (cmdIdx)++,I2C_CMD_END, 0,false,false,false); + i2c->dev->int_ena.end_detect=1; + i2c->dev->int_clr.end_detect=1; + done = true; + } + + if(!done) { + if(tdq->ctrl.stopCmdSent) { // this queue element has been completely added to command[] buffer + qp++; + if(qp < i2c->queueCount) { + tdq = &i2c->dq[qp]; + } else { + done = true; + } } } + }// while(!done) + if(INTS) { // don't want to prematurely enable fifo ints until ISR is ready to handle them. + if(ena_rx) { + i2c->dev->int_ena.rx_fifo_full = 1; + } + if(ena_tx) { + i2c->dev->int_ena.tx_fifo_empty = 1; + } } - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_OK; } -uint8_t inc( uint8_t* index ) +static void IRAM_ATTR fillTxFifo(i2c_t * i2c) { - uint8_t i = index[ 0 ]; - if (++index[ 0 ] == COMMAND_BUFFER_LENGTH) - { - index[ 0 ] = 0; + /* + 12/01/2017 The Fifo's are independent, 32 bytes of tx and 32 bytes of Rx. + overlap is not an issue, just keep them full/empty the status_reg.xx_fifo_cnt + tells the truth. And the INT's fire correctly + */ + uint16_t a=i2c->queuePos; // currently executing dq, + bool full=!(i2c->dev->status_reg.tx_fifo_cnt<31); + uint8_t cnt; + bool rxQueueEncountered = false; + while((a < i2c->queueCount) && !full) { + I2C_DATA_QUEUE_t *tdq = &i2c->dq[a]; + cnt=0; + // add to address to fifo ctrl.addr already has R/W bit positioned correctly + if(tdq->ctrl.addrSent < tdq->ctrl.addrReq) { // need to send address bytes + if(tdq->ctrl.addrReq==2) { //10bit + if(tdq->ctrl.addrSent==0) { //10bit highbyte needs sent + if(!full) { // room in fifo + i2c->dev->fifo_data.val = ((tdq->ctrl.addr>>8)&0xFF); + cnt++; + tdq->ctrl.addrSent=1; //10bit highbyte sent + } + } + full=!(i2c->dev->status_reg.tx_fifo_cnt<31); + + if(tdq->ctrl.addrSent==1) { //10bit Lowbyte needs sent + if(!full) { // room in fifo + i2c->dev->fifo_data.val = tdq->ctrl.addr&0xFF; + cnt++; + tdq->ctrl.addrSent=2; //10bit lowbyte sent + } + } + } else { // 7bit} + if(tdq->ctrl.addrSent==0) { // 7bit Lowbyte needs sent + if(!full) { // room in fifo + i2c->dev->fifo_data.val = tdq->ctrl.addr&0xFF; + cnt++; + tdq->ctrl.addrSent=1; // 7bit lowbyte sent +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) && (defined ENABLE_I2C_DEBUG_BUFFER) + uint16_t a = 0x8000 | tdq->ctrl.addr | (tdq->ctrl.mode<<8); + fifoBuffer[fifoPos++] = a; + fifoPos %= FIFOMAX; +#endif + } + } + } + } + // add write data to fifo + if(tdq->ctrl.mode==0) { // write + if(tdq->ctrl.addrSent == tdq->ctrl.addrReq) { //address has been sent, is Write Mode! + uint32_t moveCnt = 32 - i2c->dev->status_reg.tx_fifo_cnt; // how much room in txFifo? + while(( moveCnt>0)&&(tdq->position < tdq->length)) { +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) && (defined ENABLE_I2C_DEBUG_BUFFER) + fifoBuffer[fifoPos++] = tdq->data[tdq->position]; + fifoPos %= FIFOMAX; +#endif + i2c->dev->fifo_data.val = tdq->data[tdq->position++]; + cnt++; + moveCnt--; + + } + } + } else { // read Queue Encountered, can't update QueuePos past this point, emptyRxfifo will do it + if( ! rxQueueEncountered ) { + rxQueueEncountered = true; + if(a > i2c->queuePos){ + i2c->queuePos = a; + } + } + } +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) && (defined ENABLE_I2C_DEBUG_BUFFER) + + // update debug buffer tx counts + cnt += intBuff[intPos[i2c->num]][1][i2c->num]>>16; + intBuff[intPos[i2c->num]][1][i2c->num] = (intBuff[intPos[i2c->num]][1][i2c->num]&0xFFFF)|(cnt<<16); + +#endif + full=!(i2c->dev->status_reg.tx_fifo_cnt<31); + if(!full) { + a++; // check next buffer for address tx, or write data + } + } + + if(a >= i2c->queueCount ) { // disable TX IRQ, all tx Data has been queued + i2c->dev->int_ena.tx_fifo_empty= 0; } - return i; + i2c->dev->int_clr.tx_fifo_empty=1; } -i2c_err_t i2cRead(i2c_t * i2c, uint16_t address, bool addr_10bit, uint8_t * data, uint16_t len, bool sendStop) + +static void IRAM_ATTR emptyRxFifo(i2c_t * i2c) { - address = (address << 1) | 1; - uint8_t addrLen = (addr_10bit?2:1); - uint8_t amountRead[16]; - uint16_t index = 0; - uint8_t cmdIdx = 0, currentCmdIdx = 0, nextCmdCount; - bool stopped = false, isEndNear = false; - uint8_t willRead; - - if(i2c == NULL){ - return I2C_ERROR_DEV; - } + uint32_t d, cnt=0, moveCnt; + + moveCnt = i2c->dev->status_reg.rx_fifo_cnt;//no need to check the reg until this many are read - I2C_MUTEX_LOCK(); + while((moveCnt > 0)&&(i2c->queuePos < i2c->queueCount)){ // data to move - if (i2c->dev->status_reg.bus_busy == 1) - { - log_w( "Busy Timeout! Addr: %x", address >> 1 ); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_BUSY; - } + I2C_DATA_QUEUE_t *tdq =&i2c->dq[i2c->queuePos]; //short cut - i2cResetFiFo(i2c); - i2cResetCmd(i2c); + while((tdq->position >= tdq->length)&&( i2c->queuePos < i2c->queueCount)){ // find were to store + i2c->queuePos++; + tdq = &i2c->dq[i2c->queuePos]; + } + + if(i2c->queuePos >= i2c->queueCount){ // bad stuff, rx data but no place to put it! + log_e("no Storage location for %d",moveCnt); + // discard + while(moveCnt>0){ + d = i2c->dev->fifo_data.val; + moveCnt--; + cnt++; + } + break; + } + + if(tdq->ctrl.mode == 1){ // read command + if(moveCnt > (tdq->length - tdq->position)) { //make sure they go in this dq + // part of these reads go into the next dq + moveCnt = (tdq->length - tdq->position); + } + } else {// error + log_e("RxEmpty(%d) call on TxBuffer? dq=%d",moveCnt,i2c->queuePos); + // discard + while(moveCnt>0){ + d = i2c->dev->fifo_data.val; + moveCnt--; + cnt++; + } + break; + } - //CMD START - i2cSetCmd(i2c, cmdIdx++, I2C_CMD_RSTART, 0, false, false, false); + while(moveCnt > 0) { // store data + d = i2c->dev->fifo_data.val; + moveCnt--; + cnt++; + tdq->data[tdq->position++] = (d&0xFF); + } - //CMD WRITE ADDRESS - if (addr_10bit) { // address is left-shifted with Read/Write bit set - i2c->dev->fifo_data.data = (((address >> 8) & 0x6) | 0xF1); // send a9:a8 plus 1111 0xxR mask - i2c->dev->fifo_data.data = ((address >> 1) & 0xFF); // send a7:a0, remove R bit (7bit address style) + moveCnt = i2c->dev->status_reg.rx_fifo_cnt; //any more out there? } - else { // 7bit address - i2c->dev->fifo_data.data = address & 0xFF; + +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO)&& (defined ENABLE_I2C_DEBUG_BUFFER) + // update Debug rxCount + cnt += (intBuff[intPos[i2c->num]][1][i2c->num])&0xffFF; + intBuff[intPos[i2c->num]][1][i2c->num] = (intBuff[intPos[i2c->num]][1][i2c->num]&0xFFFF0000)|cnt; +#endif +} + +static void IRAM_ATTR i2cIsrExit(i2c_t * i2c,const uint32_t eventCode,bool Fatal) +{ + + switch(eventCode) { + case EVENT_DONE: + i2c->error = I2C_OK; + break; + case EVENT_ERROR_NAK : + i2c->error =I2C_ADDR_NAK; + break; + case EVENT_ERROR_DATA_NAK : + i2c->error =I2C_DATA_NAK; + break; + case EVENT_ERROR_TIMEOUT : + i2c->error = I2C_TIMEOUT; + break; + case EVENT_ERROR_ARBITRATION: + i2c->error = I2C_ARBITRATION; + break; + default : + i2c->error = I2C_ERROR; + } + uint32_t exitCode = EVENT_DONE | eventCode |(Fatal?EVENT_ERROR:0); + if((i2c->queuePos < i2c->queueCount) && (i2c->dq[i2c->queuePos].ctrl.mode == 1)) { + emptyRxFifo(i2c); // grab last few characters + } + i2c->dev->int_ena.val = 0; // shut down interrupts + i2c->dev->int_clr.val = 0x1FFF; + i2c->stage = I2C_DONE; + i2c->exitCode = exitCode; //true eventcode + + portBASE_TYPE HPTaskAwoken = pdFALSE,xResult; + // try to notify Dispatch we are done, + // else the 50ms time out will recover the APP, just a little slower + HPTaskAwoken = pdFALSE; + xResult = xEventGroupSetBitsFromISR(i2c->i2c_event, exitCode, &HPTaskAwoken); + if(xResult == pdPASS) { + if(HPTaskAwoken==pdTRUE) { + portYIELD_FROM_ISR(); + // log_e("Yield to Higher"); + } } - i2cSetCmd(i2c, cmdIdx++, I2C_CMD_WRITE, addrLen, false, false, true); - nextCmdCount = cmdIdx; - //Clear Interrupts - i2c->dev->int_clr.val = 0x00001FFF; +} - //START Transmission - i2c->dev->ctr.trans_start = 1; - while (!stopped) { - //WAIT Transmission - uint32_t startAt = millis(); - while(1) { - //have been looping for too long - if((millis() - startAt)>50) { - log_e("Timeout! Addr: %x, index %d", (address >> 1), index); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_BUS; +static void IRAM_ATTR i2c_update_error_byte_cnt(i2c_t * i2c) +{ +/* i2c_update_error_byte_cnt 07/18/2018 + Only called after an error has occurred, so, most of the time this function is never used. + This function obliterates the need to interrupt monitor each byte transferred, at high bitrates + the byte interrupts were overwhelming the OS. Spurious Interrupts were being generated. + it updates errorByteCnt, errorQueue. + */ + uint16_t a=0; // start at top of DQ, count how many bytes added to tx fifo, and received from rx_fifo. + int16_t bc = 0; + I2C_DATA_QUEUE_t *tdq; + i2c->errorByteCnt = 0; + while( a < i2c->queueCount){ // add up all bytes loaded into fifo's + tdq = &i2c->dq[a]; + i2c->errorByteCnt += tdq->ctrl.addrSent; + i2c->errorByteCnt += tdq->position; + a++; + } + // now errorByteCnt contains total bytes moved into and out of FIFO's + // but, there may still be bytes waiting in Fifo's + i2c->errorByteCnt -= i2c->dev->status_reg.tx_fifo_cnt; // waiting to go out; + i2c->errorByteCnt += i2c->dev->status_reg.rx_fifo_cnt; // already received +// now walk thru DQ again, find which byte is 'current' + bc = i2c->errorByteCnt; + i2c->errorQueue = 0; + while( i2c->errorQueue < i2c->queueCount ){ + tdq = &i2c->dq[i2c->errorQueue]; + if(bc>0){ // not found yet + if( tdq->ctrl.addrSent >= bc){ // in address + bc = -1; // in address + break; + } else { + bc -= tdq->ctrl.addrSent; + if( tdq->length > bc) { // data nak + break; + } else { // count down + bc -= tdq->length; + } } + } else break; + + i2c->errorQueue++; + } + + i2c->errorByteCnt = bc; + } + +static void IRAM_ATTR i2c_isr_handler_default(void* arg) +{ + i2c_t* p_i2c = (i2c_t*) arg; // recover data + uint32_t activeInt = p_i2c->dev->int_status.val&0x7FF; + + if(p_i2c->stage==I2C_DONE) { //get Out, can't service, not configured + p_i2c->dev->int_ena.val = 0; + p_i2c->dev->int_clr.val = 0x1FFF; +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE + uint32_t raw = p_i2c->dev->int_raw.val; + log_w("eject raw=%p, int=%p",raw,activeInt); +#endif + return; + } + while (activeInt != 0) { // Ordering of 'if(activeInt)' statements is important, don't change + + #if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) && (defined ENABLE_I2C_DEBUG_BUFFER) + if(activeInt==(intBuff[intPos[p_i2c->num]][0][p_i2c->num]&0x1fff)) { + intBuff[intPos[p_i2c->num]][0][p_i2c->num] = (((intBuff[intPos[p_i2c->num]][0][p_i2c->num]>>16)+1)<<16)|activeInt; + } else { + intPos[p_i2c->num]++; + intPos[p_i2c->num] %= INTBUFFMAX; + intBuff[intPos[p_i2c->num]][0][p_i2c->num] = (1<<16) | activeInt; + intBuff[intPos[p_i2c->num]][1][p_i2c->num] = 0; + } - //Bus failed (maybe check for this while waiting? - if(i2c->dev->int_raw.arbitration_lost) { - log_e("Bus Fail! Addr: %x", (address >> 1)); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_BUS; - } + intBuff[intPos[p_i2c->num]][2][p_i2c->num] = xTaskGetTickCountFromISR(); // when IRQ fired - //Bus timeout - if(i2c->dev->int_raw.time_out) { - log_e("Bus Timeout! Addr: %x, index %d", (address >> 1), index ); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_TIMEOUT; +#endif + + if (activeInt & I2C_TRANS_START_INT_ST_M) { + if(p_i2c->stage==I2C_STARTUP) { + p_i2c->stage=I2C_RUNNING; } - //Transmission did not finish and ACK_ERR is set - if(i2c->dev->int_raw.ack_err) { - log_w("Ack Error! Addr: %x", address >> 1); - while((i2c->dev->status_reg.bus_busy) && ((millis() - startAt)<50)); - I2C_MUTEX_UNLOCK(); - return I2C_ERROR_ACK; - } + activeInt &=~I2C_TRANS_START_INT_ST_M; + p_i2c->dev->int_ena.trans_start = 1; // already enabled? why Again? + p_i2c->dev->int_clr.trans_start = 1; // so that will trigger after next 'END' + } - // Save bytes from the buffer as they arrive instead of doing them at the end of the loop since there is no - // pause from an END operation in this approach. - if((!isEndNear) && (nextCmdCount < 2)) { - willRead = ((len>32)?32:len); - if (willRead > 0) { - if (willRead > 1) { - i2cSetCmd(i2c, cmdIdx, I2C_CMD_READ, (amountRead[ inc( &cmdIdx ) ] = willRead -1), false, false, false); - nextCmdCount++; - } - i2cSetCmd(i2c, cmdIdx, I2C_CMD_READ, (amountRead[ inc( &cmdIdx ) ] = 1), (len<=32), false, false); - nextCmdCount++; - len -= willRead; + if (activeInt & I2C_TXFIFO_EMPTY_INT_ST) {//should this be before Trans_start? + fillTxFifo(p_i2c); //fillTxFifo will enable/disable/clear interrupt + activeInt&=~I2C_TXFIFO_EMPTY_INT_ST; + } + + if(activeInt & I2C_RXFIFO_FULL_INT_ST) { + emptyRxFifo(p_i2c); + p_i2c->dev->int_clr.rx_fifo_full=1; + p_i2c->dev->int_ena.rx_fifo_full=1; //why? + + activeInt &=~I2C_RXFIFO_FULL_INT_ST; + } + + if (activeInt & I2C_ACK_ERR_INT_ST_M) {//fatal error, abort i2c service + if (p_i2c->mode == I2C_MASTER) { + i2c_update_error_byte_cnt(p_i2c); // calc which byte caused ack Error, check if address or data + if(p_i2c->errorByteCnt < 0 ) { // address + i2cIsrExit(p_i2c,EVENT_ERROR_NAK,true); } else { - i2cSetCmd(i2c, inc( &cmdIdx ), I2C_CMD_STOP, 0, false, false, false); - isEndNear = true; - nextCmdCount++; + i2cIsrExit(p_i2c,EVENT_ERROR_DATA_NAK,true); //data } } + return; + } - if(i2c->dev->command[currentCmdIdx].done) { - nextCmdCount--; - if (i2c->dev->command[currentCmdIdx].op_code == I2C_CMD_READ) { - while(amountRead[currentCmdIdx]>0) { - data[index++] = i2c->dev->fifo_data.val & 0xFF; - amountRead[currentCmdIdx]--; - } - i2cResetFiFo(i2c); - } else if (i2c->dev->command[currentCmdIdx].op_code == I2C_CMD_STOP) { - stopped = true; - } - inc( ¤tCmdIdx ); - break; - } + if (activeInt & I2C_TIME_OUT_INT_ST_M) { + // let Gross timeout occur, Slave may release SCL before the configured timeout expires + // the Statemachine only has a 13.1ms max timout, some Devices >500ms + p_i2c->dev->int_clr.time_out =1; + activeInt &=~I2C_TIME_OUT_INT_ST; + // since a timeout occurred, capture the rxFifo data + emptyRxFifo(p_i2c); + p_i2c->dev->int_clr.rx_fifo_full=1; + p_i2c->dev->int_ena.rx_fifo_full=1; //why? + + } + + if (activeInt & I2C_TRANS_COMPLETE_INT_ST_M) { + p_i2c->dev->int_clr.trans_complete = 1; + i2cIsrExit(p_i2c,EVENT_DONE,false); + return; // no more work to do + /* + // how does slave mode act? + if (p_i2c->mode == I2C_SLAVE) { // STOP detected + // empty fifo + // dispatch callback + */ + } + + if (activeInt & I2C_ARBITRATION_LOST_INT_ST_M) { //fatal + i2cIsrExit(p_i2c,EVENT_ERROR_ARBITRATION,true); + return; // no more work to do + } + + if (activeInt & I2C_SLAVE_TRAN_COMP_INT_ST_M) { + p_i2c->dev->int_clr.slave_tran_comp = 1; + // need to complete this ! } + + if (activeInt & I2C_END_DETECT_INT_ST_M) { + p_i2c->dev->int_ena.end_detect = 0; + p_i2c->dev->int_clr.end_detect = 1; + p_i2c->dev->ctr.trans_start=0; + fillCmdQueue(p_i2c,true); // enable interrupts + p_i2c->dev->ctr.trans_start=1; // go for it + activeInt&=~I2C_END_DETECT_INT_ST_M; + } + + if(activeInt) { // clear unhandled if possible? What about Disabling interrupt? + p_i2c->dev->int_clr.val = activeInt; + log_e("unknown int=%x",activeInt); + // disable unhandled IRQ, + p_i2c->dev->int_ena.val = p_i2c->dev->int_ena.val & (~activeInt); + } + +// activeInt = p_i2c->dev->int_status.val; // start all over if another interrupt happened +// 01AUG2018 if another interrupt happened, the OS will schedule another interrupt +// this is the source of spurious interrupts } - I2C_MUTEX_UNLOCK(); +} +/* Stickbreaker added for ISR 11/2017 +functional with Silicon date=0x16042000 + */ +static i2c_err_t i2cAddQueue(i2c_t * i2c,uint8_t mode, uint16_t i2cDeviceAddr, uint8_t *dataPtr, uint16_t dataLen,bool sendStop, bool dataOnly, EventGroupHandle_t event) +{ + // need to grab a MUTEX for exclusive Queue, + // what about if ISR is running? + + if(i2c==NULL) { + return I2C_ERROR_DEV; + } + + I2C_DATA_QUEUE_t dqx; + dqx.data = dataPtr; + dqx.length = dataLen; + dqx.position = 0; + dqx.cmdBytesNeeded = dataLen; + dqx.ctrl.val = 0; + if( dataOnly) { + /* special case to add a queue data only element. + START and devAddr will not be sent, this dq element can have a STOP. + allows multiple buffers to be used for one transaction. + sequence: normal transaction(sendStop==false), [dataonly(sendStop==false)],dataOnly(sendStop==true) + *** Currently only works with WRITE, final byte NAK an READ will cause a fail between dq buffer elements. (in progress 30JUL2018) + */ + dqx.ctrl.startCmdSent = 1; // mark as already sent + dqx.ctrl.addrCmdSent = 1; + } else { + dqx.ctrl.addrReq = ((i2cDeviceAddr&0xFC00)==0x7800)?2:1; // 10bit or 7bit address + } + dqx.ctrl.addr = i2cDeviceAddr; + dqx.ctrl.mode = mode; + dqx.ctrl.stop= sendStop; + dqx.queueEvent = event; + + if(event) { // an eventGroup exist, so, initialize it + xEventGroupClearBits(event, EVENT_MASK); // all of them + } + + if(i2c->dq!=NULL) { // expand + //log_i("expand"); + I2C_DATA_QUEUE_t* tq =(I2C_DATA_QUEUE_t*)realloc(i2c->dq,sizeof(I2C_DATA_QUEUE_t)*(i2c->queueCount +1)); + if(tq!=NULL) { // ok + i2c->dq = tq; + memmove(&i2c->dq[i2c->queueCount++],&dqx,sizeof(I2C_DATA_QUEUE_t)); + } else { // bad stuff, unable to allocate more memory! + log_e("realloc Failure"); + return I2C_ERROR_MEMORY; + } + } else { // first Time + //log_i("new"); + i2c->queueCount=0; + i2c->dq =(I2C_DATA_QUEUE_t*)malloc(sizeof(I2C_DATA_QUEUE_t)); + if(i2c->dq!=NULL) { + memmove(&i2c->dq[i2c->queueCount++],&dqx,sizeof(I2C_DATA_QUEUE_t)); + } else { + log_e("malloc failure"); + return I2C_ERROR_MEMORY; + } + } return I2C_ERROR_OK; } -i2c_err_t i2cSetFrequency(i2c_t * i2c, uint32_t clk_speed) +i2c_err_t i2cAddQueueWrite(i2c_t * i2c, uint16_t i2cDeviceAddr, uint8_t *dataPtr, uint16_t dataLen,bool sendStop,EventGroupHandle_t event) { - if(i2c == NULL){ - return I2C_ERROR_DEV; + return i2cAddQueue(i2c,0,i2cDeviceAddr,dataPtr,dataLen,sendStop,false,event); +} + +i2c_err_t i2cAddQueueRead(i2c_t * i2c, uint16_t i2cDeviceAddr, uint8_t *dataPtr, uint16_t dataLen,bool sendStop,EventGroupHandle_t event) +{ + //10bit read is kind of weird, first you do a 0byte Write with 10bit + // address, then a ReSTART then a 7bit Read using the the upper 7bit + + // readBit. + + // this might cause an internal register pointer problem with 10bit + // devices, But, Don't have any to test against. + // this is the Industry Standard specification. + + if((i2cDeviceAddr &0xFC00)==0x7800) { // ten bit read + i2c_err_t err = i2cAddQueue(i2c,0,i2cDeviceAddr,NULL,0,false,false,event); + if(err==I2C_ERROR_OK) { + return i2cAddQueue(i2c,1,(i2cDeviceAddr>>8),dataPtr,dataLen,sendStop,false,event); + } else { + return err; + } } + return i2cAddQueue(i2c,1,i2cDeviceAddr,dataPtr,dataLen,sendStop,false,event); +} - uint32_t period = (APB_CLK_FREQ/clk_speed) / 2; - uint32_t halfPeriod = period/2; - uint32_t quarterPeriod = period/4; +i2c_err_t i2cProcQueue(i2c_t * i2c, uint32_t *readCount, uint16_t timeOutMillis) +{ + /* do the hard stuff here + install ISR if necessary + setup EventGroup + handle bus busy? + */ + //log_e("procQueue i2c=%p",&i2c); + if(readCount){ //total reads accomplished in all queue elements + *readCount = 0; + } + if(i2c == NULL) { + return I2C_ERROR_DEV; + } + if(i2c->debugFlags & 0xff000000) i2cTriggerDumps(i2c,(i2c->debugFlags>>24),"before ProcQueue"); + if (i2c->dev->status_reg.bus_busy) { // return error, let TwoWire() handle resetting the hardware. + /* if multi master then this if should be changed to this 03/12/2018 + if(multiMaster){// try to let the bus clear by its self + uint32_t timeOutTick = millis(); + while((i2c->dev->status_reg.bus_busy)&&(millis()-timeOutTickdev->status_reg.bus_busy){ // still busy, so die + */ + log_i("Bus busy, reinit"); + return I2C_ERROR_BUSY; + } I2C_MUTEX_LOCK(); - //the clock num during SCL is low level - i2c->dev->scl_low_period.period = period; - //the clock num during SCL is high level - i2c->dev->scl_high_period.period = period; + /* what about co-existence with SLAVE mode? + Should I check if a slaveMode xfer is in progress and hang + until it completes? + if i2c->stage == I2C_RUNNING or I2C_SLAVE_ACTIVE + */ + i2c->stage = I2C_DONE; // until ready + +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) && (defined ENABLE_I2C_DEBUG_BUFFER) + for(uint16_t i=0; inum] = 0; + intBuff[i][1][i2c->num] = 0; + intBuff[i][2][i2c->num] = 0; + } + intPos[i2c->num] = 0; + fifoPos = 0; + memset(fifoBuffer,0,FIFOMAX); +#endif + // EventGroup is used to signal transmission completion from ISR + // not always reliable. Sometimes, the FreeRTOS scheduler is maxed out and refuses request + // if that happens, this call hangs until the timeout period expires, then it continues. + if(!i2c->i2c_event) { + i2c->i2c_event = xEventGroupCreate(); + } + if(i2c->i2c_event) { + xEventGroupClearBits(i2c->i2c_event, 0xFF); + } else { // failed to create EventGroup + log_e("eventCreate failed=%p",i2c->i2c_event); + I2C_MUTEX_UNLOCK(); + return I2C_ERROR_MEMORY; + } - //the clock num between the negedge of SDA and negedge of SCL for start mark - i2c->dev->scl_start_hold.time = halfPeriod; - //the clock num between the posedge of SCL and the negedge of SDA for restart mark - i2c->dev->scl_rstart_setup.time = halfPeriod; + i2c_err_t reason = I2C_ERROR_OK; + i2c->mode = I2C_MASTER; + i2c->dev->ctr.trans_start=0; // Pause Machine + i2c->dev->timeout.tout = 0xFFFFF; // max 13ms + i2c->dev->int_clr.val = 0x1FFF; // kill them All! + + i2c->dev->ctr.ms_mode = 1; // master! + i2c->queuePos=0; + i2c->errorByteCnt=0; + i2c->errorQueue = 0; + uint32_t totalBytes=0; // total number of bytes to be Moved! + // convert address field to required I2C format + while(i2c->queuePos < i2c->queueCount) { // need to push these address modes upstream, to AddQueue + I2C_DATA_QUEUE_t *tdq = &i2c->dq[i2c->queuePos++]; + uint16_t taddr=0; + if(tdq->ctrl.addrReq ==2) { // 10bit address + taddr =((tdq->ctrl.addr >> 7) & 0xFE) + |tdq->ctrl.mode; + taddr = (taddr <<8) | (tdq->ctrl.addr&0xFF); + } else { // 7bit address + taddr = ((tdq->ctrl.addr<<1)&0xFE) + |tdq->ctrl.mode; + } + tdq->ctrl.addr = taddr; // all fixed with R/W bit + totalBytes += tdq->length + tdq->ctrl.addrReq; // total number of byte to be moved! + } + i2c->queuePos=0; + + fillCmdQueue(i2c,false); // don't enable Tx/RX irq's + // start adding command[], END irq will keep it full + //Data Fifo will be filled after trans_start is issued + i2c->exitCode=0; + + I2C_FIFO_CONF_t f; + f.val = i2c->dev->fifo_conf.val; + f.rx_fifo_rst = 1; // fifo in reset + f.tx_fifo_rst = 1; // fifo in reset + f.nonfifo_en = 0; // use fifo mode + f.nonfifo_tx_thres = 31; + // need to adjust threshold based on I2C clock rate, at 100k, 30 usually works, + // sometimes the emptyRx() actually moves 31 bytes + // it hasn't overflowed yet, I cannot tell if the new byte is added while + // emptyRX() is executing or before? + // let i2cSetFrequency() set thrhds + // f.rx_fifo_full_thrhd = 30; // 30 bytes before INT is issued + // f.tx_fifo_empty_thrhd = 0; + f.fifo_addr_cfg_en = 0; // no directed access + i2c->dev->fifo_conf.val = f.val; // post them all + + f.rx_fifo_rst = 0; // release fifo + f.tx_fifo_rst = 0; + i2c->dev->fifo_conf.val = f.val; // post them all + + i2c->stage = I2C_STARTUP; // everything configured, now start the I2C StateMachine, and + // As soon as interrupts are enabled, the ISR will start handling them. + // it should receive a TXFIFO_EMPTY immediately, even before it + // receives the TRANS_START + + + uint32_t interruptsEnabled = + I2C_ACK_ERR_INT_ENA | // (BIT(10)) Causes Fatal Error Exit + I2C_TRANS_START_INT_ENA | // (BIT(9)) Triggered by trans_start=1, initial,END + I2C_TIME_OUT_INT_ENA | //(BIT(8)) Trigger by SLAVE SCL stretching, NOT an ERROR + I2C_TRANS_COMPLETE_INT_ENA | // (BIT(7)) triggered by STOP, successful exit + I2C_ARBITRATION_LOST_INT_ENA | // (BIT(5)) cause fatal error exit + I2C_SLAVE_TRAN_COMP_INT_ENA | // (BIT(4)) unhandled + I2C_END_DETECT_INT_ENA | // (BIT(3)) refills cmd[] list + I2C_RXFIFO_OVF_INT_ENA | //(BIT(2)) unhandled + I2C_TXFIFO_EMPTY_INT_ENA | // (BIT(1)) triggers fillTxFifo() + I2C_RXFIFO_FULL_INT_ENA; // (BIT(0)) trigger emptyRxFifo() + + i2c->dev->int_ena.val = interruptsEnabled; + + if(!i2c->intr_handle) { // create ISR for either peripheral + // log_i("create ISR %d",i2c->num); + uint32_t ret = 0; + uint32_t flags = ESP_INTR_FLAG_IRAM | //< ISR can be called if cache is disabled + ESP_INTR_FLAG_LOWMED | //< Low and medium prio interrupts. These can be handled in C. + ESP_INTR_FLAG_SHARED; //< Reduce resource requirements, Share interrupts + + if(i2c->num) { + ret = esp_intr_alloc_intrstatus(ETS_I2C_EXT1_INTR_SOURCE, flags, (uint32_t)&i2c->dev->int_status.val, interruptsEnabled, &i2c_isr_handler_default,i2c, &i2c->intr_handle); + } else { + ret = esp_intr_alloc_intrstatus(ETS_I2C_EXT0_INTR_SOURCE, flags, (uint32_t)&i2c->dev->int_status.val, interruptsEnabled, &i2c_isr_handler_default,i2c, &i2c->intr_handle); + } - //the clock num after the STOP bit's posedge - i2c->dev->scl_stop_hold.time = halfPeriod; - //the clock num between the posedge of SCL and the posedge of SDA - i2c->dev->scl_stop_setup.time = halfPeriod; + if(ret!=ESP_OK) { + log_e("install interrupt handler Failed=%d",ret); + I2C_MUTEX_UNLOCK(); + return I2C_ERROR_MEMORY; + } + if( !addApbChangeCallback( i2c, i2cApbChangeCallback)) { + log_e("install apb Callback failed"); + I2C_MUTEX_UNLOCK(); + return I2C_ERROR_DEV; + } + + } + //hang until it completes. + + // how many ticks should it take to transfer totalBytes through the I2C hardware, + // add user supplied timeOutMillis to Calculated Value + + portTickType ticksTimeOut = ((totalBytes*10*1000)/(i2cGetFrequency(i2c))+timeOutMillis)/portTICK_PERIOD_MS; + + i2c->dev->ctr.trans_start=1; // go for it + +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG + portTickType tBefore=xTaskGetTickCount(); +#endif + + // wait for ISR to complete the transfer, or until timeOut in case of bus fault, hardware problem + + uint32_t eBits = xEventGroupWaitBits(i2c->i2c_event,EVENT_DONE,pdFALSE,pdTRUE,ticksTimeOut); + +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG + portTickType tAfter=xTaskGetTickCount(); +#endif + + + // if xEventGroupSetBitsFromISR() failed, the ISR could have succeeded but never been + // able to mark the success + + if(i2c->exitCode!=eBits) { // try to recover from O/S failure + // log_e("EventGroup Failed:%p!=%p",eBits,i2c->exitCode); + eBits=i2c->exitCode; + } + if((eBits&EVENT_ERROR)||(!(eBits & EVENT_DONE))){ // need accurate errorByteCnt for debug + i2c_update_error_byte_cnt(i2c); + } + + if(!(eBits==EVENT_DONE)&&(eBits&~(EVENT_ERROR_NAK|EVENT_ERROR_DATA_NAK|EVENT_ERROR|EVENT_DONE))) { // not only Done, therefore error, exclude ADDR NAK, DATA_NAK +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO + i2cDumpI2c(i2c); + i2cDumpInts(i2c->num); +#endif + } + + if(eBits&EVENT_DONE) { // no gross timeout + switch(i2c->error) { + case I2C_OK : + reason = I2C_ERROR_OK; + break; + case I2C_ERROR : + reason = I2C_ERROR_DEV; + break; + case I2C_ADDR_NAK: + reason = I2C_ERROR_ACK; + break; + case I2C_DATA_NAK: + reason = I2C_ERROR_ACK; + break; + case I2C_ARBITRATION: + reason = I2C_ERROR_BUS; + break; + case I2C_TIMEOUT: + reason = I2C_ERROR_TIMEOUT; + break; + default : + reason = I2C_ERROR_DEV; + } + } else { // GROSS timeout, shutdown ISR , report Timeout + i2c->stage = I2C_DONE; + i2c->dev->int_ena.val =0; + i2c->dev->int_clr.val = 0x1FFF; + i2c_update_error_byte_cnt(i2c); + if((i2c->errorByteCnt == 0)&&(i2c->errorQueue==0)) { // Bus Busy no bytes Moved + reason = I2C_ERROR_BUSY; + eBits = eBits | EVENT_ERROR_BUS_BUSY|EVENT_ERROR|EVENT_DONE; +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG + log_d(" Busy Timeout start=0x%x, end=0x%x, =%d, max=%d error=%d",tBefore,tAfter,(tAfter-tBefore),ticksTimeOut,i2c->error); + i2cDumpI2c(i2c); + i2cDumpInts(i2c->num); +#endif + } else { // just a timeout, some data made it out or in. + reason = I2C_ERROR_TIMEOUT; + eBits = eBits | EVENT_ERROR_TIMEOUT|EVENT_ERROR|EVENT_DONE; + +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG + log_d(" Gross Timeout Dead start=0x%x, end=0x%x, =%d, max=%d error=%d",tBefore,tAfter,(tAfter-tBefore),ticksTimeOut,i2c->error); + i2cDumpI2c(i2c); + i2cDumpInts(i2c->num); +#endif + } + } + + /* offloading all EventGroups to dispatch, EventGroups in ISR is not always successful + 11/20/2017 + if error, need to trigger all succeeding dataQueue events with the EVENT_ERROR_PREV + 07/22/2018 + Need to use the queueEvent value to identify transaction blocks, if an error occurs, + all subsequent queue items with the same queueEvent value will receive the EVENT_ERROR_PREV. + But, ProcQue should re-queue queue items that have a different queueEvent value(different transaction) + This change will support multi-thread i2c usage. Use the queueEvent as the transaction event + identifier. + */ + uint32_t b = 0; + + while(b < i2c->queueCount) { + if(i2c->dq[b].ctrl.mode==1 && readCount) { + *readCount += i2c->dq[b].position; // number of data bytes received + } + if(b < i2c->queuePos) { // before any error + if(i2c->dq[b].queueEvent) { // this data queue element has an EventGroup + xEventGroupSetBits(i2c->dq[b].queueEvent,EVENT_DONE); + } + } else if(b == i2c->queuePos) { // last processed queue + if(i2c->dq[b].queueEvent) { // this data queue element has an EventGroup + xEventGroupSetBits(i2c->dq[b].queueEvent,eBits); + } + } else { // never processed queues + if(i2c->dq[b].queueEvent) { // this data queue element has an EventGroup + xEventGroupSetBits(i2c->dq[b].queueEvent,eBits|EVENT_ERROR_PREV); + } + } + b++; + } + if(i2c->debugFlags & 0x00ff0000) i2cTriggerDumps(i2c,(i2c->debugFlags>>16),"after ProcQueue"); - //the clock num I2C used to hold the data after the negedge of SCL. - i2c->dev->sda_hold.time = quarterPeriod; - //the clock num I2C used to sample data on SDA after the posedge of SCL - i2c->dev->sda_sample.time = quarterPeriod; I2C_MUTEX_UNLOCK(); + return reason; +} + +static void i2cReleaseISR(i2c_t * i2c) +{ + if(i2c->intr_handle) { + esp_intr_free(i2c->intr_handle); + i2c->intr_handle=NULL; + if (!removeApbChangeCallback( i2c, i2cApbChangeCallback)) { + log_e("unable to release apbCallback"); + } + } +} + +static bool i2cCheckLineState(int8_t sda, int8_t scl){ + if(sda < 0 || scl < 0){ + return false;//return false since there is nothing to do + } + // if the bus is not 'clear' try the cycling SCL until SDA goes High or 9 cycles + digitalWrite(sda, HIGH); + digitalWrite(scl, HIGH); + pinMode(sda, PULLUP|OPEN_DRAIN|INPUT); + pinMode(scl, PULLUP|OPEN_DRAIN|OUTPUT); + + if(!digitalRead(sda) || !digitalRead(scl)) { // bus in busy state + log_w("invalid state sda(%d)=%d, scl(%d)=%d", sda, digitalRead(sda), scl, digitalRead(scl)); + digitalWrite(scl, HIGH); + for(uint8_t a=0; a<9; a++) { + delayMicroseconds(5); + digitalWrite(scl, LOW); + delayMicroseconds(5); + digitalWrite(scl, HIGH); + if(digitalRead(sda)){ // bus recovered + log_d("Recovered after %d Cycles",a+1); + break; + } + } + } + + if(!digitalRead(sda) || !digitalRead(scl)) { // bus in busy state + log_e("Bus Invalid State, TwoWire() Can't init sda=%d, scl=%d",digitalRead(sda),digitalRead(scl)); + return false; // bus is busy + } + return true; +} + +i2c_err_t i2cAttachSCL(i2c_t * i2c, int8_t scl) +{ + if(i2c == NULL) { + return I2C_ERROR_DEV; + } + digitalWrite(scl, HIGH); + pinMode(scl, OPEN_DRAIN | PULLUP | INPUT | OUTPUT); + pinMatrixOutAttach(scl, I2C_SCL_IDX(i2c->num), false, false); + pinMatrixInAttach(scl, I2C_SCL_IDX(i2c->num), false); return I2C_ERROR_OK; } -uint32_t i2cGetFrequency(i2c_t * i2c) +i2c_err_t i2cDetachSCL(i2c_t * i2c, int8_t scl) { - if(i2c == NULL){ - return 0; + if(i2c == NULL) { + return I2C_ERROR_DEV; } + pinMatrixOutDetach(scl, false, false); + pinMatrixInDetach(I2C_SCL_IDX(i2c->num), false, false); + pinMode(scl, INPUT | PULLUP); + return I2C_ERROR_OK; +} - return APB_CLK_FREQ/(i2c->dev->scl_low_period.period+i2c->dev->scl_high_period.period); +i2c_err_t i2cAttachSDA(i2c_t * i2c, int8_t sda) +{ + if(i2c == NULL) { + return I2C_ERROR_DEV; + } + digitalWrite(sda, HIGH); + pinMode(sda, OPEN_DRAIN | PULLUP | INPUT | OUTPUT ); + pinMatrixOutAttach(sda, I2C_SDA_IDX(i2c->num), false, false); + pinMatrixInAttach(sda, I2C_SDA_IDX(i2c->num), false); + return I2C_ERROR_OK; +} + +i2c_err_t i2cDetachSDA(i2c_t * i2c, int8_t sda) +{ + if(i2c == NULL) { + return I2C_ERROR_DEV; + } + pinMatrixOutDetach(sda, false, false); + pinMatrixInDetach(I2C_SDA_IDX(i2c->num), false, false); + pinMode(sda, INPUT | PULLUP); + return I2C_ERROR_OK; } /* - * mode - 0 = Slave, 1 = Master - * slave_addr - I2C Address - * addr_10bit_en - enable slave 10bit address mode. + * PUBLIC API * */ - -i2c_t * i2cInit(uint8_t i2c_num, uint16_t slave_addr, bool addr_10bit_en) -{ - if(i2c_num > 1){ +// 24Nov17 only supports Master Mode +i2c_t * i2cInit(uint8_t i2c_num, int8_t sda, int8_t scl, uint32_t frequency) { +#ifdef ENABLE_I2C_DEBUG_BUFFER + log_v("num=%d sda=%d scl=%d freq=%d",i2c_num, sda, scl, frequency); +#endif + if(i2c_num > 1) { return NULL; } i2c_t * i2c = &_i2c_bus_array[i2c_num]; + // pins should be detached, else glitch + if(i2c->sda >= 0){ + i2cDetachSDA(i2c, i2c->sda); + } + if(i2c->scl >= 0){ + i2cDetachSCL(i2c, i2c->scl); + } + i2c->sda = sda; + i2c->scl = scl; + #if !CONFIG_DISABLE_HAL_LOCKS - if(i2c->lock == NULL){ - i2c->lock = xSemaphoreCreateMutex(); + if(i2c->lock == NULL) { + i2c->lock = xSemaphoreCreateRecursiveMutex(); if(i2c->lock == NULL) { return NULL; } } #endif + I2C_MUTEX_LOCK(); + + i2cReleaseISR(i2c); // ISR exists, release it before disabling hardware + + if(frequency == 0) {// don't change existing frequency + frequency = i2cGetFrequency(i2c); + if(frequency == 0) { + frequency = 100000L; // default to 100khz + } + } if(i2c_num == 0) { - DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT0_RST); // I2C0 peripheral into Reset mode + DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT0_RST); //reset hardware DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG,DPORT_I2C_EXT0_CLK_EN); - DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT0_RST); // Release Reset Mode + DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT0_RST);// release reset } else { - DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT1_RST); // I2C1 peripheral into Reset Mode + DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT1_RST); //reset Hardware DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG,DPORT_I2C_EXT1_CLK_EN); - DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT1_RST); // Release Reset Mode + DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT1_RST); } - - I2C_MUTEX_LOCK(); i2c->dev->ctr.val = 0; - i2c->dev->ctr.ms_mode = (slave_addr == 0); + i2c->dev->ctr.ms_mode = 1; i2c->dev->ctr.sda_force_out = 1 ; i2c->dev->ctr.scl_force_out = 1 ; i2c->dev->ctr.clk_en = 1; //the max clock number of receiving a data - i2c->dev->timeout.tout = 1048575;//clocks max=1048575 + i2c->dev->timeout.tout = 400000;//clocks max=1048575 //disable apb nonfifo access i2c->dev->fifo_conf.nonfifo_en = 0; i2c->dev->slave_addr.val = 0; - if (slave_addr) { - i2c->dev->slave_addr.addr = slave_addr; - i2c->dev->slave_addr.en_10bit = addr_10bit_en; - } I2C_MUTEX_UNLOCK(); + i2cSetFrequency(i2c, frequency); // reconfigure + + if(!i2cCheckLineState(i2c->sda, i2c->scl)){ + return NULL; + } + + if(i2c->sda >= 0){ + i2cAttachSDA(i2c, i2c->sda); + } + if(i2c->scl >= 0){ + i2cAttachSCL(i2c, i2c->scl); + } return i2c; } -void i2cInitFix(i2c_t * i2c){ - if(i2c == NULL){ - return; - } +void i2cRelease(i2c_t *i2c) // release all resources, power down peripheral +{ I2C_MUTEX_LOCK(); - i2cResetFiFo(i2c); - i2cResetCmd(i2c); - i2c->dev->int_clr.val = 0xFFFFFFFF; - i2cSetCmd(i2c, 0, I2C_CMD_RSTART, 0, false, false, false); - i2c->dev->fifo_data.data = 0; - i2cSetCmd(i2c, 1, I2C_CMD_WRITE, 1, false, false, false); - i2cSetCmd(i2c, 2, I2C_CMD_STOP, 0, false, false, false); - if (i2c->dev->status_reg.bus_busy) // If this condition is true, the while loop will timeout as done will not be set - { - log_e("Busy at initialization!"); - } - i2c->dev->ctr.trans_start = 1; - uint16_t count = 50000; - while ((!i2c->dev->command[2].done) && (--count > 0)); + + if(i2c->sda >= 0){ + i2cDetachSDA(i2c, i2c->sda); + } + if(i2c->scl >= 0){ + i2cDetachSCL(i2c, i2c->scl); + } + + i2cReleaseISR(i2c); + + if(i2c->i2c_event) { + vEventGroupDelete(i2c->i2c_event); + i2c->i2c_event = NULL; + } + + i2cFlush(i2c); + + // reset the I2C hardware and shut off the clock, power it down. + if(i2c->num == 0) { + DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT0_RST); //reset hardware + DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG,DPORT_I2C_EXT0_CLK_EN); // shutdown hardware + } else { + DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT1_RST); //reset Hardware + DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG,DPORT_I2C_EXT1_CLK_EN); // shutdown Hardware + } + I2C_MUTEX_UNLOCK(); } -void i2cReset(i2c_t* i2c){ - if(i2c == NULL){ - return; +i2c_err_t i2cFlush(i2c_t * i2c) +{ + if(i2c==NULL) { + return I2C_ERROR_DEV; + } + i2cTriggerDumps(i2c,i2c->debugFlags & 0xff, "FLUSH"); + + // need to grab a MUTEX for exclusive Queue, + // what out if ISR is running? + i2c_err_t rc=I2C_ERROR_OK; + if(i2c->dq!=NULL) { + // log_i("free"); + // what about EventHandle? + free(i2c->dq); + i2c->dq = NULL; + } + i2c->queueCount=0; + i2c->queuePos=0; + // release Mutex + return rc; +} + +i2c_err_t i2cWrite(i2c_t * i2c, uint16_t address, uint8_t* buff, uint16_t size, bool sendStop, uint16_t timeOutMillis){ + if((i2c==NULL)||((size>0)&&(buff==NULL))) { // need to have location to store requested data + return I2C_ERROR_DEV; + } + i2c_err_t last_error = i2cAddQueueWrite(i2c, address, buff, size, sendStop, NULL); + + if(last_error == I2C_ERROR_OK) { //queued + if(sendStop) { //now actually process the queued commands, including READs + last_error = i2cProcQueue(i2c, NULL, timeOutMillis); + if(last_error == I2C_ERROR_BUSY) { // try to clear the bus + if(i2cInit(i2c->num, i2c->sda, i2c->scl, 0)) { + last_error = i2cProcQueue(i2c, NULL, timeOutMillis); + } + } + i2cFlush(i2c); + } else { // stop not received, so wait for I2C stop, + last_error = I2C_ERROR_CONTINUE; + } + } + return last_error; +} + +i2c_err_t i2cRead(i2c_t * i2c, uint16_t address, uint8_t* buff, uint16_t size, bool sendStop, uint16_t timeOutMillis, uint32_t *readCount){ + if((size == 0)||(i2c == NULL)||(buff==NULL)){ // hardware will hang if no data requested on READ + return I2C_ERROR_DEV; + } + i2c_err_t last_error=i2cAddQueueRead(i2c, address, buff, size, sendStop, NULL); + + if(last_error == I2C_ERROR_OK) { //queued + if(sendStop) { //now actually process the queued commands, including READs + last_error = i2cProcQueue(i2c, readCount, timeOutMillis); + if(last_error == I2C_ERROR_BUSY) { // try to clear the bus + if(i2cInit(i2c->num, i2c->sda, i2c->scl, 0)) { + last_error = i2cProcQueue(i2c, readCount, timeOutMillis); + } + } + i2cFlush(i2c); + } else { // stop not received, so wait for I2C stop, + last_error = I2C_ERROR_CONTINUE; + } + } + return last_error; +} + +#define MIN_I2C_CLKS 100 // minimum ratio between cpu and i2c Bus clocks +#define INTERRUPT_CYCLE_OVERHEAD 16000 // number of cpu clocks necessary to respond to interrupt +i2c_err_t i2cSetFrequency(i2c_t * i2c, uint32_t clk_speed) +{ + if(i2c == NULL) { + return I2C_ERROR_DEV; + } + uint32_t apb = getApbFrequency(); + uint32_t period = (apb/clk_speed) / 2; + + if((apb/8192 > clk_speed)||(apb/MIN_I2C_CLKS < clk_speed)){ //out of bounds + log_d("i2c freq(%d) out of bounds.vs APB Clock(%d), min=%d, max=%d",clk_speed,apb,(apb/8192),(apb/MIN_I2C_CLKS)); } + if(period < (MIN_I2C_CLKS/2) ){ + period = (MIN_I2C_CLKS/2); + clk_speed = apb/(period*2); + log_d("APB Freq too slow, Reducing i2c Freq to %d Hz",clk_speed); + } else if ( period> 4095) { + period = 4095; + clk_speed = apb/(period*2); + log_d("APB Freq too fast, Increasing i2c Freq to %d Hz",clk_speed); + } +#ifdef ENABLE_I2C_DEBUG_BUFFER + log_v("freq=%dHz",clk_speed); +#endif + uint32_t halfPeriod = period/2; + uint32_t quarterPeriod = period/4; + I2C_MUTEX_LOCK(); - periph_module_t moduleId = (i2c == &_i2c_bus_array[0])?PERIPH_I2C0_MODULE:PERIPH_I2C1_MODULE; - periph_module_disable( moduleId ); - delay( 20 ); // Seems long but delay was chosen to ensure system teardown and setup without core generation - periph_module_enable( moduleId ); + + I2C_FIFO_CONF_t f; + + f.val = i2c->dev->fifo_conf.val; +/* Adjust Fifo thresholds based on differential between cpu frequency and bus clock. + The fifo_delta is calculated such that at least INTERRUPT_CYCLE_OVERHEAD cpu clocks are + available when a Fifo interrupt is triggered. This allows enough room in the Fifo so that + interrupt latency does not cause a Fifo overflow/underflow event. +*/ +#ifdef ENABLE_I2C_DEBUG_BUFFER + log_v("cpu Freq=%dMhz, i2c Freq=%dHz",getCpuFrequencyMhz(),clk_speed); +#endif + uint32_t fifo_delta = (INTERRUPT_CYCLE_OVERHEAD/((getCpuFrequencyMhz()*1000000 / clk_speed)*10))+1; + if (fifo_delta > 24) fifo_delta=24; + f.rx_fifo_full_thrhd = 32 - fifo_delta; + f.tx_fifo_empty_thrhd = fifo_delta; + i2c->dev->fifo_conf.val = f.val; // set thresholds +#ifdef ENABLE_I2C_DEBUG_BUFFER + log_v("Fifo delta=%d",fifo_delta); +#endif + //the clock num during SCL is low level + i2c->dev->scl_low_period.period = period; + //the clock num during SCL is high level + i2c->dev->scl_high_period.period = period; + + //the clock num between the negedge of SDA and negedge of SCL for start mark + i2c->dev->scl_start_hold.time = halfPeriod; + //the clock num between the posedge of SCL and the negedge of SDA for restart mark + i2c->dev->scl_rstart_setup.time = halfPeriod; + + //the clock num after the STOP bit's posedge + i2c->dev->scl_stop_hold.time = halfPeriod; + //the clock num between the posedge of SCL and the posedge of SDA + i2c->dev->scl_stop_setup.time = halfPeriod; + + //the clock num I2C used to hold the data after the negedge of SCL. + i2c->dev->sda_hold.time = quarterPeriod; + //the clock num I2C used to sample data on SDA after the posedge of SCL + i2c->dev->sda_sample.time = quarterPeriod; I2C_MUTEX_UNLOCK(); + return I2C_ERROR_OK; } +uint32_t i2cGetFrequency(i2c_t * i2c) +{ + if(i2c == NULL) { + return 0; + } + uint32_t result = 0; + uint32_t old_count = (i2c->dev->scl_low_period.period+i2c->dev->scl_high_period.period); + if(old_count>0) { + result = getApbFrequency() / old_count; + } else { + result = 0; + } + return result; +} + + +uint32_t i2cDebug(i2c_t * i2c, uint32_t setBits, uint32_t resetBits){ + if(i2c != NULL) { + i2c->debugFlags = ((i2c->debugFlags | setBits) & ~resetBits); + return i2c->debugFlags; + } + return 0; + + } + +uint32_t i2cGetStatus(i2c_t * i2c){ + if(i2c != NULL){ + return i2c->dev->status_reg.val; + } + else return 0; +} + + +/* todo + 22JUL18 + need to add multi-thread capability, use dq.queueEvent as the group marker. When multiple threads + transactions are present in the same queue, and an error occurs, abort all succeeding unserviced transactions + with the same dq.queueEvent value. Succeeding unserviced transactions with different dq.queueEvent values + can be re-queued and processed independently. + 30JUL18 complete data only queue elements, this will allow transfers to use multiple data blocks, + */ + diff --git a/cores/esp32/esp32-hal-i2c.h b/cores/esp32/esp32-hal-i2c.h index f26c7ab2a60..1a696aca7d6 100644 --- a/cores/esp32/esp32-hal-i2c.h +++ b/cores/esp32/esp32-hal-i2c.h @@ -11,6 +11,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// modified Nov 2017 by Chuck Todd to support Interrupt Driven I/O #ifndef _ESP32_HAL_I2C_H_ #define _ESP32_HAL_I2C_H_ @@ -21,37 +22,58 @@ extern "C" { #include #include +#include "freertos/FreeRTOS.h" +#include "freertos/event_groups.h" +// External Wire.h equivalent error Codes typedef enum { - I2C_ERROR_OK, + I2C_ERROR_OK=0, I2C_ERROR_DEV, I2C_ERROR_ACK, I2C_ERROR_TIMEOUT, I2C_ERROR_BUS, - I2C_ERROR_BUSY + I2C_ERROR_BUSY, + I2C_ERROR_MEMORY, + I2C_ERROR_CONTINUE, + I2C_ERROR_NO_BEGIN } i2c_err_t; struct i2c_struct_t; typedef struct i2c_struct_t i2c_t; -i2c_t * i2cInit(uint8_t i2c_num, uint16_t slave_addr, bool addr_10bit_en); - -//call this after you setup the bus and pins to send empty packet -//required because when pins are attached, they emit pulses that lock the bus -void i2cInitFix(i2c_t * i2c); - +i2c_t * i2cInit(uint8_t i2c_num, int8_t sda, int8_t scl, uint32_t clk_speed); +void i2cRelease(i2c_t *i2c); // free ISR, Free DQ, Power off peripheral clock. Must call i2cInit() to recover +i2c_err_t i2cWrite(i2c_t * i2c, uint16_t address, uint8_t* buff, uint16_t size, bool sendStop, uint16_t timeOutMillis); +i2c_err_t i2cRead(i2c_t * i2c, uint16_t address, uint8_t* buff, uint16_t size, bool sendStop, uint16_t timeOutMillis, uint32_t *readCount); +i2c_err_t i2cFlush(i2c_t *i2c); i2c_err_t i2cSetFrequency(i2c_t * i2c, uint32_t clk_speed); uint32_t i2cGetFrequency(i2c_t * i2c); +uint32_t i2cGetStatus(i2c_t * i2c); // Status register of peripheral +//Functions below should be used only if well understood +//Might be deprecated and removed in future i2c_err_t i2cAttachSCL(i2c_t * i2c, int8_t scl); i2c_err_t i2cDetachSCL(i2c_t * i2c, int8_t scl); i2c_err_t i2cAttachSDA(i2c_t * i2c, int8_t sda); i2c_err_t i2cDetachSDA(i2c_t * i2c, int8_t sda); -i2c_err_t i2cWrite(i2c_t * i2c, uint16_t address, bool addr_10bit, uint8_t * data, uint16_t len, bool sendStop); -i2c_err_t i2cRead(i2c_t * i2c, uint16_t address, bool addr_10bit, uint8_t * data, uint16_t len, bool sendStop); +//Stickbreakers ISR Support +i2c_err_t i2cProcQueue(i2c_t *i2c, uint32_t *readCount, uint16_t timeOutMillis); +i2c_err_t i2cAddQueueWrite(i2c_t *i2c, uint16_t i2cDeviceAddr, uint8_t *dataPtr, uint16_t dataLen, bool SendStop, EventGroupHandle_t event); +i2c_err_t i2cAddQueueRead(i2c_t *i2c, uint16_t i2cDeviceAddr, uint8_t *dataPtr, uint16_t dataLen, bool SendStop, EventGroupHandle_t event); -void i2cReset(i2c_t* i2c); +//stickbreaker debug support +uint32_t i2cDebug(i2c_t *, uint32_t setBits, uint32_t resetBits); +// Debug actions have 3 currently defined locus +// 0xXX------ : at entry of ProcQueue +// 0x--XX---- : at exit of ProcQueue +// 0x------XX : at entry of Flush +// +// bit 0 causes DumpI2c to execute +// bit 1 causes DumpInts to execute +// bit 2 causes DumpCmdqueue to execute +// bit 3 causes DumpStatus to execute +// bit 4 causes DumpFifo to execute #ifdef __cplusplus } diff --git a/cores/esp32/esp32-hal-ledc.c b/cores/esp32/esp32-hal-ledc.c index 64f4dc01fef..336d1efbb6b 100644 --- a/cores/esp32/esp32-hal-ledc.c +++ b/cores/esp32/esp32-hal-ledc.c @@ -53,6 +53,33 @@ xSemaphoreHandle _ledc_sys_lock; #define LEDC_CHAN(g,c) LEDC.channel_group[(g)].channel[(c)] #define LEDC_TIMER(g,t) LEDC.timer_group[(g)].timer[(t)] +static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb){ + if(ev_type == APB_AFTER_CHANGE && old_apb != new_apb){ + uint32_t iarg = (uint32_t)arg; + uint8_t chan = iarg; + uint8_t group=(chan/8), timer=((chan/2)%4); + old_apb /= 1000000; + new_apb /= 1000000; + if(LEDC_TIMER(group, timer).conf.tick_sel){ + LEDC_MUTEX_LOCK(); + uint32_t old_div = LEDC_TIMER(group, timer).conf.clock_divider; + uint32_t div_num = (new_apb * old_div) / old_apb; + if(div_num > LEDC_DIV_NUM_HSTIMER0_V){ + new_apb = REF_CLK_FREQ / 1000000; + div_num = (new_apb * old_div) / old_apb; + if(div_num > LEDC_DIV_NUM_HSTIMER0_V) { + div_num = LEDC_DIV_NUM_HSTIMER0_V;//lowest clock possible + } + LEDC_TIMER(group, timer).conf.tick_sel = 0; + } else if(div_num < 256) { + div_num = 256;//highest clock possible + } + LEDC_TIMER(group, timer).conf.clock_divider = div_num; + LEDC_MUTEX_UNLOCK(); + } + } +} + //uint32_t frequency = (80MHz or 1MHz)/((div_num / 256.0)*(1 << bit_num)); static void _ledcSetupTimer(uint8_t chan, uint32_t div_num, uint8_t bit_num, bool apb_clk) { @@ -78,13 +105,15 @@ static void _ledcSetupTimer(uint8_t chan, uint32_t div_num, uint8_t bit_num, boo LEDC_TIMER(group, timer).conf.rst = 1;//This bit is used to reset timer the counter will be 0 after reset. LEDC_TIMER(group, timer).conf.rst = 0; LEDC_MUTEX_UNLOCK(); + uint32_t iarg = chan; + addApbChangeCallback((void*)iarg, _on_apb_change); } //max div_num 0x3FFFF (262143) //max bit_num 0x1F (31) static double _ledcSetupTimerFreq(uint8_t chan, double freq, uint8_t bit_num) { - uint64_t clk_freq = APB_CLK_FREQ; + uint64_t clk_freq = getApbFrequency(); clk_freq <<= 8;//div_num is 8 bit decimal uint32_t div_num = (clk_freq >> bit_num) / freq; bool apb_clk = true; @@ -117,7 +146,7 @@ static double _ledcTimerRead(uint8_t chan) LEDC_MUTEX_UNLOCK(); uint64_t clk_freq = 1000000; if(apb_clk) { - clk_freq *= 80; + clk_freq = getApbFrequency(); } clk_freq <<= 8;//div_num is 8 bit decimal return (clk_freq >> bit_num) / (double)div_num; @@ -138,7 +167,7 @@ static void _ledcSetupChannel(uint8_t chan, uint8_t idle_level) LEDC_CHAN(group, channel).conf0.sig_out_en = 0;//This is the output enable control bit for channel LEDC_CHAN(group, channel).conf1.duty_start = 0;//When duty_num duty_cycle and duty_scale has been configured. these register won't take effect until set duty_start. this bit is automatically cleared by hardware. if(group) { - LEDC_CHAN(group, channel).conf0.val &= ~BIT(4); + LEDC_CHAN(group, channel).conf0.low_speed_update = 1; } else { LEDC_CHAN(group, channel).conf0.clk_en = 0; } @@ -167,7 +196,7 @@ void ledcWrite(uint8_t chan, uint32_t duty) LEDC_CHAN(group, channel).conf0.sig_out_en = 1;//This is the output enable control bit for channel LEDC_CHAN(group, channel).conf1.duty_start = 1;//When duty_num duty_cycle and duty_scale has been configured. these register won't take effect until set duty_start. this bit is automatically cleared by hardware. if(group) { - LEDC_CHAN(group, channel).conf0.val |= BIT(4); + LEDC_CHAN(group, channel).conf0.low_speed_update = 1; } else { LEDC_CHAN(group, channel).conf0.clk_en = 1; } @@ -175,7 +204,7 @@ void ledcWrite(uint8_t chan, uint32_t duty) LEDC_CHAN(group, channel).conf0.sig_out_en = 0;//This is the output enable control bit for channel LEDC_CHAN(group, channel).conf1.duty_start = 0;//When duty_num duty_cycle and duty_scale has been configured. these register won't take effect until set duty_start. this bit is automatically cleared by hardware. if(group) { - LEDC_CHAN(group, channel).conf0.val &= ~BIT(4); + LEDC_CHAN(group, channel).conf0.low_speed_update = 1; } else { LEDC_CHAN(group, channel).conf0.clk_en = 0; } diff --git a/cores/esp32/esp32-hal-log.h b/cores/esp32/esp32-hal-log.h index 1b7ea77fce8..e1d4e56f3bb 100644 --- a/cores/esp32/esp32-hal-log.h +++ b/cores/esp32/esp32-hal-log.h @@ -79,32 +79,50 @@ int log_printf(const char *fmt, ...); #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE #define log_v(format, ...) log_printf(ARDUHAL_LOG_FORMAT(V, format), ##__VA_ARGS__) +#define isr_log_v(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(V, format), ##__VA_ARGS__) #else #define log_v(format, ...) +#define isr_log_v(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG #define log_d(format, ...) log_printf(ARDUHAL_LOG_FORMAT(D, format), ##__VA_ARGS__) +#define isr_log_d(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(D, format), ##__VA_ARGS__) #else #define log_d(format, ...) +#define isr_log_d(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO #define log_i(format, ...) log_printf(ARDUHAL_LOG_FORMAT(I, format), ##__VA_ARGS__) +#define isr_log_i(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(I, format), ##__VA_ARGS__) #else #define log_i(format, ...) +#define isr_log_i(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN #define log_w(format, ...) log_printf(ARDUHAL_LOG_FORMAT(W, format), ##__VA_ARGS__) +#define isr_log_w(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(W, format), ##__VA_ARGS__) #else #define log_w(format, ...) +#define isr_log_w(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_ERROR #define log_e(format, ...) log_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__) +#define isr_log_e(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__) #else #define log_e(format, ...) +#define isr_log_e(format, ...) +#endif + +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_NONE +#define log_n(format, ...) log_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__) +#define isr_log_n(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__) +#else +#define log_n(format, ...) +#define isr_log_n(format, ...) #endif #include "esp_log.h" @@ -115,12 +133,22 @@ int log_printf(const char *fmt, ...); #undef ESP_LOGI #undef ESP_LOGD #undef ESP_LOGV +#undef ESP_EARLY_LOGE +#undef ESP_EARLY_LOGW +#undef ESP_EARLY_LOGI +#undef ESP_EARLY_LOGD +#undef ESP_EARLY_LOGV #define ESP_LOGE(tag, ...) log_e(__VA_ARGS__) #define ESP_LOGW(tag, ...) log_w(__VA_ARGS__) #define ESP_LOGI(tag, ...) log_i(__VA_ARGS__) #define ESP_LOGD(tag, ...) log_d(__VA_ARGS__) #define ESP_LOGV(tag, ...) log_v(__VA_ARGS__) +#define ESP_EARLY_LOGE(tag, ...) isr_log_e(__VA_ARGS__) +#define ESP_EARLY_LOGW(tag, ...) isr_log_w(__VA_ARGS__) +#define ESP_EARLY_LOGI(tag, ...) isr_log_i(__VA_ARGS__) +#define ESP_EARLY_LOGD(tag, ...) isr_log_d(__VA_ARGS__) +#define ESP_EARLY_LOGV(tag, ...) isr_log_v(__VA_ARGS__) #endif #ifdef __cplusplus diff --git a/cores/esp32/esp32-hal-misc.c b/cores/esp32/esp32-hal-misc.c index 7c87310eac2..be08e4b7313 100644 --- a/cores/esp32/esp32-hal-misc.c +++ b/cores/esp32/esp32-hal-misc.c @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "esp32-hal.h" #include "sdkconfig.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" @@ -21,8 +20,20 @@ #include "nvs.h" #include "esp_partition.h" #include "esp_log.h" -#include "pthread.h" +#include "esp_timer.h" +#ifdef CONFIG_APP_ROLLBACK_ENABLE +#include "esp_ota_ops.h" +#endif //CONFIG_APP_ROLLBACK_ENABLE +#ifdef CONFIG_BT_ENABLED +#include "esp_bt.h" +#endif //CONFIG_BT_ENABLED #include +#include "soc/rtc.h" +#include "soc/rtc_cntl_reg.h" +#include "soc/apb_ctrl_reg.h" +#include "rom/rtc.h" +#include "esp_task_wdt.h" +#include "esp32-hal.h" //Undocumented!!! Get chip temperature in Farenheit //Source: https://github.com/pcbreflux/espressif/blob/master/esp32/arduino/sketchbook/ESP32_int_temp_sensor/ESP32_int_temp_sensor.ino @@ -33,56 +44,101 @@ float temperatureRead() return (temprature_sens_read() - 32) / 1.8; } -void yield() +void __yield() { vPortYield(); } -portMUX_TYPE microsMux = portMUX_INITIALIZER_UNLOCKED; -static pthread_key_t microsStore=NULL; // Thread Local Storage Handle +void yield() __attribute__ ((weak, alias("__yield"))); + +#if CONFIG_AUTOSTART_ARDUINO -void microsStoreDelete(void * storage) { // release thread local data when task is delete. - if(storage) free(storage); +extern TaskHandle_t loopTaskHandle; +extern bool loopTaskWDTEnabled; + +void enableLoopWDT(){ + if(loopTaskHandle != NULL){ + if(esp_task_wdt_add(loopTaskHandle) != ESP_OK){ + log_e("Failed to add loop task to WDT"); + } else { + loopTaskWDTEnabled = true; + } + } } -unsigned long IRAM_ATTR micros() -{ - if (!microsStore) { // first Time Ever thread local not init'd - portENTER_CRITICAL_ISR(µsMux); - pthread_key_create(µsStore,microsStoreDelete); // create initial holder - portEXIT_CRITICAL_ISR(µsMux); +void disableLoopWDT(){ + if(loopTaskHandle != NULL && loopTaskWDTEnabled){ + loopTaskWDTEnabled = false; + if(esp_task_wdt_delete(loopTaskHandle) != ESP_OK){ + log_e("Failed to remove loop task from WDT"); + } } - - uint32_t *ptr;// [0] is lastCount, [1] is overFlow - - ptr = pthread_getspecific(microsStore); // get address of storage - - if(ptr == NULL) { // first time in this thread, allocate mem, init it. - portENTER_CRITICAL_ISR(µsMux); - ptr = (uint32_t*)malloc(sizeof(uint32_t)*2); - pthread_setspecific(microsStore,ptr); // store the pointer to this thread's values - ptr[0] = 0; // lastCount value - ptr[1] = 0; // overFlow - portEXIT_CRITICAL_ISR(µsMux); - } - - unsigned long ccount; - - portENTER_CRITICAL_ISR(µsMux); - __asm__ __volatile__ ( "rsr %0, ccount" : "=a" (ccount) ); //get cycle count - if(ccount < ptr[0]) { // overflow occurred - ptr[1] += UINT32_MAX / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ; +} + +void feedLoopWDT(){ + esp_err_t err = esp_task_wdt_reset(); + if(err != ESP_OK){ + log_e("Failed to feed WDT! Error: %d", err); } - - ptr[0] = ccount; - portEXIT_CRITICAL_ISR(µsMux); +} +#endif - return ptr[1] + (ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ); +void enableCore0WDT(){ + TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); + if(idle_0 == NULL || esp_task_wdt_add(idle_0) != ESP_OK){ + log_e("Failed to add Core 0 IDLE task to WDT"); + } +} + +void disableCore0WDT(){ + TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); + if(idle_0 == NULL || esp_task_wdt_delete(idle_0) != ESP_OK){ + log_e("Failed to remove Core 0 IDLE task from WDT"); + } +} + +#ifndef CONFIG_FREERTOS_UNICORE +void enableCore1WDT(){ + TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); + if(idle_1 == NULL || esp_task_wdt_add(idle_1) != ESP_OK){ + log_e("Failed to add Core 1 IDLE task to WDT"); + } +} + +void disableCore1WDT(){ + TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); + if(idle_1 == NULL || esp_task_wdt_delete(idle_1) != ESP_OK){ + log_e("Failed to remove Core 1 IDLE task from WDT"); + } +} +#endif + +BaseType_t xTaskCreateUniversal( TaskFunction_t pxTaskCode, + const char * const pcName, + const uint32_t usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + const BaseType_t xCoreID ){ +#ifndef CONFIG_FREERTOS_UNICORE + if(xCoreID >= 0 && xCoreID < 2) { + return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID); + } else { +#endif + return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); +#ifndef CONFIG_FREERTOS_UNICORE + } +#endif +} + +unsigned long IRAM_ATTR micros() +{ + return (unsigned long) (esp_timer_get_time()); } unsigned long IRAM_ATTR millis() { - return xTaskGetTickCount() * portTICK_PERIOD_MS; + return (unsigned long) (esp_timer_get_time() / 1000ULL); } void delay(uint32_t ms) @@ -112,8 +168,39 @@ void initVariant() {} void init() __attribute__((weak)); void init() {} +bool verifyOta() __attribute__((weak)); +bool verifyOta() { return true; } + +#ifdef CONFIG_BT_ENABLED +//overwritten in esp32-hal-bt.c +bool btInUse() __attribute__((weak)); +bool btInUse(){ return false; } +#endif + void initArduino() { +#ifdef CONFIG_APP_ROLLBACK_ENABLE + const esp_partition_t *running = esp_ota_get_running_partition(); + esp_ota_img_states_t ota_state; + if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) { + if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) { + if (verifyOta()) { + esp_ota_mark_app_valid_cancel_rollback(); + } else { + log_e("OTA verification failed! Start rollback to the previous version ..."); + esp_ota_mark_app_invalid_rollback_and_reboot(); + } + } + } +#endif + //init proper ref tick value for PLL (uncomment if REF_TICK is different than 1MHz) + //ESP_REG(APB_CTRL_PLL_TICK_CONF_REG) = APB_CLK_FREQ / REF_CLK_FREQ - 1; +#ifdef F_CPU + setCpuFrequencyMhz(F_CPU/1000000); +#endif +#if CONFIG_SPIRAM_SUPPORT + psramInit(); +#endif esp_log_level_set("*", CONFIG_LOG_DEFAULT_LEVEL); esp_err_t err = nvs_flash_init(); if(err == ESP_ERR_NVS_NO_FREE_PAGES){ @@ -130,6 +217,11 @@ void initArduino() if(err) { log_e("Failed to initialize NVS! Error: %u", err); } +#ifdef CONFIG_BT_ENABLED + if(!btInUse()){ + esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); + } +#endif init(); initVariant(); } diff --git a/cores/esp32/esp32-hal-psram.c b/cores/esp32/esp32-hal-psram.c new file mode 100644 index 00000000000..905cb96a313 --- /dev/null +++ b/cores/esp32/esp32-hal-psram.c @@ -0,0 +1,98 @@ + +#include "esp32-hal.h" + +#if CONFIG_SPIRAM_SUPPORT +#include "esp_spiram.h" +#include "soc/efuse_reg.h" +#include "esp_heap_caps.h" + +static volatile bool spiramDetected = false; +static volatile bool spiramFailed = false; + +bool psramInit(){ + if (spiramDetected) { + return true; + } +#ifndef CONFIG_SPIRAM_BOOT_INIT + if (spiramFailed) { + return false; + } + uint32_t chip_ver = REG_GET_FIELD(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_VER_PKG); + uint32_t pkg_ver = chip_ver & 0x7; + if (pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32D2WDQ5 || pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32PICOD2) { + spiramFailed = true; + log_w("PSRAM not supported!"); + return false; + } + esp_spiram_init_cache(); + if (esp_spiram_init() != ESP_OK) { + spiramFailed = true; + log_w("PSRAM init failed!"); + pinMatrixOutDetach(16, false, false); + pinMatrixOutDetach(17, false, false); + return false; + } + if (!esp_spiram_test()) { + spiramFailed = true; + log_e("PSRAM test failed!"); + return false; + } + if (esp_spiram_add_to_heapalloc() != ESP_OK) { + spiramFailed = true; + log_e("PSRAM could not be added to the heap!"); + return false; + } +#endif + spiramDetected = true; + log_d("PSRAM enabled"); + return true; +} + +bool IRAM_ATTR psramFound(){ + return spiramDetected; +} + +void IRAM_ATTR *ps_malloc(size_t size){ + if(!spiramDetected){ + return NULL; + } + return heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); +} + +void IRAM_ATTR *ps_calloc(size_t n, size_t size){ + if(!spiramDetected){ + return NULL; + } + return heap_caps_calloc(n, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); +} + +void IRAM_ATTR *ps_realloc(void *ptr, size_t size){ + if(!spiramDetected){ + return NULL; + } + return heap_caps_realloc(ptr, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); +} + +#else + +bool psramInit(){ + return false; +} + +bool IRAM_ATTR psramFound(){ + return false; +} + +void IRAM_ATTR *ps_malloc(size_t size){ + return NULL; +} + +void IRAM_ATTR *ps_calloc(size_t n, size_t size){ + return NULL; +} + +void IRAM_ATTR *ps_realloc(void *ptr, size_t size){ + return NULL; +} + +#endif diff --git a/cores/esp32/esp32-hal-psram.h b/cores/esp32/esp32-hal-psram.h new file mode 100644 index 00000000000..36acc0a03de --- /dev/null +++ b/cores/esp32/esp32-hal-psram.h @@ -0,0 +1,33 @@ +// 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 _ESP32_HAL_PSRAM_H_ +#define _ESP32_HAL_PSRAM_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +bool psramInit(); +bool psramFound(); + +void *ps_malloc(size_t size); +void *ps_calloc(size_t n, size_t size); +void *ps_realloc(void *ptr, size_t size); + +#ifdef __cplusplus +} +#endif + +#endif /* _ESP32_HAL_PSRAM_H_ */ diff --git a/cores/esp32/esp32-hal-rmt.c b/cores/esp32/esp32-hal-rmt.c new file mode 100644 index 00000000000..0a614226c29 --- /dev/null +++ b/cores/esp32/esp32-hal-rmt.c @@ -0,0 +1,820 @@ +// 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. + +#include "freertos/FreeRTOS.h" +#include "freertos/event_groups.h" +#include "freertos/semphr.h" + +#include "esp32-hal.h" +#include "esp8266-compat.h" +#include "soc/gpio_reg.h" +#include "soc/gpio_reg.h" + +#include "esp32-hal-rmt.h" +#include "driver/periph_ctrl.h" + +#include "soc/rmt_struct.h" +#include "esp_intr_alloc.h" + +/** + * Internal macros + */ +#define MAX_CHANNELS 8 +#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) +#define __INT_TX_END (1) +#define __INT_RX_END (2) +#define __INT_ERROR (4) +#define __INT_THR_EVNT (1<<24) + +#define _INT_TX_END(channel) (__INT_TX_END<<(channel*3)) +#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)) + +#if CONFIG_DISABLE_HAL_LOCKS +# define RMT_MUTEX_LOCK(channel) +# define RMT_MUTEX_UNLOCK(channel) +#else +# define RMT_MUTEX_LOCK(channel) do {} while (xSemaphoreTake(g_rmt_objlocks[channel], portMAX_DELAY) != pdPASS) +# define RMT_MUTEX_UNLOCK(channel) xSemaphoreGive(g_rmt_objlocks[channel]) +#endif /* CONFIG_DISABLE_HAL_LOCKS */ + +#define _RMT_INTERNAL_DEBUG +#ifdef _RMT_INTERNAL_DEBUG +# define DEBUG_INTERRUPT_START(pin) digitalWrite(pin, 1); +# define DEBUG_INTERRUPT_END(pin) digitalWrite(pin, 0); +#else +# define DEBUG_INTERRUPT_START(pin) +# define DEBUG_INTERRUPT_END(pin) +#endif /* _RMT_INTERNAL_DEBUG */ + +/** + * Typedefs for internal stuctures, enums + */ +typedef enum { + E_NO_INTR = 0, + E_TX_INTR = 1, + E_TXTHR_INTR = 2, + E_RX_INTR = 4, +} intr_mode_t; + +typedef enum { + E_INACTIVE = 0, + E_FIRST_HALF = 1, + E_LAST_DATA = 2, + E_END_TRANS = 4, + E_SET_CONTI = 8, +} transaction_state_t; + +struct rmt_obj_s +{ + bool allocated; + EventGroupHandle_t events; + int pin; + int channel; + bool tx_not_rx; + int buffers; + int data_size; + uint32_t* data_ptr; + intr_mode_t intr_mode; + transaction_state_t tx_state; + rmt_rx_data_cb_t cb; + bool data_alloc; +}; + +/** + * Internal variables for channel descriptors + */ +static xSemaphoreHandle g_rmt_objlocks[MAX_CHANNELS] = { + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL +}; + +static rmt_obj_t g_rmt_objects[MAX_CHANNELS] = { + { false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false}, + { false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false}, + { false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false}, + { false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false}, + { false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false}, + { false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false}, + { false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false}, + { false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false}, +}; + +/** + * Internal variables for driver data + */ +static intr_handle_t intr_handle; + +static bool periph_enabled = false; + +static xSemaphoreHandle g_rmt_block_lock = NULL; + +/** + * Internal method (private) declarations + */ +static void _initPin(int pin, int channel, bool tx_not_rx); + +static bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size); + +static void IRAM_ATTR _rmt_isr(void* arg); + +static rmt_obj_t* _rmtAllocate(int pin, int from, int size); + +static void _initPin(int pin, int channel, bool tx_not_rx); + +static int IRAM_ATTR _rmt_get_mem_len(uint8_t channel); + +static void IRAM_ATTR _rmt_tx_mem_first(uint8_t ch); + +static void IRAM_ATTR _rmt_tx_mem_second(uint8_t ch); + + +/** + * Public method definitions + */ +bool rmtSetCarrier(rmt_obj_t* rmt, bool carrier_en, bool carrier_level, uint32_t low, uint32_t high) +{ + if (!rmt || low > 0xFFFF || high > 0xFFFF) { + return false; + } + size_t channel = rmt->channel; + + RMT_MUTEX_LOCK(channel); + + 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; + + RMT_MUTEX_UNLOCK(channel); + + return true; + +} + +bool rmtSetFilter(rmt_obj_t* rmt, bool filter_en, uint32_t filter_level) +{ + if (!rmt || filter_level > 0xFF) { + return false; + } + size_t channel = rmt->channel; + + RMT_MUTEX_LOCK(channel); + + RMT.conf_ch[channel].conf1.rx_filter_thres = filter_level; + RMT.conf_ch[channel].conf1.rx_filter_en = filter_en; + + RMT_MUTEX_UNLOCK(channel); + + return true; + +} + +bool rmtSetRxThreshold(rmt_obj_t* rmt, uint32_t value) +{ + if (!rmt || value > 0xFFFF) { + return false; + } + size_t channel = rmt->channel; + + RMT_MUTEX_LOCK(channel); + RMT.conf_ch[channel].conf0.idle_thres = value; + RMT_MUTEX_UNLOCK(channel); + + return true; +} + + +bool rmtDeinit(rmt_obj_t *rmt) +{ + if (!rmt) { + return false; + } + + // sanity check + if (rmt != &(g_rmt_objects[rmt->channel])) { + return false; + } + + size_t from = rmt->channel; + size_t to = rmt->buffers + rmt->channel; + size_t i; + +#if !CONFIG_DISABLE_HAL_LOCKS + if(g_rmt_objlocks[from] != NULL) { + vSemaphoreDelete(g_rmt_objlocks[from]); + } +#endif + + if (g_rmt_objects[from].data_alloc) { + free(g_rmt_objects[from].data_ptr); + } + + for (i = from; i < to; i++) { + g_rmt_objects[i].allocated = false; + } + + g_rmt_objects[from].channel = 0; + g_rmt_objects[from].buffers = 0; + + return true; +} + +bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size) +{ + if (!rmt) { + return false; + } + + int channel = rmt->channel; + int allocated_size = MAX_DATA_PER_CHANNEL * rmt->buffers; + + if (size > allocated_size) { + + int half_tx_nr = MAX_DATA_PER_ITTERATION/2; + RMT_MUTEX_LOCK(channel); + // setup interrupt handler if not yet installed for half and full tx + if (!intr_handle) { + esp_intr_alloc(ETS_RMT_INTR_SOURCE, (int)ESP_INTR_FLAG_IRAM, _rmt_isr, NULL, &intr_handle); + } + + rmt->data_size = size - MAX_DATA_PER_ITTERATION; + rmt->data_ptr = ((uint32_t*)data) + MAX_DATA_PER_ITTERATION; + rmt->intr_mode = E_TX_INTR | E_TXTHR_INTR; + rmt->tx_state = E_SET_CONTI | E_FIRST_HALF; + + // init the tx limit for interruption + RMT.tx_lim_ch[channel].limit = half_tx_nr+2; + // reset memory pointer + RMT.conf_ch[channel].conf1.apb_mem_rst = 1; + RMT.conf_ch[channel].conf1.apb_mem_rst = 0; + RMT.conf_ch[channel].conf1.mem_rd_rst = 1; + 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; + + // set the tx end mark + 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); + RMT.int_clr.val = _INT_THR_EVNT(channel); + RMT.int_clr.val = _INT_ERROR(channel); + + RMT.int_ena.val |= _INT_TX_END(channel); + RMT.int_ena.val |= _INT_THR_EVNT(channel); + RMT.int_ena.val |= _INT_ERROR(channel); + + RMT_MUTEX_UNLOCK(channel); + + // start the transation + return _rmtSendOnce(rmt, data, MAX_DATA_PER_ITTERATION); + } else { + // use one-go mode if data fits one buffer + return _rmtSendOnce(rmt, data, size); + } +} + +bool rmtReadData(rmt_obj_t* rmt, uint32_t* data, size_t size) +{ + if (!rmt) { + return false; + } + int channel = rmt->channel; + + if (g_rmt_objects[channel].buffers < size/MAX_DATA_PER_CHANNEL) { + return false; + } + + size_t i; + volatile uint32_t* rmt_mem_ptr = &(RMTMEM.chan[channel].data32[0].val); + for (i=0; ichannel; + + RMT.int_clr.val = _INT_ERROR(channel); + RMT.int_ena.val |= _INT_ERROR(channel); + + 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; + + return true; +} + +bool rmtReceiveCompleted(rmt_obj_t* rmt) +{ + if (!rmt) { + return false; + } + int channel = rmt->channel; + + if (RMT.int_raw.val&_INT_RX_END(channel)) { + // RX end flag + RMT.int_clr.val = _INT_RX_END(channel); + return true; + } else { + return false; + } +} + +bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb) +{ + if (!rmt && !cb) { + return false; + } + int channel = rmt->channel; + + RMT_MUTEX_LOCK(channel); + rmt->intr_mode = E_RX_INTR; + rmt->tx_state = E_FIRST_HALF; + rmt->cb = cb; + // allocate internally two buffers which would alternate + if (!rmt->data_alloc) { + rmt->data_ptr = (uint32_t*)malloc(2*MAX_DATA_PER_CHANNEL*(rmt->buffers)*sizeof(uint32_t)); + rmt->data_size = MAX_DATA_PER_CHANNEL*rmt->buffers; + rmt->data_alloc = true; + } + + RMT.conf_ch[channel].conf1.mem_owner = 1; + + 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); + + RMT.conf_ch[channel].conf1.mem_wr_rst = 1; + + RMT.conf_ch[channel].conf1.rx_en = 1; + RMT_MUTEX_UNLOCK(channel); + + return true; +} + +bool rmtReadAsync(rmt_obj_t* rmt, rmt_data_t* data, size_t size, void* eventFlag, bool waitForData, uint32_t timeout) +{ + if (!rmt) { + return false; + } + int channel = rmt->channel; + + if (g_rmt_objects[channel].buffers < size/MAX_DATA_PER_CHANNEL) { + return false; + } + + if (eventFlag) { + xEventGroupClearBits(eventFlag, RMT_FLAGS_ALL); + rmt->events = eventFlag; + } + + if (data && size>0) { + rmt->data_ptr = (uint32_t*)data; + rmt->data_size = size; + } + + RMT_MUTEX_LOCK(channel); + rmt->intr_mode = E_RX_INTR; + + RMT.conf_ch[channel].conf1.mem_owner = 1; + + 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); + + RMT.conf_ch[channel].conf1.mem_wr_rst = 1; + + RMT.conf_ch[channel].conf1.rx_en = 1; + RMT_MUTEX_UNLOCK(channel); + + // wait for data if requested so + if (waitForData && eventFlag) { + uint32_t flags = xEventGroupWaitBits(eventFlag, RMT_FLAGS_ALL, + pdTRUE /* clear on exit */, pdFALSE /* wait for all bits */, timeout); + if (flags & RMT_FLAG_ERROR) { + return false; + } + } + + return true; +} + +float rmtSetTick(rmt_obj_t* rmt, float tick) +{ + if (!rmt) { + return false; + } + /* + divider field span from 1 (smallest), 2, 3, ... , 0xFF, 0x00 (highest) + * rmt tick from 1/80M -> 12.5ns (1x) div_cnt = 0x01 + 3.2 us (256x) div_cnt = 0x00 + * 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 (_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; + return apb_tick; + } else { + RMT.conf_ch[channel].conf0.div_cnt = ref_div & 0xFF; + RMT.conf_ch[channel].conf1.ref_always_on = 0; + return ref_tick; + } +} + +rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize) +{ + int buffers = memsize; + rmt_obj_t* rmt; + size_t i; + size_t j; + + // create common block mutex for protecting allocs from multiple threads + if (!g_rmt_block_lock) { + g_rmt_block_lock = xSemaphoreCreateMutex(); + } + // lock + while (xSemaphoreTake(g_rmt_block_lock, portMAX_DELAY) != pdPASS) {} + + for (i=0; i= MAX_CHANNELS || j != buffers) { + xSemaphoreGive(g_rmt_block_lock); + return NULL; + } + rmt = _rmtAllocate(pin, i, buffers); + + xSemaphoreGive(g_rmt_block_lock); + + size_t channel = i; + +#if !CONFIG_DISABLE_HAL_LOCKS + if(g_rmt_objlocks[channel] == NULL) { + g_rmt_objlocks[channel] = xSemaphoreCreateMutex(); + if(g_rmt_objlocks[channel] == NULL) { + return NULL; + } + } +#endif + + RMT_MUTEX_LOCK(channel); + + rmt->pin = pin; + rmt->tx_not_rx = tx_not_rx; + rmt->buffers =buffers; + rmt->channel = channel; + _initPin(pin, channel, tx_not_rx); + + // Initialize the registers in default mode: + // - no carrier, filter + // - timebase tick of 1us + // - idle threshold set to 0x8000 (max pulse width + 1) + RMT.conf_ch[channel].conf0.div_cnt = 1; + RMT.conf_ch[channel].conf0.mem_size = buffers; + RMT.conf_ch[channel].conf0.carrier_en = 0; + RMT.conf_ch[channel].conf0.carrier_out_lv = 0; + RMT.conf_ch[channel].conf0.mem_pd = 0; + + RMT.conf_ch[channel].conf0.idle_thres = 0x80; + RMT.conf_ch[channel].conf1.rx_en = 0; + RMT.conf_ch[channel].conf1.tx_conti_mode = 0; + RMT.conf_ch[channel].conf1.ref_cnt_rst = 0; + RMT.conf_ch[channel].conf1.rx_filter_en = 0; + RMT.conf_ch[channel].conf1.rx_filter_thres = 0; + RMT.conf_ch[channel].conf1.idle_out_lv = 0; // signal level for idle + RMT.conf_ch[channel].conf1.idle_out_en = 1; // enable idle + RMT.conf_ch[channel].conf1.ref_always_on = 0; // base clock + RMT.apb_conf.fifo_mask = 1; + + if (tx_not_rx) { + // RMT.conf_ch[channel].conf1.rx_en = 0; + RMT.conf_ch[channel].conf1.mem_owner = 0; + RMT.conf_ch[channel].conf1.mem_rd_rst = 1; + } else { + // RMT.conf_ch[channel].conf1.rx_en = 1; + RMT.conf_ch[channel].conf1.mem_owner = 1; + RMT.conf_ch[channel].conf1.mem_wr_rst = 1; + } + + // install interrupt if at least one channel is active + if (!intr_handle) { + esp_intr_alloc(ETS_RMT_INTR_SOURCE, (int)ESP_INTR_FLAG_IRAM, _rmt_isr, NULL, &intr_handle); + } + RMT_MUTEX_UNLOCK(channel); + + return rmt; +} + +/** + * Private methods definitions + */ +bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size) +{ + if (!rmt) { + return false; + } + int channel = rmt->channel; + RMT.apb_conf.fifo_mask = 1; + if (data && size>0) { + size_t i; + volatile uint32_t* rmt_mem_ptr = &(RMTMEM.chan[channel].data32[0].val); + for (i = 0; i < size; i++) { + *rmt_mem_ptr++ = data[i].val; + } + // tx end mark + RMTMEM.chan[channel].data32[size].val = 0; + } + + RMT_MUTEX_LOCK(channel); + RMT.conf_ch[channel].conf1.mem_rd_rst = 1; + RMT.conf_ch[channel].conf1.tx_start = 1; + RMT_MUTEX_UNLOCK(channel); + + return true; +} + + +static rmt_obj_t* _rmtAllocate(int pin, int from, int size) +{ + size_t i; + // setup how many buffers shall we use + g_rmt_objects[from].buffers = size; + + for (i=0; i 0) { + size_t i; + uint32_t * data = g_rmt_objects[ch].data_ptr; + // in case of callback, provide switching between memories + if (g_rmt_objects[ch].cb) { + if (g_rmt_objects[ch].tx_state & E_FIRST_HALF) { + g_rmt_objects[ch].tx_state &= ~E_FIRST_HALF; + } else { + g_rmt_objects[ch].tx_state |= E_FIRST_HALF; + data += MAX_DATA_PER_CHANNEL*(g_rmt_objects[ch].buffers); + } + } + uint32_t *data_received = data; + for (i = 0; i < g_rmt_objects[ch].data_size; i++ ) { + *data++ = RMTMEM.chan[ch].data32[i].val; + } + if (g_rmt_objects[ch].cb) { + // actually received data ptr + (g_rmt_objects[ch].cb)(data_received, _rmt_get_mem_len(ch)); + + // restart the reception + 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; + RMT.int_ena.val |= _INT_RX_END(ch); + } else { + // if not callback provide, expect only one Rx + g_rmt_objects[ch].intr_mode &= ~E_RX_INTR; + } + } + } else { + // Report error and disable Rx interrupt + log_e("Unexpected Rx interrupt!\n"); // TODO: eplace messages with log_X + RMT.int_ena.val &= ~_INT_RX_END(ch); + } + + + } + + if (intr_val & _INT_ERROR(ch)) { + // clear the flag + RMT.int_clr.val = _INT_ERROR(ch); + RMT.int_ena.val &= ~_INT_ERROR(ch); + // report error + log_e("RMT Error %d!\n", ch); + if (g_rmt_objects[ch].events) { + xEventGroupSetBits(g_rmt_objects[ch].events, RMT_FLAG_ERROR); + } + // reset memory + 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; + } + + if (intr_val & _INT_TX_END(ch)) { + + RMT.int_clr.val = _INT_TX_END(ch); + _rmt_tx_mem_second(ch); + } + + if (intr_val & _INT_THR_EVNT(ch)) { + // clear the flag + RMT.int_clr.val = _INT_THR_EVNT(ch); + + // initial setup of continuous mode + if (g_rmt_objects[ch].tx_state & E_SET_CONTI) { + RMT.conf_ch[ch].conf1.tx_conti_mode = 1; + g_rmt_objects[ch].intr_mode &= ~E_SET_CONTI; + } + _rmt_tx_mem_first(ch); + } + } +} + +static void IRAM_ATTR _rmt_tx_mem_second(uint8_t ch) +{ + DEBUG_INTERRUPT_START(4) + uint32_t* data = g_rmt_objects[ch].data_ptr; + int half_tx_nr = MAX_DATA_PER_ITTERATION/2; + int i; + + RMT.tx_lim_ch[ch].limit = half_tx_nr+2; + RMT.int_clr.val = _INT_THR_EVNT(ch); + RMT.int_ena.val |= _INT_THR_EVNT(ch); + + g_rmt_objects[ch].tx_state |= E_FIRST_HALF; + + if (data) { + int remaining_size = g_rmt_objects[ch].data_size; + // will the remaining data occupy the entire halfbuffer + if (remaining_size > half_tx_nr) { + for (i = 0; i < half_tx_nr; i++) { + RMTMEM.chan[ch].data32[half_tx_nr+i].val = data[i]; + } + g_rmt_objects[ch].data_size -= half_tx_nr; + g_rmt_objects[ch].data_ptr += half_tx_nr; + } else { + for (i = 0; i < half_tx_nr; i++) { + if (i < remaining_size) { + RMTMEM.chan[ch].data32[half_tx_nr+i].val = data[i]; + } else { + RMTMEM.chan[ch].data32[half_tx_nr+i].val = 0x000F000F; + } + } + g_rmt_objects[ch].data_ptr = NULL; + + } + } else if ((!(g_rmt_objects[ch].tx_state & E_LAST_DATA)) && + (!(g_rmt_objects[ch].tx_state & E_END_TRANS))) { + 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; + RMT.conf_ch[ch].conf1.tx_conti_mode = 0; + } else { + log_d("RMT Tx finished %d!\n", ch); + RMT.conf_ch[ch].conf1.tx_conti_mode = 0; + 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; + g_rmt_objects[ch].tx_state = E_INACTIVE; + } + DEBUG_INTERRUPT_END(4); +} + +static void IRAM_ATTR _rmt_tx_mem_first(uint8_t ch) +{ + DEBUG_INTERRUPT_START(2); + uint32_t* data = g_rmt_objects[ch].data_ptr; + int half_tx_nr = MAX_DATA_PER_ITTERATION/2; + int i; + RMT.int_ena.val &= ~_INT_THR_EVNT(ch); + RMT.tx_lim_ch[ch].limit = 0; + + if (data) { + int remaining_size = g_rmt_objects[ch].data_size; + + // will the remaining data occupy the entire halfbuffer + if (remaining_size > half_tx_nr) { + RMTMEM.chan[ch].data32[0].val = data[0] - 1; + for (i = 1; i < half_tx_nr; i++) { + RMTMEM.chan[ch].data32[i].val = data[i]; + } + g_rmt_objects[ch].tx_state &= ~E_FIRST_HALF; + // turn off the treshold interrupt + RMT.int_ena.val &= ~_INT_THR_EVNT(ch); + RMT.tx_lim_ch[ch].limit = 0; + g_rmt_objects[ch].data_size -= half_tx_nr; + g_rmt_objects[ch].data_ptr += half_tx_nr; + } else { + RMTMEM.chan[ch].data32[0].val = data[0] - 1; + for (i = 1; i < half_tx_nr; i++) { + if (i < remaining_size) { + RMTMEM.chan[ch].data32[i].val = data[i]; + } else { + RMTMEM.chan[ch].data32[i].val = 0x000F000F; + } + } + + g_rmt_objects[ch].tx_state &= ~E_FIRST_HALF; + g_rmt_objects[ch].data_ptr = NULL; + } + } else { + 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; + RMT.tx_lim_ch[ch].limit = 0; + g_rmt_objects[ch].tx_state |= E_LAST_DATA; + RMT.conf_ch[ch].conf1.tx_conti_mode = 0; + } + DEBUG_INTERRUPT_END(2); +} + +static int IRAM_ATTR _rmt_get_mem_len(uint8_t channel) +{ + int block_num = RMT.conf_ch[channel].conf0.mem_size; + int item_block_len = block_num * 64; + volatile rmt_item32_t* data = RMTMEM.chan[channel].data32; + int idx; + for(idx = 0; idx < item_block_len; idx++) { + if(data[idx].duration0 == 0) { + return idx; + } else if(data[idx].duration1 == 0) { + return idx + 1; + } + } + return idx; +} diff --git a/cores/esp32/esp32-hal-rmt.h b/cores/esp32/esp32-hal-rmt.h new file mode 100644 index 00000000000..19afcef89c7 --- /dev/null +++ b/cores/esp32/esp32-hal-rmt.h @@ -0,0 +1,141 @@ +// 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 MAIN_ESP32_HAL_RMT_H_ +#define MAIN_ESP32_HAL_RMT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +// notification flags +#define RMT_FLAG_TX_DONE (1) +#define RMT_FLAG_RX_DONE (2) +#define RMT_FLAG_ERROR (4) +#define RMT_FLAGS_ALL (RMT_FLAG_TX_DONE | RMT_FLAG_RX_DONE | RMT_FLAG_ERROR) + +struct rmt_obj_s; + +typedef enum { + RMT_MEM_64 = 1, + RMT_MEM_128 = 2, + RMT_MEM_192 = 3, + RMT_MEM_256 = 4, + RMT_MEM_320 = 5, + RMT_MEM_384 = 6, + RMT_MEM_448 = 7, + RMT_MEM_512 = 8, +} rmt_reserve_memsize_t; + +typedef struct rmt_obj_s rmt_obj_t; + +typedef void (*rmt_rx_data_cb_t)(uint32_t *data, size_t len); + +typedef struct { + union { + struct { + uint32_t duration0 :15; + uint32_t level0 :1; + uint32_t duration1 :15; + uint32_t level1 :1; + }; + uint32_t val; + }; +} rmt_data_t; + +/** +* Initialize the object +* +*/ +rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize); + +/** +* Sets the clock/divider of timebase the nearest tick to the supplied value in nanoseconds +* return the real actual tick value in ns +*/ +float rmtSetTick(rmt_obj_t* rmt, float tick); + +/** +* Sending data in one-go mode or continual mode +* (more data being send while updating buffers in interrupts) +* +*/ +bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size); + +/** +* Initiates async receive, event flag indicates data received +* +*/ +bool rmtReadAsync(rmt_obj_t* rmt, rmt_data_t* data, size_t size, void* eventFlag, bool waitForData, uint32_t timeout); + +/** +* Initiates async receive with automatic buffering +* and callback with data from ISR +* +*/ +bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb); + + +/* Additional interface */ + +/** +* Start reception +* +*/ +bool rmtBeginReceive(rmt_obj_t* rmt); + +/** +* Checks if reception completes +* +*/ +bool rmtReceiveCompleted(rmt_obj_t* rmt); + +/** +* Reads the data for particular channel +* +*/ +bool rmtReadData(rmt_obj_t* rmt, uint32_t* data, size_t size); + +/** + * Setting threshold for Rx completed + */ +bool rmtSetRxThreshold(rmt_obj_t* rmt, uint32_t value); + +/** + * Setting carrier + */ +bool rmtSetCarrier(rmt_obj_t* rmt, bool carrier_en, bool carrier_level, uint32_t low, uint32_t high); + +/** + * Setting input filter + */ +bool rmtSetFilter(rmt_obj_t* rmt, bool filter_en, uint32_t filter_level); + +/** + * Deinitialize the driver + */ +bool rmtDeinit(rmt_obj_t *rmt); + +// TODO: +// * uninstall interrupt when all channels are deinit +// * send only-conti mode with circular-buffer +// * put sanity checks to some macro or inlines +// * doxy comments +// * error reporting + +#ifdef __cplusplus +} +#endif + +#endif /* MAIN_ESP32_HAL_RMT_H_ */ diff --git a/cores/esp32/esp32-hal-sigmadelta.c b/cores/esp32/esp32-hal-sigmadelta.c index 78d8c40f606..098181c77ae 100644 --- a/cores/esp32/esp32-hal-sigmadelta.c +++ b/cores/esp32/esp32-hal-sigmadelta.c @@ -31,6 +31,26 @@ xSemaphoreHandle _sd_sys_lock; #endif +static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb){ + if(old_apb == new_apb){ + return; + } + uint32_t iarg = (uint32_t)arg; + uint8_t channel = iarg; + if(ev_type == APB_BEFORE_CHANGE){ + SIGMADELTA.cg.clk_en = 0; + } else { + old_apb /= 1000000; + new_apb /= 1000000; + SD_MUTEX_LOCK(); + uint32_t old_prescale = SIGMADELTA.channel[channel].prescale + 1; + SIGMADELTA.channel[channel].prescale = ((new_apb * old_prescale) / old_apb) - 1; + SIGMADELTA.cg.clk_en = 0; + SIGMADELTA.cg.clk_en = 1; + SD_MUTEX_UNLOCK(); + } +} + uint32_t sigmaDeltaSetup(uint8_t channel, uint32_t freq) //chan 0-7 freq 1220-312500 { if(channel > 7) { @@ -43,7 +63,8 @@ uint32_t sigmaDeltaSetup(uint8_t channel, uint32_t freq) //chan 0-7 freq 1220-31 _sd_sys_lock = xSemaphoreCreateMutex(); } #endif - uint32_t prescale = (10000000/(freq*32)) - 1; + uint32_t apb_freq = getApbFrequency(); + uint32_t prescale = (apb_freq/(freq*256)) - 1; if(prescale > 0xFF) { prescale = 0xFF; } @@ -52,7 +73,9 @@ uint32_t sigmaDeltaSetup(uint8_t channel, uint32_t freq) //chan 0-7 freq 1220-31 SIGMADELTA.cg.clk_en = 0; SIGMADELTA.cg.clk_en = 1; SD_MUTEX_UNLOCK(); - return 10000000/((prescale + 1) * 32); + uint32_t iarg = channel; + addApbChangeCallback((void*)iarg, _on_apb_change); + return apb_freq/((prescale + 1) * 256); } void sigmaDeltaWrite(uint8_t channel, uint8_t duty) //chan 0-7 duty 8 bit @@ -60,7 +83,7 @@ void sigmaDeltaWrite(uint8_t channel, uint8_t duty) //chan 0-7 duty 8 bit if(channel > 7) { return; } - duty += 128; + duty -= 128; SD_MUTEX_LOCK(); SIGMADELTA.channel[channel].duty = duty; SD_MUTEX_UNLOCK(); @@ -72,7 +95,7 @@ uint8_t sigmaDeltaRead(uint8_t channel) //chan 0-7 return 0; } SD_MUTEX_LOCK(); - uint8_t duty = SIGMADELTA.channel[channel].duty - 128; + uint8_t duty = SIGMADELTA.channel[channel].duty + 128; SD_MUTEX_UNLOCK(); return duty; } diff --git a/cores/esp32/esp32-hal-spi.c b/cores/esp32/esp32-hal-spi.c index 52fa1175091..cf302cac88f 100644 --- a/cores/esp32/esp32-hal-spi.c +++ b/cores/esp32/esp32-hal-spi.c @@ -26,6 +26,7 @@ #include "soc/io_mux_reg.h" #include "soc/gpio_sig_map.h" #include "soc/dport_reg.h" +#include "soc/rtc.h" #define SPI_CLK_IDX(p) ((p==0)?SPICLK_OUT_IDX:((p==1)?SPICLK_OUT_IDX:((p==2)?HSPICLK_OUT_IDX:((p==3)?VSPICLK_OUT_IDX:0)))) #define SPI_MISO_IDX(p) ((p==0)?SPIQ_OUT_IDX:((p==1)?SPIQ_OUT_IDX:((p==2)?HSPIQ_OUT_IDX:((p==3)?VSPIQ_OUT_IDX:0)))) @@ -371,6 +372,18 @@ void spiSetBitOrder(spi_t * spi, uint8_t bitOrder) SPI_MUTEX_UNLOCK(); } +static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb) +{ + spi_t * spi = (spi_t *)arg; + if(ev_type == APB_BEFORE_CHANGE){ + SPI_MUTEX_LOCK(); + while(spi->dev->cmd.usr); + } else { + spi->dev->clock.val = spiFrequencyToClockDiv(old_apb / ((spi->dev->clock.clkdiv_pre + 1) * (spi->dev->clock.clkcnt_n + 1))); + SPI_MUTEX_UNLOCK(); + } +} + void spiStopBus(spi_t * spi) { if(!spi) { @@ -387,6 +400,7 @@ void spiStopBus(spi_t * spi) spi->dev->ctrl2.val = 0; spi->dev->clock.val = 0; SPI_MUTEX_UNLOCK(); + removeApbChangeCallback(spi, _on_apb_change); } spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_t bitOrder) @@ -433,6 +447,7 @@ spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_ } SPI_MUTEX_UNLOCK(); + addApbChangeCallback(spi, _on_apb_change); return spi; } @@ -444,7 +459,7 @@ void spiWaitReady(spi_t * spi) while(spi->dev->cmd.usr); } -void spiWrite(spi_t * spi, uint32_t *data, uint8_t len) +void spiWrite(spi_t * spi, const uint32_t *data, uint8_t len) { if(!spi) { return; @@ -517,17 +532,7 @@ uint8_t spiTransferByte(spi_t * spi, uint8_t data) return data; } -uint32_t __spiTranslate24(uint32_t data) -{ - union { - uint32_t l; - uint8_t b[4]; - } out; - out.l = data; - return out.b[2] | (out.b[1] << 8) | (out.b[0] << 16); -} - -uint32_t __spiTranslate32(uint32_t data) +static uint32_t __spiTranslate32(uint32_t data) { union { uint32_t l; @@ -615,7 +620,7 @@ uint32_t spiTransferLong(spi_t * spi, uint32_t data) return data; } -void __spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t bytes) +static void __spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, uint32_t bytes) { if(!spi) { return; @@ -656,7 +661,7 @@ void __spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t byt } } -void spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t size) +void spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, uint32_t size) { if(!spi) { return; @@ -750,7 +755,7 @@ void spiEndTransaction(spi_t * spi) SPI_MUTEX_UNLOCK(); } -void spiWriteByteNL(spi_t * spi, uint8_t data) +void IRAM_ATTR spiWriteByteNL(spi_t * spi, uint8_t data) { if(!spi) { return; @@ -776,7 +781,7 @@ uint8_t spiTransferByteNL(spi_t * spi, uint8_t data) return data; } -void spiWriteShortNL(spi_t * spi, uint16_t data) +void IRAM_ATTR spiWriteShortNL(spi_t * spi, uint16_t data) { if(!spi) { return; @@ -811,7 +816,7 @@ uint16_t spiTransferShortNL(spi_t * spi, uint16_t data) return data; } -void spiWriteLongNL(spi_t * spi, uint32_t data) +void IRAM_ATTR spiWriteLongNL(spi_t * spi, uint32_t data) { if(!spi) { return; @@ -846,7 +851,7 @@ uint32_t spiTransferLongNL(spi_t * spi, uint32_t data) return data; } -void spiWriteNL(spi_t * spi, const void * data_in, size_t len){ +void spiWriteNL(spi_t * spi, const void * data_in, uint32_t len){ size_t longs = len >> 2; if(len & 3){ longs++; @@ -872,7 +877,7 @@ void spiWriteNL(spi_t * spi, const void * data_in, size_t len){ } } -void spiTransferBytesNL(spi_t * spi, const void * data_in, uint8_t * data_out, size_t len){ +void spiTransferBytesNL(spi_t * spi, const void * data_in, uint8_t * data_out, uint32_t len){ if(!spi) { return; } @@ -959,7 +964,7 @@ void spiTransferBitsNL(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits) } } -void spiWritePixelsNL(spi_t * spi, const void * data_in, size_t len){ +void IRAM_ATTR spiWritePixelsNL(spi_t * spi, const void * data_in, uint32_t len){ size_t longs = len >> 2; if(len & 3){ longs++; @@ -1007,35 +1012,37 @@ void spiWritePixelsNL(spi_t * spi, const void * data_in, size_t len){ * */ typedef union { - uint32_t regValue; + uint32_t value; struct { - unsigned regL :6; - unsigned regH :6; - unsigned regN :6; - unsigned regPre :13; - unsigned regEQU :1; + 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)*/ + uint32_t clkdiv_pre: 13; /*it is pre-divider of spi_clk.*/ + uint32_t clk_equ_sysclk: 1; /*1: spi_clk is eqaul to system 0: spi_clk is divided from system clock.*/ }; } spiClk_t; -#define ClkRegToFreq(reg) (CPU_CLK_FREQ / (((reg)->regPre + 1) * ((reg)->regN + 1))) +#define ClkRegToFreq(reg) (apb_freq / (((reg)->clkdiv_pre + 1) * ((reg)->clkcnt_n + 1))) uint32_t spiClockDivToFrequency(uint32_t clockDiv) { + uint32_t apb_freq = getApbFrequency(); spiClk_t reg = { clockDiv }; return ClkRegToFreq(®); } uint32_t spiFrequencyToClockDiv(uint32_t freq) { + uint32_t apb_freq = getApbFrequency(); - if(freq >= CPU_CLK_FREQ) { + if(freq >= apb_freq) { return SPI_CLK_EQU_SYSCLK; } const spiClk_t minFreqReg = { 0x7FFFF000 }; uint32_t minFreq = ClkRegToFreq((spiClk_t*) &minFreqReg); if(freq < minFreq) { - return minFreqReg.regValue; + return minFreqReg.value; } uint8_t calN = 1; @@ -1048,18 +1055,18 @@ uint32_t spiFrequencyToClockDiv(uint32_t freq) int32_t calPre; int8_t calPreVari = -2; - reg.regN = calN; + reg.clkcnt_n = calN; while(calPreVari++ <= 1) { - calPre = (((CPU_CLK_FREQ / (reg.regN + 1)) / freq) - 1) + calPreVari; + calPre = (((apb_freq / (reg.clkcnt_n + 1)) / freq) - 1) + calPreVari; if(calPre > 0x1FFF) { - reg.regPre = 0x1FFF; + reg.clkdiv_pre = 0x1FFF; } else if(calPre <= 0) { - reg.regPre = 0; + reg.clkdiv_pre = 0; } else { - reg.regPre = calPre; + reg.clkdiv_pre = calPre; } - reg.regL = ((reg.regN + 1) / 2); + reg.clkcnt_l = ((reg.clkcnt_n + 1) / 2); calFreq = ClkRegToFreq(®); if(calFreq == (int32_t) freq) { memcpy(&bestReg, ®, sizeof(bestReg)); @@ -1076,6 +1083,6 @@ uint32_t spiFrequencyToClockDiv(uint32_t freq) } calN++; } - return bestReg.regValue; + return bestReg.value; } diff --git a/cores/esp32/esp32-hal-spi.h b/cores/esp32/esp32-hal-spi.h index 78ef10fa3dd..1317f38b239 100644 --- a/cores/esp32/esp32-hal-spi.h +++ b/cores/esp32/esp32-hal-spi.h @@ -96,7 +96,7 @@ void spiSetClockDiv(spi_t * spi, uint32_t clockDiv); void spiSetDataMode(spi_t * spi, uint8_t dataMode); void spiSetBitOrder(spi_t * spi, uint8_t bitOrder); -void spiWrite(spi_t * spi, uint32_t *data, uint8_t len); +void spiWrite(spi_t * spi, const uint32_t *data, uint8_t len); void spiWriteByte(spi_t * spi, uint8_t data); void spiWriteWord(spi_t * spi, uint16_t data); void spiWriteLong(spi_t * spi, uint32_t data); @@ -105,7 +105,7 @@ void spiTransfer(spi_t * spi, uint32_t *out, uint8_t len); uint8_t spiTransferByte(spi_t * spi, uint8_t data); uint16_t spiTransferWord(spi_t * spi, uint16_t data); uint32_t spiTransferLong(spi_t * spi, uint32_t data); -void spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t size); +void spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, uint32_t size); void spiTransferBits(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits); /* @@ -115,11 +115,11 @@ void spiTransaction(spi_t * spi, uint32_t clockDiv, uint8_t dataMode, uint8_t bi void spiSimpleTransaction(spi_t * spi); void spiEndTransaction(spi_t * spi); -void spiWriteNL(spi_t * spi, const void * data, uint32_t len); +void spiWriteNL(spi_t * spi, const void * data_in, uint32_t len); void spiWriteByteNL(spi_t * spi, uint8_t data); void spiWriteShortNL(spi_t * spi, uint16_t data); void spiWriteLongNL(spi_t * spi, uint32_t data); -void spiWritePixelsNL(spi_t * spi, const void * data, uint32_t len); +void spiWritePixelsNL(spi_t * spi, const void * data_in, uint32_t len); #define spiTransferNL(spi, data, len) spiTransferBytesNL(spi, data, data, len) uint8_t spiTransferByteNL(spi_t * spi, uint8_t data); diff --git a/cores/esp32/esp32-hal-time.c b/cores/esp32/esp32-hal-time.c index 176ac65cc2f..5647f1f50dc 100644 --- a/cores/esp32/esp32-hal-time.c +++ b/cores/esp32/esp32-hal-time.c @@ -13,13 +13,14 @@ // limitations under the License. #include "esp32-hal.h" -#include "apps/sntp/sntp.h" +#include "lwip/apps/sntp.h" +#include "tcpip_adapter.h" static void setTimeZone(long offset, int daylight) { - char cst[16] = {0}; - char cdt[16] = "DST"; - char tz[32] = {0}; + char cst[17] = {0}; + char cdt[17] = "DST"; + char tz[33] = {0}; if(offset % 3600){ sprintf(cst, "UTC%ld:%02u:%02u", offset / 3600, abs((offset % 3600) / 60), abs(offset % 60)); @@ -45,6 +46,7 @@ static void setTimeZone(long offset, int daylight) * */ void configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1, const char* server2, const char* server3) { + tcpip_adapter_init(); // Should not hurt anything if already inited if(sntp_enabled()){ sntp_stop(); } @@ -62,6 +64,7 @@ void configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1, * */ void configTzTime(const char* tz, const char* server1, const char* server2, const char* server3) { + tcpip_adapter_init(); // Should not hurt anything if already inited if(sntp_enabled()){ sntp_stop(); } @@ -76,23 +79,15 @@ void configTzTime(const char* tz, const char* server1, const char* server2, cons bool getLocalTime(struct tm * info, uint32_t ms) { - uint32_t count = ms / 10; + uint32_t start = millis(); time_t now; - - time(&now); - localtime_r(&now, info); - - if(info->tm_year > (2016 - 1900)){ - return true; - } - - while(count--) { - delay(10); + while((millis()-start) <= ms) { time(&now); localtime_r(&now, info); if(info->tm_year > (2016 - 1900)){ return true; } + delay(10); } return false; } diff --git a/cores/esp32/esp32-hal-timer.c b/cores/esp32/esp32-hal-timer.c index 17743a4f6d8..ed804d4e348 100644 --- a/cores/esp32/esp32-hal-timer.c +++ b/cores/esp32/esp32-hal-timer.c @@ -84,7 +84,7 @@ void IRAM_ATTR __timerISR(void * arg){ i = 4; //call callbacks while(i--){ - if(__timerInterruptHandlers[i] && status & (1 << i)){ + if(__timerInterruptHandlers[i] && (status & (1 << i))){ __timerInterruptHandlers[i](); } } @@ -165,6 +165,7 @@ void timerStop(hw_timer_t *timer){ void timerRestart(hw_timer_t *timer){ timer->dev->config.enable = 0; + timer->dev->reload = 1; timer->dev->config.enable = 1; } @@ -184,6 +185,18 @@ bool timerAlarmEnabled(hw_timer_t *timer){ return timer->dev->config.alarm_en; } +static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb){ + hw_timer_t * timer = (hw_timer_t *)arg; + if(ev_type == APB_BEFORE_CHANGE){ + timer->dev->config.enable = 0; + } else { + old_apb /= 1000000; + new_apb /= 1000000; + timer->dev->config.divider = (new_apb * timer->dev->config.divider) / old_apb; + timer->dev->config.enable = 1; + } +} + hw_timer_t * timerBegin(uint8_t num, uint16_t divider, bool countUp){ if(num > 3){ return NULL; @@ -205,12 +218,14 @@ hw_timer_t * timerBegin(uint8_t num, uint16_t divider, bool countUp){ timerAttachInterrupt(timer, NULL, false); timerWrite(timer, 0); timer->dev->config.enable = 1; + addApbChangeCallback(timer, _on_apb_change); return timer; } void timerEnd(hw_timer_t *timer){ timer->dev->config.enable = 0; timerAttachInterrupt(timer, NULL, false); + removeApbChangeCallback(timer, _on_apb_change); } void timerAttachInterrupt(hw_timer_t *timer, void (*fn)(void), bool edge){ @@ -271,23 +286,23 @@ void timerDetachInterrupt(hw_timer_t *timer){ uint64_t timerReadMicros(hw_timer_t *timer){ uint64_t timer_val = timerRead(timer); uint16_t div = timerGetDivider(timer); - return timer_val * div / 80; + return timer_val * div / (getApbFrequency() / 1000000); } double timerReadSeconds(hw_timer_t *timer){ uint64_t timer_val = timerRead(timer); uint16_t div = timerGetDivider(timer); - return (double)timer_val * div / 80000000; + return (double)timer_val * div / getApbFrequency(); } uint64_t timerAlarmReadMicros(hw_timer_t *timer){ uint64_t timer_val = timerAlarmRead(timer); uint16_t div = timerGetDivider(timer); - return timer_val * div / 80; + return timer_val * div / (getApbFrequency() / 1000000); } double timerAlarmReadSeconds(hw_timer_t *timer){ uint64_t timer_val = timerAlarmRead(timer); uint16_t div = timerGetDivider(timer); - return (double)timer_val * div / 80000000; + return (double)timer_val * div / getApbFrequency(); } diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c index bcf9d045093..8bb4b185566 100644 --- a/cores/esp32/esp32-hal-uart.c +++ b/cores/esp32/esp32-hal-uart.c @@ -27,6 +27,7 @@ #include "soc/io_mux_reg.h" #include "soc/gpio_sig_map.h" #include "soc/dport_reg.h" +#include "soc/rtc.h" #include "esp_intr_alloc.h" #define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:( (u==2)?DR_REG_UART2_BASE:0))) @@ -66,6 +67,8 @@ static uart_t _uart_bus_array[3] = { }; #endif +static void uart_on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb); + static void IRAM_ATTR _uart_isr(void *arg) { uint8_t i, c; @@ -80,7 +83,7 @@ static void IRAM_ATTR _uart_isr(void *arg) uart->dev->int_clr.rxfifo_full = 1; uart->dev->int_clr.frm_err = 1; uart->dev->int_clr.rxfifo_tout = 1; - while(uart->dev->status.rxfifo_cnt) { + while(uart->dev->status.rxfifo_cnt || (uart->dev->mem_rx_status.wr_addr != uart->dev->mem_rx_status.rd_addr)) { c = uart->dev->fifo.rw_byte; if(uart->queue != NULL && !xQueueIsQueueFullFromISR(uart->queue)) { xQueueSendFromISR(uart->queue, &c, &xHigherPriorityTaskWoken); @@ -215,6 +218,7 @@ uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rx uartAttachTx(uart, txPin, inverted); } + addApbChangeCallback(uart, uart_on_apb_change); return uart; } @@ -223,11 +227,10 @@ void uartEnd(uart_t* uart) if(uart == NULL) { return; } + removeApbChangeCallback(uart, uart_on_apb_change); UART_MUTEX_LOCK(); if(uart->queue != NULL) { - uint8_t c; - while(xQueueReceive(uart->queue, &c, 0)); vQueueDelete(uart->queue); uart->queue = NULL; } @@ -240,6 +243,24 @@ void uartEnd(uart_t* uart) uartDetachTx(uart); } +size_t uartResizeRxBuffer(uart_t * uart, size_t new_size) { + if(uart == NULL) { + return 0; + } + + UART_MUTEX_LOCK(); + if(uart->queue != NULL) { + vQueueDelete(uart->queue); + uart->queue = xQueueCreate(new_size, sizeof(uint8_t)); + if(uart->queue == NULL) { + return NULL; + } + } + UART_MUTEX_UNLOCK(); + + return new_size; +} + uint32_t uartAvailable(uart_t* uart) { if(uart == NULL || uart->queue == NULL) { @@ -298,28 +319,39 @@ void uartWriteBuf(uart_t* uart, const uint8_t * data, size_t len) } UART_MUTEX_LOCK(); while(len) { - while(len && uart->dev->status.txfifo_cnt < 0x7F) { - uart->dev->fifo.rw_byte = *data++; - len--; - } + while(uart->dev->status.txfifo_cnt == 0x7F); + uart->dev->fifo.rw_byte = *data++; + len--; } UART_MUTEX_UNLOCK(); } void uartFlush(uart_t* uart) +{ + uartFlushTxOnly(uart,false); +} + +void uartFlushTxOnly(uart_t* uart, bool txOnly) { if(uart == NULL) { return; } UART_MUTEX_LOCK(); - while(uart->dev->status.txfifo_cnt); - - uart->dev->conf0.txfifo_rst = 1; - uart->dev->conf0.txfifo_rst = 0; + while(uart->dev->status.txfifo_cnt || uart->dev->status.st_utx_out); + + if( !txOnly ){ + //Due to hardware issue, we can not use fifo_rst to reset uart fifo. + //See description about UART_TXFIFO_RST and UART_RXFIFO_RST in <> v2.6 or later. + + // we read the data out and make `fifo_len == 0 && rd_addr == wr_addr`. + while(uart->dev->status.rxfifo_cnt != 0 || (uart->dev->mem_rx_status.wr_addr != uart->dev->mem_rx_status.rd_addr)) { + READ_PERI_REG(UART_FIFO_REG(uart->num)); + } - uart->dev->conf0.rxfifo_rst = 1; - uart->dev->conf0.rxfifo_rst = 0; + xQueueReset(uart->queue); + } + UART_MUTEX_UNLOCK(); } @@ -329,19 +361,60 @@ void uartSetBaudRate(uart_t* uart, uint32_t baud_rate) return; } UART_MUTEX_LOCK(); - uint32_t clk_div = ((UART_CLK_FREQ<<4)/baud_rate); + 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_MUTEX_UNLOCK(); } +static void uart_on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb) +{ + uart_t* uart = (uart_t*)arg; + if(ev_type == APB_BEFORE_CHANGE){ + UART_MUTEX_LOCK(); + //disabple interrupt + uart->dev->int_ena.val = 0; + uart->dev->int_clr.val = 0xffffffff; + // read RX fifo + uint8_t c; + BaseType_t xHigherPriorityTaskWoken; + while(uart->dev->status.rxfifo_cnt != 0 || (uart->dev->mem_rx_status.wr_addr != uart->dev->mem_rx_status.rd_addr)) { + c = uart->dev->fifo.rw_byte; + if(uart->queue != NULL && !xQueueIsQueueFullFromISR(uart->queue)) { + xQueueSendFromISR(uart->queue, &c, &xHigherPriorityTaskWoken); + } + } + // wait TX empty + while(uart->dev->status.txfifo_cnt || uart->dev->status.st_utx_out); + } else { + //todo: + // set baudrate + uint32_t clk_div = (uart->dev->clk_div.div_int << 4) | (uart->dev->clk_div.div_frag & 0x0F); + uint32_t baud_rate = ((old_apb<<4)/clk_div); + clk_div = ((new_apb<<4)/baud_rate); + uart->dev->clk_div.div_int = clk_div>>4 ; + uart->dev->clk_div.div_frag = clk_div & 0xf; + //enable interrupts + uart->dev->int_ena.rxfifo_full = 1; + uart->dev->int_ena.frm_err = 1; + uart->dev->int_ena.rxfifo_tout = 1; + uart->dev->int_clr.val = 0xffffffff; + UART_MUTEX_UNLOCK(); + } +} + uint32_t uartGetBaudRate(uart_t* uart) { if(uart == NULL) { return 0; } + uint32_t clk_div = (uart->dev->clk_div.div_int << 4) | (uart->dev->clk_div.div_frag & 0x0F); - return ((UART_CLK_FREQ<<4)/clk_div); + if(!clk_div) { + return 0; + } + + return ((getApbFrequency()<<4)/clk_div); } static void IRAM_ATTR uart0_write_char(char c) @@ -362,17 +435,8 @@ static void IRAM_ATTR uart2_write_char(char c) ESP_REG(DR_REG_UART2_BASE) = c; } -void uartSetDebug(uart_t* uart) +void uart_install_putc() { - if(uart == NULL || uart->num > 2) { - s_uart_debug_nr = -1; - ets_install_putc1(NULL); - return; - } - if(s_uart_debug_nr == uart->num) { - return; - } - s_uart_debug_nr = uart->num; switch(s_uart_debug_nr) { case 0: ets_install_putc1((void (*)(char)) &uart0_write_char); @@ -389,6 +453,20 @@ void uartSetDebug(uart_t* uart) } } +void uartSetDebug(uart_t* uart) +{ + if(uart == NULL || uart->num > 2) { + s_uart_debug_nr = -1; + //ets_install_putc1(NULL); + //return; + } else + if(s_uart_debug_nr == uart->num) { + return; + } else + s_uart_debug_nr = uart->num; + uart_install_putc(); +} + int uartGetDebug() { return s_uart_debug_nr; @@ -417,7 +495,7 @@ int log_printf(const char *format, ...) vsnprintf(temp, len+1, format, arg); #if !CONFIG_DISABLE_HAL_LOCKS if(_uart_bus_array[s_uart_debug_nr].lock){ - while (xSemaphoreTake(_uart_bus_array[s_uart_debug_nr].lock, portMAX_DELAY) != pdPASS); + xSemaphoreTake(_uart_bus_array[s_uart_debug_nr].lock, portMAX_DELAY); ets_printf("%s", temp); xSemaphoreGive(_uart_bus_array[s_uart_debug_nr].lock); } else { @@ -427,8 +505,85 @@ int log_printf(const char *format, ...) ets_printf("%s", temp); #endif va_end(arg); - if(len > 64){ + if(len >= sizeof(loc_buf)){ free(temp); } return len; } + +/* + * if enough pulses are detected return the minimum high pulse duration + minimum low pulse duration divided by two. + * This equals one bit period. If flag is true the function return inmediately, otherwise it waits for enough pulses. + */ +unsigned long uartBaudrateDetect(uart_t *uart, bool flg) +{ + while(uart->dev->rxd_cnt.edge_cnt < 30) { // UART_PULSE_NUM(uart_num) + if(flg) return 0; + ets_delay_us(1000); + } + + UART_MUTEX_LOCK(); + unsigned long ret = ((uart->dev->lowpulse.min_cnt + uart->dev->highpulse.min_cnt) >> 1) + 12; + UART_MUTEX_UNLOCK(); + + return ret; +} + +/* + * To start detection of baud rate with the uart the auto_baud.en bit needs to be cleared and set. The bit period is + * detected calling uartBadrateDetect(). The raw baudrate is computed using the UART_CLK_FREQ. The raw baudrate is + * rounded to the closed real baudrate. +*/ +void uartStartDetectBaudrate(uart_t *uart) { + if(!uart) return; + + uart->dev->auto_baud.glitch_filt = 0x08; + uart->dev->auto_baud.en = 0; + uart->dev->auto_baud.en = 1; +} + +unsigned long +uartDetectBaudrate(uart_t *uart) +{ + static bool uartStateDetectingBaudrate = false; + + if(!uartStateDetectingBaudrate) { + uart->dev->auto_baud.glitch_filt = 0x08; + uart->dev->auto_baud.en = 0; + uart->dev->auto_baud.en = 1; + uartStateDetectingBaudrate = true; + } + + unsigned long divisor = uartBaudrateDetect(uart, true); + if (!divisor) { + return 0; + } + + uart->dev->auto_baud.en = 0; + uartStateDetectingBaudrate = false; // Initialize for the next round + + unsigned long baudrate = getApbFrequency() / divisor; + + static const unsigned long default_rates[] = {300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 74880, 115200, 230400, 256000, 460800, 921600, 1843200, 3686400}; + + size_t i; + for (i = 1; i < sizeof(default_rates) / sizeof(default_rates[0]) - 1; i++) // find the nearest real baudrate + { + if (baudrate <= default_rates[i]) + { + if (baudrate - default_rates[i - 1] < default_rates[i] - baudrate) { + i--; + } + break; + } + } + + return default_rates[i]; +} + +/* + * Returns the status of the RX state machine, if the value is non-zero the state machine is active. + */ +bool uartRxActive(uart_t* uart) { + return uart->dev->status.st_urx_out != 0; +} diff --git a/cores/esp32/esp32-hal-uart.h b/cores/esp32/esp32-hal-uart.h index 5cd6e965099..e44d25bbc5e 100644 --- a/cores/esp32/esp32-hal-uart.h +++ b/cores/esp32/esp32-hal-uart.h @@ -63,13 +63,21 @@ void uartWrite(uart_t* uart, uint8_t c); void uartWriteBuf(uart_t* uart, const uint8_t * data, size_t len); void uartFlush(uart_t* uart); +void uartFlushTxOnly(uart_t* uart, bool txOnly ); void uartSetBaudRate(uart_t* uart, uint32_t baud_rate); uint32_t uartGetBaudRate(uart_t* uart); +size_t uartResizeRxBuffer(uart_t* uart, size_t new_size); + void uartSetDebug(uart_t* uart); int uartGetDebug(); +void uartStartDetectBaudrate(uart_t *uart); +unsigned long uartDetectBaudrate(uart_t *uart); + +bool uartRxActive(uart_t* uart); + #ifdef __cplusplus } #endif diff --git a/cores/esp32/esp32-hal.h b/cores/esp32/esp32-hal.h index d6e5ca8ca65..4b5fb2c2ebb 100644 --- a/cores/esp32/esp32-hal.h +++ b/cores/esp32/esp32-hal.h @@ -33,6 +33,7 @@ extern "C" { #include #include #include "sdkconfig.h" +#include "esp_system.h" #ifndef F_CPU #define F_CPU (CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ * 1000000U) @@ -56,14 +57,49 @@ void yield(void); #include "esp32-hal-spi.h" #include "esp32-hal-i2c.h" #include "esp32-hal-ledc.h" +#include "esp32-hal-rmt.h" #include "esp32-hal-sigmadelta.h" #include "esp32-hal-timer.h" #include "esp32-hal-bt.h" -#include "esp_system.h" +#include "esp32-hal-psram.h" +#include "esp32-hal-cpu.h" + +#ifndef BOARD_HAS_PSRAM +#ifdef CONFIG_SPIRAM_SUPPORT +#undef CONFIG_SPIRAM_SUPPORT +#endif +#endif //returns chip temperature in Celsius float temperatureRead(); +#if CONFIG_AUTOSTART_ARDUINO +//enable/disable WDT for Arduino's setup and loop functions +void enableLoopWDT(); +void disableLoopWDT(); +//feed WDT for the loop task +void feedLoopWDT(); +#endif + +//enable/disable WDT for the IDLE task on Core 0 (SYSTEM) +void enableCore0WDT(); +void disableCore0WDT(); +#ifndef CONFIG_FREERTOS_UNICORE +//enable/disable WDT for the IDLE task on Core 1 (Arduino) +void enableCore1WDT(); +void disableCore1WDT(); +#endif + +//if xCoreID < 0 or CPU is unicore, it will use xTaskCreate, else xTaskCreatePinnedToCore +//allows to easily handle all possible situations without repetitive code +BaseType_t xTaskCreateUniversal( TaskFunction_t pxTaskCode, + const char * const pcName, + const uint32_t usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + const BaseType_t xCoreID ); + unsigned long micros(); unsigned long millis(); void delay(uint32_t); diff --git a/cores/esp32/esp8266-compat.h b/cores/esp32/esp8266-compat.h index 7a8df1da1a8..078fdb72f09 100644 --- a/cores/esp32/esp8266-compat.h +++ b/cores/esp32/esp8266-compat.h @@ -1,24 +1,24 @@ -// esp8266-compat.h - Compatibility functions to help ESP8266 libraries and user code run on ESP32 - -// Copyright (c) 2017 Evandro Luis Copercini. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 _ESP8266_COMPAT_H_ -#define _ESP8266_COMPAT_H_ - -#define ICACHE_FLASH_ATTR -#define ICACHE_RAM_ATTR IRAM_ATTR - - +// esp8266-compat.h - Compatibility functions to help ESP8266 libraries and user code run on ESP32 + +// Copyright (c) 2017 Evandro Luis Copercini. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ESP8266_COMPAT_H_ +#define _ESP8266_COMPAT_H_ + +#define ICACHE_FLASH_ATTR +#define ICACHE_RAM_ATTR IRAM_ATTR + + #endif /* _ESP8266_COMPAT_H_ */ \ No newline at end of file diff --git a/cores/esp32/libb64/cencode.c b/cores/esp32/libb64/cencode.c index ee9a18f0557..48a0d30b7e9 100755 --- a/cores/esp32/libb64/cencode.c +++ b/cores/esp32/libb64/cencode.c @@ -7,13 +7,10 @@ For details, see http://sourceforge.net/projects/libb64 #include "cencode.h" -const int CHARS_PER_LINE = 72; - void base64_init_encodestate(base64_encodestate* state_in) { state_in->step = step_A; state_in->result = 0; - state_in->stepcount = 0; } char base64_encode_value(char value_in) @@ -68,12 +65,6 @@ int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, *codechar++ = base64_encode_value(result); result = (fragment & 0x03f) >> 0; *codechar++ = base64_encode_value(result); - - ++(state_in->stepcount); - if (state_in->stepcount == CHARS_PER_LINE/4) { - *codechar++ = '\n'; - state_in->stepcount = 0; - } } } /* control should not reach here */ diff --git a/cores/esp32/main.cpp b/cores/esp32/main.cpp index 0cba93ee0ec..41f1985b94c 100644 --- a/cores/esp32/main.cpp +++ b/cores/esp32/main.cpp @@ -1,28 +1,31 @@ #include "freertos/FreeRTOS.h" #include "freertos/task.h" +#include "esp_task_wdt.h" #include "Arduino.h" +TaskHandle_t loopTaskHandle = NULL; + #if CONFIG_AUTOSTART_ARDUINO -#if CONFIG_FREERTOS_UNICORE -#define ARDUINO_RUNNING_CORE 0 -#else -#define ARDUINO_RUNNING_CORE 1 -#endif +bool loopTaskWDTEnabled; void loopTask(void *pvParameters) { setup(); for(;;) { - micros(); //update overflow + if(loopTaskWDTEnabled){ + esp_task_wdt_reset(); + } loop(); + if (serialEventRun) serialEventRun(); } } extern "C" void app_main() { + loopTaskWDTEnabled = false; initArduino(); - xTaskCreatePinnedToCore(loopTask, "loopTask", 8192, NULL, 1, NULL, ARDUINO_RUNNING_CORE); + xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE); } #endif diff --git a/cores/esp32/pgmspace.h b/cores/esp32/pgmspace.h index d1e81ffc5d7..aa58775ff57 100644 --- a/cores/esp32/pgmspace.h +++ b/cores/esp32/pgmspace.h @@ -32,7 +32,6 @@ typedef unsigned long prog_uint32_t; #define PROGMEM #define PGM_P const char * #define PGM_VOID_P const void * -#define FPSTR(p) ((const char *)(p)) #define PSTR(s) (s) #define _SFR_BYTE(n) (n) @@ -71,7 +70,7 @@ typedef unsigned long prog_uint32_t; #define memcpy_P memcpy #define strcpy_P strcpy #define strncpy_P strncpy -#define strcat_p strcat +#define strcat_P strcat #define strncat_P strncat #define strcmp_P strcmp #define strncmp_P strncmp diff --git a/cores/esp32/wiring_shift.c b/cores/esp32/wiring_shift.c index 44c13700d1e..c6c279aa8a3 100644 --- a/cores/esp32/wiring_shift.c +++ b/cores/esp32/wiring_shift.c @@ -25,11 +25,12 @@ uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) { uint8_t i; for(i = 0; i < 8; ++i) { - digitalWrite(clockPin, HIGH); + //digitalWrite(clockPin, HIGH); if(bitOrder == LSBFIRST) value |= digitalRead(dataPin) << i; else value |= digitalRead(dataPin) << (7 - i); + digitalWrite(clockPin, HIGH); digitalWrite(clockPin, LOW); } return value; diff --git a/docs/ISSUE_TEMPLATE.md b/docs/ISSUE_TEMPLATE.md index aa43350cb17..55f00770c68 100644 --- a/docs/ISSUE_TEMPLATE.md +++ b/docs/ISSUE_TEMPLATE.md @@ -1,24 +1,32 @@ -Please fill the info fields, it helps to get you faster support ;) +Make your question, not a Statement, inclusive. Include all pertinent information: -If you have a Guru Meditation Error, please decode it: +What you are trying to do. +Describe your system( Hardware, computer, O/S, core version, environment) +Describe what is failing +Show the shortest possible code that will duplicate the error +Show the EXACT error message(it doesn't work is not enough) +Then if someone is interested and knowledgeable you might get a answer. All of this work on your part shows us that you have worked to solve YOUR problem. The more complete your issue posting is, the more likely someone will volunteer their time to help you. + +If you have a Guru Meditation Error or Backtrace, ***please decode it***: https://github.com/me-no-dev/EspExceptionDecoder ----------------------------- Remove above ----------------------------- ### Hardware: -Board: ?ESP32 Dev Module? +Board: ?ESP32 Dev Module? ?node32? ?ttgo_lora? Core Installation/update date: ?11/jul/2017? IDE name: ?Arduino IDE? ?Platform.io? ?IDF component? Flash Frequency: ?40Mhz? +PSRAM enabled: ?no? Upload Speed: ?115200? - +Computer OS: ?Windows 10? ?Mac OSX? ?Ubuntu? ### Description: Describe your problem here -### Sketch: +### Sketch: (leave the backquotes for [code formatting](https://help.github.com/articles/creating-and-highlighting-code-blocks/)) ```cpp //Change the code below by your sketch diff --git a/docs/OTAWebUpdate/OTAWebUpdate.md b/docs/OTAWebUpdate/OTAWebUpdate.md new file mode 100644 index 00000000000..383f6214433 --- /dev/null +++ b/docs/OTAWebUpdate/OTAWebUpdate.md @@ -0,0 +1,59 @@ +# Over the Air through Web browser +OTAWebUpdate is done with a web browser that can be useful in the following typical scenarios: +- Once the application developed and loading directly from Arduino IDE is inconvenient or not possible +- after deployment if user is unable to expose Firmware for OTA from external update server +- provide updates after deployment to small quantity of modules when setting an update server is not practicable + +## Requirements +- The ESP and the computer must be connected to the same network + +## Implementation +The sample implementation has been done using: +- example sketch OTAWebUpdater.ino +- ESP32 (Dev Module) + +You can use another module also if it meets Flash chip size of the sketch + +1-Before you begin, please make sure that you have the following software installed: + - Arduino IDE + - Host software depending on O/S you use: + - Avahi http://avahi.org/ for Linux + - Bonjour http://www.apple.com/support/bonjour/ for Windows + - Mac OSX and iOS - support is already built in / no any extra s/w is required + +Prepare the sketch and configuration for initial upload with a serial port +- Start Arduino IDE and load sketch OTAWebUpdater.ino available under File > Examples > OTAWebUpdater.ino +- Update ssid and pass in the sketch so the module can join your Wi-Fi network +- Open File > Preferences, look for “Show verbose output during:” and check out “compilation” option + +![verbrose](esp32verbose.PNG) + +- Upload sketch (Ctrl+U) +- Now open web browser and enter the url, i.e. http://esp32.local. Once entered, browser should display a form + +![login](esp32login.PNG) + +> username= admin + +> password= admin + +**Note**-*If entering “http://ESP32.local” does not work, try replacing “ESP32” with module’s IP address.This workaround is useful in case the host software installed does not work*. + +Now click on Login button and browser will display a upload form + +![upload](esp32upload.PNG) + +For Uploading the New Firmware you need to provide the Binary File of your Code. + +Exporting Binary file of the Firmware (Code) +- Open up the Arduino IDE +- Open up the Code, for Exporting up Binary file +- Now go to Sketch > export compiled Binary +![export](exportTobinary.PNG) + +- Binary file is exported to the same Directory where your code is present + +Once you are comfortable with this procedure go ahead and modify OTAWebUpdater.ino sketch to print some additional messages, compile it, Export new binary file and upload it using web browser to see entered changes on a Serial Monitor + + + diff --git a/docs/OTAWebUpdate/esp32login.PNG b/docs/OTAWebUpdate/esp32login.PNG new file mode 100644 index 00000000000..48c90c7f452 Binary files /dev/null and b/docs/OTAWebUpdate/esp32login.PNG differ diff --git a/docs/OTAWebUpdate/esp32upload.PNG b/docs/OTAWebUpdate/esp32upload.PNG new file mode 100644 index 00000000000..81f2eaba79d Binary files /dev/null and b/docs/OTAWebUpdate/esp32upload.PNG differ diff --git a/docs/OTAWebUpdate/esp32verbose.PNG b/docs/OTAWebUpdate/esp32verbose.PNG new file mode 100644 index 00000000000..bd9c3fc41fe Binary files /dev/null and b/docs/OTAWebUpdate/esp32verbose.PNG differ diff --git a/docs/OTAWebUpdate/exportTobinary.PNG b/docs/OTAWebUpdate/exportTobinary.PNG new file mode 100644 index 00000000000..62d85831724 Binary files /dev/null and b/docs/OTAWebUpdate/exportTobinary.PNG differ diff --git a/docs/arduino-ide/boards_manager.md b/docs/arduino-ide/boards_manager.md new file mode 100644 index 00000000000..59428b9c3eb --- /dev/null +++ b/docs/arduino-ide/boards_manager.md @@ -0,0 +1,12 @@ +## Installation instructions using Arduino IDE Boards Manager +### ========================================================== + +- Stable release link: `https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json` +- Development release link: `https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json` + +Starting with 1.6.4, Arduino allows installation of third-party platform packages using Boards Manager. We have packages available for Windows, Mac OS, and Linux (32, 64 bit and ARM). + +- Install the current upstream Arduino IDE at the 1.8 level or later. The current version is at the [Arduino website](http://www.arduino.cc/en/main/software). +- Start Arduino and open Preferences window. +- Enter one of the release links above into *Additional Board Manager URLs* field. You can add multiple URLs, separating them with commas. +- Open Boards Manager from Tools > Board menu and install *esp32* platform (and don't forget to select your ESP32 board from Tools > Board menu after installation). diff --git a/docs/arduino-ide/debian_ubuntu.md b/docs/arduino-ide/debian_ubuntu.md index 78f144edd2f..79149673677 100644 --- a/docs/arduino-ide/debian_ubuntu.md +++ b/docs/arduino-ide/debian_ubuntu.md @@ -16,20 +16,21 @@ Installation instructions for Debian / Ubuntu OS cd esp32 && \ git submodule update --init --recursive && \ cd tools && \ - python2 get.py + python3 get.py ``` - Restart Arduino IDE -- If you have Arduino.app installed to /Applications/, modify the installation as follows, beginning at `mkdir -p ~/Arduino...`: +- If you have Arduino installed to ~/, modify the installation as follows, beginning at `mkdir -p ~/Arduino/hardware`: -```bash - cd /Applications/Arduino_*/Contents/java/hardware/ + ```bash + cd ~/Arduino/hardware mkdir -p espressif && \ cd espressif && \ git clone https://github.com/espressif/arduino-esp32.git esp32 && \ cd esp32 && \ git submodule update --init --recursive && \ cd tools && \ - python2 get.py``` + python3 get.py + ``` diff --git a/docs/arduino-ide/mac.md b/docs/arduino-ide/mac.md index d3d022bdec4..9807cc7df2d 100644 --- a/docs/arduino-ide/mac.md +++ b/docs/arduino-ide/mac.md @@ -11,13 +11,19 @@ Installation instructions for Mac OS cd esp32 && \ git submodule update --init --recursive && \ cd tools && \ - python get.py + python get.py ``` + Where `~/Documents/Arduino` represents your sketch book location as per "Arduino" > "Preferences" > "Sketchbook location" (in the IDE once started). Adjust the command above accordingly if necessary! +   - If you get the error below. Install the command line dev tools with xcode-select --install and try the command above again: -```xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun``` + ```xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun``` + + ```xcode-select --install``` + +- Try `python3` instead of `python` if you get the error: `IOError: [Errno socket error] [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590)` when running `python get.py` -```xcode-select --install``` +- If you get the following error when running `python get.py` urllib.error.URLError: Applications > Python3.6 folder (or any other python version), and run the following scripts: Install Certificates.command and Update Shell Profile.command - Restart Arduino IDE diff --git a/docs/esp-idf_component.md b/docs/esp-idf_component.md index be685125707..4e29b1acb2a 100644 --- a/docs/esp-idf_component.md +++ b/docs/esp-idf_component.md @@ -1,6 +1,10 @@ To use as a component of ESP-IDF ================================================= +## esp32-arduino-lib-builder + +For a simplified method, see [lib-builder](lib_builder.md) + ## Installation - Download and install [esp-idf](https://github.com/espressif/esp-idf) @@ -68,3 +72,6 @@ If you are writing code that does not require Arduino to compile and you want yo #endif ``` +## Compilation Errors + +As commits are made to esp-idf and submodules, the codebases can develop incompatibilities which cause compilation errors. If you have problems compiling, follow the instructions in [Issue #1142](https://github.com/espressif/arduino-esp32/issues/1142) to roll esp-idf back to a known good version. diff --git a/docs/esp32_pinmap.png b/docs/esp32_pinmap.png index d8f96efff5b..2c46148f330 100644 Binary files a/docs/esp32_pinmap.png and b/docs/esp32_pinmap.png differ diff --git a/docs/lib_builder.md b/docs/lib_builder.md new file mode 100644 index 00000000000..66cca92206a --- /dev/null +++ b/docs/lib_builder.md @@ -0,0 +1,14 @@ +## Using esp32-arduino-lib-builder to compile custom libraries + +Espressif has provided a [tool](https://github.com/espressif/esp32-arduino-lib-builder) to simplify building your own compiled libraries for use in Arduino IDE (or your favorite IDE). +To use it to generate custom libraries, follow these steps: +1. `git clone https://github.com/espressif/esp32-arduino-lib-builder` +2. `cd esp32-arduino-lib-builder` +3. `./tools/update-components.sh` +4. `./tools/install-esp-idf.sh` (if you already have an $IDF_PATH defined, it will use your local copy of the repository) +5. `make menuconfig` or directly edit sdkconfig. +6. `./build.sh` + +The script automates the process of building [arduino as an ESP-IDF component](https://github.com/espressif/arduino-esp32/blob/master/docs/esp-idf_component.md). +Once it is complete, you can cherry pick the needed libraries from `out/tools/sdk/lib`, or run `tools/copy-to-arduino.sh` to copy the entire built system. +`tools/config.sh` contains a number of variables that control the process, particularly the $IDF_BRANCH variable. You can adjust this to try building against newer versions, but there are absolutely no guarantees that any components will work or even successfully compile against a newer IDF. diff --git a/docs/platformio.md b/docs/platformio.md index fac446539e5..33f4b22cba3 100644 --- a/docs/platformio.md +++ b/docs/platformio.md @@ -1,11 +1,11 @@ Installation instructions for using PlatformIO ================================================= -- [What is PlatformIO?](http://docs.platformio.org/en/latest/what-is-platformio.html?utm_source=github&utm_medium=arduino-esp32) -- [PlatformIO IDE](http://platformio.org/platformio-ide?utm_source=github&utm_medium=arduino-esp32) -- [PlatformIO Core](http://docs.platformio.org/en/latest/core.html?utm_source=github&utm_medium=arduino-esp32) (command line tool) -- [Advanced usage](http://docs.platformio.org/en/latest/platforms/espressif32.html?utm_source=github&utm_medium=arduino-esp32) - +- [What is PlatformIO?](https://docs.platformio.org/en/latest/what-is-platformio.html?utm_source=github&utm_medium=arduino-esp32) +- [PlatformIO IDE](https://platformio.org/platformio-ide?utm_source=github&utm_medium=arduino-esp32) +- [PlatformIO Core](https://docs.platformio.org/en/latest/core.html?utm_source=github&utm_medium=arduino-esp32) (command line tool) +- [Advanced usage](https://docs.platformio.org/en/latest/platforms/espressif32.html?utm_source=github&utm_medium=arduino-esp32) - custom settings, uploading to SPIFFS, Over-the-Air (OTA), staging version -- [Integration with Cloud and Standalone IDEs](http://docs.platformio.org/en/latest/ide.html?utm_source=github&utm_medium=arduino-esp32) - +- [Integration with Cloud and Standalone IDEs](https://docs.platformio.org/en/latest/ide.html?utm_source=github&utm_medium=arduino-esp32) - Cloud9, Codeanywhere, Eclipse Che (Codenvy), Atom, CLion, Eclipse, Emacs, NetBeans, Qt Creator, Sublime Text, VIM, Visual Studio, and VSCode -- [Project Examples](http://docs.platformio.org/en/latest/platforms/espressif32.html?utm_source=github&utm_medium=arduino-esp32#examples) +- [Project Examples](https://docs.platformio.org/en/latest/platforms/espressif32.html?utm_source=github&utm_medium=arduino-esp32#examples) diff --git a/libraries/ArduinoOTA/examples/OTAWebUpdater/OTAWebUpdater.ino b/libraries/ArduinoOTA/examples/OTAWebUpdater/OTAWebUpdater.ino new file mode 100644 index 00000000000..ed93c59f975 --- /dev/null +++ b/libraries/ArduinoOTA/examples/OTAWebUpdater/OTAWebUpdater.ino @@ -0,0 +1,168 @@ +#include +#include +#include +#include +#include + +const char* host = "esp32"; +const char* ssid = "xxx"; +const char* password = "xxxx"; + +WebServer server(80); + +/* + * Login page + */ + +const char* loginIndex = + "
" + "" + "" + "" + "
" + "
" + "" + "" + "" + "" + "
" + "
" + "" + "" + "" + "
" + "
" + "" + "" + "" + "" + "
" + "
ESP32 Login Page
" + "
" + "
Username:
Password:
" +"
" +""; + +/* + * Server Index Page + */ + +const char* serverIndex = +"" +"
" + "" + "" + "
" + "
progress: 0%
" + ""; + +/* + * setup function + */ +void setup(void) { + Serial.begin(115200); + + // Connect to WiFi network + WiFi.begin(ssid, password); + Serial.println(""); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.print("Connected to "); + Serial.println(ssid); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + /*use mdns for host name resolution*/ + if (!MDNS.begin(host)) { //http://esp32.local + Serial.println("Error setting up MDNS responder!"); + while (1) { + delay(1000); + } + } + Serial.println("mDNS responder started"); + /*return index page which is stored in serverIndex */ + server.on("/", HTTP_GET, []() { + server.sendHeader("Connection", "close"); + server.send(200, "text/html", loginIndex); + }); + server.on("/serverIndex", HTTP_GET, []() { + server.sendHeader("Connection", "close"); + server.send(200, "text/html", serverIndex); + }); + /*handling uploading firmware file */ + server.on("/update", HTTP_POST, []() { + server.sendHeader("Connection", "close"); + server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); + ESP.restart(); + }, []() { + HTTPUpload& upload = server.upload(); + if (upload.status == UPLOAD_FILE_START) { + Serial.printf("Update: %s\n", upload.filename.c_str()); + if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size + Update.printError(Serial); + } + } else if (upload.status == UPLOAD_FILE_WRITE) { + /* flashing firmware to ESP*/ + if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + Update.printError(Serial); + } + } else if (upload.status == UPLOAD_FILE_END) { + if (Update.end(true)) { //true to set the size to the current progress + Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); + } else { + Update.printError(Serial); + } + } + }); + server.begin(); +} + +void loop(void) { + server.handleClient(); + delay(1); +} diff --git a/libraries/ArduinoOTA/src/ArduinoOTA.cpp b/libraries/ArduinoOTA/src/ArduinoOTA.cpp index 251642031db..884c9d341c1 100644 --- a/libraries/ArduinoOTA/src/ArduinoOTA.cpp +++ b/libraries/ArduinoOTA/src/ArduinoOTA.cpp @@ -9,7 +9,7 @@ #include "Update.h" -//#define OTA_DEBUG Serial +// #define OTA_DEBUG Serial ArduinoOTAClass::ArduinoOTAClass() : _port(0) @@ -20,6 +20,7 @@ ArduinoOTAClass::ArduinoOTAClass() , _size(0) , _cmd(0) , _ota_port(0) +, _ota_timeout(1000) , _start_callback(NULL) , _end_callback(NULL) , _error_callback(NULL) @@ -126,9 +127,7 @@ void ArduinoOTAClass::begin() { } _initialized = true; _state = OTA_IDLE; -#ifdef OTA_DEBUG - OTA_DEBUG.printf("OTA server at: %s.local:%u\n", _hostname.c_str(), _port); -#endif + log_i("OTA server at: %s.local:%u", _hostname.c_str(), _port); } int ArduinoOTAClass::parseInt(){ @@ -149,13 +148,13 @@ int ArduinoOTAClass::parseInt(){ String ArduinoOTAClass::readStringUntil(char end){ String res = ""; - char value; + int value; while(true){ value = _udp_ota.read(); - if(value == '\0' || value == end){ + if(value <= 0 || value == end){ return res; } - res += value; + res += (char)value; } return res; } @@ -172,6 +171,7 @@ void ArduinoOTAClass::_onRx(){ _md5 = readStringUntil('\n'); _md5.trim(); if(_md5.length() != 32){ + log_e("bad md5 length"); return; } @@ -197,6 +197,7 @@ void ArduinoOTAClass::_onRx(){ } else if (_state == OTA_WAITAUTH) { int cmd = parseInt(); if (cmd != U_AUTH) { + log_e("%d was expected. got %d instead", U_AUTH, cmd); _state = OTA_IDLE; return; } @@ -204,6 +205,7 @@ void ArduinoOTAClass::_onRx(){ String cnonce = readStringUntil(' '); String response = readStringUntil('\n'); if (cnonce.length() != 32 || response.length() != 32) { + log_e("auth param fail"); _state = OTA_IDLE; return; } @@ -224,6 +226,7 @@ void ArduinoOTAClass::_onRx(){ } else { _udp_ota.beginPacket(_udp_ota.remoteIP(), _udp_ota.remotePort()); _udp_ota.print("Authentication Failed"); + log_w("Authentication Failed"); _udp_ota.endPacket(); if (_error_callback) _error_callback(OTA_AUTH_ERROR); _state = OTA_IDLE; @@ -233,9 +236,9 @@ void ArduinoOTAClass::_onRx(){ void ArduinoOTAClass::_runUpdate() { if (!Update.begin(_size, _cmd)) { -#ifdef OTA_DEBUG - Update.printError(OTA_DEBUG); -#endif + + log_e("Begin ERROR: %s", Update.errorString()); + if (_error_callback) { _error_callback(OTA_BEGIN_ERROR); } @@ -260,8 +263,9 @@ void ArduinoOTAClass::_runUpdate() { } uint32_t written = 0, total = 0, tried = 0; + while (!Update.isFinished() && client.connected()) { - size_t waited = 1000; + size_t waited = _ota_timeout; size_t available = client.available(); while (!available && waited){ delay(1); @@ -270,21 +274,15 @@ void ArduinoOTAClass::_runUpdate() { } if (!waited){ if(written && tried++ < 3){ -#ifdef OTA_DEBUG - OTA_DEBUG.printf("Try[%u]: %u\n", tried, written); -#endif + log_i("Try[%u]: %u", tried, written); if(!client.printf("%u", written)){ -#ifdef OTA_DEBUG - OTA_DEBUG.printf("failed to respond\n"); -#endif + log_e("failed to respond"); _state = OTA_IDLE; break; } continue; } -#ifdef OTA_DEBUG - OTA_DEBUG.printf("Receive Failed\n"); -#endif + log_e("Receive Failed"); if (_error_callback) { _error_callback(OTA_RECEIVE_ERROR); } @@ -293,9 +291,7 @@ void ArduinoOTAClass::_runUpdate() { return; } if(!available){ -#ifdef OTA_DEBUG - OTA_DEBUG.printf("No Data: %u\n", waited); -#endif + log_e("No Data: %u", waited); _state = OTA_IDLE; break; } @@ -315,18 +311,14 @@ void ArduinoOTAClass::_runUpdate() { log_w("didn't write enough! %u != %u", written, r); } if(!client.printf("%u", written)){ -#ifdef OTA_DEBUG - OTA_DEBUG.printf("failed to respond\n"); -#endif + log_w("failed to respond"); } total += written; if(_progress_callback) { _progress_callback(total, _size); } } else { -#ifdef OTA_DEBUG - Update.printError(OTA_DEBUG); -#endif + log_e("Write ERROR: %s", Update.errorString()); } } @@ -349,10 +341,7 @@ void ArduinoOTAClass::_runUpdate() { Update.printError(client); client.stop(); delay(10); -#ifdef OTA_DEBUG - OTA_DEBUG.print("Update ERROR: "); - Update.printError(OTA_DEBUG); -#endif + log_e("Update ERROR: %s", Update.errorString()); _state = OTA_IDLE; } } @@ -364,12 +353,13 @@ void ArduinoOTAClass::end() { MDNS.end(); } _state = OTA_IDLE; -#ifdef OTA_DEBUG - OTA_DEBUG.println("OTA server stopped."); -#endif + log_i("OTA server stopped."); } void ArduinoOTAClass::handle() { + if (!_initialized) { + return; + } if (_state == OTA_RUNUPDATE) { _runUpdate(); _state = OTA_IDLE; @@ -384,6 +374,10 @@ int ArduinoOTAClass::getCommand() { return _cmd; } +void ArduinoOTAClass::setTimeout(int timeoutInMillis) { + _ota_timeout = timeoutInMillis; +} + #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_ARDUINOOTA) ArduinoOTAClass ArduinoOTA; #endif diff --git a/libraries/ArduinoOTA/src/ArduinoOTA.h b/libraries/ArduinoOTA/src/ArduinoOTA.h index ee8d589702f..db0ead631db 100644 --- a/libraries/ArduinoOTA/src/ArduinoOTA.h +++ b/libraries/ArduinoOTA/src/ArduinoOTA.h @@ -7,7 +7,6 @@ #define INT_BUFFER_SIZE 16 - typedef enum { OTA_IDLE, OTA_WAITAUTH, @@ -25,9 +24,9 @@ typedef enum { class ArduinoOTAClass { public: - typedef std::function THandlerFunction; - typedef std::function THandlerFunction_Error; - typedef std::function THandlerFunction_Progress; + typedef std::function THandlerFunction; + typedef std::function THandlerFunction_Error; + typedef std::function THandlerFunction_Progress; ArduinoOTAClass(); ~ArduinoOTAClass(); @@ -75,6 +74,8 @@ class ArduinoOTAClass //Gets update command type after OTA has started. Either U_FLASH or U_SPIFFS int getCommand(); + void setTimeout(int timeoutInMillis); + private: int _port; String _password; @@ -88,6 +89,7 @@ class ArduinoOTAClass int _size; int _cmd; int _ota_port; + int _ota_timeout; IPAddress _ota_ip; String _md5; @@ -106,4 +108,4 @@ class ArduinoOTAClass extern ArduinoOTAClass ArduinoOTA; #endif -#endif /* __ARDUINO_OTA_H */ +#endif /* __ARDUINO_OTA_H */ \ No newline at end of file diff --git a/libraries/AsyncUDP/examples/AsyncUDPClient/AsyncUDPClient.ino b/libraries/AsyncUDP/examples/AsyncUDPClient/AsyncUDPClient.ino new file mode 100644 index 00000000000..3348f8a76a4 --- /dev/null +++ b/libraries/AsyncUDP/examples/AsyncUDPClient/AsyncUDPClient.ino @@ -0,0 +1,51 @@ +#include "WiFi.h" +#include "AsyncUDP.h" + +const char * ssid = "***********"; +const char * password = "***********"; + +AsyncUDP udp; + +void setup() +{ + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Failed"); + while(1) { + delay(1000); + } + } + if(udp.connect(IPAddress(192,168,1,100), 1234)) { + Serial.println("UDP connected"); + udp.onPacket([](AsyncUDPPacket packet) { + Serial.print("UDP Packet Type: "); + Serial.print(packet.isBroadcast()?"Broadcast":packet.isMulticast()?"Multicast":"Unicast"); + Serial.print(", From: "); + Serial.print(packet.remoteIP()); + Serial.print(":"); + Serial.print(packet.remotePort()); + Serial.print(", To: "); + Serial.print(packet.localIP()); + Serial.print(":"); + Serial.print(packet.localPort()); + Serial.print(", Length: "); + Serial.print(packet.length()); + Serial.print(", Data: "); + Serial.write(packet.data(), packet.length()); + Serial.println(); + //reply to the client + packet.printf("Got %u bytes of data", packet.length()); + }); + //Send unicast + udp.print("Hello Server!"); + } +} + +void loop() +{ + delay(1000); + //Send broadcast on port 1234 + udp.broadcastTo("Anyone here?", 1234); +} diff --git a/libraries/AsyncUDP/examples/AsyncUDPMulticastServer/AsyncUDPMulticastServer.ino b/libraries/AsyncUDP/examples/AsyncUDPMulticastServer/AsyncUDPMulticastServer.ino new file mode 100644 index 00000000000..2bbbac51c4d --- /dev/null +++ b/libraries/AsyncUDP/examples/AsyncUDPMulticastServer/AsyncUDPMulticastServer.ino @@ -0,0 +1,52 @@ +#include "WiFi.h" +#include "AsyncUDP.h" + +const char * ssid = "***********"; +const char * password = "***********"; + +AsyncUDP udp; + +void setup() +{ + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Failed"); + while(1) { + delay(1000); + } + } + if(udp.listenMulticast(IPAddress(239,1,2,3), 1234)) { + Serial.print("UDP Listening on IP: "); + Serial.println(WiFi.localIP()); + udp.onPacket([](AsyncUDPPacket packet) { + Serial.print("UDP Packet Type: "); + Serial.print(packet.isBroadcast()?"Broadcast":packet.isMulticast()?"Multicast":"Unicast"); + Serial.print(", From: "); + Serial.print(packet.remoteIP()); + Serial.print(":"); + Serial.print(packet.remotePort()); + Serial.print(", To: "); + Serial.print(packet.localIP()); + Serial.print(":"); + Serial.print(packet.localPort()); + Serial.print(", Length: "); + Serial.print(packet.length()); + Serial.print(", Data: "); + Serial.write(packet.data(), packet.length()); + Serial.println(); + //reply to the client + packet.printf("Got %u bytes of data", packet.length()); + }); + //Send multicast + udp.print("Hello!"); + } +} + +void loop() +{ + delay(1000); + //Send multicast + udp.print("Anyone here?"); +} diff --git a/libraries/AsyncUDP/examples/AsyncUDPServer/AsyncUDPServer.ino b/libraries/AsyncUDP/examples/AsyncUDPServer/AsyncUDPServer.ino new file mode 100644 index 00000000000..1f8529bd51d --- /dev/null +++ b/libraries/AsyncUDP/examples/AsyncUDPServer/AsyncUDPServer.ino @@ -0,0 +1,50 @@ +#include "WiFi.h" +#include "AsyncUDP.h" + +const char * ssid = "***********"; +const char * password = "***********"; + +AsyncUDP udp; + +void setup() +{ + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Failed"); + while(1) { + delay(1000); + } + } + if(udp.listen(1234)) { + Serial.print("UDP Listening on IP: "); + Serial.println(WiFi.localIP()); + udp.onPacket([](AsyncUDPPacket packet) { + Serial.print("UDP Packet Type: "); + Serial.print(packet.isBroadcast()?"Broadcast":packet.isMulticast()?"Multicast":"Unicast"); + Serial.print(", From: "); + Serial.print(packet.remoteIP()); + Serial.print(":"); + Serial.print(packet.remotePort()); + Serial.print(", To: "); + Serial.print(packet.localIP()); + Serial.print(":"); + Serial.print(packet.localPort()); + Serial.print(", Length: "); + Serial.print(packet.length()); + Serial.print(", Data: "); + Serial.write(packet.data(), packet.length()); + Serial.println(); + //reply to the client + packet.printf("Got %u bytes of data", packet.length()); + }); + } +} + +void loop() +{ + delay(1000); + //Send broadcast + udp.broadcast("Anyone here?"); +} diff --git a/libraries/AsyncUDP/keywords.txt b/libraries/AsyncUDP/keywords.txt new file mode 100644 index 00000000000..67c0b97a715 --- /dev/null +++ b/libraries/AsyncUDP/keywords.txt @@ -0,0 +1,33 @@ +####################################### +# Syntax Coloring Map For Ultrasound +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +AsyncUDP KEYWORD1 +AsyncUDPPacket KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +connect KEYWORD2 +connected KEYWORD2 +listen KEYWORD2 +listenMulticast KEYWORD2 +close KEYWORD2 +write KEYWORD2 +broadcast KEYWORD2 +onPacket KEYWORD2 +data KEYWORD2 +length KEYWORD2 +localIP KEYWORD2 +localPort KEYWORD2 +remoteIP KEYWORD2 +remotePort KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/libraries/AsyncUDP/library.properties b/libraries/AsyncUDP/library.properties new file mode 100644 index 00000000000..95a5e148d2f --- /dev/null +++ b/libraries/AsyncUDP/library.properties @@ -0,0 +1,9 @@ +name=ESP32 Async UDP +version=1.0.0 +author=Me-No-Dev +maintainer=Me-No-Dev +sentence=Async UDP Library for ESP32 +paragraph=Async UDP Library for ESP32 +category=Other +url=https://github.com/me-no-dev/ESPAsyncUDP +architectures=* diff --git a/libraries/AsyncUDP/src/AsyncUDP.cpp b/libraries/AsyncUDP/src/AsyncUDP.cpp new file mode 100644 index 00000000000..762529b9e0f --- /dev/null +++ b/libraries/AsyncUDP/src/AsyncUDP.cpp @@ -0,0 +1,881 @@ +#include "Arduino.h" +#include "AsyncUDP.h" + +extern "C" { +#include "lwip/opt.h" +#include "lwip/inet.h" +#include "lwip/udp.h" +#include "lwip/igmp.h" +#include "lwip/ip_addr.h" +#include "lwip/mld6.h" +#include "lwip/prot/ethernet.h" +#include +#include +} + +#include "lwip/priv/tcpip_priv.h" + +typedef struct { + struct tcpip_api_call_data call; + udp_pcb * pcb; + const ip_addr_t *addr; + uint16_t port; + struct pbuf *pb; + struct netif *netif; + err_t err; +} udp_api_call_t; + +static err_t _udp_connect_api(struct tcpip_api_call_data *api_call_msg){ + udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; + msg->err = udp_connect(msg->pcb, msg->addr, msg->port); + return msg->err; +} + +static err_t _udp_connect(struct udp_pcb *pcb, const ip_addr_t *addr, u16_t port){ + udp_api_call_t msg; + msg.pcb = pcb; + msg.addr = addr; + msg.port = port; + tcpip_api_call(_udp_connect_api, (struct tcpip_api_call_data*)&msg); + return msg.err; +} + +static err_t _udp_disconnect_api(struct tcpip_api_call_data *api_call_msg){ + udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; + msg->err = 0; + udp_disconnect(msg->pcb); + return msg->err; +} + +static void _udp_disconnect(struct udp_pcb *pcb){ + udp_api_call_t msg; + msg.pcb = pcb; + tcpip_api_call(_udp_disconnect_api, (struct tcpip_api_call_data*)&msg); +} + +static err_t _udp_remove_api(struct tcpip_api_call_data *api_call_msg){ + udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; + msg->err = 0; + udp_remove(msg->pcb); + return msg->err; +} + +static void _udp_remove(struct udp_pcb *pcb){ + udp_api_call_t msg; + msg.pcb = pcb; + tcpip_api_call(_udp_remove_api, (struct tcpip_api_call_data*)&msg); +} + +static err_t _udp_bind_api(struct tcpip_api_call_data *api_call_msg){ + udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; + msg->err = udp_bind(msg->pcb, msg->addr, msg->port); + return msg->err; +} + +static err_t _udp_bind(struct udp_pcb *pcb, const ip_addr_t *addr, u16_t port){ + udp_api_call_t msg; + msg.pcb = pcb; + msg.addr = addr; + msg.port = port; + tcpip_api_call(_udp_bind_api, (struct tcpip_api_call_data*)&msg); + return msg.err; +} + +static err_t _udp_sendto_api(struct tcpip_api_call_data *api_call_msg){ + udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; + msg->err = udp_sendto(msg->pcb, msg->pb, msg->addr, msg->port); + return msg->err; +} + +static err_t _udp_sendto(struct udp_pcb *pcb, struct pbuf *pb, const ip_addr_t *addr, u16_t port){ + udp_api_call_t msg; + msg.pcb = pcb; + msg.addr = addr; + msg.port = port; + msg.pb = pb; + tcpip_api_call(_udp_sendto_api, (struct tcpip_api_call_data*)&msg); + return msg.err; +} + +static err_t _udp_sendto_if_api(struct tcpip_api_call_data *api_call_msg){ + udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; + msg->err = udp_sendto_if(msg->pcb, msg->pb, msg->addr, msg->port, msg->netif); + return msg->err; +} + +static err_t _udp_sendto_if(struct udp_pcb *pcb, struct pbuf *pb, const ip_addr_t *addr, u16_t port, struct netif *netif){ + udp_api_call_t msg; + msg.pcb = pcb; + msg.addr = addr; + msg.port = port; + msg.pb = pb; + msg.netif = netif; + tcpip_api_call(_udp_sendto_if_api, (struct tcpip_api_call_data*)&msg); + return msg.err; +} + +typedef struct { + void *arg; + udp_pcb *pcb; + pbuf *pb; + const ip_addr_t *addr; + uint16_t port; + struct netif * netif; +} lwip_event_packet_t; + +static xQueueHandle _udp_queue; +static volatile TaskHandle_t _udp_task_handle = NULL; + +static void _udp_task(void *pvParameters){ + lwip_event_packet_t * e = NULL; + for (;;) { + if(xQueueReceive(_udp_queue, &e, portMAX_DELAY) == pdTRUE){ + if(!e->pb){ + free((void*)(e)); + continue; + } + AsyncUDP::_s_recv(e->arg, e->pcb, e->pb, e->addr, e->port, e->netif); + free((void*)(e)); + } + } + _udp_task_handle = NULL; + vTaskDelete(NULL); +} + +static bool _udp_task_start(){ + if(!_udp_queue){ + _udp_queue = xQueueCreate(32, sizeof(lwip_event_packet_t *)); + if(!_udp_queue){ + return false; + } + } + if(!_udp_task_handle){ + xTaskCreateUniversal(_udp_task, "async_udp", 4096, NULL, 3, (TaskHandle_t*)&_udp_task_handle, CONFIG_ARDUINO_UDP_RUNNING_CORE); + if(!_udp_task_handle){ + return false; + } + } + return true; +} + +static bool _udp_task_post(void *arg, udp_pcb *pcb, pbuf *pb, const ip_addr_t *addr, uint16_t port, struct netif *netif) +{ + if(!_udp_task_handle || !_udp_queue){ + return false; + } + lwip_event_packet_t * e = (lwip_event_packet_t *)malloc(sizeof(lwip_event_packet_t)); + if(!e){ + return false; + } + e->arg = arg; + e->pcb = pcb; + e->pb = pb; + e->addr = addr; + e->port = port; + e->netif = netif; + if (xQueueSend(_udp_queue, &e, portMAX_DELAY) != pdPASS) { + free((void*)(e)); + return false; + } + return true; +} + +static void _udp_recv(void *arg, udp_pcb *pcb, pbuf *pb, const ip_addr_t *addr, uint16_t port) +{ + while(pb != NULL) { + pbuf * this_pb = pb; + pb = pb->next; + this_pb->next = NULL; + if(!_udp_task_post(arg, pcb, this_pb, addr, port, ip_current_input_netif())){ + pbuf_free(this_pb); + } + } +} +/* +static bool _udp_task_stop(){ + if(!_udp_task_post(NULL, NULL, NULL, NULL, 0, NULL)){ + return false; + } + while(_udp_task_handle){ + vTaskDelay(10); + } + + lwip_event_packet_t * e; + while (xQueueReceive(_udp_queue, &e, 0) == pdTRUE) { + if(e->pb){ + pbuf_free(e->pb); + } + free((void*)(e)); + } + vQueueDelete(_udp_queue); + _udp_queue = NULL; +} +*/ + + + +#define UDP_MUTEX_LOCK() //xSemaphoreTake(_lock, portMAX_DELAY) +#define UDP_MUTEX_UNLOCK() //xSemaphoreGive(_lock) + + +AsyncUDPMessage::AsyncUDPMessage(size_t size) +{ + _index = 0; + if(size > CONFIG_TCP_MSS) { + size = CONFIG_TCP_MSS; + } + _size = size; + _buffer = (uint8_t *)malloc(size); +} + +AsyncUDPMessage::~AsyncUDPMessage() +{ + if(_buffer) { + free(_buffer); + } +} + +size_t AsyncUDPMessage::write(const uint8_t *data, size_t len) +{ + if(_buffer == NULL) { + return 0; + } + size_t s = space(); + if(len > s) { + len = s; + } + memcpy(_buffer + _index, data, len); + _index += len; + return len; +} + +size_t AsyncUDPMessage::write(uint8_t data) +{ + return write(&data, 1); +} + +size_t AsyncUDPMessage::space() +{ + if(_buffer == NULL) { + return 0; + } + return _size - _index; +} + +uint8_t * AsyncUDPMessage::data() +{ + return _buffer; +} + +size_t AsyncUDPMessage::length() +{ + return _index; +} + +void AsyncUDPMessage::flush() +{ + _index = 0; +} + + +AsyncUDPPacket::AsyncUDPPacket(AsyncUDP *udp, pbuf *pb, const ip_addr_t *raddr, uint16_t rport, struct netif * ntif) +{ + _udp = udp; + _pb = pb; + _if = TCPIP_ADAPTER_IF_MAX; + _data = (uint8_t*)(pb->payload); + _len = pb->len; + _index = 0; + + pbuf_ref(_pb); + + //memcpy(&_remoteIp, raddr, sizeof(ip_addr_t)); + _remoteIp.type = raddr->type; + _localIp.type = _remoteIp.type; + + eth_hdr* eth = NULL; + udp_hdr* udphdr = reinterpret_cast(_data - UDP_HLEN); + _localPort = ntohs(udphdr->dest); + _remotePort = ntohs(udphdr->src); + + if (_remoteIp.type == IPADDR_TYPE_V4) { + eth = (eth_hdr *)(((uint8_t *)(pb->payload)) - UDP_HLEN - IP_HLEN - SIZEOF_ETH_HDR); + struct ip_hdr * iphdr = (struct ip_hdr *)(((uint8_t *)(pb->payload)) - UDP_HLEN - IP_HLEN); + _localIp.u_addr.ip4.addr = iphdr->dest.addr; + _remoteIp.u_addr.ip4.addr = iphdr->src.addr; + } else { + eth = (eth_hdr *)(((uint8_t *)(pb->payload)) - UDP_HLEN - IP6_HLEN - SIZEOF_ETH_HDR); + struct ip6_hdr * ip6hdr = (struct ip6_hdr *)(((uint8_t *)(pb->payload)) - UDP_HLEN - IP6_HLEN); + memcpy(&_localIp.u_addr.ip6.addr, (uint8_t *)ip6hdr->dest.addr, 16); + memcpy(&_remoteIp.u_addr.ip6.addr, (uint8_t *)ip6hdr->src.addr, 16); + } + memcpy(_remoteMac, eth->src.addr, 6); + + struct netif * netif = NULL; + void * nif = NULL; + int i; + for (i=0; i a){ + len = a; + } + for(i=0;iwriteTo(data, len, &_remoteIp, _remotePort, _if); +} + +size_t AsyncUDPPacket::write(uint8_t data) +{ + return write(&data, 1); +} + +size_t AsyncUDPPacket::send(AsyncUDPMessage &message) +{ + return write(message.data(), message.length()); +} + +bool AsyncUDP::_init(){ + if(_pcb){ + return true; + } + _pcb = udp_new(); + if(!_pcb){ + return false; + } + //_lock = xSemaphoreCreateMutex(); + udp_recv(_pcb, &_udp_recv, (void *) this); + return true; +} + +AsyncUDP::AsyncUDP() +{ + _pcb = NULL; + _connected = false; + _handler = NULL; +} + +AsyncUDP::~AsyncUDP() +{ + close(); + UDP_MUTEX_LOCK(); + udp_recv(_pcb, NULL, NULL); + _udp_remove(_pcb); + _pcb = NULL; + UDP_MUTEX_UNLOCK(); + //vSemaphoreDelete(_lock); +} + +void AsyncUDP::close() +{ + UDP_MUTEX_LOCK(); + if(_pcb != NULL) { + if(_connected) { + _udp_disconnect(_pcb); + } + _connected = false; + //todo: unjoin multicast group + } + UDP_MUTEX_UNLOCK(); +} + +bool AsyncUDP::connect(const ip_addr_t *addr, uint16_t port) +{ + if(!_udp_task_start()){ + log_e("failed to start task"); + return false; + } + if(!_init()) { + return false; + } + close(); + UDP_MUTEX_LOCK(); + err_t err = _udp_connect(_pcb, addr, port); + if(err != ERR_OK) { + UDP_MUTEX_UNLOCK(); + return false; + } + _connected = true; + UDP_MUTEX_UNLOCK(); + return true; +} + +bool AsyncUDP::listen(const ip_addr_t *addr, uint16_t port) +{ + if(!_udp_task_start()){ + log_e("failed to start task"); + return false; + } + if(!_init()) { + return false; + } + close(); + if(addr){ + IP_SET_TYPE_VAL(_pcb->local_ip, addr->type); + IP_SET_TYPE_VAL(_pcb->remote_ip, addr->type); + } + UDP_MUTEX_LOCK(); + if(_udp_bind(_pcb, addr, port) != ERR_OK) { + UDP_MUTEX_UNLOCK(); + return false; + } + _connected = true; + UDP_MUTEX_UNLOCK(); + return true; +} + +static esp_err_t joinMulticastGroup(const ip_addr_t *addr, bool join, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX) +{ + struct netif * netif = NULL; + if(tcpip_if < TCPIP_ADAPTER_IF_MAX){ + void * nif = NULL; + esp_err_t err = tcpip_adapter_get_netif(tcpip_if, &nif); + if (err) { + return ESP_ERR_INVALID_ARG; + } + netif = (struct netif *)nif; + + if (addr->type == IPADDR_TYPE_V4) { + if(join){ + if (igmp_joingroup_netif(netif, (const ip4_addr *)&(addr->u_addr.ip4))) { + return ESP_ERR_INVALID_STATE; + } + } else { + if (igmp_leavegroup_netif(netif, (const ip4_addr *)&(addr->u_addr.ip4))) { + return ESP_ERR_INVALID_STATE; + } + } + } else { + if(join){ + if (mld6_joingroup_netif(netif, &(addr->u_addr.ip6))) { + return ESP_ERR_INVALID_STATE; + } + } else { + if (mld6_leavegroup_netif(netif, &(addr->u_addr.ip6))) { + return ESP_ERR_INVALID_STATE; + } + } + } + } else { + if (addr->type == IPADDR_TYPE_V4) { + if(join){ + if (igmp_joingroup((const ip4_addr *)IP4_ADDR_ANY, (const ip4_addr *)&(addr->u_addr.ip4))) { + return ESP_ERR_INVALID_STATE; + } + } else { + if (igmp_leavegroup((const ip4_addr *)IP4_ADDR_ANY, (const ip4_addr *)&(addr->u_addr.ip4))) { + return ESP_ERR_INVALID_STATE; + } + } + } else { + if(join){ + if (mld6_joingroup((const ip6_addr *)IP6_ADDR_ANY, &(addr->u_addr.ip6))) { + return ESP_ERR_INVALID_STATE; + } + } else { + if (mld6_leavegroup((const ip6_addr *)IP6_ADDR_ANY, &(addr->u_addr.ip6))) { + return ESP_ERR_INVALID_STATE; + } + } + } + } + return ESP_OK; +} + +bool AsyncUDP::listenMulticast(const ip_addr_t *addr, uint16_t port, uint8_t ttl, tcpip_adapter_if_t tcpip_if) +{ + if(!ip_addr_ismulticast(addr)) { + return false; + } + + if (joinMulticastGroup(addr, true, tcpip_if)!= ERR_OK) { + return false; + } + + if(!listen(NULL, port)) { + return false; + } + + UDP_MUTEX_LOCK(); + _pcb->mcast_ttl = ttl; + _pcb->remote_port = port; + ip_addr_copy(_pcb->remote_ip, *addr); + //ip_addr_copy(_pcb->remote_ip, ip_addr_any_type); + UDP_MUTEX_UNLOCK(); + + return true; +} + +size_t AsyncUDP::writeTo(const uint8_t * data, size_t len, const ip_addr_t * addr, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + if(!_pcb) { + UDP_MUTEX_LOCK(); + _pcb = udp_new(); + UDP_MUTEX_UNLOCK(); + if(_pcb == NULL) { + return 0; + } + } + if(len > CONFIG_TCP_MSS) { + len = CONFIG_TCP_MSS; + } + err_t err = ERR_OK; + pbuf* pbt = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); + if(pbt != NULL) { + uint8_t* dst = reinterpret_cast(pbt->payload); + memcpy(dst, data, len); + UDP_MUTEX_LOCK(); + if(tcpip_if < TCPIP_ADAPTER_IF_MAX){ + void * nif = NULL; + tcpip_adapter_get_netif((tcpip_adapter_if_t)tcpip_if, &nif); + if(!nif){ + err = _udp_sendto(_pcb, pbt, addr, port); + } else { + err = _udp_sendto_if(_pcb, pbt, addr, port, (struct netif *)nif); + } + } else { + err = _udp_sendto(_pcb, pbt, addr, port); + } + UDP_MUTEX_UNLOCK(); + pbuf_free(pbt); + if(err < ERR_OK) { + return 0; + } + return len; + } + return 0; +} + +void AsyncUDP::_recv(udp_pcb *upcb, pbuf *pb, const ip_addr_t *addr, uint16_t port, struct netif * netif) +{ + while(pb != NULL) { + pbuf * this_pb = pb; + pb = pb->next; + this_pb->next = NULL; + if(_handler) { + AsyncUDPPacket packet(this, this_pb, addr, port, netif); + _handler(packet); + } else { + pbuf_free(this_pb); + } + } +} + +void AsyncUDP::_s_recv(void *arg, udp_pcb *upcb, pbuf *p, const ip_addr_t *addr, uint16_t port, struct netif * netif) +{ + reinterpret_cast(arg)->_recv(upcb, p, addr, port, netif); +} + +bool AsyncUDP::listen(uint16_t port) +{ + return listen(IP_ANY_TYPE, port); +} + +bool AsyncUDP::listen(const IPAddress addr, uint16_t port) +{ + ip_addr_t laddr; + laddr.type = IPADDR_TYPE_V4; + laddr.u_addr.ip4.addr = addr; + return listen(&laddr, port); +} + +bool AsyncUDP::listenMulticast(const IPAddress addr, uint16_t port, uint8_t ttl, tcpip_adapter_if_t tcpip_if) +{ + ip_addr_t laddr; + laddr.type = IPADDR_TYPE_V4; + laddr.u_addr.ip4.addr = addr; + return listenMulticast(&laddr, port, ttl, tcpip_if); +} + +bool AsyncUDP::connect(const IPAddress addr, uint16_t port) +{ + ip_addr_t daddr; + daddr.type = IPADDR_TYPE_V4; + daddr.u_addr.ip4.addr = addr; + return connect(&daddr, port); +} + +size_t AsyncUDP::writeTo(const uint8_t *data, size_t len, const IPAddress addr, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + ip_addr_t daddr; + daddr.type = IPADDR_TYPE_V4; + daddr.u_addr.ip4.addr = addr; + return writeTo(data, len, &daddr, port, tcpip_if); +} + +IPAddress AsyncUDP::listenIP() +{ + if(!_pcb || _pcb->remote_ip.type != IPADDR_TYPE_V4){ + return IPAddress(); + } + return IPAddress(_pcb->remote_ip.u_addr.ip4.addr); +} + +bool AsyncUDP::listen(const IPv6Address addr, uint16_t port) +{ + ip_addr_t laddr; + laddr.type = IPADDR_TYPE_V6; + memcpy((uint8_t*)(laddr.u_addr.ip6.addr), (const uint8_t*)addr, 16); + return listen(&laddr, port); +} + +bool AsyncUDP::listenMulticast(const IPv6Address addr, uint16_t port, uint8_t ttl, tcpip_adapter_if_t tcpip_if) +{ + ip_addr_t laddr; + laddr.type = IPADDR_TYPE_V6; + memcpy((uint8_t*)(laddr.u_addr.ip6.addr), (const uint8_t*)addr, 16); + return listenMulticast(&laddr, port, ttl, tcpip_if); +} + +bool AsyncUDP::connect(const IPv6Address addr, uint16_t port) +{ + ip_addr_t daddr; + daddr.type = IPADDR_TYPE_V6; + memcpy((uint8_t*)(daddr.u_addr.ip6.addr), (const uint8_t*)addr, 16); + return connect(&daddr, port); +} + +size_t AsyncUDP::writeTo(const uint8_t *data, size_t len, const IPv6Address addr, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + ip_addr_t daddr; + daddr.type = IPADDR_TYPE_V6; + memcpy((uint8_t*)(daddr.u_addr.ip6.addr), (const uint8_t*)addr, 16); + return writeTo(data, len, &daddr, port, tcpip_if); +} + +IPv6Address AsyncUDP::listenIPv6() +{ + if(!_pcb || _pcb->remote_ip.type != IPADDR_TYPE_V6){ + return IPv6Address(); + } + return IPv6Address(_pcb->remote_ip.u_addr.ip6.addr); +} + +size_t AsyncUDP::write(const uint8_t *data, size_t len) +{ + return writeTo(data, len, &(_pcb->remote_ip), _pcb->remote_port); +} + +size_t AsyncUDP::write(uint8_t data) +{ + return write(&data, 1); +} + +size_t AsyncUDP::broadcastTo(uint8_t *data, size_t len, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + return writeTo(data, len, IP_ADDR_BROADCAST, port, tcpip_if); +} + +size_t AsyncUDP::broadcastTo(const char * data, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + return broadcastTo((uint8_t *)data, strlen(data), port, tcpip_if); +} + +size_t AsyncUDP::broadcast(uint8_t *data, size_t len) +{ + if(_pcb->local_port != 0) { + return broadcastTo(data, len, _pcb->local_port); + } + return 0; +} + +size_t AsyncUDP::broadcast(const char * data) +{ + return broadcast((uint8_t *)data, strlen(data)); +} + + +size_t AsyncUDP::sendTo(AsyncUDPMessage &message, const ip_addr_t *addr, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + if(!message) { + return 0; + } + return writeTo(message.data(), message.length(), addr, port, tcpip_if); +} + +size_t AsyncUDP::sendTo(AsyncUDPMessage &message, const IPAddress addr, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + if(!message) { + return 0; + } + return writeTo(message.data(), message.length(), addr, port, tcpip_if); +} + +size_t AsyncUDP::sendTo(AsyncUDPMessage &message, const IPv6Address addr, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + if(!message) { + return 0; + } + return writeTo(message.data(), message.length(), addr, port, tcpip_if); +} + +size_t AsyncUDP::send(AsyncUDPMessage &message) +{ + if(!message) { + return 0; + } + return writeTo(message.data(), message.length(), &(_pcb->remote_ip), _pcb->remote_port); +} + +size_t AsyncUDP::broadcastTo(AsyncUDPMessage &message, uint16_t port, tcpip_adapter_if_t tcpip_if) +{ + if(!message) { + return 0; + } + return broadcastTo(message.data(), message.length(), port, tcpip_if); +} + +size_t AsyncUDP::broadcast(AsyncUDPMessage &message) +{ + if(!message) { + return 0; + } + return broadcast(message.data(), message.length()); +} + +AsyncUDP::operator bool() +{ + return _connected; +} + +bool AsyncUDP::connected() +{ + return _connected; +} + +void AsyncUDP::onPacket(AuPacketHandlerFunctionWithArg cb, void * arg) +{ + onPacket(std::bind(cb, arg, std::placeholders::_1)); +} + +void AsyncUDP::onPacket(AuPacketHandlerFunction cb) +{ + _handler = cb; +} diff --git a/libraries/AsyncUDP/src/AsyncUDP.h b/libraries/AsyncUDP/src/AsyncUDP.h new file mode 100644 index 00000000000..2ac48a69684 --- /dev/null +++ b/libraries/AsyncUDP/src/AsyncUDP.h @@ -0,0 +1,152 @@ +#ifndef ESPASYNCUDP_H +#define ESPASYNCUDP_H + +#include "IPAddress.h" +#include "IPv6Address.h" +#include "Print.h" +#include +extern "C" { +#include "lwip/ip_addr.h" +#include +#include "freertos/queue.h" +#include "freertos/semphr.h" +} + +class AsyncUDP; +class AsyncUDPPacket; +class AsyncUDPMessage; +struct udp_pcb; +struct pbuf; +struct netif; + +typedef std::function AuPacketHandlerFunction; +typedef std::function AuPacketHandlerFunctionWithArg; + +class AsyncUDPMessage : public Print +{ +protected: + uint8_t *_buffer; + size_t _index; + size_t _size; +public: + AsyncUDPMessage(size_t size=CONFIG_TCP_MSS); + virtual ~AsyncUDPMessage(); + size_t write(const uint8_t *data, size_t len); + size_t write(uint8_t data); + size_t space(); + uint8_t * data(); + size_t length(); + void flush(); + operator bool() + { + return _buffer != NULL; + } +}; + +class AsyncUDPPacket : public Stream +{ +protected: + AsyncUDP *_udp; + pbuf *_pb; + tcpip_adapter_if_t _if; + ip_addr_t _localIp; + uint16_t _localPort; + ip_addr_t _remoteIp; + uint16_t _remotePort; + uint8_t _remoteMac[6]; + uint8_t *_data; + size_t _len; + size_t _index; +public: + AsyncUDPPacket(AsyncUDP *udp, pbuf *pb, const ip_addr_t *addr, uint16_t port, struct netif * netif); + virtual ~AsyncUDPPacket(); + + uint8_t * data(); + size_t length(); + bool isBroadcast(); + bool isMulticast(); + bool isIPv6(); + + tcpip_adapter_if_t interface(); + + IPAddress localIP(); + IPv6Address localIPv6(); + uint16_t localPort(); + IPAddress remoteIP(); + IPv6Address remoteIPv6(); + uint16_t remotePort(); + void remoteMac(uint8_t * mac); + + size_t send(AsyncUDPMessage &message); + + int available(); + size_t read(uint8_t *data, size_t len); + int read(); + int peek(); + void flush(); + + size_t write(const uint8_t *data, size_t len); + size_t write(uint8_t data); +}; + +class AsyncUDP : public Print +{ +protected: + udp_pcb *_pcb; + //xSemaphoreHandle _lock; + bool _connected; + AuPacketHandlerFunction _handler; + + bool _init(); + void _recv(udp_pcb *upcb, pbuf *pb, const ip_addr_t *addr, uint16_t port, struct netif * netif); + +public: + AsyncUDP(); + virtual ~AsyncUDP(); + + void onPacket(AuPacketHandlerFunctionWithArg cb, void * arg=NULL); + void onPacket(AuPacketHandlerFunction cb); + + bool listen(const ip_addr_t *addr, uint16_t port); + bool listen(const IPAddress addr, uint16_t port); + bool listen(const IPv6Address addr, uint16_t port); + bool listen(uint16_t port); + + bool listenMulticast(const ip_addr_t *addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + bool listenMulticast(const IPAddress addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + bool listenMulticast(const IPv6Address addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + + bool connect(const ip_addr_t *addr, uint16_t port); + bool connect(const IPAddress addr, uint16_t port); + bool connect(const IPv6Address addr, uint16_t port); + + void close(); + + size_t writeTo(const uint8_t *data, size_t len, const ip_addr_t *addr, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t writeTo(const uint8_t *data, size_t len, const IPAddress addr, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t writeTo(const uint8_t *data, size_t len, const IPv6Address addr, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t write(const uint8_t *data, size_t len); + size_t write(uint8_t data); + + size_t broadcastTo(uint8_t *data, size_t len, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t broadcastTo(const char * data, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t broadcast(uint8_t *data, size_t len); + size_t broadcast(const char * data); + + size_t sendTo(AsyncUDPMessage &message, const ip_addr_t *addr, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t sendTo(AsyncUDPMessage &message, const IPAddress addr, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t sendTo(AsyncUDPMessage &message, const IPv6Address addr, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t send(AsyncUDPMessage &message); + + size_t broadcastTo(AsyncUDPMessage &message, uint16_t port, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + size_t broadcast(AsyncUDPMessage &message); + + IPAddress listenIP(); + IPv6Address listenIPv6(); + bool connected(); + operator bool(); + + static void _s_recv(void *arg, udp_pcb *upcb, pbuf *p, const ip_addr_t *addr, uint16_t port, struct netif * netif); +}; + +#endif diff --git a/libraries/AzureIoT b/libraries/AzureIoT new file mode 160000 index 00000000000..67dfa4f31ef --- /dev/null +++ b/libraries/AzureIoT @@ -0,0 +1 @@ +Subproject commit 67dfa4f31ef88b0938dd87d955612100dea5562e diff --git a/libraries/BLE b/libraries/BLE deleted file mode 160000 index af865a91679..00000000000 --- a/libraries/BLE +++ /dev/null @@ -1 +0,0 @@ -Subproject commit af865a916795289c8e7e09b091ff2140c33fc3fe diff --git a/libraries/BLE/README.md b/libraries/BLE/README.md new file mode 100644 index 00000000000..e80fbe0c52b --- /dev/null +++ b/libraries/BLE/README.md @@ -0,0 +1,15 @@ +# ESP32 BLE for Arduino +The Arduino IDE provides an excellent library package manager where versions of libraries can be downloaded and installed. This Github project provides the repository for the ESP32 BLE support for Arduino. + +The actual source of the project which is being maintained can be found here: + +https://github.com/nkolban/esp32-snippets + +Issues and questions should be raised here: + +https://github.com/nkolban/esp32-snippets/issues + + +Documentation for using the library can be found here: + +https://github.com/nkolban/esp32-snippets/tree/master/Documentation \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_client/BLE_client.ino b/libraries/BLE/examples/BLE_client/BLE_client.ino new file mode 100644 index 00000000000..55d9fa0de6a --- /dev/null +++ b/libraries/BLE/examples/BLE_client/BLE_client.ino @@ -0,0 +1,161 @@ +/** + * A BLE client example that is rich in capabilities. + * There is a lot new capabilities implemented. + * author unknown + * updated by chegewara + */ + +#include "BLEDevice.h" +//#include "BLEScan.h" + +// The remote service we wish to connect to. +static BLEUUID serviceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b"); +// The characteristic of the remote service we are interested in. +static BLEUUID charUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8"); + +static boolean doConnect = false; +static boolean connected = false; +static boolean doScan = false; +static BLERemoteCharacteristic* pRemoteCharacteristic; +static BLEAdvertisedDevice* myDevice; + +static void notifyCallback( + BLERemoteCharacteristic* pBLERemoteCharacteristic, + uint8_t* pData, + size_t length, + bool isNotify) { + Serial.print("Notify callback for characteristic "); + Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str()); + Serial.print(" of data length "); + Serial.println(length); + Serial.print("data: "); + Serial.println((char*)pData); +} + +class MyClientCallback : public BLEClientCallbacks { + void onConnect(BLEClient* pclient) { + } + + void onDisconnect(BLEClient* pclient) { + connected = false; + Serial.println("onDisconnect"); + } +}; + +bool connectToServer() { + Serial.print("Forming a connection to "); + Serial.println(myDevice->getAddress().toString().c_str()); + + BLEClient* pClient = BLEDevice::createClient(); + Serial.println(" - Created client"); + + pClient->setClientCallbacks(new MyClientCallback()); + + // Connect to the remove BLE Server. + pClient->connect(myDevice); // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private) + Serial.println(" - Connected to server"); + + // Obtain a reference to the service we are after in the remote BLE server. + BLERemoteService* pRemoteService = pClient->getService(serviceUUID); + if (pRemoteService == nullptr) { + Serial.print("Failed to find our service UUID: "); + Serial.println(serviceUUID.toString().c_str()); + pClient->disconnect(); + return false; + } + Serial.println(" - Found our service"); + + + // Obtain a reference to the characteristic in the service of the remote BLE server. + pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID); + if (pRemoteCharacteristic == nullptr) { + Serial.print("Failed to find our characteristic UUID: "); + Serial.println(charUUID.toString().c_str()); + pClient->disconnect(); + return false; + } + Serial.println(" - Found our characteristic"); + + // Read the value of the characteristic. + if(pRemoteCharacteristic->canRead()) { + std::string value = pRemoteCharacteristic->readValue(); + Serial.print("The characteristic value was: "); + Serial.println(value.c_str()); + } + + if(pRemoteCharacteristic->canNotify()) + pRemoteCharacteristic->registerForNotify(notifyCallback); + + connected = true; + return true; +} +/** + * Scan for BLE servers and find the first one that advertises the service we are looking for. + */ +class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { + /** + * Called for each advertising BLE server. + */ + void onResult(BLEAdvertisedDevice advertisedDevice) { + Serial.print("BLE Advertised Device found: "); + Serial.println(advertisedDevice.toString().c_str()); + + // We have found a device, let us now see if it contains the service we are looking for. + if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) { + + BLEDevice::getScan()->stop(); + myDevice = new BLEAdvertisedDevice(advertisedDevice); + doConnect = true; + doScan = true; + + } // Found our server + } // onResult +}; // MyAdvertisedDeviceCallbacks + + +void setup() { + Serial.begin(115200); + Serial.println("Starting Arduino BLE Client application..."); + BLEDevice::init(""); + + // Retrieve a Scanner and set the callback we want to use to be informed when we + // have detected a new device. Specify that we want active scanning and start the + // scan to run for 5 seconds. + BLEScan* pBLEScan = BLEDevice::getScan(); + pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); + pBLEScan->setInterval(1349); + pBLEScan->setWindow(449); + pBLEScan->setActiveScan(true); + pBLEScan->start(5, false); +} // End of setup. + + +// This is the Arduino main loop function. +void loop() { + + // If the flag "doConnect" is true then we have scanned for and found the desired + // BLE Server with which we wish to connect. Now we connect to it. Once we are + // connected we set the connected flag to be true. + if (doConnect == true) { + if (connectToServer()) { + Serial.println("We are now connected to the BLE Server."); + } else { + Serial.println("We have failed to connect to the server; there is nothin more we will do."); + } + doConnect = false; + } + + // If we are connected to a peer BLE Server, update the characteristic each time we are reached + // with the current time since boot. + if (connected) { + String newValue = "Time since boot: " + String(millis()/1000); + Serial.println("Setting new characteristic value to \"" + newValue + "\""); + + // Set the characteristic's value to be the array of bytes that is actually a string. + pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length()); + }else if(doScan){ + BLEDevice::getScan()->start(0); // this is just example to start scan after disconnect, most likely there is better way to do it in arduino + } + + delay(1000); // Delay a second between loops. +} // End of loop diff --git a/libraries/BLE/examples/BLE_iBeacon/BLE_iBeacon.ino b/libraries/BLE/examples/BLE_iBeacon/BLE_iBeacon.ino new file mode 100644 index 00000000000..e43174d4d51 --- /dev/null +++ b/libraries/BLE/examples/BLE_iBeacon/BLE_iBeacon.ino @@ -0,0 +1,103 @@ +/* + Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp + Ported to Arduino ESP32 by pcbreflux +*/ + + +/* + Create a BLE server that will send periodic iBeacon frames. + The design of creating the BLE server is: + 1. Create a BLE Server + 2. Create advertising data + 3. Start advertising. + 4. wait + 5. Stop advertising. + 6. deep sleep + +*/ +#include "sys/time.h" + +#include "BLEDevice.h" +#include "BLEUtils.h" +#include "BLEBeacon.h" +#include "esp_sleep.h" + +#define GPIO_DEEP_SLEEP_DURATION 10 // sleep x seconds and then wake up +RTC_DATA_ATTR static time_t last; // remember last boot in RTC Memory +RTC_DATA_ATTR static uint32_t bootcount; // remember number of boots in RTC Memory + +#ifdef __cplusplus +extern "C" { +#endif + +uint8_t temprature_sens_read(); +//uint8_t g_phyFuns; + +#ifdef __cplusplus +} +#endif + +// See the following for generating UUIDs: +// https://www.uuidgenerator.net/ +BLEAdvertising *pAdvertising; +struct timeval now; + +#define BEACON_UUID "8ec76ea3-6668-48da-9866-75be8bc86f4d" // UUID 1 128-Bit (may use linux tool uuidgen or random numbers via https://www.uuidgenerator.net/) + +void setBeacon() { + + BLEBeacon oBeacon = BLEBeacon(); + oBeacon.setManufacturerId(0x4C00); // fake Apple 0x004C LSB (ENDIAN_CHANGE_U16!) + oBeacon.setProximityUUID(BLEUUID(BEACON_UUID)); + oBeacon.setMajor((bootcount & 0xFFFF0000) >> 16); + oBeacon.setMinor(bootcount&0xFFFF); + BLEAdvertisementData oAdvertisementData = BLEAdvertisementData(); + BLEAdvertisementData oScanResponseData = BLEAdvertisementData(); + + oAdvertisementData.setFlags(0x04); // BR_EDR_NOT_SUPPORTED 0x04 + + std::string strServiceData = ""; + + strServiceData += (char)26; // Len + strServiceData += (char)0xFF; // Type + strServiceData += oBeacon.getData(); + oAdvertisementData.addData(strServiceData); + + pAdvertising->setAdvertisementData(oAdvertisementData); + pAdvertising->setScanResponseData(oScanResponseData); + +} + +void setup() { + + + Serial.begin(115200); + gettimeofday(&now, NULL); + + Serial.printf("start ESP32 %d\n",bootcount++); + + Serial.printf("deep sleep (%lds since last reset, %lds since last boot)\n",now.tv_sec,now.tv_sec-last); + + last = now.tv_sec; + + // Create the BLE Device + BLEDevice::init(""); + + // Create the BLE Server + // BLEServer *pServer = BLEDevice::createServer(); // <-- no longer required to instantiate BLEServer, less flash and ram usage + + pAdvertising = BLEDevice::getAdvertising(); + + setBeacon(); + // Start advertising + pAdvertising->start(); + Serial.println("Advertizing started..."); + delay(100); + pAdvertising->stop(); + Serial.printf("enter deep sleep\n"); + esp_deep_sleep(1000000LL * GPIO_DEEP_SLEEP_DURATION); + Serial.printf("in deep sleep\n"); +} + +void loop() { +} diff --git a/libraries/BLE/examples/BLE_notify/BLE_notify.ino b/libraries/BLE/examples/BLE_notify/BLE_notify.ino new file mode 100644 index 00000000000..42b9e7273f3 --- /dev/null +++ b/libraries/BLE/examples/BLE_notify/BLE_notify.ino @@ -0,0 +1,110 @@ +/* + Video: https://www.youtube.com/watch?v=oCMOYS71NIU + Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp + Ported to Arduino ESP32 by Evandro Copercini + updated by chegewara + + Create a BLE server that, once we receive a connection, will send periodic notifications. + The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b + And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8 + + The design of creating the BLE server is: + 1. Create a BLE Server + 2. Create a BLE Service + 3. Create a BLE Characteristic on the Service + 4. Create a BLE Descriptor on the characteristic + 5. Start the service. + 6. Start advertising. + + A connect hander associated with the server starts a background task that performs notification + every couple of seconds. +*/ +#include +#include +#include +#include + +BLEServer* pServer = NULL; +BLECharacteristic* pCharacteristic = NULL; +bool deviceConnected = false; +bool oldDeviceConnected = false; +uint32_t value = 0; + +// See the following for generating UUIDs: +// https://www.uuidgenerator.net/ + +#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" +#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" + + +class MyServerCallbacks: public BLEServerCallbacks { + void onConnect(BLEServer* pServer) { + deviceConnected = true; + }; + + void onDisconnect(BLEServer* pServer) { + deviceConnected = false; + } +}; + + + +void setup() { + Serial.begin(115200); + + // Create the BLE Device + BLEDevice::init("ESP32"); + + // Create the BLE Server + pServer = BLEDevice::createServer(); + pServer->setCallbacks(new MyServerCallbacks()); + + // Create the BLE Service + BLEService *pService = pServer->createService(SERVICE_UUID); + + // Create a BLE Characteristic + pCharacteristic = pService->createCharacteristic( + CHARACTERISTIC_UUID, + BLECharacteristic::PROPERTY_READ | + BLECharacteristic::PROPERTY_WRITE | + BLECharacteristic::PROPERTY_NOTIFY | + BLECharacteristic::PROPERTY_INDICATE + ); + + // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml + // Create a BLE Descriptor + pCharacteristic->addDescriptor(new BLE2902()); + + // Start the service + pService->start(); + + // Start advertising + BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); + pAdvertising->addServiceUUID(SERVICE_UUID); + pAdvertising->setScanResponse(false); + pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter + BLEDevice::startAdvertising(); + Serial.println("Waiting a client connection to notify..."); +} + +void loop() { + // notify changed value + if (deviceConnected) { + pCharacteristic->setValue((uint8_t*)&value, 4); + pCharacteristic->notify(); + value++; + delay(3); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms + } + // disconnecting + if (!deviceConnected && oldDeviceConnected) { + delay(500); // give the bluetooth stack the chance to get things ready + pServer->startAdvertising(); // restart advertising + Serial.println("start advertising"); + oldDeviceConnected = deviceConnected; + } + // connecting + if (deviceConnected && !oldDeviceConnected) { + // do stuff here on connecting + oldDeviceConnected = deviceConnected; + } +} \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_scan/BLE_scan.ino b/libraries/BLE/examples/BLE_scan/BLE_scan.ino new file mode 100644 index 00000000000..094f7933ac7 --- /dev/null +++ b/libraries/BLE/examples/BLE_scan/BLE_scan.ino @@ -0,0 +1,40 @@ +/* + Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp + Ported to Arduino ESP32 by Evandro Copercini +*/ + +#include +#include +#include +#include + +int scanTime = 5; //In seconds +BLEScan* pBLEScan; + +class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { + void onResult(BLEAdvertisedDevice advertisedDevice) { + Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str()); + } +}; + +void setup() { + Serial.begin(115200); + Serial.println("Scanning..."); + + BLEDevice::init(""); + pBLEScan = BLEDevice::getScan(); //create new scan + pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); + pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster + pBLEScan->setInterval(100); + pBLEScan->setWindow(99); // less or equal setInterval value +} + +void loop() { + // put your main code here, to run repeatedly: + BLEScanResults foundDevices = pBLEScan->start(scanTime, false); + Serial.print("Devices found: "); + Serial.println(foundDevices.getCount()); + Serial.println("Scan done!"); + pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory + delay(2000); +} \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_server/BLE_server.ino b/libraries/BLE/examples/BLE_server/BLE_server.ino new file mode 100644 index 00000000000..3f9176acf5e --- /dev/null +++ b/libraries/BLE/examples/BLE_server/BLE_server.ino @@ -0,0 +1,45 @@ +/* + Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp + Ported to Arduino ESP32 by Evandro Copercini + updates by chegewara +*/ + +#include +#include +#include + +// See the following for generating UUIDs: +// https://www.uuidgenerator.net/ + +#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" +#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" + +void setup() { + Serial.begin(115200); + Serial.println("Starting BLE work!"); + + BLEDevice::init("Long name works now"); + BLEServer *pServer = BLEDevice::createServer(); + BLEService *pService = pServer->createService(SERVICE_UUID); + BLECharacteristic *pCharacteristic = pService->createCharacteristic( + CHARACTERISTIC_UUID, + BLECharacteristic::PROPERTY_READ | + BLECharacteristic::PROPERTY_WRITE + ); + + pCharacteristic->setValue("Hello World says Neil"); + pService->start(); + // BLEAdvertising *pAdvertising = pServer->getAdvertising(); // this still is working for backward compatibility + BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); + pAdvertising->addServiceUUID(SERVICE_UUID); + pAdvertising->setScanResponse(true); + pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue + pAdvertising->setMinPreferred(0x12); + BLEDevice::startAdvertising(); + Serial.println("Characteristic defined! Now you can read it in your phone!"); +} + +void loop() { + // put your main code here, to run repeatedly: + delay(2000); +} \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_server_multiconnect/BLE_server_multiconnect.ino b/libraries/BLE/examples/BLE_server_multiconnect/BLE_server_multiconnect.ino new file mode 100644 index 00000000000..90704ef16ad --- /dev/null +++ b/libraries/BLE/examples/BLE_server_multiconnect/BLE_server_multiconnect.ino @@ -0,0 +1,111 @@ +/* + Video: https://www.youtube.com/watch?v=oCMOYS71NIU + Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp + Ported to Arduino ESP32 by Evandro Copercini + updated by chegewara + + Create a BLE server that, once we receive a connection, will send periodic notifications. + The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b + And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8 + + The design of creating the BLE server is: + 1. Create a BLE Server + 2. Create a BLE Service + 3. Create a BLE Characteristic on the Service + 4. Create a BLE Descriptor on the characteristic + 5. Start the service. + 6. Start advertising. + + A connect hander associated with the server starts a background task that performs notification + every couple of seconds. +*/ +#include +#include +#include +#include + +BLEServer* pServer = NULL; +BLECharacteristic* pCharacteristic = NULL; +bool deviceConnected = false; +bool oldDeviceConnected = false; +uint32_t value = 0; + +// See the following for generating UUIDs: +// https://www.uuidgenerator.net/ + +#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" +#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" + + +class MyServerCallbacks: public BLEServerCallbacks { + void onConnect(BLEServer* pServer) { + deviceConnected = true; + BLEDevice::startAdvertising(); + }; + + void onDisconnect(BLEServer* pServer) { + deviceConnected = false; + } +}; + + + +void setup() { + Serial.begin(115200); + + // Create the BLE Device + BLEDevice::init("ESP32"); + + // Create the BLE Server + pServer = BLEDevice::createServer(); + pServer->setCallbacks(new MyServerCallbacks()); + + // Create the BLE Service + BLEService *pService = pServer->createService(SERVICE_UUID); + + // Create a BLE Characteristic + pCharacteristic = pService->createCharacteristic( + CHARACTERISTIC_UUID, + BLECharacteristic::PROPERTY_READ | + BLECharacteristic::PROPERTY_WRITE | + BLECharacteristic::PROPERTY_NOTIFY | + BLECharacteristic::PROPERTY_INDICATE + ); + + // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml + // Create a BLE Descriptor + pCharacteristic->addDescriptor(new BLE2902()); + + // Start the service + pService->start(); + + // Start advertising + BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); + pAdvertising->addServiceUUID(SERVICE_UUID); + pAdvertising->setScanResponse(false); + pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter + BLEDevice::startAdvertising(); + Serial.println("Waiting a client connection to notify..."); +} + +void loop() { + // notify changed value + if (deviceConnected) { + pCharacteristic->setValue((uint8_t*)&value, 4); + pCharacteristic->notify(); + value++; + delay(10); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms + } + // disconnecting + if (!deviceConnected && oldDeviceConnected) { + delay(500); // give the bluetooth stack the chance to get things ready + pServer->startAdvertising(); // restart advertising + Serial.println("start advertising"); + oldDeviceConnected = deviceConnected; + } + // connecting + if (deviceConnected && !oldDeviceConnected) { + // do stuff here on connecting + oldDeviceConnected = deviceConnected; + } +} diff --git a/libraries/BLE/examples/BLE_uart/BLE_uart.ino b/libraries/BLE/examples/BLE_uart/BLE_uart.ino new file mode 100644 index 00000000000..35b570b9192 --- /dev/null +++ b/libraries/BLE/examples/BLE_uart/BLE_uart.ino @@ -0,0 +1,125 @@ +/* + Video: https://www.youtube.com/watch?v=oCMOYS71NIU + Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp + Ported to Arduino ESP32 by Evandro Copercini + + Create a BLE server that, once we receive a connection, will send periodic notifications. + The service advertises itself as: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E + Has a characteristic of: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E - used for receiving data with "WRITE" + Has a characteristic of: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E - used to send data with "NOTIFY" + + The design of creating the BLE server is: + 1. Create a BLE Server + 2. Create a BLE Service + 3. Create a BLE Characteristic on the Service + 4. Create a BLE Descriptor on the characteristic + 5. Start the service. + 6. Start advertising. + + In this example rxValue is the data received (only accessible inside that function). + And txValue is the data to be sent, in this example just a byte incremented every second. +*/ +#include +#include +#include +#include + +BLEServer *pServer = NULL; +BLECharacteristic * pTxCharacteristic; +bool deviceConnected = false; +bool oldDeviceConnected = false; +uint8_t txValue = 0; + +// See the following for generating UUIDs: +// https://www.uuidgenerator.net/ + +#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID +#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" +#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" + + +class MyServerCallbacks: public BLEServerCallbacks { + void onConnect(BLEServer* pServer) { + deviceConnected = true; + }; + + void onDisconnect(BLEServer* pServer) { + deviceConnected = false; + } +}; + +class MyCallbacks: public BLECharacteristicCallbacks { + void onWrite(BLECharacteristic *pCharacteristic) { + std::string rxValue = pCharacteristic->getValue(); + + if (rxValue.length() > 0) { + Serial.println("*********"); + Serial.print("Received Value: "); + for (int i = 0; i < rxValue.length(); i++) + Serial.print(rxValue[i]); + + Serial.println(); + Serial.println("*********"); + } + } +}; + + +void setup() { + Serial.begin(115200); + + // Create the BLE Device + BLEDevice::init("UART Service"); + + // Create the BLE Server + pServer = BLEDevice::createServer(); + pServer->setCallbacks(new MyServerCallbacks()); + + // Create the BLE Service + BLEService *pService = pServer->createService(SERVICE_UUID); + + // Create a BLE Characteristic + pTxCharacteristic = pService->createCharacteristic( + CHARACTERISTIC_UUID_TX, + BLECharacteristic::PROPERTY_NOTIFY + ); + + pTxCharacteristic->addDescriptor(new BLE2902()); + + BLECharacteristic * pRxCharacteristic = pService->createCharacteristic( + CHARACTERISTIC_UUID_RX, + BLECharacteristic::PROPERTY_WRITE + ); + + pRxCharacteristic->setCallbacks(new MyCallbacks()); + + // Start the service + pService->start(); + + // Start advertising + pServer->getAdvertising()->start(); + Serial.println("Waiting a client connection to notify..."); +} + +void loop() { + + if (deviceConnected) { + pTxCharacteristic->setValue(&txValue, 1); + pTxCharacteristic->notify(); + txValue++; + delay(10); // bluetooth stack will go into congestion, if too many packets are sent + } + + // disconnecting + if (!deviceConnected && oldDeviceConnected) { + delay(500); // give the bluetooth stack the chance to get things ready + pServer->startAdvertising(); // restart advertising + Serial.println("start advertising"); + oldDeviceConnected = deviceConnected; + } + // connecting + if (deviceConnected && !oldDeviceConnected) { + // do stuff here on connecting + oldDeviceConnected = deviceConnected; + } +} diff --git a/libraries/BLE/examples/BLE_write/BLE_write.ino b/libraries/BLE/examples/BLE_write/BLE_write.ino new file mode 100644 index 00000000000..24a0cd23d7a --- /dev/null +++ b/libraries/BLE/examples/BLE_write/BLE_write.ino @@ -0,0 +1,65 @@ +/* + Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleWrite.cpp + Ported to Arduino ESP32 by Evandro Copercini +*/ + +#include +#include +#include + +// See the following for generating UUIDs: +// https://www.uuidgenerator.net/ + +#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" +#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" + + +class MyCallbacks: public BLECharacteristicCallbacks { + void onWrite(BLECharacteristic *pCharacteristic) { + std::string value = pCharacteristic->getValue(); + + if (value.length() > 0) { + Serial.println("*********"); + Serial.print("New value: "); + for (int i = 0; i < value.length(); i++) + Serial.print(value[i]); + + Serial.println(); + Serial.println("*********"); + } + } +}; + +void setup() { + Serial.begin(115200); + + Serial.println("1- Download and install an BLE scanner app in your phone"); + Serial.println("2- Scan for BLE devices in the app"); + Serial.println("3- Connect to MyESP32"); + Serial.println("4- Go to CUSTOM CHARACTERISTIC in CUSTOM SERVICE and write something"); + Serial.println("5- See the magic =)"); + + BLEDevice::init("MyESP32"); + BLEServer *pServer = BLEDevice::createServer(); + + BLEService *pService = pServer->createService(SERVICE_UUID); + + BLECharacteristic *pCharacteristic = pService->createCharacteristic( + CHARACTERISTIC_UUID, + BLECharacteristic::PROPERTY_READ | + BLECharacteristic::PROPERTY_WRITE + ); + + pCharacteristic->setCallbacks(new MyCallbacks()); + + pCharacteristic->setValue("Hello World"); + pService->start(); + + BLEAdvertising *pAdvertising = pServer->getAdvertising(); + pAdvertising->start(); +} + +void loop() { + // put your main code here, to run repeatedly: + delay(2000); +} \ No newline at end of file diff --git a/libraries/BLE/library.properties b/libraries/BLE/library.properties new file mode 100644 index 00000000000..8c2a019fe57 --- /dev/null +++ b/libraries/BLE/library.properties @@ -0,0 +1,10 @@ +name=ESP32 BLE Arduino +version=1.0.1 +author=Neil Kolban +maintainer=Dariusz Krempa +sentence=BLE functions for ESP32 +paragraph=This library provides an implementation Bluetooth Low Energy support for the ESP32 using the Arduino platform. +category=Communication +url=https://github.com/nkolban/ESP32_BLE_Arduino +architectures=esp32 +includes=BLEDevice.h, BLEUtils.h, BLEScan.h, BLEAdvertisedDevice.h diff --git a/libraries/BLE/src/BLE2902.cpp b/libraries/BLE/src/BLE2902.cpp new file mode 100644 index 00000000000..23d9c77c093 --- /dev/null +++ b/libraries/BLE/src/BLE2902.cpp @@ -0,0 +1,62 @@ +/* + * BLE2902.cpp + * + * Created on: Jun 25, 2017 + * Author: kolban + */ + +/* + * See also: + * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include "BLE2902.h" + +BLE2902::BLE2902() : BLEDescriptor(BLEUUID((uint16_t) 0x2902)) { + uint8_t data[2] = { 0, 0 }; + setValue(data, 2); +} // BLE2902 + + +/** + * @brief Get the notifications value. + * @return The notifications value. True if notifications are enabled and false if not. + */ +bool BLE2902::getNotifications() { + return (getValue()[0] & (1 << 0)) != 0; +} // getNotifications + + +/** + * @brief Get the indications value. + * @return The indications value. True if indications are enabled and false if not. + */ +bool BLE2902::getIndications() { + return (getValue()[0] & (1 << 1)) != 0; +} // getIndications + + +/** + * @brief Set the indications flag. + * @param [in] flag The indications flag. + */ +void BLE2902::setIndications(bool flag) { + uint8_t *pValue = getValue(); + if (flag) pValue[0] |= 1 << 1; + else pValue[0] &= ~(1 << 1); +} // setIndications + + +/** + * @brief Set the notifications flag. + * @param [in] flag The notifications flag. + */ +void BLE2902::setNotifications(bool flag) { + uint8_t *pValue = getValue(); + if (flag) pValue[0] |= 1 << 0; + else pValue[0] &= ~(1 << 0); +} // setNotifications + +#endif diff --git a/libraries/BLE/src/BLE2902.h b/libraries/BLE/src/BLE2902.h new file mode 100644 index 00000000000..397360ab128 --- /dev/null +++ b/libraries/BLE/src/BLE2902.h @@ -0,0 +1,34 @@ +/* + * BLE2902.h + * + * Created on: Jun 25, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLE2902_H_ +#define COMPONENTS_CPP_UTILS_BLE2902_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include "BLEDescriptor.h" + +/** + * @brief Descriptor for Client Characteristic Configuration. + * + * This is a convenience descriptor for the Client Characteristic Configuration which has a UUID of 0x2902. + * + * See also: + * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml + */ +class BLE2902: public BLEDescriptor { +public: + BLE2902(); + bool getNotifications(); + bool getIndications(); + void setNotifications(bool flag); + void setIndications(bool flag); + +}; // BLE2902 + +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLE2902_H_ */ diff --git a/libraries/BLE/src/BLE2904.cpp b/libraries/BLE/src/BLE2904.cpp new file mode 100644 index 00000000000..02252a1d676 --- /dev/null +++ b/libraries/BLE/src/BLE2904.cpp @@ -0,0 +1,74 @@ +/* + * BLE2904.cpp + * + * Created on: Dec 23, 2017 + * Author: kolban + */ + +/* + * See also: + * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include "BLE2904.h" + + +BLE2904::BLE2904() : BLEDescriptor(BLEUUID((uint16_t) 0x2904)) { + m_data.m_format = 0; + m_data.m_exponent = 0; + m_data.m_namespace = 1; // 1 = Bluetooth SIG Assigned Numbers + m_data.m_unit = 0; + m_data.m_description = 0; + setValue((uint8_t*) &m_data, sizeof(m_data)); +} // BLE2902 + + +/** + * @brief Set the description. + */ +void BLE2904::setDescription(uint16_t description) { + m_data.m_description = description; + setValue((uint8_t*) &m_data, sizeof(m_data)); +} + + +/** + * @brief Set the exponent. + */ +void BLE2904::setExponent(int8_t exponent) { + m_data.m_exponent = exponent; + setValue((uint8_t*) &m_data, sizeof(m_data)); +} // setExponent + + +/** + * @brief Set the format. + */ +void BLE2904::setFormat(uint8_t format) { + m_data.m_format = format; + setValue((uint8_t*) &m_data, sizeof(m_data)); +} // setFormat + + +/** + * @brief Set the namespace. + */ +void BLE2904::setNamespace(uint8_t namespace_value) { + m_data.m_namespace = namespace_value; + setValue((uint8_t*) &m_data, sizeof(m_data)); +} // setNamespace + + +/** + * @brief Set the units for this value. It should be one of the encoded values defined here: + * https://www.bluetooth.com/specifications/assigned-numbers/units + * @param [in] unit The type of units of this characteristic as defined by assigned numbers. + */ +void BLE2904::setUnit(uint16_t unit) { + m_data.m_unit = unit; + setValue((uint8_t*) &m_data, sizeof(m_data)); +} // setUnit + +#endif diff --git a/libraries/BLE/src/BLE2904.h b/libraries/BLE/src/BLE2904.h new file mode 100644 index 00000000000..cb337e22bed --- /dev/null +++ b/libraries/BLE/src/BLE2904.h @@ -0,0 +1,74 @@ +/* + * BLE2904.h + * + * Created on: Dec 23, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLE2904_H_ +#define COMPONENTS_CPP_UTILS_BLE2904_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include "BLEDescriptor.h" + +struct BLE2904_Data { + uint8_t m_format; + int8_t m_exponent; + uint16_t m_unit; // See https://www.bluetooth.com/specifications/assigned-numbers/units + uint8_t m_namespace; + uint16_t m_description; + +} __attribute__((packed)); + +/** + * @brief Descriptor for Characteristic Presentation Format. + * + * This is a convenience descriptor for the Characteristic Presentation Format which has a UUID of 0x2904. + * + * See also: + * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml + */ +class BLE2904: public BLEDescriptor { +public: + BLE2904(); + static const uint8_t FORMAT_BOOLEAN = 1; + static const uint8_t FORMAT_UINT2 = 2; + static const uint8_t FORMAT_UINT4 = 3; + static const uint8_t FORMAT_UINT8 = 4; + static const uint8_t FORMAT_UINT12 = 5; + static const uint8_t FORMAT_UINT16 = 6; + static const uint8_t FORMAT_UINT24 = 7; + static const uint8_t FORMAT_UINT32 = 8; + static const uint8_t FORMAT_UINT48 = 9; + static const uint8_t FORMAT_UINT64 = 10; + static const uint8_t FORMAT_UINT128 = 11; + static const uint8_t FORMAT_SINT8 = 12; + static const uint8_t FORMAT_SINT12 = 13; + static const uint8_t FORMAT_SINT16 = 14; + static const uint8_t FORMAT_SINT24 = 15; + static const uint8_t FORMAT_SINT32 = 16; + static const uint8_t FORMAT_SINT48 = 17; + static const uint8_t FORMAT_SINT64 = 18; + static const uint8_t FORMAT_SINT128 = 19; + static const uint8_t FORMAT_FLOAT32 = 20; + static const uint8_t FORMAT_FLOAT64 = 21; + static const uint8_t FORMAT_SFLOAT16 = 22; + static const uint8_t FORMAT_SFLOAT32 = 23; + static const uint8_t FORMAT_IEEE20601 = 24; + static const uint8_t FORMAT_UTF8 = 25; + static const uint8_t FORMAT_UTF16 = 26; + static const uint8_t FORMAT_OPAQUE = 27; + + void setDescription(uint16_t); + void setExponent(int8_t exponent); + void setFormat(uint8_t format); + void setNamespace(uint8_t namespace_value); + void setUnit(uint16_t unit); + +private: + BLE2904_Data m_data; +}; // BLE2904 + +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLE2904_H_ */ diff --git a/libraries/BLE/src/BLEAddress.cpp b/libraries/BLE/src/BLEAddress.cpp new file mode 100644 index 00000000000..6d83b17e68e --- /dev/null +++ b/libraries/BLE/src/BLEAddress.cpp @@ -0,0 +1,94 @@ +/* + * BLEAddress.cpp + * + * Created on: Jul 2, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include "BLEAddress.h" +#include +#include +#include +#include +#include +#include +#ifdef ARDUINO_ARCH_ESP32 +#include "esp32-hal-log.h" +#endif + + +/** + * @brief Create an address from the native ESP32 representation. + * @param [in] address The native representation. + */ +BLEAddress::BLEAddress(esp_bd_addr_t address) { + memcpy(m_address, address, ESP_BD_ADDR_LEN); +} // BLEAddress + + +/** + * @brief Create an address from a hex string + * + * A hex string is of the format: + * ``` + * 00:00:00:00:00:00 + * ``` + * which is 17 characters in length. + * + * @param [in] stringAddress The hex representation of the address. + */ +BLEAddress::BLEAddress(std::string stringAddress) { + if (stringAddress.length() != 17) return; + + int data[6]; + sscanf(stringAddress.c_str(), "%x:%x:%x:%x:%x:%x", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5]); + m_address[0] = (uint8_t) data[0]; + m_address[1] = (uint8_t) data[1]; + m_address[2] = (uint8_t) data[2]; + m_address[3] = (uint8_t) data[3]; + m_address[4] = (uint8_t) data[4]; + m_address[5] = (uint8_t) data[5]; +} // BLEAddress + + +/** + * @brief Determine if this address equals another. + * @param [in] otherAddress The other address to compare against. + * @return True if the addresses are equal. + */ +bool BLEAddress::equals(BLEAddress otherAddress) { + return memcmp(otherAddress.getNative(), m_address, 6) == 0; +} // equals + + +/** + * @brief Return the native representation of the address. + * @return The native representation of the address. + */ +esp_bd_addr_t *BLEAddress::getNative() { + return &m_address; +} // getNative + + +/** + * @brief Convert a BLE address to a string. + * + * A string representation of an address is in the format: + * + * ``` + * xx:xx:xx:xx:xx:xx + * ``` + * + * @return The string representation of the address. + */ +std::string BLEAddress::toString() { + auto size = 18; + char *res = (char*)malloc(size); + snprintf(res, size, "%02x:%02x:%02x:%02x:%02x:%02x", m_address[0], m_address[1], m_address[2], m_address[3], m_address[4], m_address[5]); + std::string ret(res); + free(res); + return ret; +} // toString +#endif diff --git a/libraries/BLE/src/BLEAddress.h b/libraries/BLE/src/BLEAddress.h new file mode 100644 index 00000000000..7eff4da4bb6 --- /dev/null +++ b/libraries/BLE/src/BLEAddress.h @@ -0,0 +1,34 @@ +/* + * BLEAddress.h + * + * Created on: Jul 2, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEADDRESS_H_ +#define COMPONENTS_CPP_UTILS_BLEADDRESS_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include // ESP32 BLE +#include + + +/** + * @brief A %BLE device address. + * + * Every %BLE device has a unique address which can be used to identify it and form connections. + */ +class BLEAddress { +public: + BLEAddress(esp_bd_addr_t address); + BLEAddress(std::string stringAddress); + bool equals(BLEAddress otherAddress); + esp_bd_addr_t* getNative(); + std::string toString(); + +private: + esp_bd_addr_t m_address; +}; + +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLEADDRESS_H_ */ diff --git a/libraries/BLE/src/BLEAdvertisedDevice.cpp b/libraries/BLE/src/BLEAdvertisedDevice.cpp new file mode 100644 index 00000000000..1c341cf2412 --- /dev/null +++ b/libraries/BLE/src/BLEAdvertisedDevice.cpp @@ -0,0 +1,529 @@ +/* + * BLEAdvertisedDevice.cpp + * + * During the scanning procedure, we will be finding advertised BLE devices. This class + * models a found device. + * + * + * See also: + * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile + * + * Created on: Jul 3, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include "BLEAdvertisedDevice.h" +#include "BLEUtils.h" +#include "esp32-hal-log.h" + +BLEAdvertisedDevice::BLEAdvertisedDevice() { + m_adFlag = 0; + m_appearance = 0; + m_deviceType = 0; + m_manufacturerData = ""; + m_name = ""; + m_rssi = -9999; + m_serviceData = ""; + m_txPower = 0; + m_pScan = nullptr; + + m_haveAppearance = false; + m_haveManufacturerData = false; + m_haveName = false; + m_haveRSSI = false; + m_haveServiceData = false; + m_haveServiceUUID = false; + m_haveTXPower = false; + +} // BLEAdvertisedDevice + + +/** + * @brief Get the address. + * + * Every %BLE device exposes an address that is used to identify it and subsequently connect to it. + * Call this function to obtain the address of the advertised device. + * + * @return The address of the advertised device. + */ +BLEAddress BLEAdvertisedDevice::getAddress() { + return m_address; +} // getAddress + + +/** + * @brief Get the appearance. + * + * A %BLE device can declare its own appearance. The appearance is how it would like to be shown to an end user + * typcially in the form of an icon. + * + * @return The appearance of the advertised device. + */ +uint16_t BLEAdvertisedDevice::getAppearance() { + return m_appearance; +} // getAppearance + + +/** + * @brief Get the manufacturer data. + * @return The manufacturer data of the advertised device. + */ +std::string BLEAdvertisedDevice::getManufacturerData() { + return m_manufacturerData; +} // getManufacturerData + + +/** + * @brief Get the name. + * @return The name of the advertised device. + */ +std::string BLEAdvertisedDevice::getName() { + return m_name; +} // getName + + +/** + * @brief Get the RSSI. + * @return The RSSI of the advertised device. + */ +int BLEAdvertisedDevice::getRSSI() { + return m_rssi; +} // getRSSI + + +/** + * @brief Get the scan object that created this advertisement. + * @return The scan object. + */ +BLEScan* BLEAdvertisedDevice::getScan() { + return m_pScan; +} // getScan + + +/** + * @brief Get the service data. + * @return The ServiceData of the advertised device. + */ +std::string BLEAdvertisedDevice::getServiceData() { + return m_serviceData; +} //getServiceData + + +/** + * @brief Get the service data UUID. + * @return The service data UUID. + */ +BLEUUID BLEAdvertisedDevice::getServiceDataUUID() { + return m_serviceDataUUID; +} // getServiceDataUUID + + +/** + * @brief Get the Service UUID. + * @return The Service UUID of the advertised device. + */ +BLEUUID BLEAdvertisedDevice::getServiceUUID() { //TODO Remove it eventually, is no longer useful + return m_serviceUUIDs[0]; +} // getServiceUUID + +/** + * @brief Check advertised serviced for existence required UUID + * @return Return true if service is advertised + */ +bool BLEAdvertisedDevice::isAdvertisingService(BLEUUID uuid){ + for (int i = 0; i < m_serviceUUIDs.size(); i++) { + if (m_serviceUUIDs[i].equals(uuid)) return true; + } + return false; +} + +/** + * @brief Get the TX Power. + * @return The TX Power of the advertised device. + */ +int8_t BLEAdvertisedDevice::getTXPower() { + return m_txPower; +} // getTXPower + + + +/** + * @brief Does this advertisement have an appearance value? + * @return True if there is an appearance value present. + */ +bool BLEAdvertisedDevice::haveAppearance() { + return m_haveAppearance; +} // haveAppearance + + +/** + * @brief Does this advertisement have manufacturer data? + * @return True if there is manufacturer data present. + */ +bool BLEAdvertisedDevice::haveManufacturerData() { + return m_haveManufacturerData; +} // haveManufacturerData + + +/** + * @brief Does this advertisement have a name value? + * @return True if there is a name value present. + */ +bool BLEAdvertisedDevice::haveName() { + return m_haveName; +} // haveName + + +/** + * @brief Does this advertisement have a signal strength value? + * @return True if there is a signal strength value present. + */ +bool BLEAdvertisedDevice::haveRSSI() { + return m_haveRSSI; +} // haveRSSI + + +/** + * @brief Does this advertisement have a service data value? + * @return True if there is a service data value present. + */ +bool BLEAdvertisedDevice::haveServiceData() { + return m_haveServiceData; +} // haveServiceData + + +/** + * @brief Does this advertisement have a service UUID value? + * @return True if there is a service UUID value present. + */ +bool BLEAdvertisedDevice::haveServiceUUID() { + return m_haveServiceUUID; +} // haveServiceUUID + + +/** + * @brief Does this advertisement have a transmission power value? + * @return True if there is a transmission power value present. + */ +bool BLEAdvertisedDevice::haveTXPower() { + return m_haveTXPower; +} // haveTXPower + + +/** + * @brief Parse the advertising pay load. + * + * The pay load is a buffer of bytes that is either 31 bytes long or terminated by + * a 0 length value. Each entry in the buffer has the format: + * [length][type][data...] + * + * The length does not include itself but does include everything after it until the next record. A record + * with a length value of 0 indicates a terminator. + * + * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile + */ +void BLEAdvertisedDevice::parseAdvertisement(uint8_t* payload, size_t total_len) { + uint8_t length; + uint8_t ad_type; + uint8_t sizeConsumed = 0; + bool finished = false; + m_payload = payload; + m_payloadLength = total_len; + + while(!finished) { + length = *payload; // Retrieve the length of the record. + payload++; // Skip to type + sizeConsumed += 1 + length; // increase the size consumed. + + if (length != 0) { // A length of 0 indicates that we have reached the end. + ad_type = *payload; + payload++; + length--; + + char* pHex = BLEUtils::buildHexData(nullptr, payload, length); + log_d("Type: 0x%.2x (%s), length: %d, data: %s", + ad_type, BLEUtils::advTypeToString(ad_type), length, pHex); + free(pHex); + + switch(ad_type) { + case ESP_BLE_AD_TYPE_NAME_CMPL: { // Adv Data Type: 0x09 + setName(std::string(reinterpret_cast(payload), length)); + break; + } // ESP_BLE_AD_TYPE_NAME_CMPL + + case ESP_BLE_AD_TYPE_TX_PWR: { // Adv Data Type: 0x0A + setTXPower(*payload); + break; + } // ESP_BLE_AD_TYPE_TX_PWR + + case ESP_BLE_AD_TYPE_APPEARANCE: { // Adv Data Type: 0x19 + setAppearance(*reinterpret_cast(payload)); + break; + } // ESP_BLE_AD_TYPE_APPEARANCE + + case ESP_BLE_AD_TYPE_FLAG: { // Adv Data Type: 0x01 + setAdFlag(*payload); + break; + } // ESP_BLE_AD_TYPE_FLAG + + case ESP_BLE_AD_TYPE_16SRV_CMPL: + case ESP_BLE_AD_TYPE_16SRV_PART: { // Adv Data Type: 0x02 + for (int var = 0; var < length/2; ++var) { + setServiceUUID(BLEUUID(*reinterpret_cast(payload + var * 2))); + } + break; + } // ESP_BLE_AD_TYPE_16SRV_PART + + case ESP_BLE_AD_TYPE_32SRV_CMPL: + case ESP_BLE_AD_TYPE_32SRV_PART: { // Adv Data Type: 0x04 + for (int var = 0; var < length/4; ++var) { + setServiceUUID(BLEUUID(*reinterpret_cast(payload + var * 4))); + } + break; + } // ESP_BLE_AD_TYPE_32SRV_PART + + case ESP_BLE_AD_TYPE_128SRV_CMPL: { // Adv Data Type: 0x07 + setServiceUUID(BLEUUID(payload, 16, false)); + break; + } // ESP_BLE_AD_TYPE_128SRV_CMPL + + case ESP_BLE_AD_TYPE_128SRV_PART: { // Adv Data Type: 0x06 + setServiceUUID(BLEUUID(payload, 16, false)); + break; + } // ESP_BLE_AD_TYPE_128SRV_PART + + // See CSS Part A 1.4 Manufacturer Specific Data + case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: { + setManufacturerData(std::string(reinterpret_cast(payload), length)); + break; + } // ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE + + case ESP_BLE_AD_TYPE_SERVICE_DATA: { // Adv Data Type: 0x16 (Service Data) - 2 byte UUID + if (length < 2) { + log_e("Length too small for ESP_BLE_AD_TYPE_SERVICE_DATA"); + break; + } + uint16_t uuid = *(uint16_t*)payload; + setServiceDataUUID(BLEUUID(uuid)); + if (length > 2) { + setServiceData(std::string(reinterpret_cast(payload + 2), length - 2)); + } + break; + } //ESP_BLE_AD_TYPE_SERVICE_DATA + + case ESP_BLE_AD_TYPE_32SERVICE_DATA: { // Adv Data Type: 0x20 (Service Data) - 4 byte UUID + if (length < 4) { + log_e("Length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA"); + break; + } + uint32_t uuid = *(uint32_t*) payload; + setServiceDataUUID(BLEUUID(uuid)); + if (length > 4) { + setServiceData(std::string(reinterpret_cast(payload + 4), length - 4)); + } + break; + } //ESP_BLE_AD_TYPE_32SERVICE_DATA + + case ESP_BLE_AD_TYPE_128SERVICE_DATA: { // Adv Data Type: 0x21 (Service Data) - 16 byte UUID + if (length < 16) { + log_e("Length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA"); + break; + } + + setServiceDataUUID(BLEUUID(payload, (size_t)16, false)); + if (length > 16) { + setServiceData(std::string(reinterpret_cast(payload + 16), length - 16)); + } + break; + } //ESP_BLE_AD_TYPE_32SERVICE_DATA + + default: { + log_d("Unhandled type: adType: %d - 0x%.2x", ad_type, ad_type); + break; + } + } // switch + payload += length; + } // Length <> 0 + + + if (sizeConsumed >= total_len) + finished = true; + + } // !finished +} // parseAdvertisement + + +/** + * @brief Set the address of the advertised device. + * @param [in] address The address of the advertised device. + */ +void BLEAdvertisedDevice::setAddress(BLEAddress address) { + m_address = address; +} // setAddress + + +/** + * @brief Set the adFlag for this device. + * @param [in] The discovered adFlag. + */ +void BLEAdvertisedDevice::setAdFlag(uint8_t adFlag) { + m_adFlag = adFlag; +} // setAdFlag + + +/** + * @brief Set the appearance for this device. + * @param [in] The discovered appearance. + */ +void BLEAdvertisedDevice::setAppearance(uint16_t appearance) { + m_appearance = appearance; + m_haveAppearance = true; + log_d("- appearance: %d", m_appearance); +} // setAppearance + + +/** + * @brief Set the manufacturer data for this device. + * @param [in] The discovered manufacturer data. + */ +void BLEAdvertisedDevice::setManufacturerData(std::string manufacturerData) { + m_manufacturerData = manufacturerData; + m_haveManufacturerData = true; + char* pHex = BLEUtils::buildHexData(nullptr, (uint8_t*) m_manufacturerData.data(), (uint8_t) m_manufacturerData.length()); + log_d("- manufacturer data: %s", pHex); + free(pHex); +} // setManufacturerData + + +/** + * @brief Set the name for this device. + * @param [in] name The discovered name. + */ +void BLEAdvertisedDevice::setName(std::string name) { + m_name = name; + m_haveName = true; + log_d("- setName(): name: %s", m_name.c_str()); +} // setName + + +/** + * @brief Set the RSSI for this device. + * @param [in] rssi The discovered RSSI. + */ +void BLEAdvertisedDevice::setRSSI(int rssi) { + m_rssi = rssi; + m_haveRSSI = true; + log_d("- setRSSI(): rssi: %d", m_rssi); +} // setRSSI + + +/** + * @brief Set the Scan that created this advertised device. + * @param pScan The Scan that created this advertised device. + */ +void BLEAdvertisedDevice::setScan(BLEScan* pScan) { + m_pScan = pScan; +} // setScan + + +/** + * @brief Set the Service UUID for this device. + * @param [in] serviceUUID The discovered serviceUUID + */ +void BLEAdvertisedDevice::setServiceUUID(const char* serviceUUID) { + return setServiceUUID(BLEUUID(serviceUUID)); +} // setServiceUUID + + +/** + * @brief Set the Service UUID for this device. + * @param [in] serviceUUID The discovered serviceUUID + */ +void BLEAdvertisedDevice::setServiceUUID(BLEUUID serviceUUID) { + m_serviceUUIDs.push_back(serviceUUID); + m_haveServiceUUID = true; + log_d("- addServiceUUID(): serviceUUID: %s", serviceUUID.toString().c_str()); +} // setServiceUUID + + +/** + * @brief Set the ServiceData value. + * @param [in] data ServiceData value. + */ +void BLEAdvertisedDevice::setServiceData(std::string serviceData) { + m_haveServiceData = true; // Set the flag that indicates we have service data. + m_serviceData = serviceData; // Save the service data that we received. +} //setServiceData + + +/** + * @brief Set the ServiceDataUUID value. + * @param [in] data ServiceDataUUID value. + */ +void BLEAdvertisedDevice::setServiceDataUUID(BLEUUID uuid) { + m_haveServiceData = true; // Set the flag that indicates we have service data. + m_serviceDataUUID = uuid; +} // setServiceDataUUID + + +/** + * @brief Set the power level for this device. + * @param [in] txPower The discovered power level. + */ +void BLEAdvertisedDevice::setTXPower(int8_t txPower) { + m_txPower = txPower; + m_haveTXPower = true; + log_d("- txPower: %d", m_txPower); +} // setTXPower + + +/** + * @brief Create a string representation of this device. + * @return A string representation of this device. + */ +std::string BLEAdvertisedDevice::toString() { + std::string res = "Name: " + getName() + ", Address: " + getAddress().toString(); + if (haveAppearance()) { + char val[6]; + snprintf(val, sizeof(val), "%d", getAppearance()); + res += ", appearance: "; + res += val; + } + if (haveManufacturerData()) { + char *pHex = BLEUtils::buildHexData(nullptr, (uint8_t*)getManufacturerData().data(), getManufacturerData().length()); + res += ", manufacturer data: "; + res += pHex; + free(pHex); + } + if (haveServiceUUID()) { + res += ", serviceUUID: " + getServiceUUID().toString(); + } + if (haveTXPower()) { + char val[4]; + snprintf(val, sizeof(val), "%d", getTXPower()); + res += ", txPower: "; + res += val; + } + return res; +} // toString + +uint8_t* BLEAdvertisedDevice::getPayload() { + return m_payload; +} + +esp_ble_addr_type_t BLEAdvertisedDevice::getAddressType() { + return m_addressType; +} + +void BLEAdvertisedDevice::setAddressType(esp_ble_addr_type_t type) { + m_addressType = type; +} + +size_t BLEAdvertisedDevice::getPayloadLength() { + return m_payloadLength; +} + +#endif /* CONFIG_BT_ENABLED */ + diff --git a/libraries/BLE/src/BLEAdvertisedDevice.h b/libraries/BLE/src/BLEAdvertisedDevice.h new file mode 100644 index 00000000000..aec83746ed8 --- /dev/null +++ b/libraries/BLE/src/BLEAdvertisedDevice.h @@ -0,0 +1,123 @@ +/* + * BLEAdvertisedDevice.h + * + * Created on: Jul 3, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ +#define COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include + +#include + +#include "BLEAddress.h" +#include "BLEScan.h" +#include "BLEUUID.h" + + +class BLEScan; +/** + * @brief A representation of a %BLE advertised device found by a scan. + * + * When we perform a %BLE scan, the result will be a set of devices that are advertising. This + * class provides a model of a detected device. + */ +class BLEAdvertisedDevice { +public: + BLEAdvertisedDevice(); + + BLEAddress getAddress(); + uint16_t getAppearance(); + std::string getManufacturerData(); + std::string getName(); + int getRSSI(); + BLEScan* getScan(); + std::string getServiceData(); + BLEUUID getServiceDataUUID(); + BLEUUID getServiceUUID(); + int8_t getTXPower(); + uint8_t* getPayload(); + size_t getPayloadLength(); + esp_ble_addr_type_t getAddressType(); + void setAddressType(esp_ble_addr_type_t type); + + + bool isAdvertisingService(BLEUUID uuid); + bool haveAppearance(); + bool haveManufacturerData(); + bool haveName(); + bool haveRSSI(); + bool haveServiceData(); + bool haveServiceUUID(); + bool haveTXPower(); + + std::string toString(); + +private: + friend class BLEScan; + + void parseAdvertisement(uint8_t* payload, size_t total_len=62); + void setAddress(BLEAddress address); + void setAdFlag(uint8_t adFlag); + void setAdvertizementResult(uint8_t* payload); + void setAppearance(uint16_t appearance); + void setManufacturerData(std::string manufacturerData); + void setName(std::string name); + void setRSSI(int rssi); + void setScan(BLEScan* pScan); + void setServiceData(std::string data); + void setServiceDataUUID(BLEUUID uuid); + void setServiceUUID(const char* serviceUUID); + void setServiceUUID(BLEUUID serviceUUID); + void setTXPower(int8_t txPower); + + bool m_haveAppearance; + bool m_haveManufacturerData; + bool m_haveName; + bool m_haveRSSI; + bool m_haveServiceData; + bool m_haveServiceUUID; + bool m_haveTXPower; + + + BLEAddress m_address = BLEAddress((uint8_t*)"\0\0\0\0\0\0"); + uint8_t m_adFlag; + uint16_t m_appearance; + int m_deviceType; + std::string m_manufacturerData; + std::string m_name; + BLEScan* m_pScan; + int m_rssi; + std::vector m_serviceUUIDs; + int8_t m_txPower; + std::string m_serviceData; + BLEUUID m_serviceDataUUID; + uint8_t* m_payload; + size_t m_payloadLength = 0; + esp_ble_addr_type_t m_addressType; +}; + +/** + * @brief A callback handler for callbacks associated device scanning. + * + * When we are performing a scan as a %BLE client, we may wish to know when a new device that is advertising + * has been found. This class can be sub-classed and registered such that when a scan is performed and + * a new advertised device has been found, we will be called back to be notified. + */ +class BLEAdvertisedDeviceCallbacks { +public: + virtual ~BLEAdvertisedDeviceCallbacks() {} + /** + * @brief Called when a new scan result is detected. + * + * As we are scanning, we will find new devices. When found, this call back is invoked with a reference to the + * device that was found. During any individual scan, a device will only be detected one time. + */ + virtual void onResult(BLEAdvertisedDevice advertisedDevice) = 0; +}; + +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ */ diff --git a/libraries/BLE/src/BLEAdvertising.cpp b/libraries/BLE/src/BLEAdvertising.cpp new file mode 100644 index 00000000000..ec73400c6d8 --- /dev/null +++ b/libraries/BLE/src/BLEAdvertising.cpp @@ -0,0 +1,517 @@ +/* + * BLEAdvertising.cpp + * + * This class encapsulates advertising a BLE Server. + * Created on: Jun 21, 2017 + * Author: kolban + * + * The ESP-IDF provides a framework for BLE advertising. It has determined that there are a common set + * of properties that are advertised and has built a data structure that can be populated by the programmer. + * This means that the programmer doesn't have to "mess with" the low level construction of a low level + * BLE advertising frame. Many of the fields are determined for us while others we can set before starting + * to advertise. + * + * Should we wish to construct our own payload, we can use the BLEAdvertisementData class and call the setters + * upon it. Once it is populated, we can then associate it with the advertising and what ever the programmer + * set in the data will be advertised. + * + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include "BLEAdvertising.h" +#include +#include "BLEUtils.h" +#include "GeneralUtils.h" +#include "esp32-hal-log.h" + +/** + * @brief Construct a default advertising object. + * + */ +BLEAdvertising::BLEAdvertising() { + m_advData.set_scan_rsp = false; + m_advData.include_name = true; + m_advData.include_txpower = true; + m_advData.min_interval = 0x20; + m_advData.max_interval = 0x40; + m_advData.appearance = 0x00; + m_advData.manufacturer_len = 0; + m_advData.p_manufacturer_data = nullptr; + m_advData.service_data_len = 0; + m_advData.p_service_data = nullptr; + m_advData.service_uuid_len = 0; + m_advData.p_service_uuid = nullptr; + m_advData.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT); + + m_advParams.adv_int_min = 0x20; + m_advParams.adv_int_max = 0x40; + m_advParams.adv_type = ADV_TYPE_IND; + m_advParams.own_addr_type = BLE_ADDR_TYPE_PUBLIC; + m_advParams.channel_map = ADV_CHNL_ALL; + m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; + m_advParams.peer_addr_type = BLE_ADDR_TYPE_PUBLIC; + + m_customAdvData = false; // No custom advertising data + m_customScanResponseData = false; // No custom scan response data +} // BLEAdvertising + + +/** + * @brief Add a service uuid to exposed list of services. + * @param [in] serviceUUID The UUID of the service to expose. + */ +void BLEAdvertising::addServiceUUID(BLEUUID serviceUUID) { + m_serviceUUIDs.push_back(serviceUUID); +} // addServiceUUID + + +/** + * @brief Add a service uuid to exposed list of services. + * @param [in] serviceUUID The string representation of the service to expose. + */ +void BLEAdvertising::addServiceUUID(const char* serviceUUID) { + addServiceUUID(BLEUUID(serviceUUID)); +} // addServiceUUID + + +/** + * @brief Set the device appearance in the advertising data. + * The appearance attribute is of type 0x19. The codes for distinct appearances can be found here: + * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml. + * @param [in] appearance The appearance of the device in the advertising data. + * @return N/A. + */ +void BLEAdvertising::setAppearance(uint16_t appearance) { + m_advData.appearance = appearance; +} // setAppearance + +void BLEAdvertising::setMinInterval(uint16_t mininterval) { + m_advParams.adv_int_min = mininterval; +} // setMinInterval + +void BLEAdvertising::setMaxInterval(uint16_t maxinterval) { + m_advParams.adv_int_max = maxinterval; +} // setMaxInterval + +void BLEAdvertising::setMinPreferred(uint16_t mininterval) { + m_advData.min_interval = mininterval; +} // + +void BLEAdvertising::setMaxPreferred(uint16_t maxinterval) { + m_advData.max_interval = maxinterval; +} // + +void BLEAdvertising::setScanResponse(bool set) { + m_scanResp = set; +} + +/** + * @brief Set the filtering for the scan filter. + * @param [in] scanRequestWhitelistOnly If true, only allow scan requests from those on the white list. + * @param [in] connectWhitelistOnly If true, only allow connections from those on the white list. + */ +void BLEAdvertising::setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly) { + log_v(">> setScanFilter: scanRequestWhitelistOnly: %d, connectWhitelistOnly: %d", scanRequestWhitelistOnly, connectWhitelistOnly); + if (!scanRequestWhitelistOnly && !connectWhitelistOnly) { + m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; + log_v("<< setScanFilter"); + return; + } + if (scanRequestWhitelistOnly && !connectWhitelistOnly) { + m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY; + log_v("<< setScanFilter"); + return; + } + if (!scanRequestWhitelistOnly && connectWhitelistOnly) { + m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST; + log_v("<< setScanFilter"); + return; + } + if (scanRequestWhitelistOnly && connectWhitelistOnly) { + m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST; + log_v("<< setScanFilter"); + return; + } +} // setScanFilter + + +/** + * @brief Set the advertisement data that is to be published in a regular advertisement. + * @param [in] advertisementData The data to be advertised. + */ +void BLEAdvertising::setAdvertisementData(BLEAdvertisementData& advertisementData) { + log_v(">> setAdvertisementData"); + esp_err_t errRc = ::esp_ble_gap_config_adv_data_raw( + (uint8_t*)advertisementData.getPayload().data(), + advertisementData.getPayload().length()); + if (errRc != ESP_OK) { + log_e("esp_ble_gap_config_adv_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); + } + m_customAdvData = true; // Set the flag that indicates we are using custom advertising data. + log_v("<< setAdvertisementData"); +} // setAdvertisementData + + +/** + * @brief Set the advertisement data that is to be published in a scan response. + * @param [in] advertisementData The data to be advertised. + */ +void BLEAdvertising::setScanResponseData(BLEAdvertisementData& advertisementData) { + log_v(">> setScanResponseData"); + esp_err_t errRc = ::esp_ble_gap_config_scan_rsp_data_raw( + (uint8_t*)advertisementData.getPayload().data(), + advertisementData.getPayload().length()); + if (errRc != ESP_OK) { + log_e("esp_ble_gap_config_scan_rsp_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); + } + m_customScanResponseData = true; // Set the flag that indicates we are using custom scan response data. + log_v("<< setScanResponseData"); +} // setScanResponseData + +/** + * @brief Start advertising. + * Start advertising. + * @return N/A. + */ +void BLEAdvertising::start() { + log_v(">> start: customAdvData: %d, customScanResponseData: %d", m_customAdvData, m_customScanResponseData); + + // We have a vector of service UUIDs that we wish to advertise. In order to use the + // ESP-IDF framework, these must be supplied in a contiguous array of their 128bit (16 byte) + // representations. If we have 1 or more services to advertise then we allocate enough + // storage to host them and then copy them in one at a time into the contiguous storage. + int numServices = m_serviceUUIDs.size(); + if (numServices > 0) { + m_advData.service_uuid_len = 16 * numServices; + m_advData.p_service_uuid = new uint8_t[m_advData.service_uuid_len]; + uint8_t* p = m_advData.p_service_uuid; + for (int i = 0; i < numServices; i++) { + log_d("- advertising service: %s", m_serviceUUIDs[i].toString().c_str()); + BLEUUID serviceUUID128 = m_serviceUUIDs[i].to128(); + memcpy(p, serviceUUID128.getNative()->uuid.uuid128, 16); + p += 16; + } + } else { + m_advData.service_uuid_len = 0; + log_d("- no services advertised"); + } + + esp_err_t errRc; + + if (!m_customAdvData) { + // Set the configuration for advertising. + m_advData.set_scan_rsp = false; + m_advData.include_name = !m_scanResp; + m_advData.include_txpower = !m_scanResp; + errRc = ::esp_ble_gap_config_adv_data(&m_advData); + if (errRc != ESP_OK) { + log_e("<< esp_ble_gap_config_adv_data: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + } + + if (!m_customScanResponseData && m_scanResp) { + m_advData.set_scan_rsp = true; + m_advData.include_name = m_scanResp; + m_advData.include_txpower = m_scanResp; + errRc = ::esp_ble_gap_config_adv_data(&m_advData); + if (errRc != ESP_OK) { + log_e("<< esp_ble_gap_config_adv_data (Scan response): rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + } + + // If we had services to advertise then we previously allocated some storage for them. + // Here we release that storage. + if (m_advData.service_uuid_len > 0) { + delete[] m_advData.p_service_uuid; + m_advData.p_service_uuid = nullptr; + } + + // Start advertising. + errRc = ::esp_ble_gap_start_advertising(&m_advParams); + if (errRc != ESP_OK) { + log_e("<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + log_v("<< start"); +} // start + + +/** + * @brief Stop advertising. + * Stop advertising. + * @return N/A. + */ +void BLEAdvertising::stop() { + log_v(">> stop"); + esp_err_t errRc = ::esp_ble_gap_stop_advertising(); + if (errRc != ESP_OK) { + log_e("esp_ble_gap_stop_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + log_v("<< stop"); +} // stop + +/** + * @brief Set BLE address. + * @param [in] Bluetooth address. + * @param [in] Bluetooth address type. + * Set BLE address. + */ + +void BLEAdvertising::setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type) +{ + log_v(">> setPrivateAddress"); + + m_advParams.own_addr_type = type; + esp_err_t errRc = esp_ble_gap_set_rand_addr((uint8_t*)addr); + if (errRc != ESP_OK) + { + log_e("esp_ble_gap_set_rand_addr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + log_v("<< setPrivateAddress"); +} // setPrivateAddress + +/** + * @brief Add data to the payload to be advertised. + * @param [in] data The data to be added to the payload. + */ +void BLEAdvertisementData::addData(std::string data) { + if ((m_payload.length() + data.length()) > ESP_BLE_ADV_DATA_LEN_MAX) { + return; + } + m_payload.append(data); +} // addData + + +/** + * @brief Set the appearance. + * @param [in] appearance The appearance code value. + * + * See also: + * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml + */ +void BLEAdvertisementData::setAppearance(uint16_t appearance) { + char cdata[2]; + cdata[0] = 3; + cdata[1] = ESP_BLE_AD_TYPE_APPEARANCE; // 0x19 + addData(std::string(cdata, 2) + std::string((char*) &appearance, 2)); +} // setAppearance + + +/** + * @brief Set the complete services. + * @param [in] uuid The single service to advertise. + */ +void BLEAdvertisementData::setCompleteServices(BLEUUID uuid) { + char cdata[2]; + switch (uuid.bitSize()) { + case 16: { + // [Len] [0x02] [LL] [HH] + cdata[0] = 3; + cdata[1] = ESP_BLE_AD_TYPE_16SRV_CMPL; // 0x03 + addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid16, 2)); + break; + } + + case 32: { + // [Len] [0x04] [LL] [LL] [HH] [HH] + cdata[0] = 5; + cdata[1] = ESP_BLE_AD_TYPE_32SRV_CMPL; // 0x05 + addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid32, 4)); + break; + } + + case 128: { + // [Len] [0x04] [0] [1] ... [15] + cdata[0] = 17; + cdata[1] = ESP_BLE_AD_TYPE_128SRV_CMPL; // 0x07 + addData(std::string(cdata, 2) + std::string((char*) uuid.getNative()->uuid.uuid128, 16)); + break; + } + + default: + return; + } +} // setCompleteServices + + +/** + * @brief Set the advertisement flags. + * @param [in] The flags to be set in the advertisement. + * + * * ESP_BLE_ADV_FLAG_LIMIT_DISC + * * ESP_BLE_ADV_FLAG_GEN_DISC + * * ESP_BLE_ADV_FLAG_BREDR_NOT_SPT + * * ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT + * * ESP_BLE_ADV_FLAG_DMT_HOST_SPT + * * ESP_BLE_ADV_FLAG_NON_LIMIT_DISC + */ +void BLEAdvertisementData::setFlags(uint8_t flag) { + char cdata[3]; + cdata[0] = 2; + cdata[1] = ESP_BLE_AD_TYPE_FLAG; // 0x01 + cdata[2] = flag; + addData(std::string(cdata, 3)); +} // setFlag + + + +/** + * @brief Set manufacturer specific data. + * @param [in] data Manufacturer data. + */ +void BLEAdvertisementData::setManufacturerData(std::string data) { + log_d("BLEAdvertisementData", ">> setManufacturerData"); + char cdata[2]; + cdata[0] = data.length() + 1; + cdata[1] = ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE; // 0xff + addData(std::string(cdata, 2) + data); + log_d("BLEAdvertisementData", "<< setManufacturerData"); +} // setManufacturerData + + +/** + * @brief Set the name. + * @param [in] The complete name of the device. + */ +void BLEAdvertisementData::setName(std::string name) { + log_d("BLEAdvertisementData", ">> setName: %s", name.c_str()); + char cdata[2]; + cdata[0] = name.length() + 1; + cdata[1] = ESP_BLE_AD_TYPE_NAME_CMPL; // 0x09 + addData(std::string(cdata, 2) + name); + log_d("BLEAdvertisementData", "<< setName"); +} // setName + + +/** + * @brief Set the partial services. + * @param [in] uuid The single service to advertise. + */ +void BLEAdvertisementData::setPartialServices(BLEUUID uuid) { + char cdata[2]; + switch (uuid.bitSize()) { + case 16: { + // [Len] [0x02] [LL] [HH] + cdata[0] = 3; + cdata[1] = ESP_BLE_AD_TYPE_16SRV_PART; // 0x02 + addData(std::string(cdata, 2) + std::string((char *) &uuid.getNative()->uuid.uuid16, 2)); + break; + } + + case 32: { + // [Len] [0x04] [LL] [LL] [HH] [HH] + cdata[0] = 5; + cdata[1] = ESP_BLE_AD_TYPE_32SRV_PART; // 0x04 + addData(std::string(cdata, 2) + std::string((char *) &uuid.getNative()->uuid.uuid32, 4)); + break; + } + + case 128: { + // [Len] [0x04] [0] [1] ... [15] + cdata[0] = 17; + cdata[1] = ESP_BLE_AD_TYPE_128SRV_PART; // 0x06 + addData(std::string(cdata, 2) + std::string((char *) &uuid.getNative()->uuid.uuid128, 16)); + break; + } + + default: + return; + } +} // setPartialServices + + +/** + * @brief Set the service data (UUID + data) + * @param [in] uuid The UUID to set with the service data. Size of UUID will be used. + * @param [in] data The data to be associated with the service data advert. + */ +void BLEAdvertisementData::setServiceData(BLEUUID uuid, std::string data) { + char cdata[2]; + switch (uuid.bitSize()) { + case 16: { + // [Len] [0x16] [UUID16] data + cdata[0] = data.length() + 3; + cdata[1] = ESP_BLE_AD_TYPE_SERVICE_DATA; // 0x16 + addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid16, 2) + data); + break; + } + + case 32: { + // [Len] [0x20] [UUID32] data + cdata[0] = data.length() + 5; + cdata[1] = ESP_BLE_AD_TYPE_32SERVICE_DATA; // 0x20 + addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid32, 4) + data); + break; + } + + case 128: { + // [Len] [0x21] [UUID128] data + cdata[0] = data.length() + 17; + cdata[1] = ESP_BLE_AD_TYPE_128SERVICE_DATA; // 0x21 + addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid128, 16) + data); + break; + } + + default: + return; + } +} // setServiceData + + +/** + * @brief Set the short name. + * @param [in] The short name of the device. + */ +void BLEAdvertisementData::setShortName(std::string name) { + log_d("BLEAdvertisementData", ">> setShortName: %s", name.c_str()); + char cdata[2]; + cdata[0] = name.length() + 1; + cdata[1] = ESP_BLE_AD_TYPE_NAME_SHORT; // 0x08 + addData(std::string(cdata, 2) + name); + log_d("BLEAdvertisementData", "<< setShortName"); +} // setShortName + + +/** + * @brief Retrieve the payload that is to be advertised. + * @return The payload that is to be advertised. + */ +std::string BLEAdvertisementData::getPayload() { + return m_payload; +} // getPayload + +void BLEAdvertising::handleGAPEvent( + esp_gap_ble_cb_event_t event, + esp_ble_gap_cb_param_t* param) { + + log_d("handleGAPEvent [event no: %d]", (int)event); + + switch(event) { + case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: { + // m_semaphoreSetAdv.give(); + break; + } + case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: { + // m_semaphoreSetAdv.give(); + break; + } + case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: { + // m_semaphoreSetAdv.give(); + break; + } + case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: { + log_i("STOP advertising"); + //start(); + break; + } + default: + break; + } +} + + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEAdvertising.h b/libraries/BLE/src/BLEAdvertising.h new file mode 100644 index 00000000000..be85371ec64 --- /dev/null +++ b/libraries/BLE/src/BLEAdvertising.h @@ -0,0 +1,79 @@ +/* + * BLEAdvertising.h + * + * Created on: Jun 21, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ +#define COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include "BLEUUID.h" +#include +#include "FreeRTOS.h" + +/** + * @brief Advertisement data set by the programmer to be published by the %BLE server. + */ +class BLEAdvertisementData { + // Only a subset of the possible BLE architected advertisement fields are currently exposed. Others will + // be exposed on demand/request or as time permits. + // +public: + void setAppearance(uint16_t appearance); + void setCompleteServices(BLEUUID uuid); + void setFlags(uint8_t); + void setManufacturerData(std::string data); + void setName(std::string name); + void setPartialServices(BLEUUID uuid); + void setServiceData(BLEUUID uuid, std::string data); + void setShortName(std::string name); + void addData(std::string data); // Add data to the payload. + std::string getPayload(); // Retrieve the current advert payload. + +private: + friend class BLEAdvertising; + std::string m_payload; // The payload of the advertisement. +}; // BLEAdvertisementData + + +/** + * @brief Perform and manage %BLE advertising. + * + * A %BLE server will want to perform advertising in order to make itself known to %BLE clients. + */ +class BLEAdvertising { +public: + BLEAdvertising(); + void addServiceUUID(BLEUUID serviceUUID); + void addServiceUUID(const char* serviceUUID); + void start(); + void stop(); + void setAppearance(uint16_t appearance); + void setMaxInterval(uint16_t maxinterval); + void setMinInterval(uint16_t mininterval); + void setAdvertisementData(BLEAdvertisementData& advertisementData); + void setScanFilter(bool scanRequertWhitelistOnly, bool connectWhitelistOnly); + void setScanResponseData(BLEAdvertisementData& advertisementData); + void setPrivateAddress(esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM); + void setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM); + + void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param); + void setMinPreferred(uint16_t); + void setMaxPreferred(uint16_t); + void setScanResponse(bool); + +private: + esp_ble_adv_data_t m_advData; + esp_ble_adv_params_t m_advParams; + std::vector m_serviceUUIDs; + bool m_customAdvData = false; // Are we using custom advertising data? + bool m_customScanResponseData = false; // Are we using custom scan response data? + FreeRTOS::Semaphore m_semaphoreSetAdv = FreeRTOS::Semaphore("startAdvert"); + bool m_scanResp = true; + +}; +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ */ \ No newline at end of file diff --git a/libraries/BLE/src/BLEBeacon.cpp b/libraries/BLE/src/BLEBeacon.cpp new file mode 100644 index 00000000000..1056cd54b04 --- /dev/null +++ b/libraries/BLE/src/BLEBeacon.cpp @@ -0,0 +1,83 @@ +/* + * BLEBeacon.cpp + * + * Created on: Jan 4, 2018 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include "BLEBeacon.h" +#include "esp32-hal-log.h" + +#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) + + +BLEBeacon::BLEBeacon() { + m_beaconData.manufacturerId = 0x4c00; + m_beaconData.subType = 0x02; + m_beaconData.subTypeLength = 0x15; + m_beaconData.major = 0; + m_beaconData.minor = 0; + m_beaconData.signalPower = 0; + memset(m_beaconData.proximityUUID, 0, sizeof(m_beaconData.proximityUUID)); +} // BLEBeacon + +std::string BLEBeacon::getData() { + return std::string((char*) &m_beaconData, sizeof(m_beaconData)); +} // getData + +uint16_t BLEBeacon::getMajor() { + return m_beaconData.major; +} + +uint16_t BLEBeacon::getManufacturerId() { + return m_beaconData.manufacturerId; +} + +uint16_t BLEBeacon::getMinor() { + return m_beaconData.minor; +} + +BLEUUID BLEBeacon::getProximityUUID() { + return BLEUUID(m_beaconData.proximityUUID, 16, false); +} + +int8_t BLEBeacon::getSignalPower() { + return m_beaconData.signalPower; +} + +/** + * Set the raw data for the beacon record. + */ +void BLEBeacon::setData(std::string data) { + if (data.length() != sizeof(m_beaconData)) { + log_e("Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_beaconData)); + return; + } + memcpy(&m_beaconData, data.data(), sizeof(m_beaconData)); +} // setData + +void BLEBeacon::setMajor(uint16_t major) { + m_beaconData.major = ENDIAN_CHANGE_U16(major); +} // setMajor + +void BLEBeacon::setManufacturerId(uint16_t manufacturerId) { + m_beaconData.manufacturerId = ENDIAN_CHANGE_U16(manufacturerId); +} // setManufacturerId + +void BLEBeacon::setMinor(uint16_t minor) { + m_beaconData.minor = ENDIAN_CHANGE_U16(minor); +} // setMinior + +void BLEBeacon::setProximityUUID(BLEUUID uuid) { + uuid = uuid.to128(); + memcpy(m_beaconData.proximityUUID, uuid.getNative()->uuid.uuid128, 16); +} // setProximityUUID + +void BLEBeacon::setSignalPower(int8_t signalPower) { + m_beaconData.signalPower = signalPower; +} // setSignalPower + + +#endif diff --git a/libraries/BLE/src/BLEBeacon.h b/libraries/BLE/src/BLEBeacon.h new file mode 100644 index 00000000000..277bd670776 --- /dev/null +++ b/libraries/BLE/src/BLEBeacon.h @@ -0,0 +1,43 @@ +/* + * BLEBeacon2.h + * + * Created on: Jan 4, 2018 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEBEACON_H_ +#define COMPONENTS_CPP_UTILS_BLEBEACON_H_ +#include "BLEUUID.h" +/** + * @brief Representation of a beacon. + * See: + * * https://en.wikipedia.org/wiki/IBeacon + */ +class BLEBeacon { +private: + struct { + uint16_t manufacturerId; + uint8_t subType; + uint8_t subTypeLength; + uint8_t proximityUUID[16]; + uint16_t major; + uint16_t minor; + int8_t signalPower; + } __attribute__((packed)) m_beaconData; +public: + BLEBeacon(); + std::string getData(); + uint16_t getMajor(); + uint16_t getMinor(); + uint16_t getManufacturerId(); + BLEUUID getProximityUUID(); + int8_t getSignalPower(); + void setData(std::string data); + void setMajor(uint16_t major); + void setMinor(uint16_t minor); + void setManufacturerId(uint16_t manufacturerId); + void setProximityUUID(BLEUUID uuid); + void setSignalPower(int8_t signalPower); +}; // BLEBeacon + +#endif /* COMPONENTS_CPP_UTILS_BLEBEACON_H_ */ diff --git a/libraries/BLE/src/BLECharacteristic.cpp b/libraries/BLE/src/BLECharacteristic.cpp new file mode 100644 index 00000000000..25146136184 --- /dev/null +++ b/libraries/BLE/src/BLECharacteristic.cpp @@ -0,0 +1,799 @@ +/* + * BLECharacteristic.cpp + * + * Created on: Jun 22, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include +#include +#include "sdkconfig.h" +#include +#include "BLECharacteristic.h" +#include "BLEService.h" +#include "BLEDevice.h" +#include "BLEUtils.h" +#include "BLE2902.h" +#include "GeneralUtils.h" +#include "esp32-hal-log.h" + +#define NULL_HANDLE (0xffff) + +static BLECharacteristicCallbacks defaultCallback; //null-object-pattern + +/** + * @brief Construct a characteristic + * @param [in] uuid - UUID (const char*) for the characteristic. + * @param [in] properties - Properties for the characteristic. + */ +BLECharacteristic::BLECharacteristic(const char* uuid, uint32_t properties) : BLECharacteristic(BLEUUID(uuid), properties) { +} + +/** + * @brief Construct a characteristic + * @param [in] uuid - UUID for the characteristic. + * @param [in] properties - Properties for the characteristic. + */ +BLECharacteristic::BLECharacteristic(BLEUUID uuid, uint32_t properties) { + m_bleUUID = uuid; + m_handle = NULL_HANDLE; + m_properties = (esp_gatt_char_prop_t)0; + m_pCallbacks = &defaultCallback; + + setBroadcastProperty((properties & PROPERTY_BROADCAST) != 0); + setReadProperty((properties & PROPERTY_READ) != 0); + setWriteProperty((properties & PROPERTY_WRITE) != 0); + setNotifyProperty((properties & PROPERTY_NOTIFY) != 0); + setIndicateProperty((properties & PROPERTY_INDICATE) != 0); + setWriteNoResponseProperty((properties & PROPERTY_WRITE_NR) != 0); +} // BLECharacteristic + +/** + * @brief Destructor. + */ +BLECharacteristic::~BLECharacteristic() { + //free(m_value.attr_value); // Release the storage for the value. +} // ~BLECharacteristic + + +/** + * @brief Associate a descriptor with this characteristic. + * @param [in] pDescriptor + * @return N/A. + */ +void BLECharacteristic::addDescriptor(BLEDescriptor* pDescriptor) { + log_v(">> addDescriptor(): Adding %s to %s", pDescriptor->toString().c_str(), toString().c_str()); + m_descriptorMap.setByUUID(pDescriptor->getUUID(), pDescriptor); + log_v("<< addDescriptor()"); +} // addDescriptor + + +/** + * @brief Register a new characteristic with the ESP runtime. + * @param [in] pService The service with which to associate this characteristic. + */ +void BLECharacteristic::executeCreate(BLEService* pService) { + log_v(">> executeCreate()"); + + if (m_handle != NULL_HANDLE) { + log_e("Characteristic already has a handle."); + return; + } + + m_pService = pService; // Save the service to which this characteristic belongs. + + log_d("Registering characteristic (esp_ble_gatts_add_char): uuid: %s, service: %s", + getUUID().toString().c_str(), + m_pService->toString().c_str()); + + esp_attr_control_t control; + control.auto_rsp = ESP_GATT_RSP_BY_APP; + + m_semaphoreCreateEvt.take("executeCreate"); + esp_err_t errRc = ::esp_ble_gatts_add_char( + m_pService->getHandle(), + getUUID().getNative(), + static_cast(m_permissions), + getProperties(), + nullptr, + &control); // Whether to auto respond or not. + + if (errRc != ESP_OK) { + log_e("<< esp_ble_gatts_add_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + m_semaphoreCreateEvt.wait("executeCreate"); + + BLEDescriptor* pDescriptor = m_descriptorMap.getFirst(); + while (pDescriptor != nullptr) { + pDescriptor->executeCreate(this); + pDescriptor = m_descriptorMap.getNext(); + } // End while + + log_v("<< executeCreate"); +} // executeCreate + + +/** + * @brief Return the BLE Descriptor for the given UUID if associated with this characteristic. + * @param [in] descriptorUUID The UUID of the descriptor that we wish to retrieve. + * @return The BLE Descriptor. If no such descriptor is associated with the characteristic, nullptr is returned. + */ +BLEDescriptor* BLECharacteristic::getDescriptorByUUID(const char* descriptorUUID) { + return m_descriptorMap.getByUUID(BLEUUID(descriptorUUID)); +} // getDescriptorByUUID + + +/** + * @brief Return the BLE Descriptor for the given UUID if associated with this characteristic. + * @param [in] descriptorUUID The UUID of the descriptor that we wish to retrieve. + * @return The BLE Descriptor. If no such descriptor is associated with the characteristic, nullptr is returned. + */ +BLEDescriptor* BLECharacteristic::getDescriptorByUUID(BLEUUID descriptorUUID) { + return m_descriptorMap.getByUUID(descriptorUUID); +} // getDescriptorByUUID + + +/** + * @brief Get the handle of the characteristic. + * @return The handle of the characteristic. + */ +uint16_t BLECharacteristic::getHandle() { + return m_handle; +} // getHandle + +void BLECharacteristic::setAccessPermissions(esp_gatt_perm_t perm) { + m_permissions = perm; +} + +esp_gatt_char_prop_t BLECharacteristic::getProperties() { + return m_properties; +} // getProperties + + +/** + * @brief Get the service associated with this characteristic. + */ +BLEService* BLECharacteristic::getService() { + return m_pService; +} // getService + + +/** + * @brief Get the UUID of the characteristic. + * @return The UUID of the characteristic. + */ +BLEUUID BLECharacteristic::getUUID() { + return m_bleUUID; +} // getUUID + + +/** + * @brief Retrieve the current value of the characteristic. + * @return A pointer to storage containing the current characteristic value. + */ +std::string BLECharacteristic::getValue() { + return m_value.getValue(); +} // getValue + +/** + * @brief Retrieve the current raw data of the characteristic. + * @return A pointer to storage containing the current characteristic data. + */ +uint8_t* BLECharacteristic::getData() { + return m_value.getData(); +} // getData + + +/** + * Handle a GATT server event. + */ +void BLECharacteristic::handleGATTServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* param) { + log_v(">> handleGATTServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); + + switch(event) { + // Events handled: + // + // ESP_GATTS_ADD_CHAR_EVT + // ESP_GATTS_CONF_EVT + // ESP_GATTS_CONNECT_EVT + // ESP_GATTS_DISCONNECT_EVT + // ESP_GATTS_EXEC_WRITE_EVT + // ESP_GATTS_READ_EVT + // ESP_GATTS_WRITE_EVT + + // + // ESP_GATTS_EXEC_WRITE_EVT + // When we receive this event it is an indication that a previous write long needs to be committed. + // + // exec_write: + // - uint16_t conn_id + // - uint32_t trans_id + // - esp_bd_addr_t bda + // - uint8_t exec_write_flag - Either ESP_GATT_PREP_WRITE_EXEC or ESP_GATT_PREP_WRITE_CANCEL + // + case ESP_GATTS_EXEC_WRITE_EVT: { + if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) { + m_value.commit(); + m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. + } else { + m_value.cancel(); + } +// ??? + esp_err_t errRc = ::esp_ble_gatts_send_response( + gatts_if, + param->write.conn_id, + param->write.trans_id, ESP_GATT_OK, nullptr); + if (errRc != ESP_OK) { + log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } + break; + } // ESP_GATTS_EXEC_WRITE_EVT + + + // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. + // add_char: + // - esp_gatt_status_t status + // - uint16_t attr_handle + // - uint16_t service_handle + // - esp_bt_uuid_t char_uuid + case ESP_GATTS_ADD_CHAR_EVT: { + if (getHandle() == param->add_char.attr_handle) { + // we have created characteristic, now we can create descriptors + // BLEDescriptor* pDescriptor = m_descriptorMap.getFirst(); + // while (pDescriptor != nullptr) { + // pDescriptor->executeCreate(this); + // pDescriptor = m_descriptorMap.getNext(); + // } // End while + m_semaphoreCreateEvt.give(); + } + break; + } // ESP_GATTS_ADD_CHAR_EVT + + + // ESP_GATTS_WRITE_EVT - A request to write the value of a characteristic has arrived. + // + // write: + // - uint16_t conn_id + // - uint16_t trans_id + // - esp_bd_addr_t bda + // - uint16_t handle + // - uint16_t offset + // - bool need_rsp + // - bool is_prep + // - uint16_t len + // - uint8_t *value + // + case ESP_GATTS_WRITE_EVT: { +// We check if this write request is for us by comparing the handles in the event. If it is for us +// we save the new value. Next we look at the need_rsp flag which indicates whether or not we need +// to send a response. If we do, then we formulate a response and send it. + if (param->write.handle == m_handle) { + if (param->write.is_prep) { + m_value.addPart(param->write.value, param->write.len); + } else { + setValue(param->write.value, param->write.len); + } + + log_d(" - Response to write event: New value: handle: %.2x, uuid: %s", + getHandle(), getUUID().toString().c_str()); + + char* pHexData = BLEUtils::buildHexData(nullptr, param->write.value, param->write.len); + log_d(" - Data: length: %d, data: %s", param->write.len, pHexData); + free(pHexData); + + if (param->write.need_rsp) { + esp_gatt_rsp_t rsp; + + rsp.attr_value.len = param->write.len; + rsp.attr_value.handle = m_handle; + rsp.attr_value.offset = param->write.offset; + rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; + memcpy(rsp.attr_value.value, param->write.value, param->write.len); + + esp_err_t errRc = ::esp_ble_gatts_send_response( + gatts_if, + param->write.conn_id, + param->write.trans_id, ESP_GATT_OK, &rsp); + if (errRc != ESP_OK) { + log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } + } // Response needed + + if (param->write.is_prep != true) { + m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. + } + } // Match on handles. + break; + } // ESP_GATTS_WRITE_EVT + + + // ESP_GATTS_READ_EVT - A request to read the value of a characteristic has arrived. + // + // read: + // - uint16_t conn_id + // - uint32_t trans_id + // - esp_bd_addr_t bda + // - uint16_t handle + // - uint16_t offset + // - bool is_long + // - bool need_rsp + // + case ESP_GATTS_READ_EVT: { + if (param->read.handle == m_handle) { + + + +// Here's an interesting thing. The read request has the option of saying whether we need a response +// or not. What would it "mean" to receive a read request and NOT send a response back? That feels like +// a very strange read. +// +// We have to handle the case where the data we wish to send back to the client is greater than the maximum +// packet size of 22 bytes. In this case, we become responsible for chunking the data into units of 22 bytes. +// The apparent algorithm is as follows: +// +// If the is_long flag is set then this is a follow on from an original read and we will already have sent at least 22 bytes. +// If the is_long flag is not set then we need to check how much data we are going to send. If we are sending LESS than +// 22 bytes, then we "just" send it and thats the end of the story. +// If we are sending 22 bytes exactly, we just send it BUT we will get a follow on request. +// If we are sending more than 22 bytes, we send the first 22 bytes and we will get a follow on request. +// Because of follow on request processing, we need to maintain an offset of how much data we have already sent +// so that when a follow on request arrives, we know where to start in the data to send the next sequence. +// Note that the indication that the client will send a follow on request is that we sent exactly 22 bytes as a response. +// If our payload is divisible by 22 then the last response will be a response of 0 bytes in length. +// +// The following code has deliberately not been factored to make it fewer statements because this would cloud the +// the logic flow comprehension. +// + + // get mtu for peer device that we are sending read request to + uint16_t maxOffset = getService()->getServer()->getPeerMTU(param->read.conn_id) - 1; + log_d("mtu value: %d", maxOffset); + if (param->read.need_rsp) { + log_d("Sending a response (esp_ble_gatts_send_response)"); + esp_gatt_rsp_t rsp; + + if (param->read.is_long) { + std::string value = m_value.getValue(); + + if (value.length() - m_value.getReadOffset() < maxOffset) { + // This is the last in the chain + rsp.attr_value.len = value.length() - m_value.getReadOffset(); + rsp.attr_value.offset = m_value.getReadOffset(); + memcpy(rsp.attr_value.value, value.data() + rsp.attr_value.offset, rsp.attr_value.len); + m_value.setReadOffset(0); + } else { + // There will be more to come. + rsp.attr_value.len = maxOffset; + rsp.attr_value.offset = m_value.getReadOffset(); + memcpy(rsp.attr_value.value, value.data() + rsp.attr_value.offset, rsp.attr_value.len); + m_value.setReadOffset(rsp.attr_value.offset + maxOffset); + } + } else { // read.is_long == false + + // If is.long is false then this is the first (or only) request to read data, so invoke the callback + // Invoke the read callback. + m_pCallbacks->onRead(this); + + std::string value = m_value.getValue(); + + if (value.length() + 1 > maxOffset) { + // Too big for a single shot entry. + m_value.setReadOffset(maxOffset); + rsp.attr_value.len = maxOffset; + rsp.attr_value.offset = 0; + memcpy(rsp.attr_value.value, value.data(), rsp.attr_value.len); + } else { + // Will fit in a single packet with no callbacks required. + rsp.attr_value.len = value.length(); + rsp.attr_value.offset = 0; + memcpy(rsp.attr_value.value, value.data(), rsp.attr_value.len); + } + } + rsp.attr_value.handle = param->read.handle; + rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; + + char *pHexData = BLEUtils::buildHexData(nullptr, rsp.attr_value.value, rsp.attr_value.len); + log_d(" - Data: length=%d, data=%s, offset=%d", rsp.attr_value.len, pHexData, rsp.attr_value.offset); + free(pHexData); + + esp_err_t errRc = ::esp_ble_gatts_send_response( + gatts_if, param->read.conn_id, + param->read.trans_id, + ESP_GATT_OK, + &rsp); + if (errRc != ESP_OK) { + log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } + } // Response needed + } // Handle matches this characteristic. + break; + } // ESP_GATTS_READ_EVT + + + // ESP_GATTS_CONF_EVT + // + // conf: + // - esp_gatt_status_t status – The status code. + // - uint16_t conn_id – The connection used. + // + case ESP_GATTS_CONF_EVT: { + // log_d("m_handle = %d, conf->handle = %d", m_handle, param->conf.handle); + if(param->conf.conn_id == getService()->getServer()->getConnId()) // && param->conf.handle == m_handle) // bug in esp-idf and not implemented in arduino yet + m_semaphoreConfEvt.give(param->conf.status); + break; + } + + case ESP_GATTS_CONNECT_EVT: { + break; + } + + case ESP_GATTS_DISCONNECT_EVT: { + m_semaphoreConfEvt.give(); + break; + } + + default: { + break; + } // default + + } // switch event + + // Give each of the descriptors associated with this characteristic the opportunity to handle the + // event. + + m_descriptorMap.handleGATTServerEvent(event, gatts_if, param); + log_v("<< handleGATTServerEvent"); +} // handleGATTServerEvent + + +/** + * @brief Send an indication. + * An indication is a transmission of up to the first 20 bytes of the characteristic value. An indication + * will block waiting a positive confirmation from the client. + * @return N/A + */ +void BLECharacteristic::indicate() { + + log_v(">> indicate: length: %d", m_value.getValue().length()); + notify(false); + log_v("<< indicate"); +} // indicate + + +/** + * @brief Send a notify. + * A notification is a transmission of up to the first 20 bytes of the characteristic value. An notification + * will not block; it is a fire and forget. + * @return N/A. + */ +void BLECharacteristic::notify(bool is_notification) { + log_v(">> notify: length: %d", m_value.getValue().length()); + + assert(getService() != nullptr); + assert(getService()->getServer() != nullptr); + + m_pCallbacks->onNotify(this); // Invoke the notify callback. + + GeneralUtils::hexDump((uint8_t*)m_value.getValue().data(), m_value.getValue().length()); + + if (getService()->getServer()->getConnectedCount() == 0) { + log_v("<< notify: No connected clients."); + m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NO_CLIENT, 0); + return; + } + + // Test to see if we have a 0x2902 descriptor. If we do, then check to see if notification is enabled + // and, if not, prevent the notification. + + BLE2902 *p2902 = (BLE2902*)getDescriptorByUUID((uint16_t)0x2902); + if(is_notification) { + if (p2902 != nullptr && !p2902->getNotifications()) { + log_v("<< notifications disabled; ignoring"); + m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NOTIFY_DISABLED, 0); // Invoke the notify callback. + return; + } + } + else{ + if (p2902 != nullptr && !p2902->getIndications()) { + log_v("<< indications disabled; ignoring"); + m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_DISABLED, 0); // Invoke the notify callback. + return; + } + } + for (auto &myPair : getService()->getServer()->getPeerDevices(false)) { + uint16_t _mtu = (myPair.second.mtu); + if (m_value.getValue().length() > _mtu - 3) { + log_w("- Truncating to %d bytes (maximum notify size)", _mtu - 3); + } + + size_t length = m_value.getValue().length(); + if(!is_notification) // is indication + m_semaphoreConfEvt.take("indicate"); + esp_err_t errRc = ::esp_ble_gatts_send_indicate( + getService()->getServer()->getGattsIf(), + myPair.first, + getHandle(), length, (uint8_t*)m_value.getValue().data(), !is_notification); // The need_confirm = false makes this a notify. + if (errRc != ESP_OK) { + log_e("<< esp_ble_gatts_send_ %s: rc=%d %s",is_notification?"notify":"indicate", errRc, GeneralUtils::errorToString(errRc)); + m_semaphoreConfEvt.give(); + m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_GATT, errRc); // Invoke the notify callback. + return; + } + if(!is_notification){ // is indication + if(!m_semaphoreConfEvt.timedWait("indicate", indicationTimeout)){ + m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_TIMEOUT, 0); // Invoke the notify callback. + } else { + auto code = (esp_gatt_status_t) m_semaphoreConfEvt.value(); + if(code == ESP_GATT_OK) { + m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_INDICATE, code); // Invoke the notify callback. + } else { + m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_FAILURE, code); + } + } + } else { + m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_NOTIFY, 0); // Invoke the notify callback. + } + } + log_v("<< notify"); +} // Notify + + +/** + * @brief Set the permission to broadcast. + * A characteristics has properties associated with it which define what it is capable of doing. + * One of these is the broadcast flag. + * @param [in] value The flag value of the property. + * @return N/A + */ +void BLECharacteristic::setBroadcastProperty(bool value) { + //log_d("setBroadcastProperty(%d)", value); + if (value) { + m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_BROADCAST); + } else { + m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_BROADCAST); + } +} // setBroadcastProperty + + +/** + * @brief Set the callback handlers for this characteristic. + * @param [in] pCallbacks An instance of a callbacks structure used to define any callbacks for the characteristic. + */ +void BLECharacteristic::setCallbacks(BLECharacteristicCallbacks* pCallbacks) { + log_v(">> setCallbacks: 0x%x", (uint32_t)pCallbacks); + if (pCallbacks != nullptr){ + m_pCallbacks = pCallbacks; + } else { + m_pCallbacks = &defaultCallback; + } + log_v("<< setCallbacks"); +} // setCallbacks + + +/** + * @brief Set the BLE handle associated with this characteristic. + * A user program will request that a characteristic be created against a service. When the characteristic has been + * registered, the service will be given a "handle" that it knows the characteristic as. This handle is unique to the + * server/service but it is told to the service, not the characteristic associated with the service. This internally + * exposed function can be invoked by the service against this model of the characteristic to allow the characteristic + * to learn its own handle. Once the characteristic knows its own handle, it will be able to see incoming GATT events + * that will be propagated down to it which contain a handle value and now know that the event is destined for it. + * @param [in] handle The handle associated with this characteristic. + */ +void BLECharacteristic::setHandle(uint16_t handle) { + log_v(">> setHandle: handle=0x%.2x, characteristic uuid=%s", handle, getUUID().toString().c_str()); + m_handle = handle; + log_v("<< setHandle"); +} // setHandle + + +/** + * @brief Set the Indicate property value. + * @param [in] value Set to true if we are to allow indicate messages. + */ +void BLECharacteristic::setIndicateProperty(bool value) { + //log_d("setIndicateProperty(%d)", value); + if (value) { + m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_INDICATE); + } else { + m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_INDICATE); + } +} // setIndicateProperty + + +/** + * @brief Set the Notify property value. + * @param [in] value Set to true if we are to allow notification messages. + */ +void BLECharacteristic::setNotifyProperty(bool value) { + //log_d("setNotifyProperty(%d)", value); + if (value) { + m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_NOTIFY); + } else { + m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_NOTIFY); + } +} // setNotifyProperty + + +/** + * @brief Set the Read property value. + * @param [in] value Set to true if we are to allow reads. + */ +void BLECharacteristic::setReadProperty(bool value) { + //log_d("setReadProperty(%d)", value); + if (value) { + m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_READ); + } else { + m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_READ); + } +} // setReadProperty + + +/** + * @brief Set the value of the characteristic. + * @param [in] data The data to set for the characteristic. + * @param [in] length The length of the data in bytes. + */ +void BLECharacteristic::setValue(uint8_t* data, size_t length) { + char* pHex = BLEUtils::buildHexData(nullptr, data, length); + log_v(">> setValue: length=%d, data=%s, characteristic UUID=%s", length, pHex, getUUID().toString().c_str()); + free(pHex); + if (length > ESP_GATT_MAX_ATTR_LEN) { + log_e("Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); + return; + } + m_semaphoreSetValue.take(); + m_value.setValue(data, length); + m_semaphoreSetValue.give(); + log_v("<< setValue"); +} // setValue + + +/** + * @brief Set the value of the characteristic from string data. + * We set the value of the characteristic from the bytes contained in the + * string. + * @param [in] Set the value of the characteristic. + * @return N/A. + */ +void BLECharacteristic::setValue(std::string value) { + setValue((uint8_t*)(value.data()), value.length()); +} // setValue + +void BLECharacteristic::setValue(uint16_t& data16) { + uint8_t temp[2]; + temp[0] = data16; + temp[1] = data16 >> 8; + setValue(temp, 2); +} // setValue + +void BLECharacteristic::setValue(uint32_t& data32) { + uint8_t temp[4]; + temp[0] = data32; + temp[1] = data32 >> 8; + temp[2] = data32 >> 16; + temp[3] = data32 >> 24; + setValue(temp, 4); +} // setValue + +void BLECharacteristic::setValue(int& data32) { + uint8_t temp[4]; + temp[0] = data32; + temp[1] = data32 >> 8; + temp[2] = data32 >> 16; + temp[3] = data32 >> 24; + setValue(temp, 4); +} // setValue + +void BLECharacteristic::setValue(float& data32) { + float temp = data32; + setValue((uint8_t*)&temp, 4); +} // setValue + +void BLECharacteristic::setValue(double& data64) { + double temp = data64; + setValue((uint8_t*)&temp, 8); +} // setValue + + +/** + * @brief Set the Write No Response property value. + * @param [in] value Set to true if we are to allow writes with no response. + */ +void BLECharacteristic::setWriteNoResponseProperty(bool value) { + //log_d("setWriteNoResponseProperty(%d)", value); + if (value) { + m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_WRITE_NR); + } else { + m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_WRITE_NR); + } +} // setWriteNoResponseProperty + + +/** + * @brief Set the Write property value. + * @param [in] value Set to true if we are to allow writes. + */ +void BLECharacteristic::setWriteProperty(bool value) { + //log_d("setWriteProperty(%d)", value); + if (value) { + m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_WRITE); + } else { + m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_WRITE); + } +} // setWriteProperty + + +/** + * @brief Return a string representation of the characteristic. + * @return A string representation of the characteristic. + */ +std::string BLECharacteristic::toString() { + std::string res = "UUID: " + m_bleUUID.toString() + ", handle : 0x"; + char hex[5]; + snprintf(hex, sizeof(hex), "%04x", m_handle); + res += hex; + res += " "; + if (m_properties & ESP_GATT_CHAR_PROP_BIT_READ) res += "Read "; + if (m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE) res += "Write "; + if (m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) res += "WriteNoResponse "; + if (m_properties & ESP_GATT_CHAR_PROP_BIT_BROADCAST) res += "Broadcast "; + if (m_properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY) res += "Notify "; + if (m_properties & ESP_GATT_CHAR_PROP_BIT_INDICATE) res += "Indicate "; + return res; +} // toString + + +BLECharacteristicCallbacks::~BLECharacteristicCallbacks() {} + + +/** + * @brief Callback function to support a read request. + * @param [in] pCharacteristic The characteristic that is the source of the event. + */ +void BLECharacteristicCallbacks::onRead(BLECharacteristic* pCharacteristic) { + log_d("BLECharacteristicCallbacks", ">> onRead: default"); + log_d("BLECharacteristicCallbacks", "<< onRead"); +} // onRead + + +/** + * @brief Callback function to support a write request. + * @param [in] pCharacteristic The characteristic that is the source of the event. + */ +void BLECharacteristicCallbacks::onWrite(BLECharacteristic* pCharacteristic) { + log_d("BLECharacteristicCallbacks", ">> onWrite: default"); + log_d("BLECharacteristicCallbacks", "<< onWrite"); +} // onWrite + + +/** + * @brief Callback function to support a Notify request. + * @param [in] pCharacteristic The characteristic that is the source of the event. + */ +void BLECharacteristicCallbacks::onNotify(BLECharacteristic* pCharacteristic) { + log_d("BLECharacteristicCallbacks", ">> onNotify: default"); + log_d("BLECharacteristicCallbacks", "<< onNotify"); +} // onNotify + + +/** + * @brief Callback function to support a Notify/Indicate Status report. + * @param [in] pCharacteristic The characteristic that is the source of the event. + * @param [in] s Status of the notification/indication + * @param [in] code Additional code of underlying errors + */ +void BLECharacteristicCallbacks::onStatus(BLECharacteristic* pCharacteristic, Status s, uint32_t code) { + log_d("BLECharacteristicCallbacks", ">> onStatus: default"); + log_d("BLECharacteristicCallbacks", "<< onStatus"); +} // onStatus + + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLECharacteristic.h b/libraries/BLE/src/BLECharacteristic.h new file mode 100644 index 00000000000..adec9587ee0 --- /dev/null +++ b/libraries/BLE/src/BLECharacteristic.h @@ -0,0 +1,153 @@ +/* + * BLECharacteristic.h + * + * Created on: Jun 22, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ +#define COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include "BLEUUID.h" +#include +#include +#include "BLEDescriptor.h" +#include "BLEValue.h" +#include "FreeRTOS.h" + +class BLEService; +class BLEDescriptor; +class BLECharacteristicCallbacks; + +/** + * @brief A management structure for %BLE descriptors. + */ +class BLEDescriptorMap { +public: + void setByUUID(const char* uuid, BLEDescriptor* pDescriptor); + void setByUUID(BLEUUID uuid, BLEDescriptor* pDescriptor); + void setByHandle(uint16_t handle, BLEDescriptor* pDescriptor); + BLEDescriptor* getByUUID(const char* uuid); + BLEDescriptor* getByUUID(BLEUUID uuid); + BLEDescriptor* getByHandle(uint16_t handle); + std::string toString(); + void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param); + BLEDescriptor* getFirst(); + BLEDescriptor* getNext(); +private: + std::map m_uuidMap; + std::map m_handleMap; + std::map::iterator m_iterator; +}; + + +/** + * @brief The model of a %BLE Characteristic. + * + * A BLE Characteristic is an identified value container that manages a value. It is exposed by a BLE server and + * can be read and written to by a %BLE client. + */ +class BLECharacteristic { +public: + BLECharacteristic(const char* uuid, uint32_t properties = 0); + BLECharacteristic(BLEUUID uuid, uint32_t properties = 0); + virtual ~BLECharacteristic(); + + void addDescriptor(BLEDescriptor* pDescriptor); + BLEDescriptor* getDescriptorByUUID(const char* descriptorUUID); + BLEDescriptor* getDescriptorByUUID(BLEUUID descriptorUUID); + BLEUUID getUUID(); + std::string getValue(); + uint8_t* getData(); + + void indicate(); + void notify(bool is_notification = true); + void setBroadcastProperty(bool value); + void setCallbacks(BLECharacteristicCallbacks* pCallbacks); + void setIndicateProperty(bool value); + void setNotifyProperty(bool value); + void setReadProperty(bool value); + void setValue(uint8_t* data, size_t size); + void setValue(std::string value); + void setValue(uint16_t& data16); + void setValue(uint32_t& data32); + void setValue(int& data32); + void setValue(float& data32); + void setValue(double& data64); + void setWriteProperty(bool value); + void setWriteNoResponseProperty(bool value); + std::string toString(); + uint16_t getHandle(); + void setAccessPermissions(esp_gatt_perm_t perm); + + static const uint32_t PROPERTY_READ = 1<<0; + static const uint32_t PROPERTY_WRITE = 1<<1; + static const uint32_t PROPERTY_NOTIFY = 1<<2; + static const uint32_t PROPERTY_BROADCAST = 1<<3; + static const uint32_t PROPERTY_INDICATE = 1<<4; + static const uint32_t PROPERTY_WRITE_NR = 1<<5; + + static const uint32_t indicationTimeout = 1000; + +private: + + friend class BLEServer; + friend class BLEService; + friend class BLEDescriptor; + friend class BLECharacteristicMap; + + BLEUUID m_bleUUID; + BLEDescriptorMap m_descriptorMap; + uint16_t m_handle; + esp_gatt_char_prop_t m_properties; + BLECharacteristicCallbacks* m_pCallbacks; + BLEService* m_pService; + BLEValue m_value; + esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE; + + void handleGATTServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* param); + + void executeCreate(BLEService* pService); + esp_gatt_char_prop_t getProperties(); + BLEService* getService(); + void setHandle(uint16_t handle); + FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); + FreeRTOS::Semaphore m_semaphoreConfEvt = FreeRTOS::Semaphore("ConfEvt"); + FreeRTOS::Semaphore m_semaphoreSetValue = FreeRTOS::Semaphore("SetValue"); +}; // BLECharacteristic + + +/** + * @brief Callbacks that can be associated with a %BLE characteristic to inform of events. + * + * When a server application creates a %BLE characteristic, we may wish to be informed when there is either + * a read or write request to the characteristic's value. An application can register a + * sub-classed instance of this class and will be notified when such an event happens. + */ +class BLECharacteristicCallbacks { +public: + typedef enum { + SUCCESS_INDICATE, + SUCCESS_NOTIFY, + ERROR_INDICATE_DISABLED, + ERROR_NOTIFY_DISABLED, + ERROR_GATT, + ERROR_NO_CLIENT, + ERROR_INDICATE_TIMEOUT, + ERROR_INDICATE_FAILURE + }Status; + + virtual ~BLECharacteristicCallbacks(); + virtual void onRead(BLECharacteristic* pCharacteristic); + virtual void onWrite(BLECharacteristic* pCharacteristic); + virtual void onNotify(BLECharacteristic* pCharacteristic); + virtual void onStatus(BLECharacteristic* pCharacteristic, Status s, uint32_t code); +}; +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ */ diff --git a/libraries/BLE/src/BLECharacteristicMap.cpp b/libraries/BLE/src/BLECharacteristicMap.cpp new file mode 100644 index 00000000000..6e648fc7cdc --- /dev/null +++ b/libraries/BLE/src/BLECharacteristicMap.cpp @@ -0,0 +1,134 @@ +/* + * BLECharacteristicMap.cpp + * + * Created on: Jun 22, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include "BLEService.h" +#ifdef ARDUINO_ARCH_ESP32 +#include "esp32-hal-log.h" +#endif + + +/** + * @brief Return the characteristic by handle. + * @param [in] handle The handle to look up the characteristic. + * @return The characteristic. + */ +BLECharacteristic* BLECharacteristicMap::getByHandle(uint16_t handle) { + return m_handleMap.at(handle); +} // getByHandle + + +/** + * @brief Return the characteristic by UUID. + * @param [in] UUID The UUID to look up the characteristic. + * @return The characteristic. + */ +BLECharacteristic* BLECharacteristicMap::getByUUID(const char* uuid) { + return getByUUID(BLEUUID(uuid)); +} + + +/** + * @brief Return the characteristic by UUID. + * @param [in] UUID The UUID to look up the characteristic. + * @return The characteristic. + */ +BLECharacteristic* BLECharacteristicMap::getByUUID(BLEUUID uuid) { + for (auto &myPair : m_uuidMap) { + if (myPair.first->getUUID().equals(uuid)) { + return myPair.first; + } + } + //return m_uuidMap.at(uuid.toString()); + return nullptr; +} // getByUUID + + +/** + * @brief Get the first characteristic in the map. + * @return The first characteristic in the map. + */ +BLECharacteristic* BLECharacteristicMap::getFirst() { + m_iterator = m_uuidMap.begin(); + if (m_iterator == m_uuidMap.end()) return nullptr; + BLECharacteristic* pRet = m_iterator->first; + m_iterator++; + return pRet; +} // getFirst + + +/** + * @brief Get the next characteristic in the map. + * @return The next characteristic in the map. + */ +BLECharacteristic* BLECharacteristicMap::getNext() { + if (m_iterator == m_uuidMap.end()) return nullptr; + BLECharacteristic* pRet = m_iterator->first; + m_iterator++; + return pRet; +} // getNext + + +/** + * @brief Pass the GATT server event onwards to each of the characteristics found in the mapping + * @param [in] event + * @param [in] gatts_if + * @param [in] param + */ +void BLECharacteristicMap::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { + // Invoke the handler for every Service we have. + for (auto& myPair : m_uuidMap) { + myPair.first->handleGATTServerEvent(event, gatts_if, param); + } +} // handleGATTServerEvent + + +/** + * @brief Set the characteristic by handle. + * @param [in] handle The handle of the characteristic. + * @param [in] characteristic The characteristic to cache. + * @return N/A. + */ +void BLECharacteristicMap::setByHandle(uint16_t handle, BLECharacteristic* characteristic) { + m_handleMap.insert(std::pair(handle, characteristic)); +} // setByHandle + + +/** + * @brief Set the characteristic by UUID. + * @param [in] uuid The uuid of the characteristic. + * @param [in] characteristic The characteristic to cache. + * @return N/A. + */ +void BLECharacteristicMap::setByUUID(BLECharacteristic* pCharacteristic, BLEUUID uuid) { + m_uuidMap.insert(std::pair(pCharacteristic, uuid.toString())); +} // setByUUID + + +/** + * @brief Return a string representation of the characteristic map. + * @return A string representation of the characteristic map. + */ +std::string BLECharacteristicMap::toString() { + std::string res; + int count = 0; + char hex[5]; + for (auto &myPair: m_uuidMap) { + if (count > 0) {res += "\n";} + snprintf(hex, sizeof(hex), "%04x", myPair.first->getHandle()); + count++; + res += "handle: 0x"; + res += hex; + res += ", uuid: " + myPair.first->getUUID().toString(); + } + return res; +} // toString + + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEClient.cpp b/libraries/BLE/src/BLEClient.cpp new file mode 100644 index 00000000000..436813f859d --- /dev/null +++ b/libraries/BLE/src/BLEClient.cpp @@ -0,0 +1,529 @@ +/* + * BLEDevice.cpp + * + * Created on: Mar 22, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include +#include +#include "BLEClient.h" +#include "BLEUtils.h" +#include "BLEService.h" +#include "GeneralUtils.h" +#include +#include +#include +#include "BLEDevice.h" +#include "esp32-hal-log.h" + +/* + * Design + * ------ + * When we perform a searchService() requests, we are asking the BLE server to return each of the services + * that it exposes. For each service, we received an ESP_GATTC_SEARCH_RES_EVT event which contains details + * of the exposed service including its UUID. + * + * The objects we will invent for a BLEClient will be as follows: + * * BLERemoteService - A model of a remote service. + * * BLERemoteCharacteristic - A model of a remote characteristic + * * BLERemoteDescriptor - A model of a remote descriptor. + * + * Since there is a hierarchical relationship here, we will have the idea that from a BLERemoteService will own + * zero or more remote characteristics and a BLERemoteCharacteristic will own zero or more remote BLEDescriptors. + * + * We will assume that a BLERemoteService contains a map that maps BLEUUIDs to the set of owned characteristics + * and that a BLECharacteristic contains a map that maps BLEUUIDs to the set of owned descriptors. + * + * + */ + +BLEClient::BLEClient() { + m_pClientCallbacks = nullptr; + m_conn_id = ESP_GATT_IF_NONE; + m_gattc_if = ESP_GATT_IF_NONE; + m_haveServices = false; + m_isConnected = false; // Initially, we are flagged as not connected. +} // BLEClient + + +/** + * @brief Destructor. + */ +BLEClient::~BLEClient() { + // We may have allocated service references associated with this client. Before we are finished + // with the client, we must release resources. + for (auto &myPair : m_servicesMap) { + delete myPair.second; + } + m_servicesMap.clear(); +} // ~BLEClient + + +/** + * @brief Clear any existing services. + * + */ +void BLEClient::clearServices() { + log_v(">> clearServices"); + // Delete all the services. + for (auto &myPair : m_servicesMap) { + delete myPair.second; + } + m_servicesMap.clear(); + m_haveServices = false; + log_v("<< clearServices"); +} // clearServices + +/** + * Add overloaded function to ease connect to peer device with not public address + */ +bool BLEClient::connect(BLEAdvertisedDevice* device) { + BLEAddress address = device->getAddress(); + esp_ble_addr_type_t type = device->getAddressType(); + return connect(address, type); +} + +/** + * @brief Connect to the partner (BLE Server). + * @param [in] address The address of the partner. + * @return True on success. + */ +bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) { + log_v(">> connect(%s)", address.toString().c_str()); + +// We need the connection handle that we get from registering the application. We register the app +// and then block on its completion. When the event has arrived, we will have the handle. + m_appId = BLEDevice::m_appId++; + BLEDevice::addPeerDevice(this, true, m_appId); + m_semaphoreRegEvt.take("connect"); + + // clearServices(); // we dont need to delete services since every client is unique? + esp_err_t errRc = ::esp_ble_gattc_app_register(m_appId); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_app_register: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return false; + } + + m_semaphoreRegEvt.wait("connect"); + + m_peerAddress = address; + + // Perform the open connection request against the target BLE Server. + m_semaphoreOpenEvt.take("connect"); + errRc = ::esp_ble_gattc_open( + m_gattc_if, + *getPeerAddress().getNative(), // address + type, // Note: This was added on 2018-04-03 when the latest ESP-IDF was detected to have changed the signature. + 1 // direct connection <-- maybe needs to be changed in case of direct indirect connection??? + ); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return false; + } + + uint32_t rc = m_semaphoreOpenEvt.wait("connect"); // Wait for the connection to complete. + log_v("<< connect(), rc=%d", rc==ESP_GATT_OK); + return rc == ESP_GATT_OK; +} // connect + + +/** + * @brief Disconnect from the peer. + * @return N/A. + */ +void BLEClient::disconnect() { + log_v(">> disconnect()"); + esp_err_t errRc = ::esp_ble_gattc_close(getGattcIf(), getConnId()); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_close: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + log_v("<< disconnect()"); +} // disconnect + + +/** + * @brief Handle GATT Client events + */ +void BLEClient::gattClientEventHandler( + esp_gattc_cb_event_t event, + esp_gatt_if_t gattc_if, + esp_ble_gattc_cb_param_t* evtParam) { + + log_d("gattClientEventHandler [esp_gatt_if: %d] ... %s", + gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str()); + + // Execute handler code based on the type of event received. + switch(event) { + + case ESP_GATTC_SRVC_CHG_EVT: + log_i("SERVICE CHANGED"); + break; + + case ESP_GATTC_CLOSE_EVT: { + // esp_ble_gattc_app_unregister(m_appId); + // BLEDevice::removePeerDevice(m_gattc_if, true); + break; + } + + // + // ESP_GATTC_DISCONNECT_EVT + // + // disconnect: + // - esp_gatt_status_t status + // - uint16_t conn_id + // - esp_bd_addr_t remote_bda + case ESP_GATTC_DISCONNECT_EVT: { + // If we receive a disconnect event, set the class flag that indicates that we are + // no longer connected. + m_isConnected = false; + if (m_pClientCallbacks != nullptr) { + m_pClientCallbacks->onDisconnect(this); + } + esp_ble_gattc_app_unregister(m_gattc_if); + m_semaphoreOpenEvt.give(ESP_GATT_IF_NONE); + m_semaphoreRssiCmplEvt.give(); + m_semaphoreSearchCmplEvt.give(1); + BLEDevice::removePeerDevice(m_appId, true); + break; + } // ESP_GATTC_DISCONNECT_EVT + + // + // ESP_GATTC_OPEN_EVT + // + // open: + // - esp_gatt_status_t status + // - uint16_t conn_id + // - esp_bd_addr_t remote_bda + // + case ESP_GATTC_OPEN_EVT: { + m_conn_id = evtParam->open.conn_id; + if (m_pClientCallbacks != nullptr) { + m_pClientCallbacks->onConnect(this); + } + if (evtParam->open.status == ESP_GATT_OK) { + m_isConnected = true; // Flag us as connected. + } + m_semaphoreOpenEvt.give(evtParam->open.status); + break; + } // ESP_GATTC_OPEN_EVT + + + // + // ESP_GATTC_REG_EVT + // + // reg: + // esp_gatt_status_t status + // uint16_t app_id + // + case ESP_GATTC_REG_EVT: { + m_gattc_if = gattc_if; + m_semaphoreRegEvt.give(); + break; + } // ESP_GATTC_REG_EVT + + case ESP_GATTC_CFG_MTU_EVT: + if(evtParam->cfg_mtu.status != ESP_GATT_OK) { + log_e("Config mtu failed"); + } + m_mtu = evtParam->cfg_mtu.mtu; + break; + + case ESP_GATTC_CONNECT_EVT: { + BLEDevice::updatePeerDevice(this, true, m_gattc_if); + esp_err_t errRc = esp_ble_gattc_send_mtu_req(gattc_if, evtParam->connect.conn_id); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_send_mtu_req: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + if(BLEDevice::m_securityLevel){ + esp_ble_set_encryption(evtParam->connect.remote_bda, BLEDevice::m_securityLevel); + } +#endif // CONFIG_BLE_SMP_ENABLE + break; + } // ESP_GATTC_CONNECT_EVT + + // + // ESP_GATTC_SEARCH_CMPL_EVT + // + // search_cmpl: + // - esp_gatt_status_t status + // - uint16_t conn_id + // + case ESP_GATTC_SEARCH_CMPL_EVT: { + esp_ble_gattc_cb_param_t* p_data = (esp_ble_gattc_cb_param_t*)evtParam; + if (p_data->search_cmpl.status != ESP_GATT_OK){ + log_e("search service failed, error status = %x", p_data->search_cmpl.status); + break; + } +#ifndef ARDUINO_ARCH_ESP32 +// commented out just for now to keep backward compatibility + // if(p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_REMOTE_DEVICE) { + // log_i("Get service information from remote device"); + // } else if (p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_NVS_FLASH) { + // log_i("Get service information from flash"); + // } else { + // log_i("unknown service source"); + // } +#endif + m_semaphoreSearchCmplEvt.give(0); + break; + } // ESP_GATTC_SEARCH_CMPL_EVT + + + // + // ESP_GATTC_SEARCH_RES_EVT + // + // search_res: + // - uint16_t conn_id + // - uint16_t start_handle + // - uint16_t end_handle + // - esp_gatt_id_t srvc_id + // + case ESP_GATTC_SEARCH_RES_EVT: { + BLEUUID uuid = BLEUUID(evtParam->search_res.srvc_id); + BLERemoteService* pRemoteService = new BLERemoteService( + evtParam->search_res.srvc_id, + this, + evtParam->search_res.start_handle, + evtParam->search_res.end_handle + ); + m_servicesMap.insert(std::pair(uuid.toString(), pRemoteService)); + m_servicesMapByInstID.insert(std::pair(pRemoteService, evtParam->search_res.srvc_id.inst_id)); + break; + } // ESP_GATTC_SEARCH_RES_EVT + + + default: { + break; + } + } // Switch + + // Pass the request on to all services. + for (auto &myPair : m_servicesMap) { + myPair.second->gattClientEventHandler(event, gattc_if, evtParam); + } + +} // gattClientEventHandler + + +uint16_t BLEClient::getConnId() { + return m_conn_id; +} // getConnId + + + +esp_gatt_if_t BLEClient::getGattcIf() { + return m_gattc_if; +} // getGattcIf + + +/** + * @brief Retrieve the address of the peer. + * + * Returns the Bluetooth device address of the %BLE peer to which this client is connected. + */ +BLEAddress BLEClient::getPeerAddress() { + return m_peerAddress; +} // getAddress + + +/** + * @brief Ask the BLE server for the RSSI value. + * @return The RSSI value. + */ +int BLEClient::getRssi() { + log_v(">> getRssi()"); + if (!isConnected()) { + log_v("<< getRssi(): Not connected"); + return 0; + } + // We make the API call to read the RSSI value which is an asynchronous operation. We expect to receive + // an ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT to indicate completion. + // + m_semaphoreRssiCmplEvt.take("getRssi"); + esp_err_t rc = ::esp_ble_gap_read_rssi(*getPeerAddress().getNative()); + if (rc != ESP_OK) { + log_e("<< getRssi: esp_ble_gap_read_rssi: rc=%d %s", rc, GeneralUtils::errorToString(rc)); + return 0; + } + int rssiValue = m_semaphoreRssiCmplEvt.wait("getRssi"); + log_v("<< getRssi(): %d", rssiValue); + return rssiValue; +} // getRssi + + +/** + * @brief Get the service BLE Remote Service instance corresponding to the uuid. + * @param [in] uuid The UUID of the service being sought. + * @return A reference to the Service or nullptr if don't know about it. + */ +BLERemoteService* BLEClient::getService(const char* uuid) { + return getService(BLEUUID(uuid)); +} // getService + + +/** + * @brief Get the service object corresponding to the uuid. + * @param [in] uuid The UUID of the service being sought. + * @return A reference to the Service or nullptr if don't know about it. + * @throws BLEUuidNotFound + */ +BLERemoteService* BLEClient::getService(BLEUUID uuid) { + log_v(">> getService: uuid: %s", uuid.toString().c_str()); +// Design +// ------ +// We wish to retrieve the service given its UUID. It is possible that we have not yet asked the +// device what services it has in which case we have nothing to match against. If we have not +// asked the device about its services, then we do that now. Once we get the results we can then +// examine the services map to see if it has the service we are looking for. + if (!m_haveServices) { + getServices(); + } + std::string uuidStr = uuid.toString(); + for (auto &myPair : m_servicesMap) { + if (myPair.first == uuidStr) { + log_v("<< getService: found the service with uuid: %s", uuid.toString().c_str()); + return myPair.second; + } + } // End of each of the services. + log_v("<< getService: not found"); + return nullptr; +} // getService + + +/** + * @brief Ask the remote %BLE server for its services. + * A %BLE Server exposes a set of services for its partners. Here we ask the server for its set of + * services and wait until we have received them all. + * @return N/A + */ +std::map* BLEClient::getServices() { +/* + * Design + * ------ + * We invoke esp_ble_gattc_search_service. This will request a list of the service exposed by the + * peer BLE partner to be returned as events. Each event will be an an instance of ESP_GATTC_SEARCH_RES_EVT + * and will culminate with an ESP_GATTC_SEARCH_CMPL_EVT when all have been received. + */ + log_v(">> getServices"); +// TODO implement retrieving services from cache + clearServices(); // Clear any services that may exist. + + esp_err_t errRc = esp_ble_gattc_search_service( + getGattcIf(), + getConnId(), + NULL // Filter UUID + ); + + m_semaphoreSearchCmplEvt.take("getServices"); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_search_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return &m_servicesMap; + } + // If sucessfull, remember that we now have services. + m_haveServices = (m_semaphoreSearchCmplEvt.wait("getServices") == 0); + log_v("<< getServices"); + return &m_servicesMap; +} // getServices + + +/** + * @brief Get the value of a specific characteristic associated with a specific service. + * @param [in] serviceUUID The service that owns the characteristic. + * @param [in] characteristicUUID The characteristic whose value we wish to read. + * @throws BLEUuidNotFound + */ +std::string BLEClient::getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID) { + log_v(">> getValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); + std::string ret = getService(serviceUUID)->getCharacteristic(characteristicUUID)->readValue(); + log_v("<read_rssi_cmpl.rssi); + break; + } // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT + + default: + break; + } +} // handleGAPEvent + + +/** + * @brief Are we connected to a partner? + * @return True if we are connected and false if we are not connected. + */ +bool BLEClient::isConnected() { + return m_isConnected; +} // isConnected + + + + +/** + * @brief Set the callbacks that will be invoked. + */ +void BLEClient::setClientCallbacks(BLEClientCallbacks* pClientCallbacks) { + m_pClientCallbacks = pClientCallbacks; +} // setClientCallbacks + + +/** + * @brief Set the value of a specific characteristic associated with a specific service. + * @param [in] serviceUUID The service that owns the characteristic. + * @param [in] characteristicUUID The characteristic whose value we wish to write. + * @throws BLEUuidNotFound + */ +void BLEClient::setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value) { + log_v(">> setValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); + getService(serviceUUID)->getCharacteristic(characteristicUUID)->writeValue(value); + log_v("<< setValue"); +} // setValue + +uint16_t BLEClient::getMTU() { + return m_mtu; +} + +/** + * @brief Return a string representation of this client. + * @return A string representation of this client. + */ +std::string BLEClient::toString() { + std::string res = "peer address: " + m_peerAddress.toString(); + res += "\nServices:\n"; + for (auto &myPair : m_servicesMap) { + res += myPair.second->toString() + "\n"; + // myPair.second is the value + } + return res; +} // toString + + +#endif // CONFIG_BT_ENABLED diff --git a/libraries/BLE/src/BLEClient.h b/libraries/BLE/src/BLEClient.h new file mode 100644 index 00000000000..75a288e4329 --- /dev/null +++ b/libraries/BLE/src/BLEClient.h @@ -0,0 +1,103 @@ +/* + * BLEDevice.h + * + * Created on: Mar 22, 2017 + * Author: kolban + */ + +#ifndef MAIN_BLEDEVICE_H_ +#define MAIN_BLEDEVICE_H_ + +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include +#include +#include +#include +//#include "BLEExceptions.h" +#include "BLERemoteService.h" +#include "BLEService.h" +#include "BLEAddress.h" +#include "BLEAdvertisedDevice.h" + +class BLERemoteService; +class BLEClientCallbacks; +class BLEAdvertisedDevice; + +/** + * @brief A model of a %BLE client. + */ +class BLEClient { +public: + BLEClient(); + ~BLEClient(); + + bool connect(BLEAdvertisedDevice* device); + bool connect(BLEAddress address, esp_ble_addr_type_t type = BLE_ADDR_TYPE_PUBLIC); // Connect to the remote BLE Server + void disconnect(); // Disconnect from the remote BLE Server + BLEAddress getPeerAddress(); // Get the address of the remote BLE Server + int getRssi(); // Get the RSSI of the remote BLE Server + std::map* getServices(); // Get a map of the services offered by the remote BLE Server + BLERemoteService* getService(const char* uuid); // Get a reference to a specified service offered by the remote BLE server. + BLERemoteService* getService(BLEUUID uuid); // Get a reference to a specified service offered by the remote BLE server. + std::string getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID); // Get the value of a given characteristic at a given service. + + + void handleGAPEvent( + esp_gap_ble_cb_event_t event, + esp_ble_gap_cb_param_t* param); + + bool isConnected(); // Return true if we are connected. + + void setClientCallbacks(BLEClientCallbacks *pClientCallbacks); + void setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value); // Set the value of a given characteristic at a given service. + + std::string toString(); // Return a string representation of this client. + uint16_t getConnId(); + esp_gatt_if_t getGattcIf(); + uint16_t getMTU(); + +uint16_t m_appId; +private: + friend class BLEDevice; + friend class BLERemoteService; + friend class BLERemoteCharacteristic; + friend class BLERemoteDescriptor; + + void gattClientEventHandler( + esp_gattc_cb_event_t event, + esp_gatt_if_t gattc_if, + esp_ble_gattc_cb_param_t* param); + + BLEAddress m_peerAddress = BLEAddress((uint8_t*)"\0\0\0\0\0\0"); // The BD address of the remote server. + uint16_t m_conn_id; +// int m_deviceType; + esp_gatt_if_t m_gattc_if; + bool m_haveServices = false; // Have we previously obtain the set of services from the remote server. + bool m_isConnected = false; // Are we currently connected. + + BLEClientCallbacks* m_pClientCallbacks; + FreeRTOS::Semaphore m_semaphoreRegEvt = FreeRTOS::Semaphore("RegEvt"); + FreeRTOS::Semaphore m_semaphoreOpenEvt = FreeRTOS::Semaphore("OpenEvt"); + FreeRTOS::Semaphore m_semaphoreSearchCmplEvt = FreeRTOS::Semaphore("SearchCmplEvt"); + FreeRTOS::Semaphore m_semaphoreRssiCmplEvt = FreeRTOS::Semaphore("RssiCmplEvt"); + std::map m_servicesMap; + std::map m_servicesMapByInstID; + void clearServices(); // Clear any existing services. + uint16_t m_mtu = 23; +}; // class BLEDevice + + +/** + * @brief Callbacks associated with a %BLE client. + */ +class BLEClientCallbacks { +public: + virtual ~BLEClientCallbacks() {}; + virtual void onConnect(BLEClient *pClient) = 0; + virtual void onDisconnect(BLEClient *pClient) = 0; +}; + +#endif // CONFIG_BT_ENABLED +#endif /* MAIN_BLEDEVICE_H_ */ diff --git a/libraries/BLE/src/BLEDescriptor.cpp b/libraries/BLE/src/BLEDescriptor.cpp new file mode 100644 index 00000000000..96b2de87c95 --- /dev/null +++ b/libraries/BLE/src/BLEDescriptor.cpp @@ -0,0 +1,287 @@ +/* + * BLEDescriptor.cpp + * + * Created on: Jun 22, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include +#include +#include "sdkconfig.h" +#include +#include "BLEService.h" +#include "BLEDescriptor.h" +#include "GeneralUtils.h" +#include "esp32-hal-log.h" + +#define NULL_HANDLE (0xffff) + + +/** + * @brief BLEDescriptor constructor. + */ +BLEDescriptor::BLEDescriptor(const char* uuid, uint16_t len) : BLEDescriptor(BLEUUID(uuid), len) { +} + +/** + * @brief BLEDescriptor constructor. + */ +BLEDescriptor::BLEDescriptor(BLEUUID uuid, uint16_t max_len) { + m_bleUUID = uuid; + m_value.attr_len = 0; // Initial length is 0. + m_value.attr_max_len = max_len; // Maximum length of the data. + m_handle = NULL_HANDLE; // Handle is initially unknown. + m_pCharacteristic = nullptr; // No initial characteristic. + m_pCallback = nullptr; // No initial callback. + + m_value.attr_value = (uint8_t*) malloc(max_len); // Allocate storage for the value. +} // BLEDescriptor + + +/** + * @brief BLEDescriptor destructor. + */ +BLEDescriptor::~BLEDescriptor() { + free(m_value.attr_value); // Release the storage we created in the constructor. +} // ~BLEDescriptor + + +/** + * @brief Execute the creation of the descriptor with the BLE runtime in ESP. + * @param [in] pCharacteristic The characteristic to which to register this descriptor. + */ +void BLEDescriptor::executeCreate(BLECharacteristic* pCharacteristic) { + log_v(">> executeCreate(): %s", toString().c_str()); + + if (m_handle != NULL_HANDLE) { + log_e("Descriptor already has a handle."); + return; + } + + m_pCharacteristic = pCharacteristic; // Save the characteristic associated with this service. + + esp_attr_control_t control; + control.auto_rsp = ESP_GATT_AUTO_RSP; + m_semaphoreCreateEvt.take("executeCreate"); + esp_err_t errRc = ::esp_ble_gatts_add_char_descr( + pCharacteristic->getService()->getHandle(), + getUUID().getNative(), + (esp_gatt_perm_t)m_permissions, + &m_value, + &control); + if (errRc != ESP_OK) { + log_e("<< esp_ble_gatts_add_char_descr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + + m_semaphoreCreateEvt.wait("executeCreate"); + log_v("<< executeCreate"); +} // executeCreate + + +/** + * @brief Get the BLE handle for this descriptor. + * @return The handle for this descriptor. + */ +uint16_t BLEDescriptor::getHandle() { + return m_handle; +} // getHandle + + +/** + * @brief Get the length of the value of this descriptor. + * @return The length (in bytes) of the value of this descriptor. + */ +size_t BLEDescriptor::getLength() { + return m_value.attr_len; +} // getLength + + +/** + * @brief Get the UUID of the descriptor. + */ +BLEUUID BLEDescriptor::getUUID() { + return m_bleUUID; +} // getUUID + + + +/** + * @brief Get the value of this descriptor. + * @return A pointer to the value of this descriptor. + */ +uint8_t* BLEDescriptor::getValue() { + return m_value.attr_value; +} // getValue + + +/** + * @brief Handle GATT server events for the descripttor. + * @param [in] event + * @param [in] gatts_if + * @param [in] param + */ +void BLEDescriptor::handleGATTServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* param) { + switch (event) { + // ESP_GATTS_ADD_CHAR_DESCR_EVT + // + // add_char_descr: + // - esp_gatt_status_t status + // - uint16_t attr_handle + // - uint16_t service_handle + // - esp_bt_uuid_t char_uuid + case ESP_GATTS_ADD_CHAR_DESCR_EVT: { + if (m_pCharacteristic != nullptr && + m_bleUUID.equals(BLEUUID(param->add_char_descr.descr_uuid)) && + m_pCharacteristic->getService()->getHandle() == param->add_char_descr.service_handle && + m_pCharacteristic == m_pCharacteristic->getService()->getLastCreatedCharacteristic()) { + setHandle(param->add_char_descr.attr_handle); + m_semaphoreCreateEvt.give(); + } + break; + } // ESP_GATTS_ADD_CHAR_DESCR_EVT + + // ESP_GATTS_WRITE_EVT - A request to write the value of a descriptor has arrived. + // + // write: + // - uint16_t conn_id + // - uint16_t trans_id + // - esp_bd_addr_t bda + // - uint16_t handle + // - uint16_t offset + // - bool need_rsp + // - bool is_prep + // - uint16_t len + // - uint8_t *value + case ESP_GATTS_WRITE_EVT: { + if (param->write.handle == m_handle) { + setValue(param->write.value, param->write.len); // Set the value of the descriptor. + + if (m_pCallback != nullptr) { // We have completed the write, if there is a user supplied callback handler, invoke it now. + m_pCallback->onWrite(this); // Invoke the onWrite callback handler. + } + } // End of ... this is our handle. + + break; + } // ESP_GATTS_WRITE_EVT + + // ESP_GATTS_READ_EVT - A request to read the value of a descriptor has arrived. + // + // read: + // - uint16_t conn_id + // - uint32_t trans_id + // - esp_bd_addr_t bda + // - uint16_t handle + // - uint16_t offset + // - bool is_long + // - bool need_rsp + // + case ESP_GATTS_READ_EVT: { + if (param->read.handle == m_handle) { // If this event is for this descriptor ... process it + + if (m_pCallback != nullptr) { // If we have a user supplied callback, invoke it now. + m_pCallback->onRead(this); // Invoke the onRead callback method in the callback handler. + } + + } // End of this is our handle + break; + } // ESP_GATTS_READ_EVT + + default: + break; + } // switch event +} // handleGATTServerEvent + + +/** + * @brief Set the callback handlers for this descriptor. + * @param [in] pCallbacks An instance of a callback structure used to define any callbacks for the descriptor. + */ +void BLEDescriptor::setCallbacks(BLEDescriptorCallbacks* pCallback) { + log_v(">> setCallbacks: 0x%x", (uint32_t) pCallback); + m_pCallback = pCallback; + log_v("<< setCallbacks"); +} // setCallbacks + + +/** + * @brief Set the handle of this descriptor. + * Set the handle of this descriptor to be the supplied value. + * @param [in] handle The handle to be associated with this descriptor. + * @return N/A. + */ +void BLEDescriptor::setHandle(uint16_t handle) { + log_v(">> setHandle(0x%.2x): Setting descriptor handle to be 0x%.2x", handle, handle); + m_handle = handle; + log_v("<< setHandle()"); +} // setHandle + + +/** + * @brief Set the value of the descriptor. + * @param [in] data The data to set for the descriptor. + * @param [in] length The length of the data in bytes. + */ +void BLEDescriptor::setValue(uint8_t* data, size_t length) { + if (length > ESP_GATT_MAX_ATTR_LEN) { + log_e("Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); + return; + } + m_value.attr_len = length; + memcpy(m_value.attr_value, data, length); +} // setValue + + +/** + * @brief Set the value of the descriptor. + * @param [in] value The value of the descriptor in string form. + */ +void BLEDescriptor::setValue(std::string value) { + setValue((uint8_t*) value.data(), value.length()); +} // setValue + +void BLEDescriptor::setAccessPermissions(esp_gatt_perm_t perm) { + m_permissions = perm; +} + +/** + * @brief Return a string representation of the descriptor. + * @return A string representation of the descriptor. + */ +std::string BLEDescriptor::toString() { + char hex[5]; + snprintf(hex, sizeof(hex), "%04x", m_handle); + std::string res = "UUID: " + m_bleUUID.toString() + ", handle: 0x" + hex; + return res; +} // toString + + +BLEDescriptorCallbacks::~BLEDescriptorCallbacks() {} + +/** + * @brief Callback function to support a read request. + * @param [in] pDescriptor The descriptor that is the source of the event. + */ +void BLEDescriptorCallbacks::onRead(BLEDescriptor* pDescriptor) { + log_d("BLEDescriptorCallbacks", ">> onRead: default"); + log_d("BLEDescriptorCallbacks", "<< onRead"); +} // onRead + + +/** + * @brief Callback function to support a write request. + * @param [in] pDescriptor The descriptor that is the source of the event. + */ +void BLEDescriptorCallbacks::onWrite(BLEDescriptor* pDescriptor) { + log_d("BLEDescriptorCallbacks", ">> onWrite: default"); + log_d("BLEDescriptorCallbacks", "<< onWrite"); +} // onWrite + + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEDescriptor.h b/libraries/BLE/src/BLEDescriptor.h new file mode 100644 index 00000000000..03cc5791727 --- /dev/null +++ b/libraries/BLE/src/BLEDescriptor.h @@ -0,0 +1,77 @@ +/* + * BLEDescriptor.h + * + * Created on: Jun 22, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ +#define COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include "BLEUUID.h" +#include "BLECharacteristic.h" +#include +#include "FreeRTOS.h" + +class BLEService; +class BLECharacteristic; +class BLEDescriptorCallbacks; + +/** + * @brief A model of a %BLE descriptor. + */ +class BLEDescriptor { +public: + BLEDescriptor(const char* uuid, uint16_t max_len = 100); + BLEDescriptor(BLEUUID uuid, uint16_t max_len = 100); + virtual ~BLEDescriptor(); + + uint16_t getHandle(); // Get the handle of the descriptor. + size_t getLength(); // Get the length of the value of the descriptor. + BLEUUID getUUID(); // Get the UUID of the descriptor. + uint8_t* getValue(); // Get a pointer to the value of the descriptor. + void handleGATTServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* param); + + void setAccessPermissions(esp_gatt_perm_t perm); // Set the permissions of the descriptor. + void setCallbacks(BLEDescriptorCallbacks* pCallbacks); // Set callbacks to be invoked for the descriptor. + void setValue(uint8_t* data, size_t size); // Set the value of the descriptor as a pointer to data. + void setValue(std::string value); // Set the value of the descriptor as a data buffer. + + std::string toString(); // Convert the descriptor to a string representation. + +private: + friend class BLEDescriptorMap; + friend class BLECharacteristic; + BLEUUID m_bleUUID; + uint16_t m_handle; + BLEDescriptorCallbacks* m_pCallback; + BLECharacteristic* m_pCharacteristic; + esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE; + FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); + esp_attr_value_t m_value; + + void executeCreate(BLECharacteristic* pCharacteristic); + void setHandle(uint16_t handle); +}; // BLEDescriptor + + +/** + * @brief Callbacks that can be associated with a %BLE descriptors to inform of events. + * + * When a server application creates a %BLE descriptor, we may wish to be informed when there is either + * a read or write request to the descriptors value. An application can register a + * sub-classed instance of this class and will be notified when such an event happens. + */ +class BLEDescriptorCallbacks { +public: + virtual ~BLEDescriptorCallbacks(); + virtual void onRead(BLEDescriptor* pDescriptor); + virtual void onWrite(BLEDescriptor* pDescriptor); +}; +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ */ diff --git a/libraries/BLE/src/BLEDescriptorMap.cpp b/libraries/BLE/src/BLEDescriptorMap.cpp new file mode 100644 index 00000000000..0b5d3175a9d --- /dev/null +++ b/libraries/BLE/src/BLEDescriptorMap.cpp @@ -0,0 +1,148 @@ +/* + * BLEDescriptorMap.cpp + * + * Created on: Jun 22, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include "BLECharacteristic.h" +#include "BLEDescriptor.h" +#include // ESP32 BLE +#ifdef ARDUINO_ARCH_ESP32 +#include "esp32-hal-log.h" +#endif + +/** + * @brief Return the descriptor by UUID. + * @param [in] UUID The UUID to look up the descriptor. + * @return The descriptor. If not present, then nullptr is returned. + */ +BLEDescriptor* BLEDescriptorMap::getByUUID(const char* uuid) { + return getByUUID(BLEUUID(uuid)); +} + + +/** + * @brief Return the descriptor by UUID. + * @param [in] UUID The UUID to look up the descriptor. + * @return The descriptor. If not present, then nullptr is returned. + */ +BLEDescriptor* BLEDescriptorMap::getByUUID(BLEUUID uuid) { + for (auto &myPair : m_uuidMap) { + if (myPair.first->getUUID().equals(uuid)) { + return myPair.first; + } + } + //return m_uuidMap.at(uuid.toString()); + return nullptr; +} // getByUUID + + +/** + * @brief Return the descriptor by handle. + * @param [in] handle The handle to look up the descriptor. + * @return The descriptor. + */ +BLEDescriptor* BLEDescriptorMap::getByHandle(uint16_t handle) { + return m_handleMap.at(handle); +} // getByHandle + + +/** + * @brief Set the descriptor by UUID. + * @param [in] uuid The uuid of the descriptor. + * @param [in] characteristic The descriptor to cache. + * @return N/A. + */ +void BLEDescriptorMap::setByUUID(const char* uuid, BLEDescriptor* pDescriptor){ + m_uuidMap.insert(std::pair(pDescriptor, uuid)); +} // setByUUID + + + +/** + * @brief Set the descriptor by UUID. + * @param [in] uuid The uuid of the descriptor. + * @param [in] characteristic The descriptor to cache. + * @return N/A. + */ +void BLEDescriptorMap::setByUUID(BLEUUID uuid, BLEDescriptor* pDescriptor) { + m_uuidMap.insert(std::pair(pDescriptor, uuid.toString())); +} // setByUUID + + +/** + * @brief Set the descriptor by handle. + * @param [in] handle The handle of the descriptor. + * @param [in] descriptor The descriptor to cache. + * @return N/A. + */ +void BLEDescriptorMap::setByHandle(uint16_t handle, BLEDescriptor* pDescriptor) { + m_handleMap.insert(std::pair(handle, pDescriptor)); +} // setByHandle + + +/** + * @brief Return a string representation of the descriptor map. + * @return A string representation of the descriptor map. + */ +std::string BLEDescriptorMap::toString() { + std::string res; + char hex[5]; + int count = 0; + for (auto &myPair : m_uuidMap) { + if (count > 0) {res += "\n";} + snprintf(hex, sizeof(hex), "%04x", myPair.first->getHandle()); + count++; + res += "handle: 0x"; + res += hex; + res += ", uuid: " + myPair.first->getUUID().toString(); + } + return res; +} // toString + + +/** + * @breif Pass the GATT server event onwards to each of the descriptors found in the mapping + * @param [in] event + * @param [in] gatts_if + * @param [in] param + */ +void BLEDescriptorMap::handleGATTServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* param) { + // Invoke the handler for every descriptor we have. + for (auto &myPair : m_uuidMap) { + myPair.first->handleGATTServerEvent(event, gatts_if, param); + } +} // handleGATTServerEvent + + +/** + * @brief Get the first descriptor in the map. + * @return The first descriptor in the map. + */ +BLEDescriptor* BLEDescriptorMap::getFirst() { + m_iterator = m_uuidMap.begin(); + if (m_iterator == m_uuidMap.end()) return nullptr; + BLEDescriptor* pRet = m_iterator->first; + m_iterator++; + return pRet; +} // getFirst + + +/** + * @brief Get the next descriptor in the map. + * @return The next descriptor in the map. + */ +BLEDescriptor* BLEDescriptorMap::getNext() { + if (m_iterator == m_uuidMap.end()) return nullptr; + BLEDescriptor* pRet = m_iterator->first; + m_iterator++; + return pRet; +} // getNext +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEDevice.cpp b/libraries/BLE/src/BLEDevice.cpp new file mode 100644 index 00000000000..d828b4e1946 --- /dev/null +++ b/libraries/BLE/src/BLEDevice.cpp @@ -0,0 +1,643 @@ +/* + * BLE.cpp + * + * Created on: Mar 16, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include +#include +#include +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 ESP-IDF +#include // Part of C++ Standard library +#include // Part of C++ Standard library +#include // Part of C++ Standard library + +#include "BLEDevice.h" +#include "BLEClient.h" +#include "BLEUtils.h" +#include "GeneralUtils.h" + +#if defined(ARDUINO_ARCH_ESP32) +#include "esp32-hal-bt.h" +#endif + +#include "esp32-hal-log.h" + + +/** + * Singletons for the BLEDevice. + */ +BLEServer* BLEDevice::m_pServer = nullptr; +BLEScan* BLEDevice::m_pScan = nullptr; +BLEClient* BLEDevice::m_pClient = nullptr; +bool initialized = false; +esp_ble_sec_act_t BLEDevice::m_securityLevel = (esp_ble_sec_act_t)0; +BLESecurityCallbacks* BLEDevice::m_securityCallbacks = nullptr; +uint16_t BLEDevice::m_localMTU = 23; // not sure if this variable is useful +BLEAdvertising* BLEDevice::m_bleAdvertising = nullptr; +uint16_t BLEDevice::m_appId = 0; +std::map BLEDevice::m_connectedClientsMap; +gap_event_handler BLEDevice::m_customGapHandler = nullptr; +gattc_event_handler BLEDevice::m_customGattcHandler = nullptr; +gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; + +/** + * @brief Create a new instance of a client. + * @return A new instance of the client. + */ +/* STATIC */ BLEClient* BLEDevice::createClient() { + log_v(">> createClient"); +#ifndef CONFIG_GATTC_ENABLE // Check that BLE GATTC is enabled in make menuconfig + log_e("BLE GATTC is not enabled - CONFIG_GATTC_ENABLE not defined"); + abort(); +#endif // CONFIG_GATTC_ENABLE + m_pClient = new BLEClient(); + log_v("<< createClient"); + return m_pClient; +} // createClient + + +/** + * @brief Create a new instance of a server. + * @return A new instance of the server. + */ +/* STATIC */ BLEServer* BLEDevice::createServer() { + log_v(">> createServer"); +#ifndef CONFIG_GATTS_ENABLE // Check that BLE GATTS is enabled in make menuconfig + log_e("BLE GATTS is not enabled - CONFIG_GATTS_ENABLE not defined"); + abort(); +#endif // CONFIG_GATTS_ENABLE + m_pServer = new BLEServer(); + m_pServer->createApp(m_appId++); + log_v("<< createServer"); + return m_pServer; +} // createServer + + +/** + * @brief Handle GATT server events. + * + * @param [in] event The event that has been newly received. + * @param [in] gatts_if The connection to the GATT interface. + * @param [in] param Parameters for the event. + */ +/* STATIC */ void BLEDevice::gattServerEventHandler( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* param +) { + log_d("gattServerEventHandler [esp_gatt_if: %d] ... %s", + gatts_if, + BLEUtils::gattServerEventTypeToString(event).c_str()); + + BLEUtils::dumpGattServerEvent(event, gatts_if, param); + + switch (event) { + case ESP_GATTS_CONNECT_EVT: { +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + if(BLEDevice::m_securityLevel){ + esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel); + } +#endif // CONFIG_BLE_SMP_ENABLE + break; + } // ESP_GATTS_CONNECT_EVT + + default: { + break; + } + } // switch + + + if (BLEDevice::m_pServer != nullptr) { + BLEDevice::m_pServer->handleGATTServerEvent(event, gatts_if, param); + } + + if(m_customGattsHandler != nullptr) { + m_customGattsHandler(event, gatts_if, param); + } + +} // gattServerEventHandler + + +/** + * @brief Handle GATT client events. + * + * Handler for the GATT client events. + * + * @param [in] event + * @param [in] gattc_if + * @param [in] param + */ +/* STATIC */ void BLEDevice::gattClientEventHandler( + esp_gattc_cb_event_t event, + esp_gatt_if_t gattc_if, + esp_ble_gattc_cb_param_t* param) { + + log_d("gattClientEventHandler [esp_gatt_if: %d] ... %s", + gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str()); + BLEUtils::dumpGattClientEvent(event, gattc_if, param); + + switch(event) { + case ESP_GATTC_CONNECT_EVT: { +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + if(BLEDevice::m_securityLevel){ + esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel); + } +#endif // CONFIG_BLE_SMP_ENABLE + break; + } // ESP_GATTS_CONNECT_EVT + + default: + break; + } // switch + for(auto &myPair : BLEDevice::getPeerDevices(true)) { + conn_status_t conn_status = (conn_status_t)myPair.second; + if(((BLEClient*)conn_status.peer_device)->getGattcIf() == gattc_if || ((BLEClient*)conn_status.peer_device)->getGattcIf() == ESP_GATT_IF_NONE || gattc_if == ESP_GATT_IF_NONE){ + ((BLEClient*)conn_status.peer_device)->gattClientEventHandler(event, gattc_if, param); + } + } + + if(m_customGattcHandler != nullptr) { + m_customGattcHandler(event, gattc_if, param); + } + + +} // gattClientEventHandler + + +/** + * @brief Handle GAP events. + */ +/* STATIC */ void BLEDevice::gapEventHandler( + esp_gap_ble_cb_event_t event, + esp_ble_gap_cb_param_t *param) { + + BLEUtils::dumpGapEvent(event, param); + + switch(event) { + + case ESP_GAP_BLE_OOB_REQ_EVT: /* OOB request event */ + log_i("ESP_GAP_BLE_OOB_REQ_EVT"); + break; + case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ + log_i("ESP_GAP_BLE_LOCAL_IR_EVT"); + break; + case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ + log_i("ESP_GAP_BLE_LOCAL_ER_EVT"); + break; + case ESP_GAP_BLE_NC_REQ_EVT: /* NUMERIC CONFIRMATION */ + log_i("ESP_GAP_BLE_NC_REQ_EVT"); +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + if(BLEDevice::m_securityCallbacks != nullptr){ + esp_ble_confirm_reply(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onConfirmPIN(param->ble_security.key_notif.passkey)); + } +#endif // CONFIG_BLE_SMP_ENABLE + break; + case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ + log_i("ESP_GAP_BLE_PASSKEY_REQ_EVT: "); + // esp_log_buffer_hex(m_remote_bda, sizeof(m_remote_bda)); +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + if(BLEDevice::m_securityCallbacks != nullptr){ + esp_ble_passkey_reply(param->ble_security.ble_req.bd_addr, true, BLEDevice::m_securityCallbacks->onPassKeyRequest()); + } +#endif // CONFIG_BLE_SMP_ENABLE + break; + /* + * TODO should we add white/black list comparison? + */ + case ESP_GAP_BLE_SEC_REQ_EVT: + /* send the positive(true) security response to the peer device to accept the security request. + If not accept the security request, should sent the security response with negative(false) accept value*/ + log_i("ESP_GAP_BLE_SEC_REQ_EVT"); +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + if(BLEDevice::m_securityCallbacks!=nullptr){ + esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onSecurityRequest()); + } + else{ + esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true); + } +#endif // CONFIG_BLE_SMP_ENABLE + break; + /* + * + */ + case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: //the app will receive this evt when the IO has Output capability and the peer device IO has Input capability. + //display the passkey number to the user to input it in the peer deivce within 30 seconds + log_i("ESP_GAP_BLE_PASSKEY_NOTIF_EVT"); +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + log_i("passKey = %d", param->ble_security.key_notif.passkey); + if(BLEDevice::m_securityCallbacks!=nullptr){ + BLEDevice::m_securityCallbacks->onPassKeyNotify(param->ble_security.key_notif.passkey); + } +#endif // CONFIG_BLE_SMP_ENABLE + break; + case ESP_GAP_BLE_KEY_EVT: + //shows the ble key type info share with peer device to the user. + log_d("ESP_GAP_BLE_KEY_EVT"); +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + log_i("key type = %s", BLESecurity::esp_key_type_to_str(param->ble_security.ble_key.key_type)); +#endif // CONFIG_BLE_SMP_ENABLE + break; + case ESP_GAP_BLE_AUTH_CMPL_EVT: + log_i("ESP_GAP_BLE_AUTH_CMPL_EVT"); +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + if(BLEDevice::m_securityCallbacks != nullptr){ + BLEDevice::m_securityCallbacks->onAuthenticationComplete(param->ble_security.auth_cmpl); + } +#endif // CONFIG_BLE_SMP_ENABLE + break; + default: { + break; + } + } // switch + + if (BLEDevice::m_pClient != nullptr) { + BLEDevice::m_pClient->handleGAPEvent(event, param); + } + + if (BLEDevice::m_pScan != nullptr) { + BLEDevice::getScan()->handleGAPEvent(event, param); + } + + if(m_bleAdvertising != nullptr) { + BLEDevice::getAdvertising()->handleGAPEvent(event, param); + } + + if(m_customGapHandler != nullptr) { + BLEDevice::m_customGapHandler(event, param); + } + +} // gapEventHandler + + +/** + * @brief Get the BLE device address. + * @return The BLE device address. + */ +/* STATIC*/ BLEAddress BLEDevice::getAddress() { + const uint8_t* bdAddr = esp_bt_dev_get_address(); + esp_bd_addr_t addr; + memcpy(addr, bdAddr, sizeof(addr)); + return BLEAddress(addr); +} // getAddress + + +/** + * @brief Retrieve the Scan object that we use for scanning. + * @return The scanning object reference. This is a singleton object. The caller should not + * try and release/delete it. + */ +/* STATIC */ BLEScan* BLEDevice::getScan() { + //log_v(">> getScan"); + if (m_pScan == nullptr) { + m_pScan = new BLEScan(); + //log_d(" - creating a new scan object"); + } + //log_v("<< getScan: Returning object at 0x%x", (uint32_t)m_pScan); + return m_pScan; +} // getScan + + +/** + * @brief Get the value of a characteristic of a service on a remote device. + * @param [in] bdAddress + * @param [in] serviceUUID + * @param [in] characteristicUUID + */ +/* STATIC */ std::string BLEDevice::getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID) { + log_v(">> getValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); + BLEClient* pClient = createClient(); + pClient->connect(bdAddress); + std::string ret = pClient->getValue(serviceUUID, characteristicUUID); + pClient->disconnect(); + log_v("<< getValue"); + return ret; +} // getValue + + +/** + * @brief Initialize the %BLE environment. + * @param deviceName The device name of the device. + */ +/* STATIC */ void BLEDevice::init(std::string deviceName) { + if(!initialized){ + initialized = true; // Set the initialization flag to ensure we are only initialized once. + + esp_err_t errRc = ESP_OK; +#ifdef ARDUINO_ARCH_ESP32 + if (!btStart()) { + errRc = ESP_FAIL; + return; + } +#else + errRc = ::nvs_flash_init(); + if (errRc != ESP_OK) { + log_e("nvs_flash_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + +#ifndef CLASSIC_BT_ENABLED + esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT); +#endif + esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); + errRc = esp_bt_controller_init(&bt_cfg); + if (errRc != ESP_OK) { + log_e("esp_bt_controller_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + +#ifndef CLASSIC_BT_ENABLED + errRc = esp_bt_controller_enable(ESP_BT_MODE_BLE); + if (errRc != ESP_OK) { + log_e("esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } +#else + errRc = esp_bt_controller_enable(ESP_BT_MODE_BTDM); + if (errRc != ESP_OK) { + log_e("esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } +#endif +#endif + + esp_bluedroid_status_t bt_state = esp_bluedroid_get_status(); + if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED) { + errRc = esp_bluedroid_init(); + if (errRc != ESP_OK) { + log_e("esp_bluedroid_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + } + + if (bt_state != ESP_BLUEDROID_STATUS_ENABLED) { + errRc = esp_bluedroid_enable(); + if (errRc != ESP_OK) { + log_e("esp_bluedroid_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + } + + errRc = esp_ble_gap_register_callback(BLEDevice::gapEventHandler); + if (errRc != ESP_OK) { + log_e("esp_ble_gap_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + +#ifdef CONFIG_GATTC_ENABLE // Check that BLE client is configured in make menuconfig + errRc = esp_ble_gattc_register_callback(BLEDevice::gattClientEventHandler); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } +#endif // CONFIG_GATTC_ENABLE + +#ifdef CONFIG_GATTS_ENABLE // Check that BLE server is configured in make menuconfig + errRc = esp_ble_gatts_register_callback(BLEDevice::gattServerEventHandler); + if (errRc != ESP_OK) { + log_e("esp_ble_gatts_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } +#endif // CONFIG_GATTS_ENABLE + + errRc = ::esp_ble_gap_set_device_name(deviceName.c_str()); + if (errRc != ESP_OK) { + log_e("esp_ble_gap_set_device_name: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + }; + +#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig + esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE; + errRc = ::esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); + if (errRc != ESP_OK) { + log_e("esp_ble_gap_set_security_param: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + }; +#endif // CONFIG_BLE_SMP_ENABLE + } + vTaskDelay(200 / portTICK_PERIOD_MS); // Delay for 200 msecs as a workaround to an apparent Arduino environment issue. +} // init + + +/** + * @brief Set the transmission power. + * The power level can be one of: + * * ESP_PWR_LVL_N14 + * * ESP_PWR_LVL_N11 + * * ESP_PWR_LVL_N8 + * * ESP_PWR_LVL_N5 + * * ESP_PWR_LVL_N2 + * * ESP_PWR_LVL_P1 + * * ESP_PWR_LVL_P4 + * * ESP_PWR_LVL_P7 + * @param [in] powerLevel. + */ +/* STATIC */ void BLEDevice::setPower(esp_power_level_t powerLevel) { + log_v(">> setPower: %d", powerLevel); + esp_err_t errRc = ::esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_DEFAULT, powerLevel); + if (errRc != ESP_OK) { + log_e("esp_ble_tx_power_set: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + }; + log_v("<< setPower"); +} // setPower + + +/** + * @brief Set the value of a characteristic of a service on a remote device. + * @param [in] bdAddress + * @param [in] serviceUUID + * @param [in] characteristicUUID + */ +/* STATIC */ void BLEDevice::setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value) { + log_v(">> setValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); + BLEClient* pClient = createClient(); + pClient->connect(bdAddress); + pClient->setValue(serviceUUID, characteristicUUID, value); + pClient->disconnect(); +} // setValue + + +/** + * @brief Return a string representation of the nature of this device. + * @return A string representation of the nature of this device. + */ +/* STATIC */ std::string BLEDevice::toString() { + std::string res = "BD Address: " + getAddress().toString(); + return res; +} // toString + + +/** + * @brief Add an entry to the BLE white list. + * @param [in] address The address to add to the white list. + */ +void BLEDevice::whiteListAdd(BLEAddress address) { + log_v(">> whiteListAdd: %s", address.toString().c_str()); + esp_err_t errRc = esp_ble_gap_update_whitelist(true, *address.getNative()); // True to add an entry. + if (errRc != ESP_OK) { + log_e("esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } + log_v("<< whiteListAdd"); +} // whiteListAdd + + +/** + * @brief Remove an entry from the BLE white list. + * @param [in] address The address to remove from the white list. + */ +void BLEDevice::whiteListRemove(BLEAddress address) { + log_v(">> whiteListRemove: %s", address.toString().c_str()); + esp_err_t errRc = esp_ble_gap_update_whitelist(false, *address.getNative()); // False to remove an entry. + if (errRc != ESP_OK) { + log_e("esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } + log_v("<< whiteListRemove"); +} // whiteListRemove + +/* + * @brief Set encryption level that will be negotiated with peer device durng connection + * @param [in] level Requested encryption level + */ +void BLEDevice::setEncryptionLevel(esp_ble_sec_act_t level) { + BLEDevice::m_securityLevel = level; +} + +/* + * @brief Set callbacks that will be used to handle encryption negotiation events and authentication events + * @param [in] cllbacks Pointer to BLESecurityCallbacks class callback + */ +void BLEDevice::setSecurityCallbacks(BLESecurityCallbacks* callbacks) { + BLEDevice::m_securityCallbacks = callbacks; +} + +/* + * @brief Setup local mtu that will be used to negotiate mtu during request from client peer + * @param [in] mtu Value to set local mtu, should be larger than 23 and lower or equal to 517 + */ +esp_err_t BLEDevice::setMTU(uint16_t mtu) { + log_v(">> setLocalMTU: %d", mtu); + esp_err_t err = esp_ble_gatt_set_local_mtu(mtu); + if (err == ESP_OK) { + m_localMTU = mtu; + } else { + log_e("can't set local mtu value: %d", mtu); + } + log_v("<< setLocalMTU"); + return err; +} + +/* + * @brief Get local MTU value set during mtu request or default value + */ +uint16_t BLEDevice::getMTU() { + return m_localMTU; +} + +bool BLEDevice::getInitialized() { + return initialized; +} + +BLEAdvertising* BLEDevice::getAdvertising() { + if(m_bleAdvertising == nullptr) { + m_bleAdvertising = new BLEAdvertising(); + log_i("create advertising"); + } + log_d("get advertising"); + return m_bleAdvertising; +} + +void BLEDevice::startAdvertising() { + log_v(">> startAdvertising"); + getAdvertising()->start(); + log_v("<< startAdvertising"); +} // startAdvertising + +/* multi connect support */ +/* requires a little more work */ +std::map BLEDevice::getPeerDevices(bool _client) { + return m_connectedClientsMap; +} + +BLEClient* BLEDevice::getClientByGattIf(uint16_t conn_id) { + return (BLEClient*)m_connectedClientsMap.find(conn_id)->second.peer_device; +} + +void BLEDevice::updatePeerDevice(void* peer, bool _client, uint16_t conn_id) { + log_d("update conn_id: %d, GATT role: %s", conn_id, _client? "client":"server"); + std::map::iterator it = m_connectedClientsMap.find(ESP_GATT_IF_NONE); + if (it != m_connectedClientsMap.end()) { + std::swap(m_connectedClientsMap[conn_id], it->second); + m_connectedClientsMap.erase(it); + }else{ + it = m_connectedClientsMap.find(conn_id); + if (it != m_connectedClientsMap.end()) { + conn_status_t _st = it->second; + _st.peer_device = peer; + std::swap(m_connectedClientsMap[conn_id], _st); + } + } +} + +void BLEDevice::addPeerDevice(void* peer, bool _client, uint16_t conn_id) { + log_i("add conn_id: %d, GATT role: %s", conn_id, _client? "client":"server"); + conn_status_t status = { + .peer_device = peer, + .connected = true, + .mtu = 23 + }; + + m_connectedClientsMap.insert(std::pair(conn_id, status)); +} + +void BLEDevice::removePeerDevice(uint16_t conn_id, bool _client) { + log_i("remove: %d, GATT role %s", conn_id, _client?"client":"server"); + if(m_connectedClientsMap.find(conn_id) != m_connectedClientsMap.end()) + m_connectedClientsMap.erase(conn_id); +} + +/* multi connect support */ + +/** + * @brief de-Initialize the %BLE environment. + * @param release_memory release the internal BT stack memory + */ +/* STATIC */ void BLEDevice::deinit(bool release_memory) { + if (!initialized) return; + + esp_bluedroid_disable(); + esp_bluedroid_deinit(); + esp_bt_controller_disable(); + esp_bt_controller_deinit(); +#ifdef ARDUINO_ARCH_ESP32 + if (release_memory) { + esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); // <-- require tests because we released classic BT memory and this can cause crash (most likely not, esp-idf takes care of it) + } else { + initialized = false; + } +#endif +} + +void BLEDevice::setCustomGapHandler(gap_event_handler handler) { + m_customGapHandler = handler; +} + +void BLEDevice::setCustomGattcHandler(gattc_event_handler handler) { + m_customGattcHandler = handler; +} + +void BLEDevice::setCustomGattsHandler(gatts_event_handler handler) { + m_customGattsHandler = handler; +} + +#endif // CONFIG_BT_ENABLED diff --git a/libraries/BLE/src/BLEDevice.h b/libraries/BLE/src/BLEDevice.h new file mode 100644 index 00000000000..e9cd40a34a2 --- /dev/null +++ b/libraries/BLE/src/BLEDevice.h @@ -0,0 +1,99 @@ +/* + * BLEDevice.h + * + * Created on: Mar 16, 2017 + * Author: kolban + */ + +#ifndef MAIN_BLEDevice_H_ +#define MAIN_BLEDevice_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include // ESP32 BLE +#include // ESP32 BLE +#include // Part of C++ STL +#include +#include + +#include "BLEServer.h" +#include "BLEClient.h" +#include "BLEUtils.h" +#include "BLEScan.h" +#include "BLEAddress.h" + +/** + * @brief BLE functions. + */ +typedef void (*gap_event_handler)(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param); +typedef void (*gattc_event_handler)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* param); +typedef void (*gatts_event_handler)(esp_gatts_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gatts_cb_param_t* param); + +class BLEDevice { +public: + + static BLEClient* createClient(); // Create a new BLE client. + static BLEServer* createServer(); // Cretae a new BLE server. + static BLEAddress getAddress(); // Retrieve our own local BD address. + static BLEScan* getScan(); // Get the scan object + static std::string getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID); // Get the value of a characteristic of a service on a server. + static void init(std::string deviceName); // Initialize the local BLE environment. + static void setPower(esp_power_level_t powerLevel); // Set our power level. + static void setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value); // Set the value of a characteristic on a service on a server. + static std::string toString(); // Return a string representation of our device. + static void whiteListAdd(BLEAddress address); // Add an entry to the BLE white list. + static void whiteListRemove(BLEAddress address); // Remove an entry from the BLE white list. + static void setEncryptionLevel(esp_ble_sec_act_t level); + static void setSecurityCallbacks(BLESecurityCallbacks* pCallbacks); + static esp_err_t setMTU(uint16_t mtu); + static uint16_t getMTU(); + static bool getInitialized(); // Returns the state of the device, is it initialized or not? + /* move advertising to BLEDevice for saving ram and flash in beacons */ + static BLEAdvertising* getAdvertising(); + static void startAdvertising(); + static uint16_t m_appId; + /* multi connect */ + static std::map getPeerDevices(bool client); + static void addPeerDevice(void* peer, bool is_client, uint16_t conn_id); + static void updatePeerDevice(void* peer, bool _client, uint16_t conn_id); + static void removePeerDevice(uint16_t conn_id, bool client); + static BLEClient* getClientByGattIf(uint16_t conn_id); + static void setCustomGapHandler(gap_event_handler handler); + static void setCustomGattcHandler(gattc_event_handler handler); + static void setCustomGattsHandler(gatts_event_handler handler); + static void deinit(bool release_memory = false); + static uint16_t m_localMTU; + static esp_ble_sec_act_t m_securityLevel; + +private: + static BLEServer* m_pServer; + static BLEScan* m_pScan; + static BLEClient* m_pClient; + static BLESecurityCallbacks* m_securityCallbacks; + static BLEAdvertising* m_bleAdvertising; + static esp_gatt_if_t getGattcIF(); + static std::map m_connectedClientsMap; + + static void gattClientEventHandler( + esp_gattc_cb_event_t event, + esp_gatt_if_t gattc_if, + esp_ble_gattc_cb_param_t* param); + + static void gattServerEventHandler( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* param); + + static void gapEventHandler( + esp_gap_ble_cb_event_t event, + esp_ble_gap_cb_param_t* param); + +public: +/* custom gap and gatt handlers for flexibility */ + static gap_event_handler m_customGapHandler; + static gattc_event_handler m_customGattcHandler; + static gatts_event_handler m_customGattsHandler; + +}; // class BLE + +#endif // CONFIG_BT_ENABLED +#endif /* MAIN_BLEDevice_H_ */ diff --git a/libraries/BLE/src/BLEEddystoneTLM.cpp b/libraries/BLE/src/BLEEddystoneTLM.cpp new file mode 100644 index 00000000000..1ab794932e2 --- /dev/null +++ b/libraries/BLE/src/BLEEddystoneTLM.cpp @@ -0,0 +1,132 @@ +/* + * BLEEddystoneTLM.cpp + * + * Created on: Mar 12, 2018 + * Author: pcbreflux + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include "esp32-hal-log.h" +#include "BLEEddystoneTLM.h" + +static const char LOG_TAG[] = "BLEEddystoneTLM"; +#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) +#define ENDIAN_CHANGE_U32(x) ((((x)&0xFF000000)>>24) + (((x)&0x00FF0000)>>8)) + ((((x)&0xFF00)<<8) + (((x)&0xFF)<<24)) + +BLEEddystoneTLM::BLEEddystoneTLM() { + beaconUUID = 0xFEAA; + m_eddystoneData.frameType = EDDYSTONE_TLM_FRAME_TYPE; + m_eddystoneData.version = 0; + m_eddystoneData.volt = 3300; // 3300mV = 3.3V + m_eddystoneData.temp = (uint16_t) ((float) 23.00); + m_eddystoneData.advCount = 0; + m_eddystoneData.tmil = 0; +} // BLEEddystoneTLM + +std::string BLEEddystoneTLM::getData() { + return std::string((char*) &m_eddystoneData, sizeof(m_eddystoneData)); +} // getData + +BLEUUID BLEEddystoneTLM::getUUID() { + return BLEUUID(beaconUUID); +} // getUUID + +uint8_t BLEEddystoneTLM::getVersion() { + return m_eddystoneData.version; +} // getVersion + +uint16_t BLEEddystoneTLM::getVolt() { + return m_eddystoneData.volt; +} // getVolt + +float BLEEddystoneTLM::getTemp() { + return (float)m_eddystoneData.temp; +} // getTemp + +uint32_t BLEEddystoneTLM::getCount() { + return m_eddystoneData.advCount; +} // getCount + +uint32_t BLEEddystoneTLM::getTime() { + return m_eddystoneData.tmil; +} // getTime + +std::string BLEEddystoneTLM::toString() { + std::string out = ""; + uint32_t rawsec = ENDIAN_CHANGE_U32(m_eddystoneData.tmil); + char val[6]; + + out += "Version " + m_eddystoneData.version; + out += "\n"; + out += "Battery Voltage " + ENDIAN_CHANGE_U16(m_eddystoneData.volt); + out += " mV\n"; + + out += "Temperature "; + snprintf(val, sizeof(val), "%d", m_eddystoneData.temp); + out += val; + out += ".0 °C\n"; + + out += "Adv. Count "; + snprintf(val, sizeof(val), "%d", ENDIAN_CHANGE_U32(m_eddystoneData.advCount)); + out += val; + out += "\n"; + + out += "Time "; + + snprintf(val, sizeof(val), "%04d", rawsec / 864000); + out += val; + out += "."; + + snprintf(val, sizeof(val), "%02d", (rawsec / 36000) % 24); + out += val; + out += ":"; + + snprintf(val, sizeof(val), "%02d", (rawsec / 600) % 60); + out += val; + out += ":"; + + snprintf(val, sizeof(val), "%02d", (rawsec / 10) % 60); + out += val; + out += "\n"; + + return out; +} // toString + +/** + * Set the raw data for the beacon record. + */ +void BLEEddystoneTLM::setData(std::string data) { + if (data.length() != sizeof(m_eddystoneData)) { + log_e("Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_eddystoneData)); + return; + } + memcpy(&m_eddystoneData, data.data(), data.length()); +} // setData + +void BLEEddystoneTLM::setUUID(BLEUUID l_uuid) { + beaconUUID = l_uuid.getNative()->uuid.uuid16; +} // setUUID + +void BLEEddystoneTLM::setVersion(uint8_t version) { + m_eddystoneData.version = version; +} // setVersion + +void BLEEddystoneTLM::setVolt(uint16_t volt) { + m_eddystoneData.volt = volt; +} // setVolt + +void BLEEddystoneTLM::setTemp(float temp) { + m_eddystoneData.temp = (uint16_t)temp; +} // setTemp + +void BLEEddystoneTLM::setCount(uint32_t advCount) { + m_eddystoneData.advCount = advCount; +} // setCount + +void BLEEddystoneTLM::setTime(uint32_t tmil) { + m_eddystoneData.tmil = tmil; +} // setTime + +#endif diff --git a/libraries/BLE/src/BLEEddystoneTLM.h b/libraries/BLE/src/BLEEddystoneTLM.h new file mode 100644 index 00000000000..a93e224fdf0 --- /dev/null +++ b/libraries/BLE/src/BLEEddystoneTLM.h @@ -0,0 +1,51 @@ +/* + * BLEEddystoneTLM.cpp + * + * Created on: Mar 12, 2018 + * Author: pcbreflux + */ + +#ifndef _BLEEddystoneTLM_H_ +#define _BLEEddystoneTLM_H_ +#include "BLEUUID.h" + +#define EDDYSTONE_TLM_FRAME_TYPE 0x20 + +/** + * @brief Representation of a beacon. + * See: + * * https://github.com/google/eddystone + */ +class BLEEddystoneTLM { +public: + BLEEddystoneTLM(); + std::string getData(); + BLEUUID getUUID(); + uint8_t getVersion(); + uint16_t getVolt(); + float getTemp(); + uint32_t getCount(); + uint32_t getTime(); + std::string toString(); + void setData(std::string data); + void setUUID(BLEUUID l_uuid); + void setVersion(uint8_t version); + void setVolt(uint16_t volt); + void setTemp(float temp); + void setCount(uint32_t advCount); + void setTime(uint32_t tmil); + +private: + uint16_t beaconUUID; + struct { + uint8_t frameType; + uint8_t version; + uint16_t volt; + uint16_t temp; + uint32_t advCount; + uint32_t tmil; + } __attribute__((packed)) m_eddystoneData; + +}; // BLEEddystoneTLM + +#endif /* _BLEEddystoneTLM_H_ */ diff --git a/libraries/BLE/src/BLEEddystoneURL.cpp b/libraries/BLE/src/BLEEddystoneURL.cpp new file mode 100644 index 00000000000..19a56b28b79 --- /dev/null +++ b/libraries/BLE/src/BLEEddystoneURL.cpp @@ -0,0 +1,148 @@ +/* + * BLEEddystoneURL.cpp + * + * Created on: Mar 12, 2018 + * Author: pcbreflux + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include "esp32-hal-log.h" +#include "BLEEddystoneURL.h" + +static const char LOG_TAG[] = "BLEEddystoneURL"; + +BLEEddystoneURL::BLEEddystoneURL() { + beaconUUID = 0xFEAA; + lengthURL = 0; + m_eddystoneData.frameType = EDDYSTONE_URL_FRAME_TYPE; + m_eddystoneData.advertisedTxPower = 0; + memset(m_eddystoneData.url, 0, sizeof(m_eddystoneData.url)); +} // BLEEddystoneURL + +std::string BLEEddystoneURL::getData() { + return std::string((char*) &m_eddystoneData, sizeof(m_eddystoneData)); +} // getData + +BLEUUID BLEEddystoneURL::getUUID() { + return BLEUUID(beaconUUID); +} // getUUID + +int8_t BLEEddystoneURL::getPower() { + return m_eddystoneData.advertisedTxPower; +} // getPower + +std::string BLEEddystoneURL::getURL() { + return std::string((char*) &m_eddystoneData.url, sizeof(m_eddystoneData.url)); +} // getURL + +std::string BLEEddystoneURL::getDecodedURL() { + std::string decodedURL = ""; + + switch (m_eddystoneData.url[0]) { + case 0x00: + decodedURL += "http://www."; + break; + case 0x01: + decodedURL += "https://www."; + break; + case 0x02: + decodedURL += "http://"; + break; + case 0x03: + decodedURL += "https://"; + break; + default: + decodedURL += m_eddystoneData.url[0]; + } + + for (int i = 1; i < lengthURL; i++) { + if (m_eddystoneData.url[i] > 33 && m_eddystoneData.url[i] < 127) { + decodedURL += m_eddystoneData.url[i]; + } else { + switch (m_eddystoneData.url[i]) { + case 0x00: + decodedURL += ".com/"; + break; + case 0x01: + decodedURL += ".org/"; + break; + case 0x02: + decodedURL += ".edu/"; + break; + case 0x03: + decodedURL += ".net/"; + break; + case 0x04: + decodedURL += ".info/"; + break; + case 0x05: + decodedURL += ".biz/"; + break; + case 0x06: + decodedURL += ".gov/"; + break; + case 0x07: + decodedURL += ".com"; + break; + case 0x08: + decodedURL += ".org"; + break; + case 0x09: + decodedURL += ".edu"; + break; + case 0x0A: + decodedURL += ".net"; + break; + case 0x0B: + decodedURL += ".info"; + break; + case 0x0C: + decodedURL += ".biz"; + break; + case 0x0D: + decodedURL += ".gov"; + break; + default: + break; + } + } + } + return decodedURL; +} // getDecodedURL + + + +/** + * Set the raw data for the beacon record. + */ +void BLEEddystoneURL::setData(std::string data) { + if (data.length() > sizeof(m_eddystoneData)) { + log_e("Unable to set the data ... length passed in was %d and max expected %d", data.length(), sizeof(m_eddystoneData)); + return; + } + memset(&m_eddystoneData, 0, sizeof(m_eddystoneData)); + memcpy(&m_eddystoneData, data.data(), data.length()); + lengthURL = data.length() - (sizeof(m_eddystoneData) - sizeof(m_eddystoneData.url)); +} // setData + +void BLEEddystoneURL::setUUID(BLEUUID l_uuid) { + beaconUUID = l_uuid.getNative()->uuid.uuid16; +} // setUUID + +void BLEEddystoneURL::setPower(int8_t advertisedTxPower) { + m_eddystoneData.advertisedTxPower = advertisedTxPower; +} // setPower + +void BLEEddystoneURL::setURL(std::string url) { + if (url.length() > sizeof(m_eddystoneData.url)) { + log_e("Unable to set the url ... length passed in was %d and max expected %d", url.length(), sizeof(m_eddystoneData.url)); + return; + } + memset(m_eddystoneData.url, 0, sizeof(m_eddystoneData.url)); + memcpy(m_eddystoneData.url, url.data(), url.length()); + lengthURL = url.length(); +} // setURL + + +#endif diff --git a/libraries/BLE/src/BLEEddystoneURL.h b/libraries/BLE/src/BLEEddystoneURL.h new file mode 100644 index 00000000000..0b538c07d00 --- /dev/null +++ b/libraries/BLE/src/BLEEddystoneURL.h @@ -0,0 +1,43 @@ +/* + * BLEEddystoneURL.cpp + * + * Created on: Mar 12, 2018 + * Author: pcbreflux + */ + +#ifndef _BLEEddystoneURL_H_ +#define _BLEEddystoneURL_H_ +#include "BLEUUID.h" + +#define EDDYSTONE_URL_FRAME_TYPE 0x10 + +/** + * @brief Representation of a beacon. + * See: + * * https://github.com/google/eddystone + */ +class BLEEddystoneURL { +public: + BLEEddystoneURL(); + std::string getData(); + BLEUUID getUUID(); + int8_t getPower(); + std::string getURL(); + std::string getDecodedURL(); + void setData(std::string data); + void setUUID(BLEUUID l_uuid); + void setPower(int8_t advertisedTxPower); + void setURL(std::string url); + +private: + uint16_t beaconUUID; + uint8_t lengthURL; + struct { + uint8_t frameType; + int8_t advertisedTxPower; + uint8_t url[16]; + } __attribute__((packed)) m_eddystoneData; + +}; // BLEEddystoneURL + +#endif /* _BLEEddystoneURL_H_ */ diff --git a/libraries/BLE/src/BLEExceptions.cpp b/libraries/BLE/src/BLEExceptions.cpp new file mode 100644 index 00000000000..549e4425bd8 --- /dev/null +++ b/libraries/BLE/src/BLEExceptions.cpp @@ -0,0 +1,9 @@ +/* + * BLExceptions.cpp + * + * Created on: Nov 27, 2017 + * Author: kolban + */ + +//#include "BLEExceptions.h" + diff --git a/libraries/BLE/src/BLEExceptions.h b/libraries/BLE/src/BLEExceptions.h new file mode 100644 index 00000000000..ea9db8550bc --- /dev/null +++ b/libraries/BLE/src/BLEExceptions.h @@ -0,0 +1,31 @@ +/* + * BLExceptions.h + * + * Created on: Nov 27, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ +#define COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ +#include "sdkconfig.h" + +#if CONFIG_CXX_EXCEPTIONS != 1 +#error "C++ exception handling must be enabled within make menuconfig. See Compiler Options > Enable C++ Exceptions." +#endif + +#include + + +class BLEDisconnectedException : public std::exception { + const char* what() const throw () { + return "BLE Disconnected"; + } +}; + +class BLEUuidNotFoundException : public std::exception { + const char* what() const throw () { + return "No such UUID"; + } +}; + +#endif /* COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ */ diff --git a/libraries/BLE/src/BLEHIDDevice.cpp b/libraries/BLE/src/BLEHIDDevice.cpp new file mode 100644 index 00000000000..69e18be7a5f --- /dev/null +++ b/libraries/BLE/src/BLEHIDDevice.cpp @@ -0,0 +1,243 @@ +/* + * BLEHIDDevice.cpp + * + * Created on: Jan 03, 2018 + * Author: chegewara + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include "BLEHIDDevice.h" +#include "BLE2904.h" + + +BLEHIDDevice::BLEHIDDevice(BLEServer* server) { + /* + * Here we create mandatory services described in bluetooth specification + */ + m_deviceInfoService = server->createService(BLEUUID((uint16_t) 0x180a)); + m_hidService = server->createService(BLEUUID((uint16_t) 0x1812), 40); + m_batteryService = server->createService(BLEUUID((uint16_t) 0x180f)); + + /* + * Mandatory characteristic for device info service + */ + m_pnpCharacteristic = m_deviceInfoService->createCharacteristic((uint16_t) 0x2a50, BLECharacteristic::PROPERTY_READ); + + /* + * Mandatory characteristics for HID service + */ + m_hidInfoCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4a, BLECharacteristic::PROPERTY_READ); + m_reportMapCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4b, BLECharacteristic::PROPERTY_READ); + m_hidControlCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4c, BLECharacteristic::PROPERTY_WRITE_NR); + m_protocolModeCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4e, BLECharacteristic::PROPERTY_WRITE_NR | BLECharacteristic::PROPERTY_READ); + + /* + * Mandatory battery level characteristic with notification and presence descriptor + */ + BLE2904* batteryLevelDescriptor = new BLE2904(); + batteryLevelDescriptor->setFormat(BLE2904::FORMAT_UINT8); + batteryLevelDescriptor->setNamespace(1); + batteryLevelDescriptor->setUnit(0x27ad); + + m_batteryLevelCharacteristic = m_batteryService->createCharacteristic((uint16_t) 0x2a19, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY); + m_batteryLevelCharacteristic->addDescriptor(batteryLevelDescriptor); + m_batteryLevelCharacteristic->addDescriptor(new BLE2902()); + + /* + * This value is setup here because its default value in most usage cases, its very rare to use boot mode + * and we want to simplify library using as much as possible + */ + const uint8_t pMode[] = { 0x01 }; + protocolMode()->setValue((uint8_t*) pMode, 1); +} + +BLEHIDDevice::~BLEHIDDevice() { +} + +/* + * @brief + */ +void BLEHIDDevice::reportMap(uint8_t* map, uint16_t size) { + m_reportMapCharacteristic->setValue(map, size); +} + +/* + * @brief This function suppose to be called at the end, when we have created all characteristics we need to build HID service + */ +void BLEHIDDevice::startServices() { + m_deviceInfoService->start(); + m_hidService->start(); + m_batteryService->start(); +} + +/* + * @brief Create manufacturer characteristic (this characteristic is optional) + */ +BLECharacteristic* BLEHIDDevice::manufacturer() { + m_manufacturerCharacteristic = m_deviceInfoService->createCharacteristic((uint16_t) 0x2a29, BLECharacteristic::PROPERTY_READ); + return m_manufacturerCharacteristic; +} + +/* + * @brief Set manufacturer name + * @param [in] name manufacturer name + */ +void BLEHIDDevice::manufacturer(std::string name) { + m_manufacturerCharacteristic->setValue(name); +} + +/* + * @brief + */ +void BLEHIDDevice::pnp(uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version) { + uint8_t pnp[] = { sig, (uint8_t) (vid >> 8), (uint8_t) vid, (uint8_t) (pid >> 8), (uint8_t) pid, (uint8_t) (version >> 8), (uint8_t) version }; + m_pnpCharacteristic->setValue(pnp, sizeof(pnp)); +} + +/* + * @brief + */ +void BLEHIDDevice::hidInfo(uint8_t country, uint8_t flags) { + uint8_t info[] = { 0x11, 0x1, country, flags }; + m_hidInfoCharacteristic->setValue(info, sizeof(info)); +} + +/* + * @brief Create input report characteristic that need to be saved as new characteristic object so can be further used + * @param [in] reportID input report ID, the same as in report map for input object related to created characteristic + * @return pointer to new input report characteristic + */ +BLECharacteristic* BLEHIDDevice::inputReport(uint8_t reportID) { + BLECharacteristic* inputReportCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY); + BLEDescriptor* inputReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t) 0x2908)); + BLE2902* p2902 = new BLE2902(); + inputReportCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); + inputReportDescriptor->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); + p2902->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); + + uint8_t desc1_val[] = { reportID, 0x01 }; + inputReportDescriptor->setValue((uint8_t*) desc1_val, 2); + inputReportCharacteristic->addDescriptor(p2902); + inputReportCharacteristic->addDescriptor(inputReportDescriptor); + + return inputReportCharacteristic; +} + +/* + * @brief Create output report characteristic that need to be saved as new characteristic object so can be further used + * @param [in] reportID Output report ID, the same as in report map for output object related to created characteristic + * @return Pointer to new output report characteristic + */ +BLECharacteristic* BLEHIDDevice::outputReport(uint8_t reportID) { + BLECharacteristic* outputReportCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR); + BLEDescriptor* outputReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t) 0x2908)); + outputReportCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); + outputReportDescriptor->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); + + uint8_t desc1_val[] = { reportID, 0x02 }; + outputReportDescriptor->setValue((uint8_t*) desc1_val, 2); + outputReportCharacteristic->addDescriptor(outputReportDescriptor); + + return outputReportCharacteristic; +} + +/* + * @brief Create feature report characteristic that need to be saved as new characteristic object so can be further used + * @param [in] reportID Feature report ID, the same as in report map for feature object related to created characteristic + * @return Pointer to new feature report characteristic + */ +BLECharacteristic* BLEHIDDevice::featureReport(uint8_t reportID) { + BLECharacteristic* featureReportCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE); + BLEDescriptor* featureReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t) 0x2908)); + + featureReportCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); + featureReportDescriptor->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); + + uint8_t desc1_val[] = { reportID, 0x03 }; + featureReportDescriptor->setValue((uint8_t*) desc1_val, 2); + featureReportCharacteristic->addDescriptor(featureReportDescriptor); + + return featureReportCharacteristic; +} + +/* + * @brief + */ +BLECharacteristic* BLEHIDDevice::bootInput() { + BLECharacteristic* bootInputCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a22, BLECharacteristic::PROPERTY_NOTIFY); + bootInputCharacteristic->addDescriptor(new BLE2902()); + + return bootInputCharacteristic; +} + +/* + * @brief + */ +BLECharacteristic* BLEHIDDevice::bootOutput() { + return m_hidService->createCharacteristic((uint16_t) 0x2a32, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR); +} + +/* + * @brief + */ +BLECharacteristic* BLEHIDDevice::hidControl() { + return m_hidControlCharacteristic; +} + +/* + * @brief + */ +BLECharacteristic* BLEHIDDevice::protocolMode() { + return m_protocolModeCharacteristic; +} + +void BLEHIDDevice::setBatteryLevel(uint8_t level) { + m_batteryLevelCharacteristic->setValue(&level, 1); +} +/* + * @brief Returns battery level characteristic + * @ return battery level characteristic + *//* +BLECharacteristic* BLEHIDDevice::batteryLevel() { + return m_batteryLevelCharacteristic; +} + + + +BLECharacteristic* BLEHIDDevice::reportMap() { + return m_reportMapCharacteristic; +} + +BLECharacteristic* BLEHIDDevice::pnp() { + return m_pnpCharacteristic; +} + + +BLECharacteristic* BLEHIDDevice::hidInfo() { + return m_hidInfoCharacteristic; +} +*/ +/* + * @brief + */ +BLEService* BLEHIDDevice::deviceInfo() { + return m_deviceInfoService; +} + +/* + * @brief + */ +BLEService* BLEHIDDevice::hidService() { + return m_hidService; +} + +/* + * @brief + */ +BLEService* BLEHIDDevice::batteryService() { + return m_batteryService; +} + +#endif // CONFIG_BT_ENABLED + diff --git a/libraries/BLE/src/BLEHIDDevice.h b/libraries/BLE/src/BLEHIDDevice.h new file mode 100644 index 00000000000..33e6b46c540 --- /dev/null +++ b/libraries/BLE/src/BLEHIDDevice.h @@ -0,0 +1,75 @@ +/* + * BLEHIDDevice.h + * + * Created on: Jan 03, 2018 + * Author: chegewara + */ + +#ifndef _BLEHIDDEVICE_H_ +#define _BLEHIDDEVICE_H_ + +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include "BLECharacteristic.h" +#include "BLEService.h" +#include "BLEDescriptor.h" +#include "BLE2902.h" +#include "HIDTypes.h" + +#define GENERIC_HID 0x03C0 +#define HID_KEYBOARD 0x03C1 +#define HID_MOUSE 0x03C2 +#define HID_JOYSTICK 0x03C3 +#define HID_GAMEPAD 0x03C4 +#define HID_TABLET 0x03C5 +#define HID_CARD_READER 0x03C6 +#define HID_DIGITAL_PEN 0x03C7 +#define HID_BARCODE 0x03C8 + +class BLEHIDDevice { +public: + BLEHIDDevice(BLEServer*); + virtual ~BLEHIDDevice(); + + void reportMap(uint8_t* map, uint16_t); + void startServices(); + + BLEService* deviceInfo(); + BLEService* hidService(); + BLEService* batteryService(); + + BLECharacteristic* manufacturer(); + void manufacturer(std::string name); + //BLECharacteristic* pnp(); + void pnp(uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version); + //BLECharacteristic* hidInfo(); + void hidInfo(uint8_t country, uint8_t flags); + //BLECharacteristic* batteryLevel(); + void setBatteryLevel(uint8_t level); + + + //BLECharacteristic* reportMap(); + BLECharacteristic* hidControl(); + BLECharacteristic* inputReport(uint8_t reportID); + BLECharacteristic* outputReport(uint8_t reportID); + BLECharacteristic* featureReport(uint8_t reportID); + BLECharacteristic* protocolMode(); + BLECharacteristic* bootInput(); + BLECharacteristic* bootOutput(); + +private: + BLEService* m_deviceInfoService; //0x180a + BLEService* m_hidService; //0x1812 + BLEService* m_batteryService = 0; //0x180f + + BLECharacteristic* m_manufacturerCharacteristic; //0x2a29 + BLECharacteristic* m_pnpCharacteristic; //0x2a50 + BLECharacteristic* m_hidInfoCharacteristic; //0x2a4a + BLECharacteristic* m_reportMapCharacteristic; //0x2a4b + BLECharacteristic* m_hidControlCharacteristic; //0x2a4c + BLECharacteristic* m_protocolModeCharacteristic; //0x2a4e + BLECharacteristic* m_batteryLevelCharacteristic; //0x2a19 +}; +#endif // CONFIG_BT_ENABLED +#endif /* _BLEHIDDEVICE_H_ */ diff --git a/libraries/BLE/src/BLERemoteCharacteristic.cpp b/libraries/BLE/src/BLERemoteCharacteristic.cpp new file mode 100644 index 00000000000..fe4559199bd --- /dev/null +++ b/libraries/BLE/src/BLERemoteCharacteristic.cpp @@ -0,0 +1,598 @@ +/* + * BLERemoteCharacteristic.cpp + * + * Created on: Jul 8, 2017 + * Author: kolban + */ + +#include "BLERemoteCharacteristic.h" + +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include +#include + +#include +//#include "BLEExceptions.h" +#include "BLEUtils.h" +#include "GeneralUtils.h" +#include "BLERemoteDescriptor.h" +#include "esp32-hal-log.h" + + +/** + * @brief Constructor. + * @param [in] handle The BLE server side handle of this characteristic. + * @param [in] uuid The UUID of this characteristic. + * @param [in] charProp The properties of this characteristic. + * @param [in] pRemoteService A reference to the remote service to which this remote characteristic pertains. + */ +BLERemoteCharacteristic::BLERemoteCharacteristic( + uint16_t handle, + BLEUUID uuid, + esp_gatt_char_prop_t charProp, + BLERemoteService* pRemoteService) { + log_v(">> BLERemoteCharacteristic: handle: %d 0x%d, uuid: %s", handle, handle, uuid.toString().c_str()); + m_handle = handle; + m_uuid = uuid; + m_charProp = charProp; + m_pRemoteService = pRemoteService; + m_notifyCallback = nullptr; + m_rawData = nullptr; + + retrieveDescriptors(); // Get the descriptors for this characteristic + log_v("<< BLERemoteCharacteristic"); +} // BLERemoteCharacteristic + + +/** + *@brief Destructor. + */ +BLERemoteCharacteristic::~BLERemoteCharacteristic() { + removeDescriptors(); // Release resources for any descriptor information we may have allocated. +} // ~BLERemoteCharacteristic + + +/** + * @brief Does the characteristic support broadcasting? + * @return True if the characteristic supports broadcasting. + */ +bool BLERemoteCharacteristic::canBroadcast() { + return (m_charProp & ESP_GATT_CHAR_PROP_BIT_BROADCAST) != 0; +} // canBroadcast + + +/** + * @brief Does the characteristic support indications? + * @return True if the characteristic supports indications. + */ +bool BLERemoteCharacteristic::canIndicate() { + return (m_charProp & ESP_GATT_CHAR_PROP_BIT_INDICATE) != 0; +} // canIndicate + + +/** + * @brief Does the characteristic support notifications? + * @return True if the characteristic supports notifications. + */ +bool BLERemoteCharacteristic::canNotify() { + return (m_charProp & ESP_GATT_CHAR_PROP_BIT_NOTIFY) != 0; +} // canNotify + + +/** + * @brief Does the characteristic support reading? + * @return True if the characteristic supports reading. + */ +bool BLERemoteCharacteristic::canRead() { + return (m_charProp & ESP_GATT_CHAR_PROP_BIT_READ) != 0; +} // canRead + + +/** + * @brief Does the characteristic support writing? + * @return True if the characteristic supports writing. + */ +bool BLERemoteCharacteristic::canWrite() { + return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE) != 0; +} // canWrite + + +/** + * @brief Does the characteristic support writing with no response? + * @return True if the characteristic supports writing with no response. + */ +bool BLERemoteCharacteristic::canWriteNoResponse() { + return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) != 0; +} // canWriteNoResponse + + +/* +static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) { + if (id1.id.inst_id != id2.id.inst_id) { + return false; + } + if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) { + return false; + } + return true; +} // compareSrvcId +*/ + +/* +static bool compareGattId(esp_gatt_id_t id1, esp_gatt_id_t id2) { + if (id1.inst_id != id2.inst_id) { + return false; + } + if (!BLEUUID(id1.uuid).equals(BLEUUID(id2.uuid))) { + return false; + } + return true; +} // compareCharId +*/ + + +/** + * @brief Handle GATT Client events. + * When an event arrives for a GATT client we give this characteristic the opportunity to + * take a look at it to see if there is interest in it. + * @param [in] event The type of event. + * @param [in] gattc_if The interface on which the event was received. + * @param [in] evtParam Payload data for the event. + * @returns N/A + */ +void BLERemoteCharacteristic::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam) { + switch(event) { + // ESP_GATTC_NOTIFY_EVT + // + // notify + // - uint16_t conn_id - The connection identifier of the server. + // - esp_bd_addr_t remote_bda - The device address of the BLE server. + // - uint16_t handle - The handle of the characteristic for which the event is being received. + // - uint16_t value_len - The length of the received data. + // - uint8_t* value - The received data. + // - bool is_notify - True if this is a notify, false if it is an indicate. + // + // We have received a notification event which means that the server wishes us to know about a notification + // piece of data. What we must now do is find the characteristic with the associated handle and then + // invoke its notification callback (if it has one). + case ESP_GATTC_NOTIFY_EVT: { + if (evtParam->notify.handle != getHandle()) break; + if (m_notifyCallback != nullptr) { + log_d("Invoking callback for notification on characteristic %s", toString().c_str()); + m_notifyCallback(this, evtParam->notify.value, evtParam->notify.value_len, evtParam->notify.is_notify); + } // End we have a callback function ... + break; + } // ESP_GATTC_NOTIFY_EVT + + // ESP_GATTC_READ_CHAR_EVT + // This event indicates that the server has responded to the read request. + // + // read: + // - esp_gatt_status_t status + // - uint16_t conn_id + // - uint16_t handle + // - uint8_t* value + // - uint16_t value_len + case ESP_GATTC_READ_CHAR_EVT: { + // If this event is not for us, then nothing further to do. + if (evtParam->read.handle != getHandle()) break; + + // At this point, we have determined that the event is for us, so now we save the value + // and unlock the semaphore to ensure that the requestor of the data can continue. + if (evtParam->read.status == ESP_GATT_OK) { + m_value = std::string((char*) evtParam->read.value, evtParam->read.value_len); + if(m_rawData != nullptr) free(m_rawData); + m_rawData = (uint8_t*) calloc(evtParam->read.value_len, sizeof(uint8_t)); + memcpy(m_rawData, evtParam->read.value, evtParam->read.value_len); + } else { + m_value = ""; + } + + m_semaphoreReadCharEvt.give(); + break; + } // ESP_GATTC_READ_CHAR_EVT + + // ESP_GATTC_REG_FOR_NOTIFY_EVT + // + // reg_for_notify: + // - esp_gatt_status_t status + // - uint16_t handle + case ESP_GATTC_REG_FOR_NOTIFY_EVT: { + // If the request is not for this BLERemoteCharacteristic then move on to the next. + if (evtParam->reg_for_notify.handle != getHandle()) break; + + // We have processed the notify registration and can unlock the semaphore. + m_semaphoreRegForNotifyEvt.give(); + break; + } // ESP_GATTC_REG_FOR_NOTIFY_EVT + + // ESP_GATTC_UNREG_FOR_NOTIFY_EVT + // + // unreg_for_notify: + // - esp_gatt_status_t status + // - uint16_t handle + case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: { + if (evtParam->unreg_for_notify.handle != getHandle()) break; + // We have processed the notify un-registration and can unlock the semaphore. + m_semaphoreRegForNotifyEvt.give(); + break; + } // ESP_GATTC_UNREG_FOR_NOTIFY_EVT: + + // ESP_GATTC_WRITE_CHAR_EVT + // + // write: + // - esp_gatt_status_t status + // - uint16_t conn_id + // - uint16_t handle + case ESP_GATTC_WRITE_CHAR_EVT: { + // Determine if this event is for us and, if not, pass onwards. + if (evtParam->write.handle != getHandle()) break; + + // There is nothing further we need to do here. This is merely an indication + // that the write has completed and we can unlock the caller. + m_semaphoreWriteCharEvt.give(); + break; + } // ESP_GATTC_WRITE_CHAR_EVT + + + default: + break; + } // End switch +}; // gattClientEventHandler + + +/** + * @brief Populate the descriptors (if any) for this characteristic. + */ +void BLERemoteCharacteristic::retrieveDescriptors() { + log_v(">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str()); + + removeDescriptors(); // Remove any existing descriptors. + + // Loop over each of the descriptors within the service associated with this characteristic. + // For each descriptor we find, create a BLERemoteDescriptor instance. + uint16_t offset = 0; + esp_gattc_descr_elem_t result; + while(true) { + uint16_t count = 10; + esp_gatt_status_t status = ::esp_ble_gattc_get_all_descr( + getRemoteService()->getClient()->getGattcIf(), + getRemoteService()->getClient()->getConnId(), + getHandle(), + &result, + &count, + offset + ); + + if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries. + break; + } + + if (status != ESP_GATT_OK) { + log_e("esp_ble_gattc_get_all_descr: %s", BLEUtils::gattStatusToString(status).c_str()); + break; + } + + if (count == 0) break; + + log_d("Found a descriptor: Handle: %d, UUID: %s", result.handle, BLEUUID(result.uuid).toString().c_str()); + + // We now have a new characteristic ... let us add that to our set of known characteristics + BLERemoteDescriptor* pNewRemoteDescriptor = new BLERemoteDescriptor( + result.handle, + BLEUUID(result.uuid), + this + ); + + m_descriptorMap.insert(std::pair(pNewRemoteDescriptor->getUUID().toString(), pNewRemoteDescriptor)); + + offset++; + } // while true + //m_haveCharacteristics = true; // Remember that we have received the characteristics. + log_v("<< retrieveDescriptors(): Found %d descriptors.", offset); +} // getDescriptors + + +/** + * @brief Retrieve the map of descriptors keyed by UUID. + */ +std::map* BLERemoteCharacteristic::getDescriptors() { + return &m_descriptorMap; +} // getDescriptors + + +/** + * @brief Get the handle for this characteristic. + * @return The handle for this characteristic. + */ +uint16_t BLERemoteCharacteristic::getHandle() { + //log_v(">> getHandle: Characteristic: %s", getUUID().toString().c_str()); + //log_v("<< getHandle: %d 0x%.2x", m_handle, m_handle); + return m_handle; +} // getHandle + + +/** + * @brief Get the descriptor instance with the given UUID that belongs to this characteristic. + * @param [in] uuid The UUID of the descriptor to find. + * @return The Remote descriptor (if present) or null if not present. + */ +BLERemoteDescriptor* BLERemoteCharacteristic::getDescriptor(BLEUUID uuid) { + log_v(">> getDescriptor: uuid: %s", uuid.toString().c_str()); + std::string v = uuid.toString(); + for (auto &myPair : m_descriptorMap) { + if (myPair.first == v) { + log_v("<< getDescriptor: found"); + return myPair.second; + } + } + log_v("<< getDescriptor: Not found"); + return nullptr; +} // getDescriptor + + +/** + * @brief Get the remote service associated with this characteristic. + * @return The remote service associated with this characteristic. + */ +BLERemoteService* BLERemoteCharacteristic::getRemoteService() { + return m_pRemoteService; +} // getRemoteService + + +/** + * @brief Get the UUID for this characteristic. + * @return The UUID for this characteristic. + */ +BLEUUID BLERemoteCharacteristic::getUUID() { + return m_uuid; +} // getUUID + + +/** + * @brief Read an unsigned 16 bit value + * @return The unsigned 16 bit value. + */ +uint16_t BLERemoteCharacteristic::readUInt16() { + std::string value = readValue(); + if (value.length() >= 2) { + return *(uint16_t*)(value.data()); + } + return 0; +} // readUInt16 + + +/** + * @brief Read an unsigned 32 bit value. + * @return the unsigned 32 bit value. + */ +uint32_t BLERemoteCharacteristic::readUInt32() { + std::string value = readValue(); + if (value.length() >= 4) { + return *(uint32_t*)(value.data()); + } + return 0; +} // readUInt32 + + +/** + * @brief Read a byte value + * @return The value as a byte + */ +uint8_t BLERemoteCharacteristic::readUInt8() { + std::string value = readValue(); + if (value.length() >= 1) { + return (uint8_t)value[0]; + } + return 0; +} // readUInt8 + +/** + * @brief Read a float value. + * @return the float value. + */ +float BLERemoteCharacteristic::readFloat() { + std::string value = readValue(); + if (value.length() >= 4) { + return *(float*)(value.data()); + } + return 0.0; +} // readFloat + +/** + * @brief Read the value of the remote characteristic. + * @return The value of the remote characteristic. + */ +std::string BLERemoteCharacteristic::readValue() { + log_v(">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle()); + + // Check to see that we are connected. + if (!getRemoteService()->getClient()->isConnected()) { + log_e("Disconnected"); + return std::string(); + } + + m_semaphoreReadCharEvt.take("readValue"); + + // Ask the BLE subsystem to retrieve the value for the remote hosted characteristic. + // This is an asynchronous request which means that we must block waiting for the response + // to become available. + esp_err_t errRc = ::esp_ble_gattc_read_char( + m_pRemoteService->getClient()->getGattcIf(), + m_pRemoteService->getClient()->getConnId(), // The connection ID to the BLE server + getHandle(), // The handle of this characteristic + ESP_GATT_AUTH_REQ_NONE); // Security + + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return ""; + } + + // Block waiting for the event that indicates that the read has completed. When it has, the std::string found + // in m_value will contain our data. + m_semaphoreReadCharEvt.wait("readValue"); + + log_v("<< readValue(): length: %d", m_value.length()); + return m_value; +} // readValue + + +/** + * @brief Register for notifications. + * @param [in] notifyCallback A callback to be invoked for a notification. If NULL is provided then we are + * unregistering a notification. + * @return N/A. + */ +void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback, bool notifications) { + log_v(">> registerForNotify(): %s", toString().c_str()); + + m_notifyCallback = notifyCallback; // Save the notification callback. + + m_semaphoreRegForNotifyEvt.take("registerForNotify"); + + if (notifyCallback != nullptr) { // If we have a callback function, then this is a registration. + esp_err_t errRc = ::esp_ble_gattc_register_for_notify( + m_pRemoteService->getClient()->getGattcIf(), + *m_pRemoteService->getClient()->getPeerAddress().getNative(), + getHandle() + ); + + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_register_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } + + uint8_t val[] = {0x01, 0x00}; + if(!notifications) val[0] = 0x02; + BLERemoteDescriptor* desc = getDescriptor(BLEUUID((uint16_t)0x2902)); + desc->writeValue(val, 2); + } // End Register + else { // If we weren't passed a callback function, then this is an unregistration. + esp_err_t errRc = ::esp_ble_gattc_unregister_for_notify( + m_pRemoteService->getClient()->getGattcIf(), + *m_pRemoteService->getClient()->getPeerAddress().getNative(), + getHandle() + ); + + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_unregister_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } + + uint8_t val[] = {0x00, 0x00}; + BLERemoteDescriptor* desc = getDescriptor((uint16_t)0x2902); + desc->writeValue(val, 2); + } // End Unregister + + m_semaphoreRegForNotifyEvt.wait("registerForNotify"); + + log_v("<< registerForNotify()"); +} // registerForNotify + + +/** + * @brief Delete the descriptors in the descriptor map. + * We maintain a map called m_descriptorMap that contains pointers to BLERemoteDescriptors + * object references. Since we allocated these in this class, we are also responsible for deleteing + * them. This method does just that. + * @return N/A. + */ +void BLERemoteCharacteristic::removeDescriptors() { + // Iterate through all the descriptors releasing their storage and erasing them from the map. + for (auto &myPair : m_descriptorMap) { + m_descriptorMap.erase(myPair.first); + delete myPair.second; + } + m_descriptorMap.clear(); // Technically not neeeded, but just to be sure. +} // removeCharacteristics + + +/** + * @brief Convert a BLERemoteCharacteristic to a string representation; + * @return a String representation. + */ +std::string BLERemoteCharacteristic::toString() { + std::string res = "Characteristic: uuid: " + m_uuid.toString(); + char val[6]; + res += ", handle: "; + snprintf(val, sizeof(val), "%d", getHandle()); + res += val; + res += " 0x"; + snprintf(val, sizeof(val), "%04x", getHandle()); + res += val; + res += ", props: " + BLEUtils::characteristicPropertiesToString(m_charProp); + return res; +} // toString + + +/** + * @brief Write the new value for the characteristic. + * @param [in] newValue The new value to write. + * @param [in] response Do we expect a response? + * @return N/A. + */ +void BLERemoteCharacteristic::writeValue(std::string newValue, bool response) { + writeValue((uint8_t*)newValue.c_str(), strlen(newValue.c_str()), response); +} // writeValue + + +/** + * @brief Write the new value for the characteristic. + * + * This is a convenience function. Many BLE characteristics are a single byte of data. + * @param [in] newValue The new byte value to write. + * @param [in] response Whether we require a response from the write. + * @return N/A. + */ +void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) { + writeValue(&newValue, 1, response); +} // writeValue + + +/** + * @brief Write the new value for the characteristic from a data buffer. + * @param [in] data A pointer to a data buffer. + * @param [in] length The length of the data in the data buffer. + * @param [in] response Whether we require a response from the write. + */ +void BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool response) { + // writeValue(std::string((char*)data, length), response); + log_v(">> writeValue(), length: %d", length); + + // Check to see that we are connected. + if (!getRemoteService()->getClient()->isConnected()) { + log_e("Disconnected"); + return; + } + + m_semaphoreWriteCharEvt.take("writeValue"); + // Invoke the ESP-IDF API to perform the write. + esp_err_t errRc = ::esp_ble_gattc_write_char( + m_pRemoteService->getClient()->getGattcIf(), + m_pRemoteService->getClient()->getConnId(), + getHandle(), + length, + data, + response?ESP_GATT_WRITE_TYPE_RSP:ESP_GATT_WRITE_TYPE_NO_RSP, + ESP_GATT_AUTH_REQ_NONE + ); + + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + + m_semaphoreWriteCharEvt.wait("writeValue"); + + log_v("<< writeValue"); +} // writeValue + +/** + * @brief Read raw data from remote characteristic as hex bytes + * @return return pointer data read + */ +uint8_t* BLERemoteCharacteristic::readRawData() { + return m_rawData; +} + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLERemoteCharacteristic.h b/libraries/BLE/src/BLERemoteCharacteristic.h new file mode 100644 index 00000000000..1d0db1c379d --- /dev/null +++ b/libraries/BLE/src/BLERemoteCharacteristic.h @@ -0,0 +1,85 @@ +/* + * BLERemoteCharacteristic.h + * + * Created on: Jul 8, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ +#define COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include + +#include + +#include "BLERemoteService.h" +#include "BLERemoteDescriptor.h" +#include "BLEUUID.h" +#include "FreeRTOS.h" + +class BLERemoteService; +class BLERemoteDescriptor; +typedef void (*notify_callback)(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify); + +/** + * @brief A model of a remote %BLE characteristic. + */ +class BLERemoteCharacteristic { +public: + ~BLERemoteCharacteristic(); + + // Public member functions + bool canBroadcast(); + bool canIndicate(); + bool canNotify(); + bool canRead(); + bool canWrite(); + bool canWriteNoResponse(); + BLERemoteDescriptor* getDescriptor(BLEUUID uuid); + std::map* getDescriptors(); + uint16_t getHandle(); + BLEUUID getUUID(); + std::string readValue(); + uint8_t readUInt8(); + uint16_t readUInt16(); + uint32_t readUInt32(); + float readFloat(); + void registerForNotify(notify_callback _callback, bool notifications = true); + void writeValue(uint8_t* data, size_t length, bool response = false); + void writeValue(std::string newValue, bool response = false); + void writeValue(uint8_t newValue, bool response = false); + std::string toString(); + uint8_t* readRawData(); + +private: + BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService* pRemoteService); + friend class BLEClient; + friend class BLERemoteService; + friend class BLERemoteDescriptor; + + // Private member functions + void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam); + + BLERemoteService* getRemoteService(); + void removeDescriptors(); + void retrieveDescriptors(); + + // Private properties + BLEUUID m_uuid; + esp_gatt_char_prop_t m_charProp; + uint16_t m_handle; + BLERemoteService* m_pRemoteService; + FreeRTOS::Semaphore m_semaphoreReadCharEvt = FreeRTOS::Semaphore("ReadCharEvt"); + FreeRTOS::Semaphore m_semaphoreRegForNotifyEvt = FreeRTOS::Semaphore("RegForNotifyEvt"); + FreeRTOS::Semaphore m_semaphoreWriteCharEvt = FreeRTOS::Semaphore("WriteCharEvt"); + std::string m_value; + uint8_t *m_rawData; + notify_callback m_notifyCallback; + + // We maintain a map of descriptors owned by this characteristic keyed by a string representation of the UUID. + std::map m_descriptorMap; +}; // BLERemoteCharacteristic +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ */ diff --git a/libraries/BLE/src/BLERemoteDescriptor.cpp b/libraries/BLE/src/BLERemoteDescriptor.cpp new file mode 100644 index 00000000000..54e59759a04 --- /dev/null +++ b/libraries/BLE/src/BLERemoteDescriptor.cpp @@ -0,0 +1,175 @@ +/* + * BLERemoteDescriptor.cpp + * + * Created on: Jul 8, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include "BLERemoteDescriptor.h" +#include "GeneralUtils.h" +#include "esp32-hal-log.h" + +BLERemoteDescriptor::BLERemoteDescriptor( + uint16_t handle, + BLEUUID uuid, + BLERemoteCharacteristic* pRemoteCharacteristic) { + + m_handle = handle; + m_uuid = uuid; + m_pRemoteCharacteristic = pRemoteCharacteristic; +} + + +/** + * @brief Retrieve the handle associated with this remote descriptor. + * @return The handle associated with this remote descriptor. + */ +uint16_t BLERemoteDescriptor::getHandle() { + return m_handle; +} // getHandle + + +/** + * @brief Get the characteristic that owns this descriptor. + * @return The characteristic that owns this descriptor. + */ +BLERemoteCharacteristic* BLERemoteDescriptor::getRemoteCharacteristic() { + return m_pRemoteCharacteristic; +} // getRemoteCharacteristic + + +/** + * @brief Retrieve the UUID associated this remote descriptor. + * @return The UUID associated this remote descriptor. + */ +BLEUUID BLERemoteDescriptor::getUUID() { + return m_uuid; +} // getUUID + + +std::string BLERemoteDescriptor::readValue() { + log_v(">> readValue: %s", toString().c_str()); + + // Check to see that we are connected. + if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) { + log_e("Disconnected"); + return std::string(); + } + + m_semaphoreReadDescrEvt.take("readValue"); + + // Ask the BLE subsystem to retrieve the value for the remote hosted characteristic. + esp_err_t errRc = ::esp_ble_gattc_read_char_descr( + m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(), + m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(), // The connection ID to the BLE server + getHandle(), // The handle of this characteristic + ESP_GATT_AUTH_REQ_NONE); // Security + + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return ""; + } + + // Block waiting for the event that indicates that the read has completed. When it has, the std::string found + // in m_value will contain our data. + m_semaphoreReadDescrEvt.wait("readValue"); + + log_v("<< readValue(): length: %d", m_value.length()); + return m_value; +} // readValue + + +uint8_t BLERemoteDescriptor::readUInt8() { + std::string value = readValue(); + if (value.length() >= 1) { + return (uint8_t) value[0]; + } + return 0; +} // readUInt8 + + +uint16_t BLERemoteDescriptor::readUInt16() { + std::string value = readValue(); + if (value.length() >= 2) { + return *(uint16_t*) value.data(); + } + return 0; +} // readUInt16 + + +uint32_t BLERemoteDescriptor::readUInt32() { + std::string value = readValue(); + if (value.length() >= 4) { + return *(uint32_t*) value.data(); + } + return 0; +} // readUInt32 + + +/** + * @brief Return a string representation of this BLE Remote Descriptor. + * @retun A string representation of this BLE Remote Descriptor. + */ +std::string BLERemoteDescriptor::toString() { + char val[6]; + snprintf(val, sizeof(val), "%d", getHandle()); + std::string res = "handle: "; + res += val; + res += ", uuid: " + getUUID().toString(); + return res; +} // toString + + +/** + * @brief Write data to the BLE Remote Descriptor. + * @param [in] data The data to send to the remote descriptor. + * @param [in] length The length of the data to send. + * @param [in] response True if we expect a response. + */ +void BLERemoteDescriptor::writeValue(uint8_t* data, size_t length, bool response) { + log_v(">> writeValue: %s", toString().c_str()); + // Check to see that we are connected. + if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) { + log_e("Disconnected"); + return; + } + + esp_err_t errRc = ::esp_ble_gattc_write_char_descr( + m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(), + m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(), + getHandle(), + length, // Data length + data, // Data + response ? ESP_GATT_WRITE_TYPE_RSP : ESP_GATT_WRITE_TYPE_NO_RSP, + ESP_GATT_AUTH_REQ_NONE + ); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_write_char_descr: %d", errRc); + } + log_v("<< writeValue"); +} // writeValue + + +/** + * @brief Write data represented as a string to the BLE Remote Descriptor. + * @param [in] newValue The data to send to the remote descriptor. + * @param [in] response True if we expect a response. + */ +void BLERemoteDescriptor::writeValue(std::string newValue, bool response) { + writeValue((uint8_t*) newValue.data(), newValue.length(), response); +} // writeValue + + +/** + * @brief Write a byte value to the Descriptor. + * @param [in] The single byte to write. + * @param [in] True if we expect a response. + */ +void BLERemoteDescriptor::writeValue(uint8_t newValue, bool response) { + writeValue(&newValue, 1, response); +} // writeValue + + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLERemoteDescriptor.h b/libraries/BLE/src/BLERemoteDescriptor.h new file mode 100644 index 00000000000..7bbc48f12d9 --- /dev/null +++ b/libraries/BLE/src/BLERemoteDescriptor.h @@ -0,0 +1,55 @@ +/* + * BLERemoteDescriptor.h + * + * Created on: Jul 8, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ +#define COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include + +#include + +#include "BLERemoteCharacteristic.h" +#include "BLEUUID.h" +#include "FreeRTOS.h" + +class BLERemoteCharacteristic; +/** + * @brief A model of remote %BLE descriptor. + */ +class BLERemoteDescriptor { +public: + uint16_t getHandle(); + BLERemoteCharacteristic* getRemoteCharacteristic(); + BLEUUID getUUID(); + std::string readValue(void); + uint8_t readUInt8(void); + uint16_t readUInt16(void); + uint32_t readUInt32(void); + std::string toString(void); + void writeValue(uint8_t* data, size_t length, bool response = false); + void writeValue(std::string newValue, bool response = false); + void writeValue(uint8_t newValue, bool response = false); + + +private: + friend class BLERemoteCharacteristic; + BLERemoteDescriptor( + uint16_t handle, + BLEUUID uuid, + BLERemoteCharacteristic* pRemoteCharacteristic + ); + uint16_t m_handle; // Server handle of this descriptor. + BLEUUID m_uuid; // UUID of this descriptor. + std::string m_value; // Last received value of the descriptor. + BLERemoteCharacteristic* m_pRemoteCharacteristic; // Reference to the Remote characteristic of which this descriptor is associated. + FreeRTOS::Semaphore m_semaphoreReadDescrEvt = FreeRTOS::Semaphore("ReadDescrEvt"); + + +}; +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ */ diff --git a/libraries/BLE/src/BLERemoteService.cpp b/libraries/BLE/src/BLERemoteService.cpp new file mode 100644 index 00000000000..278e9c1cab4 --- /dev/null +++ b/libraries/BLE/src/BLERemoteService.cpp @@ -0,0 +1,357 @@ +/* + * BLERemoteService.cpp + * + * Created on: Jul 8, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include +#include "BLERemoteService.h" +#include "BLEUtils.h" +#include "GeneralUtils.h" +#include +#include "esp32-hal-log.h" + +#pragma GCC diagnostic warning "-Wunused-but-set-parameter" + +BLERemoteService::BLERemoteService( + esp_gatt_id_t srvcId, + BLEClient* pClient, + uint16_t startHandle, + uint16_t endHandle + ) { + + log_v(">> BLERemoteService()"); + m_srvcId = srvcId; + m_pClient = pClient; + m_uuid = BLEUUID(m_srvcId); + m_haveCharacteristics = false; + m_startHandle = startHandle; + m_endHandle = endHandle; + + log_v("<< BLERemoteService()"); +} + + +BLERemoteService::~BLERemoteService() { + removeCharacteristics(); +} + +/* +static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) { + if (id1.id.inst_id != id2.id.inst_id) { + return false; + } + if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) { + return false; + } + return true; +} // compareSrvcId +*/ + +/** + * @brief Handle GATT Client events + */ +void BLERemoteService::gattClientEventHandler( + esp_gattc_cb_event_t event, + esp_gatt_if_t gattc_if, + esp_ble_gattc_cb_param_t* evtParam) { + switch (event) { + // + // ESP_GATTC_GET_CHAR_EVT + // + // get_char: + // - esp_gatt_status_t status + // - uin1t6_t conn_id + // - esp_gatt_srvc_id_t srvc_id + // - esp_gatt_id_t char_id + // - esp_gatt_char_prop_t char_prop + // + /* + case ESP_GATTC_GET_CHAR_EVT: { + // Is this event for this service? If yes, then the local srvc_id and the event srvc_id will be + // the same. + if (compareSrvcId(m_srvcId, evtParam->get_char.srvc_id) == false) { + break; + } + + // If the status is NOT OK then we have a problem and continue. + if (evtParam->get_char.status != ESP_GATT_OK) { + m_semaphoreGetCharEvt.give(); + break; + } + + // This is an indication that we now have the characteristic details for a characteristic owned + // by this service so remember it. + m_characteristicMap.insert(std::pair( + BLEUUID(evtParam->get_char.char_id.uuid).toString(), + new BLERemoteCharacteristic(evtParam->get_char.char_id, evtParam->get_char.char_prop, this) )); + + + // Now that we have received a characteristic, lets ask for the next one. + esp_err_t errRc = ::esp_ble_gattc_get_characteristic( + m_pClient->getGattcIf(), + m_pClient->getConnId(), + &m_srvcId, + &evtParam->get_char.char_id); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_get_characteristic: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + break; + } + + //m_semaphoreGetCharEvt.give(); + break; + } // ESP_GATTC_GET_CHAR_EVT +*/ + default: + break; + } // switch + + // Send the event to each of the characteristics owned by this service. + for (auto &myPair : m_characteristicMapByHandle) { + myPair.second->gattClientEventHandler(event, gattc_if, evtParam); + } +} // gattClientEventHandler + + +/** + * @brief Get the remote characteristic object for the characteristic UUID. + * @param [in] uuid Remote characteristic uuid. + * @return Reference to the remote characteristic object. + * @throws BLEUuidNotFoundException + */ +BLERemoteCharacteristic* BLERemoteService::getCharacteristic(const char* uuid) { + return getCharacteristic(BLEUUID(uuid)); +} // getCharacteristic + +/** + * @brief Get the characteristic object for the UUID. + * @param [in] uuid Characteristic uuid. + * @return Reference to the characteristic object. + * @throws BLEUuidNotFoundException + */ +BLERemoteCharacteristic* BLERemoteService::getCharacteristic(BLEUUID uuid) { +// Design +// ------ +// We wish to retrieve the characteristic given its UUID. It is possible that we have not yet asked the +// device what characteristics it has in which case we have nothing to match against. If we have not +// asked the device about its characteristics, then we do that now. Once we get the results we can then +// examine the characteristics map to see if it has the characteristic we are looking for. + if (!m_haveCharacteristics) { + retrieveCharacteristics(); + } + std::string v = uuid.toString(); + for (auto &myPair : m_characteristicMap) { + if (myPair.first == v) { + return myPair.second; + } + } + // throw new BLEUuidNotFoundException(); // <-- we dont want exception here, which will cause app crash, we want to search if any characteristic can be found one after another + return nullptr; +} // getCharacteristic + + +/** + * @brief Retrieve all the characteristics for this service. + * This function will not return until we have all the characteristics. + * @return N/A + */ +void BLERemoteService::retrieveCharacteristics() { + log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str()); + + removeCharacteristics(); // Forget any previous characteristics. + + uint16_t offset = 0; + esp_gattc_char_elem_t result; + while (true) { + uint16_t count = 1; // only room for 1 result allocated, so go one by one + esp_gatt_status_t status = ::esp_ble_gattc_get_all_char( + getClient()->getGattcIf(), + getClient()->getConnId(), + m_startHandle, + m_endHandle, + &result, + &count, + offset + ); + + if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries. + break; + } + + if (status != ESP_GATT_OK) { // If we got an error, end. + log_e("esp_ble_gattc_get_all_char: %s", BLEUtils::gattStatusToString(status).c_str()); + break; + } + + if (count == 0) { // If we failed to get any new records, end. + break; + } + + log_d("Found a characteristic: Handle: %d, UUID: %s", result.char_handle, BLEUUID(result.uuid).toString().c_str()); + + // We now have a new characteristic ... let us add that to our set of known characteristics + BLERemoteCharacteristic *pNewRemoteCharacteristic = new BLERemoteCharacteristic( + result.char_handle, + BLEUUID(result.uuid), + result.properties, + this + ); + + m_characteristicMap.insert(std::pair(pNewRemoteCharacteristic->getUUID().toString(), pNewRemoteCharacteristic)); + m_characteristicMapByHandle.insert(std::pair(result.char_handle, pNewRemoteCharacteristic)); + offset++; // Increment our count of number of descriptors found. + } // Loop forever (until we break inside the loop). + + m_haveCharacteristics = true; // Remember that we have received the characteristics. + log_v("<< getCharacteristics()"); +} // getCharacteristics + + +/** + * @brief Retrieve a map of all the characteristics of this service. + * @return A map of all the characteristics of this service. + */ +std::map* BLERemoteService::getCharacteristics() { + log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str()); + // If is possible that we have not read the characteristics associated with the service so do that + // now. The request to retrieve the characteristics by calling "retrieveCharacteristics" is a blocking + // call and does not return until all the characteristics are available. + if (!m_haveCharacteristics) { + retrieveCharacteristics(); + } + log_v("<< getCharacteristics() for service: %s", getUUID().toString().c_str()); + return &m_characteristicMap; +} // getCharacteristics + +/** + * @brief Retrieve a map of all the characteristics of this service. + * @return A map of all the characteristics of this service. + */ +std::map* BLERemoteService::getCharacteristicsByHandle() { + // If is possible that we have not read the characteristics associated with the service so do that + // now. The request to retrieve the characteristics by calling "retrieveCharacteristics" is a blocking + // call and does not return until all the characteristics are available. + if (!m_haveCharacteristics) { + retrieveCharacteristics(); + } + return &m_characteristicMapByHandle; +} // getCharacteristicsByHandle + +/** + * @brief This function is designed to get characteristics map when we have multiple characteristics with the same UUID + */ +void BLERemoteService::getCharacteristics(std::map* pCharacteristicMap) { + pCharacteristicMap = &m_characteristicMapByHandle; +} // Get the characteristics map. + +/** + * @brief Get the client associated with this service. + * @return A reference to the client associated with this service. + */ +BLEClient* BLERemoteService::getClient() { + return m_pClient; +} // getClient + + +uint16_t BLERemoteService::getEndHandle() { + return m_endHandle; +} // getEndHandle + + +esp_gatt_id_t* BLERemoteService::getSrvcId() { + return &m_srvcId; +} // getSrvcId + + +uint16_t BLERemoteService::getStartHandle() { + return m_startHandle; +} // getStartHandle + + +uint16_t BLERemoteService::getHandle() { + log_v(">> getHandle: service: %s", getUUID().toString().c_str()); + log_v("<< getHandle: %d 0x%.2x", getStartHandle(), getStartHandle()); + return getStartHandle(); +} // getHandle + + +BLEUUID BLERemoteService::getUUID() { + return m_uuid; +} + +/** + * @brief Read the value of a characteristic associated with this service. + */ +std::string BLERemoteService::getValue(BLEUUID characteristicUuid) { + log_v(">> readValue: uuid: %s", characteristicUuid.toString().c_str()); + std::string ret = getCharacteristic(characteristicUuid)->readValue(); + log_v("<< readValue"); + return ret; +} // readValue + + + +/** + * @brief Delete the characteristics in the characteristics map. + * We maintain a map called m_characteristicsMap that contains pointers to BLERemoteCharacteristic + * object references. Since we allocated these in this class, we are also responsible for deleteing + * them. This method does just that. + * @return N/A. + */ +void BLERemoteService::removeCharacteristics() { + for (auto &myPair : m_characteristicMap) { + delete myPair.second; + //m_characteristicMap.erase(myPair.first); // Should be no need to delete as it will be deleted by the clear + } + m_characteristicMap.clear(); // Clear the map + for (auto &myPair : m_characteristicMapByHandle) { + delete myPair.second; + } + m_characteristicMapByHandle.clear(); // Clear the map +} // removeCharacteristics + + +/** + * @brief Set the value of a characteristic. + * @param [in] characteristicUuid The characteristic to set. + * @param [in] value The value to set. + * @throws BLEUuidNotFound + */ +void BLERemoteService::setValue(BLEUUID characteristicUuid, std::string value) { + log_v(">> setValue: uuid: %s", characteristicUuid.toString().c_str()); + getCharacteristic(characteristicUuid)->writeValue(value); + log_v("<< setValue"); +} // setValue + + +/** + * @brief Create a string representation of this remote service. + * @return A string representation of this remote service. + */ +std::string BLERemoteService::toString() { + std::string res = "Service: uuid: " + m_uuid.toString(); + char val[6]; + res += ", start_handle: "; + snprintf(val, sizeof(val), "%d", m_startHandle); + res += val; + snprintf(val, sizeof(val), "%04x", m_startHandle); + res += " 0x"; + res += val; + res += ", end_handle: "; + snprintf(val, sizeof(val), "%d", m_endHandle); + res += val; + snprintf(val, sizeof(val), "%04x", m_endHandle); + res += " 0x"; + res += val; + for (auto &myPair : m_characteristicMap) { + res += "\n" + myPair.second->toString(); + // myPair.second is the value + } + return res; +} // toString + + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLERemoteService.h b/libraries/BLE/src/BLERemoteService.h new file mode 100644 index 00000000000..2ab86738452 --- /dev/null +++ b/libraries/BLE/src/BLERemoteService.h @@ -0,0 +1,85 @@ +/* + * BLERemoteService.h + * + * Created on: Jul 8, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ +#define COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include + +#include "BLEClient.h" +#include "BLERemoteCharacteristic.h" +#include "BLEUUID.h" +#include "FreeRTOS.h" + +class BLEClient; +class BLERemoteCharacteristic; + + +/** + * @brief A model of a remote %BLE service. + */ +class BLERemoteService { +public: + virtual ~BLERemoteService(); + + // Public methods + BLERemoteCharacteristic* getCharacteristic(const char* uuid); // Get the specified characteristic reference. + BLERemoteCharacteristic* getCharacteristic(BLEUUID uuid); // Get the specified characteristic reference. + BLERemoteCharacteristic* getCharacteristic(uint16_t uuid); // Get the specified characteristic reference. + std::map* getCharacteristics(); + std::map* getCharacteristicsByHandle(); // Get the characteristics map. + void getCharacteristics(std::map* pCharacteristicMap); + + BLEClient* getClient(void); // Get a reference to the client associated with this service. + uint16_t getHandle(); // Get the handle of this service. + BLEUUID getUUID(void); // Get the UUID of this service. + std::string getValue(BLEUUID characteristicUuid); // Get the value of a characteristic. + void setValue(BLEUUID characteristicUuid, std::string value); // Set the value of a characteristic. + std::string toString(void); + +private: + // Private constructor ... never meant to be created by a user application. + BLERemoteService(esp_gatt_id_t srvcId, BLEClient* pClient, uint16_t startHandle, uint16_t endHandle); + + // Friends + friend class BLEClient; + friend class BLERemoteCharacteristic; + + // Private methods + void retrieveCharacteristics(void); // Retrieve the characteristics from the BLE Server. + esp_gatt_id_t* getSrvcId(void); + uint16_t getStartHandle(); // Get the start handle for this service. + uint16_t getEndHandle(); // Get the end handle for this service. + + void gattClientEventHandler( + esp_gattc_cb_event_t event, + esp_gatt_if_t gattc_if, + esp_ble_gattc_cb_param_t* evtParam); + + void removeCharacteristics(); + + // Properties + + // We maintain a map of characteristics owned by this service keyed by a string representation of the UUID. + std::map m_characteristicMap; + + // We maintain a map of characteristics owned by this service keyed by a handle. + std::map m_characteristicMapByHandle; + + bool m_haveCharacteristics; // Have we previously obtained the characteristics. + BLEClient* m_pClient; + FreeRTOS::Semaphore m_semaphoreGetCharEvt = FreeRTOS::Semaphore("GetCharEvt"); + esp_gatt_id_t m_srvcId; + BLEUUID m_uuid; // The UUID of this service. + uint16_t m_startHandle; // The starting handle of this service. + uint16_t m_endHandle; // The ending handle of this service. +}; // BLERemoteService + +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ */ diff --git a/libraries/BLE/src/BLEScan.cpp b/libraries/BLE/src/BLEScan.cpp new file mode 100644 index 00000000000..cb28dd395a7 --- /dev/null +++ b/libraries/BLE/src/BLEScan.cpp @@ -0,0 +1,322 @@ +/* + * BLEScan.cpp + * + * Created on: Jul 1, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + + +#include + +#include + +#include "BLEAdvertisedDevice.h" +#include "BLEScan.h" +#include "BLEUtils.h" +#include "GeneralUtils.h" +#include "esp32-hal-log.h" + +/** + * Constructor + */ +BLEScan::BLEScan() { + m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE; // Default is a passive scan. + m_scan_params.own_addr_type = BLE_ADDR_TYPE_PUBLIC; + m_scan_params.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL; + m_pAdvertisedDeviceCallbacks = nullptr; + m_stopped = true; + m_wantDuplicates = false; + setInterval(100); + setWindow(100); +} // BLEScan + + +/** + * @brief Handle GAP events related to scans. + * @param [in] event The event type for this event. + * @param [in] param Parameter data for this event. + */ +void BLEScan::handleGAPEvent( + esp_gap_ble_cb_event_t event, + esp_ble_gap_cb_param_t* param) { + + switch(event) { + + // --------------------------- + // scan_rst: + // esp_gap_search_evt_t search_evt + // esp_bd_addr_t bda + // esp_bt_dev_type_t dev_type + // esp_ble_addr_type_t ble_addr_type + // esp_ble_evt_type_t ble_evt_type + // int rssi + // uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX] + // int flag + // int num_resps + // uint8_t adv_data_len + // uint8_t scan_rsp_len + case ESP_GAP_BLE_SCAN_RESULT_EVT: { + + switch(param->scan_rst.search_evt) { + // + // ESP_GAP_SEARCH_INQ_CMPL_EVT + // + // Event that indicates that the duration allowed for the search has completed or that we have been + // asked to stop. + case ESP_GAP_SEARCH_INQ_CMPL_EVT: { + log_w("ESP_GAP_SEARCH_INQ_CMPL_EVT"); + m_stopped = true; + m_semaphoreScanEnd.give(); + if (m_scanCompleteCB != nullptr) { + m_scanCompleteCB(m_scanResults); + } + break; + } // ESP_GAP_SEARCH_INQ_CMPL_EVT + + // + // ESP_GAP_SEARCH_INQ_RES_EVT + // + // Result that has arrived back from a Scan inquiry. + case ESP_GAP_SEARCH_INQ_RES_EVT: { + if (m_stopped) { // If we are not scanning, nothing to do with the extra results. + break; + } + +// Examine our list of previously scanned addresses and, if we found this one already, +// ignore it. + BLEAddress advertisedAddress(param->scan_rst.bda); + bool found = false; + + if (m_scanResults.m_vectorAdvertisedDevices.count(advertisedAddress.toString()) != 0) { + found = true; + } + + if (found && !m_wantDuplicates) { // If we found a previous entry AND we don't want duplicates, then we are done. + log_d("Ignoring %s, already seen it.", advertisedAddress.toString().c_str()); + vTaskDelay(1); // <--- allow to switch task in case we scan infinity and dont have new devices to report, or we are blocked here + break; + } + + // We now construct a model of the advertised device that we have just found for the first + // time. + // ESP_LOG_BUFFER_HEXDUMP((uint8_t*)param->scan_rst.ble_adv, param->scan_rst.adv_data_len + param->scan_rst.scan_rsp_len, ESP_LOG_DEBUG); + // log_w("bytes length: %d + %d, addr type: %d", param->scan_rst.adv_data_len, param->scan_rst.scan_rsp_len, param->scan_rst.ble_addr_type); + BLEAdvertisedDevice *advertisedDevice = new BLEAdvertisedDevice(); + advertisedDevice->setAddress(advertisedAddress); + advertisedDevice->setRSSI(param->scan_rst.rssi); + advertisedDevice->setAdFlag(param->scan_rst.flag); + advertisedDevice->parseAdvertisement((uint8_t*)param->scan_rst.ble_adv, param->scan_rst.adv_data_len + param->scan_rst.scan_rsp_len); + advertisedDevice->setScan(this); + advertisedDevice->setAddressType(param->scan_rst.ble_addr_type); + + if (!found) { // If we have previously seen this device, don't record it again. + m_scanResults.m_vectorAdvertisedDevices.insert(std::pair(advertisedAddress.toString(), advertisedDevice)); + } + + if (m_pAdvertisedDeviceCallbacks) { + m_pAdvertisedDeviceCallbacks->onResult(*advertisedDevice); + } + if(found) + delete advertisedDevice; + + break; + } // ESP_GAP_SEARCH_INQ_RES_EVT + + default: { + break; + } + } // switch - search_evt + + + break; + } // ESP_GAP_BLE_SCAN_RESULT_EVT + + default: { + break; + } // default + } // End switch +} // gapEventHandler + + +/** + * @brief Should we perform an active or passive scan? + * The default is a passive scan. An active scan means that we will wish a scan response. + * @param [in] active If true, we perform an active scan otherwise a passive scan. + * @return N/A. + */ +void BLEScan::setActiveScan(bool active) { + if (active) { + m_scan_params.scan_type = BLE_SCAN_TYPE_ACTIVE; + } else { + m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE; + } +} // setActiveScan + + +/** + * @brief Set the call backs to be invoked. + * @param [in] pAdvertisedDeviceCallbacks Call backs to be invoked. + * @param [in] wantDuplicates True if we wish to be called back with duplicates. Default is false. + */ +void BLEScan::setAdvertisedDeviceCallbacks(BLEAdvertisedDeviceCallbacks* pAdvertisedDeviceCallbacks, bool wantDuplicates) { + m_wantDuplicates = wantDuplicates; + m_pAdvertisedDeviceCallbacks = pAdvertisedDeviceCallbacks; +} // setAdvertisedDeviceCallbacks + + +/** + * @brief Set the interval to scan. + * @param [in] The interval in msecs. + */ +void BLEScan::setInterval(uint16_t intervalMSecs) { + m_scan_params.scan_interval = intervalMSecs / 0.625; +} // setInterval + + +/** + * @brief Set the window to actively scan. + * @param [in] windowMSecs How long to actively scan. + */ +void BLEScan::setWindow(uint16_t windowMSecs) { + m_scan_params.scan_window = windowMSecs / 0.625; +} // setWindow + + +/** + * @brief Start scanning. + * @param [in] duration The duration in seconds for which to scan. + * @param [in] scanCompleteCB A function to be called when scanning has completed. + * @param [in] are we continue scan (true) or we want to clear stored devices (false) + * @return True if scan started or false if there was an error. + */ +bool BLEScan::start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), bool is_continue) { + log_v(">> start(duration=%d)", duration); + + m_semaphoreScanEnd.take(std::string("start")); + m_scanCompleteCB = scanCompleteCB; // Save the callback to be invoked when the scan completes. + + // if we are connecting to devices that are advertising even after being connected, multiconnecting peripherals + // then we should not clear map or we will connect the same device few times + if(!is_continue) { + for(auto _dev : m_scanResults.m_vectorAdvertisedDevices){ + delete _dev.second; + } + m_scanResults.m_vectorAdvertisedDevices.clear(); + } + + esp_err_t errRc = ::esp_ble_gap_set_scan_params(&m_scan_params); + + if (errRc != ESP_OK) { + log_e("esp_ble_gap_set_scan_params: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); + m_semaphoreScanEnd.give(); + return false; + } + + errRc = ::esp_ble_gap_start_scanning(duration); + + if (errRc != ESP_OK) { + log_e("esp_ble_gap_start_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); + m_semaphoreScanEnd.give(); + return false; + } + + m_stopped = false; + + log_v("<< start()"); + return true; +} // start + + +/** + * @brief Start scanning and block until scanning has been completed. + * @param [in] duration The duration in seconds for which to scan. + * @return The BLEScanResults. + */ +BLEScanResults BLEScan::start(uint32_t duration, bool is_continue) { + if(start(duration, nullptr, is_continue)) { + m_semaphoreScanEnd.wait("start"); // Wait for the semaphore to release. + } + return m_scanResults; +} // start + + +/** + * @brief Stop an in progress scan. + * @return N/A. + */ +void BLEScan::stop() { + log_v(">> stop()"); + + esp_err_t errRc = ::esp_ble_gap_stop_scanning(); + + m_stopped = true; + m_semaphoreScanEnd.give(); + + if (errRc != ESP_OK) { + log_e("esp_ble_gap_stop_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + + log_v("<< stop()"); +} // stop + +// delete peer device from cache after disconnecting, it is required in case we are connecting to devices with not public address +void BLEScan::erase(BLEAddress address) { + log_i("erase device: %s", address.toString().c_str()); + BLEAdvertisedDevice *advertisedDevice = m_scanResults.m_vectorAdvertisedDevices.find(address.toString())->second; + m_scanResults.m_vectorAdvertisedDevices.erase(address.toString()); + delete advertisedDevice; +} + + +/** + * @brief Dump the scan results to the log. + */ +void BLEScanResults::dump() { + log_v(">> Dump scan results:"); + for (int i=0; isecond; + for (auto it = m_vectorAdvertisedDevices.begin(); it != m_vectorAdvertisedDevices.end(); it++) { + dev = *it->second; + if (x==i) break; + x++; + } + return dev; +} + +BLEScanResults BLEScan::getResults() { + return m_scanResults; +} + +void BLEScan::clearResults() { + for(auto _dev : m_scanResults.m_vectorAdvertisedDevices){ + delete _dev.second; + } + m_scanResults.m_vectorAdvertisedDevices.clear(); +} + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEScan.h b/libraries/BLE/src/BLEScan.h new file mode 100644 index 00000000000..2f71a72738e --- /dev/null +++ b/libraries/BLE/src/BLEScan.h @@ -0,0 +1,83 @@ +/* + * BLEScan.h + * + * Created on: Jul 1, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLESCAN_H_ +#define COMPONENTS_CPP_UTILS_BLESCAN_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include + +// #include +#include +#include "BLEAdvertisedDevice.h" +#include "BLEClient.h" +#include "FreeRTOS.h" + +class BLEAdvertisedDevice; +class BLEAdvertisedDeviceCallbacks; +class BLEClient; +class BLEScan; + + +/** + * @brief The result of having performed a scan. + * When a scan completes, we have a set of found devices. Each device is described + * by a BLEAdvertisedDevice object. The number of items in the set is given by + * getCount(). We can retrieve a device by calling getDevice() passing in the + * index (starting at 0) of the desired device. + */ +class BLEScanResults { +public: + void dump(); + int getCount(); + BLEAdvertisedDevice getDevice(uint32_t i); + +private: + friend BLEScan; + std::map m_vectorAdvertisedDevices; +}; + +/** + * @brief Perform and manage %BLE scans. + * + * Scanning is associated with a %BLE client that is attempting to locate BLE servers. + */ +class BLEScan { +public: + void setActiveScan(bool active); + void setAdvertisedDeviceCallbacks( + BLEAdvertisedDeviceCallbacks* pAdvertisedDeviceCallbacks, + bool wantDuplicates = false); + void setInterval(uint16_t intervalMSecs); + void setWindow(uint16_t windowMSecs); + bool start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), bool is_continue = false); + BLEScanResults start(uint32_t duration, bool is_continue = false); + void stop(); + void erase(BLEAddress address); + BLEScanResults getResults(); + void clearResults(); + +private: + BLEScan(); // One doesn't create a new instance instead one asks the BLEDevice for the singleton. + friend class BLEDevice; + void handleGAPEvent( + esp_gap_ble_cb_event_t event, + esp_ble_gap_cb_param_t* param); + void parseAdvertisement(BLEClient* pRemoteDevice, uint8_t *payload); + + + esp_ble_scan_params_t m_scan_params; + BLEAdvertisedDeviceCallbacks* m_pAdvertisedDeviceCallbacks = nullptr; + bool m_stopped = true; + FreeRTOS::Semaphore m_semaphoreScanEnd = FreeRTOS::Semaphore("ScanEnd"); + BLEScanResults m_scanResults; + bool m_wantDuplicates; + void (*m_scanCompleteCB)(BLEScanResults scanResults); +}; // BLEScan + +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLESCAN_H_ */ diff --git a/libraries/BLE/src/BLESecurity.cpp b/libraries/BLE/src/BLESecurity.cpp new file mode 100644 index 00000000000..921f5424431 --- /dev/null +++ b/libraries/BLE/src/BLESecurity.cpp @@ -0,0 +1,104 @@ +/* + * BLESecurity.cpp + * + * Created on: Dec 17, 2017 + * Author: chegewara + */ + +#include "BLESecurity.h" +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +BLESecurity::BLESecurity() { +} + +BLESecurity::~BLESecurity() { +} +/* + * @brief Set requested authentication mode + */ +void BLESecurity::setAuthenticationMode(esp_ble_auth_req_t auth_req) { + m_authReq = auth_req; + esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &m_authReq, sizeof(uint8_t)); // <--- setup requested authentication mode +} + +/** + * @brief Set our device IO capability to let end user perform authorization + * either by displaying or entering generated 6-digits pin code + */ +void BLESecurity::setCapability(esp_ble_io_cap_t iocap) { + m_iocap = iocap; + esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); +} // setCapability + + +/** + * @brief Init encryption key by server + * @param key_size is value between 7 and 16 + */ +void BLESecurity::setInitEncryptionKey(uint8_t init_key) { + m_initKey = init_key; + esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &m_initKey, sizeof(uint8_t)); +} // setInitEncryptionKey + + +/** + * @brief Init encryption key by client + * @param key_size is value between 7 and 16 + */ +void BLESecurity::setRespEncryptionKey(uint8_t resp_key) { + m_respKey = resp_key; + esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &m_respKey, sizeof(uint8_t)); +} // setRespEncryptionKey + + +/** + * + * + */ +void BLESecurity::setKeySize(uint8_t key_size) { + m_keySize = key_size; + esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &m_keySize, sizeof(uint8_t)); +} //setKeySize + + +/** + * @brief Debug function to display what keys are exchanged by peers + */ +char* BLESecurity::esp_key_type_to_str(esp_ble_key_type_t key_type) { + char* key_str = nullptr; + switch (key_type) { + case ESP_LE_KEY_NONE: + key_str = (char*) "ESP_LE_KEY_NONE"; + break; + case ESP_LE_KEY_PENC: + key_str = (char*) "ESP_LE_KEY_PENC"; + break; + case ESP_LE_KEY_PID: + key_str = (char*) "ESP_LE_KEY_PID"; + break; + case ESP_LE_KEY_PCSRK: + key_str = (char*) "ESP_LE_KEY_PCSRK"; + break; + case ESP_LE_KEY_PLK: + key_str = (char*) "ESP_LE_KEY_PLK"; + break; + case ESP_LE_KEY_LLK: + key_str = (char*) "ESP_LE_KEY_LLK"; + break; + case ESP_LE_KEY_LENC: + key_str = (char*) "ESP_LE_KEY_LENC"; + break; + case ESP_LE_KEY_LID: + key_str = (char*) "ESP_LE_KEY_LID"; + break; + case ESP_LE_KEY_LCSRK: + key_str = (char*) "ESP_LE_KEY_LCSRK"; + break; + default: + key_str = (char*) "INVALID BLE KEY TYPE"; + break; + } + return key_str; +} // esp_key_type_to_str +#endif // CONFIG_BT_ENABLED diff --git a/libraries/BLE/src/BLESecurity.h b/libraries/BLE/src/BLESecurity.h new file mode 100644 index 00000000000..48d09d2f3f6 --- /dev/null +++ b/libraries/BLE/src/BLESecurity.h @@ -0,0 +1,72 @@ +/* + * BLESecurity.h + * + * Created on: Dec 17, 2017 + * Author: chegewara + */ + +#ifndef COMPONENTS_CPP_UTILS_BLESECURITY_H_ +#define COMPONENTS_CPP_UTILS_BLESECURITY_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include + +class BLESecurity { +public: + BLESecurity(); + virtual ~BLESecurity(); + void setAuthenticationMode(esp_ble_auth_req_t auth_req); + void setCapability(esp_ble_io_cap_t iocap); + void setInitEncryptionKey(uint8_t init_key); + void setRespEncryptionKey(uint8_t resp_key); + void setKeySize(uint8_t key_size = 16); + static char* esp_key_type_to_str(esp_ble_key_type_t key_type); + +private: + esp_ble_auth_req_t m_authReq; + esp_ble_io_cap_t m_iocap; + uint8_t m_initKey; + uint8_t m_respKey; + uint8_t m_keySize; + +}; // BLESecurity + + +/* + * @brief Callbacks to handle GAP events related to authorization + */ +class BLESecurityCallbacks { +public: + virtual ~BLESecurityCallbacks() {}; + + /** + * @brief Its request from peer device to input authentication pin code displayed on peer device. + * It requires that our device is capable to input 6-digits code by end user + * @return Return 6-digits integer value from input device + */ + virtual uint32_t onPassKeyRequest() = 0; + + /** + * @brief Provide us 6-digits code to perform authentication. + * It requires that our device is capable to display this code to end user + * @param + */ + virtual void onPassKeyNotify(uint32_t pass_key) = 0; + + /** + * @brief Here we can make decision if we want to let negotiate authorization with peer device or not + * return Return true if we accept this peer device request + */ + + virtual bool onSecurityRequest() = 0 ; + /** + * Provide us information when authentication process is completed + */ + virtual void onAuthenticationComplete(esp_ble_auth_cmpl_t) = 0; + + virtual bool onConfirmPIN(uint32_t pin) = 0; +}; // BLESecurityCallbacks + +#endif // CONFIG_BT_ENABLED +#endif // COMPONENTS_CPP_UTILS_BLESECURITY_H_ diff --git a/libraries/BLE/src/BLEServer.cpp b/libraries/BLE/src/BLEServer.cpp new file mode 100644 index 00000000000..73d60c81cfe --- /dev/null +++ b/libraries/BLE/src/BLEServer.cpp @@ -0,0 +1,420 @@ +/* + * BLEServer.cpp + * + * Created on: Apr 16, 2017 + * Author: kolban + */ + +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include "GeneralUtils.h" +#include "BLEDevice.h" +#include "BLEServer.h" +#include "BLEService.h" +#include "BLEUtils.h" +#include +#include +#include +#include "esp32-hal-log.h" + +/** + * @brief Construct a %BLE Server + * + * This class is not designed to be individually instantiated. Instead one should create a server by asking + * the BLEDevice class. + */ +BLEServer::BLEServer() { + m_appId = ESP_GATT_IF_NONE; + m_gatts_if = ESP_GATT_IF_NONE; + m_connectedCount = 0; + m_connId = ESP_GATT_IF_NONE; + m_pServerCallbacks = nullptr; +} // BLEServer + + +void BLEServer::createApp(uint16_t appId) { + m_appId = appId; + registerApp(appId); +} // createApp + + +/** + * @brief Create a %BLE Service. + * + * With a %BLE server, we can host one or more services. Invoking this function causes the creation of a definition + * of a new service. Every service must have a unique UUID. + * @param [in] uuid The UUID of the new service. + * @return A reference to the new service object. + */ +BLEService* BLEServer::createService(const char* uuid) { + return createService(BLEUUID(uuid)); +} + + +/** + * @brief Create a %BLE Service. + * + * With a %BLE server, we can host one or more services. Invoking this function causes the creation of a definition + * of a new service. Every service must have a unique UUID. + * @param [in] uuid The UUID of the new service. + * @param [in] numHandles The maximum number of handles associated with this service. + * @param [in] inst_id With multiple services with the same UUID we need to provide inst_id value different for each service. + * @return A reference to the new service object. + */ +BLEService* BLEServer::createService(BLEUUID uuid, uint32_t numHandles, uint8_t inst_id) { + log_v(">> createService - %s", uuid.toString().c_str()); + m_semaphoreCreateEvt.take("createService"); + + // Check that a service with the supplied UUID does not already exist. + if (m_serviceMap.getByUUID(uuid) != nullptr) { + log_w("<< Attempt to create a new service with uuid %s but a service with that UUID already exists.", + uuid.toString().c_str()); + } + + BLEService* pService = new BLEService(uuid, numHandles); + pService->m_instId = inst_id; + m_serviceMap.setByUUID(uuid, pService); // Save a reference to this service being on this server. + pService->executeCreate(this); // Perform the API calls to actually create the service. + + m_semaphoreCreateEvt.wait("createService"); + + log_v("<< createService"); + return pService; +} // createService + + +/** + * @brief Get a %BLE Service by its UUID + * @param [in] uuid The UUID of the new service. + * @return A reference to the service object. + */ +BLEService* BLEServer::getServiceByUUID(const char* uuid) { + return m_serviceMap.getByUUID(uuid); +} + +/** + * @brief Get a %BLE Service by its UUID + * @param [in] uuid The UUID of the new service. + * @return A reference to the service object. + */ +BLEService* BLEServer::getServiceByUUID(BLEUUID uuid) { + return m_serviceMap.getByUUID(uuid); +} + +/** + * @brief Retrieve the advertising object that can be used to advertise the existence of the server. + * + * @return An advertising object. + */ +BLEAdvertising* BLEServer::getAdvertising() { + return BLEDevice::getAdvertising(); +} + +uint16_t BLEServer::getConnId() { + return m_connId; +} + + +/** + * @brief Return the number of connected clients. + * @return The number of connected clients. + */ +uint32_t BLEServer::getConnectedCount() { + return m_connectedCount; +} // getConnectedCount + + +uint16_t BLEServer::getGattsIf() { + return m_gatts_if; +} + + +/** + * @brief Handle a GATT Server Event. + * + * @param [in] event + * @param [in] gatts_if + * @param [in] param + * + */ +void BLEServer::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { + log_v(">> handleGATTServerEvent: %s", + BLEUtils::gattServerEventTypeToString(event).c_str()); + + switch(event) { + // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. + // add_char: + // - esp_gatt_status_t status + // - uint16_t attr_handle + // - uint16_t service_handle + // - esp_bt_uuid_t char_uuid + // + case ESP_GATTS_ADD_CHAR_EVT: { + break; + } // ESP_GATTS_ADD_CHAR_EVT + + case ESP_GATTS_MTU_EVT: + updatePeerMTU(param->mtu.conn_id, param->mtu.mtu); + break; + + // ESP_GATTS_CONNECT_EVT + // connect: + // - uint16_t conn_id + // - esp_bd_addr_t remote_bda + // + case ESP_GATTS_CONNECT_EVT: { + m_connId = param->connect.conn_id; + addPeerDevice((void*)this, false, m_connId); + if (m_pServerCallbacks != nullptr) { + m_pServerCallbacks->onConnect(this); + m_pServerCallbacks->onConnect(this, param); + } + m_connectedCount++; // Increment the number of connected devices count. + break; + } // ESP_GATTS_CONNECT_EVT + + + // ESP_GATTS_CREATE_EVT + // Called when a new service is registered as having been created. + // + // create: + // * esp_gatt_status_t status + // * uint16_t service_handle + // * esp_gatt_srvc_id_t service_id + // + case ESP_GATTS_CREATE_EVT: { + BLEService* pService = m_serviceMap.getByUUID(param->create.service_id.id.uuid, param->create.service_id.id.inst_id); // <--- very big bug for multi services with the same uuid + m_serviceMap.setByHandle(param->create.service_handle, pService); + m_semaphoreCreateEvt.give(); + break; + } // ESP_GATTS_CREATE_EVT + + + // ESP_GATTS_DISCONNECT_EVT + // + // disconnect + // - uint16_t conn_id + // - esp_bd_addr_t remote_bda + // - esp_gatt_conn_reason_t reason + // + // If we receive a disconnect event then invoke the callback for disconnects (if one is present). + // we also want to start advertising again. + case ESP_GATTS_DISCONNECT_EVT: { + m_connectedCount--; // Decrement the number of connected devices count. + if (m_pServerCallbacks != nullptr) { // If we have callbacks, call now. + m_pServerCallbacks->onDisconnect(this); + } + startAdvertising(); //- do this with some delay from the loop() + removePeerDevice(param->disconnect.conn_id, false); + break; + } // ESP_GATTS_DISCONNECT_EVT + + + // ESP_GATTS_READ_EVT - A request to read the value of a characteristic has arrived. + // + // read: + // - uint16_t conn_id + // - uint32_t trans_id + // - esp_bd_addr_t bda + // - uint16_t handle + // - uint16_t offset + // - bool is_long + // - bool need_rsp + // + case ESP_GATTS_READ_EVT: { + break; + } // ESP_GATTS_READ_EVT + + + // ESP_GATTS_REG_EVT + // reg: + // - esp_gatt_status_t status + // - uint16_t app_id + // + case ESP_GATTS_REG_EVT: { + m_gatts_if = gatts_if; + m_semaphoreRegisterAppEvt.give(); // Unlock the mutex waiting for the registration of the app. + break; + } // ESP_GATTS_REG_EVT + + + // ESP_GATTS_WRITE_EVT - A request to write the value of a characteristic has arrived. + // + // write: + // - uint16_t conn_id + // - uint16_t trans_id + // - esp_bd_addr_t bda + // - uint16_t handle + // - uint16_t offset + // - bool need_rsp + // - bool is_prep + // - uint16_t len + // - uint8_t* value + // + case ESP_GATTS_WRITE_EVT: { + break; + } + + case ESP_GATTS_OPEN_EVT: + m_semaphoreOpenEvt.give(param->open.status); + break; + + default: + break; + } + + // Invoke the handler for every Service we have. + m_serviceMap.handleGATTServerEvent(event, gatts_if, param); + + log_v("<< handleGATTServerEvent"); +} // handleGATTServerEvent + + +/** + * @brief Register the app. + * + * @return N/A + */ +void BLEServer::registerApp(uint16_t m_appId) { + log_v(">> registerApp - %d", m_appId); + m_semaphoreRegisterAppEvt.take("registerApp"); // Take the mutex, will be released by ESP_GATTS_REG_EVT event. + ::esp_ble_gatts_app_register(m_appId); + m_semaphoreRegisterAppEvt.wait("registerApp"); + log_v("<< registerApp"); +} // registerApp + + +/** + * @brief Set the server callbacks. + * + * As a %BLE server operates, it will generate server level events such as a new client connecting or a previous client + * disconnecting. This function can be called to register a callback handler that will be invoked when these + * events are detected. + * + * @param [in] pCallbacks The callbacks to be invoked. + */ +void BLEServer::setCallbacks(BLEServerCallbacks* pCallbacks) { + m_pServerCallbacks = pCallbacks; +} // setCallbacks + +/* + * Remove service + */ +void BLEServer::removeService(BLEService* service) { + service->stop(); + service->executeDelete(); + m_serviceMap.removeService(service); +} + +/** + * @brief Start advertising. + * + * Start the server advertising its existence. This is a convenience function and is equivalent to + * retrieving the advertising object and invoking start upon it. + */ +void BLEServer::startAdvertising() { + log_v(">> startAdvertising"); + BLEDevice::startAdvertising(); + log_v("<< startAdvertising"); +} // startAdvertising + +/** + * Allow to connect GATT server to peer device + * Probably can be used in ANCS for iPhone + */ +bool BLEServer::connect(BLEAddress address) { + esp_bd_addr_t addr; + memcpy(&addr, address.getNative(), 6); + // Perform the open connection request against the target BLE Server. + m_semaphoreOpenEvt.take("connect"); + esp_err_t errRc = ::esp_ble_gatts_open( + getGattsIf(), + addr, // address + 1 // direct connection + ); + if (errRc != ESP_OK) { + log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return false; + } + + uint32_t rc = m_semaphoreOpenEvt.wait("connect"); // Wait for the connection to complete. + log_v("<< connect(), rc=%d", rc==ESP_GATT_OK); + return rc == ESP_GATT_OK; +} // connect + + + +void BLEServerCallbacks::onConnect(BLEServer* pServer) { + log_d("BLEServerCallbacks", ">> onConnect(): Default"); + log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); + log_d("BLEServerCallbacks", "<< onConnect()"); +} // onConnect + +void BLEServerCallbacks::onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t* param) { + log_d("BLEServerCallbacks", ">> onConnect(): Default"); + log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); + log_d("BLEServerCallbacks", "<< onConnect()"); +} // onConnect + + +void BLEServerCallbacks::onDisconnect(BLEServer* pServer) { + log_d("BLEServerCallbacks", ">> onDisconnect(): Default"); + log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); + log_d("BLEServerCallbacks", "<< onDisconnect()"); +} // onDisconnect + +/* multi connect support */ +/* TODO do some more tweaks */ +void BLEServer::updatePeerMTU(uint16_t conn_id, uint16_t mtu) { + // set mtu in conn_status_t + const std::map::iterator it = m_connectedServersMap.find(conn_id); + if (it != m_connectedServersMap.end()) { + it->second.mtu = mtu; + std::swap(m_connectedServersMap[conn_id], it->second); + } +} + +std::map BLEServer::getPeerDevices(bool _client) { + return m_connectedServersMap; +} + + +uint16_t BLEServer::getPeerMTU(uint16_t conn_id) { + return m_connectedServersMap.find(conn_id)->second.mtu; +} + +void BLEServer::addPeerDevice(void* peer, bool _client, uint16_t conn_id) { + conn_status_t status = { + .peer_device = peer, + .connected = true, + .mtu = 23 + }; + + m_connectedServersMap.insert(std::pair(conn_id, status)); +} + +void BLEServer::removePeerDevice(uint16_t conn_id, bool _client) { + m_connectedServersMap.erase(conn_id); +} +/* multi connect support */ + +/** + * Update connection parameters can be called only after connection has been established + */ +void BLEServer::updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout) { + esp_ble_conn_update_params_t conn_params; + memcpy(conn_params.bda, remote_bda, sizeof(esp_bd_addr_t)); + conn_params.latency = latency; + conn_params.max_int = maxInterval; // max_int = 0x20*1.25ms = 40ms + conn_params.min_int = minInterval; // min_int = 0x10*1.25ms = 20ms + conn_params.timeout = timeout; // timeout = 400*10ms = 4000ms + esp_ble_gap_update_conn_params(&conn_params); +} + +void BLEServer::disconnect(uint16_t connId) { + esp_ble_gatts_close(m_gatts_if, connId); +} + +#endif // CONFIG_BT_ENABLED diff --git a/libraries/BLE/src/BLEServer.h b/libraries/BLE/src/BLEServer.h new file mode 100644 index 00000000000..d2f8038d268 --- /dev/null +++ b/libraries/BLE/src/BLEServer.h @@ -0,0 +1,141 @@ +/* + * BLEServer.h + * + * Created on: Apr 16, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLESERVER_H_ +#define COMPONENTS_CPP_UTILS_BLESERVER_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include + +#include +#include +// #include "BLEDevice.h" + +#include "BLEUUID.h" +#include "BLEAdvertising.h" +#include "BLECharacteristic.h" +#include "BLEService.h" +#include "BLESecurity.h" +#include "FreeRTOS.h" +#include "BLEAddress.h" + +class BLEServerCallbacks; +/* TODO possibly refactor this struct */ +typedef struct { + void *peer_device; // peer device BLEClient or BLEServer - maybe its better to have 2 structures or union here + bool connected; // do we need it? + uint16_t mtu; // every peer device negotiate own mtu +} conn_status_t; + + +/** + * @brief A data structure that manages the %BLE servers owned by a BLE server. + */ +class BLEServiceMap { +public: + BLEService* getByHandle(uint16_t handle); + BLEService* getByUUID(const char* uuid); + BLEService* getByUUID(BLEUUID uuid, uint8_t inst_id = 0); + void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param); + void setByHandle(uint16_t handle, BLEService* service); + void setByUUID(const char* uuid, BLEService* service); + void setByUUID(BLEUUID uuid, BLEService* service); + std::string toString(); + BLEService* getFirst(); + BLEService* getNext(); + void removeService(BLEService *service); + int getRegisteredServiceCount(); + +private: + std::map m_handleMap; + std::map m_uuidMap; + std::map::iterator m_iterator; +}; + + +/** + * @brief The model of a %BLE server. + */ +class BLEServer { +public: + uint32_t getConnectedCount(); + BLEService* createService(const char* uuid); + BLEService* createService(BLEUUID uuid, uint32_t numHandles=15, uint8_t inst_id=0); + BLEAdvertising* getAdvertising(); + void setCallbacks(BLEServerCallbacks* pCallbacks); + void startAdvertising(); + void removeService(BLEService* service); + BLEService* getServiceByUUID(const char* uuid); + BLEService* getServiceByUUID(BLEUUID uuid); + bool connect(BLEAddress address); + void disconnect(uint16_t connId); + uint16_t m_appId; + void updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout); + + /* multi connection support */ + std::map getPeerDevices(bool client); + void addPeerDevice(void* peer, bool is_client, uint16_t conn_id); + void removePeerDevice(uint16_t conn_id, bool client); + BLEServer* getServerByConnId(uint16_t conn_id); + void updatePeerMTU(uint16_t connId, uint16_t mtu); + uint16_t getPeerMTU(uint16_t conn_id); + uint16_t getConnId(); + + +private: + BLEServer(); + friend class BLEService; + friend class BLECharacteristic; + friend class BLEDevice; + esp_ble_adv_data_t m_adv_data; + // BLEAdvertising m_bleAdvertising; + uint16_t m_connId; + uint32_t m_connectedCount; + uint16_t m_gatts_if; + std::map m_connectedServersMap; + + FreeRTOS::Semaphore m_semaphoreRegisterAppEvt = FreeRTOS::Semaphore("RegisterAppEvt"); + FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); + FreeRTOS::Semaphore m_semaphoreOpenEvt = FreeRTOS::Semaphore("OpenEvt"); + BLEServiceMap m_serviceMap; + BLEServerCallbacks* m_pServerCallbacks = nullptr; + + void createApp(uint16_t appId); + uint16_t getGattsIf(); + void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param); + void registerApp(uint16_t); +}; // BLEServer + + +/** + * @brief Callbacks associated with the operation of a %BLE server. + */ +class BLEServerCallbacks { +public: + virtual ~BLEServerCallbacks() {}; + /** + * @brief Handle a new client connection. + * + * When a new client connects, we are invoked. + * + * @param [in] pServer A reference to the %BLE server that received the client connection. + */ + virtual void onConnect(BLEServer* pServer); + virtual void onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t *param); + /** + * @brief Handle an existing client disconnection. + * + * When an existing client disconnects, we are invoked. + * + * @param [in] pServer A reference to the %BLE server that received the existing client disconnection. + */ + virtual void onDisconnect(BLEServer* pServer); +}; // BLEServerCallbacks + + +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLESERVER_H_ */ diff --git a/libraries/BLE/src/BLEService.cpp b/libraries/BLE/src/BLEService.cpp new file mode 100644 index 00000000000..3ea6141c0d4 --- /dev/null +++ b/libraries/BLE/src/BLEService.cpp @@ -0,0 +1,413 @@ +/* + * BLEService.cpp + * + * Created on: Mar 25, 2017 + * Author: kolban + */ + +// A service is identified by a UUID. A service is also the container for one or more characteristics. + +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include + +#include +#include +#include + +#include "BLEServer.h" +#include "BLEService.h" +#include "BLEUtils.h" +#include "GeneralUtils.h" +#include "esp32-hal-log.h" + +#define NULL_HANDLE (0xffff) + + +/** + * @brief Construct an instance of the BLEService + * @param [in] uuid The UUID of the service. + * @param [in] numHandles The maximum number of handles associated with the service. + */ +BLEService::BLEService(const char* uuid, uint16_t numHandles) : BLEService(BLEUUID(uuid), numHandles) { +} + + +/** + * @brief Construct an instance of the BLEService + * @param [in] uuid The UUID of the service. + * @param [in] numHandles The maximum number of handles associated with the service. + */ +BLEService::BLEService(BLEUUID uuid, uint16_t numHandles) { + m_uuid = uuid; + m_handle = NULL_HANDLE; + m_pServer = nullptr; + //m_serializeMutex.setName("BLEService"); + m_lastCreatedCharacteristic = nullptr; + m_numHandles = numHandles; +} // BLEService + + +/** + * @brief Create the service. + * Create the service. + * @param [in] gatts_if The handle of the GATT server interface. + * @return N/A. + */ + +void BLEService::executeCreate(BLEServer* pServer) { + log_v(">> executeCreate() - Creating service (esp_ble_gatts_create_service) service uuid: %s", getUUID().toString().c_str()); + m_pServer = pServer; + m_semaphoreCreateEvt.take("executeCreate"); // Take the mutex and release at event ESP_GATTS_CREATE_EVT + + esp_gatt_srvc_id_t srvc_id; + srvc_id.is_primary = true; + srvc_id.id.inst_id = m_instId; + srvc_id.id.uuid = *m_uuid.getNative(); + esp_err_t errRc = ::esp_ble_gatts_create_service(getServer()->getGattsIf(), &srvc_id, m_numHandles); // The maximum number of handles associated with the service. + + if (errRc != ESP_OK) { + log_e("esp_ble_gatts_create_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + + m_semaphoreCreateEvt.wait("executeCreate"); + log_v("<< executeCreate"); +} // executeCreate + + +/** + * @brief Delete the service. + * Delete the service. + * @return N/A. + */ + +void BLEService::executeDelete() { + log_v(">> executeDelete()"); + m_semaphoreDeleteEvt.take("executeDelete"); // Take the mutex and release at event ESP_GATTS_DELETE_EVT + + esp_err_t errRc = ::esp_ble_gatts_delete_service(getHandle()); + + if (errRc != ESP_OK) { + log_e("esp_ble_gatts_delete_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + + m_semaphoreDeleteEvt.wait("executeDelete"); + log_v("<< executeDelete"); +} // executeDelete + + +/** + * @brief Dump details of this BLE GATT service. + * @return N/A. + */ +void BLEService::dump() { + log_d("Service: uuid:%s, handle: 0x%.2x", + m_uuid.toString().c_str(), + m_handle); + log_d("Characteristics:\n%s", m_characteristicMap.toString().c_str()); +} // dump + + +/** + * @brief Get the UUID of the service. + * @return the UUID of the service. + */ +BLEUUID BLEService::getUUID() { + return m_uuid; +} // getUUID + + +/** + * @brief Start the service. + * Here we wish to start the service which means that we will respond to partner requests about it. + * Starting a service also means that we can create the corresponding characteristics. + * @return Start the service. + */ +void BLEService::start() { +// We ask the BLE runtime to start the service and then create each of the characteristics. +// We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event +// obtained as a result of calling esp_ble_gatts_create_service(). +// + log_v(">> start(): Starting service (esp_ble_gatts_start_service): %s", toString().c_str()); + if (m_handle == NULL_HANDLE) { + log_e("<< !!! We attempted to start a service but don't know its handle!"); + return; + } + + BLECharacteristic *pCharacteristic = m_characteristicMap.getFirst(); + + while (pCharacteristic != nullptr) { + m_lastCreatedCharacteristic = pCharacteristic; + pCharacteristic->executeCreate(this); + + pCharacteristic = m_characteristicMap.getNext(); + } + // Start each of the characteristics ... these are found in the m_characteristicMap. + + m_semaphoreStartEvt.take("start"); + esp_err_t errRc = ::esp_ble_gatts_start_service(m_handle); + + if (errRc != ESP_OK) { + log_e("<< esp_ble_gatts_start_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + m_semaphoreStartEvt.wait("start"); + + log_v("<< start()"); +} // start + + +/** + * @brief Stop the service. + */ +void BLEService::stop() { +// We ask the BLE runtime to start the service and then create each of the characteristics. +// We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event +// obtained as a result of calling esp_ble_gatts_create_service(). + log_v(">> stop(): Stopping service (esp_ble_gatts_stop_service): %s", toString().c_str()); + if (m_handle == NULL_HANDLE) { + log_e("<< !!! We attempted to stop a service but don't know its handle!"); + return; + } + + m_semaphoreStopEvt.take("stop"); + esp_err_t errRc = ::esp_ble_gatts_stop_service(m_handle); + + if (errRc != ESP_OK) { + log_e("<< esp_ble_gatts_stop_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + m_semaphoreStopEvt.wait("stop"); + + log_v("<< stop()"); +} // start + + +/** + * @brief Set the handle associated with this service. + * @param [in] handle The handle associated with the service. + */ +void BLEService::setHandle(uint16_t handle) { + log_v(">> setHandle - Handle=0x%.2x, service UUID=%s)", handle, getUUID().toString().c_str()); + if (m_handle != NULL_HANDLE) { + log_e("!!! Handle is already set %.2x", m_handle); + return; + } + m_handle = handle; + log_v("<< setHandle"); +} // setHandle + + +/** + * @brief Get the handle associated with this service. + * @return The handle associated with this service. + */ +uint16_t BLEService::getHandle() { + return m_handle; +} // getHandle + + +/** + * @brief Add a characteristic to the service. + * @param [in] pCharacteristic A pointer to the characteristic to be added. + */ +void BLEService::addCharacteristic(BLECharacteristic* pCharacteristic) { + // We maintain a mapping of characteristics owned by this service. These are managed by the + // BLECharacteristicMap class instance found in m_characteristicMap. We add the characteristic + // to the map and then ask the service to add the characteristic at the BLE level (ESP-IDF). + + log_v(">> addCharacteristic()"); + log_d("Adding characteristic: uuid=%s to service: %s", + pCharacteristic->getUUID().toString().c_str(), + toString().c_str()); + + // Check that we don't add the same characteristic twice. + if (m_characteristicMap.getByUUID(pCharacteristic->getUUID()) != nullptr) { + log_w("<< Adding a new characteristic with the same UUID as a previous one"); + //return; + } + + // Remember this characteristic in our map of characteristics. At this point, we can lookup by UUID + // but not by handle. The handle is allocated to us on the ESP_GATTS_ADD_CHAR_EVT. + m_characteristicMap.setByUUID(pCharacteristic, pCharacteristic->getUUID()); + + log_v("<< addCharacteristic()"); +} // addCharacteristic + + +/** + * @brief Create a new BLE Characteristic associated with this service. + * @param [in] uuid - The UUID of the characteristic. + * @param [in] properties - The properties of the characteristic. + * @return The new BLE characteristic. + */ +BLECharacteristic* BLEService::createCharacteristic(const char* uuid, uint32_t properties) { + return createCharacteristic(BLEUUID(uuid), properties); +} + + +/** + * @brief Create a new BLE Characteristic associated with this service. + * @param [in] uuid - The UUID of the characteristic. + * @param [in] properties - The properties of the characteristic. + * @return The new BLE characteristic. + */ +BLECharacteristic* BLEService::createCharacteristic(BLEUUID uuid, uint32_t properties) { + BLECharacteristic* pCharacteristic = new BLECharacteristic(uuid, properties); + addCharacteristic(pCharacteristic); + return pCharacteristic; +} // createCharacteristic + + +/** + * @brief Handle a GATTS server event. + */ +void BLEService::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { + switch (event) { + // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. + // add_char: + // - esp_gatt_status_t status + // - uint16_t attr_handle + // - uint16_t service_handle + // - esp_bt_uuid_t char_uuid + + // If we have reached the correct service, then locate the characteristic and remember the handle + // for that characteristic. + case ESP_GATTS_ADD_CHAR_EVT: { + if (m_handle == param->add_char.service_handle) { + BLECharacteristic *pCharacteristic = getLastCreatedCharacteristic(); + if (pCharacteristic == nullptr) { + log_e("Expected to find characteristic with UUID: %s, but didnt!", + BLEUUID(param->add_char.char_uuid).toString().c_str()); + dump(); + break; + } + pCharacteristic->setHandle(param->add_char.attr_handle); + m_characteristicMap.setByHandle(param->add_char.attr_handle, pCharacteristic); + break; + } // Reached the correct service. + break; + } // ESP_GATTS_ADD_CHAR_EVT + + + // ESP_GATTS_START_EVT + // + // start: + // esp_gatt_status_t status + // uint16_t service_handle + case ESP_GATTS_START_EVT: { + if (param->start.service_handle == getHandle()) { + m_semaphoreStartEvt.give(); + } + break; + } // ESP_GATTS_START_EVT + + // ESP_GATTS_STOP_EVT + // + // stop: + // esp_gatt_status_t status + // uint16_t service_handle + // + case ESP_GATTS_STOP_EVT: { + if (param->stop.service_handle == getHandle()) { + m_semaphoreStopEvt.give(); + } + break; + } // ESP_GATTS_STOP_EVT + + + // ESP_GATTS_CREATE_EVT + // Called when a new service is registered as having been created. + // + // create: + // * esp_gatt_status_t status + // * uint16_t service_handle + // * esp_gatt_srvc_id_t service_id + // * - esp_gatt_id id + // * - esp_bt_uuid uuid + // * - uint8_t inst_id + // * - bool is_primary + // + case ESP_GATTS_CREATE_EVT: { + if (getUUID().equals(BLEUUID(param->create.service_id.id.uuid)) && m_instId == param->create.service_id.id.inst_id) { + setHandle(param->create.service_handle); + m_semaphoreCreateEvt.give(); + } + break; + } // ESP_GATTS_CREATE_EVT + + + // ESP_GATTS_DELETE_EVT + // Called when a service is deleted. + // + // delete: + // * esp_gatt_status_t status + // * uint16_t service_handle + // + case ESP_GATTS_DELETE_EVT: { + if (param->del.service_handle == getHandle()) { + m_semaphoreDeleteEvt.give(); + } + break; + } // ESP_GATTS_DELETE_EVT + + default: + break; + } // Switch + + // Invoke the GATTS handler in each of the associated characteristics. + m_characteristicMap.handleGATTServerEvent(event, gatts_if, param); +} // handleGATTServerEvent + + +BLECharacteristic* BLEService::getCharacteristic(const char* uuid) { + return getCharacteristic(BLEUUID(uuid)); +} + + +BLECharacteristic* BLEService::getCharacteristic(BLEUUID uuid) { + return m_characteristicMap.getByUUID(uuid); +} + + +/** + * @brief Return a string representation of this service. + * A service is defined by: + * * Its UUID + * * Its handle + * @return A string representation of this service. + */ +std::string BLEService::toString() { + std::string res = "UUID: " + getUUID().toString(); + char hex[5]; + snprintf(hex, sizeof(hex), "%04x", getHandle()); + res += ", handle: 0x"; + res += hex; + return res; +} // toString + + +/** + * @brief Get the last created characteristic. + * It is lamentable that this function has to exist. It returns the last created characteristic. + * We need this because the descriptor API is built around the notion that a new descriptor, when created, + * is associated with the last characteristics created and we need that information. + * @return The last created characteristic. + */ +BLECharacteristic* BLEService::getLastCreatedCharacteristic() { + return m_lastCreatedCharacteristic; +} // getLastCreatedCharacteristic + + +/** + * @brief Get the BLE server associated with this service. + * @return The BLEServer associated with this service. + */ +BLEServer* BLEService::getServer() { + return m_pServer; +} // getServer + +#endif // CONFIG_BT_ENABLED diff --git a/libraries/BLE/src/BLEService.h b/libraries/BLE/src/BLEService.h new file mode 100644 index 00000000000..b42d57f2afb --- /dev/null +++ b/libraries/BLE/src/BLEService.h @@ -0,0 +1,97 @@ +/* + * BLEService.h + * + * Created on: Mar 25, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLESERVICE_H_ +#define COMPONENTS_CPP_UTILS_BLESERVICE_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) + +#include + +#include "BLECharacteristic.h" +#include "BLEServer.h" +#include "BLEUUID.h" +#include "FreeRTOS.h" + +class BLEServer; + +/** + * @brief A data mapping used to manage the set of %BLE characteristics known to the server. + */ +class BLECharacteristicMap { +public: + void setByUUID(BLECharacteristic* pCharacteristic, const char* uuid); + void setByUUID(BLECharacteristic* pCharacteristic, BLEUUID uuid); + void setByHandle(uint16_t handle, BLECharacteristic* pCharacteristic); + BLECharacteristic* getByUUID(const char* uuid); + BLECharacteristic* getByUUID(BLEUUID uuid); + BLECharacteristic* getByHandle(uint16_t handle); + BLECharacteristic* getFirst(); + BLECharacteristic* getNext(); + std::string toString(); + void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param); + +private: + std::map m_uuidMap; + std::map m_handleMap; + std::map::iterator m_iterator; +}; + + +/** + * @brief The model of a %BLE service. + * + */ +class BLEService { +public: + void addCharacteristic(BLECharacteristic* pCharacteristic); + BLECharacteristic* createCharacteristic(const char* uuid, uint32_t properties); + BLECharacteristic* createCharacteristic(BLEUUID uuid, uint32_t properties); + void dump(); + void executeCreate(BLEServer* pServer); + void executeDelete(); + BLECharacteristic* getCharacteristic(const char* uuid); + BLECharacteristic* getCharacteristic(BLEUUID uuid); + BLEUUID getUUID(); + BLEServer* getServer(); + void start(); + void stop(); + std::string toString(); + uint16_t getHandle(); + uint8_t m_instId = 0; + +private: + BLEService(const char* uuid, uint16_t numHandles); + BLEService(BLEUUID uuid, uint16_t numHandles); + friend class BLEServer; + friend class BLEServiceMap; + friend class BLEDescriptor; + friend class BLECharacteristic; + friend class BLEDevice; + + BLECharacteristicMap m_characteristicMap; + uint16_t m_handle; + BLECharacteristic* m_lastCreatedCharacteristic = nullptr; + BLEServer* m_pServer = nullptr; + BLEUUID m_uuid; + + FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); + FreeRTOS::Semaphore m_semaphoreDeleteEvt = FreeRTOS::Semaphore("DeleteEvt"); + FreeRTOS::Semaphore m_semaphoreStartEvt = FreeRTOS::Semaphore("StartEvt"); + FreeRTOS::Semaphore m_semaphoreStopEvt = FreeRTOS::Semaphore("StopEvt"); + + uint16_t m_numHandles; + + BLECharacteristic* getLastCreatedCharacteristic(); + void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param); + void setHandle(uint16_t handle); + //void setService(esp_gatt_srvc_id_t srvc_id); +}; // BLEService + + +#endif // CONFIG_BT_ENABLED +#endif /* COMPONENTS_CPP_UTILS_BLESERVICE_H_ */ diff --git a/libraries/BLE/src/BLEServiceMap.cpp b/libraries/BLE/src/BLEServiceMap.cpp new file mode 100644 index 00000000000..a8a1f8e567c --- /dev/null +++ b/libraries/BLE/src/BLEServiceMap.cpp @@ -0,0 +1,137 @@ +/* + * BLEServiceMap.cpp + * + * Created on: Jun 22, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include "BLEService.h" + + +/** + * @brief Return the service by UUID. + * @param [in] UUID The UUID to look up the service. + * @return The characteristic. + */ +BLEService* BLEServiceMap::getByUUID(const char* uuid) { + return getByUUID(BLEUUID(uuid)); +} + +/** + * @brief Return the service by UUID. + * @param [in] UUID The UUID to look up the service. + * @return The characteristic. + */ +BLEService* BLEServiceMap::getByUUID(BLEUUID uuid, uint8_t inst_id) { + for (auto &myPair : m_uuidMap) { + if (myPair.first->getUUID().equals(uuid)) { + return myPair.first; + } + } + //return m_uuidMap.at(uuid.toString()); + return nullptr; +} // getByUUID + + +/** + * @brief Return the service by handle. + * @param [in] handle The handle to look up the service. + * @return The service. + */ +BLEService* BLEServiceMap::getByHandle(uint16_t handle) { + return m_handleMap.at(handle); +} // getByHandle + + +/** + * @brief Set the service by UUID. + * @param [in] uuid The uuid of the service. + * @param [in] characteristic The service to cache. + * @return N/A. + */ +void BLEServiceMap::setByUUID(BLEUUID uuid, BLEService* service) { + m_uuidMap.insert(std::pair(service, uuid.toString())); +} // setByUUID + + +/** + * @brief Set the service by handle. + * @param [in] handle The handle of the service. + * @param [in] service The service to cache. + * @return N/A. + */ +void BLEServiceMap::setByHandle(uint16_t handle, BLEService* service) { + m_handleMap.insert(std::pair(handle, service)); +} // setByHandle + + +/** + * @brief Return a string representation of the service map. + * @return A string representation of the service map. + */ +std::string BLEServiceMap::toString() { + std::string res; + char hex[5]; + for (auto &myPair: m_handleMap) { + res += "handle: 0x"; + snprintf(hex, sizeof(hex), "%04x", myPair.first); + res += hex; + res += ", uuid: " + myPair.second->getUUID().toString() + "\n"; + } + return res; +} // toString + +void BLEServiceMap::handleGATTServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* param) { + // Invoke the handler for every Service we have. + for (auto &myPair : m_uuidMap) { + myPair.first->handleGATTServerEvent(event, gatts_if, param); + } +} + +/** + * @brief Get the first service in the map. + * @return The first service in the map. + */ +BLEService* BLEServiceMap::getFirst() { + m_iterator = m_uuidMap.begin(); + if (m_iterator == m_uuidMap.end()) return nullptr; + BLEService* pRet = m_iterator->first; + m_iterator++; + return pRet; +} // getFirst + +/** + * @brief Get the next service in the map. + * @return The next service in the map. + */ +BLEService* BLEServiceMap::getNext() { + if (m_iterator == m_uuidMap.end()) return nullptr; + BLEService* pRet = m_iterator->first; + m_iterator++; + return pRet; +} // getNext + +/** + * @brief Removes service from maps. + * @return N/A. + */ +void BLEServiceMap::removeService(BLEService* service) { + m_handleMap.erase(service->getHandle()); + m_uuidMap.erase(service); +} // removeService + +/** + * @brief Returns the amount of registered services + * @return amount of registered services + */ +int BLEServiceMap::getRegisteredServiceCount(){ + return m_handleMap.size(); +} + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEUUID.cpp b/libraries/BLE/src/BLEUUID.cpp new file mode 100644 index 00000000000..1a9473678b2 --- /dev/null +++ b/libraries/BLE/src/BLEUUID.cpp @@ -0,0 +1,386 @@ +/* + * BLEUUID.cpp + * + * Created on: Jun 21, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include +#include +#include +#include +#include "BLEUUID.h" +#include "esp32-hal-log.h" + +/** + * @brief Copy memory from source to target but in reverse order. + * + * When we move memory from one location it is normally: + * + * ``` + * [0][1][2]...[n] -> [0][1][2]...[n] + * ``` + * + * with this function, it is: + * + * ``` + * [0][1][2]...[n] -> [n][n-1][n-2]...[0] + * ``` + * + * @param [in] target The target of the copy + * @param [in] source The source of the copy + * @param [in] size The number of bytes to copy + */ +static void memrcpy(uint8_t* target, uint8_t* source, uint32_t size) { + assert(size > 0); + target += (size - 1); // Point target to the last byte of the target data + while (size > 0) { + *target = *source; + target--; + source++; + size--; + } +} // memrcpy + + +/** + * @brief Create a UUID from a string. + * + * Create a UUID from a string. There will be two possible stories here. Either the string represents + * a binary data field or the string represents a hex encoding of a UUID. + * For the hex encoding, here is an example: + * + * ``` + * "beb5483e-36e1-4688-b7f5-ea07361b26a8" + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 + * 12345678-90ab-cdef-1234-567890abcdef + * ``` + * + * This has a length of 36 characters. We need to parse this into 16 bytes. + * + * @param [in] value The string to build a UUID from. + */ +BLEUUID::BLEUUID(std::string value) { + m_valueSet = true; + if (value.length() == 4) { + m_uuid.len = ESP_UUID_LEN_16; + m_uuid.uuid.uuid16 = 0; + for(int i=0;i '9') MSB -= 7; + if(LSB > '9') LSB -= 7; + m_uuid.uuid.uuid16 += (((MSB&0x0F) <<4) | (LSB & 0x0F))<<(2-i)*4; + i+=2; + } + } + else if (value.length() == 8) { + m_uuid.len = ESP_UUID_LEN_32; + m_uuid.uuid.uuid32 = 0; + for(int i=0;i '9') MSB -= 7; + if(LSB > '9') LSB -= 7; + m_uuid.uuid.uuid32 += (((MSB&0x0F) <<4) | (LSB & 0x0F))<<(6-i)*4; + i+=2; + } + } + else if (value.length() == 16) { // how we can have 16 byte length string reprezenting 128 bit uuid??? needs to be investigated (lack of time) + m_uuid.len = ESP_UUID_LEN_128; + memrcpy(m_uuid.uuid.uuid128, (uint8_t*)value.data(), 16); + } + else if (value.length() == 36) { + // If the length of the string is 36 bytes then we will assume it is a long hex string in + // UUID format. + m_uuid.len = ESP_UUID_LEN_128; + int n = 0; + for(int i=0;i '9') MSB -= 7; + if(LSB > '9') LSB -= 7; + m_uuid.uuid.uuid128[15-n++] = ((MSB&0x0F) <<4) | (LSB & 0x0F); + i+=2; + } + } + else { + log_e("ERROR: UUID value not 2, 4, 16 or 36 bytes"); + m_valueSet = false; + } +} //BLEUUID(std::string) + + +/** + * @brief Create a UUID from 16 bytes of memory. + * + * @param [in] pData The pointer to the start of the UUID. + * @param [in] size The size of the data. + * @param [in] msbFirst Is the MSB first in pData memory? + */ +BLEUUID::BLEUUID(uint8_t* pData, size_t size, bool msbFirst) { + if (size != 16) { + log_e("ERROR: UUID length not 16 bytes"); + return; + } + m_uuid.len = ESP_UUID_LEN_128; + if (msbFirst) { + memrcpy(m_uuid.uuid.uuid128, pData, 16); + } else { + memcpy(m_uuid.uuid.uuid128, pData, 16); + } + m_valueSet = true; +} // BLEUUID + + +/** + * @brief Create a UUID from the 16bit value. + * + * @param [in] uuid The 16bit short form UUID. + */ +BLEUUID::BLEUUID(uint16_t uuid) { + m_uuid.len = ESP_UUID_LEN_16; + m_uuid.uuid.uuid16 = uuid; + m_valueSet = true; +} // BLEUUID + + +/** + * @brief Create a UUID from the 32bit value. + * + * @param [in] uuid The 32bit short form UUID. + */ +BLEUUID::BLEUUID(uint32_t uuid) { + m_uuid.len = ESP_UUID_LEN_32; + m_uuid.uuid.uuid32 = uuid; + m_valueSet = true; +} // BLEUUID + + +/** + * @brief Create a UUID from the native UUID. + * + * @param [in] uuid The native UUID. + */ +BLEUUID::BLEUUID(esp_bt_uuid_t uuid) { + m_uuid = uuid; + m_valueSet = true; +} // BLEUUID + + +/** + * @brief Create a UUID from the ESP32 esp_gat_id_t. + * + * @param [in] gattId The data to create the UUID from. + */ +BLEUUID::BLEUUID(esp_gatt_id_t gattId) : BLEUUID(gattId.uuid) { +} // BLEUUID + + +BLEUUID::BLEUUID() { + m_valueSet = false; +} // BLEUUID + + +/** + * @brief Get the number of bits in this uuid. + * @return The number of bits in the UUID. One of 16, 32 or 128. + */ +uint8_t BLEUUID::bitSize() { + if (!m_valueSet) return 0; + switch (m_uuid.len) { + case ESP_UUID_LEN_16: + return 16; + case ESP_UUID_LEN_32: + return 32; + case ESP_UUID_LEN_128: + return 128; + default: + log_e("Unknown UUID length: %d", m_uuid.len); + return 0; + } // End of switch +} // bitSize + + +/** + * @brief Compare a UUID against this UUID. + * + * @param [in] uuid The UUID to compare against. + * @return True if the UUIDs are equal and false otherwise. + */ +bool BLEUUID::equals(BLEUUID uuid) { + //log_d("Comparing: %s to %s", toString().c_str(), uuid.toString().c_str()); + if (!m_valueSet || !uuid.m_valueSet) return false; + + if (uuid.m_uuid.len != m_uuid.len) { + return uuid.toString() == toString(); + } + + if (uuid.m_uuid.len == ESP_UUID_LEN_16) { + return uuid.m_uuid.uuid.uuid16 == m_uuid.uuid.uuid16; + } + + if (uuid.m_uuid.len == ESP_UUID_LEN_32) { + return uuid.m_uuid.uuid.uuid32 == m_uuid.uuid.uuid32; + } + + return memcmp(uuid.m_uuid.uuid.uuid128, m_uuid.uuid.uuid128, 16) == 0; +} // equals + + +/** + * Create a BLEUUID from a string of the form: + * 0xNNNN + * 0xNNNNNNNN + * 0x + * NNNN + * NNNNNNNN + * + */ +BLEUUID BLEUUID::fromString(std::string _uuid) { + uint8_t start = 0; + if (strstr(_uuid.c_str(), "0x") != nullptr) { // If the string starts with 0x, skip those characters. + start = 2; + } + uint8_t len = _uuid.length() - start; // Calculate the length of the string we are going to use. + + if(len == 4) { + uint16_t x = strtoul(_uuid.substr(start, len).c_str(), NULL, 16); + return BLEUUID(x); + } else if (len == 8) { + uint32_t x = strtoul(_uuid.substr(start, len).c_str(), NULL, 16); + return BLEUUID(x); + } else if (len == 36) { + return BLEUUID(_uuid); + } + return BLEUUID(); +} // fromString + + +/** + * @brief Get the native UUID value. + * + * @return The native UUID value or NULL if not set. + */ +esp_bt_uuid_t* BLEUUID::getNative() { + //log_d(">> getNative()") + if (m_valueSet == false) { + log_v("<< Return of un-initialized UUID!"); + return nullptr; + } + //log_d("<< getNative()"); + return &m_uuid; +} // getNative + + +/** + * @brief Convert a UUID to its 128 bit representation. + * + * A UUID can be internally represented as 16bit, 32bit or the full 128bit. This method + * will convert 16 or 32 bit representations to the full 128bit. + */ +BLEUUID BLEUUID::to128() { + //log_v(">> toFull() - %s", toString().c_str()); + + // If we either don't have a value or are already a 128 bit UUID, nothing further to do. + if (!m_valueSet || m_uuid.len == ESP_UUID_LEN_128) { + return *this; + } + + // If we are 16 bit or 32 bit, then set the 4 bytes of the variable part of the UUID. + if (m_uuid.len == ESP_UUID_LEN_16) { + uint16_t temp = m_uuid.uuid.uuid16; + m_uuid.uuid.uuid128[15] = 0; + m_uuid.uuid.uuid128[14] = 0; + m_uuid.uuid.uuid128[13] = (temp >> 8) & 0xff; + m_uuid.uuid.uuid128[12] = temp & 0xff; + + } + else if (m_uuid.len == ESP_UUID_LEN_32) { + uint32_t temp = m_uuid.uuid.uuid32; + m_uuid.uuid.uuid128[15] = (temp >> 24) & 0xff; + m_uuid.uuid.uuid128[14] = (temp >> 16) & 0xff; + m_uuid.uuid.uuid128[13] = (temp >> 8) & 0xff; + m_uuid.uuid.uuid128[12] = temp & 0xff; + } + + // Set the fixed parts of the UUID. + m_uuid.uuid.uuid128[11] = 0x00; + m_uuid.uuid.uuid128[10] = 0x00; + + m_uuid.uuid.uuid128[9] = 0x10; + m_uuid.uuid.uuid128[8] = 0x00; + + m_uuid.uuid.uuid128[7] = 0x80; + m_uuid.uuid.uuid128[6] = 0x00; + + m_uuid.uuid.uuid128[5] = 0x00; + m_uuid.uuid.uuid128[4] = 0x80; + m_uuid.uuid.uuid128[3] = 0x5f; + m_uuid.uuid.uuid128[2] = 0x9b; + m_uuid.uuid.uuid128[1] = 0x34; + m_uuid.uuid.uuid128[0] = 0xfb; + + m_uuid.len = ESP_UUID_LEN_128; + //log_d("<< toFull <- %s", toString().c_str()); + return *this; +} // to128 + + + + +/** + * @brief Get a string representation of the UUID. + * + * The format of a string is: + * 01234567 8901 2345 6789 012345678901 + * 0000180d-0000-1000-8000-00805f9b34fb + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 + * + * @return A string representation of the UUID. + */ +std::string BLEUUID::toString() { + if (!m_valueSet) return ""; // If we have no value, nothing to format. + // If the UUIDs are 16 or 32 bit, pad correctly. + + if (m_uuid.len == ESP_UUID_LEN_16) { // If the UUID is 16bit, pad correctly. + char hex[9]; + snprintf(hex, sizeof(hex), "%08x", m_uuid.uuid.uuid16); + return std::string(hex) + "-0000-1000-8000-00805f9b34fb"; + } // End 16bit UUID + + if (m_uuid.len == ESP_UUID_LEN_32) { // If the UUID is 32bit, pad correctly. + char hex[9]; + snprintf(hex, sizeof(hex), "%08x", m_uuid.uuid.uuid32); + return std::string(hex) + "-0000-1000-8000-00805f9b34fb"; + } // End 32bit UUID + + // The UUID is not 16bit or 32bit which means that it is 128bit. + // + // UUID string format: + // AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP + auto size = 37; // 32 for UUID data, 4 for '-' delimiters and one for a terminator == 37 chars + char *hex = (char *)malloc(size); + snprintf(hex, size, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", + m_uuid.uuid.uuid128[15], m_uuid.uuid.uuid128[14], + m_uuid.uuid.uuid128[13], m_uuid.uuid.uuid128[12], + m_uuid.uuid.uuid128[11], m_uuid.uuid.uuid128[10], + m_uuid.uuid.uuid128[9], m_uuid.uuid.uuid128[8], + m_uuid.uuid.uuid128[7], m_uuid.uuid.uuid128[6], + m_uuid.uuid.uuid128[5], m_uuid.uuid.uuid128[4], + m_uuid.uuid.uuid128[3], m_uuid.uuid.uuid128[2], + m_uuid.uuid.uuid128[1], m_uuid.uuid.uuid128[0]); + std::string res(hex); + free(hex); + return res; +} // toString + +#endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEUUID.h b/libraries/BLE/src/BLEUUID.h new file mode 100644 index 00000000000..700739bec81 --- /dev/null +++ b/libraries/BLE/src/BLEUUID.h @@ -0,0 +1,39 @@ +/* + * BLEUUID.h + * + * Created on: Jun 21, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEUUID_H_ +#define COMPONENTS_CPP_UTILS_BLEUUID_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include + +/** + * @brief A model of a %BLE UUID. + */ +class BLEUUID { +public: + BLEUUID(std::string uuid); + BLEUUID(uint16_t uuid); + BLEUUID(uint32_t uuid); + BLEUUID(esp_bt_uuid_t uuid); + BLEUUID(uint8_t* pData, size_t size, bool msbFirst); + BLEUUID(esp_gatt_id_t gattId); + BLEUUID(); + uint8_t bitSize(); // Get the number of bits in this uuid. + bool equals(BLEUUID uuid); + esp_bt_uuid_t* getNative(); + BLEUUID to128(); + std::string toString(); + static BLEUUID fromString(std::string uuid); // Create a BLEUUID from a string + +private: + esp_bt_uuid_t m_uuid; // The underlying UUID structure that this class wraps. + bool m_valueSet = false; // Is there a value set for this instance. +}; // BLEUUID +#endif /* CONFIG_BT_ENABLED */ +#endif /* COMPONENTS_CPP_UTILS_BLEUUID_H_ */ diff --git a/libraries/BLE/src/BLEUtils.cpp b/libraries/BLE/src/BLEUtils.cpp new file mode 100644 index 00000000000..b9cf591f426 --- /dev/null +++ b/libraries/BLE/src/BLEUtils.cpp @@ -0,0 +1,2040 @@ +/* + * BLEUtils.cpp + * + * Created on: Mar 25, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include "BLEAddress.h" +#include "BLEClient.h" +#include "BLEUtils.h" +#include "BLEUUID.h" +#include "GeneralUtils.h" + +#include +#include +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 ESP-IDF +#include // Part of C++ STL +#include +#include + +#include "esp32-hal-log.h" + +/* +static std::map g_addressMap; +static std::map g_connIdMap; +*/ + +typedef struct { + uint32_t assignedNumber; + const char* name; +} member_t; + +static const member_t members_ids[] = { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + {0xFE08, "Microsoft"}, + {0xFE09, "Pillsy, Inc."}, + {0xFE0A, "ruwido austria gmbh"}, + {0xFE0B, "ruwido austria gmbh"}, + {0xFE0C, "Procter & Gamble"}, + {0xFE0D, "Procter & Gamble"}, + {0xFE0E, "Setec Pty Ltd"}, + {0xFE0F, "Philips Lighting B.V."}, + {0xFE10, "Lapis Semiconductor Co., Ltd."}, + {0xFE11, "GMC-I Messtechnik GmbH"}, + {0xFE12, "M-Way Solutions GmbH"}, + {0xFE13, "Apple Inc."}, + {0xFE14, "Flextronics International USA Inc."}, + {0xFE15, "Amazon Fulfillment Services, Inc."}, + {0xFE16, "Footmarks, Inc."}, + {0xFE17, "Telit Wireless Solutions GmbH"}, + {0xFE18, "Runtime, Inc."}, + {0xFE19, "Google Inc."}, + {0xFE1A, "Tyto Life LLC"}, + {0xFE1B, "Tyto Life LLC"}, + {0xFE1C, "NetMedia, Inc."}, + {0xFE1D, "Illuminati Instrument Corporation"}, + {0xFE1E, "Smart Innovations Co., Ltd"}, + {0xFE1F, "Garmin International, Inc."}, + {0xFE20, "Emerson"}, + {0xFE21, "Bose Corporation"}, + {0xFE22, "Zoll Medical Corporation"}, + {0xFE23, "Zoll Medical Corporation"}, + {0xFE24, "August Home Inc"}, + {0xFE25, "Apple, Inc. "}, + {0xFE26, "Google Inc."}, + {0xFE27, "Google Inc."}, + {0xFE28, "Ayla Networks"}, + {0xFE29, "Gibson Innovations"}, + {0xFE2A, "DaisyWorks, Inc."}, + {0xFE2B, "ITT Industries"}, + {0xFE2C, "Google Inc."}, + {0xFE2D, "SMART INNOVATION Co.,Ltd"}, + {0xFE2E, "ERi,Inc."}, + {0xFE2F, "CRESCO Wireless, Inc"}, + {0xFE30, "Volkswagen AG"}, + {0xFE31, "Volkswagen AG"}, + {0xFE32, "Pro-Mark, Inc."}, + {0xFE33, "CHIPOLO d.o.o."}, + {0xFE34, "SmallLoop LLC"}, + {0xFE35, "HUAWEI Technologies Co., Ltd"}, + {0xFE36, "HUAWEI Technologies Co., Ltd"}, + {0xFE37, "Spaceek LTD"}, + {0xFE38, "Spaceek LTD"}, + {0xFE39, "TTS Tooltechnic Systems AG & Co. KG"}, + {0xFE3A, "TTS Tooltechnic Systems AG & Co. KG"}, + {0xFE3B, "Dolby Laboratories"}, + {0xFE3C, "Alibaba"}, + {0xFE3D, "BD Medical"}, + {0xFE3E, "BD Medical"}, + {0xFE3F, "Friday Labs Limited"}, + {0xFE40, "Inugo Systems Limited"}, + {0xFE41, "Inugo Systems Limited"}, + {0xFE42, "Nets A/S "}, + {0xFE43, "Andreas Stihl AG & Co. KG"}, + {0xFE44, "SK Telecom "}, + {0xFE45, "Snapchat Inc"}, + {0xFE46, "B&O Play A/S "}, + {0xFE47, "General Motors"}, + {0xFE48, "General Motors"}, + {0xFE49, "SenionLab AB"}, + {0xFE4A, "OMRON HEALTHCARE Co., Ltd."}, + {0xFE4B, "Philips Lighting B.V."}, + {0xFE4C, "Volkswagen AG"}, + {0xFE4D, "Casambi Technologies Oy"}, + {0xFE4E, "NTT docomo"}, + {0xFE4F, "Molekule, Inc."}, + {0xFE50, "Google Inc."}, + {0xFE51, "SRAM"}, + {0xFE52, "SetPoint Medical"}, + {0xFE53, "3M"}, + {0xFE54, "Motiv, Inc."}, + {0xFE55, "Google Inc."}, + {0xFE56, "Google Inc."}, + {0xFE57, "Dotted Labs"}, + {0xFE58, "Nordic Semiconductor ASA"}, + {0xFE59, "Nordic Semiconductor ASA"}, + {0xFE5A, "Chronologics Corporation"}, + {0xFE5B, "GT-tronics HK Ltd"}, + {0xFE5C, "million hunters GmbH"}, + {0xFE5D, "Grundfos A/S"}, + {0xFE5E, "Plastc Corporation"}, + {0xFE5F, "Eyefi, Inc."}, + {0xFE60, "Lierda Science & Technology Group Co., Ltd."}, + {0xFE61, "Logitech International SA"}, + {0xFE62, "Indagem Tech LLC"}, + {0xFE63, "Connected Yard, Inc."}, + {0xFE64, "Siemens AG"}, + {0xFE65, "CHIPOLO d.o.o."}, + {0xFE66, "Intel Corporation"}, + {0xFE67, "Lab Sensor Solutions"}, + {0xFE68, "Qualcomm Life Inc"}, + {0xFE69, "Qualcomm Life Inc"}, + {0xFE6A, "Kontakt Micro-Location Sp. z o.o."}, + {0xFE6B, "TASER International, Inc."}, + {0xFE6C, "TASER International, Inc."}, + {0xFE6D, "The University of Tokyo"}, + {0xFE6E, "The University of Tokyo"}, + {0xFE6F, "LINE Corporation"}, + {0xFE70, "Beijing Jingdong Century Trading Co., Ltd."}, + {0xFE71, "Plume Design Inc"}, + {0xFE72, "St. Jude Medical, Inc."}, + {0xFE73, "St. Jude Medical, Inc."}, + {0xFE74, "unwire"}, + {0xFE75, "TangoMe"}, + {0xFE76, "TangoMe"}, + {0xFE77, "Hewlett-Packard Company"}, + {0xFE78, "Hewlett-Packard Company"}, + {0xFE79, "Zebra Technologies"}, + {0xFE7A, "Bragi GmbH"}, + {0xFE7B, "Orion Labs, Inc."}, + {0xFE7C, "Telit Wireless Solutions (Formerly Stollmann E+V GmbH)"}, + {0xFE7D, "Aterica Health Inc."}, + {0xFE7E, "Awear Solutions Ltd"}, + {0xFE7F, "Doppler Lab"}, + {0xFE80, "Doppler Lab"}, + {0xFE81, "Medtronic Inc."}, + {0xFE82, "Medtronic Inc."}, + {0xFE83, "Blue Bite"}, + {0xFE84, "RF Digital Corp"}, + {0xFE85, "RF Digital Corp"}, + {0xFE86, "HUAWEI Technologies Co., Ltd. ( )"}, + {0xFE87, "Qingdao Yeelink Information Technology Co., Ltd. ( )"}, + {0xFE88, "SALTO SYSTEMS S.L."}, + {0xFE89, "B&O Play A/S"}, + {0xFE8A, "Apple, Inc."}, + {0xFE8B, "Apple, Inc."}, + {0xFE8C, "TRON Forum"}, + {0xFE8D, "Interaxon Inc."}, + {0xFE8E, "ARM Ltd"}, + {0xFE8F, "CSR"}, + {0xFE90, "JUMA"}, + {0xFE91, "Shanghai Imilab Technology Co.,Ltd"}, + {0xFE92, "Jarden Safety & Security"}, + {0xFE93, "OttoQ Inc."}, + {0xFE94, "OttoQ Inc."}, + {0xFE95, "Xiaomi Inc."}, + {0xFE96, "Tesla Motor Inc."}, + {0xFE97, "Tesla Motor Inc."}, + {0xFE98, "Currant, Inc."}, + {0xFE99, "Currant, Inc."}, + {0xFE9A, "Estimote"}, + {0xFE9B, "Samsara Networks, Inc"}, + {0xFE9C, "GSI Laboratories, Inc."}, + {0xFE9D, "Mobiquity Networks Inc"}, + {0xFE9E, "Dialog Semiconductor B.V."}, + {0xFE9F, "Google Inc."}, + {0xFEA0, "Google Inc."}, + {0xFEA1, "Intrepid Control Systems, Inc."}, + {0xFEA2, "Intrepid Control Systems, Inc."}, + {0xFEA3, "ITT Industries"}, + {0xFEA4, "Paxton Access Ltd"}, + {0xFEA5, "GoPro, Inc."}, + {0xFEA6, "GoPro, Inc."}, + {0xFEA7, "UTC Fire and Security"}, + {0xFEA8, "Savant Systems LLC"}, + {0xFEA9, "Savant Systems LLC"}, + {0xFEAA, "Google Inc."}, + {0xFEAB, "Nokia Corporation"}, + {0xFEAC, "Nokia Corporation"}, + {0xFEAD, "Nokia Corporation"}, + {0xFEAE, "Nokia Corporation"}, + {0xFEAF, "Nest Labs Inc."}, + {0xFEB0, "Nest Labs Inc."}, + {0xFEB1, "Electronics Tomorrow Limited"}, + {0xFEB2, "Microsoft Corporation"}, + {0xFEB3, "Taobao"}, + {0xFEB4, "WiSilica Inc."}, + {0xFEB5, "WiSilica Inc."}, + {0xFEB6, "Vencer Co, Ltd"}, + {0xFEB7, "Facebook, Inc."}, + {0xFEB8, "Facebook, Inc."}, + {0xFEB9, "LG Electronics"}, + {0xFEBA, "Tencent Holdings Limited"}, + {0xFEBB, "adafruit industries"}, + {0xFEBC, "Dexcom, Inc. "}, + {0xFEBD, "Clover Network, Inc."}, + {0xFEBE, "Bose Corporation"}, + {0xFEBF, "Nod, Inc."}, + {0xFEC0, "KDDI Corporation"}, + {0xFEC1, "KDDI Corporation"}, + {0xFEC2, "Blue Spark Technologies, Inc."}, + {0xFEC3, "360fly, Inc."}, + {0xFEC4, "PLUS Location Systems"}, + {0xFEC5, "Realtek Semiconductor Corp."}, + {0xFEC6, "Kocomojo, LLC"}, + {0xFEC7, "Apple, Inc."}, + {0xFEC8, "Apple, Inc."}, + {0xFEC9, "Apple, Inc."}, + {0xFECA, "Apple, Inc."}, + {0xFECB, "Apple, Inc."}, + {0xFECC, "Apple, Inc."}, + {0xFECD, "Apple, Inc."}, + {0xFECE, "Apple, Inc."}, + {0xFECF, "Apple, Inc."}, + {0xFED0, "Apple, Inc."}, + {0xFED1, "Apple, Inc."}, + {0xFED2, "Apple, Inc."}, + {0xFED3, "Apple, Inc."}, + {0xFED4, "Apple, Inc."}, + {0xFED5, "Plantronics Inc."}, + {0xFED6, "Broadcom Corporation"}, + {0xFED7, "Broadcom Corporation"}, + {0xFED8, "Google Inc."}, + {0xFED9, "Pebble Technology Corporation"}, + {0xFEDA, "ISSC Technologies Corporation"}, + {0xFEDB, "Perka, Inc."}, + {0xFEDC, "Jawbone"}, + {0xFEDD, "Jawbone"}, + {0xFEDE, "Coin, Inc."}, + {0xFEDF, "Design SHIFT"}, + {0xFEE0, "Anhui Huami Information Technology Co."}, + {0xFEE1, "Anhui Huami Information Technology Co."}, + {0xFEE2, "Anki, Inc."}, + {0xFEE3, "Anki, Inc."}, + {0xFEE4, "Nordic Semiconductor ASA"}, + {0xFEE5, "Nordic Semiconductor ASA"}, + {0xFEE6, "Silvair, Inc."}, + {0xFEE7, "Tencent Holdings Limited"}, + {0xFEE8, "Quintic Corp."}, + {0xFEE9, "Quintic Corp."}, + {0xFEEA, "Swirl Networks, Inc."}, + {0xFEEB, "Swirl Networks, Inc."}, + {0xFEEC, "Tile, Inc."}, + {0xFEED, "Tile, Inc."}, + {0xFEEE, "Polar Electro Oy"}, + {0xFEEF, "Polar Electro Oy"}, + {0xFEF0, "Intel"}, + {0xFEF1, "CSR"}, + {0xFEF2, "CSR"}, + {0xFEF3, "Google Inc."}, + {0xFEF4, "Google Inc."}, + {0xFEF5, "Dialog Semiconductor GmbH"}, + {0xFEF6, "Wicentric, Inc."}, + {0xFEF7, "Aplix Corporation"}, + {0xFEF8, "Aplix Corporation"}, + {0xFEF9, "PayPal, Inc."}, + {0xFEFA, "PayPal, Inc."}, + {0xFEFB, "Telit Wireless Solutions (Formerly Stollmann E+V GmbH)"}, + {0xFEFC, "Gimbal, Inc."}, + {0xFEFD, "Gimbal, Inc."}, + {0xFEFE, "GN ReSound A/S"}, + {0xFEFF, "GN Netcom"}, + {0xFFFF, "Reserved"}, /*for testing purposes only*/ +#endif + {0, "" } +}; + +typedef struct { + uint32_t assignedNumber; + const char* name; +} gattdescriptor_t; + +static const gattdescriptor_t g_descriptor_ids[] = { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + {0x2905,"Characteristic Aggregate Format"}, + {0x2900,"Characteristic Extended Properties"}, + {0x2904,"Characteristic Presentation Format"}, + {0x2901,"Characteristic User Description"}, + {0x2902,"Client Characteristic Configuration"}, + {0x290B,"Environmental Sensing Configuration"}, + {0x290C,"Environmental Sensing Measurement"}, + {0x290D,"Environmental Sensing Trigger Setting"}, + {0x2907,"External Report Reference"}, + {0x2909,"Number of Digitals"}, + {0x2908,"Report Reference"}, + {0x2903,"Server Characteristic Configuration"}, + {0x290E,"Time Trigger Setting"}, + {0x2906,"Valid Range"}, + {0x290A,"Value Trigger Setting"}, +#endif + { 0, "" } +}; + +typedef struct { + uint32_t assignedNumber; + const char* name; +} characteristicMap_t; + +static const characteristicMap_t g_characteristicsMappings[] = { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + {0x2A7E,"Aerobic Heart Rate Lower Limit"}, + {0x2A84,"Aerobic Heart Rate Upper Limit"}, + {0x2A7F,"Aerobic Threshold"}, + {0x2A80,"Age"}, + {0x2A5A,"Aggregate"}, + {0x2A43,"Alert Category ID"}, + {0x2A42,"Alert Category ID Bit Mask"}, + {0x2A06,"Alert Level"}, + {0x2A44,"Alert Notification Control Point"}, + {0x2A3F,"Alert Status"}, + {0x2AB3,"Altitude"}, + {0x2A81,"Anaerobic Heart Rate Lower Limit"}, + {0x2A82,"Anaerobic Heart Rate Upper Limit"}, + {0x2A83,"Anaerobic Threshold"}, + {0x2A58,"Analog"}, + {0x2A59,"Analog Output"}, + {0x2A73,"Apparent Wind Direction"}, + {0x2A72,"Apparent Wind Speed"}, + {0x2A01,"Appearance"}, + {0x2AA3,"Barometric Pressure Trend"}, + {0x2A19,"Battery Level"}, + {0x2A1B,"Battery Level State"}, + {0x2A1A,"Battery Power State"}, + {0x2A49,"Blood Pressure Feature"}, + {0x2A35,"Blood Pressure Measurement"}, + {0x2A9B,"Body Composition Feature"}, + {0x2A9C,"Body Composition Measurement"}, + {0x2A38,"Body Sensor Location"}, + {0x2AA4,"Bond Management Control Point"}, + {0x2AA5,"Bond Management Features"}, + {0x2A22,"Boot Keyboard Input Report"}, + {0x2A32,"Boot Keyboard Output Report"}, + {0x2A33,"Boot Mouse Input Report"}, + {0x2AA6,"Central Address Resolution"}, + {0x2AA8,"CGM Feature"}, + {0x2AA7,"CGM Measurement"}, + {0x2AAB,"CGM Session Run Time"}, + {0x2AAA,"CGM Session Start Time"}, + {0x2AAC,"CGM Specific Ops Control Point"}, + {0x2AA9,"CGM Status"}, + {0x2ACE,"Cross Trainer Data"}, + {0x2A5C,"CSC Feature"}, + {0x2A5B,"CSC Measurement"}, + {0x2A2B,"Current Time"}, + {0x2A66,"Cycling Power Control Point"}, + {0x2A66,"Cycling Power Control Point"}, + {0x2A65,"Cycling Power Feature"}, + {0x2A65,"Cycling Power Feature"}, + {0x2A63,"Cycling Power Measurement"}, + {0x2A64,"Cycling Power Vector"}, + {0x2A99,"Database Change Increment"}, + {0x2A85,"Date of Birth"}, + {0x2A86,"Date of Threshold Assessment"}, + {0x2A08,"Date Time"}, + {0x2A0A,"Day Date Time"}, + {0x2A09,"Day of Week"}, + {0x2A7D,"Descriptor Value Changed"}, + {0x2A00,"Device Name"}, + {0x2A7B,"Dew Point"}, + {0x2A56,"Digital"}, + {0x2A57,"Digital Output"}, + {0x2A0D,"DST Offset"}, + {0x2A6C,"Elevation"}, + {0x2A87,"Email Address"}, + {0x2A0B,"Exact Time 100"}, + {0x2A0C,"Exact Time 256"}, + {0x2A88,"Fat Burn Heart Rate Lower Limit"}, + {0x2A89,"Fat Burn Heart Rate Upper Limit"}, + {0x2A26,"Firmware Revision String"}, + {0x2A8A,"First Name"}, + {0x2AD9,"Fitness Machine Control Point"}, + {0x2ACC,"Fitness Machine Feature"}, + {0x2ADA,"Fitness Machine Status"}, + {0x2A8B,"Five Zone Heart Rate Limits"}, + {0x2AB2,"Floor Number"}, + {0x2A8C,"Gender"}, + {0x2A51,"Glucose Feature"}, + {0x2A18,"Glucose Measurement"}, + {0x2A34,"Glucose Measurement Context"}, + {0x2A74,"Gust Factor"}, + {0x2A27,"Hardware Revision String"}, + {0x2A39,"Heart Rate Control Point"}, + {0x2A8D,"Heart Rate Max"}, + {0x2A37,"Heart Rate Measurement"}, + {0x2A7A,"Heat Index"}, + {0x2A8E,"Height"}, + {0x2A4C,"HID Control Point"}, + {0x2A4A,"HID Information"}, + {0x2A8F,"Hip Circumference"}, + {0x2ABA,"HTTP Control Point"}, + {0x2AB9,"HTTP Entity Body"}, + {0x2AB7,"HTTP Headers"}, + {0x2AB8,"HTTP Status Code"}, + {0x2ABB,"HTTPS Security"}, + {0x2A6F,"Humidity"}, + {0x2A2A,"IEEE 11073-20601 Regulatory Certification Data List"}, + {0x2AD2,"Indoor Bike Data"}, + {0x2AAD,"Indoor Positioning Configuration"}, + {0x2A36,"Intermediate Cuff Pressure"}, + {0x2A1E,"Intermediate Temperature"}, + {0x2A77,"Irradiance"}, + {0x2AA2,"Language"}, + {0x2A90,"Last Name"}, + {0x2AAE,"Latitude"}, + {0x2A6B,"LN Control Point"}, + {0x2A6A,"LN Feature"}, + {0x2AB1,"Local East Coordinate"}, + {0x2AB0,"Local North Coordinate"}, + {0x2A0F,"Local Time Information"}, + {0x2A67,"Location and Speed Characteristic"}, + {0x2AB5,"Location Name"}, + {0x2AAF,"Longitude"}, + {0x2A2C,"Magnetic Declination"}, + {0x2AA0,"Magnetic Flux Density - 2D"}, + {0x2AA1,"Magnetic Flux Density - 3D"}, + {0x2A29,"Manufacturer Name String"}, + {0x2A91,"Maximum Recommended Heart Rate"}, + {0x2A21,"Measurement Interval"}, + {0x2A24,"Model Number String"}, + {0x2A68,"Navigation"}, + {0x2A3E,"Network Availability"}, + {0x2A46,"New Alert"}, + {0x2AC5,"Object Action Control Point"}, + {0x2AC8,"Object Changed"}, + {0x2AC1,"Object First-Created"}, + {0x2AC3,"Object ID"}, + {0x2AC2,"Object Last-Modified"}, + {0x2AC6,"Object List Control Point"}, + {0x2AC7,"Object List Filter"}, + {0x2ABE,"Object Name"}, + {0x2AC4,"Object Properties"}, + {0x2AC0,"Object Size"}, + {0x2ABF,"Object Type"}, + {0x2ABD,"OTS Feature"}, + {0x2A04,"Peripheral Preferred Connection Parameters"}, + {0x2A02,"Peripheral Privacy Flag"}, + {0x2A5F,"PLX Continuous Measurement Characteristic"}, + {0x2A60,"PLX Features"}, + {0x2A5E,"PLX Spot-Check Measurement"}, + {0x2A50,"PnP ID"}, + {0x2A75,"Pollen Concentration"}, + {0x2A2F,"Position 2D"}, + {0x2A30,"Position 3D"}, + {0x2A69,"Position Quality"}, + {0x2A6D,"Pressure"}, + {0x2A4E,"Protocol Mode"}, + {0x2A62,"Pulse Oximetry Control Point"}, + {0x2A60,"Pulse Oximetry Pulsatile Event Characteristic"}, + {0x2A78,"Rainfall"}, + {0x2A03,"Reconnection Address"}, + {0x2A52,"Record Access Control Point"}, + {0x2A14,"Reference Time Information"}, + {0x2A3A,"Removable"}, + {0x2A4D,"Report"}, + {0x2A4B,"Report Map"}, + {0x2AC9,"Resolvable Private Address Only"}, + {0x2A92,"Resting Heart Rate"}, + {0x2A40,"Ringer Control point"}, + {0x2A41,"Ringer Setting"}, + {0x2AD1,"Rower Data"}, + {0x2A54,"RSC Feature"}, + {0x2A53,"RSC Measurement"}, + {0x2A55,"SC Control Point"}, + {0x2A4F,"Scan Interval Window"}, + {0x2A31,"Scan Refresh"}, + {0x2A3C,"Scientific Temperature Celsius"}, + {0x2A10,"Secondary Time Zone"}, + {0x2A5D,"Sensor Location"}, + {0x2A25,"Serial Number String"}, + {0x2A05,"Service Changed"}, + {0x2A3B,"Service Required"}, + {0x2A28,"Software Revision String"}, + {0x2A93,"Sport Type for Aerobic and Anaerobic Thresholds"}, + {0x2AD0,"Stair Climber Data"}, + {0x2ACF,"Step Climber Data"}, + {0x2A3D,"String"}, + {0x2AD7,"Supported Heart Rate Range"}, + {0x2AD5,"Supported Inclination Range"}, + {0x2A47,"Supported New Alert Category"}, + {0x2AD8,"Supported Power Range"}, + {0x2AD6,"Supported Resistance Level Range"}, + {0x2AD4,"Supported Speed Range"}, + {0x2A48,"Supported Unread Alert Category"}, + {0x2A23,"System ID"}, + {0x2ABC,"TDS Control Point"}, + {0x2A6E,"Temperature"}, + {0x2A1F,"Temperature Celsius"}, + {0x2A20,"Temperature Fahrenheit"}, + {0x2A1C,"Temperature Measurement"}, + {0x2A1D,"Temperature Type"}, + {0x2A94,"Three Zone Heart Rate Limits"}, + {0x2A12,"Time Accuracy"}, + {0x2A15,"Time Broadcast"}, + {0x2A13,"Time Source"}, + {0x2A16,"Time Update Control Point"}, + {0x2A17,"Time Update State"}, + {0x2A11,"Time with DST"}, + {0x2A0E,"Time Zone"}, + {0x2AD3,"Training Status"}, + {0x2ACD,"Treadmill Data"}, + {0x2A71,"True Wind Direction"}, + {0x2A70,"True Wind Speed"}, + {0x2A95,"Two Zone Heart Rate Limit"}, + {0x2A07,"Tx Power Level"}, + {0x2AB4,"Uncertainty"}, + {0x2A45,"Unread Alert Status"}, + {0x2AB6,"URI"}, + {0x2A9F,"User Control Point"}, + {0x2A9A,"User Index"}, + {0x2A76,"UV Index"}, + {0x2A96,"VO2 Max"}, + {0x2A97,"Waist Circumference"}, + {0x2A98,"Weight"}, + {0x2A9D,"Weight Measurement"}, + {0x2A9E,"Weight Scale Feature"}, + {0x2A79,"Wind Chill"}, +#endif + {0, ""} +}; + +/** + * @brief Mapping from service ids to names + */ +typedef struct { + const char* name; + const char* type; + uint32_t assignedNumber; +} gattService_t; + + +/** + * Definition of the service ids to names that we know about. + */ +static const gattService_t g_gattServices[] = { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + {"Alert Notification Service", "org.bluetooth.service.alert_notification", 0x1811}, + {"Automation IO", "org.bluetooth.service.automation_io", 0x1815 }, + {"Battery Service","org.bluetooth.service.battery_service", 0x180F}, + {"Blood Pressure", "org.bluetooth.service.blood_pressure", 0x1810}, + {"Body Composition", "org.bluetooth.service.body_composition", 0x181B}, + {"Bond Management", "org.bluetooth.service.bond_management", 0x181E}, + {"Continuous Glucose Monitoring", "org.bluetooth.service.continuous_glucose_monitoring", 0x181F}, + {"Current Time Service", "org.bluetooth.service.current_time", 0x1805}, + {"Cycling Power", "org.bluetooth.service.cycling_power", 0x1818}, + {"Cycling Speed and Cadence", "org.bluetooth.service.cycling_speed_and_cadence", 0x1816}, + {"Device Information", "org.bluetooth.service.device_information", 0x180A}, + {"Environmental Sensing", "org.bluetooth.service.environmental_sensing", 0x181A}, + {"Generic Access", "org.bluetooth.service.generic_access", 0x1800}, + {"Generic Attribute", "org.bluetooth.service.generic_attribute", 0x1801}, + {"Glucose", "org.bluetooth.service.glucose", 0x1808}, + {"Health Thermometer", "org.bluetooth.service.health_thermometer", 0x1809}, + {"Heart Rate", "org.bluetooth.service.heart_rate", 0x180D}, + {"HTTP Proxy", "org.bluetooth.service.http_proxy", 0x1823}, + {"Human Interface Device", "org.bluetooth.service.human_interface_device", 0x1812}, + {"Immediate Alert", "org.bluetooth.service.immediate_alert", 0x1802}, + {"Indoor Positioning", "org.bluetooth.service.indoor_positioning", 0x1821}, + {"Internet Protocol Support", "org.bluetooth.service.internet_protocol_support", 0x1820}, + {"Link Loss", "org.bluetooth.service.link_loss", 0x1803}, + {"Location and Navigation", "org.bluetooth.service.location_and_navigation", 0x1819}, + {"Next DST Change Service", "org.bluetooth.service.next_dst_change", 0x1807}, + {"Object Transfer", "org.bluetooth.service.object_transfer", 0x1825}, + {"Phone Alert Status Service", "org.bluetooth.service.phone_alert_status", 0x180E}, + {"Pulse Oximeter", "org.bluetooth.service.pulse_oximeter", 0x1822}, + {"Reference Time Update Service", "org.bluetooth.service.reference_time_update", 0x1806}, + {"Running Speed and Cadence", "org.bluetooth.service.running_speed_and_cadence", 0x1814}, + {"Scan Parameters", "org.bluetooth.service.scan_parameters", 0x1813}, + {"Transport Discovery", "org.bluetooth.service.transport_discovery", 0x1824}, + {"Tx Power", "org.bluetooth.service.tx_power", 0x1804}, + {"User Data", "org.bluetooth.service.user_data", 0x181C}, + {"Weight Scale", "org.bluetooth.service.weight_scale", 0x181D}, +#endif + {"", "", 0 } +}; + + +/** + * @brief Convert characteristic properties into a string representation. + * @param [in] prop Characteristic properties. + * @return A string representation of characteristic properties. + */ +std::string BLEUtils::characteristicPropertiesToString(esp_gatt_char_prop_t prop) { + std::string res = "broadcast: "; + res += ((prop & ESP_GATT_CHAR_PROP_BIT_BROADCAST)?"1":"0"); + res += ", read: "; + res += ((prop & ESP_GATT_CHAR_PROP_BIT_READ)?"1":"0"); + res += ", write_nr: "; + res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE_NR)?"1":"0"); + res += ", write: "; + res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE)?"1":"0"); + res += ", notify: "; + res += ((prop & ESP_GATT_CHAR_PROP_BIT_NOTIFY)?"1":"0"); + res += ", indicate: "; + res += ((prop & ESP_GATT_CHAR_PROP_BIT_INDICATE)?"1":"0"); + res += ", auth: "; + res += ((prop & ESP_GATT_CHAR_PROP_BIT_AUTH)?"1":"0"); + return res; +} // characteristicPropertiesToString + +/** + * @brief Convert an esp_gatt_id_t to a string. + */ +static std::string gattIdToString(esp_gatt_id_t gattId) { + std::string res = "uuid: " + BLEUUID(gattId.uuid).toString() + ", inst_id: "; + char val[8]; + snprintf(val, sizeof(val), "%d", (int)gattId.inst_id); + res += val; + return res; +} // gattIdToString + + +/** + * @brief Convert an esp_ble_addr_type_t to a string representation. + */ +const char* BLEUtils::addressTypeToString(esp_ble_addr_type_t type) { + switch (type) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case BLE_ADDR_TYPE_PUBLIC: + return "BLE_ADDR_TYPE_PUBLIC"; + case BLE_ADDR_TYPE_RANDOM: + return "BLE_ADDR_TYPE_RANDOM"; + case BLE_ADDR_TYPE_RPA_PUBLIC: + return "BLE_ADDR_TYPE_RPA_PUBLIC"; + case BLE_ADDR_TYPE_RPA_RANDOM: + return "BLE_ADDR_TYPE_RPA_RANDOM"; +#endif + default: + return " esp_ble_addr_type_t"; + } +} // addressTypeToString + + +/** + * @brief Convert the BLE Advertising Data flags to a string. + * @param adFlags The flags to convert + * @return std::string A string representation of the advertising flags. + */ +std::string BLEUtils::adFlagsToString(uint8_t adFlags) { + std::string res; + if (adFlags & (1 << 0)) { + res += "[LE Limited Discoverable Mode] "; + } + if (adFlags & (1 << 1)) { + res += "[LE General Discoverable Mode] "; + } + if (adFlags & (1 << 2)) { + res += "[BR/EDR Not Supported] "; + } + if (adFlags & (1 << 3)) { + res += "[Simultaneous LE and BR/EDR to Same Device Capable (Controller)] "; + } + if (adFlags & (1 << 4)) { + res += "[Simultaneous LE and BR/EDR to Same Device Capable (Host)] "; + } + return res; +} // adFlagsToString + + +/** + * @brief Given an advertising type, return a string representation of the type. + * + * For details see ... + * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile + * + * @return A string representation of the type. + */ +const char* BLEUtils::advTypeToString(uint8_t advType) { + switch (advType) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_BLE_AD_TYPE_FLAG: // 0x01 + return "ESP_BLE_AD_TYPE_FLAG"; + case ESP_BLE_AD_TYPE_16SRV_PART: // 0x02 + return "ESP_BLE_AD_TYPE_16SRV_PART"; + case ESP_BLE_AD_TYPE_16SRV_CMPL: // 0x03 + return "ESP_BLE_AD_TYPE_16SRV_CMPL"; + case ESP_BLE_AD_TYPE_32SRV_PART: // 0x04 + return "ESP_BLE_AD_TYPE_32SRV_PART"; + case ESP_BLE_AD_TYPE_32SRV_CMPL: // 0x05 + return "ESP_BLE_AD_TYPE_32SRV_CMPL"; + case ESP_BLE_AD_TYPE_128SRV_PART: // 0x06 + return "ESP_BLE_AD_TYPE_128SRV_PART"; + case ESP_BLE_AD_TYPE_128SRV_CMPL: // 0x07 + return "ESP_BLE_AD_TYPE_128SRV_CMPL"; + case ESP_BLE_AD_TYPE_NAME_SHORT: // 0x08 + return "ESP_BLE_AD_TYPE_NAME_SHORT"; + case ESP_BLE_AD_TYPE_NAME_CMPL: // 0x09 + return "ESP_BLE_AD_TYPE_NAME_CMPL"; + case ESP_BLE_AD_TYPE_TX_PWR: // 0x0a + return "ESP_BLE_AD_TYPE_TX_PWR"; + case ESP_BLE_AD_TYPE_DEV_CLASS: // 0x0b + return "ESP_BLE_AD_TYPE_DEV_CLASS"; + case ESP_BLE_AD_TYPE_SM_TK: // 0x10 + return "ESP_BLE_AD_TYPE_SM_TK"; + case ESP_BLE_AD_TYPE_SM_OOB_FLAG: // 0x11 + return "ESP_BLE_AD_TYPE_SM_OOB_FLAG"; + case ESP_BLE_AD_TYPE_INT_RANGE: // 0x12 + return "ESP_BLE_AD_TYPE_INT_RANGE"; + case ESP_BLE_AD_TYPE_SOL_SRV_UUID: // 0x14 + return "ESP_BLE_AD_TYPE_SOL_SRV_UUID"; + case ESP_BLE_AD_TYPE_128SOL_SRV_UUID: // 0x15 + return "ESP_BLE_AD_TYPE_128SOL_SRV_UUID"; + case ESP_BLE_AD_TYPE_SERVICE_DATA: // 0x16 + return "ESP_BLE_AD_TYPE_SERVICE_DATA"; + case ESP_BLE_AD_TYPE_PUBLIC_TARGET: // 0x17 + return "ESP_BLE_AD_TYPE_PUBLIC_TARGET"; + case ESP_BLE_AD_TYPE_RANDOM_TARGET: // 0x18 + return "ESP_BLE_AD_TYPE_RANDOM_TARGET"; + case ESP_BLE_AD_TYPE_APPEARANCE: // 0x19 + return "ESP_BLE_AD_TYPE_APPEARANCE"; + case ESP_BLE_AD_TYPE_ADV_INT: // 0x1a + return "ESP_BLE_AD_TYPE_ADV_INT"; + case ESP_BLE_AD_TYPE_32SOL_SRV_UUID: + return "ESP_BLE_AD_TYPE_32SOL_SRV_UUID"; + case ESP_BLE_AD_TYPE_32SERVICE_DATA: // 0x20 + return "ESP_BLE_AD_TYPE_32SERVICE_DATA"; + case ESP_BLE_AD_TYPE_128SERVICE_DATA: // 0x21 + return "ESP_BLE_AD_TYPE_128SERVICE_DATA"; + case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: // 0xff + return "ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE"; +#endif + default: + log_v(" adv data type: 0x%x", advType); + return ""; + } // End switch +} // advTypeToString + + +esp_gatt_id_t BLEUtils::buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id) { + esp_gatt_id_t retGattId; + retGattId.uuid = uuid; + retGattId.inst_id = inst_id; + return retGattId; +} + +esp_gatt_srvc_id_t BLEUtils::buildGattSrvcId(esp_gatt_id_t gattId, bool is_primary) { + esp_gatt_srvc_id_t retSrvcId; + retSrvcId.id = gattId; + retSrvcId.is_primary = is_primary; + return retSrvcId; +} + +/** + * @brief Create a hex representation of data. + * + * @param [in] target Where to write the hex string. If this is null, we malloc storage. + * @param [in] source The start of the binary data. + * @param [in] length The length of the data to convert. + * @return A pointer to the formatted buffer. + */ +char* BLEUtils::buildHexData(uint8_t* target, uint8_t* source, uint8_t length) { + // Guard against too much data. + if (length > 100) length = 100; + + if (target == nullptr) { + target = (uint8_t*) malloc(length * 2 + 1); + if (target == nullptr) { + log_e("buildHexData: malloc failed"); + return nullptr; + } + } + char* startOfData = (char*) target; + + for (int i = 0; i < length; i++) { + sprintf((char*) target, "%.2x", (char) *source); + source++; + target += 2; + } + + // Handle the special case where there was no data. + if (length == 0) { + *startOfData = 0; + } + + return startOfData; +} // buildHexData + + +/** + * @brief Build a printable string of memory range. + * Create a string representation of a piece of memory. Only printable characters will be included + * while those that are not printable will be replaced with '.'. + * @param [in] source Start of memory. + * @param [in] length Length of memory. + * @return A string representation of a piece of memory. + */ +std::string BLEUtils::buildPrintData(uint8_t* source, size_t length) { + std::string res; + for (int i = 0; i < length; i++) { + char c = *source; + res += (isprint(c) ? c : '.'); + source++; + } + return res; +} // buildPrintData + + +/** + * @brief Convert a close/disconnect reason to a string. + * @param [in] reason The close reason. + * @return A string representation of the reason. + */ +std::string BLEUtils::gattCloseReasonToString(esp_gatt_conn_reason_t reason) { + switch (reason) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_GATT_CONN_UNKNOWN: { + return "ESP_GATT_CONN_UNKNOWN"; + } + case ESP_GATT_CONN_L2C_FAILURE: { + return "ESP_GATT_CONN_L2C_FAILURE"; + } + case ESP_GATT_CONN_TIMEOUT: { + return "ESP_GATT_CONN_TIMEOUT"; + } + case ESP_GATT_CONN_TERMINATE_PEER_USER: { + return "ESP_GATT_CONN_TERMINATE_PEER_USER"; + } + case ESP_GATT_CONN_TERMINATE_LOCAL_HOST: { + return "ESP_GATT_CONN_TERMINATE_LOCAL_HOST"; + } + case ESP_GATT_CONN_FAIL_ESTABLISH: { + return "ESP_GATT_CONN_FAIL_ESTABLISH"; + } + case ESP_GATT_CONN_LMP_TIMEOUT: { + return "ESP_GATT_CONN_LMP_TIMEOUT"; + } + case ESP_GATT_CONN_CONN_CANCEL: { + return "ESP_GATT_CONN_CONN_CANCEL"; + } + case ESP_GATT_CONN_NONE: { + return "ESP_GATT_CONN_NONE"; + } +#endif + default: { + return "Unknown"; + } + } +} // gattCloseReasonToString + + +std::string BLEUtils::gattClientEventTypeToString(esp_gattc_cb_event_t eventType) { + switch (eventType) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_GATTC_ACL_EVT: + return "ESP_GATTC_ACL_EVT"; + case ESP_GATTC_ADV_DATA_EVT: + return "ESP_GATTC_ADV_DATA_EVT"; + case ESP_GATTC_ADV_VSC_EVT: + return "ESP_GATTC_ADV_VSC_EVT"; + case ESP_GATTC_BTH_SCAN_CFG_EVT: + return "ESP_GATTC_BTH_SCAN_CFG_EVT"; + case ESP_GATTC_BTH_SCAN_DIS_EVT: + return "ESP_GATTC_BTH_SCAN_DIS_EVT"; + case ESP_GATTC_BTH_SCAN_ENB_EVT: + return "ESP_GATTC_BTH_SCAN_ENB_EVT"; + case ESP_GATTC_BTH_SCAN_PARAM_EVT: + return "ESP_GATTC_BTH_SCAN_PARAM_EVT"; + case ESP_GATTC_BTH_SCAN_RD_EVT: + return "ESP_GATTC_BTH_SCAN_RD_EVT"; + case ESP_GATTC_BTH_SCAN_THR_EVT: + return "ESP_GATTC_BTH_SCAN_THR_EVT"; + case ESP_GATTC_CANCEL_OPEN_EVT: + return "ESP_GATTC_CANCEL_OPEN_EVT"; + case ESP_GATTC_CFG_MTU_EVT: + return "ESP_GATTC_CFG_MTU_EVT"; + case ESP_GATTC_CLOSE_EVT: + return "ESP_GATTC_CLOSE_EVT"; + case ESP_GATTC_CONGEST_EVT: + return "ESP_GATTC_CONGEST_EVT"; + case ESP_GATTC_CONNECT_EVT: + return "ESP_GATTC_CONNECT_EVT"; + case ESP_GATTC_DISCONNECT_EVT: + return "ESP_GATTC_DISCONNECT_EVT"; + case ESP_GATTC_ENC_CMPL_CB_EVT: + return "ESP_GATTC_ENC_CMPL_CB_EVT"; + case ESP_GATTC_EXEC_EVT: + return "ESP_GATTC_EXEC_EVT"; + //case ESP_GATTC_GET_CHAR_EVT: +// return "ESP_GATTC_GET_CHAR_EVT"; + //case ESP_GATTC_GET_DESCR_EVT: +// return "ESP_GATTC_GET_DESCR_EVT"; + //case ESP_GATTC_GET_INCL_SRVC_EVT: +// return "ESP_GATTC_GET_INCL_SRVC_EVT"; + case ESP_GATTC_MULT_ADV_DATA_EVT: + return "ESP_GATTC_MULT_ADV_DATA_EVT"; + case ESP_GATTC_MULT_ADV_DIS_EVT: + return "ESP_GATTC_MULT_ADV_DIS_EVT"; + case ESP_GATTC_MULT_ADV_ENB_EVT: + return "ESP_GATTC_MULT_ADV_ENB_EVT"; + case ESP_GATTC_MULT_ADV_UPD_EVT: + return "ESP_GATTC_MULT_ADV_UPD_EVT"; + case ESP_GATTC_NOTIFY_EVT: + return "ESP_GATTC_NOTIFY_EVT"; + case ESP_GATTC_OPEN_EVT: + return "ESP_GATTC_OPEN_EVT"; + case ESP_GATTC_PREP_WRITE_EVT: + return "ESP_GATTC_PREP_WRITE_EVT"; + case ESP_GATTC_READ_CHAR_EVT: + return "ESP_GATTC_READ_CHAR_EVT"; + case ESP_GATTC_REG_EVT: + return "ESP_GATTC_REG_EVT"; + case ESP_GATTC_REG_FOR_NOTIFY_EVT: + return "ESP_GATTC_REG_FOR_NOTIFY_EVT"; + case ESP_GATTC_SCAN_FLT_CFG_EVT: + return "ESP_GATTC_SCAN_FLT_CFG_EVT"; + case ESP_GATTC_SCAN_FLT_PARAM_EVT: + return "ESP_GATTC_SCAN_FLT_PARAM_EVT"; + case ESP_GATTC_SCAN_FLT_STATUS_EVT: + return "ESP_GATTC_SCAN_FLT_STATUS_EVT"; + case ESP_GATTC_SEARCH_CMPL_EVT: + return "ESP_GATTC_SEARCH_CMPL_EVT"; + case ESP_GATTC_SEARCH_RES_EVT: + return "ESP_GATTC_SEARCH_RES_EVT"; + case ESP_GATTC_SRVC_CHG_EVT: + return "ESP_GATTC_SRVC_CHG_EVT"; + case ESP_GATTC_READ_DESCR_EVT: + return "ESP_GATTC_READ_DESCR_EVT"; + case ESP_GATTC_UNREG_EVT: + return "ESP_GATTC_UNREG_EVT"; + case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: + return "ESP_GATTC_UNREG_FOR_NOTIFY_EVT"; + case ESP_GATTC_WRITE_CHAR_EVT: + return "ESP_GATTC_WRITE_CHAR_EVT"; + case ESP_GATTC_WRITE_DESCR_EVT: + return "ESP_GATTC_WRITE_DESCR_EVT"; +#endif + default: + log_v("Unknown GATT Client event type: %d", eventType); + return "Unknown"; + } +} // gattClientEventTypeToString + + +/** + * @brief Return a string representation of a GATT server event code. + * @param [in] eventType A GATT server event code. + * @return A string representation of the GATT server event code. + */ +std::string BLEUtils::gattServerEventTypeToString(esp_gatts_cb_event_t eventType) { + switch (eventType) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_GATTS_REG_EVT: + return "ESP_GATTS_REG_EVT"; + case ESP_GATTS_READ_EVT: + return "ESP_GATTS_READ_EVT"; + case ESP_GATTS_WRITE_EVT: + return "ESP_GATTS_WRITE_EVT"; + case ESP_GATTS_EXEC_WRITE_EVT: + return "ESP_GATTS_EXEC_WRITE_EVT"; + case ESP_GATTS_MTU_EVT: + return "ESP_GATTS_MTU_EVT"; + case ESP_GATTS_CONF_EVT: + return "ESP_GATTS_CONF_EVT"; + case ESP_GATTS_UNREG_EVT: + return "ESP_GATTS_UNREG_EVT"; + case ESP_GATTS_CREATE_EVT: + return "ESP_GATTS_CREATE_EVT"; + case ESP_GATTS_ADD_INCL_SRVC_EVT: + return "ESP_GATTS_ADD_INCL_SRVC_EVT"; + case ESP_GATTS_ADD_CHAR_EVT: + return "ESP_GATTS_ADD_CHAR_EVT"; + case ESP_GATTS_ADD_CHAR_DESCR_EVT: + return "ESP_GATTS_ADD_CHAR_DESCR_EVT"; + case ESP_GATTS_DELETE_EVT: + return "ESP_GATTS_DELETE_EVT"; + case ESP_GATTS_START_EVT: + return "ESP_GATTS_START_EVT"; + case ESP_GATTS_STOP_EVT: + return "ESP_GATTS_STOP_EVT"; + case ESP_GATTS_CONNECT_EVT: + return "ESP_GATTS_CONNECT_EVT"; + case ESP_GATTS_DISCONNECT_EVT: + return "ESP_GATTS_DISCONNECT_EVT"; + case ESP_GATTS_OPEN_EVT: + return "ESP_GATTS_OPEN_EVT"; + case ESP_GATTS_CANCEL_OPEN_EVT: + return "ESP_GATTS_CANCEL_OPEN_EVT"; + case ESP_GATTS_CLOSE_EVT: + return "ESP_GATTS_CLOSE_EVT"; + case ESP_GATTS_LISTEN_EVT: + return "ESP_GATTS_LISTEN_EVT"; + case ESP_GATTS_CONGEST_EVT: + return "ESP_GATTS_CONGEST_EVT"; + case ESP_GATTS_RESPONSE_EVT: + return "ESP_GATTS_RESPONSE_EVT"; + case ESP_GATTS_CREAT_ATTR_TAB_EVT: + return "ESP_GATTS_CREAT_ATTR_TAB_EVT"; + case ESP_GATTS_SET_ATTR_VAL_EVT: + return "ESP_GATTS_SET_ATTR_VAL_EVT"; + case ESP_GATTS_SEND_SERVICE_CHANGE_EVT: + return "ESP_GATTS_SEND_SERVICE_CHANGE_EVT"; +#endif + default: + return "Unknown"; + } +} // gattServerEventTypeToString + + + +/** + * @brief Convert a BLE device type to a string. + * @param [in] type The device type. + */ +const char* BLEUtils::devTypeToString(esp_bt_dev_type_t type) { + switch (type) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_BT_DEVICE_TYPE_BREDR: + return "ESP_BT_DEVICE_TYPE_BREDR"; + case ESP_BT_DEVICE_TYPE_BLE: + return "ESP_BT_DEVICE_TYPE_BLE"; + case ESP_BT_DEVICE_TYPE_DUMO: + return "ESP_BT_DEVICE_TYPE_DUMO"; +#endif + default: + return "Unknown"; + } +} // devTypeToString + + +/** + * @brief Dump the GAP event to the log. + */ +void BLEUtils::dumpGapEvent( + esp_gap_ble_cb_event_t event, + esp_ble_gap_cb_param_t* param) { + log_v("Received a GAP event: %s", gapEventToString(event)); + switch (event) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + // ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT + // adv_data_cmpl + // - esp_bt_status_t + case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: { + log_v("[status: %d]", param->adv_data_cmpl.status); + break; + } // ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT + + // ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT + // + // adv_data_raw_cmpl + // - esp_bt_status_t status + case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: { + log_v("[status: %d]", param->adv_data_raw_cmpl.status); + break; + } // ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT + + // ESP_GAP_BLE_ADV_START_COMPLETE_EVT + // + // adv_start_cmpl + // - esp_bt_status_t status + case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: { + log_v("[status: %d]", param->adv_start_cmpl.status); + break; + } // ESP_GAP_BLE_ADV_START_COMPLETE_EVT + + // ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT + // + // adv_stop_cmpl + // - esp_bt_status_t status + case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: { + log_v("[status: %d]", param->adv_stop_cmpl.status); + break; + } // ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT + + // ESP_GAP_BLE_AUTH_CMPL_EVT + // + // auth_cmpl + // - esp_bd_addr_t bd_addr + // - bool key_present + // - esp_link_key key + // - bool success + // - uint8_t fail_reason + // - esp_bd_addr_type_t addr_type + // - esp_bt_dev_type_t dev_type + case ESP_GAP_BLE_AUTH_CMPL_EVT: { + log_v("[bd_addr: %s, key_present: %d, key: ***, key_type: %d, success: %d, fail_reason: %d, addr_type: ***, dev_type: %s]", + BLEAddress(param->ble_security.auth_cmpl.bd_addr).toString().c_str(), + param->ble_security.auth_cmpl.key_present, + param->ble_security.auth_cmpl.key_type, + param->ble_security.auth_cmpl.success, + param->ble_security.auth_cmpl.fail_reason, + BLEUtils::devTypeToString(param->ble_security.auth_cmpl.dev_type) + ); + break; + } // ESP_GAP_BLE_AUTH_CMPL_EVT + + // ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT + // + // clear_bond_dev_cmpl + // - esp_bt_status_t status + case ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT: { + log_v("[status: %d]", param->clear_bond_dev_cmpl.status); + break; + } // ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT + + // ESP_GAP_BLE_LOCAL_IR_EVT + case ESP_GAP_BLE_LOCAL_IR_EVT: { + break; + } // ESP_GAP_BLE_LOCAL_IR_EVT + + // ESP_GAP_BLE_LOCAL_ER_EVT + case ESP_GAP_BLE_LOCAL_ER_EVT: { + break; + } // ESP_GAP_BLE_LOCAL_ER_EVT + + // ESP_GAP_BLE_NC_REQ_EVT + case ESP_GAP_BLE_NC_REQ_EVT: { + log_v("[bd_addr: %s, passkey: %d]", + BLEAddress(param->ble_security.key_notif.bd_addr).toString().c_str(), + param->ble_security.key_notif.passkey); + break; + } // ESP_GAP_BLE_NC_REQ_EVT + + // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT + // + // read_rssi_cmpl + // - esp_bt_status_t status + // - int8_t rssi + // - esp_bd_addr_t remote_addr + case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT: { + log_v("[status: %d, rssi: %d, remote_addr: %s]", + param->read_rssi_cmpl.status, + param->read_rssi_cmpl.rssi, + BLEAddress(param->read_rssi_cmpl.remote_addr).toString().c_str() + ); + break; + } // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT + + // ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT + // + // scan_param_cmpl. + // - esp_bt_status_t status + case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: { + log_v("[status: %d]", param->scan_param_cmpl.status); + break; + } // ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT + + // ESP_GAP_BLE_SCAN_RESULT_EVT + // + // scan_rst: + // - search_evt + // - bda + // - dev_type + // - ble_addr_type + // - ble_evt_type + // - rssi + // - ble_adv + // - flag + // - num_resps + // - adv_data_len + // - scan_rsp_len + case ESP_GAP_BLE_SCAN_RESULT_EVT: { + switch (param->scan_rst.search_evt) { + case ESP_GAP_SEARCH_INQ_RES_EVT: { + log_v("search_evt: %s, bda: %s, dev_type: %s, ble_addr_type: %s, ble_evt_type: %s, rssi: %d, ble_adv: ??, flag: %d (%s), num_resps: %d, adv_data_len: %d, scan_rsp_len: %d", + searchEventTypeToString(param->scan_rst.search_evt), + BLEAddress(param->scan_rst.bda).toString().c_str(), + devTypeToString(param->scan_rst.dev_type), + addressTypeToString(param->scan_rst.ble_addr_type), + eventTypeToString(param->scan_rst.ble_evt_type), + param->scan_rst.rssi, + param->scan_rst.flag, + adFlagsToString(param->scan_rst.flag).c_str(), + param->scan_rst.num_resps, + param->scan_rst.adv_data_len, + param->scan_rst.scan_rsp_len + ); + break; + } // ESP_GAP_SEARCH_INQ_RES_EVT + + default: { + log_v("search_evt: %s",searchEventTypeToString(param->scan_rst.search_evt)); + break; + } + } + break; + } // ESP_GAP_BLE_SCAN_RESULT_EVT + + // ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT + // + // scan_rsp_data_cmpl + // - esp_bt_status_t status + case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: { + log_v("[status: %d]", param->scan_rsp_data_cmpl.status); + break; + } // ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT + + // ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT + case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: { + log_v("[status: %d]", param->scan_rsp_data_raw_cmpl.status); + break; + } // ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT + + // ESP_GAP_BLE_SCAN_START_COMPLETE_EVT + // + // scan_start_cmpl + // - esp_bt_status_t status + case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: { + log_v("[status: %d]", param->scan_start_cmpl.status); + break; + } // ESP_GAP_BLE_SCAN_START_COMPLETE_EVT + + // ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT + // + // scan_stop_cmpl + // - esp_bt_status_t status + case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT: { + log_v("[status: %d]", param->scan_stop_cmpl.status); + break; + } // ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT + + // ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT + // + // update_conn_params + // - esp_bt_status_t status + // - esp_bd_addr_t bda + // - uint16_t min_int + // - uint16_t max_int + // - uint16_t latency + // - uint16_t conn_int + // - uint16_t timeout + case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: { + log_v("[status: %d, bd_addr: %s, min_int: %d, max_int: %d, latency: %d, conn_int: %d, timeout: %d]", + param->update_conn_params.status, + BLEAddress(param->update_conn_params.bda).toString().c_str(), + param->update_conn_params.min_int, + param->update_conn_params.max_int, + param->update_conn_params.latency, + param->update_conn_params.conn_int, + param->update_conn_params.timeout + ); + break; + } // ESP_GAP_BLE_SCAN_UPDATE_CONN_PARAMS_EVT + + // ESP_GAP_BLE_SEC_REQ_EVT + case ESP_GAP_BLE_SEC_REQ_EVT: { + log_v("[bd_addr: %s]", BLEAddress(param->ble_security.ble_req.bd_addr).toString().c_str()); + break; + } // ESP_GAP_BLE_SEC_REQ_EVT +#endif + default: { + log_v("*** dumpGapEvent: Logger not coded ***"); + break; + } // default + } // switch +} // dumpGapEvent + + +/** + * @brief Decode and dump a GATT client event + * + * @param [in] event The type of event received. + * @param [in] evtParam The data associated with the event. + */ +void BLEUtils::dumpGattClientEvent( + esp_gattc_cb_event_t event, + esp_gatt_if_t gattc_if, + esp_ble_gattc_cb_param_t* evtParam) { + + //esp_ble_gattc_cb_param_t* evtParam = (esp_ble_gattc_cb_param_t*) param; + log_v("GATT Event: %s", BLEUtils::gattClientEventTypeToString(event).c_str()); + switch (event) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + // ESP_GATTC_CLOSE_EVT + // + // close: + // - esp_gatt_status_t status + // - uint16_t conn_id + // - esp_bd_addr_t remote_bda + // - esp_gatt_conn_reason_t reason + case ESP_GATTC_CLOSE_EVT: { + log_v("[status: %s, reason:%s, conn_id: %d]", + BLEUtils::gattStatusToString(evtParam->close.status).c_str(), + BLEUtils::gattCloseReasonToString(evtParam->close.reason).c_str(), + evtParam->close.conn_id); + break; + } + + // ESP_GATTC_CONNECT_EVT + // + // connect: + // - esp_gatt_status_t status + // - uint16_t conn_id + // - esp_bd_addr_t remote_bda + case ESP_GATTC_CONNECT_EVT: { + log_v("[conn_id: %d, remote_bda: %s]", + evtParam->connect.conn_id, + BLEAddress(evtParam->connect.remote_bda).toString().c_str() + ); + break; + } + + // ESP_GATTC_DISCONNECT_EVT + // + // disconnect: + // - esp_gatt_conn_reason_t reason + // - uint16_t conn_id + // - esp_bd_addr_t remote_bda + case ESP_GATTC_DISCONNECT_EVT: { + log_v("[reason: %s, conn_id: %d, remote_bda: %s]", + BLEUtils::gattCloseReasonToString(evtParam->disconnect.reason).c_str(), + evtParam->disconnect.conn_id, + BLEAddress(evtParam->disconnect.remote_bda).toString().c_str() + ); + break; + } // ESP_GATTC_DISCONNECT_EVT + + // ESP_GATTC_GET_CHAR_EVT + // + // get_char: + // - esp_gatt_status_t status + // - uin1t6_t conn_id + // - esp_gatt_srvc_id_t srvc_id + // - esp_gatt_id_t char_id + // - esp_gatt_char_prop_t char_prop + /* + case ESP_GATTC_GET_CHAR_EVT: { + + // If the status of the event shows that we have a value other than ESP_GATT_OK then the + // characteristic fields are not set to a usable value .. so don't try and log them. + if (evtParam->get_char.status == ESP_GATT_OK) { + std::string description = "Unknown"; + if (evtParam->get_char.char_id.uuid.len == ESP_UUID_LEN_16) { + description = BLEUtils::gattCharacteristicUUIDToString(evtParam->get_char.char_id.uuid.uuid.uuid16); + } + log_v("[status: %s, conn_id: %d, srvc_id: %s, char_id: %s [description: %s]\nchar_prop: %s]", + BLEUtils::gattStatusToString(evtParam->get_char.status).c_str(), + evtParam->get_char.conn_id, + BLEUtils::gattServiceIdToString(evtParam->get_char.srvc_id).c_str(), + gattIdToString(evtParam->get_char.char_id).c_str(), + description.c_str(), + BLEUtils::characteristicPropertiesToString(evtParam->get_char.char_prop).c_str() + ); + } else { + log_v("[status: %s, conn_id: %d, srvc_id: %s]", + BLEUtils::gattStatusToString(evtParam->get_char.status).c_str(), + evtParam->get_char.conn_id, + BLEUtils::gattServiceIdToString(evtParam->get_char.srvc_id).c_str() + ); + } + break; + } // ESP_GATTC_GET_CHAR_EVT + */ + + // ESP_GATTC_NOTIFY_EVT + // + // notify + // uint16_t conn_id + // esp_bd_addr_t remote_bda + // handle handle + // uint16_t value_len + // uint8_t* value + // bool is_notify + // + case ESP_GATTC_NOTIFY_EVT: { + log_v("[conn_id: %d, remote_bda: %s, handle: %d 0x%.2x, value_len: %d, is_notify: %d]", + evtParam->notify.conn_id, + BLEAddress(evtParam->notify.remote_bda).toString().c_str(), + evtParam->notify.handle, + evtParam->notify.handle, + evtParam->notify.value_len, + evtParam->notify.is_notify + ); + break; + } + + // ESP_GATTC_OPEN_EVT + // + // open: + // - esp_gatt_status_t status + // - uint16_t conn_id + // - esp_bd_addr_t remote_bda + // - uint16_t mtu + // + case ESP_GATTC_OPEN_EVT: { + log_v("[status: %s, conn_id: %d, remote_bda: %s, mtu: %d]", + BLEUtils::gattStatusToString(evtParam->open.status).c_str(), + evtParam->open.conn_id, + BLEAddress(evtParam->open.remote_bda).toString().c_str(), + evtParam->open.mtu); + break; + } // ESP_GATTC_OPEN_EVT + + // ESP_GATTC_READ_CHAR_EVT + // + // Callback to indicate that requested data that we wanted to read is now available. + // + // read: + // esp_gatt_status_t status + // uint16_t conn_id + // uint16_t handle + // uint8_t* value + // uint16_t value_type + // uint16_t value_len + case ESP_GATTC_READ_CHAR_EVT: { + log_v("[status: %s, conn_id: %d, handle: %d 0x%.2x, value_len: %d]", + BLEUtils::gattStatusToString(evtParam->read.status).c_str(), + evtParam->read.conn_id, + evtParam->read.handle, + evtParam->read.handle, + evtParam->read.value_len + ); + if (evtParam->read.status == ESP_GATT_OK) { + GeneralUtils::hexDump(evtParam->read.value, evtParam->read.value_len); + /* + char* pHexData = BLEUtils::buildHexData(nullptr, evtParam->read.value, evtParam->read.value_len); + log_v("value: %s \"%s\"", pHexData, BLEUtils::buildPrintData(evtParam->read.value, evtParam->read.value_len).c_str()); + free(pHexData); + */ + } + break; + } // ESP_GATTC_READ_CHAR_EVT + + // ESP_GATTC_REG_EVT + // + // reg: + // - esp_gatt_status_t status + // - uint16_t app_id + case ESP_GATTC_REG_EVT: { + log_v("[status: %s, app_id: 0x%x]", + BLEUtils::gattStatusToString(evtParam->reg.status).c_str(), + evtParam->reg.app_id); + break; + } // ESP_GATTC_REG_EVT + + // ESP_GATTC_REG_FOR_NOTIFY_EVT + // + // reg_for_notify: + // - esp_gatt_status_t status + // - uint16_t handle + case ESP_GATTC_REG_FOR_NOTIFY_EVT: { + log_v("[status: %s, handle: %d 0x%.2x]", + BLEUtils::gattStatusToString(evtParam->reg_for_notify.status).c_str(), + evtParam->reg_for_notify.handle, + evtParam->reg_for_notify.handle + ); + break; + } // ESP_GATTC_REG_FOR_NOTIFY_EVT + + // ESP_GATTC_SEARCH_CMPL_EVT + // + // search_cmpl: + // - esp_gatt_status_t status + // - uint16_t conn_id + case ESP_GATTC_SEARCH_CMPL_EVT: { + log_v("[status: %s, conn_id: %d]", + BLEUtils::gattStatusToString(evtParam->search_cmpl.status).c_str(), + evtParam->search_cmpl.conn_id); + break; + } // ESP_GATTC_SEARCH_CMPL_EVT + + // ESP_GATTC_SEARCH_RES_EVT + // + // search_res: + // - uint16_t conn_id + // - uint16_t start_handle + // - uint16_t end_handle + // - esp_gatt_id_t srvc_id + case ESP_GATTC_SEARCH_RES_EVT: { + log_v("[conn_id: %d, start_handle: %d 0x%.2x, end_handle: %d 0x%.2x, srvc_id: %s", + evtParam->search_res.conn_id, + evtParam->search_res.start_handle, + evtParam->search_res.start_handle, + evtParam->search_res.end_handle, + evtParam->search_res.end_handle, + gattIdToString(evtParam->search_res.srvc_id).c_str()); + break; + } // ESP_GATTC_SEARCH_RES_EVT + + // ESP_GATTC_WRITE_CHAR_EVT + // + // write: + // - esp_gatt_status_t status + // - uint16_t conn_id + // - uint16_t handle + // - uint16_t offset + case ESP_GATTC_WRITE_CHAR_EVT: { + log_v("[status: %s, conn_id: %d, handle: %d 0x%.2x, offset: %d]", + BLEUtils::gattStatusToString(evtParam->write.status).c_str(), + evtParam->write.conn_id, + evtParam->write.handle, + evtParam->write.handle, + evtParam->write.offset + ); + break; + } // ESP_GATTC_WRITE_CHAR_EVT +#endif + default: + break; + } +} // dumpGattClientEvent + + +/** + * @brief Dump the details of a GATT server event. + * A GATT Server event is a callback received from the BLE subsystem when we are acting as a BLE + * server. The callback indicates the type of event in the `event` field. The `evtParam` is a + * union of structures where we can use the `event` to indicate which of the structures has been + * populated and hence is valid. + * + * @param [in] event The event type that was posted. + * @param [in] evtParam A union of structures only one of which is populated. + */ +void BLEUtils::dumpGattServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* evtParam) { + log_v("GATT ServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); + switch (event) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + + case ESP_GATTS_ADD_CHAR_DESCR_EVT: { + log_v("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", + gattStatusToString(evtParam->add_char_descr.status).c_str(), + evtParam->add_char_descr.attr_handle, + evtParam->add_char_descr.attr_handle, + evtParam->add_char_descr.service_handle, + evtParam->add_char_descr.service_handle, + BLEUUID(evtParam->add_char_descr.descr_uuid).toString().c_str()); + break; + } // ESP_GATTS_ADD_CHAR_DESCR_EVT + + case ESP_GATTS_ADD_CHAR_EVT: { + if (evtParam->add_char.status == ESP_GATT_OK) { + log_v("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", + gattStatusToString(evtParam->add_char.status).c_str(), + evtParam->add_char.attr_handle, + evtParam->add_char.attr_handle, + evtParam->add_char.service_handle, + evtParam->add_char.service_handle, + BLEUUID(evtParam->add_char.char_uuid).toString().c_str()); + } else { + log_e("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", + gattStatusToString(evtParam->add_char.status).c_str(), + evtParam->add_char.attr_handle, + evtParam->add_char.attr_handle, + evtParam->add_char.service_handle, + evtParam->add_char.service_handle, + BLEUUID(evtParam->add_char.char_uuid).toString().c_str()); + } + break; + } // ESP_GATTS_ADD_CHAR_EVT + + + // ESP_GATTS_CONF_EVT + // + // conf: + // - esp_gatt_status_t status – The status code. + // - uint16_t conn_id – The connection used. + case ESP_GATTS_CONF_EVT: { + log_v("[status: %s, conn_id: 0x%.2x]", + gattStatusToString(evtParam->conf.status).c_str(), + evtParam->conf.conn_id); + break; + } // ESP_GATTS_CONF_EVT + + + case ESP_GATTS_CONGEST_EVT: { + log_v("[conn_id: %d, congested: %d]", + evtParam->congest.conn_id, + evtParam->congest.congested); + break; + } // ESP_GATTS_CONGEST_EVT + + case ESP_GATTS_CONNECT_EVT: { + log_v("[conn_id: %d, remote_bda: %s]", + evtParam->connect.conn_id, + BLEAddress(evtParam->connect.remote_bda).toString().c_str()); + break; + } // ESP_GATTS_CONNECT_EVT + + case ESP_GATTS_CREATE_EVT: { + log_v("[status: %s, service_handle: %d 0x%.2x, service_id: [%s]]", + gattStatusToString(evtParam->create.status).c_str(), + evtParam->create.service_handle, + evtParam->create.service_handle, + gattServiceIdToString(evtParam->create.service_id).c_str()); + break; + } // ESP_GATTS_CREATE_EVT + + case ESP_GATTS_DISCONNECT_EVT: { + log_v("[conn_id: %d, remote_bda: %s]", + evtParam->connect.conn_id, + BLEAddress(evtParam->connect.remote_bda).toString().c_str()); + break; + } // ESP_GATTS_DISCONNECT_EVT + + + // ESP_GATTS_EXEC_WRITE_EVT + // exec_write: + // - uint16_t conn_id + // - uint32_t trans_id + // - esp_bd_addr_t bda + // - uint8_t exec_write_flag + case ESP_GATTS_EXEC_WRITE_EVT: { + char* pWriteFlagText; + switch (evtParam->exec_write.exec_write_flag) { + case ESP_GATT_PREP_WRITE_EXEC: { + pWriteFlagText = (char*) "WRITE"; + break; + } + + case ESP_GATT_PREP_WRITE_CANCEL: { + pWriteFlagText = (char*) "CANCEL"; + break; + } + + default: + pWriteFlagText = (char*) ""; + break; + } + + log_v("[conn_id: %d, trans_id: %d, bda: %s, exec_write_flag: 0x%.2x=%s]", + evtParam->exec_write.conn_id, + evtParam->exec_write.trans_id, + BLEAddress(evtParam->exec_write.bda).toString().c_str(), + evtParam->exec_write.exec_write_flag, + pWriteFlagText); + break; + } // ESP_GATTS_DISCONNECT_EVT + + + case ESP_GATTS_MTU_EVT: { + log_v("[conn_id: %d, mtu: %d]", + evtParam->mtu.conn_id, + evtParam->mtu.mtu); + break; + } // ESP_GATTS_MTU_EVT + + case ESP_GATTS_READ_EVT: { + log_v("[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, is_long: %d, need_rsp:%d]", + evtParam->read.conn_id, + evtParam->read.trans_id, + BLEAddress(evtParam->read.bda).toString().c_str(), + evtParam->read.handle, + evtParam->read.is_long, + evtParam->read.need_rsp); + break; + } // ESP_GATTS_READ_EVT + + case ESP_GATTS_RESPONSE_EVT: { + log_v("[status: %s, handle: 0x%.2x]", + gattStatusToString(evtParam->rsp.status).c_str(), + evtParam->rsp.handle); + break; + } // ESP_GATTS_RESPONSE_EVT + + case ESP_GATTS_REG_EVT: { + log_v("[status: %s, app_id: %d]", + gattStatusToString(evtParam->reg.status).c_str(), + evtParam->reg.app_id); + break; + } // ESP_GATTS_REG_EVT + + + // ESP_GATTS_START_EVT + // + // start: + // - esp_gatt_status_t status + // - uint16_t service_handle + case ESP_GATTS_START_EVT: { + log_v("[status: %s, service_handle: 0x%.2x]", + gattStatusToString(evtParam->start.status).c_str(), + evtParam->start.service_handle); + break; + } // ESP_GATTS_START_EVT + + + // ESP_GATTS_WRITE_EVT + // + // write: + // - uint16_t conn_id – The connection id. + // - uint16_t trans_id – The transfer id. + // - esp_bd_addr_t bda – The address of the partner. + // - uint16_t handle – The attribute handle. + // - uint16_t offset – The offset of the currently received within the whole value. + // - bool need_rsp – Do we need a response? + // - bool is_prep – Is this a write prepare? If set, then this is to be considered part of the received value and not the whole value. A subsequent ESP_GATTS_EXEC_WRITE will mark the total. + // - uint16_t len – The length of the incoming value part. + // - uint8_t* value – The data for this value part. + case ESP_GATTS_WRITE_EVT: { + log_v("[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, offset: %d, need_rsp: %d, is_prep: %d, len: %d]", + evtParam->write.conn_id, + evtParam->write.trans_id, + BLEAddress(evtParam->write.bda).toString().c_str(), + evtParam->write.handle, + evtParam->write.offset, + evtParam->write.need_rsp, + evtParam->write.is_prep, + evtParam->write.len); + char* pHex = buildHexData(nullptr, evtParam->write.value, evtParam->write.len); + log_v("[Data: %s]", pHex); + free(pHex); + break; + } // ESP_GATTS_WRITE_EVT +#endif + default: + log_v("dumpGattServerEvent: *** NOT CODED ***"); + break; + } +} // dumpGattServerEvent + + +/** + * @brief Convert a BLE event type to a string. + * @param [in] eventType The event type. + * @return The event type as a string. + */ +const char* BLEUtils::eventTypeToString(esp_ble_evt_type_t eventType) { + switch (eventType) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_BLE_EVT_CONN_ADV: + return "ESP_BLE_EVT_CONN_ADV"; + case ESP_BLE_EVT_CONN_DIR_ADV: + return "ESP_BLE_EVT_CONN_DIR_ADV"; + case ESP_BLE_EVT_DISC_ADV: + return "ESP_BLE_EVT_DISC_ADV"; + case ESP_BLE_EVT_NON_CONN_ADV: + return "ESP_BLE_EVT_NON_CONN_ADV"; + case ESP_BLE_EVT_SCAN_RSP: + return "ESP_BLE_EVT_SCAN_RSP"; +#endif + default: + log_v("Unknown esp_ble_evt_type_t: %d (0x%.2x)", eventType, eventType); + return "*** Unknown ***"; + } +} // eventTypeToString + + + +/** + * @brief Convert a BT GAP event type to a string representation. + * @param [in] eventType The type of event. + * @return A string representation of the event type. + */ +const char* BLEUtils::gapEventToString(uint32_t eventType) { + switch (eventType) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: + return "ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT"; + case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: + return "ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT"; + case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: + return "ESP_GAP_BLE_ADV_START_COMPLETE_EVT"; + case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: /* !< When stop adv complete, the event comes */ + return "ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT"; + case ESP_GAP_BLE_AUTH_CMPL_EVT: /* Authentication complete indication. */ + return "ESP_GAP_BLE_AUTH_CMPL_EVT"; + case ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT: + return "ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT"; + case ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT: + return "ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT"; + case ESP_GAP_BLE_KEY_EVT: /* BLE key event for peer device keys */ + return "ESP_GAP_BLE_KEY_EVT"; + case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ + return "ESP_GAP_BLE_LOCAL_IR_EVT"; + case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ + return "ESP_GAP_BLE_LOCAL_ER_EVT"; + case ESP_GAP_BLE_NC_REQ_EVT: /* Numeric Comparison request event */ + return "ESP_GAP_BLE_NC_REQ_EVT"; + case ESP_GAP_BLE_OOB_REQ_EVT: /* OOB request event */ + return "ESP_GAP_BLE_OOB_REQ_EVT"; + case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: /* passkey notification event */ + return "ESP_GAP_BLE_PASSKEY_NOTIF_EVT"; + case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ + return "ESP_GAP_BLE_PASSKEY_REQ_EVT"; + case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT: + return "ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT"; + case ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT: + return "ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT"; + case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: + return "ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT"; + case ESP_GAP_BLE_SCAN_RESULT_EVT: + return "ESP_GAP_BLE_SCAN_RESULT_EVT"; + case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: + return "ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT"; + case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: + return "ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT"; + case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: + return "ESP_GAP_BLE_SCAN_START_COMPLETE_EVT"; + case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT: + return "ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT"; + case ESP_GAP_BLE_SEC_REQ_EVT: /* BLE security request */ + return "ESP_GAP_BLE_SEC_REQ_EVT"; + case ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT: + return "ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT"; + case ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT: + return "ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT"; + case ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT: + return "ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT"; + case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: + return "ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT"; +#endif + default: + log_v("gapEventToString: Unknown event type %d 0x%.2x", eventType, eventType); + return "Unknown event type"; + } +} // gapEventToString + + +std::string BLEUtils::gattCharacteristicUUIDToString(uint32_t characteristicUUID) { + const characteristicMap_t* p = g_characteristicsMappings; + while (strlen(p->name) > 0) { + if (p->assignedNumber == characteristicUUID) { + return std::string(p->name); + } + p++; + } + return "Unknown"; +} // gattCharacteristicUUIDToString + + +/** + * @brief Given the UUID for a BLE defined descriptor, return its string representation. + * @param [in] descriptorUUID UUID of the descriptor to be returned as a string. + * @return The string representation of a descriptor UUID. + */ +std::string BLEUtils::gattDescriptorUUIDToString(uint32_t descriptorUUID) { + gattdescriptor_t* p = (gattdescriptor_t*) g_descriptor_ids; + while (strlen(p->name) > 0) { + if (p->assignedNumber == descriptorUUID) { + return std::string(p->name); + } + p++; + } + return ""; +} // gattDescriptorUUIDToString + + +/** + * @brief Return a string representation of an esp_gattc_service_elem_t. + * @return A string representation of an esp_gattc_service_elem_t. + */ +std::string BLEUtils::gattcServiceElementToString(esp_gattc_service_elem_t* pGATTCServiceElement) { + std::string res; + char val[6]; + res += "[uuid: " + BLEUUID(pGATTCServiceElement->uuid).toString() + ", start_handle: "; + snprintf(val, sizeof(val), "%d", pGATTCServiceElement->start_handle); + res += val; + res += " 0x"; + snprintf(val, sizeof(val), "%04x", pGATTCServiceElement->start_handle); + res += val; + res += ", end_handle: "; + snprintf(val, sizeof(val), "%d", pGATTCServiceElement->end_handle); + res += val; + res += " 0x"; + snprintf(val, sizeof(val), "%04x", pGATTCServiceElement->end_handle); + res += val; + res += "]"; + return res; +} // gattcServiceElementToString + + +/** + * @brief Convert an esp_gatt_srvc_id_t to a string. + */ +std::string BLEUtils::gattServiceIdToString(esp_gatt_srvc_id_t srvcId) { + return gattIdToString(srvcId.id); +} // gattServiceIdToString + + +std::string BLEUtils::gattServiceToString(uint32_t serviceId) { + gattService_t* p = (gattService_t*) g_gattServices; + while (strlen(p->name) > 0) { + if (p->assignedNumber == serviceId) { + return std::string(p->name); + } + p++; + } + return "Unknown"; +} // gattServiceToString + + +/** + * @brief Convert a GATT status to a string. + * + * @param [in] status The status to convert. + * @return A string representation of the status. + */ +std::string BLEUtils::gattStatusToString(esp_gatt_status_t status) { + switch (status) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_GATT_OK: + return "ESP_GATT_OK"; + case ESP_GATT_INVALID_HANDLE: + return "ESP_GATT_INVALID_HANDLE"; + case ESP_GATT_READ_NOT_PERMIT: + return "ESP_GATT_READ_NOT_PERMIT"; + case ESP_GATT_WRITE_NOT_PERMIT: + return "ESP_GATT_WRITE_NOT_PERMIT"; + case ESP_GATT_INVALID_PDU: + return "ESP_GATT_INVALID_PDU"; + case ESP_GATT_INSUF_AUTHENTICATION: + return "ESP_GATT_INSUF_AUTHENTICATION"; + case ESP_GATT_REQ_NOT_SUPPORTED: + return "ESP_GATT_REQ_NOT_SUPPORTED"; + case ESP_GATT_INVALID_OFFSET: + return "ESP_GATT_INVALID_OFFSET"; + case ESP_GATT_INSUF_AUTHORIZATION: + return "ESP_GATT_INSUF_AUTHORIZATION"; + case ESP_GATT_PREPARE_Q_FULL: + return "ESP_GATT_PREPARE_Q_FULL"; + case ESP_GATT_NOT_FOUND: + return "ESP_GATT_NOT_FOUND"; + case ESP_GATT_NOT_LONG: + return "ESP_GATT_NOT_LONG"; + case ESP_GATT_INSUF_KEY_SIZE: + return "ESP_GATT_INSUF_KEY_SIZE"; + case ESP_GATT_INVALID_ATTR_LEN: + return "ESP_GATT_INVALID_ATTR_LEN"; + case ESP_GATT_ERR_UNLIKELY: + return "ESP_GATT_ERR_UNLIKELY"; + case ESP_GATT_INSUF_ENCRYPTION: + return "ESP_GATT_INSUF_ENCRYPTION"; + case ESP_GATT_UNSUPPORT_GRP_TYPE: + return "ESP_GATT_UNSUPPORT_GRP_TYPE"; + case ESP_GATT_INSUF_RESOURCE: + return "ESP_GATT_INSUF_RESOURCE"; + case ESP_GATT_NO_RESOURCES: + return "ESP_GATT_NO_RESOURCES"; + case ESP_GATT_INTERNAL_ERROR: + return "ESP_GATT_INTERNAL_ERROR"; + case ESP_GATT_WRONG_STATE: + return "ESP_GATT_WRONG_STATE"; + case ESP_GATT_DB_FULL: + return "ESP_GATT_DB_FULL"; + case ESP_GATT_BUSY: + return "ESP_GATT_BUSY"; + case ESP_GATT_ERROR: + return "ESP_GATT_ERROR"; + case ESP_GATT_CMD_STARTED: + return "ESP_GATT_CMD_STARTED"; + case ESP_GATT_ILLEGAL_PARAMETER: + return "ESP_GATT_ILLEGAL_PARAMETER"; + case ESP_GATT_PENDING: + return "ESP_GATT_PENDING"; + case ESP_GATT_AUTH_FAIL: + return "ESP_GATT_AUTH_FAIL"; + case ESP_GATT_MORE: + return "ESP_GATT_MORE"; + case ESP_GATT_INVALID_CFG: + return "ESP_GATT_INVALID_CFG"; + case ESP_GATT_SERVICE_STARTED: + return "ESP_GATT_SERVICE_STARTED"; + case ESP_GATT_ENCRYPED_NO_MITM: + return "ESP_GATT_ENCRYPED_NO_MITM"; + case ESP_GATT_NOT_ENCRYPTED: + return "ESP_GATT_NOT_ENCRYPTED"; + case ESP_GATT_CONGESTED: + return "ESP_GATT_CONGESTED"; + case ESP_GATT_DUP_REG: + return "ESP_GATT_DUP_REG"; + case ESP_GATT_ALREADY_OPEN: + return "ESP_GATT_ALREADY_OPEN"; + case ESP_GATT_CANCEL: + return "ESP_GATT_CANCEL"; + case ESP_GATT_STACK_RSP: + return "ESP_GATT_STACK_RSP"; + case ESP_GATT_APP_RSP: + return "ESP_GATT_APP_RSP"; + case ESP_GATT_UNKNOWN_ERROR: + return "ESP_GATT_UNKNOWN_ERROR"; + case ESP_GATT_CCC_CFG_ERR: + return "ESP_GATT_CCC_CFG_ERR"; + case ESP_GATT_PRC_IN_PROGRESS: + return "ESP_GATT_PRC_IN_PROGRESS"; + case ESP_GATT_OUT_OF_RANGE: + return "ESP_GATT_OUT_OF_RANGE"; +#endif + default: + return "Unknown"; + } +} // gattStatusToString + + + +std::string BLEUtils::getMember(uint32_t memberId) { + member_t* p = (member_t*) members_ids; + + while (strlen(p->name) > 0) { + if (p->assignedNumber == memberId) { + return std::string(p->name); + } + p++; + } + return "Unknown"; +} + +/** + * @brief convert a GAP search event to a string. + * @param [in] searchEvt + * @return The search event type as a string. + */ +const char* BLEUtils::searchEventTypeToString(esp_gap_search_evt_t searchEvt) { + switch (searchEvt) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_GAP_SEARCH_INQ_RES_EVT: + return "ESP_GAP_SEARCH_INQ_RES_EVT"; + case ESP_GAP_SEARCH_INQ_CMPL_EVT: + return "ESP_GAP_SEARCH_INQ_CMPL_EVT"; + case ESP_GAP_SEARCH_DISC_RES_EVT: + return "ESP_GAP_SEARCH_DISC_RES_EVT"; + case ESP_GAP_SEARCH_DISC_BLE_RES_EVT: + return "ESP_GAP_SEARCH_DISC_BLE_RES_EVT"; + case ESP_GAP_SEARCH_DISC_CMPL_EVT: + return "ESP_GAP_SEARCH_DISC_CMPL_EVT"; + case ESP_GAP_SEARCH_DI_DISC_CMPL_EVT: + return "ESP_GAP_SEARCH_DI_DISC_CMPL_EVT"; + case ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT: + return "ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT"; +#endif + default: + log_v("Unknown event type: 0x%x", searchEvt); + return "Unknown event type"; + } +} // searchEventTypeToString + +#endif // CONFIG_BT_ENABLED diff --git a/libraries/BLE/src/BLEUtils.h b/libraries/BLE/src/BLEUtils.h new file mode 100644 index 00000000000..7981691cc84 --- /dev/null +++ b/libraries/BLE/src/BLEUtils.h @@ -0,0 +1,63 @@ +/* + * BLEUtils.h + * + * Created on: Mar 25, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEUTILS_H_ +#define COMPONENTS_CPP_UTILS_BLEUTILS_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include // ESP32 BLE +#include // ESP32 BLE +#include // ESP32 BLE +#include +#include "BLEClient.h" + +/** + * @brief A set of general %BLE utilities. + */ +class BLEUtils { +public: + static const char* addressTypeToString(esp_ble_addr_type_t type); + static std::string adFlagsToString(uint8_t adFlags); + static const char* advTypeToString(uint8_t advType); + static char* buildHexData(uint8_t* target, uint8_t* source, uint8_t length); + static std::string buildPrintData(uint8_t* source, size_t length); + static std::string characteristicPropertiesToString(esp_gatt_char_prop_t prop); + static const char* devTypeToString(esp_bt_dev_type_t type); + static esp_gatt_id_t buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id = 0); + static esp_gatt_srvc_id_t buildGattSrvcId(esp_gatt_id_t gattId, bool is_primary = true); + static void dumpGapEvent( + esp_gap_ble_cb_event_t event, + esp_ble_gap_cb_param_t* param); + static void dumpGattClientEvent( + esp_gattc_cb_event_t event, + esp_gatt_if_t gattc_if, + esp_ble_gattc_cb_param_t* evtParam); + static void dumpGattServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t* evtParam); + static const char* eventTypeToString(esp_ble_evt_type_t eventType); + static BLEClient* findByAddress(BLEAddress address); + static BLEClient* findByConnId(uint16_t conn_id); + static const char* gapEventToString(uint32_t eventType); + static std::string gattCharacteristicUUIDToString(uint32_t characteristicUUID); + static std::string gattClientEventTypeToString(esp_gattc_cb_event_t eventType); + static std::string gattCloseReasonToString(esp_gatt_conn_reason_t reason); + static std::string gattcServiceElementToString(esp_gattc_service_elem_t* pGATTCServiceElement); + static std::string gattDescriptorUUIDToString(uint32_t descriptorUUID); + static std::string gattServerEventTypeToString(esp_gatts_cb_event_t eventType); + static std::string gattServiceIdToString(esp_gatt_srvc_id_t srvcId); + static std::string gattServiceToString(uint32_t serviceId); + static std::string gattStatusToString(esp_gatt_status_t status); + static std::string getMember(uint32_t memberId); + static void registerByAddress(BLEAddress address, BLEClient* pDevice); + static void registerByConnId(uint16_t conn_id, BLEClient* pDevice); + static const char* searchEventTypeToString(esp_gap_search_evt_t searchEvt); +}; + +#endif // CONFIG_BT_ENABLED +#endif /* COMPONENTS_CPP_UTILS_BLEUTILS_H_ */ diff --git a/libraries/BLE/src/BLEValue.cpp b/libraries/BLE/src/BLEValue.cpp new file mode 100644 index 00000000000..40f6a20a656 --- /dev/null +++ b/libraries/BLE/src/BLEValue.cpp @@ -0,0 +1,130 @@ +/* + * BLEValue.cpp + * + * Created on: Jul 17, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include "BLEValue.h" +#include "esp32-hal-log.h" + +BLEValue::BLEValue() { + m_accumulation = ""; + m_value = ""; + m_readOffset = 0; +} // BLEValue + + +/** + * @brief Add a message part to the accumulation. + * The accumulation is a growing set of data that is added to until a commit or cancel. + * @param [in] part A message part being added. + */ +void BLEValue::addPart(std::string part) { + log_v(">> addPart: length=%d", part.length()); + m_accumulation += part; +} // addPart + + +/** + * @brief Add a message part to the accumulation. + * The accumulation is a growing set of data that is added to until a commit or cancel. + * @param [in] pData A message part being added. + * @param [in] length The number of bytes being added. + */ +void BLEValue::addPart(uint8_t* pData, size_t length) { + log_v(">> addPart: length=%d", length); + m_accumulation += std::string((char*) pData, length); +} // addPart + + +/** + * @brief Cancel the current accumulation. + */ +void BLEValue::cancel() { + log_v(">> cancel"); + m_accumulation = ""; + m_readOffset = 0; +} // cancel + + +/** + * @brief Commit the current accumulation. + * When writing a value, we may find that we write it in "parts" meaning that the writes come in in pieces + * of the overall message. After the last part has been received, we may perform a commit which means that + * we now have the complete message and commit the change as a unit. + */ +void BLEValue::commit() { + log_v(">> commit"); + // If there is nothing to commit, do nothing. + if (m_accumulation.length() == 0) return; + setValue(m_accumulation); + m_accumulation = ""; + m_readOffset = 0; +} // commit + + +/** + * @brief Get a pointer to the data. + * @return A pointer to the data. + */ +uint8_t* BLEValue::getData() { + return (uint8_t*) m_value.data(); +} + + +/** + * @brief Get the length of the data in bytes. + * @return The length of the data in bytes. + */ +size_t BLEValue::getLength() { + return m_value.length(); +} // getLength + + +/** + * @brief Get the read offset. + * @return The read offset into the read. + */ +uint16_t BLEValue::getReadOffset() { + return m_readOffset; +} // getReadOffset + + +/** + * @brief Get the current value. + */ +std::string BLEValue::getValue() { + return m_value; +} // getValue + + +/** + * @brief Set the read offset + * @param [in] readOffset The offset into the read. + */ +void BLEValue::setReadOffset(uint16_t readOffset) { + m_readOffset = readOffset; +} // setReadOffset + + +/** + * @brief Set the current value. + */ +void BLEValue::setValue(std::string value) { + m_value = value; +} // setValue + + +/** + * @brief Set the current value. + * @param [in] pData The data for the current value. + * @param [in] The length of the new current value. + */ +void BLEValue::setValue(uint8_t* pData, size_t length) { + m_value = std::string((char*) pData, length); +} // setValue + + +#endif // CONFIG_BT_ENABLED diff --git a/libraries/BLE/src/BLEValue.h b/libraries/BLE/src/BLEValue.h new file mode 100644 index 00000000000..5df904c10bf --- /dev/null +++ b/libraries/BLE/src/BLEValue.h @@ -0,0 +1,39 @@ +/* + * BLEValue.h + * + * Created on: Jul 17, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_BLEVALUE_H_ +#define COMPONENTS_CPP_UTILS_BLEVALUE_H_ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include + +/** + * @brief The model of a %BLE value. + */ +class BLEValue { +public: + BLEValue(); + void addPart(std::string part); + void addPart(uint8_t* pData, size_t length); + void cancel(); + void commit(); + uint8_t* getData(); + size_t getLength(); + uint16_t getReadOffset(); + std::string getValue(); + void setReadOffset(uint16_t readOffset); + void setValue(std::string value); + void setValue(uint8_t* pData, size_t length); + +private: + std::string m_accumulation; + uint16_t m_readOffset; + std::string m_value; + +}; +#endif // CONFIG_BT_ENABLED +#endif /* COMPONENTS_CPP_UTILS_BLEVALUE_H_ */ diff --git a/libraries/BLE/src/FreeRTOS.cpp b/libraries/BLE/src/FreeRTOS.cpp new file mode 100644 index 00000000000..895ba267f81 --- /dev/null +++ b/libraries/BLE/src/FreeRTOS.cpp @@ -0,0 +1,301 @@ +/* + * FreeRTOS.cpp + * + * Created on: Feb 24, 2017 + * Author: kolban + */ +#include // Include the base FreeRTOS definitions +#include // Include the task definitions +#include // Include the semaphore definitions +#include +#include +#include +#include "FreeRTOS.h" +#include "sdkconfig.h" +#include "esp32-hal-log.h" + +/** + * Sleep for the specified number of milliseconds. + * @param[in] ms The period in milliseconds for which to sleep. + */ +void FreeRTOS::sleep(uint32_t ms) { + ::vTaskDelay(ms / portTICK_PERIOD_MS); +} // sleep + + +/** + * Start a new task. + * @param[in] task The function pointer to the function to be run in the task. + * @param[in] taskName A string identifier for the task. + * @param[in] param An optional parameter to be passed to the started task. + * @param[in] stackSize An optional paremeter supplying the size of the stack in which to run the task. + */ +void FreeRTOS::startTask(void task(void*), std::string taskName, void* param, uint32_t stackSize) { + ::xTaskCreate(task, taskName.data(), stackSize, param, 5, NULL); +} // startTask + + +/** + * Delete the task. + * @param[in] pTask An optional handle to the task to be deleted. If not supplied the calling task will be deleted. + */ +void FreeRTOS::deleteTask(TaskHandle_t pTask) { + ::vTaskDelete(pTask); +} // deleteTask + + +/** + * Get the time in milliseconds since the %FreeRTOS scheduler started. + * @return The time in milliseconds since the %FreeRTOS scheduler started. + */ +uint32_t FreeRTOS::getTimeSinceStart() { + return (uint32_t) (xTaskGetTickCount() * portTICK_PERIOD_MS); +} // getTimeSinceStart + + +/** + * @brief Wait for a semaphore to be released by trying to take it and + * then releasing it again. + * @param [in] owner A debug tag. + * @return The value associated with the semaphore. + */ +uint32_t FreeRTOS::Semaphore::wait(std::string owner) { + log_v(">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str()); + + if (m_usePthreads) { + pthread_mutex_lock(&m_pthread_mutex); + } else { + xSemaphoreTake(m_semaphore, portMAX_DELAY); + } + + if (m_usePthreads) { + pthread_mutex_unlock(&m_pthread_mutex); + } else { + xSemaphoreGive(m_semaphore); + } + + log_v("<< wait: Semaphore released: %s", toString().c_str()); + return m_value; +} // wait + +/** + * @brief Wait for a semaphore to be released in a given period of time by trying to take it and + * then releasing it again. The value associated with the semaphore can be taken by value() call after return + * @param [in] owner A debug tag. + * @param [in] timeoutMs timeout to wait in ms. + * @return True if we took the semaphore within timeframe. + */ +bool FreeRTOS::Semaphore::timedWait(std::string owner, uint32_t timeoutMs) { + log_v(">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str()); + + if (m_usePthreads && timeoutMs != portMAX_DELAY) { + assert(false); // We apparently don't have a timed wait for pthreads. + } + + auto ret = pdTRUE; + + if (m_usePthreads) { + pthread_mutex_lock(&m_pthread_mutex); + } else { + ret = xSemaphoreTake(m_semaphore, timeoutMs); + } + + if (m_usePthreads) { + pthread_mutex_unlock(&m_pthread_mutex); + } else { + xSemaphoreGive(m_semaphore); + } + + log_v("<< wait: Semaphore %s released: %d", toString().c_str(), ret); + return ret; +} // wait + + +FreeRTOS::Semaphore::Semaphore(std::string name) { + m_usePthreads = false; // Are we using pThreads or FreeRTOS? + if (m_usePthreads) { + pthread_mutex_init(&m_pthread_mutex, nullptr); + } else { + m_semaphore = xSemaphoreCreateBinary(); + xSemaphoreGive(m_semaphore); + } + + m_name = name; + m_owner = std::string(""); + m_value = 0; +} + + +FreeRTOS::Semaphore::~Semaphore() { + if (m_usePthreads) { + pthread_mutex_destroy(&m_pthread_mutex); + } else { + vSemaphoreDelete(m_semaphore); + } +} + + +/** + * @brief Give a semaphore. + * The Semaphore is given. + */ +void FreeRTOS::Semaphore::give() { + log_v("Semaphore giving: %s", toString().c_str()); + m_owner = std::string(""); + + if (m_usePthreads) { + pthread_mutex_unlock(&m_pthread_mutex); + } else { + xSemaphoreGive(m_semaphore); + } +// #ifdef ARDUINO_ARCH_ESP32 +// FreeRTOS::sleep(10); +// #endif + +} // Semaphore::give + + +/** + * @brief Give a semaphore. + * The Semaphore is given with an associated value. + * @param [in] value The value to associate with the semaphore. + */ +void FreeRTOS::Semaphore::give(uint32_t value) { + m_value = value; + give(); +} // give + + +/** + * @brief Give a semaphore from an ISR. + */ +void FreeRTOS::Semaphore::giveFromISR() { + BaseType_t higherPriorityTaskWoken; + if (m_usePthreads) { + assert(false); + } else { + xSemaphoreGiveFromISR(m_semaphore, &higherPriorityTaskWoken); + } +} // giveFromISR + + +/** + * @brief Take a semaphore. + * Take a semaphore and wait indefinitely. + * @param [in] owner The new owner (for debugging) + * @return True if we took the semaphore. + */ +bool FreeRTOS::Semaphore::take(std::string owner) { + log_d("Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); + bool rc = false; + if (m_usePthreads) { + pthread_mutex_lock(&m_pthread_mutex); + } else { + rc = ::xSemaphoreTake(m_semaphore, portMAX_DELAY) == pdTRUE; + } + m_owner = owner; + if (rc) { + log_d("Semaphore taken: %s", toString().c_str()); + } else { + log_e("Semaphore NOT taken: %s", toString().c_str()); + } + return rc; +} // Semaphore::take + + +/** + * @brief Take a semaphore. + * Take a semaphore but return if we haven't obtained it in the given period of milliseconds. + * @param [in] timeoutMs Timeout in milliseconds. + * @param [in] owner The new owner (for debugging) + * @return True if we took the semaphore. + */ +bool FreeRTOS::Semaphore::take(uint32_t timeoutMs, std::string owner) { + log_v("Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); + bool rc = false; + if (m_usePthreads) { + assert(false); // We apparently don't have a timed wait for pthreads. + } else { + rc = ::xSemaphoreTake(m_semaphore, timeoutMs / portTICK_PERIOD_MS) == pdTRUE; + } + m_owner = owner; + if (rc) { + log_v("Semaphore taken: %s", toString().c_str()); + } else { + log_e("Semaphore NOT taken: %s", toString().c_str()); + } + return rc; +} // Semaphore::take + + + +/** + * @brief Create a string representation of the semaphore. + * @return A string representation of the semaphore. + */ +std::string FreeRTOS::Semaphore::toString() { + char hex[9]; + std::string res = "name: " + m_name + " (0x"; + snprintf(hex, sizeof(hex), "%08x", (uint32_t)m_semaphore); + res += hex; + res += "), owner: " + m_owner; + return res; +} // toString + + +/** + * @brief Set the name of the semaphore. + * @param [in] name The name of the semaphore. + */ +void FreeRTOS::Semaphore::setName(std::string name) { + m_name = name; +} // setName + + +/** + * @brief Create a ring buffer. + * @param [in] length The amount of storage to allocate for the ring buffer. + * @param [in] type The type of buffer. One of RINGBUF_TYPE_NOSPLIT, RINGBUF_TYPE_ALLOWSPLIT, RINGBUF_TYPE_BYTEBUF. + */ +Ringbuffer::Ringbuffer(size_t length, ringbuf_type_t type) { + m_handle = ::xRingbufferCreate(length, type); +} // Ringbuffer + + +Ringbuffer::~Ringbuffer() { + ::vRingbufferDelete(m_handle); +} // ~Ringbuffer + + +/** + * @brief Receive data from the buffer. + * @param [out] size On return, the size of data returned. + * @param [in] wait How long to wait. + * @return A pointer to the storage retrieved. + */ +void* Ringbuffer::receive(size_t* size, TickType_t wait) { + return ::xRingbufferReceive(m_handle, size, wait); +} // receive + + +/** + * @brief Return an item. + * @param [in] item The item to be returned/released. + */ +void Ringbuffer::returnItem(void* item) { + ::vRingbufferReturnItem(m_handle, item); +} // returnItem + + +/** + * @brief Send data to the buffer. + * @param [in] data The data to place into the buffer. + * @param [in] length The length of data to place into the buffer. + * @param [in] wait How long to wait before giving up. The default is to wait indefinitely. + * @return + */ +bool Ringbuffer::send(void* data, size_t length, TickType_t wait) { + return ::xRingbufferSend(m_handle, data, length, wait) == pdTRUE; +} // send + + diff --git a/libraries/BLE/src/FreeRTOS.h b/libraries/BLE/src/FreeRTOS.h new file mode 100644 index 00000000000..4d089c81db6 --- /dev/null +++ b/libraries/BLE/src/FreeRTOS.h @@ -0,0 +1,73 @@ +/* + * FreeRTOS.h + * + * Created on: Feb 24, 2017 + * Author: kolban + */ + +#ifndef MAIN_FREERTOS_H_ +#define MAIN_FREERTOS_H_ +#include +#include +#include + +#include // Include the base FreeRTOS definitions. +#include // Include the task definitions. +#include // Include the semaphore definitions. +#include // Include the ringbuffer definitions. + + +/** + * @brief Interface to %FreeRTOS functions. + */ +class FreeRTOS { +public: + static void sleep(uint32_t ms); + static void startTask(void task(void*), std::string taskName, void* param = nullptr, uint32_t stackSize = 2048); + static void deleteTask(TaskHandle_t pTask = nullptr); + + static uint32_t getTimeSinceStart(); + + class Semaphore { + public: + Semaphore(std::string owner = ""); + ~Semaphore(); + void give(); + void give(uint32_t value); + void giveFromISR(); + void setName(std::string name); + bool take(std::string owner = ""); + bool take(uint32_t timeoutMs, std::string owner = ""); + std::string toString(); + uint32_t wait(std::string owner = ""); + bool timedWait(std::string owner = "", uint32_t timeoutMs = portMAX_DELAY); + uint32_t value(){ return m_value; }; + + private: + SemaphoreHandle_t m_semaphore; + pthread_mutex_t m_pthread_mutex; + std::string m_name; + std::string m_owner; + uint32_t m_value; + bool m_usePthreads; + + }; +}; + + +/** + * @brief Ringbuffer. + */ +class Ringbuffer { +public: + Ringbuffer(size_t length, ringbuf_type_t type = RINGBUF_TYPE_NOSPLIT); + ~Ringbuffer(); + + void* receive(size_t* size, TickType_t wait = portMAX_DELAY); + void returnItem(void* item); + bool send(void* data, size_t length, TickType_t wait = portMAX_DELAY); +private: + RingbufHandle_t m_handle; +}; + +#endif /* MAIN_FREERTOS_H_ */ diff --git a/libraries/BLE/src/GeneralUtils.cpp b/libraries/BLE/src/GeneralUtils.cpp new file mode 100644 index 00000000000..02736b81b1a --- /dev/null +++ b/libraries/BLE/src/GeneralUtils.cpp @@ -0,0 +1,541 @@ +/* + * GeneralUtils.cpp + * + * Created on: May 20, 2017 + * Author: kolban + */ + +#include "GeneralUtils.h" +#include +#include +#include +#include +#include +#include +#include "FreeRTOS.h" +#include +#include +#include +#include +#include +#include "esp32-hal-log.h" + +static const char kBase64Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +static int base64EncodedLength(size_t length) { + return (length + 2 - ((length + 2) % 3)) / 3 * 4; +} // base64EncodedLength + + +static int base64EncodedLength(const std::string& in) { + return base64EncodedLength(in.length()); +} // base64EncodedLength + + +static void a3_to_a4(unsigned char* a4, unsigned char* a3) { + a4[0] = (a3[0] & 0xfc) >> 2; + a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4); + a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6); + a4[3] = (a3[2] & 0x3f); +} // a3_to_a4 + + +static void a4_to_a3(unsigned char* a3, unsigned char* a4) { + a3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4); + a3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2); + a3[2] = ((a4[2] & 0x3) << 6) + a4[3]; +} // a4_to_a3 + + +/** + * @brief Encode a string into base 64. + * @param [in] in + * @param [out] out + */ +bool GeneralUtils::base64Encode(const std::string& in, std::string* out) { + int i = 0, j = 0; + size_t enc_len = 0; + unsigned char a3[3]; + unsigned char a4[4]; + + out->resize(base64EncodedLength(in)); + + int input_len = in.size(); + std::string::const_iterator input = in.begin(); + + while (input_len--) { + a3[i++] = *(input++); + if (i == 3) { + a3_to_a4(a4, a3); + + for (i = 0; i < 4; i++) { + (*out)[enc_len++] = kBase64Alphabet[a4[i]]; + } + + i = 0; + } + } + + if (i) { + for (j = i; j < 3; j++) { + a3[j] = '\0'; + } + + a3_to_a4(a4, a3); + + for (j = 0; j < i + 1; j++) { + (*out)[enc_len++] = kBase64Alphabet[a4[j]]; + } + + while ((i++ < 3)) { + (*out)[enc_len++] = '='; + } + } + + return (enc_len == out->size()); +} // base64Encode + + +/** + * @brief Dump general info to the log. + * Data includes: + * * Amount of free RAM + */ +void GeneralUtils::dumpInfo() { + esp_chip_info_t chipInfo; + esp_chip_info(&chipInfo); + log_v("--- dumpInfo ---"); + log_v("Free heap: %d", heap_caps_get_free_size(MALLOC_CAP_8BIT)); + log_v("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model, chipInfo.cores, chipInfo.revision); + log_v("ESP-IDF version: %s", esp_get_idf_version()); + log_v("---"); +} // dumpInfo + + +/** + * @brief Does the string end with a specific character? + * @param [in] str The string to examine. + * @param [in] c The character to look form. + * @return True if the string ends with the given character. + */ +bool GeneralUtils::endsWith(std::string str, char c) { + if (str.empty()) { + return false; + } + if (str.at(str.length() - 1) == c) { + return true; + } + return false; +} // endsWidth + + +static int DecodedLength(const std::string& in) { + int numEq = 0; + int n = (int) in.size(); + + for (std::string::const_reverse_iterator it = in.rbegin(); *it == '='; ++it) { + ++numEq; + } + return ((6 * n) / 8) - numEq; +} // DecodedLength + + +static unsigned char b64_lookup(unsigned char c) { + if(c >='A' && c <='Z') return c - 'A'; + if(c >='a' && c <='z') return c - 71; + if(c >='0' && c <='9') return c + 4; + if(c == '+') return 62; + if(c == '/') return 63; + return 255; +}; // b64_lookup + + +/** + * @brief Decode a chunk of data that is base64 encoded. + * @param [in] in The string to be decoded. + * @param [out] out The resulting data. + */ +bool GeneralUtils::base64Decode(const std::string& in, std::string* out) { + int i = 0, j = 0; + size_t dec_len = 0; + unsigned char a3[3]; + unsigned char a4[4]; + + int input_len = in.size(); + std::string::const_iterator input = in.begin(); + + out->resize(DecodedLength(in)); + + while (input_len--) { + if (*input == '=') { + break; + } + + a4[i++] = *(input++); + if (i == 4) { + for (i = 0; i <4; i++) { + a4[i] = b64_lookup(a4[i]); + } + + a4_to_a3(a3,a4); + + for (i = 0; i < 3; i++) { + (*out)[dec_len++] = a3[i]; + } + + i = 0; + } + } + + if (i) { + for (j = i; j < 4; j++) { + a4[j] = '\0'; + } + + for (j = 0; j < 4; j++) { + a4[j] = b64_lookup(a4[j]); + } + + a4_to_a3(a3,a4); + + for (j = 0; j < i - 1; j++) { + (*out)[dec_len++] = a3[j]; + } + } + + return (dec_len == out->size()); + } // base64Decode + +/* +void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { + uint32_t index=0; + std::stringstream ascii; + std::stringstream hex; + char asciiBuf[80]; + char hexBuf[80]; + hex.str(""); + ascii.str(""); + while(index < length) { + hex << std::setfill('0') << std::setw(2) << std::hex << (int)pData[index] << ' '; + if (std::isprint(pData[index])) { + ascii << pData[index]; + } else { + ascii << '.'; + } + index++; + if (index % 16 == 0) { + strcpy(hexBuf, hex.str().c_str()); + strcpy(asciiBuf, ascii.str().c_str()); + log_v("%s %s", hexBuf, asciiBuf); + hex.str(""); + ascii.str(""); + } + } + if (index %16 != 0) { + while(index % 16 != 0) { + hex << " "; + index++; + } + strcpy(hexBuf, hex.str().c_str()); + strcpy(asciiBuf, ascii.str().c_str()); + log_v("%s %s", hexBuf, asciiBuf); + //log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); + } + FreeRTOS::sleep(1000); +} +*/ + +/* +void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { + uint32_t index=0; + static std::stringstream ascii; + static std::stringstream hex; + hex.str(""); + ascii.str(""); + while(index < length) { + hex << std::setfill('0') << std::setw(2) << std::hex << (int)pData[index] << ' '; + if (std::isprint(pData[index])) { + ascii << pData[index]; + } else { + ascii << '.'; + } + index++; + if (index % 16 == 0) { + log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); + hex.str(""); + ascii.str(""); + } + } + if (index %16 != 0) { + while(index % 16 != 0) { + hex << " "; + index++; + } + log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); + } + FreeRTOS::sleep(1000); +} +*/ + + +/** + * @brief Dump a representation of binary data to the console. + * + * @param [in] pData Pointer to the start of data to be logged. + * @param [in] length Length of the data (in bytes) to be logged. + * @return N/A. + */ +void GeneralUtils::hexDump(const uint8_t* pData, uint32_t length) { + char ascii[80]; + char hex[80]; + char tempBuf[80]; + uint32_t lineNumber = 0; + + log_v(" 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f"); + log_v(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); + strcpy(ascii, ""); + strcpy(hex, ""); + uint32_t index = 0; + while (index < length) { + sprintf(tempBuf, "%.2x ", pData[index]); + strcat(hex, tempBuf); + if (isprint(pData[index])) { + sprintf(tempBuf, "%c", pData[index]); + } else { + sprintf(tempBuf, "."); + } + strcat(ascii, tempBuf); + index++; + if (index % 16 == 0) { + log_v("%.4x %s %s", lineNumber * 16, hex, ascii); + strcpy(ascii, ""); + strcpy(hex, ""); + lineNumber++; + } + } + if (index %16 != 0) { + while (index % 16 != 0) { + strcat(hex, " "); + index++; + } + log_v("%.4x %s %s", lineNumber * 16, hex, ascii); + } +} // hexDump + + +/** + * @brief Convert an IP address to string. + * @param ip The 4 byte IP address. + * @return A string representation of the IP address. + */ +std::string GeneralUtils::ipToString(uint8_t *ip) { + auto size = 16; + char *val = (char*)malloc(size); + snprintf(val, size, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + std::string res(val); + free(val); + return res; +} // ipToString + + +/** + * @brief Split a string into parts based on a delimiter. + * @param [in] source The source string to split. + * @param [in] delimiter The delimiter characters. + * @return A vector of strings that are the split of the input. + */ +std::vector GeneralUtils::split(std::string source, char delimiter) { + // See also: https://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g + std::vector strings; + std::size_t current, previous = 0; + current = source.find(delimiter); + while (current != std::string::npos) { + strings.push_back(trim(source.substr(previous, current - previous))); + previous = current + 1; + current = source.find(delimiter, previous); + } + strings.push_back(trim(source.substr(previous, current - previous))); + return strings; +} // split + + +/** + * @brief Convert an ESP error code to a string. + * @param [in] errCode The errCode to be converted. + * @return A string representation of the error code. + */ +const char* GeneralUtils::errorToString(esp_err_t errCode) { + switch (errCode) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case ESP_OK: + return "ESP_OK"; + case ESP_FAIL: + return "ESP_FAIL"; + case ESP_ERR_NO_MEM: + return "ESP_ERR_NO_MEM"; + case ESP_ERR_INVALID_ARG: + return "ESP_ERR_INVALID_ARG"; + case ESP_ERR_INVALID_SIZE: + return "ESP_ERR_INVALID_SIZE"; + case ESP_ERR_INVALID_STATE: + return "ESP_ERR_INVALID_STATE"; + case ESP_ERR_NOT_FOUND: + return "ESP_ERR_NOT_FOUND"; + case ESP_ERR_NOT_SUPPORTED: + return "ESP_ERR_NOT_SUPPORTED"; + case ESP_ERR_TIMEOUT: + return "ESP_ERR_TIMEOUT"; + case ESP_ERR_NVS_NOT_INITIALIZED: + return "ESP_ERR_NVS_NOT_INITIALIZED"; + case ESP_ERR_NVS_NOT_FOUND: + return "ESP_ERR_NVS_NOT_FOUND"; + case ESP_ERR_NVS_TYPE_MISMATCH: + return "ESP_ERR_NVS_TYPE_MISMATCH"; + case ESP_ERR_NVS_READ_ONLY: + return "ESP_ERR_NVS_READ_ONLY"; + case ESP_ERR_NVS_NOT_ENOUGH_SPACE: + return "ESP_ERR_NVS_NOT_ENOUGH_SPACE"; + case ESP_ERR_NVS_INVALID_NAME: + return "ESP_ERR_NVS_INVALID_NAME"; + case ESP_ERR_NVS_INVALID_HANDLE: + return "ESP_ERR_NVS_INVALID_HANDLE"; + case ESP_ERR_NVS_REMOVE_FAILED: + return "ESP_ERR_NVS_REMOVE_FAILED"; + case ESP_ERR_NVS_KEY_TOO_LONG: + return "ESP_ERR_NVS_KEY_TOO_LONG"; + case ESP_ERR_NVS_PAGE_FULL: + return "ESP_ERR_NVS_PAGE_FULL"; + case ESP_ERR_NVS_INVALID_STATE: + return "ESP_ERR_NVS_INVALID_STATE"; + case ESP_ERR_NVS_INVALID_LENGTH: + return "ESP_ERR_NVS_INVALID_LENGTH"; + case ESP_ERR_WIFI_NOT_INIT: + return "ESP_ERR_WIFI_NOT_INIT"; + //case ESP_ERR_WIFI_NOT_START: + // return "ESP_ERR_WIFI_NOT_START"; + case ESP_ERR_WIFI_IF: + return "ESP_ERR_WIFI_IF"; + case ESP_ERR_WIFI_MODE: + return "ESP_ERR_WIFI_MODE"; + case ESP_ERR_WIFI_STATE: + return "ESP_ERR_WIFI_STATE"; + case ESP_ERR_WIFI_CONN: + return "ESP_ERR_WIFI_CONN"; + case ESP_ERR_WIFI_NVS: + return "ESP_ERR_WIFI_NVS"; + case ESP_ERR_WIFI_MAC: + return "ESP_ERR_WIFI_MAC"; + case ESP_ERR_WIFI_SSID: + return "ESP_ERR_WIFI_SSID"; + case ESP_ERR_WIFI_PASSWORD: + return "ESP_ERR_WIFI_PASSWORD"; + case ESP_ERR_WIFI_TIMEOUT: + return "ESP_ERR_WIFI_TIMEOUT"; + case ESP_ERR_WIFI_WAKE_FAIL: + return "ESP_ERR_WIFI_WAKE_FAIL"; +#endif + default: + return "Unknown ESP_ERR error"; + } +} // errorToString + +/** + * @brief Convert a wifi_err_reason_t code to a string. + * @param [in] errCode The errCode to be converted. + * @return A string representation of the error code. + * + * @note: wifi_err_reason_t values as of April 2018 are: (1-24, 200-204) and are defined in ~/esp-idf/components/esp32/include/esp_wifi_types.h. + */ +const char* GeneralUtils::wifiErrorToString(uint8_t errCode) { + if (errCode == ESP_OK) return "ESP_OK (received SYSTEM_EVENT_STA_GOT_IP event)"; + if (errCode == UINT8_MAX) return "Not Connected (default value)"; + + switch ((wifi_err_reason_t) errCode) { +#if CONFIG_LOG_DEFAULT_LEVEL > 4 + case WIFI_REASON_UNSPECIFIED: + return "WIFI_REASON_UNSPECIFIED"; + case WIFI_REASON_AUTH_EXPIRE: + return "WIFI_REASON_AUTH_EXPIRE"; + case WIFI_REASON_AUTH_LEAVE: + return "WIFI_REASON_AUTH_LEAVE"; + case WIFI_REASON_ASSOC_EXPIRE: + return "WIFI_REASON_ASSOC_EXPIRE"; + case WIFI_REASON_ASSOC_TOOMANY: + return "WIFI_REASON_ASSOC_TOOMANY"; + case WIFI_REASON_NOT_AUTHED: + return "WIFI_REASON_NOT_AUTHED"; + case WIFI_REASON_NOT_ASSOCED: + return "WIFI_REASON_NOT_ASSOCED"; + case WIFI_REASON_ASSOC_LEAVE: + return "WIFI_REASON_ASSOC_LEAVE"; + case WIFI_REASON_ASSOC_NOT_AUTHED: + return "WIFI_REASON_ASSOC_NOT_AUTHED"; + case WIFI_REASON_DISASSOC_PWRCAP_BAD: + return "WIFI_REASON_DISASSOC_PWRCAP_BAD"; + case WIFI_REASON_DISASSOC_SUPCHAN_BAD: + return "WIFI_REASON_DISASSOC_SUPCHAN_BAD"; + case WIFI_REASON_IE_INVALID: + return "WIFI_REASON_IE_INVALID"; + case WIFI_REASON_MIC_FAILURE: + return "WIFI_REASON_MIC_FAILURE"; + case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: + return "WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT"; + case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT: + return "WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT"; + case WIFI_REASON_IE_IN_4WAY_DIFFERS: + return "WIFI_REASON_IE_IN_4WAY_DIFFERS"; + case WIFI_REASON_GROUP_CIPHER_INVALID: + return "WIFI_REASON_GROUP_CIPHER_INVALID"; + case WIFI_REASON_PAIRWISE_CIPHER_INVALID: + return "WIFI_REASON_PAIRWISE_CIPHER_INVALID"; + case WIFI_REASON_AKMP_INVALID: + return "WIFI_REASON_AKMP_INVALID"; + case WIFI_REASON_UNSUPP_RSN_IE_VERSION: + return "WIFI_REASON_UNSUPP_RSN_IE_VERSION"; + case WIFI_REASON_INVALID_RSN_IE_CAP: + return "WIFI_REASON_INVALID_RSN_IE_CAP"; + case WIFI_REASON_802_1X_AUTH_FAILED: + return "WIFI_REASON_802_1X_AUTH_FAILED"; + case WIFI_REASON_CIPHER_SUITE_REJECTED: + return "WIFI_REASON_CIPHER_SUITE_REJECTED"; + case WIFI_REASON_BEACON_TIMEOUT: + return "WIFI_REASON_BEACON_TIMEOUT"; + case WIFI_REASON_NO_AP_FOUND: + return "WIFI_REASON_NO_AP_FOUND"; + case WIFI_REASON_AUTH_FAIL: + return "WIFI_REASON_AUTH_FAIL"; + case WIFI_REASON_ASSOC_FAIL: + return "WIFI_REASON_ASSOC_FAIL"; + case WIFI_REASON_HANDSHAKE_TIMEOUT: + return "WIFI_REASON_HANDSHAKE_TIMEOUT"; +#endif + default: + return "Unknown ESP_ERR error"; + } +} // wifiErrorToString + + +/** + * @brief Convert a string to lower case. + * @param [in] value The string to convert to lower case. + * @return A lower case representation of the string. + */ +std::string GeneralUtils::toLower(std::string& value) { + // Question: Could this be improved with a signature of: + // std::string& GeneralUtils::toLower(std::string& value) + std::transform(value.begin(), value.end(), value.begin(), ::tolower); + return value; +} // toLower + + +/** + * @brief Remove white space from a string. + */ +std::string GeneralUtils::trim(const std::string& str) { + size_t first = str.find_first_not_of(' '); + if (std::string::npos == first) return str; + size_t last = str.find_last_not_of(' '); + return str.substr(first, (last - first + 1)); +} // trim diff --git a/libraries/BLE/src/GeneralUtils.h b/libraries/BLE/src/GeneralUtils.h new file mode 100644 index 00000000000..8eecbd4d029 --- /dev/null +++ b/libraries/BLE/src/GeneralUtils.h @@ -0,0 +1,35 @@ +/* + * GeneralUtils.h + * + * Created on: May 20, 2017 + * Author: kolban + */ + +#ifndef COMPONENTS_CPP_UTILS_GENERALUTILS_H_ +#define COMPONENTS_CPP_UTILS_GENERALUTILS_H_ +#include +#include +#include +#include +#include + +/** + * @brief General utilities. + */ +class GeneralUtils { +public: + static bool base64Decode(const std::string& in, std::string* out); + static bool base64Encode(const std::string& in, std::string* out); + static void dumpInfo(); + static bool endsWith(std::string str, char c); + static const char* errorToString(esp_err_t errCode); + static const char* wifiErrorToString(uint8_t value); + static void hexDump(const uint8_t* pData, uint32_t length); + static std::string ipToString(uint8_t* ip); + static std::vector split(std::string source, char delimiter); + static std::string toLower(std::string& value); + static std::string trim(const std::string& str); + +}; + +#endif /* COMPONENTS_CPP_UTILS_GENERALUTILS_H_ */ diff --git a/libraries/BLE/src/HIDKeyboardTypes.h b/libraries/BLE/src/HIDKeyboardTypes.h new file mode 100644 index 00000000000..4e221d57f8d --- /dev/null +++ b/libraries/BLE/src/HIDKeyboardTypes.h @@ -0,0 +1,402 @@ +/* Copyright (c) 2015 mbed.org, 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. + * + * Note: this file was pulled from different parts of the USBHID library, in mbed SDK + */ + +#ifndef KEYBOARD_DEFS_H +#define KEYBOARD_DEFS_H + +#define REPORT_ID_KEYBOARD 1 +#define REPORT_ID_VOLUME 3 + +/* Modifiers */ +enum MODIFIER_KEY { + KEY_CTRL = 1, + KEY_SHIFT = 2, + KEY_ALT = 4, +}; + + +enum MEDIA_KEY { + KEY_NEXT_TRACK, /*!< next Track Button */ + KEY_PREVIOUS_TRACK, /*!< Previous track Button */ + KEY_STOP, /*!< Stop Button */ + KEY_PLAY_PAUSE, /*!< Play/Pause Button */ + KEY_MUTE, /*!< Mute Button */ + KEY_VOLUME_UP, /*!< Volume Up Button */ + KEY_VOLUME_DOWN, /*!< Volume Down Button */ +}; + +enum FUNCTION_KEY { + KEY_F1 = 128, /* F1 key */ + KEY_F2, /* F2 key */ + KEY_F3, /* F3 key */ + KEY_F4, /* F4 key */ + KEY_F5, /* F5 key */ + KEY_F6, /* F6 key */ + KEY_F7, /* F7 key */ + KEY_F8, /* F8 key */ + KEY_F9, /* F9 key */ + KEY_F10, /* F10 key */ + KEY_F11, /* F11 key */ + KEY_F12, /* F12 key */ + + KEY_PRINT_SCREEN, /* Print Screen key */ + KEY_SCROLL_LOCK, /* Scroll lock */ + KEY_CAPS_LOCK, /* caps lock */ + KEY_NUM_LOCK, /* num lock */ + KEY_INSERT, /* Insert key */ + KEY_HOME, /* Home key */ + KEY_PAGE_UP, /* Page Up key */ + KEY_PAGE_DOWN, /* Page Down key */ + + RIGHT_ARROW, /* Right arrow */ + LEFT_ARROW, /* Left arrow */ + DOWN_ARROW, /* Down arrow */ + UP_ARROW, /* Up arrow */ +}; + +typedef struct { + unsigned char usage; + unsigned char modifier; +} KEYMAP; + +#ifdef US_KEYBOARD +/* US keyboard (as HID standard) */ +#define KEYMAP_SIZE (152) +const KEYMAP keymap[KEYMAP_SIZE] = { + {0, 0}, /* NUL */ + {0, 0}, /* SOH */ + {0, 0}, /* STX */ + {0, 0}, /* ETX */ + {0, 0}, /* EOT */ + {0, 0}, /* ENQ */ + {0, 0}, /* ACK */ + {0, 0}, /* BEL */ + {0x2a, 0}, /* BS */ /* Keyboard Delete (Backspace) */ + {0x2b, 0}, /* TAB */ /* Keyboard Tab */ + {0x28, 0}, /* LF */ /* Keyboard Return (Enter) */ + {0, 0}, /* VT */ + {0, 0}, /* FF */ + {0, 0}, /* CR */ + {0, 0}, /* SO */ + {0, 0}, /* SI */ + {0, 0}, /* DEL */ + {0, 0}, /* DC1 */ + {0, 0}, /* DC2 */ + {0, 0}, /* DC3 */ + {0, 0}, /* DC4 */ + {0, 0}, /* NAK */ + {0, 0}, /* SYN */ + {0, 0}, /* ETB */ + {0, 0}, /* CAN */ + {0, 0}, /* EM */ + {0, 0}, /* SUB */ + {0, 0}, /* ESC */ + {0, 0}, /* FS */ + {0, 0}, /* GS */ + {0, 0}, /* RS */ + {0, 0}, /* US */ + {0x2c, 0}, /* */ + {0x1e, KEY_SHIFT}, /* ! */ + {0x34, KEY_SHIFT}, /* " */ + {0x20, KEY_SHIFT}, /* # */ + {0x21, KEY_SHIFT}, /* $ */ + {0x22, KEY_SHIFT}, /* % */ + {0x24, KEY_SHIFT}, /* & */ + {0x34, 0}, /* ' */ + {0x26, KEY_SHIFT}, /* ( */ + {0x27, KEY_SHIFT}, /* ) */ + {0x25, KEY_SHIFT}, /* * */ + {0x2e, KEY_SHIFT}, /* + */ + {0x36, 0}, /* , */ + {0x2d, 0}, /* - */ + {0x37, 0}, /* . */ + {0x38, 0}, /* / */ + {0x27, 0}, /* 0 */ + {0x1e, 0}, /* 1 */ + {0x1f, 0}, /* 2 */ + {0x20, 0}, /* 3 */ + {0x21, 0}, /* 4 */ + {0x22, 0}, /* 5 */ + {0x23, 0}, /* 6 */ + {0x24, 0}, /* 7 */ + {0x25, 0}, /* 8 */ + {0x26, 0}, /* 9 */ + {0x33, KEY_SHIFT}, /* : */ + {0x33, 0}, /* ; */ + {0x36, KEY_SHIFT}, /* < */ + {0x2e, 0}, /* = */ + {0x37, KEY_SHIFT}, /* > */ + {0x38, KEY_SHIFT}, /* ? */ + {0x1f, KEY_SHIFT}, /* @ */ + {0x04, KEY_SHIFT}, /* A */ + {0x05, KEY_SHIFT}, /* B */ + {0x06, KEY_SHIFT}, /* C */ + {0x07, KEY_SHIFT}, /* D */ + {0x08, KEY_SHIFT}, /* E */ + {0x09, KEY_SHIFT}, /* F */ + {0x0a, KEY_SHIFT}, /* G */ + {0x0b, KEY_SHIFT}, /* H */ + {0x0c, KEY_SHIFT}, /* I */ + {0x0d, KEY_SHIFT}, /* J */ + {0x0e, KEY_SHIFT}, /* K */ + {0x0f, KEY_SHIFT}, /* L */ + {0x10, KEY_SHIFT}, /* M */ + {0x11, KEY_SHIFT}, /* N */ + {0x12, KEY_SHIFT}, /* O */ + {0x13, KEY_SHIFT}, /* P */ + {0x14, KEY_SHIFT}, /* Q */ + {0x15, KEY_SHIFT}, /* R */ + {0x16, KEY_SHIFT}, /* S */ + {0x17, KEY_SHIFT}, /* T */ + {0x18, KEY_SHIFT}, /* U */ + {0x19, KEY_SHIFT}, /* V */ + {0x1a, KEY_SHIFT}, /* W */ + {0x1b, KEY_SHIFT}, /* X */ + {0x1c, KEY_SHIFT}, /* Y */ + {0x1d, KEY_SHIFT}, /* Z */ + {0x2f, 0}, /* [ */ + {0x31, 0}, /* \ */ + {0x30, 0}, /* ] */ + {0x23, KEY_SHIFT}, /* ^ */ + {0x2d, KEY_SHIFT}, /* _ */ + {0x35, 0}, /* ` */ + {0x04, 0}, /* a */ + {0x05, 0}, /* b */ + {0x06, 0}, /* c */ + {0x07, 0}, /* d */ + {0x08, 0}, /* e */ + {0x09, 0}, /* f */ + {0x0a, 0}, /* g */ + {0x0b, 0}, /* h */ + {0x0c, 0}, /* i */ + {0x0d, 0}, /* j */ + {0x0e, 0}, /* k */ + {0x0f, 0}, /* l */ + {0x10, 0}, /* m */ + {0x11, 0}, /* n */ + {0x12, 0}, /* o */ + {0x13, 0}, /* p */ + {0x14, 0}, /* q */ + {0x15, 0}, /* r */ + {0x16, 0}, /* s */ + {0x17, 0}, /* t */ + {0x18, 0}, /* u */ + {0x19, 0}, /* v */ + {0x1a, 0}, /* w */ + {0x1b, 0}, /* x */ + {0x1c, 0}, /* y */ + {0x1d, 0}, /* z */ + {0x2f, KEY_SHIFT}, /* { */ + {0x31, KEY_SHIFT}, /* | */ + {0x30, KEY_SHIFT}, /* } */ + {0x35, KEY_SHIFT}, /* ~ */ + {0,0}, /* DEL */ + + {0x3a, 0}, /* F1 */ + {0x3b, 0}, /* F2 */ + {0x3c, 0}, /* F3 */ + {0x3d, 0}, /* F4 */ + {0x3e, 0}, /* F5 */ + {0x3f, 0}, /* F6 */ + {0x40, 0}, /* F7 */ + {0x41, 0}, /* F8 */ + {0x42, 0}, /* F9 */ + {0x43, 0}, /* F10 */ + {0x44, 0}, /* F11 */ + {0x45, 0}, /* F12 */ + + {0x46, 0}, /* PRINT_SCREEN */ + {0x47, 0}, /* SCROLL_LOCK */ + {0x39, 0}, /* CAPS_LOCK */ + {0x53, 0}, /* NUM_LOCK */ + {0x49, 0}, /* INSERT */ + {0x4a, 0}, /* HOME */ + {0x4b, 0}, /* PAGE_UP */ + {0x4e, 0}, /* PAGE_DOWN */ + + {0x4f, 0}, /* RIGHT_ARROW */ + {0x50, 0}, /* LEFT_ARROW */ + {0x51, 0}, /* DOWN_ARROW */ + {0x52, 0}, /* UP_ARROW */ +}; + +#else +/* UK keyboard */ +#define KEYMAP_SIZE (152) +const KEYMAP keymap[KEYMAP_SIZE] = { + {0, 0}, /* NUL */ + {0, 0}, /* SOH */ + {0, 0}, /* STX */ + {0, 0}, /* ETX */ + {0, 0}, /* EOT */ + {0, 0}, /* ENQ */ + {0, 0}, /* ACK */ + {0, 0}, /* BEL */ + {0x2a, 0}, /* BS */ /* Keyboard Delete (Backspace) */ + {0x2b, 0}, /* TAB */ /* Keyboard Tab */ + {0x28, 0}, /* LF */ /* Keyboard Return (Enter) */ + {0, 0}, /* VT */ + {0, 0}, /* FF */ + {0, 0}, /* CR */ + {0, 0}, /* SO */ + {0, 0}, /* SI */ + {0, 0}, /* DEL */ + {0, 0}, /* DC1 */ + {0, 0}, /* DC2 */ + {0, 0}, /* DC3 */ + {0, 0}, /* DC4 */ + {0, 0}, /* NAK */ + {0, 0}, /* SYN */ + {0, 0}, /* ETB */ + {0, 0}, /* CAN */ + {0, 0}, /* EM */ + {0, 0}, /* SUB */ + {0, 0}, /* ESC */ + {0, 0}, /* FS */ + {0, 0}, /* GS */ + {0, 0}, /* RS */ + {0, 0}, /* US */ + {0x2c, 0}, /* */ + {0x1e, KEY_SHIFT}, /* ! */ + {0x1f, KEY_SHIFT}, /* " */ + {0x32, 0}, /* # */ + {0x21, KEY_SHIFT}, /* $ */ + {0x22, KEY_SHIFT}, /* % */ + {0x24, KEY_SHIFT}, /* & */ + {0x34, 0}, /* ' */ + {0x26, KEY_SHIFT}, /* ( */ + {0x27, KEY_SHIFT}, /* ) */ + {0x25, KEY_SHIFT}, /* * */ + {0x2e, KEY_SHIFT}, /* + */ + {0x36, 0}, /* , */ + {0x2d, 0}, /* - */ + {0x37, 0}, /* . */ + {0x38, 0}, /* / */ + {0x27, 0}, /* 0 */ + {0x1e, 0}, /* 1 */ + {0x1f, 0}, /* 2 */ + {0x20, 0}, /* 3 */ + {0x21, 0}, /* 4 */ + {0x22, 0}, /* 5 */ + {0x23, 0}, /* 6 */ + {0x24, 0}, /* 7 */ + {0x25, 0}, /* 8 */ + {0x26, 0}, /* 9 */ + {0x33, KEY_SHIFT}, /* : */ + {0x33, 0}, /* ; */ + {0x36, KEY_SHIFT}, /* < */ + {0x2e, 0}, /* = */ + {0x37, KEY_SHIFT}, /* > */ + {0x38, KEY_SHIFT}, /* ? */ + {0x34, KEY_SHIFT}, /* @ */ + {0x04, KEY_SHIFT}, /* A */ + {0x05, KEY_SHIFT}, /* B */ + {0x06, KEY_SHIFT}, /* C */ + {0x07, KEY_SHIFT}, /* D */ + {0x08, KEY_SHIFT}, /* E */ + {0x09, KEY_SHIFT}, /* F */ + {0x0a, KEY_SHIFT}, /* G */ + {0x0b, KEY_SHIFT}, /* H */ + {0x0c, KEY_SHIFT}, /* I */ + {0x0d, KEY_SHIFT}, /* J */ + {0x0e, KEY_SHIFT}, /* K */ + {0x0f, KEY_SHIFT}, /* L */ + {0x10, KEY_SHIFT}, /* M */ + {0x11, KEY_SHIFT}, /* N */ + {0x12, KEY_SHIFT}, /* O */ + {0x13, KEY_SHIFT}, /* P */ + {0x14, KEY_SHIFT}, /* Q */ + {0x15, KEY_SHIFT}, /* R */ + {0x16, KEY_SHIFT}, /* S */ + {0x17, KEY_SHIFT}, /* T */ + {0x18, KEY_SHIFT}, /* U */ + {0x19, KEY_SHIFT}, /* V */ + {0x1a, KEY_SHIFT}, /* W */ + {0x1b, KEY_SHIFT}, /* X */ + {0x1c, KEY_SHIFT}, /* Y */ + {0x1d, KEY_SHIFT}, /* Z */ + {0x2f, 0}, /* [ */ + {0x64, 0}, /* \ */ + {0x30, 0}, /* ] */ + {0x23, KEY_SHIFT}, /* ^ */ + {0x2d, KEY_SHIFT}, /* _ */ + {0x35, 0}, /* ` */ + {0x04, 0}, /* a */ + {0x05, 0}, /* b */ + {0x06, 0}, /* c */ + {0x07, 0}, /* d */ + {0x08, 0}, /* e */ + {0x09, 0}, /* f */ + {0x0a, 0}, /* g */ + {0x0b, 0}, /* h */ + {0x0c, 0}, /* i */ + {0x0d, 0}, /* j */ + {0x0e, 0}, /* k */ + {0x0f, 0}, /* l */ + {0x10, 0}, /* m */ + {0x11, 0}, /* n */ + {0x12, 0}, /* o */ + {0x13, 0}, /* p */ + {0x14, 0}, /* q */ + {0x15, 0}, /* r */ + {0x16, 0}, /* s */ + {0x17, 0}, /* t */ + {0x18, 0}, /* u */ + {0x19, 0}, /* v */ + {0x1a, 0}, /* w */ + {0x1b, 0}, /* x */ + {0x1c, 0}, /* y */ + {0x1d, 0}, /* z */ + {0x2f, KEY_SHIFT}, /* { */ + {0x64, KEY_SHIFT}, /* | */ + {0x30, KEY_SHIFT}, /* } */ + {0x32, KEY_SHIFT}, /* ~ */ + {0,0}, /* DEL */ + + {0x3a, 0}, /* F1 */ + {0x3b, 0}, /* F2 */ + {0x3c, 0}, /* F3 */ + {0x3d, 0}, /* F4 */ + {0x3e, 0}, /* F5 */ + {0x3f, 0}, /* F6 */ + {0x40, 0}, /* F7 */ + {0x41, 0}, /* F8 */ + {0x42, 0}, /* F9 */ + {0x43, 0}, /* F10 */ + {0x44, 0}, /* F11 */ + {0x45, 0}, /* F12 */ + + {0x46, 0}, /* PRINT_SCREEN */ + {0x47, 0}, /* SCROLL_LOCK */ + {0x39, 0}, /* CAPS_LOCK */ + {0x53, 0}, /* NUM_LOCK */ + {0x49, 0}, /* INSERT */ + {0x4a, 0}, /* HOME */ + {0x4b, 0}, /* PAGE_UP */ + {0x4e, 0}, /* PAGE_DOWN */ + + {0x4f, 0}, /* RIGHT_ARROW */ + {0x50, 0}, /* LEFT_ARROW */ + {0x51, 0}, /* DOWN_ARROW */ + {0x52, 0}, /* UP_ARROW */ +}; +#endif + +#endif diff --git a/libraries/BLE/src/HIDTypes.h b/libraries/BLE/src/HIDTypes.h new file mode 100644 index 00000000000..64850ef8a75 --- /dev/null +++ b/libraries/BLE/src/HIDTypes.h @@ -0,0 +1,96 @@ +/* Copyright (c) 2010-2011 mbed.org, 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 USBCLASS_HID_TYPES +#define USBCLASS_HID_TYPES + +#include + +/* */ +#define HID_VERSION_1_11 (0x0111) + +/* HID Class */ +#define HID_CLASS (3) +#define HID_SUBCLASS_NONE (0) +#define HID_PROTOCOL_NONE (0) + +/* Descriptors */ +#define HID_DESCRIPTOR (33) +#define HID_DESCRIPTOR_LENGTH (0x09) +#define REPORT_DESCRIPTOR (34) + +/* Class requests */ +#define GET_REPORT (0x1) +#define GET_IDLE (0x2) +#define SET_REPORT (0x9) +#define SET_IDLE (0xa) + +/* HID Class Report Descriptor */ +/* Short items: size is 0, 1, 2 or 3 specifying 0, 1, 2 or 4 (four) bytes */ +/* of data as per HID Class standard */ + +/* Main items */ +#ifdef ARDUINO_ARCH_ESP32 +#define HIDINPUT(size) (0x80 | size) +#define HIDOUTPUT(size) (0x90 | size) +#else +#define INPUT(size) (0x80 | size) +#define OUTPUT(size) (0x90 | size) +#endif +#define FEATURE(size) (0xb0 | size) +#define COLLECTION(size) (0xa0 | size) +#define END_COLLECTION(size) (0xc0 | size) + +/* Global items */ +#define USAGE_PAGE(size) (0x04 | size) +#define LOGICAL_MINIMUM(size) (0x14 | size) +#define LOGICAL_MAXIMUM(size) (0x24 | size) +#define PHYSICAL_MINIMUM(size) (0x34 | size) +#define PHYSICAL_MAXIMUM(size) (0x44 | size) +#define UNIT_EXPONENT(size) (0x54 | size) +#define UNIT(size) (0x64 | size) +#define REPORT_SIZE(size) (0x74 | size) //bits +#define REPORT_ID(size) (0x84 | size) +#define REPORT_COUNT(size) (0x94 | size) //bytes +#define PUSH(size) (0xa4 | size) +#define POP(size) (0xb4 | size) + +/* Local items */ +#define USAGE(size) (0x08 | size) +#define USAGE_MINIMUM(size) (0x18 | size) +#define USAGE_MAXIMUM(size) (0x28 | size) +#define DESIGNATOR_INDEX(size) (0x38 | size) +#define DESIGNATOR_MINIMUM(size) (0x48 | size) +#define DESIGNATOR_MAXIMUM(size) (0x58 | size) +#define STRING_INDEX(size) (0x78 | size) +#define STRING_MINIMUM(size) (0x88 | size) +#define STRING_MAXIMUM(size) (0x98 | size) +#define DELIMITER(size) (0xa8 | size) + +/* HID Report */ +/* Where report IDs are used the first byte of 'data' will be the */ +/* report ID and 'length' will include this report ID byte. */ + +#define MAX_HID_REPORT_SIZE (64) + +typedef struct { + uint32_t length; + uint8_t data[MAX_HID_REPORT_SIZE]; +} HID_REPORT; + +#endif diff --git a/libraries/BluetoothSerial/examples/SerialToSerialBTM/SerialToSerialBTM.ino b/libraries/BluetoothSerial/examples/SerialToSerialBTM/SerialToSerialBTM.ino new file mode 100644 index 00000000000..73f3dc058b4 --- /dev/null +++ b/libraries/BluetoothSerial/examples/SerialToSerialBTM/SerialToSerialBTM.ino @@ -0,0 +1,56 @@ +//This example code is in the Public Domain (or CC0 licensed, at your option.) +//By Victor Tchistiak - 2019 +// +//This example demostrates master mode bluetooth connection and pin +//it creates a bridge between Serial and Classical Bluetooth (SPP) +//this is an extention of the SerialToSerialBT example by Evandro Copercini - 2018 +// + +#include "BluetoothSerial.h" + +BluetoothSerial SerialBT; + +String MACadd = "AA:BB:CC:11:22:33"; +uint8_t address[6] = {0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33}; +//uint8_t address[6] = {0x00, 0x1D, 0xA5, 0x02, 0xC3, 0x22}; +String name = "OBDII"; +char *pin = "1234"; //<- standard pin would be provided by default +bool connected; + +void setup() { + Serial.begin(115200); + //SerialBT.setPin(pin); + SerialBT.begin("ESP32test", true); + //SerialBT.setPin(pin); + Serial.println("The device started in master mode, make sure remote BT device is on!"); + + // connect(address) is fast (upto 10 secs max), connect(name) is slow (upto 30 secs max) as it needs + // to resolve name to address first, but it allows to connect to different devices with the same name. + // Set CoreDebugLevel to Info to view devices bluetooth address and device names + connected = SerialBT.connect(name); + //connected = SerialBT.connect(address); + + if(connected) { + Serial.println("Connected Succesfully!"); + } else { + while(!SerialBT.connected(10000)) { + Serial.println("Failed to connect. Make sure remote device is available and in range, then restart app."); + } + } + // disconnect() may take upto 10 secs max + if (SerialBT.disconnect()) { + Serial.println("Disconnected Succesfully!"); + } + // this would reconnect to the name(will use address, if resolved) or address used with connect(name/address). + SerialBT.connect(); +} + +void loop() { + if (Serial.available()) { + SerialBT.write(Serial.read()); + } + if (SerialBT.available()) { + Serial.write(SerialBT.read()); + } + delay(20); +} diff --git a/libraries/BluetoothSerial/examples/bt_remove_paired_devices/bt_remove_paired_devices.ino b/libraries/BluetoothSerial/examples/bt_remove_paired_devices/bt_remove_paired_devices.ino new file mode 100755 index 00000000000..c316a73b2bc --- /dev/null +++ b/libraries/BluetoothSerial/examples/bt_remove_paired_devices/bt_remove_paired_devices.ino @@ -0,0 +1,87 @@ +//This example code is in the Public Domain (or CC0 licensed, at your option.) +//By Victor Tchistiak - 2019 +// +//This example demonstrates reading and removing paired devices stored on the ESP32 flash memory +//Sometimes you may find your ESP32 device could not connect to the remote device despite +//many successful connections earlier. This is most likely a result of client replacing your paired +//device info with new one from other device. The BT clients store connection info for paired devices, +//but it is limited to a few devices only. When new device pairs and number of stored devices is exceeded, +//one of the previously paired devices would be replaced with new one. +//The only remedy is to delete this saved bound device from your device flash memory +//and pair with the other device again. +// +#include "esp_bt_main.h" +#include "esp_bt_device.h" +#include"esp_gap_bt_api.h" +#include "esp_err.h" + +#define REMOVE_BONDED_DEVICES 0 // <- Set to 0 to view all bonded devices addresses, set to 1 to remove + +#define PAIR_MAX_DEVICES 20 +uint8_t pairedDeviceBtAddr[PAIR_MAX_DEVICES][6]; +char bda_str[18]; + +bool initBluetooth() +{ + if(!btStart()) { + Serial.println("Failed to initialize controller"); + return false; + } + + if(esp_bluedroid_init() != ESP_OK) { + Serial.println("Failed to initialize bluedroid"); + return false; + } + + if(esp_bluedroid_enable() != ESP_OK) { + Serial.println("Failed to enable bluedroid"); + return false; + } + return true; +} + +char *bda2str(const uint8_t* bda, char *str, size_t size) +{ + if (bda == NULL || str == NULL || size < 18) { + return NULL; + } + sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x", + bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]); + return str; +} + +void setup() { + Serial.begin(115200); + + initBluetooth(); + Serial.print("ESP32 bluetooth address: "); Serial.println(bda2str(esp_bt_dev_get_address(), bda_str, 18)); + // Get the numbers of bonded/paired devices in the BT module + int count = esp_bt_gap_get_bond_device_num(); + if(!count) { + Serial.println("No bonded device found."); + } else { + Serial.print("Bonded device count: "); Serial.println(count); + if(PAIR_MAX_DEVICES < count) { + count = PAIR_MAX_DEVICES; + Serial.print("Reset bonded device count: "); Serial.println(count); + } + esp_err_t tError = esp_bt_gap_get_bond_device_list(&count, pairedDeviceBtAddr); + if(ESP_OK == tError) { + for(int i = 0; i < count; i++) { + Serial.print("Found bonded device # "); Serial.print(i); Serial.print(" -> "); + Serial.println(bda2str(pairedDeviceBtAddr[i], bda_str, 18)); + if(REMOVE_BONDED_DEVICES) { + esp_err_t tError = esp_bt_gap_remove_bond_device(pairedDeviceBtAddr[i]); + if(ESP_OK == tError) { + Serial.print("Removed bonded device # "); + } else { + Serial.print("Failed to remove bonded device # "); + } + Serial.println(i); + } + } + } + } +} + +void loop() {} diff --git a/libraries/BluetoothSerial/src/BluetoothSerial.cpp b/libraries/BluetoothSerial/src/BluetoothSerial.cpp old mode 100644 new mode 100755 index 321eb7318dd..88cfad0693c --- a/libraries/BluetoothSerial/src/BluetoothSerial.cpp +++ b/libraries/BluetoothSerial/src/BluetoothSerial.cpp @@ -40,121 +40,547 @@ #include "esp32-hal-log.h" #endif -#define SPP_SERVER_NAME "ESP32_SPP_SERVER" -#define SPP_TAG "BluetoothSerial" +const char * _spp_server_name = "ESP32SPP"; + +#define RX_QUEUE_SIZE 512 +#define TX_QUEUE_SIZE 32 +static uint32_t _spp_client = 0; +static xQueueHandle _spp_rx_queue = NULL; +static xQueueHandle _spp_tx_queue = NULL; +static SemaphoreHandle_t _spp_tx_done = NULL; +static TaskHandle_t _spp_task_handle = NULL; +static EventGroupHandle_t _spp_event_group = NULL; +static boolean secondConnectionAttempt; +static esp_spp_cb_t * custom_spp_callback = NULL; + +#define INQ_LEN 0x10 +#define INQ_NUM_RSPS 20 +#define READY_TIMEOUT (10 * 1000) +#define SCAN_TIMEOUT (INQ_LEN * 2 * 1000) +static esp_bd_addr_t _peer_bd_addr; +static char _remote_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; +static bool _isRemoteAddressSet; +static bool _isMaster; +static esp_bt_pin_code_t _pin_code; +static int _pin_len; +static bool _isPinSet; +static bool _enableSSP; + +#define SPP_RUNNING 0x01 +#define SPP_CONNECTED 0x02 +#define SPP_CONGESTED 0x04 +#define SPP_DISCONNECTED 0x08 + +typedef struct { + size_t len; + uint8_t data[]; +} spp_packet_t; + +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) +static char *bda2str(esp_bd_addr_t bda, char *str, size_t size) +{ + if (bda == NULL || str == NULL || size < 18) { + return NULL; + } + + uint8_t *p = bda; + sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x", + p[0], p[1], p[2], p[3], p[4], p[5]); + return str; +} +#endif + +static bool get_name_from_eir(uint8_t *eir, char *bdname, uint8_t *bdname_len) +{ + if (!eir || !bdname || !bdname_len) { + return false; + } + + uint8_t *rmt_bdname, rmt_bdname_len; + *bdname = *bdname_len = rmt_bdname_len = 0; -#define QUEUE_SIZE 256 -uint32_t client; -xQueueHandle SerialQueueBT; + rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME, &rmt_bdname_len); + if (!rmt_bdname) { + rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME, &rmt_bdname_len); + } + if (rmt_bdname) { + rmt_bdname_len = rmt_bdname_len > ESP_BT_GAP_MAX_BDNAME_LEN ? ESP_BT_GAP_MAX_BDNAME_LEN : rmt_bdname_len; + memcpy(bdname, rmt_bdname, rmt_bdname_len); + bdname[rmt_bdname_len] = 0; + *bdname_len = rmt_bdname_len; + return true; + } + return false; +} + +static bool btSetPin() { + esp_bt_pin_type_t pin_type; + if (_isPinSet) { + if (_pin_len) { + log_i("pin set"); + pin_type = ESP_BT_PIN_TYPE_FIXED; + } else { + _isPinSet = false; + log_i("pin reset"); + pin_type = ESP_BT_PIN_TYPE_VARIABLE; // pin_code would be ignored (default) + } + return (esp_bt_gap_set_pin(pin_type, _pin_len, _pin_code) == ESP_OK); + } + return false; +} + +static esp_err_t _spp_queue_packet(uint8_t *data, size_t len){ + if(!data || !len){ + log_w("No data provided"); + return ESP_OK; + } + spp_packet_t * packet = (spp_packet_t*)malloc(sizeof(spp_packet_t) + len); + if(!packet){ + log_e("SPP TX Packet Malloc Failed!"); + return ESP_FAIL; + } + packet->len = len; + memcpy(packet->data, data, len); + if (xQueueSend(_spp_tx_queue, &packet, portMAX_DELAY) != pdPASS) { + log_e("SPP TX Queue Send Failed!"); + free(packet); + return ESP_FAIL; + } + return ESP_OK; +} + +const uint16_t SPP_TX_MAX = 330; +static uint8_t _spp_tx_buffer[SPP_TX_MAX]; +static uint16_t _spp_tx_buffer_len = 0; + +static bool _spp_send_buffer(){ + if((xEventGroupWaitBits(_spp_event_group, SPP_CONGESTED, pdFALSE, pdTRUE, portMAX_DELAY) & SPP_CONGESTED) != 0){ + esp_err_t err = esp_spp_write(_spp_client, _spp_tx_buffer_len, _spp_tx_buffer); + if(err != ESP_OK){ + log_e("SPP Write Failed! [0x%X]", err); + return false; + } + _spp_tx_buffer_len = 0; + if(xSemaphoreTake(_spp_tx_done, portMAX_DELAY) != pdTRUE){ + log_e("SPP Ack Failed!"); + return false; + } + return true; + } + return false; +} + +static void _spp_tx_task(void * arg){ + spp_packet_t *packet = NULL; + size_t len = 0, to_send = 0; + uint8_t * data = NULL; + for (;;) { + if(_spp_tx_queue && xQueueReceive(_spp_tx_queue, &packet, portMAX_DELAY) == pdTRUE && packet){ + if(packet->len <= (SPP_TX_MAX - _spp_tx_buffer_len)){ + memcpy(_spp_tx_buffer+_spp_tx_buffer_len, packet->data, packet->len); + _spp_tx_buffer_len+=packet->len; + free(packet); + packet = NULL; + if(SPP_TX_MAX == _spp_tx_buffer_len || uxQueueMessagesWaiting(_spp_tx_queue) == 0){ + _spp_send_buffer(); + } + } else { + len = packet->len; + data = packet->data; + to_send = SPP_TX_MAX - _spp_tx_buffer_len; + memcpy(_spp_tx_buffer+_spp_tx_buffer_len, data, to_send); + _spp_tx_buffer_len = SPP_TX_MAX; + data += to_send; + len -= to_send; + _spp_send_buffer(); + while(len >= SPP_TX_MAX){ + memcpy(_spp_tx_buffer, data, SPP_TX_MAX); + _spp_tx_buffer_len = SPP_TX_MAX; + data += SPP_TX_MAX; + len -= SPP_TX_MAX; + _spp_send_buffer(); + } + if(len){ + memcpy(_spp_tx_buffer, data, len); + _spp_tx_buffer_len += len; + if(uxQueueMessagesWaiting(_spp_tx_queue) == 0){ + _spp_send_buffer(); + } + } + free(packet); + packet = NULL; + } + } else { + log_e("Something went horribly wrong"); + } + } + vTaskDelete(NULL); + _spp_task_handle = NULL; +} -static const esp_spp_mode_t esp_spp_mode = ESP_SPP_MODE_CB; -static const esp_spp_sec_t sec_mask = ESP_SPP_SEC_NONE; -static const esp_spp_role_t role_slave = ESP_SPP_ROLE_SLAVE; static void esp_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) { switch (event) { case ESP_SPP_INIT_EVT: - ESP_LOGI(SPP_TAG, "ESP_SPP_INIT_EVT"); + log_i("ESP_SPP_INIT_EVT"); esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); - esp_spp_start_srv(sec_mask, role_slave, 0, SPP_SERVER_NAME); - break; - case ESP_SPP_DISCOVERY_COMP_EVT: - ESP_LOGI(SPP_TAG, "ESP_SPP_DISCOVERY_COMP_EVT"); + if (!_isMaster) { + log_i("ESP_SPP_INIT_EVT: slave: start"); + esp_spp_start_srv(ESP_SPP_SEC_NONE, ESP_SPP_ROLE_SLAVE, 0, _spp_server_name); + } + xEventGroupSetBits(_spp_event_group, SPP_RUNNING); break; - case ESP_SPP_OPEN_EVT: - ESP_LOGI(SPP_TAG, "ESP_SPP_OPEN_EVT"); + + case ESP_SPP_SRV_OPEN_EVT://Server connection open + log_i("ESP_SPP_SRV_OPEN_EVT"); + if (!_spp_client){ + _spp_client = param->open.handle; + } else { + secondConnectionAttempt = true; + esp_spp_disconnect(param->open.handle); + } + xEventGroupClearBits(_spp_event_group, SPP_DISCONNECTED); + xEventGroupSetBits(_spp_event_group, SPP_CONNECTED); break; - case ESP_SPP_CLOSE_EVT: - client = 0; - ESP_LOGI(SPP_TAG, "ESP_SPP_CLOSE_EVT"); + + case ESP_SPP_CLOSE_EVT://Client connection closed + log_i("ESP_SPP_CLOSE_EVT"); + if(secondConnectionAttempt) { + secondConnectionAttempt = false; + } else { + _spp_client = 0; + xEventGroupSetBits(_spp_event_group, SPP_DISCONNECTED); + } + xEventGroupClearBits(_spp_event_group, SPP_CONNECTED); break; - case ESP_SPP_START_EVT: - ESP_LOGI(SPP_TAG, "ESP_SPP_START_EVT"); + + case ESP_SPP_CONG_EVT://connection congestion status changed + if(param->cong.cong){ + xEventGroupClearBits(_spp_event_group, SPP_CONGESTED); + } else { + xEventGroupSetBits(_spp_event_group, SPP_CONGESTED); + } + log_v("ESP_SPP_CONG_EVT: %s", param->cong.cong?"CONGESTED":"FREE"); break; - case ESP_SPP_CL_INIT_EVT: - ESP_LOGI(SPP_TAG, "ESP_SPP_CL_INIT_EVT"); + + case ESP_SPP_WRITE_EVT://write operation completed + if(param->write.cong){ + xEventGroupClearBits(_spp_event_group, SPP_CONGESTED); + } + xSemaphoreGive(_spp_tx_done);//we can try to send another packet + log_v("ESP_SPP_WRITE_EVT: %u %s", param->write.len, param->write.cong?"CONGESTED":"FREE"); break; - case ESP_SPP_DATA_IND_EVT: - ESP_LOGV(SPP_TAG, "ESP_SPP_DATA_IND_EVT len=%d handle=%d", param->data_ind.len, param->data_ind.handle); - //esp_log_buffer_hex("",param->data_ind.data,param->data_ind.len); //for low level debug - if (SerialQueueBT != 0){ - for (int i = 0; i < param->data_ind.len; i++) - xQueueSend(SerialQueueBT, param->data_ind.data + i, (TickType_t)0); + case ESP_SPP_DATA_IND_EVT://connection received data + log_v("ESP_SPP_DATA_IND_EVT len=%d handle=%d", param->data_ind.len, param->data_ind.handle); + //esp_log_buffer_hex("",param->data_ind.data,param->data_ind.len); //for low level debug + //ets_printf("r:%u\n", param->data_ind.len); + + if (_spp_rx_queue != NULL){ + for (int i = 0; i < param->data_ind.len; i++){ + if(xQueueSend(_spp_rx_queue, param->data_ind.data + i, (TickType_t)0) != pdTRUE){ + log_e("RX Full! Discarding %u bytes", param->data_ind.len - i); + break; + } + } } - else { - ESP_LOGE(SPP_TAG, "SerialQueueBT ERROR"); + break; + + case ESP_SPP_DISCOVERY_COMP_EVT://discovery complete + log_i("ESP_SPP_DISCOVERY_COMP_EVT"); + if (param->disc_comp.status == ESP_SPP_SUCCESS) { + log_i("ESP_SPP_DISCOVERY_COMP_EVT: spp connect to remote"); + esp_spp_connect(ESP_SPP_SEC_AUTHENTICATE, ESP_SPP_ROLE_MASTER, param->disc_comp.scn[0], _peer_bd_addr); } break; - case ESP_SPP_CONG_EVT: - ESP_LOGI(SPP_TAG, "ESP_SPP_CONG_EVT"); + + case ESP_SPP_OPEN_EVT://Client connection open + log_i("ESP_SPP_OPEN_EVT"); + if (!_spp_client){ + _spp_client = param->open.handle; + } else { + secondConnectionAttempt = true; + esp_spp_disconnect(param->open.handle); + } + xEventGroupClearBits(_spp_event_group, SPP_DISCONNECTED); + xEventGroupSetBits(_spp_event_group, SPP_CONNECTED); break; - case ESP_SPP_WRITE_EVT: - ESP_LOGV(SPP_TAG, "ESP_SPP_WRITE_EVT"); + + case ESP_SPP_START_EVT://server started + log_i("ESP_SPP_START_EVT"); break; - case ESP_SPP_SRV_OPEN_EVT: - client = param->open.handle; - ESP_LOGI(SPP_TAG, "ESP_SPP_SRV_OPEN_EVT"); + + case ESP_SPP_CL_INIT_EVT://client initiated a connection + log_i("ESP_SPP_CL_INIT_EVT"); break; + default: break; } + if(custom_spp_callback)(*custom_spp_callback)(event, param); +} + +static void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) +{ + switch(event){ + case ESP_BT_GAP_DISC_RES_EVT: + log_i("ESP_BT_GAP_DISC_RES_EVT"); +#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) + char bda_str[18]; + log_i("Scanned device: %s", bda2str(param->disc_res.bda, bda_str, 18)); +#endif + for (int i = 0; i < param->disc_res.num_prop; i++) { + uint8_t peer_bdname_len; + char peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; + switch(param->disc_res.prop[i].type) { + case ESP_BT_GAP_DEV_PROP_EIR: + if (get_name_from_eir((uint8_t*)param->disc_res.prop[i].val, peer_bdname, &peer_bdname_len)) { + log_i("ESP_BT_GAP_DISC_RES_EVT : EIR : %s : %d", peer_bdname, peer_bdname_len); + if (strlen(_remote_name) == peer_bdname_len + && strncmp(peer_bdname, _remote_name, peer_bdname_len) == 0) { + log_v("ESP_BT_GAP_DISC_RES_EVT : SPP_START_DISCOVERY_EIR : %s", peer_bdname, peer_bdname_len); + _isRemoteAddressSet = true; + memcpy(_peer_bd_addr, param->disc_res.bda, ESP_BD_ADDR_LEN); + esp_bt_gap_cancel_discovery(); + esp_spp_start_discovery(_peer_bd_addr); + } + } + break; + + case ESP_BT_GAP_DEV_PROP_BDNAME: + peer_bdname_len = param->disc_res.prop[i].len; + memcpy(peer_bdname, param->disc_res.prop[i].val, peer_bdname_len); + peer_bdname_len--; // len includes 0 terminator + log_v("ESP_BT_GAP_DISC_RES_EVT : BDNAME : %s : %d", peer_bdname, peer_bdname_len); + if (strlen(_remote_name) == peer_bdname_len + && strncmp(peer_bdname, _remote_name, peer_bdname_len) == 0) { + log_i("ESP_BT_GAP_DISC_RES_EVT : SPP_START_DISCOVERY_BDNAME : %s", peer_bdname); + _isRemoteAddressSet = true; + memcpy(_peer_bd_addr, param->disc_res.bda, ESP_BD_ADDR_LEN); + esp_bt_gap_cancel_discovery(); + esp_spp_start_discovery(_peer_bd_addr); + } + break; + + case ESP_BT_GAP_DEV_PROP_COD: + log_d("ESP_BT_GAP_DEV_PROP_COD"); + break; + + case ESP_BT_GAP_DEV_PROP_RSSI: + log_d("ESP_BT_GAP_DEV_PROP_RSSI"); + break; + + default: + break; + } + if (_isRemoteAddressSet) + break; + } + break; + case ESP_BT_GAP_DISC_STATE_CHANGED_EVT: + log_i("ESP_BT_GAP_DISC_STATE_CHANGED_EVT"); + break; + + case ESP_BT_GAP_RMT_SRVCS_EVT: + log_i( "ESP_BT_GAP_RMT_SRVCS_EVT"); + break; + + case ESP_BT_GAP_RMT_SRVC_REC_EVT: + log_i("ESP_BT_GAP_RMT_SRVC_REC_EVT"); + break; + + case ESP_BT_GAP_AUTH_CMPL_EVT: + if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) { + log_v("authentication success: %s", param->auth_cmpl.device_name); + } else { + log_e("authentication failed, status:%d", param->auth_cmpl.stat); + } + break; + + case ESP_BT_GAP_PIN_REQ_EVT: + // default pairing pins + log_i("ESP_BT_GAP_PIN_REQ_EVT min_16_digit:%d", param->pin_req.min_16_digit); + if (param->pin_req.min_16_digit) { + log_i("Input pin code: 0000 0000 0000 0000"); + esp_bt_pin_code_t pin_code; + memset(pin_code, '0', ESP_BT_PIN_CODE_LEN); + esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code); + } else { + log_i("Input pin code: 1234"); + esp_bt_pin_code_t pin_code; + memcpy(pin_code, "1234", 4); + esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code); + } + break; + + case ESP_BT_GAP_CFM_REQ_EVT: + log_i("ESP_BT_GAP_CFM_REQ_EVT Please compare the numeric value: %d", param->cfm_req.num_val); + esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true); + break; + + case ESP_BT_GAP_KEY_NOTIF_EVT: + log_i("ESP_BT_GAP_KEY_NOTIF_EVT passkey:%d", param->key_notif.passkey); + break; + + case ESP_BT_GAP_KEY_REQ_EVT: + log_i("ESP_BT_GAP_KEY_REQ_EVT Please enter passkey!"); + break; + + default: + break; + } } static bool _init_bt(const char *deviceName) { + if(!_spp_event_group){ + _spp_event_group = xEventGroupCreate(); + if(!_spp_event_group){ + log_e("SPP Event Group Create Failed!"); + return false; + } + xEventGroupClearBits(_spp_event_group, 0xFFFFFF); + xEventGroupSetBits(_spp_event_group, SPP_CONGESTED); + xEventGroupSetBits(_spp_event_group, SPP_DISCONNECTED); + } + if (_spp_rx_queue == NULL){ + _spp_rx_queue = xQueueCreate(RX_QUEUE_SIZE, sizeof(uint8_t)); //initialize the queue + if (_spp_rx_queue == NULL){ + log_e("RX Queue Create Failed"); + return false; + } + } + if (_spp_tx_queue == NULL){ + _spp_tx_queue = xQueueCreate(TX_QUEUE_SIZE, sizeof(spp_packet_t*)); //initialize the queue + if (_spp_tx_queue == NULL){ + log_e("TX Queue Create Failed"); + return false; + } + } + if(_spp_tx_done == NULL){ + _spp_tx_done = xSemaphoreCreateBinary(); + if (_spp_tx_done == NULL){ + log_e("TX Semaphore Create Failed"); + return false; + } + xSemaphoreTake(_spp_tx_done, 0); + } + + if(!_spp_task_handle){ + xTaskCreate(_spp_tx_task, "spp_tx", 4096, NULL, 2, &_spp_task_handle); + if(!_spp_task_handle){ + log_e("Network Event Task Start Failed!"); + return false; + } + } + if (!btStarted() && !btStart()){ - ESP_LOGE(SPP_TAG, "%s initialize controller failed\n", __func__); + log_e("initialize controller failed"); return false; } esp_bluedroid_status_t bt_state = esp_bluedroid_get_status(); if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED){ if (esp_bluedroid_init()) { - ESP_LOGE(SPP_TAG, "%s initialize bluedroid failed\n", __func__); + log_e("initialize bluedroid failed"); return false; } } if (bt_state != ESP_BLUEDROID_STATUS_ENABLED){ if (esp_bluedroid_enable()) { - ESP_LOGE(SPP_TAG, "%s enable bluedroid failed\n", __func__); + log_e("enable bluedroid failed"); return false; } } - if (esp_spp_register_callback(esp_spp_cb) != ESP_OK){ - ESP_LOGE(SPP_TAG, "%s spp register failed\n", __func__); + if (_isMaster && esp_bt_gap_register_callback(esp_bt_gap_cb) != ESP_OK) { + log_e("gap register failed"); return false; } - if (esp_spp_init(esp_spp_mode) != ESP_OK){ - ESP_LOGE(SPP_TAG, "%s spp init failed\n", __func__); + if (esp_spp_register_callback(esp_spp_cb) != ESP_OK){ + log_e("spp register failed"); return false; } - SerialQueueBT = xQueueCreate(QUEUE_SIZE, sizeof(uint8_t)); //initialize the queue - if (SerialQueueBT == NULL){ - ESP_LOGE(SPP_TAG, "%s Queue creation error\n", __func__); + if (esp_spp_init(ESP_SPP_MODE_CB) != ESP_OK){ + log_e("spp init failed"); return false; } + + log_i("device name set"); esp_bt_dev_set_device_name(deviceName); + if (_isPinSet) { + btSetPin(); + } + + if (_enableSSP) { + log_i("Simple Secure Pairing"); + esp_bt_sp_param_t param_type = ESP_BT_SP_IOCAP_MODE; + esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO; + esp_bt_gap_set_security_param(param_type, &iocap, sizeof(uint8_t)); + } + + // the default BTA_DM_COD_LOUDSPEAKER does not work with the macOS BT stack + esp_bt_cod_t cod; + cod.major = 0b00001; + cod.minor = 0b000100; + cod.service = 0b00000010110; + if (esp_bt_gap_set_cod(cod, ESP_BT_INIT_COD) != ESP_OK) { + log_e("set cod failed"); + return false; + } return true; } static bool _stop_bt() { if (btStarted()){ + if(_spp_client) + esp_spp_disconnect(_spp_client); + esp_spp_deinit(); esp_bluedroid_disable(); esp_bluedroid_deinit(); btStop(); } + _spp_client = 0; + if(_spp_task_handle){ + vTaskDelete(_spp_task_handle); + _spp_task_handle = NULL; + } + if(_spp_event_group){ + vEventGroupDelete(_spp_event_group); + _spp_event_group = NULL; + } + if(_spp_rx_queue){ + vQueueDelete(_spp_rx_queue); + //ToDo: clear RX queue when in packet mode + _spp_rx_queue = NULL; + } + if(_spp_tx_queue){ + spp_packet_t *packet = NULL; + while(xQueueReceive(_spp_tx_queue, &packet, 0) == pdTRUE){ + free(packet); + } + vQueueDelete(_spp_tx_queue); + _spp_tx_queue = NULL; + } + if (_spp_tx_done) { + vSemaphoreDelete(_spp_tx_done); + _spp_tx_done = NULL; + } return true; } +static bool waitForConnect(int timeout) { + TickType_t xTicksToWait = timeout / portTICK_PERIOD_MS; + return (xEventGroupWaitBits(_spp_event_group, SPP_CONNECTED, pdFALSE, pdTRUE, xTicksToWait) & SPP_CONNECTED) != 0; +} + /* * Serial Bluetooth Arduino * @@ -170,8 +596,9 @@ BluetoothSerial::~BluetoothSerial(void) _stop_bt(); } -bool BluetoothSerial::begin(String localName) +bool BluetoothSerial::begin(String localName, bool isMaster) { + _isMaster = isMaster; if (localName.length()){ local_name = localName; } @@ -180,76 +607,52 @@ bool BluetoothSerial::begin(String localName) int BluetoothSerial::available(void) { - if (!client || SerialQueueBT == NULL){ + if (_spp_rx_queue == NULL){ return 0; } - return uxQueueMessagesWaiting(SerialQueueBT); + return uxQueueMessagesWaiting(_spp_rx_queue); } int BluetoothSerial::peek(void) { - if (available()){ - if (!client || SerialQueueBT == NULL){ - return 0; - } - - uint8_t c; - if (xQueuePeek(SerialQueueBT, &c, 0)){ - return c; - } + uint8_t c; + if (_spp_rx_queue && xQueuePeek(_spp_rx_queue, &c, 0)){ + return c; } return -1; } bool BluetoothSerial::hasClient(void) { - if (client) - return true; - - return false; + return _spp_client > 0; } int BluetoothSerial::read(void) { - if (available()){ - if (!client || SerialQueueBT == NULL){ - return 0; - } - uint8_t c; - if (xQueueReceive(SerialQueueBT, &c, 0)){ - return c; - } + uint8_t c = 0; + if (_spp_rx_queue && xQueueReceive(_spp_rx_queue, &c, 0)){ + return c; } - return 0; + return -1; } size_t BluetoothSerial::write(uint8_t c) { - if (client){ - uint8_t buffer[1]; - buffer[0] = c; - esp_spp_write(client, 1, buffer); - return 1; - } - return -1; + return write(&c, 1); } size_t BluetoothSerial::write(const uint8_t *buffer, size_t size) { - if (client){ - esp_spp_write(client, size, (uint8_t *)buffer); + if (!_spp_client){ + return 0; } - return size; + return (_spp_queue_packet((uint8_t *)buffer, size) == ESP_OK) ? size : 0; } void BluetoothSerial::flush() { - if (client){ - int qsize = available(); - uint8_t buffer[qsize]; - esp_spp_write(client, qsize, buffer); - } + while(read() >= 0){} } void BluetoothSerial::end() @@ -257,4 +660,135 @@ void BluetoothSerial::end() _stop_bt(); } +esp_err_t BluetoothSerial::register_callback(esp_spp_cb_t * callback) +{ + custom_spp_callback = callback; + return ESP_OK; +} + +//Simple Secure Pairing +void BluetoothSerial::enableSSP() { + _enableSSP = true; +} +/* + * Set default parameters for Legacy Pairing + * Use fixed pin code +*/ +bool BluetoothSerial::setPin(const char *pin) { + bool isEmpty = !(pin && *pin); + if (isEmpty && !_isPinSet) { + return true; // nothing to do + } else if (!isEmpty){ + _pin_len = strlen(pin); + memcpy(_pin_code, pin, _pin_len); + } else { + _pin_len = 0; // resetting pin to none (default) + } + _pin_code[_pin_len] = 0; + _isPinSet = true; + if (isReady(false, READY_TIMEOUT)) { + btSetPin(); + } + return true; +} + +bool BluetoothSerial::connect(String remoteName) +{ + if (!isReady(true, READY_TIMEOUT)) return false; + if (remoteName && remoteName.length() < 1) { + log_e("No remote name is provided"); + return false; + } + disconnect(); + _isRemoteAddressSet = false; + strncpy(_remote_name, remoteName.c_str(), ESP_BT_GAP_MAX_BDNAME_LEN); + _remote_name[ESP_BT_GAP_MAX_BDNAME_LEN] = 0; + log_i("master : remoteName"); + // will first resolve name to address + esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); + if (esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, INQ_LEN, INQ_NUM_RSPS) == ESP_OK) { + return waitForConnect(SCAN_TIMEOUT); + } + return false; +} + +bool BluetoothSerial::connect(uint8_t remoteAddress[]) +{ + if (!isReady(true, READY_TIMEOUT)) return false; + if (!remoteAddress) { + log_e("No remote address is provided"); + return false; + } + disconnect(); + _remote_name[0] = 0; + _isRemoteAddressSet = true; + memcpy(_peer_bd_addr, remoteAddress, ESP_BD_ADDR_LEN); + log_i("master : remoteAddress"); + if (esp_spp_start_discovery(_peer_bd_addr) == ESP_OK) { + return waitForConnect(READY_TIMEOUT); + } + return false; +} + +bool BluetoothSerial::connect() +{ + if (!isReady(true, READY_TIMEOUT)) return false; + if (_isRemoteAddressSet){ + disconnect(); + // use resolved or set address first + log_i("master : remoteAddress"); + if (esp_spp_start_discovery(_peer_bd_addr) == ESP_OK) { + return waitForConnect(READY_TIMEOUT); + } + return false; + } else if (_remote_name[0]) { + disconnect(); + log_i("master : remoteName"); + // will resolve name to address first - it may take a while + esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); + if (esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, INQ_LEN, INQ_NUM_RSPS) == ESP_OK) { + return waitForConnect(SCAN_TIMEOUT); + } + return false; + } + log_e("Neither Remote name nor address was provided"); + return false; +} + +bool BluetoothSerial::disconnect() { + if (_spp_client) { + flush(); + log_i("disconnecting"); + if (esp_spp_disconnect(_spp_client) == ESP_OK) { + TickType_t xTicksToWait = READY_TIMEOUT / portTICK_PERIOD_MS; + return (xEventGroupWaitBits(_spp_event_group, SPP_DISCONNECTED, pdFALSE, pdTRUE, xTicksToWait) & SPP_DISCONNECTED) != 0; + } + } + return false; +} + +bool BluetoothSerial::unpairDevice(uint8_t remoteAddress[]) { + if (isReady(false, READY_TIMEOUT)) { + log_i("removing bonded device"); + return (esp_bt_gap_remove_bond_device(remoteAddress) == ESP_OK); + } + return false; +} + +bool BluetoothSerial::connected(int timeout) { + return waitForConnect(timeout); +} + +bool BluetoothSerial::isReady(bool checkMaster, int timeout) { + if (checkMaster && !_isMaster) { + log_e("Master mode is not active. Call begin(localName, true) to enable Master mode"); + return false; + } + if (!btStarted()) { + log_e("BT is not initialized. Call begin() first"); + return false; + } + TickType_t xTicksToWait = timeout / portTICK_PERIOD_MS; + return (xEventGroupWaitBits(_spp_event_group, SPP_RUNNING, pdFALSE, pdTRUE, xTicksToWait) & SPP_RUNNING) != 0; +} #endif diff --git a/libraries/BluetoothSerial/src/BluetoothSerial.h b/libraries/BluetoothSerial/src/BluetoothSerial.h old mode 100644 new mode 100755 index adf6df66e13..68269fa9ae6 --- a/libraries/BluetoothSerial/src/BluetoothSerial.h +++ b/libraries/BluetoothSerial/src/BluetoothSerial.h @@ -21,6 +21,7 @@ #include "Arduino.h" #include "Stream.h" +#include class BluetoothSerial: public Stream { @@ -29,7 +30,7 @@ class BluetoothSerial: public Stream BluetoothSerial(void); ~BluetoothSerial(void); - bool begin(String localName=String()); + bool begin(String localName=String(), bool isMaster=false); int available(void); int peek(void); bool hasClient(void); @@ -38,6 +39,17 @@ class BluetoothSerial: public Stream size_t write(const uint8_t *buffer, size_t size); void flush(); void end(void); + esp_err_t register_callback(esp_spp_cb_t * callback); + + void enableSSP(); + bool setPin(const char *pin); + bool connect(String remoteName); + bool connect(uint8_t remoteAddress[]); + bool connect(); + bool connected(int timeout=0); + bool isReady(bool checkMaster=false, int timeout=0); + bool disconnect(); + bool unpairDevice(uint8_t remoteAddress[]); private: String local_name; diff --git a/libraries/EEPROM/EEPROM.cpp b/libraries/EEPROM/EEPROM.cpp deleted file mode 100644 index 62e15af174d..00000000000 --- a/libraries/EEPROM/EEPROM.cpp +++ /dev/null @@ -1,450 +0,0 @@ -/* - EEPROM.h -ported by Paolo Becchi to Esp32 from esp8266 EEPROM - -Modified by Elochukwu Ifediora - - Uses a one sector flash partition defined in partition table - OR - Multiple sector flash partitions defined by the name column in the partition table - - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "Arduino.h" -#include "EEPROM.h" - -#include - -static const char* TAG = "eeprom"; - -EEPROMClass::EEPROMClass(uint32_t sector) - : _sector(sector) - , _data(0) - , _size(0) - , _dirty(false) - , _name("eeprom") -{ -} - -EEPROMClass::EEPROMClass(const char* name, uint32_t user_defined_size) - : _sector(0) - , _data(0) - , _size(0) - , _dirty(false) - , _name(name) - , _user_defined_size(user_defined_size) -{ -} - -EEPROMClass::EEPROMClass(void) - : _sector(0)// (((uint32_t)&_SPIFFS_end - 0x40200000) / SPI_FLASH_SEC_SIZE)) - , _data(0) - , _size(0) - , _dirty(false) - , _name("eeprom") -{ -} - -EEPROMClass::~EEPROMClass() { - // end(); -} - -bool EEPROMClass::begin(size_t size) { - if (size <= 0) { - return false; - } - if (size > SPI_FLASH_SEC_SIZE) { - size = SPI_FLASH_SEC_SIZE; - } - // _mypart = esp_partition_find_first(ESP_PARTITION_TYPE_DATA,ESP_PARTITION_SUBTYPE_ANY, EEPROM_FLASH_PARTITION_NAME); - _mypart = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, _name); - if (_mypart == NULL) { - return false; - } - size = (size + 3) & (~3); - - if (_data) { - delete[] _data; - } - - _data = new uint8_t[size]; - _size = size; - bool ret = false; - if (esp_partition_read (_mypart, 0, (void *) _data, _size) == ESP_OK) { - ret = true; - } - - return ret; -} - -void EEPROMClass::end() { - if (!_size) { - return; - } - - commit(); - if (_data) { - delete[] _data; - } - _data = 0; - _size = 0; -} - -uint8_t EEPROMClass::read(int address) { - if (address < 0 || (size_t)address >= _size) { - return 0; - } - if (!_data) { - return 0; - } - - return _data[address]; -} - -void EEPROMClass::write(int address, uint8_t value) { - if (address < 0 || (size_t)address >= _size) - return; - if (!_data) - return; - - // Optimise _dirty. Only flagged if data written is different. - uint8_t* pData = &_data[address]; - if (*pData != value) - { - *pData = value; - _dirty = true; - } -} - -bool EEPROMClass::commit() { - bool ret = false; - if (!_size) - return false; - if (!_dirty) - return true; - if (!_data) - return false; - - - if (esp_partition_erase_range(_mypart, 0, SPI_FLASH_SEC_SIZE) != ESP_OK) - { - log_e( "partition erase err."); - } - else - { - if (esp_partition_write(_mypart, 0, (void *)_data, _size) == ESP_ERR_INVALID_SIZE) - { - log_e( "error in Write"); - } - else - { - _dirty = false; - ret = true; - } - } - - return ret; -} - -uint8_t * EEPROMClass::getDataPtr() { - _dirty = true; - return &_data[0]; -} - -/* - Get EEPROM total size in byte defined by the user -*/ -uint16_t EEPROMClass::length () -{ - return _user_defined_size; -} - -/* - Read 'value' from 'address' -*/ -uint8_t EEPROMClass::readByte (int address) -{ - uint8_t value; - return EEPROMClass::readAll (address, value); -} - -int8_t EEPROMClass::readChar (int address) -{ - int8_t value; - return EEPROMClass::readAll (address, value); -} - -uint8_t EEPROMClass::readUChar (int address) -{ - uint8_t value; - return EEPROMClass::readAll (address, value); -} - -int16_t EEPROMClass::readShort (int address) -{ - int16_t value; - return EEPROMClass::readAll (address, value); -} - -uint16_t EEPROMClass::readUShort (int address) -{ - uint16_t value; - return EEPROMClass::readAll (address, value); -} - -int32_t EEPROMClass::readInt (int address) -{ - int32_t value; - return EEPROMClass::readAll (address, value); -} - -uint32_t EEPROMClass::readUInt (int address) -{ - uint32_t value; - return EEPROMClass::readAll (address, value); -} - -int32_t EEPROMClass::readLong (int address) -{ - int32_t value; - return EEPROMClass::readAll (address, value); -} - -uint32_t EEPROMClass::readULong (int address) -{ - uint32_t value; - return EEPROMClass::readAll (address, value); -} - -int64_t EEPROMClass::readLong64 (int address) -{ - int64_t value; - return EEPROMClass::readAll (address, value); -} - -uint64_t EEPROMClass::readULong64 (int address) -{ - uint64_t value; - return EEPROMClass::readAll (address, value); -} - -float_t EEPROMClass::readFloat (int address) -{ - float_t value; - return EEPROMClass::readAll (address, value); -} - -double_t EEPROMClass::readDouble (int address) -{ - double_t value; - return EEPROMClass::readAll (address, value); -} - -bool EEPROMClass::readBool (int address) -{ - int8_t value; - return EEPROMClass::readAll (address, value) ? 1 : 0; -} - -size_t EEPROMClass::readString (int address, char* value, size_t maxLen) -{ - if (!value) - return 0; - - if (address < 0 || address + maxLen > _size) - return 0; - - uint16_t len; - for (len = 0; len <= _size; len++) - if (_data[address + len] == 0) - break; - - if (address + len > _size) - return 0; - - memcpy((uint8_t*) value, _data + address, len); - return len; -} - -String EEPROMClass::readString (int address) -{ - if (address < 0 || address > _size) - return String(0); - - uint16_t len; - for (len = 0; len <= _size; len++) - if (_data[address + len] == 0) - break; - - if (address + len > _size) - return String(0); - - char value[len + 1]; - memcpy((uint8_t*) value, _data + address, len); - value[len + 1] = 0; - return String(value); -} - -size_t EEPROMClass::readBytes (int address, void* value, size_t maxLen) -{ - if (!value || !maxLen) - return 0; - - if (address < 0 || address + maxLen > _size) - return 0; - - memcpy((void*) value, _data + address, maxLen); - return maxLen; -} - -template T EEPROMClass::readAll (int address, T &value) -{ - if (address < 0 || address + sizeof(T) > _size) - return value; - - memcpy((uint8_t*) &value, _data + address, sizeof(T)); - return value; -} - -/* - Write 'value' to 'address' -*/ -size_t EEPROMClass::writeByte (int address, uint8_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeChar (int address, int8_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeUChar (int address, uint8_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeShort (int address, int16_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeUShort (int address, uint16_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeInt (int address, int32_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeUInt (int address, uint32_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeLong (int address, int32_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeULong (int address, uint32_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeLong64 (int address, int64_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeULong64 (int address, uint64_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeFloat (int address, float_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeDouble (int address, double_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeBool (int address, bool value) -{ - int8_t Bool; - value ? Bool = 1 : Bool = 0; - return EEPROMClass::writeAll (address, Bool); -} - -size_t EEPROMClass::writeString (int address, const char* value) -{ - if (!value) - return 0; - - if (address < 0 || address > _size) - return 0; - - uint16_t len; - for (len = 0; len <= _size; len++) - if (value[len] == 0) - break; - - if (address + len > _size) - return 0; - - memcpy(_data + address, (const uint8_t*) value, len + 1); - _dirty = true; - return strlen(value); -} - -size_t EEPROMClass::writeString (int address, String value) -{ - return EEPROMClass::writeString (address, value.c_str()); -} - -size_t EEPROMClass::writeBytes (int address, const void* value, size_t len) -{ - if (!value || !len) - return 0; - - if (address < 0 || address + len > _size) - return 0; - - memcpy(_data + address, (const void*) value, len); - _dirty = true; - return len; -} - -template T EEPROMClass::writeAll (int address, const T &value) -{ - if (address < 0 || address + sizeof(T) > _size) - return value; - - memcpy(_data + address, (const uint8_t*) &value, sizeof(T)); - _dirty = true; - - return sizeof (value); -} - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) -EEPROMClass EEPROM; -#endif diff --git a/libraries/EEPROM/README.md b/libraries/EEPROM/README.md new file mode 100644 index 00000000000..896ca5b3019 --- /dev/null +++ b/libraries/EEPROM/README.md @@ -0,0 +1,4 @@ +## EEPROM + +EEPROM is deprecated. For new applications on ESP32, use Preferences. EEPROM is provided for backwards compatibility with existing Arduino applications. +EEPROM is implemented using a single blob within NVS, so it is a container within a container. As such, it is not going to be a high performance storage method. Preferences will directly use nvs, and store each entry as a single object therein. diff --git a/libraries/EEPROM/examples/eeprom_class/eeprom_class.ino b/libraries/EEPROM/examples/eeprom_class/eeprom_class.ino index af098809643..f5301f4ef1d 100644 --- a/libraries/EEPROM/examples/eeprom_class/eeprom_class.ino +++ b/libraries/EEPROM/examples/eeprom_class/eeprom_class.ino @@ -1,37 +1,21 @@ /* ESP32 eeprom_class example with EEPROM library - This simple example demonstrates using EEPROM library to store different data in - ESP32 Flash memory in a multiple user-defined EEPROM partition (0x1000 or 4KB max size or less). - - Install 'ESP32 Partiton Manager' ONCE from https://github.com/francis94c/ESP32Partitions - And generate different partitions with 'partition_name' - Usage: EEPROMClass ANY_OBJECT_NAME("partition_name", size); + ESP32 Flash memory in a multiple user-defined EEPROM class objects. - Generated partition that would work perfectly with this example - #Name, Type, SubType, Offset, Size, Flags - nvs, data, nvs, 0x9000, 0x5000, - otadata, data, ota, 0xe000, 0x2000, - app0, app, ota_0, 0x10000, 0x140000, - app1, app, ota_1, 0x150000, 0x140000, - eeprom0, data, 0x99, 0x290000, 0x1000, - eeprom1, data, 0x9a, 0x291000, 0x500, - eeprom2, data, 0x9b, 0x292000, 0x100, - spiffs, data, spiffs, 0x293000, 0x16d000, - Created for arduino-esp32 on 25 Dec, 2017 by Elochukwu Ifediora (fedy0) + converted to nvs by lbernstone - 06/22/2019 */ #include "EEPROM.h" -// Instantiate eeprom objects with parameter/argument names and size same as in the partition table -EEPROMClass NAMES("eeprom0", 0x1000); -EEPROMClass HEIGHT("eeprom1", 0x500); +// Instantiate eeprom objects with parameter/argument names and sizes +EEPROMClass NAMES("eeprom0", 0x500); +EEPROMClass HEIGHT("eeprom1", 0x200); EEPROMClass AGE("eeprom2", 0x100); void setup() { - // put your setup code here, to run once: Serial.begin(115200); Serial.println("Testing EEPROMClass\n"); if (!NAMES.begin(NAMES.length())) { @@ -53,11 +37,12 @@ void setup() { ESP.restart(); } - char* name = "Teo Swee Ann"; + const char* name = "Teo Swee Ann"; + char rname[32]; double height = 5.8; uint32_t age = 47; - // Write: Variables ---> EEPROM partitions + // Write: Variables ---> EEPROM stores NAMES.put(0, name); HEIGHT.put(0, height); AGE.put(0, age); @@ -75,11 +60,11 @@ void setup() { Serial.print("age: "); Serial.println(age); Serial.println("------------------------------------\n"); - // Read: Variables <--- EEPROM partitions - NAMES.get(0, name); + // Read: Variables <--- EEPROM stores + NAMES.get(0, rname); HEIGHT.get(0, height); AGE.get(0, age); - Serial.print("name: "); Serial.println(name); + Serial.print("name: "); Serial.println(rname); Serial.print("height: "); Serial.println(height); Serial.print("age: "); Serial.println(age); @@ -87,6 +72,5 @@ void setup() { } void loop() { - // put your main code here, to run repeatedly: - + delay(0xFFFFFFFF); } diff --git a/libraries/EEPROM/examples/eeprom_extra/eeprom_extra.ino b/libraries/EEPROM/examples/eeprom_extra/eeprom_extra.ino index b2ea72f7d73..5ae01fb2268 100644 --- a/libraries/EEPROM/examples/eeprom_extra/eeprom_extra.ino +++ b/libraries/EEPROM/examples/eeprom_extra/eeprom_extra.ino @@ -13,78 +13,127 @@ void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println("\nTesting EEPROM Library\n"); - if (!EEPROM.begin(EEPROM.length())) { + if (!EEPROM.begin(1000)) { Serial.println("Failed to initialise EEPROM"); Serial.println("Restarting..."); delay(1000); ESP.restart(); } - int address = 0; // Same address is used through the example + int address = 0; EEPROM.writeByte(address, -128); // -2^7 - Serial.println(EEPROM.readByte(address)); + address += sizeof(byte); EEPROM.writeChar(address, 'A'); // Same as writyByte and readByte - Serial.println(char(EEPROM.readChar(address))); + address += sizeof(char); EEPROM.writeUChar(address, 255); // 2^8 - 1 - Serial.println(EEPROM.readUChar(address)); + address += sizeof(unsigned char); EEPROM.writeShort(address, -32768); // -2^15 - Serial.println(EEPROM.readShort(address)); + address += sizeof(short); EEPROM.writeUShort(address, 65535); // 2^16 - 1 - Serial.println(EEPROM.readUShort(address)); + address += sizeof(unsigned short); EEPROM.writeInt(address, -2147483648); // -2^31 - Serial.println(EEPROM.readInt(address)); + address += sizeof(int); EEPROM.writeUInt(address, 4294967295); // 2^32 - 1 - Serial.println(EEPROM.readUInt(address)); + address += sizeof(unsigned int); EEPROM.writeLong(address, -2147483648); // Same as writeInt and readInt - Serial.println(EEPROM.readLong(address)); + address += sizeof(long); EEPROM.writeULong(address, 4294967295); // Same as writeUInt and readUInt - Serial.println(EEPROM.readULong(address)); + address += sizeof(unsigned long); - int64_t value = -9223372036854775808; // -2^63 + int64_t value = -1223372036854775808LL; // -2^63 EEPROM.writeLong64(address, value); - value = 0; // Clear value + address += sizeof(int64_t); + + uint64_t Value = 18446744073709551615ULL; // 2^64 - 1 + EEPROM.writeULong64(address, Value); + address += sizeof(uint64_t); + + EEPROM.writeFloat(address, 1234.1234); + address += sizeof(float); + + EEPROM.writeDouble(address, 123456789.123456789); + address += sizeof(double); + + EEPROM.writeBool(address, true); + address += sizeof(bool); + + String sentence = "I love ESP32."; + EEPROM.writeString(address, sentence); + address += sentence.length() + 1; + + char gratitude[21] = "Thank You Espressif!"; + EEPROM.writeString(address, gratitude); + address += 21; + + // See also the general purpose writeBytes() and readBytes() for BLOB in EEPROM library + EEPROM.commit(); + address = 0; + + Serial.println(EEPROM.readByte(address)); + address += sizeof(byte); + + Serial.println((char)EEPROM.readChar(address)); + address += sizeof(char); + + Serial.println(EEPROM.readUChar(address)); + address += sizeof(unsigned char); + + Serial.println(EEPROM.readShort(address)); + address += sizeof(short); + + Serial.println(EEPROM.readUShort(address)); + address += sizeof(unsigned short); + + Serial.println(EEPROM.readInt(address)); + address += sizeof(int); + + Serial.println(EEPROM.readUInt(address)); + address += sizeof(unsigned int); + + Serial.println(EEPROM.readLong(address)); + address += sizeof(long); + + Serial.println(EEPROM.readULong(address)); + address += sizeof(unsigned long); + + value = 0; value = EEPROM.readLong64(value); Serial.printf("0x%08X", (uint32_t)(value >> 32)); // Print High 4 bytes in HEX Serial.printf("%08X\n", (uint32_t)value); // Print Low 4 bytes in HEX + address += sizeof(int64_t); - uint64_t Value = 18446744073709551615; // 2^64 - 1 - EEPROM.writeULong64(address, Value); Value = 0; // Clear Value Value = EEPROM.readULong64(Value); Serial.printf("0x%08X", (uint32_t)(Value >> 32)); // Print High 4 bytes in HEX Serial.printf("%08X\n", (uint32_t)Value); // Print Low 4 bytes in HEX + address += sizeof(uint64_t); - EEPROM.writeFloat(address, 1234.1234); Serial.println(EEPROM.readFloat(address), 4); + address += sizeof(float); - EEPROM.writeDouble(address, 123456789.123456789); Serial.println(EEPROM.readDouble(address), 8); + address += sizeof(double); - EEPROM.writeBool(address, true); Serial.println(EEPROM.readBool(address)); + address += sizeof(bool); - String sentence = "I love ESP32."; - EEPROM.writeString(address, sentence); Serial.println(EEPROM.readString(address)); + address += sentence.length() + 1; - char gratitude[] = "Thank You Espressif!"; - EEPROM.writeString(address, gratitude); Serial.println(EEPROM.readString(address)); - - // See also the general purpose writeBytes() and readBytes() for BLOB in EEPROM library - // To avoid data overwrite, next address should be chosen/offset by using "address =+ sizeof(previousData)" + address += 21; } void loop() { // put your main code here, to run repeatedly: -} \ No newline at end of file +} diff --git a/libraries/EEPROM/library.properties b/libraries/EEPROM/library.properties index bd32cb17706..e65520588de 100644 --- a/libraries/EEPROM/library.properties +++ b/libraries/EEPROM/library.properties @@ -1,9 +1,9 @@ name=EEPROM -version=1.0 +version=1.0.3 author=Ivan Grokhotkov maintainer=Paolo Becchi -sentence=Enables reading and writing data to the permanent FLASH storage, up to 4kb. +sentence=Enables reading and writing data a sequential, addressable FLASH storage paragraph= category=Data Storage url=http://arduino.cc/en/Reference/EEPROM -architectures=esp32 \ No newline at end of file +architectures=esp32 diff --git a/libraries/EEPROM/src/EEPROM.cpp b/libraries/EEPROM/src/EEPROM.cpp new file mode 100644 index 00000000000..7f4ab090f1f --- /dev/null +++ b/libraries/EEPROM/src/EEPROM.cpp @@ -0,0 +1,557 @@ +/* + EEPROM.h -ported by Paolo Becchi to Esp32 from esp8266 EEPROM + -Modified by Elochukwu Ifediora + -Converted to nvs lbernstone@gmail.com + + Uses a nvs byte array to emulate EEPROM + + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "EEPROM.h" +#include +#include +#include + +EEPROMClass::EEPROMClass(void) + : _handle(0) + , _data(0) + , _size(0) + , _dirty(false) + , _name("eeprom") + , _user_defined_size(0) +{ +} + +EEPROMClass::EEPROMClass(uint32_t sector) +// Only for compatiility, no sectors in nvs! + : _handle(0) + , _data(0) + , _size(0) + , _dirty(false) + , _name("eeprom") + , _user_defined_size(0) +{ +} + +EEPROMClass::EEPROMClass(const char* name, uint32_t user_defined_size) + : _handle(0) + , _data(0) + , _size(0) + , _dirty(false) + , _name(name) + , _user_defined_size(user_defined_size) +{ +} + +EEPROMClass::~EEPROMClass() { + end(); +} + +bool EEPROMClass::begin(size_t size) { + if (!size) { + return false; + } + + esp_err_t res = nvs_open(_name, NVS_READWRITE, &_handle); + if (res != ESP_OK) { + log_e("Unable to open NVS namespace: %d", res); + return false; + } + + size_t key_size = 0; + res = nvs_get_blob(_handle, _name, NULL, &key_size); + if(res != ESP_OK && res != ESP_ERR_NVS_NOT_FOUND) { + log_e("Unable to read NVS key: %d", res); + return false; + } + if (size < key_size) { // truncate + log_w("truncating EEPROM from %d to %d", key_size, size); + uint8_t* key_data = (uint8_t*) malloc(key_size); + if(!key_data) { + log_e("Not enough memory to truncate EEPROM!"); + return false; + } + nvs_get_blob(_handle, _name, key_data, &key_size); + nvs_set_blob(_handle, _name, key_data, size); + nvs_commit(_handle); + free(key_data); + } + else if (size > key_size) { // expand or new + size_t expand_size = size - key_size; + uint8_t* expand_key = (uint8_t*) malloc(expand_size); + if(!expand_key) { + log_e("Not enough memory to expand EEPROM!"); + return false; + } + // check for adequate free space + if(nvs_set_blob(_handle, "expand", expand_key, expand_size)) { + log_e("Not enough space to expand EEPROM from %d to %d", key_size, size); + free(expand_key); + return false; + } + free(expand_key); + nvs_erase_key(_handle, "expand"); + uint8_t* key_data = (uint8_t*) malloc(size); + if(!key_data) { + log_e("Not enough memory to expand EEPROM!"); + return false; + } + memset(key_data, 0xFF, size); + if(key_size) { + log_i("Expanding EEPROM from %d to %d", key_size, size); + // hold data while key is deleted + nvs_get_blob(_handle, _name, key_data, &key_size); + nvs_erase_key(_handle, _name); + } else { + log_i("New EEPROM of %d bytes", size); + } + nvs_commit(_handle); + nvs_set_blob(_handle, _name, key_data, size); + free(key_data); + nvs_commit(_handle); + } + + if (_data) { + delete[] _data; + } + + _data = (uint8_t*) malloc(size); + if(!_data) { + log_e("Not enough memory for %d bytes in EEPROM"); + return false; + } + _size = size; + nvs_get_blob(_handle, _name, _data, &_size); + return true; +} + +void EEPROMClass::end() { + if (!_size) { + return; + } + + commit(); + if (_data) { + delete[] _data; + } + _data = 0; + _size = 0; + + nvs_close(_handle); + _handle = 0; +} + +uint8_t EEPROMClass::read(int address) { + if (address < 0 || (size_t)address >= _size) { + return 0; + } + if (!_data) { + return 0; + } + + return _data[address]; +} + +void EEPROMClass::write(int address, uint8_t value) { + if (address < 0 || (size_t)address >= _size) + return; + if (!_data) + return; + + // Optimise _dirty. Only flagged if data written is different. + uint8_t* pData = &_data[address]; + if (*pData != value) + { + *pData = value; + _dirty = true; + } +} + +bool EEPROMClass::commit() { + bool ret = false; + if (!_size) { + return false; + } + if (!_data) { + return false; + } + if (!_dirty) { + return true; + } + + if (ESP_OK != nvs_set_blob(_handle, _name, _data, _size)) { + log_e( "error in write"); + } else { + _dirty = false; + ret = true; + } + + return ret; +} + +uint8_t * EEPROMClass::getDataPtr() { + _dirty = true; + return &_data[0]; +} + +/* + Get EEPROM total size in byte defined by the user +*/ +uint16_t EEPROMClass::length () +{ + return _user_defined_size; +} + +/* + Convert EEPROM partition into nvs blob + Call convert before you call begin +*/ +uint16_t EEPROMClass::convert (bool clear, const char* EEPROMname, const char* nvsname) +{ + uint16_t result = 0; + const esp_partition_t* mypart = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, EEPROMname); + if (mypart == NULL) { + log_i("EEPROM partition not found for conversion"); + return result; + } + + size_t size = mypart->size; + uint8_t* data = (uint8_t*) malloc(size); + if (!data) { + log_e("Not enough memory to convert EEPROM!"); + goto exit; + } + + if (esp_partition_read (mypart, 0, (void *) data, size) != ESP_OK) { + log_e("Unable to read EEPROM partition"); + goto exit; + } + + bool empty; + empty = true; + for (int x=0; x _size) + return 0; + + uint16_t len; + for (len = 0; len <= _size; len++) + if (_data[address + len] == 0) + break; + + if (address + len > _size) + return 0; + + memcpy((uint8_t*) value, _data + address, len); + value[len] = 0; + return len; +} + +String EEPROMClass::readString (int address) +{ + if (address < 0 || address > _size) + return String(); + + uint16_t len; + for (len = 0; len <= _size; len++) + if (_data[address + len] == 0) + break; + + if (address + len > _size) + return String(); + + char value[len]; + memcpy((uint8_t*) value, _data + address, len); + value[len] = 0; + return String(value); +} + +size_t EEPROMClass::readBytes (int address, void* value, size_t maxLen) +{ + if (!value || !maxLen) + return 0; + + if (address < 0 || address + maxLen > _size) + return 0; + + memcpy((void*) value, _data + address, maxLen); + return maxLen; +} + +template T EEPROMClass::readAll (int address, T &value) +{ + if (address < 0 || address + sizeof(T) > _size) + return value; + + memcpy((uint8_t*) &value, _data + address, sizeof(T)); + return value; +} + +/* + Write 'value' to 'address' +*/ +size_t EEPROMClass::writeByte (int address, uint8_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeChar (int address, int8_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeUChar (int address, uint8_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeShort (int address, int16_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeUShort (int address, uint16_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeInt (int address, int32_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeUInt (int address, uint32_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeLong (int address, int32_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeULong (int address, uint32_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeLong64 (int address, int64_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeULong64 (int address, uint64_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeFloat (int address, float_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeDouble (int address, double_t value) +{ + return EEPROMClass::writeAll (address, value); +} + +size_t EEPROMClass::writeBool (int address, bool value) +{ + int8_t Bool; + value ? Bool = 1 : Bool = 0; + return EEPROMClass::writeAll (address, Bool); +} + +size_t EEPROMClass::writeString (int address, const char* value) +{ + if (!value) + return 0; + + if (address < 0 || address > _size) + return 0; + + uint16_t len; + for (len = 0; len <= _size; len++) + if (value[len] == 0) + break; + + if (address + len > _size) + return 0; + + memcpy(_data + address, (const uint8_t*) value, len + 1); + _dirty = true; + return strlen(value); +} + +size_t EEPROMClass::writeString (int address, String value) +{ + return EEPROMClass::writeString (address, value.c_str()); +} + +size_t EEPROMClass::writeBytes (int address, const void* value, size_t len) +{ + if (!value || !len) + return 0; + + if (address < 0 || address + len > _size) + return 0; + + memcpy(_data + address, (const void*) value, len); + _dirty = true; + return len; +} + +template T EEPROMClass::writeAll (int address, const T &value) +{ + if (address < 0 || address + sizeof(T) > _size) + return value; + + memcpy(_data + address, (const uint8_t*) &value, sizeof(T)); + _dirty = true; + + return sizeof (value); +} + +#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) +EEPROMClass EEPROM; +#endif diff --git a/libraries/EEPROM/EEPROM.h b/libraries/EEPROM/src/EEPROM.h similarity index 89% rename from libraries/EEPROM/EEPROM.h rename to libraries/EEPROM/src/EEPROM.h index 2e4383c9bd2..032e1f65f86 100644 --- a/libraries/EEPROM/EEPROM.h +++ b/libraries/EEPROM/src/EEPROM.h @@ -1,10 +1,9 @@ /* EEPROM.h -ported by Paolo Becchi to Esp32 from esp8266 EEPROM -Modified by Elochukwu Ifediora + -Converted to nvs lbernstone@gmail.com - Uses a one sector flash partition defined in partition table - OR - Multiple sector flash partitions defined by the name column in the partition table + Uses a nvs byte array to emulate EEPROM Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. @@ -29,19 +28,10 @@ #ifndef EEPROM_FLASH_PARTITION_NAME #define EEPROM_FLASH_PARTITION_NAME "eeprom" #endif -extern "C" { - -#include -#include -#include -#include -} - -// -// need to define AT LEAST a flash partition for EEPROM with above name -// -// eeprom , data , 0x99, start address, 0x1000 -// +#include + +typedef uint32_t nvs_handle; + class EEPROMClass { public: EEPROMClass(uint32_t sector); @@ -57,6 +47,7 @@ class EEPROMClass { void end(); uint8_t * getDataPtr(); + uint16_t convert(bool clear, const char* EEPROMname = "eeprom", const char* nvsname = "eeprom"); template T &get(int address, T &t) { @@ -116,11 +107,10 @@ class EEPROMClass { template T writeAll (int address, const T &); protected: - uint32_t _sector; + nvs_handle _handle; uint8_t* _data; size_t _size; bool _dirty; - const esp_partition_t * _mypart; const char* _name; uint32_t _user_defined_size; }; diff --git a/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino b/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino new file mode 100644 index 00000000000..445797d5e85 --- /dev/null +++ b/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino @@ -0,0 +1,106 @@ +#include "esp_camera.h" +#include + +// +// WARNING!!! Make sure that you have either selected ESP32 Wrover Module, +// or another board which has PSRAM enabled +// + +// Select camera model +#define CAMERA_MODEL_WROVER_KIT +//#define CAMERA_MODEL_ESP_EYE +//#define CAMERA_MODEL_M5STACK_PSRAM +//#define CAMERA_MODEL_M5STACK_WIDE +//#define CAMERA_MODEL_AI_THINKER + +#include "camera_pins.h" + +const char* ssid = "*********"; +const char* password = "*********"; + +void startCameraServer(); + +void setup() { + Serial.begin(115200); + Serial.setDebugOutput(true); + Serial.println(); + + camera_config_t config; + config.ledc_channel = LEDC_CHANNEL_0; + config.ledc_timer = LEDC_TIMER_0; + config.pin_d0 = Y2_GPIO_NUM; + config.pin_d1 = Y3_GPIO_NUM; + config.pin_d2 = Y4_GPIO_NUM; + config.pin_d3 = Y5_GPIO_NUM; + config.pin_d4 = Y6_GPIO_NUM; + config.pin_d5 = Y7_GPIO_NUM; + config.pin_d6 = Y8_GPIO_NUM; + config.pin_d7 = Y9_GPIO_NUM; + config.pin_xclk = XCLK_GPIO_NUM; + config.pin_pclk = PCLK_GPIO_NUM; + config.pin_vsync = VSYNC_GPIO_NUM; + config.pin_href = HREF_GPIO_NUM; + config.pin_sscb_sda = SIOD_GPIO_NUM; + config.pin_sscb_scl = SIOC_GPIO_NUM; + config.pin_pwdn = PWDN_GPIO_NUM; + config.pin_reset = RESET_GPIO_NUM; + config.xclk_freq_hz = 20000000; + config.pixel_format = PIXFORMAT_JPEG; + //init with high specs to pre-allocate larger buffers + if(psramFound()){ + config.frame_size = FRAMESIZE_UXGA; + config.jpeg_quality = 10; + config.fb_count = 2; + } else { + config.frame_size = FRAMESIZE_SVGA; + config.jpeg_quality = 12; + config.fb_count = 1; + } + +#if defined(CAMERA_MODEL_ESP_EYE) + pinMode(13, INPUT_PULLUP); + pinMode(14, INPUT_PULLUP); +#endif + + // camera init + esp_err_t err = esp_camera_init(&config); + if (err != ESP_OK) { + Serial.printf("Camera init failed with error 0x%x", err); + return; + } + + sensor_t * s = esp_camera_sensor_get(); + //initial sensors are flipped vertically and colors are a bit saturated + if (s->id.PID == OV3660_PID) { + s->set_vflip(s, 1);//flip it back + s->set_brightness(s, 1);//up the blightness just a bit + s->set_saturation(s, -2);//lower the saturation + } + //drop down frame size for higher initial frame rate + s->set_framesize(s, FRAMESIZE_QVGA); + +#if defined(CAMERA_MODEL_M5STACK_WIDE) + s->set_vflip(s, 1); + s->set_hmirror(s, 1); +#endif + + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.println("WiFi connected"); + + startCameraServer(); + + Serial.print("Camera Ready! Use 'http://"); + Serial.print(WiFi.localIP()); + Serial.println("' to connect"); +} + +void loop() { + // put your main code here, to run repeatedly: + delay(10000); +} diff --git a/libraries/ESP32/examples/Camera/CameraWebServer/app_httpd.cpp b/libraries/ESP32/examples/Camera/CameraWebServer/app_httpd.cpp new file mode 100644 index 00000000000..07d29ee7175 --- /dev/null +++ b/libraries/ESP32/examples/Camera/CameraWebServer/app_httpd.cpp @@ -0,0 +1,662 @@ +// 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. +#include "esp_http_server.h" +#include "esp_timer.h" +#include "esp_camera.h" +#include "img_converters.h" +#include "camera_index.h" +#include "Arduino.h" + +#include "fb_gfx.h" +#include "fd_forward.h" +#include "fr_forward.h" + +#define ENROLL_CONFIRM_TIMES 5 +#define FACE_ID_SAVE_NUMBER 7 + +#define FACE_COLOR_WHITE 0x00FFFFFF +#define FACE_COLOR_BLACK 0x00000000 +#define FACE_COLOR_RED 0x000000FF +#define FACE_COLOR_GREEN 0x0000FF00 +#define FACE_COLOR_BLUE 0x00FF0000 +#define FACE_COLOR_YELLOW (FACE_COLOR_RED | FACE_COLOR_GREEN) +#define FACE_COLOR_CYAN (FACE_COLOR_BLUE | FACE_COLOR_GREEN) +#define FACE_COLOR_PURPLE (FACE_COLOR_BLUE | FACE_COLOR_RED) + +typedef struct { + size_t size; //number of values used for filtering + size_t index; //current value index + size_t count; //value count + int sum; + int * values; //array to be filled with values +} ra_filter_t; + +typedef struct { + httpd_req_t *req; + size_t len; +} jpg_chunking_t; + +#define PART_BOUNDARY "123456789000000000000987654321" +static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY; +static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n"; +static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n"; + +static ra_filter_t ra_filter; +httpd_handle_t stream_httpd = NULL; +httpd_handle_t camera_httpd = NULL; + +static mtmn_config_t mtmn_config = {0}; +static int8_t detection_enabled = 0; +static int8_t recognition_enabled = 0; +static int8_t is_enrolling = 0; +static face_id_list id_list = {0}; + +static ra_filter_t * ra_filter_init(ra_filter_t * filter, size_t sample_size){ + memset(filter, 0, sizeof(ra_filter_t)); + + filter->values = (int *)malloc(sample_size * sizeof(int)); + if(!filter->values){ + return NULL; + } + memset(filter->values, 0, sample_size * sizeof(int)); + + filter->size = sample_size; + return filter; +} + +static int ra_filter_run(ra_filter_t * filter, int value){ + if(!filter->values){ + return value; + } + filter->sum -= filter->values[filter->index]; + filter->values[filter->index] = value; + filter->sum += filter->values[filter->index]; + filter->index++; + filter->index = filter->index % filter->size; + if (filter->count < filter->size) { + filter->count++; + } + return filter->sum / filter->count; +} + +static void rgb_print(dl_matrix3du_t *image_matrix, uint32_t color, const char * str){ + fb_data_t fb; + fb.width = image_matrix->w; + fb.height = image_matrix->h; + fb.data = image_matrix->item; + fb.bytes_per_pixel = 3; + fb.format = FB_BGR888; + fb_gfx_print(&fb, (fb.width - (strlen(str) * 14)) / 2, 10, color, str); +} + +static int rgb_printf(dl_matrix3du_t *image_matrix, uint32_t color, const char *format, ...){ + char loc_buf[64]; + char * temp = loc_buf; + int len; + va_list arg; + va_list copy; + va_start(arg, format); + va_copy(copy, arg); + len = vsnprintf(loc_buf, sizeof(loc_buf), format, arg); + va_end(copy); + if(len >= sizeof(loc_buf)){ + temp = (char*)malloc(len+1); + if(temp == NULL) { + return 0; + } + } + vsnprintf(temp, len+1, format, arg); + va_end(arg); + rgb_print(image_matrix, color, temp); + if(len > 64){ + free(temp); + } + return len; +} + +static void draw_face_boxes(dl_matrix3du_t *image_matrix, box_array_t *boxes, int face_id){ + int x, y, w, h, i; + uint32_t color = FACE_COLOR_YELLOW; + if(face_id < 0){ + color = FACE_COLOR_RED; + } else if(face_id > 0){ + color = FACE_COLOR_GREEN; + } + fb_data_t fb; + fb.width = image_matrix->w; + fb.height = image_matrix->h; + fb.data = image_matrix->item; + fb.bytes_per_pixel = 3; + fb.format = FB_BGR888; + for (i = 0; i < boxes->len; i++){ + // rectangle box + x = (int)boxes->box[i].box_p[0]; + y = (int)boxes->box[i].box_p[1]; + w = (int)boxes->box[i].box_p[2] - x + 1; + h = (int)boxes->box[i].box_p[3] - y + 1; + fb_gfx_drawFastHLine(&fb, x, y, w, color); + fb_gfx_drawFastHLine(&fb, x, y+h-1, w, color); + fb_gfx_drawFastVLine(&fb, x, y, h, color); + fb_gfx_drawFastVLine(&fb, x+w-1, y, h, color); +#if 0 + // landmark + int x0, y0, j; + for (j = 0; j < 10; j+=2) { + x0 = (int)boxes->landmark[i].landmark_p[j]; + y0 = (int)boxes->landmark[i].landmark_p[j+1]; + fb_gfx_fillRect(&fb, x0, y0, 3, 3, color); + } +#endif + } +} + +static int run_face_recognition(dl_matrix3du_t *image_matrix, box_array_t *net_boxes){ + dl_matrix3du_t *aligned_face = NULL; + int matched_id = 0; + + aligned_face = dl_matrix3du_alloc(1, FACE_WIDTH, FACE_HEIGHT, 3); + if(!aligned_face){ + Serial.println("Could not allocate face recognition buffer"); + return matched_id; + } + if (align_face(net_boxes, image_matrix, aligned_face) == ESP_OK){ + if (is_enrolling == 1){ + int8_t left_sample_face = enroll_face(&id_list, aligned_face); + + if(left_sample_face == (ENROLL_CONFIRM_TIMES - 1)){ + Serial.printf("Enrolling Face ID: %d\n", id_list.tail); + } + Serial.printf("Enrolling Face ID: %d sample %d\n", id_list.tail, ENROLL_CONFIRM_TIMES - left_sample_face); + rgb_printf(image_matrix, FACE_COLOR_CYAN, "ID[%u] Sample[%u]", id_list.tail, ENROLL_CONFIRM_TIMES - left_sample_face); + if (left_sample_face == 0){ + is_enrolling = 0; + Serial.printf("Enrolled Face ID: %d\n", id_list.tail); + } + } else { + matched_id = recognize_face(&id_list, aligned_face); + if (matched_id >= 0) { + Serial.printf("Match Face ID: %u\n", matched_id); + rgb_printf(image_matrix, FACE_COLOR_GREEN, "Hello Subject %u", matched_id); + } else { + Serial.println("No Match Found"); + rgb_print(image_matrix, FACE_COLOR_RED, "Intruder Alert!"); + matched_id = -1; + } + } + } else { + Serial.println("Face Not Aligned"); + //rgb_print(image_matrix, FACE_COLOR_YELLOW, "Human Detected"); + } + + dl_matrix3du_free(aligned_face); + return matched_id; +} + +static size_t jpg_encode_stream(void * arg, size_t index, const void* data, size_t len){ + jpg_chunking_t *j = (jpg_chunking_t *)arg; + if(!index){ + j->len = 0; + } + if(httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK){ + return 0; + } + j->len += len; + return len; +} + +static esp_err_t capture_handler(httpd_req_t *req){ + camera_fb_t * fb = NULL; + esp_err_t res = ESP_OK; + int64_t fr_start = esp_timer_get_time(); + + fb = esp_camera_fb_get(); + if (!fb) { + Serial.println("Camera capture failed"); + httpd_resp_send_500(req); + return ESP_FAIL; + } + + httpd_resp_set_type(req, "image/jpeg"); + httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=capture.jpg"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + + size_t out_len, out_width, out_height; + uint8_t * out_buf; + bool s; + bool detected = false; + int face_id = 0; + if(!detection_enabled || fb->width > 400){ + size_t fb_len = 0; + if(fb->format == PIXFORMAT_JPEG){ + fb_len = fb->len; + res = httpd_resp_send(req, (const char *)fb->buf, fb->len); + } else { + jpg_chunking_t jchunk = {req, 0}; + res = frame2jpg_cb(fb, 80, jpg_encode_stream, &jchunk)?ESP_OK:ESP_FAIL; + httpd_resp_send_chunk(req, NULL, 0); + fb_len = jchunk.len; + } + esp_camera_fb_return(fb); + int64_t fr_end = esp_timer_get_time(); + Serial.printf("JPG: %uB %ums\n", (uint32_t)(fb_len), (uint32_t)((fr_end - fr_start)/1000)); + return res; + } + + dl_matrix3du_t *image_matrix = dl_matrix3du_alloc(1, fb->width, fb->height, 3); + if (!image_matrix) { + esp_camera_fb_return(fb); + Serial.println("dl_matrix3du_alloc failed"); + httpd_resp_send_500(req); + return ESP_FAIL; + } + + out_buf = image_matrix->item; + out_len = fb->width * fb->height * 3; + out_width = fb->width; + out_height = fb->height; + + s = fmt2rgb888(fb->buf, fb->len, fb->format, out_buf); + esp_camera_fb_return(fb); + if(!s){ + dl_matrix3du_free(image_matrix); + Serial.println("to rgb888 failed"); + httpd_resp_send_500(req); + return ESP_FAIL; + } + + box_array_t *net_boxes = face_detect(image_matrix, &mtmn_config); + + if (net_boxes){ + detected = true; + if(recognition_enabled){ + face_id = run_face_recognition(image_matrix, net_boxes); + } + draw_face_boxes(image_matrix, net_boxes, face_id); + free(net_boxes->score); + free(net_boxes->box); + free(net_boxes->landmark); + free(net_boxes); + } + + jpg_chunking_t jchunk = {req, 0}; + s = fmt2jpg_cb(out_buf, out_len, out_width, out_height, PIXFORMAT_RGB888, 90, jpg_encode_stream, &jchunk); + dl_matrix3du_free(image_matrix); + if(!s){ + Serial.println("JPEG compression failed"); + return ESP_FAIL; + } + + int64_t fr_end = esp_timer_get_time(); + Serial.printf("FACE: %uB %ums %s%d\n", (uint32_t)(jchunk.len), (uint32_t)((fr_end - fr_start)/1000), detected?"DETECTED ":"", face_id); + return res; +} + +static esp_err_t stream_handler(httpd_req_t *req){ + camera_fb_t * fb = NULL; + esp_err_t res = ESP_OK; + size_t _jpg_buf_len = 0; + uint8_t * _jpg_buf = NULL; + char * part_buf[64]; + dl_matrix3du_t *image_matrix = NULL; + bool detected = false; + int face_id = 0; + int64_t fr_start = 0; + int64_t fr_ready = 0; + int64_t fr_face = 0; + int64_t fr_recognize = 0; + int64_t fr_encode = 0; + + static int64_t last_frame = 0; + if(!last_frame) { + last_frame = esp_timer_get_time(); + } + + res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE); + if(res != ESP_OK){ + return res; + } + + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + + while(true){ + detected = false; + face_id = 0; + fb = esp_camera_fb_get(); + if (!fb) { + Serial.println("Camera capture failed"); + res = ESP_FAIL; + } else { + fr_start = esp_timer_get_time(); + fr_ready = fr_start; + fr_face = fr_start; + fr_encode = fr_start; + fr_recognize = fr_start; + if(!detection_enabled || fb->width > 400){ + if(fb->format != PIXFORMAT_JPEG){ + bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len); + esp_camera_fb_return(fb); + fb = NULL; + if(!jpeg_converted){ + Serial.println("JPEG compression failed"); + res = ESP_FAIL; + } + } else { + _jpg_buf_len = fb->len; + _jpg_buf = fb->buf; + } + } else { + + image_matrix = dl_matrix3du_alloc(1, fb->width, fb->height, 3); + + if (!image_matrix) { + Serial.println("dl_matrix3du_alloc failed"); + res = ESP_FAIL; + } else { + if(!fmt2rgb888(fb->buf, fb->len, fb->format, image_matrix->item)){ + Serial.println("fmt2rgb888 failed"); + res = ESP_FAIL; + } else { + fr_ready = esp_timer_get_time(); + box_array_t *net_boxes = NULL; + if(detection_enabled){ + net_boxes = face_detect(image_matrix, &mtmn_config); + } + fr_face = esp_timer_get_time(); + fr_recognize = fr_face; + if (net_boxes || fb->format != PIXFORMAT_JPEG){ + if(net_boxes){ + detected = true; + if(recognition_enabled){ + face_id = run_face_recognition(image_matrix, net_boxes); + } + fr_recognize = esp_timer_get_time(); + draw_face_boxes(image_matrix, net_boxes, face_id); + free(net_boxes->score); + free(net_boxes->box); + free(net_boxes->landmark); + free(net_boxes); + } + if(!fmt2jpg(image_matrix->item, fb->width*fb->height*3, fb->width, fb->height, PIXFORMAT_RGB888, 90, &_jpg_buf, &_jpg_buf_len)){ + Serial.println("fmt2jpg failed"); + res = ESP_FAIL; + } + esp_camera_fb_return(fb); + fb = NULL; + } else { + _jpg_buf = fb->buf; + _jpg_buf_len = fb->len; + } + fr_encode = esp_timer_get_time(); + } + dl_matrix3du_free(image_matrix); + } + } + } + if(res == ESP_OK){ + size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len); + res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen); + } + if(res == ESP_OK){ + res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len); + } + if(res == ESP_OK){ + res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY)); + } + if(fb){ + esp_camera_fb_return(fb); + fb = NULL; + _jpg_buf = NULL; + } else if(_jpg_buf){ + free(_jpg_buf); + _jpg_buf = NULL; + } + if(res != ESP_OK){ + break; + } + int64_t fr_end = esp_timer_get_time(); + + int64_t ready_time = (fr_ready - fr_start)/1000; + int64_t face_time = (fr_face - fr_ready)/1000; + int64_t recognize_time = (fr_recognize - fr_face)/1000; + int64_t encode_time = (fr_encode - fr_recognize)/1000; + int64_t process_time = (fr_encode - fr_start)/1000; + + int64_t frame_time = fr_end - last_frame; + last_frame = fr_end; + frame_time /= 1000; + uint32_t avg_frame_time = ra_filter_run(&ra_filter, frame_time); + Serial.printf("MJPG: %uB %ums (%.1ffps), AVG: %ums (%.1ffps), %u+%u+%u+%u=%u %s%d\n", + (uint32_t)(_jpg_buf_len), + (uint32_t)frame_time, 1000.0 / (uint32_t)frame_time, + avg_frame_time, 1000.0 / avg_frame_time, + (uint32_t)ready_time, (uint32_t)face_time, (uint32_t)recognize_time, (uint32_t)encode_time, (uint32_t)process_time, + (detected)?"DETECTED ":"", face_id + ); + } + + last_frame = 0; + return res; +} + +static esp_err_t cmd_handler(httpd_req_t *req){ + char* buf; + size_t buf_len; + char variable[32] = {0,}; + char value[32] = {0,}; + + buf_len = httpd_req_get_url_query_len(req) + 1; + if (buf_len > 1) { + buf = (char*)malloc(buf_len); + if(!buf){ + httpd_resp_send_500(req); + return ESP_FAIL; + } + if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) { + if (httpd_query_key_value(buf, "var", variable, sizeof(variable)) == ESP_OK && + httpd_query_key_value(buf, "val", value, sizeof(value)) == ESP_OK) { + } else { + free(buf); + httpd_resp_send_404(req); + return ESP_FAIL; + } + } else { + free(buf); + httpd_resp_send_404(req); + return ESP_FAIL; + } + free(buf); + } else { + httpd_resp_send_404(req); + return ESP_FAIL; + } + + int val = atoi(value); + sensor_t * s = esp_camera_sensor_get(); + int res = 0; + + if(!strcmp(variable, "framesize")) { + if(s->pixformat == PIXFORMAT_JPEG) res = s->set_framesize(s, (framesize_t)val); + } + else if(!strcmp(variable, "quality")) res = s->set_quality(s, val); + else if(!strcmp(variable, "contrast")) res = s->set_contrast(s, val); + else if(!strcmp(variable, "brightness")) res = s->set_brightness(s, val); + else if(!strcmp(variable, "saturation")) res = s->set_saturation(s, val); + else if(!strcmp(variable, "gainceiling")) res = s->set_gainceiling(s, (gainceiling_t)val); + else if(!strcmp(variable, "colorbar")) res = s->set_colorbar(s, val); + else if(!strcmp(variable, "awb")) res = s->set_whitebal(s, val); + else if(!strcmp(variable, "agc")) res = s->set_gain_ctrl(s, val); + else if(!strcmp(variable, "aec")) res = s->set_exposure_ctrl(s, val); + else if(!strcmp(variable, "hmirror")) res = s->set_hmirror(s, val); + else if(!strcmp(variable, "vflip")) res = s->set_vflip(s, val); + else if(!strcmp(variable, "awb_gain")) res = s->set_awb_gain(s, val); + else if(!strcmp(variable, "agc_gain")) res = s->set_agc_gain(s, val); + else if(!strcmp(variable, "aec_value")) res = s->set_aec_value(s, val); + else if(!strcmp(variable, "aec2")) res = s->set_aec2(s, val); + else if(!strcmp(variable, "dcw")) res = s->set_dcw(s, val); + else if(!strcmp(variable, "bpc")) res = s->set_bpc(s, val); + else if(!strcmp(variable, "wpc")) res = s->set_wpc(s, val); + else if(!strcmp(variable, "raw_gma")) res = s->set_raw_gma(s, val); + else if(!strcmp(variable, "lenc")) res = s->set_lenc(s, val); + else if(!strcmp(variable, "special_effect")) res = s->set_special_effect(s, val); + else if(!strcmp(variable, "wb_mode")) res = s->set_wb_mode(s, val); + else if(!strcmp(variable, "ae_level")) res = s->set_ae_level(s, val); + else if(!strcmp(variable, "face_detect")) { + detection_enabled = val; + if(!detection_enabled) { + recognition_enabled = 0; + } + } + else if(!strcmp(variable, "face_enroll")) is_enrolling = val; + else if(!strcmp(variable, "face_recognize")) { + recognition_enabled = val; + if(recognition_enabled){ + detection_enabled = val; + } + } + else { + res = -1; + } + + if(res){ + return httpd_resp_send_500(req); + } + + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + return httpd_resp_send(req, NULL, 0); +} + +static esp_err_t status_handler(httpd_req_t *req){ + static char json_response[1024]; + + sensor_t * s = esp_camera_sensor_get(); + char * p = json_response; + *p++ = '{'; + + p+=sprintf(p, "\"framesize\":%u,", s->status.framesize); + p+=sprintf(p, "\"quality\":%u,", s->status.quality); + p+=sprintf(p, "\"brightness\":%d,", s->status.brightness); + p+=sprintf(p, "\"contrast\":%d,", s->status.contrast); + p+=sprintf(p, "\"saturation\":%d,", s->status.saturation); + p+=sprintf(p, "\"sharpness\":%d,", s->status.sharpness); + p+=sprintf(p, "\"special_effect\":%u,", s->status.special_effect); + p+=sprintf(p, "\"wb_mode\":%u,", s->status.wb_mode); + p+=sprintf(p, "\"awb\":%u,", s->status.awb); + p+=sprintf(p, "\"awb_gain\":%u,", s->status.awb_gain); + p+=sprintf(p, "\"aec\":%u,", s->status.aec); + p+=sprintf(p, "\"aec2\":%u,", s->status.aec2); + p+=sprintf(p, "\"ae_level\":%d,", s->status.ae_level); + p+=sprintf(p, "\"aec_value\":%u,", s->status.aec_value); + p+=sprintf(p, "\"agc\":%u,", s->status.agc); + p+=sprintf(p, "\"agc_gain\":%u,", s->status.agc_gain); + p+=sprintf(p, "\"gainceiling\":%u,", s->status.gainceiling); + p+=sprintf(p, "\"bpc\":%u,", s->status.bpc); + p+=sprintf(p, "\"wpc\":%u,", s->status.wpc); + p+=sprintf(p, "\"raw_gma\":%u,", s->status.raw_gma); + p+=sprintf(p, "\"lenc\":%u,", s->status.lenc); + p+=sprintf(p, "\"vflip\":%u,", s->status.vflip); + p+=sprintf(p, "\"hmirror\":%u,", s->status.hmirror); + p+=sprintf(p, "\"dcw\":%u,", s->status.dcw); + p+=sprintf(p, "\"colorbar\":%u,", s->status.colorbar); + p+=sprintf(p, "\"face_detect\":%u,", detection_enabled); + p+=sprintf(p, "\"face_enroll\":%u,", is_enrolling); + p+=sprintf(p, "\"face_recognize\":%u", recognition_enabled); + *p++ = '}'; + *p++ = 0; + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + return httpd_resp_send(req, json_response, strlen(json_response)); +} + +static esp_err_t index_handler(httpd_req_t *req){ + httpd_resp_set_type(req, "text/html"); + httpd_resp_set_hdr(req, "Content-Encoding", "gzip"); + sensor_t * s = esp_camera_sensor_get(); + if (s->id.PID == OV3660_PID) { + return httpd_resp_send(req, (const char *)index_ov3660_html_gz, index_ov3660_html_gz_len); + } + return httpd_resp_send(req, (const char *)index_ov2640_html_gz, index_ov2640_html_gz_len); +} + +void startCameraServer(){ + httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + + httpd_uri_t index_uri = { + .uri = "/", + .method = HTTP_GET, + .handler = index_handler, + .user_ctx = NULL + }; + + httpd_uri_t status_uri = { + .uri = "/status", + .method = HTTP_GET, + .handler = status_handler, + .user_ctx = NULL + }; + + httpd_uri_t cmd_uri = { + .uri = "/control", + .method = HTTP_GET, + .handler = cmd_handler, + .user_ctx = NULL + }; + + httpd_uri_t capture_uri = { + .uri = "/capture", + .method = HTTP_GET, + .handler = capture_handler, + .user_ctx = NULL + }; + + httpd_uri_t stream_uri = { + .uri = "/stream", + .method = HTTP_GET, + .handler = stream_handler, + .user_ctx = NULL + }; + + + ra_filter_init(&ra_filter, 20); + + mtmn_config.type = FAST; + mtmn_config.min_face = 80; + mtmn_config.pyramid = 0.707; + mtmn_config.pyramid_times = 4; + mtmn_config.p_threshold.score = 0.6; + mtmn_config.p_threshold.nms = 0.7; + mtmn_config.p_threshold.candidate_number = 20; + mtmn_config.r_threshold.score = 0.7; + mtmn_config.r_threshold.nms = 0.7; + mtmn_config.r_threshold.candidate_number = 10; + mtmn_config.o_threshold.score = 0.7; + mtmn_config.o_threshold.nms = 0.7; + mtmn_config.o_threshold.candidate_number = 1; + + face_id_init(&id_list, FACE_ID_SAVE_NUMBER, ENROLL_CONFIRM_TIMES); + + Serial.printf("Starting web server on port: '%d'\n", config.server_port); + if (httpd_start(&camera_httpd, &config) == ESP_OK) { + httpd_register_uri_handler(camera_httpd, &index_uri); + httpd_register_uri_handler(camera_httpd, &cmd_uri); + httpd_register_uri_handler(camera_httpd, &status_uri); + httpd_register_uri_handler(camera_httpd, &capture_uri); + } + + config.server_port += 1; + config.ctrl_port += 1; + Serial.printf("Starting stream server on port: '%d'\n", config.server_port); + if (httpd_start(&stream_httpd, &config) == ESP_OK) { + httpd_register_uri_handler(stream_httpd, &stream_uri); + } +} diff --git a/libraries/ESP32/examples/Camera/CameraWebServer/camera_index.h b/libraries/ESP32/examples/Camera/CameraWebServer/camera_index.h new file mode 100644 index 00000000000..9e6e09bf13d --- /dev/null +++ b/libraries/ESP32/examples/Camera/CameraWebServer/camera_index.h @@ -0,0 +1,558 @@ + +//File: index_ov2640.html.gz, Size: 4316 +#define index_ov2640_html_gz_len 4316 +const uint8_t index_ov2640_html_gz[] = { + 0x1F, 0x8B, 0x08, 0x08, 0x50, 0x5C, 0xAE, 0x5C, 0x00, 0x03, 0x69, 0x6E, 0x64, 0x65, 0x78, 0x5F, + 0x6F, 0x76, 0x32, 0x36, 0x34, 0x30, 0x2E, 0x68, 0x74, 0x6D, 0x6C, 0x00, 0xE5, 0x5D, 0x7B, 0x73, + 0xD3, 0xC6, 0x16, 0xFF, 0x9F, 0x4F, 0x21, 0x04, 0x25, 0xF6, 0x34, 0x76, 0x6C, 0xC7, 0x84, 0xE0, + 0xDA, 0xE2, 0x42, 0x08, 0xD0, 0x19, 0x5E, 0x25, 0x2D, 0x74, 0xA6, 0xD3, 0x81, 0xB5, 0xB4, 0xB2, + 0x55, 0x64, 0xC9, 0x95, 0x56, 0x76, 0x52, 0x26, 0x9F, 0xE3, 0x7E, 0xA0, 0xFB, 0xC5, 0xEE, 0xD9, + 0x87, 0xA4, 0x95, 0xBC, 0x7A, 0xD8, 0x26, 0x36, 0x97, 0xEB, 0xCC, 0x14, 0xD9, 0xDA, 0x73, 0xF6, + 0x9C, 0xF3, 0x3B, 0xAF, 0x5D, 0x3D, 0x3A, 0xBC, 0x6D, 0xF9, 0x26, 0xB9, 0x9A, 0x63, 0x6D, 0x4A, + 0x66, 0xAE, 0x71, 0x6B, 0xC8, 0xFF, 0xD1, 0xE0, 0x33, 0x9C, 0x62, 0x64, 0xF1, 0x43, 0xF6, 0x75, + 0x86, 0x09, 0xD2, 0xCC, 0x29, 0x0A, 0x42, 0x4C, 0x46, 0x7A, 0x44, 0xEC, 0xD6, 0xA9, 0x9E, 0x3F, + 0xED, 0xA1, 0x19, 0x1E, 0xE9, 0x0B, 0x07, 0x2F, 0xE7, 0x7E, 0x40, 0x74, 0xCD, 0xF4, 0x3D, 0x82, + 0x3D, 0x18, 0xBE, 0x74, 0x2C, 0x32, 0x1D, 0x59, 0x78, 0xE1, 0x98, 0xB8, 0xC5, 0xBE, 0x1C, 0x3A, + 0x9E, 0x43, 0x1C, 0xE4, 0xB6, 0x42, 0x13, 0xB9, 0x78, 0xD4, 0x95, 0x79, 0x11, 0x87, 0xB8, 0xD8, + 0x38, 0xBF, 0x78, 0x7B, 0xDC, 0xD3, 0xDE, 0xBC, 0xEF, 0xF5, 0x4F, 0x3A, 0xC3, 0x23, 0xFE, 0x5B, + 0x3A, 0x26, 0x24, 0x57, 0xF2, 0x77, 0xFA, 0x19, 0xFB, 0xD6, 0x95, 0xF6, 0x25, 0xF3, 0x13, 0xFD, + 0xD8, 0x20, 0x44, 0xCB, 0x46, 0x33, 0xC7, 0xBD, 0x1A, 0x68, 0x8F, 0x03, 0x98, 0xF3, 0xF0, 0x05, + 0x76, 0x17, 0x98, 0x38, 0x26, 0x3A, 0x0C, 0x91, 0x17, 0xB6, 0x42, 0x1C, 0x38, 0xF6, 0x4F, 0x2B, + 0x84, 0x63, 0x64, 0x7E, 0x9E, 0x04, 0x7E, 0xE4, 0x59, 0x03, 0xED, 0x4E, 0xF7, 0x94, 0xFE, 0xAD, + 0x0E, 0x32, 0x7D, 0xD7, 0x0F, 0xE0, 0xFC, 0xF9, 0x33, 0xFA, 0xB7, 0x7A, 0x9E, 0xCD, 0x1E, 0x3A, + 0xFF, 0xE0, 0x81, 0xD6, 0x3D, 0x99, 0x5F, 0x66, 0xCE, 0x5F, 0xDF, 0xCA, 0x7C, 0x9D, 0xF6, 0x8A, + 0xA4, 0x17, 0xF4, 0xA7, 0xE5, 0xF4, 0x21, 0x36, 0x89, 0xE3, 0x7B, 0xED, 0x19, 0x72, 0x3C, 0x05, + 0x27, 0xCB, 0x09, 0xE7, 0x2E, 0x02, 0x1B, 0xD8, 0x2E, 0x2E, 0xE5, 0x73, 0x67, 0x86, 0xBD, 0xE8, + 0xB0, 0x82, 0x1B, 0x65, 0xD2, 0xB2, 0x9C, 0x80, 0x8F, 0x1A, 0x50, 0x3B, 0x44, 0x33, 0xAF, 0x92, + 0x6D, 0x99, 0x5C, 0x9E, 0xEF, 0x61, 0x85, 0x01, 0xE9, 0x44, 0xCB, 0x00, 0xCD, 0xE9, 0x00, 0xFA, + 0xEF, 0xEA, 0x90, 0x99, 0xE3, 0x71, 0xA7, 0x1A, 0x68, 0xC7, 0xFD, 0xCE, 0xFC, 0xB2, 0x02, 0xCA, + 0xE3, 0x13, 0xFA, 0xB7, 0x3A, 0x68, 0x8E, 0x2C, 0xCB, 0xF1, 0x26, 0x03, 0xED, 0x54, 0xC9, 0xC2, + 0x0F, 0x2C, 0x1C, 0xB4, 0x02, 0x64, 0x39, 0x51, 0x38, 0xD0, 0xFA, 0xAA, 0x31, 0x33, 0x14, 0x4C, + 0x40, 0x16, 0xE2, 0x83, 0xB0, 0xAD, 0xAE, 0x52, 0x12, 0x31, 0x24, 0x70, 0x26, 0x53, 0x02, 0x90, + 0xAE, 0x8C, 0xC9, 0x1B, 0x4D, 0x84, 0x50, 0x15, 0x9E, 0xA5, 0x76, 0x53, 0x5B, 0x0D, 0xB9, 0xCE, + 0xC4, 0x6B, 0x39, 0x04, 0xCF, 0x40, 0x9D, 0x90, 0x04, 0x98, 0x98, 0xD3, 0x32, 0x51, 0x6C, 0x67, + 0x12, 0x05, 0x58, 0x21, 0x48, 0x62, 0xB7, 0x12, 0x85, 0xE1, 0xE4, 0xEA, 0xA9, 0xD6, 0x12, 0x8F, + 0x3F, 0x3B, 0xA4, 0x25, 0x6C, 0x32, 0xC6, 0xB6, 0x1F, 0x60, 0xE5, 0xC8, 0x78, 0x84, 0xEB, 0x9B, + 0x9F, 0x5B, 0x21, 0x41, 0x01, 0xA9, 0xC3, 0x10, 0xD9, 0x04, 0x07, 0xD5, 0xFC, 0x30, 0xF5, 0x8A, + 0x6A, 0x6E, 0xC5, 0xD3, 0x8A, 0x01, 0x8E, 0xE7, 0x3A, 0x1E, 0xAE, 0x2F, 0x5E, 0xD1, 0xBC, 0x59, + 0x76, 0x7C, 0x54, 0x0D, 0x60, 0x9C, 0xD9, 0xA4, 0xCC, 0x4B, 0x98, 0xAE, 0xAB, 0x93, 0x89, 0xB8, + 0xE9, 0x76, 0x3A, 0x3F, 0xAC, 0x9E, 0x9C, 0x62, 0xEE, 0xA6, 0x28, 0x22, 0xFE, 0xF6, 0x11, 0xB1, + 0x12, 0x56, 0x39, 0x3D, 0xFE, 0x35, 0xC3, 0x96, 0x83, 0xB4, 0x86, 0x14, 0xCE, 0xA7, 0x1D, 0xF0, + 0xA9, 0xA6, 0x86, 0x3C, 0x4B, 0x6B, 0xF8, 0x81, 0x03, 0x81, 0x80, 0x58, 0xBA, 0x71, 0xE1, 0x17, + 0x28, 0x1C, 0x73, 0xDC, 0x54, 0xA8, 0x5C, 0x12, 0x33, 0xB2, 0x45, 0xD4, 0x61, 0x43, 0x3F, 0x35, + 0x52, 0x0E, 0xFD, 0x54, 0x06, 0x90, 0x42, 0x47, 0xC6, 0xBE, 0x0C, 0x2F, 0x59, 0xC2, 0x22, 0xCC, + 0xE8, 0x67, 0x86, 0x2E, 0x5B, 0xA5, 0xD8, 0xC5, 0x83, 0x62, 0x0C, 0xA1, 0xCC, 0x9A, 0x0D, 0x18, + 0xBA, 0x98, 0x6A, 0x2D, 0x8D, 0x66, 0xC9, 0xA6, 0x9A, 0x46, 0x30, 0x55, 0x43, 0x4E, 0x3F, 0xB2, + 0x53, 0xAC, 0xA1, 0xAE, 0x5A, 0xD5, 0x34, 0x77, 0xF0, 0x3F, 0x95, 0x0F, 0x71, 0x4D, 0x0A, 0xB3, + 0x08, 0xFD, 0xD4, 0xCF, 0x24, 0x29, 0xB3, 0xCA, 0x6C, 0xA2, 0x60, 0x5C, 0x9C, 0x51, 0x56, 0xF8, + 0x16, 0x45, 0xB7, 0x82, 0x6B, 0xB9, 0x08, 0x75, 0xB3, 0x8B, 0x82, 0x71, 0x99, 0x0C, 0x95, 0x59, + 0x86, 0x7E, 0xAE, 0x6B, 0xF4, 0x1B, 0x77, 0xC6, 0x11, 0x21, 0xBE, 0x17, 0x6E, 0x55, 0xA2, 0x8A, + 0xE2, 0xEC, 0xAF, 0x28, 0x24, 0x8E, 0x7D, 0xD5, 0x12, 0x21, 0x0D, 0x71, 0x36, 0x47, 0xD0, 0x42, + 0x8E, 0x31, 0x59, 0x62, 0x5C, 0xDE, 0x6E, 0x78, 0x68, 0x01, 0x79, 0x67, 0x32, 0x71, 0x55, 0xBE, + 0x67, 0x46, 0x41, 0x48, 0xFB, 0xB6, 0xB9, 0xEF, 0x00, 0xE3, 0x60, 0x75, 0xE2, 0x6C, 0x0C, 0xD6, + 0x9C, 0xA8, 0x65, 0x8E, 0x15, 0x73, 0xF9, 0x11, 0xA1, 0x36, 0x56, 0x22, 0xE1, 0x83, 0x3A, 0x0E, + 0xB9, 0x52, 0x9E, 0x13, 0x91, 0xA8, 0x38, 0x13, 0x87, 0x60, 0x69, 0x59, 0xC8, 0xCA, 0x35, 0x30, + 0xA7, 0xD8, 0xFC, 0x8C, 0xAD, 0x1F, 0x2B, 0xDB, 0xB0, 0xAA, 0xF6, 0xB0, 0xED, 0x78, 0xF3, 0x88, + 0xB4, 0x68, 0x3B, 0x35, 0xBF, 0x11, 0xCC, 0x99, 0x43, 0xC6, 0x2A, 0xF6, 0x7A, 0x65, 0x4D, 0xC5, + 0xFD, 0xF9, 0x65, 0xB9, 0x11, 0x64, 0x61, 0x0D, 0x17, 0x8D, 0xB1, 0x5B, 0x26, 0xB2, 0x08, 0x86, + 0x82, 0xB4, 0x2B, 0x72, 0x55, 0x71, 0xEF, 0xC6, 0x24, 0x4B, 0x8B, 0x57, 0xFF, 0xC1, 0x0F, 0xB5, + 0xED, 0xC8, 0x8E, 0x0F, 0x33, 0x3F, 0x85, 0xD8, 0x85, 0x00, 0x2B, 0x6A, 0xBD, 0x61, 0xCC, 0x12, + 0x64, 0x28, 0x9D, 0x20, 0x40, 0xDE, 0x04, 0x43, 0x2E, 0xB8, 0x3C, 0x8C, 0x0F, 0xCB, 0x17, 0x06, + 0xB5, 0xD4, 0xA7, 0xA9, 0xFA, 0x7E, 0xF9, 0x42, 0x84, 0x27, 0x84, 0x0D, 0x9A, 0x11, 0x09, 0xD6, + 0xD2, 0xF9, 0xBB, 0x4A, 0xA7, 0xE0, 0xFD, 0x88, 0x32, 0x60, 0xB2, 0x2E, 0xA5, 0xEC, 0xEF, 0x2B, + 0x33, 0x42, 0xBC, 0xD2, 0xB3, 0xED, 0xAA, 0xB5, 0xA2, 0x6D, 0x1F, 0x77, 0x8E, 0xFB, 0x95, 0x0D, + 0x93, 0x52, 0xCB, 0xDC, 0x7A, 0x51, 0x91, 0x31, 0x92, 0x6C, 0x52, 0x0D, 0xC1, 0x60, 0xEA, 0x2F, + 0x70, 0xA0, 0x00, 0x22, 0x27, 0x6E, 0xFF, 0x61, 0xDF, 0xAA, 0xC1, 0x0D, 0x41, 0xBE, 0x5F, 0xA8, + 0xB2, 0x69, 0x96, 0x5D, 0xAF, 0x6B, 0xF6, 0x4A, 0x1D, 0x93, 0xB3, 0x6B, 0x83, 0x37, 0xA0, 0xB1, + 0x8B, 0xAD, 0x92, 0xF4, 0x6C, 0x61, 0x1B, 0x45, 0x2E, 0xA9, 0xB0, 0x37, 0xEA, 0xD0, 0xBF, 0xB2, + 0x19, 0x59, 0x5C, 0xFD, 0x41, 0x37, 0x3A, 0x46, 0x2C, 0x12, 0xFE, 0x54, 0xCC, 0x19, 0xD7, 0x4E, + 0x34, 0x9F, 0x63, 0x04, 0xA3, 0x4C, 0x5C, 0xB4, 0x24, 0xAD, 0xD5, 0x33, 0xAB, 0x13, 0x57, 0xAD, + 0x85, 0x68, 0xA5, 0x2B, 0x26, 0xDD, 0xD0, 0x5A, 0x3A, 0x0F, 0x6C, 0xDF, 0x8C, 0x54, 0x65, 0xBA, + 0x9E, 0x4B, 0xAD, 0xF2, 0x1B, 0xC4, 0x26, 0x0B, 0x5D, 0x87, 0x39, 0x76, 0xE4, 0x79, 0x14, 0xD1, + 0x16, 0x09, 0x40, 0x4D, 0xC5, 0x44, 0xF5, 0x0C, 0xB7, 0x51, 0x74, 0x66, 0x0C, 0x5B, 0xB4, 0x19, + 0x93, 0x0B, 0x40, 0x45, 0xA2, 0x48, 0x72, 0x88, 0x16, 0xFA, 0xA0, 0x54, 0xCC, 0x6A, 0x3B, 0xBB, + 0x90, 0x69, 0x34, 0x53, 0x35, 0x06, 0xF1, 0x64, 0x5D, 0xA8, 0x62, 0x7C, 0xBA, 0x60, 0x32, 0x46, + 0x8D, 0xCE, 0x61, 0xE7, 0xF0, 0x18, 0xFE, 0xA3, 0x68, 0xD0, 0xCB, 0x9D, 0x4B, 0x98, 0xB7, 0xC0, + 0xF3, 0x72, 0xC9, 0xA7, 0x7A, 0x9F, 0xA4, 0x28, 0x8D, 0x55, 0x62, 0x51, 0x3F, 0x92, 0xB2, 0x1B, + 0x26, 0xDD, 0x76, 0x45, 0x61, 0x29, 0x70, 0xE9, 0xF5, 0x1D, 0x51, 0xE1, 0x2D, 0xEB, 0x42, 0x3C, + 0xF3, 0xFF, 0x69, 0xF1, 0xAA, 0xFA, 0x7F, 0xEF, 0xED, 0x92, 0x29, 0xBE, 0x6B, 0x4F, 0x5F, 0xDB, + 0x2E, 0xE1, 0xBE, 0x7D, 0xA3, 0x53, 0x8C, 0x7A, 0x4B, 0xF4, 0x33, 0x20, 0xA1, 0x07, 0x8B, 0xAA, + 0x00, 0x56, 0x57, 0x85, 0x3D, 0x8F, 0x34, 0x66, 0x03, 0x1B, 0xD8, 0x8E, 0xEB, 0xB6, 0x5C, 0x7F, + 0x59, 0xDD, 0x89, 0x94, 0x7B, 0xF2, 0x8A, 0x9F, 0x56, 0xBB, 0xFC, 0xA6, 0xD2, 0x46, 0x90, 0xB9, + 0xFE, 0x27, 0xA4, 0xFD, 0xBE, 0x03, 0xAE, 0x34, 0x34, 0x36, 0x2B, 0x14, 0x1B, 0xF8, 0xE3, 0x76, + 0x13, 0xD5, 0x72, 0x25, 0xDE, 0x09, 0x96, 0x2E, 0xE6, 0xC2, 0xA5, 0x43, 0xCC, 0xE9, 0x06, 0x8B, + 0xAA, 0xB9, 0x1F, 0x3A, 0xFC, 0x1A, 0x4D, 0x80, 0x5D, 0x44, 0x3B, 0xF8, 0x8D, 0x96, 0xDC, 0x95, + 0x0B, 0x13, 0x99, 0xBC, 0x8E, 0x26, 0xCC, 0x74, 0xDF, 0xCE, 0x76, 0x49, 0x9B, 0xF7, 0x0E, 0xC5, + 0xB9, 0x5A, 0xED, 0xD6, 0x15, 0xED, 0x7E, 0x36, 0x32, 0xD4, 0x83, 0xD6, 0xC8, 0xE8, 0x71, 0xD2, + 0x9E, 0x04, 0xF8, 0xAA, 0x86, 0x32, 0x87, 0xE2, 0xDF, 0x01, 0xDF, 0x10, 0xDD, 0x7C, 0xED, 0xCF, + 0x0A, 0x80, 0xF0, 0xA2, 0x76, 0x3F, 0xAC, 0x31, 0x75, 0xF1, 0x94, 0x75, 0xFC, 0x31, 0xD9, 0xEE, + 0xD3, 0xF5, 0x1A, 0xE9, 0xA6, 0xA4, 0x84, 0xAA, 0x5D, 0x35, 0xAE, 0xBE, 0xCA, 0x93, 0x2E, 0xB6, + 0x49, 0xC1, 0xD5, 0x0C, 0xD6, 0xA7, 0x1E, 0x97, 0x67, 0xB7, 0x96, 0xB4, 0x4F, 0x50, 0x99, 0x39, + 0x92, 0x5D, 0xB9, 0x62, 0xEF, 0x53, 0x72, 0xA6, 0xD9, 0x73, 0x6D, 0xE6, 0xC5, 0x90, 0xC4, 0xED, + 0x33, 0x83, 0x19, 0xC6, 0xCC, 0x44, 0xC9, 0x07, 0x78, 0xF0, 0xEF, 0x8D, 0xDE, 0x89, 0xF2, 0x62, + 0x41, 0xC9, 0xE0, 0x32, 0xD1, 0x0A, 0xB7, 0xB5, 0x56, 0x4B, 0x56, 0xE1, 0x02, 0x59, 0xCE, 0x45, + 0x4A, 0xA0, 0xCA, 0xA3, 0xB2, 0x2C, 0xC3, 0xAC, 0xEE, 0xD1, 0x94, 0x3A, 0xBB, 0x33, 0x43, 0xD0, + 0xF6, 0x52, 0x77, 0x45, 0xC0, 0x51, 0x85, 0x5F, 0x1D, 0x77, 0x97, 0x36, 0x0D, 0xBB, 0x27, 0x9D, + 0x8A, 0x29, 0x4D, 0xD7, 0x0F, 0xCB, 0xE3, 0x0A, 0x8D, 0xC1, 0x7E, 0x11, 0x51, 0x4C, 0x24, 0xB6, + 0x2E, 0x95, 0x3B, 0x4F, 0xCC, 0xB9, 0x95, 0x67, 0x6A, 0x95, 0xEE, 0xD2, 0x98, 0x2A, 0x0F, 0xC7, + 0x9C, 0xCD, 0xBB, 0x1D, 0x65, 0xA6, 0x2D, 0xDD, 0x7F, 0x23, 0xF8, 0x12, 0xD6, 0x9B, 0xF4, 0x82, + 0xDC, 0x40, 0x33, 0xB1, 0x3A, 0x8D, 0x66, 0x8A, 0x5C, 0xB7, 0xCE, 0x26, 0x60, 0x29, 0x0E, 0x53, + 0xC7, 0xB2, 0x70, 0xE9, 0x2E, 0x27, 0x5D, 0xF3, 0xE6, 0x58, 0xC4, 0x47, 0xC3, 0x23, 0xE9, 0x06, + 0x96, 0xE1, 0x51, 0x7A, 0xAF, 0xCD, 0x90, 0xDE, 0xC5, 0x22, 0xDF, 0xE7, 0xC2, 0x2F, 0xB2, 0x68, + 0xA6, 0x8B, 0xC2, 0x70, 0xA4, 0xD3, 0xBB, 0x31, 0xF4, 0xEC, 0x6D, 0x2F, 0x43, 0xCB, 0x59, 0x68, + 0x8E, 0x35, 0xD2, 0x5D, 0x7F, 0xE2, 0xE7, 0xCE, 0xB1, 0xF3, 0x7C, 0xDB, 0x1B, 0x22, 0x75, 0xA4, + 0x67, 0x2E, 0x09, 0xE8, 0x8C, 0x2A, 0xFD, 0x49, 0x37, 0xEE, 0xDD, 0x79, 0xF8, 0xE0, 0xC1, 0xC9, + 0x4F, 0xF7, 0xBC, 0x71, 0x38, 0x17, 0xFF, 0xFD, 0x95, 0x5F, 0x41, 0x79, 0xF3, 0xBE, 0x77, 0xD2, + 0x87, 0x86, 0x16, 0x13, 0xE2, 0x78, 0x93, 0x70, 0x78, 0xC4, 0x98, 0xE6, 0x04, 0x39, 0x02, 0x49, + 0x0A, 0x64, 0x13, 0x09, 0x5D, 0x25, 0x5E, 0x3C, 0x24, 0x84, 0x1C, 0x35, 0x46, 0x81, 0x62, 0x08, + 0x1B, 0xC6, 0xDB, 0x05, 0xD6, 0x69, 0xE9, 0x2C, 0xB1, 0x8D, 0xFD, 0xCB, 0xBC, 0x06, 0x4C, 0x29, + 0x91, 0xF5, 0xC4, 0x28, 0x6C, 0x15, 0x31, 0x04, 0x32, 0x46, 0x4E, 0xAF, 0x87, 0x14, 0x8C, 0x49, + 0xE4, 0x13, 0xD6, 0x97, 0xB6, 0xE7, 0xF9, 0xD4, 0x76, 0x80, 0x66, 0x98, 0x26, 0x22, 0xF1, 0x63, + 0x31, 0x9B, 0x3C, 0x12, 0x09, 0xA5, 0x6E, 0xBC, 0xC3, 0x2C, 0x5C, 0x01, 0x65, 0xA5, 0x59, 0x57, + 0xB8, 0x88, 0x0C, 0x9A, 0x99, 0x5F, 0x8F, 0x45, 0x14, 0x3B, 0xA6, 0x2D, 0xC4, 0xDC, 0xA6, 0x42, + 0x20, 0xC6, 0xCE, 0x9F, 0x33, 0x07, 0x5B, 0x20, 0x37, 0x02, 0xD3, 0x76, 0x3B, 0xBA, 0xF1, 0xDB, + 0xEF, 0xCF, 0x1F, 0x37, 0x20, 0x11, 0x75, 0x2E, 0xBB, 0xBD, 0x4E, 0xA7, 0x39, 0x3C, 0xE2, 0x43, + 0xD6, 0xE6, 0xF5, 0x50, 0x37, 0x2E, 0x18, 0xAB, 0xDE, 0x29, 0xB0, 0xEA, 0xF4, 0xFA, 0x9B, 0xB3, + 0x3A, 0xD5, 0x0D, 0xC6, 0x09, 0x98, 0x5C, 0x3E, 0x38, 0x39, 0xDD, 0x9C, 0xD1, 0x03, 0x90, 0xE9, + 0x3D, 0x70, 0x3A, 0x05, 0xED, 0x4E, 0xB6, 0x51, 0xEE, 0x44, 0x37, 0x28, 0x1F, 0x88, 0x8A, 0xCB, + 0xFE, 0xE9, 0x16, 0x7C, 0xEE, 0xEB, 0xA2, 0x24, 0x52, 0x97, 0x8D, 0x8F, 0x74, 0xE3, 0xEC, 0xE7, + 0x67, 0x8D, 0x3E, 0xC8, 0xD8, 0x7B, 0x78, 0xB2, 0x39, 0xEF, 0xBE, 0x6E, 0xFC, 0x42, 0x85, 0x3C, + 0xEE, 0x01, 0xA3, 0xFE, 0x16, 0x42, 0x1E, 0xEB, 0xC6, 0x0B, 0xC6, 0x09, 0xB8, 0x5C, 0x76, 0x1F, + 0x6C, 0x21, 0x12, 0xB8, 0xD7, 0x2F, 0x8C, 0x13, 0xF8, 0x17, 0x75, 0xAF, 0x9A, 0x9C, 0x20, 0x5F, + 0x32, 0xD3, 0x94, 0xC4, 0xE9, 0x6A, 0xF6, 0xC9, 0x9C, 0x2E, 0x0B, 0xE3, 0xBF, 0x23, 0x28, 0x1D, + 0xE4, 0x6A, 0xED, 0x20, 0x16, 0x74, 0xA0, 0x12, 0x3F, 0xA8, 0x17, 0xBF, 0x92, 0x24, 0xC9, 0x65, + 0x39, 0xDD, 0xE8, 0x76, 0x2A, 0x34, 0x60, 0xB4, 0x72, 0x16, 0x64, 0xC4, 0x19, 0x05, 0x74, 0xDA, + 0x49, 0xB0, 0x18, 0xA6, 0xB7, 0x7E, 0x80, 0x8F, 0x1E, 0xEB, 0x52, 0x5C, 0x6F, 0x94, 0x22, 0x14, + 0xD2, 0xA2, 0x4B, 0xDD, 0x38, 0x39, 0xAE, 0xB2, 0xF7, 0x16, 0x70, 0x8C, 0x59, 0x9B, 0xE2, 0xE1, + 0x30, 0x5C, 0x1B, 0x91, 0x94, 0x54, 0x37, 0x9E, 0x24, 0xC7, 0xDB, 0xE0, 0xD2, 0xEA, 0x6D, 0x81, + 0x8B, 0x24, 0x0E, 0x87, 0xA6, 0xD5, 0x13, 0xD0, 0xF4, 0xF4, 0x34, 0x22, 0xBE, 0x26, 0x30, 0x55, + 0xD2, 0x6E, 0x83, 0x0B, 0x2D, 0xE2, 0x01, 0x0A, 0xC9, 0xDA, 0xA8, 0xC4, 0x84, 0x90, 0xD6, 0xC4, + 0xD1, 0xDE, 0x10, 0x49, 0x44, 0xF9, 0x0E, 0xF0, 0x08, 0x11, 0x89, 0x02, 0x76, 0x43, 0xDC, 0xDA, + 0x88, 0xA4, 0xA4, 0x50, 0x0F, 0x93, 0xE3, 0xBD, 0xA1, 0x22, 0x89, 0xF3, 0x3D, 0xE0, 0x32, 0xC7, + 0xA6, 0x83, 0xDC, 0x8F, 0xD8, 0xB6, 0xA1, 0x64, 0xAD, 0x8F, 0x4D, 0x86, 0x1C, 0xF0, 0xE1, 0xDF, + 0xB5, 0x73, 0xF6, 0x7D, 0xED, 0x1E, 0x31, 0xC7, 0xEE, 0x6B, 0x35, 0x8A, 0x1D, 0x75, 0xDF, 0xF2, + 0xDA, 0x4F, 0xE4, 0xDC, 0xB0, 0x43, 0xE8, 0x02, 0x13, 0x3C, 0x61, 0x2B, 0xE5, 0x8D, 0x79, 0xF4, + 0x74, 0xE3, 0x79, 0x80, 0xAE, 0xD8, 0xB3, 0x05, 0xDB, 0x34, 0x3D, 0xEF, 0xB0, 0xA5, 0xFD, 0x0A, + 0x4B, 0xC1, 0x6D, 0x3A, 0xB0, 0xE7, 0x01, 0x86, 0x65, 0xE2, 0x56, 0x5C, 0xEE, 0x43, 0x31, 0x83, + 0x83, 0xED, 0x98, 0x40, 0xC3, 0x7A, 0x81, 0xE7, 0x0E, 0xFA, 0x16, 0x1A, 0x2E, 0xB4, 0x1C, 0xAF, + 0x1D, 0x16, 0x40, 0xA3, 0x1B, 0x8F, 0x3F, 0x3C, 0x59, 0x3B, 0x49, 0xF1, 0xFD, 0xE6, 0x3A, 0x1E, + 0xCE, 0xB3, 0x93, 0x10, 0x50, 0x5F, 0x59, 0x6C, 0xAA, 0x23, 0xA7, 0xEE, 0x82, 0x53, 0xA1, 0x57, + 0x2C, 0x20, 0xDB, 0x9E, 0xD3, 0x25, 0x35, 0xEB, 0xE9, 0x78, 0x73, 0x19, 0x0C, 0x84, 0xF8, 0x38, + 0x41, 0xCE, 0xFA, 0x75, 0x25, 0x26, 0x64, 0x48, 0x69, 0xCF, 0xE1, 0x68, 0x57, 0x70, 0xF1, 0x69, + 0xF7, 0x86, 0x99, 0xD0, 0x7A, 0xDF, 0xC0, 0x81, 0x20, 0x33, 0xDF, 0x5A, 0x7F, 0x3B, 0x42, 0xD0, + 0xE9, 0x06, 0xA0, 0xF6, 0x0A, 0x0E, 0xD6, 0xAE, 0x32, 0x31, 0x83, 0x1B, 0x2E, 0x2F, 0x8F, 0x23, + 0xE2, 0x6F, 0x53, 0x59, 0x2E, 0x22, 0xCF, 0xBB, 0xDA, 0xA6, 0xAC, 0x9C, 0xB9, 0x7E, 0x64, 0x6D, + 0xCE, 0x01, 0x6A, 0xCA, 0x1B, 0xDB, 0x76, 0xCC, 0xCD, 0xAB, 0x12, 0x54, 0x94, 0x17, 0xFE, 0xAC, + 0x26, 0xFD, 0x0D, 0x67, 0x71, 0x6C, 0xAE, 0x9F, 0x20, 0xB0, 0x09, 0x28, 0x9E, 0x9F, 0x69, 0x17, + 0xE7, 0xAF, 0x2F, 0xDE, 0xBC, 0xDB, 0x4D, 0x76, 0x80, 0x39, 0xF7, 0x94, 0x18, 0xA8, 0xB6, 0xFB, + 0xCE, 0x09, 0x20, 0x44, 0x6F, 0x13, 0x9C, 0x7A, 0x1C, 0xA8, 0xA7, 0x17, 0x6F, 0x77, 0x85, 0x52, + 0x6F, 0x7F, 0x30, 0xF5, 0xBE, 0x05, 0x9C, 0x3E, 0xBA, 0x78, 0x81, 0xDD, 0x0D, 0xB0, 0xE2, 0x84, + 0x14, 0x2F, 0xED, 0x25, 0x3D, 0xDA, 0xDB, 0x42, 0x2E, 0x11, 0xE5, 0x3B, 0x58, 0xC6, 0x81, 0x57, + 0x7C, 0x64, 0x42, 0x6F, 0x12, 0x3C, 0x9C, 0x52, 0x37, 0xCE, 0x2F, 0xE7, 0x7E, 0x18, 0x05, 0x35, + 0x0B, 0xAA, 0x1A, 0x91, 0x6D, 0x76, 0x06, 0x53, 0x51, 0x38, 0x22, 0xF1, 0xD6, 0x20, 0xDD, 0xD9, + 0x4F, 0x30, 0xE9, 0x75, 0xFA, 0x5F, 0x15, 0x15, 0xCA, 0xFC, 0x26, 0x81, 0x99, 0x6C, 0x50, 0x77, + 0x26, 0xB4, 0xEE, 0x3C, 0x3F, 0xDB, 0x4D, 0x2A, 0x9B, 0xEC, 0xAD, 0xE0, 0x4C, 0xF6, 0x5A, 0x70, + 0x34, 0x7E, 0x51, 0x34, 0x81, 0x69, 0xC3, 0x45, 0x84, 0x20, 0x84, 0xB5, 0xF3, 0x26, 0x0B, 0x08, + 0x79, 0x53, 0xFD, 0x72, 0x9B, 0xD0, 0x89, 0xC5, 0xC8, 0x46, 0xCE, 0x71, 0x1A, 0x37, 0xF7, 0xBF, + 0x6A, 0xD4, 0x1C, 0x57, 0x4A, 0xBB, 0x4D, 0xD0, 0x50, 0x4D, 0x4C, 0xEC, 0xB8, 0xF4, 0x09, 0xA6, + 0x75, 0x01, 0x91, 0x68, 0x39, 0x26, 0xDA, 0x19, 0xFF, 0xB6, 0x0D, 0x36, 0xBD, 0x6D, 0xB0, 0x91, + 0x25, 0xCA, 0xC2, 0x73, 0x72, 0x43, 0x95, 0xA6, 0xDB, 0x3B, 0xBD, 0x49, 0x78, 0xC6, 0xF3, 0xF5, + 0x73, 0x1A, 0xD0, 0xE8, 0xC6, 0x93, 0xB7, 0xBB, 0xC9, 0x69, 0x74, 0xB2, 0x9A, 0x39, 0x6D, 0xAB, + 0x0C, 0xC6, 0x94, 0xDA, 0x77, 0x2B, 0xB6, 0xDC, 0x00, 0x8D, 0x25, 0x15, 0xFC, 0xC3, 0x8E, 0xD0, + 0x58, 0xD6, 0x47, 0xE3, 0x2B, 0x57, 0x98, 0xE5, 0xB7, 0x80, 0x4F, 0x80, 0x96, 0x1F, 0x27, 0x33, + 0xB4, 0x36, 0x46, 0x82, 0x4E, 0x37, 0xDE, 0xA1, 0xA5, 0xF6, 0xFC, 0xD5, 0xE3, 0x9D, 0x60, 0x15, + 0x4F, 0xBA, 0x1F, 0xBC, 0x12, 0x95, 0xF7, 0x8D, 0x99, 0x8B, 0xBD, 0xF5, 0x83, 0x8A, 0x12, 0xE9, + 0xC6, 0x4B, 0xEC, 0x85, 0xDA, 0x99, 0x1F, 0x88, 0xB7, 0xCD, 0xEC, 0x04, 0x35, 0x36, 0xF3, 0x7E, + 0x20, 0xE3, 0x4A, 0xEF, 0x1B, 0xAF, 0xE9, 0xCC, 0x09, 0x02, 0x3F, 0x58, 0x1B, 0x32, 0x41, 0xA7, + 0x1B, 0x2F, 0x5A, 0xAF, 0xD8, 0xD1, 0x4E, 0xE0, 0x8A, 0x67, 0xDD, 0x0F, 0x62, 0x89, 0xCE, 0xFB, + 0x06, 0x6D, 0x61, 0xBB, 0xCE, 0x7C, 0x6D, 0xC8, 0x18, 0x95, 0x6E, 0xBC, 0x6F, 0x3D, 0x83, 0x7F, + 0x77, 0x02, 0x17, 0x9F, 0x71, 0x3F, 0x60, 0x09, 0x6D, 0xF7, 0x0D, 0x95, 0x65, 0x2E, 0xD7, 0x06, + 0x0A, 0x68, 0x74, 0xE3, 0xE9, 0xD9, 0x07, 0xAD, 0xF1, 0xD4, 0x5F, 0x7A, 0xF4, 0xC6, 0x3F, 0xED, + 0xFC, 0x75, 0x73, 0x27, 0x88, 0xD1, 0xA9, 0xF7, 0x83, 0x17, 0x53, 0x7A, 0xDF, 0x68, 0xB1, 0xBB, + 0x8F, 0xC7, 0x68, 0xFD, 0x74, 0x18, 0x13, 0xD2, 0x7B, 0x5F, 0xE0, 0x48, 0x7B, 0x82, 0x76, 0x93, + 0x10, 0x93, 0x79, 0x77, 0xD1, 0xB4, 0xA7, 0x4A, 0xEE, 0x1B, 0x27, 0x1B, 0x99, 0xF8, 0xA3, 0x85, + 0xC9, 0x26, 0x37, 0x5E, 0x48, 0xB4, 0xBA, 0xF1, 0x0C, 0xBE, 0x68, 0x4F, 0xD9, 0x97, 0x5D, 0xB5, + 0x1C, 0xF2, 0xFC, 0xBB, 0x40, 0x2D, 0xA3, 0xEF, 0x37, 0x01, 0x1C, 0x34, 0x78, 0xFE, 0xC4, 0xDB, + 0xE8, 0x7E, 0xEA, 0x0C, 0xB9, 0x80, 0xEF, 0x1D, 0xFF, 0xBE, 0x5B, 0x00, 0x53, 0x21, 0x76, 0x86, + 0xA1, 0xA4, 0xF7, 0x2E, 0x60, 0x8C, 0x9F, 0x49, 0x60, 0xDB, 0x02, 0xFC, 0xE5, 0x4F, 0x55, 0x48, + 0x89, 0x57, 0xC2, 0xB0, 0xAD, 0x1B, 0x4C, 0x5A, 0x21, 0x71, 0x5C, 0x57, 0x37, 0x9E, 0x63, 0xA2, + 0x5D, 0xD0, 0xC3, 0xE1, 0x11, 0x1F, 0x50, 0x9F, 0x8B, 0xB8, 0xE1, 0x9F, 0xBE, 0x76, 0x0D, 0xCD, + 0x74, 0xE3, 0x82, 0xBE, 0x16, 0x0B, 0x78, 0xD1, 0x6F, 0xEB, 0x33, 0x63, 0x46, 0xC4, 0x5E, 0xE0, + 0x83, 0x50, 0x09, 0x48, 0xE2, 0xED, 0x24, 0xBA, 0x16, 0x1F, 0x49, 0xBF, 0x19, 0xE7, 0x6C, 0xB0, + 0x46, 0xBD, 0xAC, 0x7A, 0x3A, 0x7A, 0x15, 0xD6, 0x2C, 0xBE, 0x58, 0x3B, 0x3C, 0xF2, 0x90, 0xC2, + 0xDC, 0x05, 0x28, 0x0C, 0xF9, 0xFB, 0xD4, 0x0A, 0x58, 0x25, 0x0F, 0x53, 0x30, 0x4B, 0xA4, 0x0F, + 0x26, 0x25, 0x6A, 0xE5, 0x1F, 0x58, 0x12, 0x1B, 0xB6, 0xF5, 0x82, 0x96, 0x3D, 0x7A, 0x24, 0xEA, + 0x21, 0x3D, 0x4C, 0xCC, 0xFF, 0x9F, 0x7F, 0x57, 0xF9, 0x0C, 0x7D, 0xDB, 0x5D, 0x2A, 0x98, 0xAE, + 0x85, 0x81, 0x39, 0xD2, 0x8B, 0x1E, 0xCD, 0x28, 0xD0, 0xFC, 0x48, 0xA5, 0x7A, 0x6E, 0xB0, 0xC2, + 0xD6, 0xC3, 0xD0, 0x0C, 0x9C, 0x39, 0x31, 0x6E, 0x59, 0xBE, 0x19, 0xCD, 0xB0, 0x47, 0xDA, 0xC8, + 0xB2, 0xCE, 0x17, 0x70, 0xF0, 0xD2, 0x09, 0x09, 0x06, 0x2B, 0x34, 0x0E, 0x9E, 0xBE, 0x79, 0x75, + 0xC6, 0x1F, 0x51, 0x79, 0xE9, 0x23, 0x0B, 0x5B, 0x07, 0x87, 0x9A, 0x1D, 0x79, 0xDC, 0xCD, 0x1B, + 0x98, 0x8E, 0xE5, 0x6F, 0x1A, 0x5C, 0xA0, 0x40, 0x1B, 0xA3, 0x10, 0xBF, 0xF0, 0x43, 0xA2, 0x8D, + 0xB4, 0x84, 0xA3, 0xEB, 0x9B, 0xEC, 0xF6, 0xC5, 0xB6, 0x1F, 0x38, 0x13, 0xC7, 0x13, 0x23, 0xB9, + 0xB2, 0xBF, 0x05, 0x2E, 0x0C, 0x4D, 0xA8, 0x7E, 0xD4, 0x0E, 0x06, 0xA7, 0xDD, 0x03, 0xFA, 0x34, + 0x11, 0xC0, 0x00, 0x3F, 0x00, 0x04, 0x18, 0x06, 0x40, 0x80, 0x8F, 0x0C, 0xF1, 0x38, 0x11, 0x76, + 0xDB, 0xCC, 0xE4, 0x54, 0x40, 0x2A, 0x6D, 0xE3, 0x80, 0xE3, 0x74, 0x40, 0x1F, 0xAD, 0xBB, 0x4E, + 0x28, 0xC3, 0xA9, 0xBF, 0x2C, 0xA3, 0x0C, 0xF0, 0xCC, 0x5F, 0xE0, 0x1C, 0x71, 0x42, 0x2D, 0xBC, + 0xB9, 0x72, 0xEA, 0xD8, 0xEB, 0x0F, 0x9A, 0xF1, 0x80, 0xE4, 0xCD, 0x3D, 0x23, 0x8D, 0x04, 0x11, + 0xCE, 0xB2, 0xC5, 0x5E, 0x15, 0xD7, 0x58, 0xAC, 0x52, 0xC6, 0x36, 0x72, 0xC3, 0x1C, 0xE7, 0x68, + 0x6E, 0x21, 0x82, 0xDF, 0xD3, 0xDD, 0x5D, 0x18, 0xD0, 0xC0, 0xEE, 0x21, 0xDF, 0xEA, 0x3D, 0x14, + 0x67, 0xDE, 0x01, 0x5F, 0x82, 0x9B, 0xE9, 0xAC, 0xF2, 0xCF, 0x40, 0x91, 0xFD, 0x3A, 0xD2, 0xBC, + 0x08, 0x42, 0xF8, 0x11, 0x53, 0x41, 0x1B, 0x64, 0xCE, 0x32, 0x6A, 0x17, 0xB2, 0x93, 0x78, 0x4B, + 0x31, 0x9B, 0x93, 0xFD, 0xE8, 0xD8, 0x74, 0xE2, 0x36, 0x7B, 0x67, 0xF2, 0x08, 0x78, 0x1C, 0xC4, + 0xD9, 0xFD, 0x20, 0x7D, 0x15, 0xA5, 0x4C, 0xC4, 0xEC, 0xD0, 0x16, 0x7D, 0xB0, 0x38, 0xBF, 0x10, + 0x27, 0x6E, 0xDF, 0x5E, 0x24, 0x7C, 0x35, 0x69, 0x18, 0x9C, 0x4A, 0x4F, 0x5C, 0xC3, 0x09, 0xE9, + 0x79, 0xBF, 0x55, 0xDE, 0x39, 0x1E, 0x31, 0x73, 0x89, 0xC3, 0xAD, 0x44, 0xF2, 0x8C, 0x05, 0xEE, + 0xDD, 0xCB, 0x72, 0xBB, 0x3D, 0x12, 0x54, 0xA9, 0x26, 0x7C, 0x3C, 0x44, 0x06, 0x44, 0x1E, 0xA8, + 0x2D, 0x9E, 0x02, 0x15, 0x22, 0x39, 0x76, 0xE3, 0x76, 0xC6, 0xF0, 0x89, 0x8C, 0x36, 0x35, 0x91, + 0x63, 0x31, 0x03, 0xB1, 0x7B, 0x20, 0x9A, 0xE9, 0x53, 0x72, 0x5C, 0xBE, 0x47, 0xCC, 0xEB, 0x1B, + 0x58, 0x5C, 0x1D, 0x6D, 0x82, 0xFD, 0xA9, 0x33, 0xA7, 0x3F, 0x88, 0xF1, 0xE9, 0x54, 0x32, 0xC7, + 0x49, 0x86, 0x23, 0x55, 0x2C, 0x27, 0x37, 0xFD, 0x30, 0x7E, 0xF4, 0x3A, 0x81, 0xB8, 0x56, 0x21, + 0x3F, 0x95, 0xCA, 0x26, 0x07, 0x36, 0xF4, 0x5A, 0x46, 0xFA, 0x7B, 0xCE, 0xD4, 0xC9, 0xC0, 0x02, + 0x26, 0x6C, 0x82, 0x55, 0x26, 0xA5, 0x92, 0xC7, 0x37, 0x8A, 0x29, 0x0C, 0xC2, 0xD8, 0x2D, 0xC7, + 0xD4, 0x14, 0x6C, 0x56, 0x38, 0x2C, 0x63, 0x95, 0x2B, 0xFC, 0x0A, 0x86, 0x3C, 0x10, 0x1B, 0xBC, + 0xAE, 0x3D, 0x61, 0x35, 0x8A, 0x32, 0x17, 0x31, 0x96, 0xFD, 0xFD, 0x96, 0x2C, 0xFC, 0x75, 0x1C, + 0x76, 0x49, 0x0A, 0x94, 0xFD, 0x80, 0xFA, 0x7F, 0x6C, 0x69, 0x1A, 0x22, 0xA9, 0xA3, 0x89, 0x07, + 0xFB, 0xE3, 0xF8, 0x48, 0xE1, 0x30, 0x21, 0xF7, 0x49, 0x91, 0x32, 0xC8, 0x89, 0x2A, 0x87, 0x08, + 0xC8, 0xDD, 0xD5, 0xE4, 0x47, 0xF5, 0xC7, 0x90, 0x42, 0x3F, 0x67, 0xF8, 0xB0, 0x8B, 0x32, 0x09, + 0x13, 0xFE, 0x1B, 0xBF, 0xCD, 0xA9, 0xE5, 0x7B, 0x58, 0xCD, 0x5D, 0x0E, 0x12, 0x15, 0x4F, 0x5E, + 0xC2, 0xF3, 0x4C, 0xA3, 0xF1, 0xCC, 0x21, 0x0A, 0x86, 0x07, 0x90, 0xBE, 0x55, 0xBC, 0x44, 0x63, + 0x97, 0x12, 0x04, 0x98, 0x44, 0x81, 0x27, 0x47, 0x21, 0xCF, 0x64, 0x7F, 0x47, 0x38, 0xB8, 0x02, + 0x46, 0x9F, 0xEE, 0x7E, 0x89, 0xEB, 0xC2, 0xF5, 0x11, 0x7B, 0x34, 0xC1, 0x77, 0x1F, 0x41, 0xE5, + 0x18, 0xDD, 0xFD, 0xC2, 0xA0, 0xBE, 0xBE, 0x07, 0x53, 0xC2, 0x17, 0x36, 0xF1, 0xF5, 0x27, 0xCE, + 0xC2, 0xA6, 0x2F, 0x9A, 0x6D, 0x30, 0x16, 0x31, 0x6E, 0x6D, 0x32, 0xC5, 0x5E, 0x23, 0xC0, 0xE1, + 0x1C, 0xD8, 0xE3, 0x34, 0x01, 0xC6, 0x33, 0xFA, 0x2E, 0x86, 0x12, 0x35, 0x69, 0x7C, 0x0A, 0x30, + 0xD0, 0x81, 0x00, 0xC4, 0xD7, 0xEE, 0x7E, 0x61, 0x2C, 0xAE, 0x35, 0x1B, 0xB2, 0x40, 0x38, 0xC5, + 0xD6, 0x21, 0xD4, 0x2B, 0x44, 0xE8, 0x13, 0xB8, 0x77, 0xBF, 0xC4, 0xAC, 0xDA, 0xFC, 0xA7, 0xEB, + 0x4F, 0x89, 0x87, 0x24, 0x45, 0x24, 0xAE, 0x7D, 0xEC, 0x44, 0x9B, 0xF1, 0xBA, 0x60, 0x28, 0xF8, + 0xC1, 0x63, 0xD7, 0x6D, 0x1C, 0xF0, 0x07, 0x95, 0x45, 0x6E, 0x6F, 0x43, 0xB3, 0x7A, 0x8E, 0x40, + 0x6C, 0xB9, 0x28, 0xB0, 0x7C, 0xE5, 0x7B, 0xA6, 0xEB, 0x98, 0x9F, 0x69, 0x42, 0x6F, 0x66, 0x05, + 0xE7, 0x19, 0xC2, 0x6D, 0xF3, 0x17, 0xCF, 0xBC, 0xF6, 0x2D, 0x9C, 0x73, 0xD3, 0x26, 0x15, 0xE3, + 0xE8, 0x08, 0xAC, 0x8C, 0xAC, 0x38, 0x95, 0x71, 0x8C, 0xE8, 0x1B, 0x0A, 0xB8, 0x99, 0x32, 0x16, + 0xE6, 0xCA, 0x08, 0x5D, 0xB8, 0xCD, 0xD2, 0x2A, 0x1F, 0xAB, 0x9C, 0xBA, 0x2D, 0x47, 0x4F, 0x4B, + 0x6C, 0xF1, 0x57, 0xE8, 0x7B, 0x8D, 0xE6, 0xAD, 0xC4, 0x0C, 0xAB, 0x3C, 0xE8, 0x04, 0x12, 0x83, + 0x8C, 0x89, 0x8A, 0xCC, 0x94, 0x5D, 0x0D, 0x1C, 0xA4, 0x99, 0xA4, 0xC0, 0x66, 0xF4, 0x23, 0x55, + 0x42, 0x56, 0x06, 0xD9, 0xBC, 0x7F, 0x30, 0x97, 0xF9, 0xF3, 0x90, 0x97, 0x4E, 0x29, 0x23, 0x35, + 0x25, 0x73, 0x71, 0xFF, 0xA3, 0xAF, 0xE8, 0x97, 0xDB, 0x17, 0xE8, 0xC9, 0xCF, 0x5D, 0x4C, 0x0F, + 0x9F, 0x5C, 0xFD, 0x0C, 0x25, 0x9F, 0x37, 0x2E, 0x4C, 0x96, 0x94, 0xE0, 0x2C, 0x69, 0x1A, 0x2B, + 0x29, 0xD3, 0x06, 0x53, 0xE2, 0xC1, 0x9A, 0x7E, 0x9E, 0x6F, 0xCA, 0x38, 0x24, 0xEB, 0x83, 0x0C, + 0x29, 0xE5, 0x5A, 0x4D, 0x9B, 0x59, 0x15, 0x48, 0xF4, 0x72, 0xAE, 0x2B, 0xA3, 0x97, 0x16, 0x02, + 0x12, 0x35, 0x73, 0xE4, 0x6A, 0x62, 0xB9, 0x25, 0x3E, 0x90, 0x8C, 0x1D, 0x12, 0x7F, 0xCE, 0x57, + 0x26, 0x39, 0x27, 0x5F, 0x3A, 0x9E, 0xE5, 0x2F, 0xDB, 0xF4, 0x7C, 0x43, 0x94, 0x56, 0x59, 0xD1, + 0xB6, 0xE3, 0x81, 0x01, 0x5F, 0xFC, 0xFA, 0xEA, 0x25, 0x4D, 0x39, 0xF2, 0x0A, 0xE7, 0x20, 0xDB, + 0x17, 0xB1, 0x77, 0x02, 0x2B, 0x67, 0xA0, 0xB0, 0xB5, 0xA1, 0xD5, 0xE6, 0xA9, 0x26, 0x69, 0x47, + 0x69, 0x24, 0xD0, 0xC3, 0x4F, 0x7C, 0x4E, 0x5A, 0x78, 0x32, 0x00, 0x37, 0x2B, 0x65, 0xF1, 0xE7, + 0x79, 0x51, 0x20, 0x0E, 0x1F, 0x13, 0x02, 0xEE, 0xAA, 0x71, 0x47, 0x0E, 0x69, 0x8E, 0x11, 0xAB, + 0xC3, 0x5B, 0x9A, 0x0C, 0x7E, 0x41, 0xC8, 0xA7, 0x66, 0x12, 0x31, 0x96, 0x15, 0x5E, 0xCA, 0x93, + 0x68, 0x0E, 0x71, 0x89, 0x1F, 0x7D, 0x34, 0xC7, 0x90, 0x1A, 0x9F, 0x82, 0xE7, 0xB7, 0x3D, 0xD0, + 0xA0, 0x79, 0x5D, 0xA6, 0x0E, 0x37, 0x57, 0x0A, 0x64, 0x5D, 0x21, 0x58, 0x12, 0x52, 0x73, 0xCB, + 0xD8, 0x47, 0xCD, 0x4E, 0xF6, 0xDE, 0x73, 0x2F, 0x6E, 0x6D, 0x8B, 0x0C, 0x3B, 0x5A, 0x35, 0x2D, + 0xEF, 0x6E, 0x32, 0x0C, 0xD2, 0xF4, 0xB2, 0x22, 0x6C, 0xAE, 0x81, 0x91, 0xFC, 0x22, 0x1E, 0x10, + 0xCB, 0x2E, 0x07, 0x44, 0x81, 0xEC, 0xD9, 0xDE, 0x2F, 0xD7, 0x2C, 0xE4, 0x20, 0x17, 0x39, 0x4C, + 0xA3, 0x2F, 0x2A, 0x98, 0xD2, 0xF2, 0x2C, 0x9C, 0xA0, 0x4E, 0x99, 0x50, 0xE6, 0xBF, 0xD2, 0x7A, + 0xC1, 0x67, 0x88, 0xA5, 0xCD, 0xF7, 0xA8, 0xD9, 0xDA, 0x70, 0x16, 0x81, 0x95, 0x66, 0xB1, 0x4F, + 0xF2, 0xDF, 0x68, 0xC3, 0x96, 0x04, 0x0F, 0x34, 0x70, 0x65, 0x41, 0x0D, 0xA7, 0xA5, 0x4C, 0x20, + 0xBA, 0xBD, 0x0A, 0x02, 0xE9, 0xAE, 0x27, 0x89, 0x56, 0xEA, 0x22, 0x4B, 0xD3, 0x5F, 0xFE, 0x3E, + 0x1D, 0xC6, 0x02, 0xB8, 0xAE, 0x6A, 0xAE, 0xC0, 0x09, 0xC6, 0x35, 0x13, 0xB7, 0xA1, 0x44, 0xA2, + 0xAD, 0x92, 0x9C, 0xA6, 0xA0, 0x2D, 0x5E, 0x6D, 0x89, 0x73, 0xDE, 0x54, 0xD4, 0x0A, 0xAF, 0xB6, + 0xC1, 0xD7, 0x92, 0x83, 0xC4, 0xF7, 0x3F, 0xA6, 0x26, 0xC4, 0xE5, 0xF6, 0xC6, 0xB2, 0xBD, 0xE3, + 0xE5, 0x40, 0x05, 0x85, 0x7C, 0x9B, 0x26, 0x37, 0x17, 0xAE, 0x69, 0x2E, 0x2C, 0xCC, 0x45, 0x09, + 0xD2, 0x0E, 0xB4, 0x7A, 0x6D, 0x92, 0xF8, 0xFF, 0x87, 0x27, 0xA9, 0x66, 0xCB, 0x71, 0xA9, 0x9C, + 0xA2, 0xF7, 0x97, 0xD4, 0x2B, 0x27, 0xC8, 0x3C, 0xCB, 0xC1, 0xD5, 0x5A, 0x8E, 0xEB, 0xA9, 0x15, + 0xAF, 0x1D, 0x28, 0x41, 0xAA, 0x96, 0x7A, 0x85, 0x11, 0xAB, 0x92, 0xEC, 0x75, 0xB3, 0xFF, 0xDD, + 0x42, 0xF2, 0x66, 0x89, 0x44, 0x58, 0xBE, 0x51, 0x5C, 0x59, 0x3D, 0xF9, 0x30, 0x49, 0xC9, 0x64, + 0x8D, 0x52, 0x49, 0x9A, 0x8C, 0x94, 0xA8, 0x13, 0x39, 0x4A, 0xA9, 0xE3, 0x41, 0xBC, 0xEC, 0x26, + 0x5F, 0x6B, 0x19, 0x2B, 0x19, 0x9D, 0x06, 0x4E, 0xCA, 0x80, 0x77, 0xFC, 0x86, 0x76, 0x3F, 0xBF, + 0x26, 0xE6, 0xBD, 0x17, 0x57, 0x36, 0xD7, 0x71, 0xC9, 0x03, 0x12, 0x95, 0x32, 0x63, 0x92, 0x00, + 0xE1, 0xF4, 0x45, 0x62, 0x56, 0x8A, 0x82, 0x5C, 0x1C, 0x90, 0x86, 0xFE, 0xD6, 0xC5, 0x74, 0xBD, + 0x22, 0x9E, 0xC6, 0x39, 0xFB, 0xF9, 0x99, 0xE6, 0x07, 0x1A, 0x7F, 0xC1, 0x5D, 0x90, 0xBC, 0x5B, + 0x44, 0x13, 0x6F, 0x7F, 0x62, 0xAB, 0x42, 0x9A, 0x83, 0xC8, 0xD4, 0x09, 0xA1, 0x49, 0xA6, 0x4F, + 0xDE, 0xE2, 0xDB, 0x7A, 0xF2, 0x82, 0xA7, 0x4A, 0xF5, 0x78, 0x57, 0xFC, 0x53, 0xA2, 0x48, 0xCE, + 0x9C, 0x9C, 0x26, 0xB5, 0xE5, 0x6D, 0xA1, 0xE3, 0x4A, 0x22, 0x2A, 0x5B, 0x87, 0xAE, 0x61, 0xC2, + 0xE4, 0xF4, 0x37, 0x6B, 0x45, 0xB5, 0x02, 0x95, 0x86, 0x4C, 0xC8, 0x52, 0x5B, 0xA6, 0xBA, 0xAE, + 0x58, 0x53, 0xB5, 0xD8, 0x2F, 0x41, 0x94, 0xEE, 0x79, 0x29, 0xB3, 0x7C, 0x31, 0x2A, 0xDC, 0xE2, + 0xBC, 0xB0, 0xF2, 0xCF, 0xF0, 0x28, 0xDE, 0x59, 0xE5, 0xDF, 0xF8, 0xAB, 0x8B, 0x86, 0x47, 0xFC, + 0x7F, 0x22, 0xF6, 0x5F, 0x04, 0x9C, 0x39, 0x76, 0x5C, 0x6C, 0x00, 0x00 +}; + + +//File: index_ov3660.html.gz, Size: 4408 +#define index_ov3660_html_gz_len 4408 +const uint8_t index_ov3660_html_gz[] = { + 0x1F, 0x8B, 0x08, 0x08, 0x28, 0x5C, 0xAE, 0x5C, 0x00, 0x03, 0x69, 0x6E, 0x64, 0x65, 0x78, 0x5F, + 0x6F, 0x76, 0x33, 0x36, 0x36, 0x30, 0x2E, 0x68, 0x74, 0x6D, 0x6C, 0x00, 0xE5, 0x5D, 0xEB, 0x92, + 0xD3, 0xC6, 0x12, 0xFE, 0xCF, 0x53, 0x08, 0x41, 0x58, 0x6F, 0x65, 0xED, 0xF5, 0x6D, 0xCD, 0xE2, + 0xD8, 0xE6, 0xC0, 0xB2, 0x84, 0x54, 0x01, 0x49, 0x20, 0x21, 0xA9, 0x4A, 0xA5, 0x60, 0x2C, 0x8D, + 0xED, 0x09, 0xB2, 0xE4, 0x48, 0x23, 0x7B, 0x37, 0xD4, 0x3E, 0xC7, 0x79, 0xA0, 0xF3, 0x62, 0xA7, + 0xE7, 0x22, 0x69, 0x24, 0x8F, 0x2E, 0xB6, 0x59, 0x9B, 0xC3, 0x31, 0x55, 0x20, 0x5B, 0xD3, 0x3D, + 0xDD, 0xFD, 0xF5, 0x6D, 0x46, 0x17, 0x06, 0x77, 0x6D, 0xCF, 0xA2, 0xD7, 0x0B, 0x6C, 0xCC, 0xE8, + 0xDC, 0x19, 0xDD, 0x19, 0x88, 0x7F, 0x0C, 0xF8, 0x0C, 0x66, 0x18, 0xD9, 0xE2, 0x90, 0x7F, 0x9D, + 0x63, 0x8A, 0x0C, 0x6B, 0x86, 0xFC, 0x00, 0xD3, 0xA1, 0x19, 0xD2, 0x49, 0xFD, 0xDC, 0xCC, 0x9E, + 0x76, 0xD1, 0x1C, 0x0F, 0xCD, 0x25, 0xC1, 0xAB, 0x85, 0xE7, 0x53, 0xD3, 0xB0, 0x3C, 0x97, 0x62, + 0x17, 0x86, 0xAF, 0x88, 0x4D, 0x67, 0x43, 0x1B, 0x2F, 0x89, 0x85, 0xEB, 0xFC, 0xCB, 0x09, 0x71, + 0x09, 0x25, 0xC8, 0xA9, 0x07, 0x16, 0x72, 0xF0, 0xB0, 0xA5, 0xF2, 0xA2, 0x84, 0x3A, 0x78, 0x74, + 0xF9, 0xF6, 0xA7, 0x4E, 0xDB, 0xF8, 0xF1, 0x5D, 0xA7, 0xD7, 0x6B, 0x0E, 0x4E, 0xC5, 0x6F, 0xC9, + 0x98, 0x80, 0x5E, 0xAB, 0xDF, 0xD9, 0x67, 0xEC, 0xD9, 0xD7, 0xC6, 0xA7, 0xD4, 0x4F, 0xEC, 0x33, + 0x01, 0x21, 0xEA, 0x13, 0x34, 0x27, 0xCE, 0x75, 0xDF, 0x78, 0xE2, 0xC3, 0x9C, 0x27, 0x2F, 0xB0, + 0xB3, 0xC4, 0x94, 0x58, 0xE8, 0x24, 0x40, 0x6E, 0x50, 0x0F, 0xB0, 0x4F, 0x26, 0xDF, 0xAD, 0x11, + 0x8E, 0x91, 0xF5, 0x71, 0xEA, 0x7B, 0xA1, 0x6B, 0xF7, 0x8D, 0x7B, 0xAD, 0x73, 0xF6, 0x67, 0x7D, + 0x90, 0xE5, 0x39, 0x9E, 0x0F, 0xE7, 0x2F, 0x9F, 0xB3, 0x3F, 0xEB, 0xE7, 0xF9, 0xEC, 0x01, 0xF9, + 0x07, 0xF7, 0x8D, 0x56, 0x6F, 0x71, 0x95, 0x3A, 0x7F, 0x73, 0x27, 0xF5, 0x75, 0xD6, 0xCE, 0x93, + 0x5E, 0xD2, 0x9F, 0x17, 0xD3, 0x07, 0xD8, 0xA2, 0xC4, 0x73, 0x1B, 0x73, 0x44, 0x5C, 0x0D, 0x27, + 0x9B, 0x04, 0x0B, 0x07, 0x81, 0x0D, 0x26, 0x0E, 0x2E, 0xE4, 0x73, 0x6F, 0x8E, 0xDD, 0xF0, 0xA4, + 0x84, 0x1B, 0x63, 0x52, 0xB7, 0x89, 0x2F, 0x46, 0xF5, 0x99, 0x1D, 0xC2, 0xB9, 0x5B, 0xCA, 0xB6, + 0x48, 0x2E, 0xD7, 0x73, 0xB1, 0xC6, 0x80, 0x6C, 0xA2, 0x95, 0x8F, 0x16, 0x6C, 0x00, 0xFB, 0x77, + 0x7D, 0xC8, 0x9C, 0xB8, 0xC2, 0xA9, 0xFA, 0x46, 0xA7, 0xDB, 0x5C, 0x5C, 0x95, 0x40, 0xD9, 0xE9, + 0xB1, 0x3F, 0xEB, 0x83, 0x16, 0xC8, 0xB6, 0x89, 0x3B, 0xED, 0x1B, 0xE7, 0x5A, 0x16, 0x9E, 0x6F, + 0x63, 0xBF, 0xEE, 0x23, 0x9B, 0x84, 0x41, 0xDF, 0xE8, 0xEA, 0xC6, 0xCC, 0x91, 0x3F, 0x05, 0x59, + 0xA8, 0x07, 0xC2, 0xD6, 0x5B, 0x5A, 0x49, 0xE4, 0x10, 0x9F, 0x4C, 0x67, 0x14, 0x20, 0x5D, 0x1B, + 0x93, 0x35, 0x9A, 0x0C, 0xA1, 0x32, 0x3C, 0x0B, 0xED, 0xA6, 0xB7, 0x1A, 0x72, 0xC8, 0xD4, 0xAD, + 0x13, 0x8A, 0xE7, 0xA0, 0x4E, 0x40, 0x7D, 0x4C, 0xAD, 0x59, 0x91, 0x28, 0x13, 0x32, 0x0D, 0x7D, + 0xAC, 0x11, 0x24, 0xB6, 0x5B, 0x81, 0xC2, 0x70, 0x72, 0xFD, 0x54, 0x7D, 0x85, 0xC7, 0x1F, 0x09, + 0xAD, 0x4B, 0x9B, 0x8C, 0xF1, 0xC4, 0xF3, 0xB1, 0x76, 0x64, 0x34, 0xC2, 0xF1, 0xAC, 0x8F, 0xF5, + 0x80, 0x22, 0x9F, 0x56, 0x61, 0x88, 0x26, 0x14, 0xFB, 0xE5, 0xFC, 0x30, 0xF3, 0x8A, 0x72, 0x6E, + 0xF9, 0xD3, 0xCA, 0x01, 0xC4, 0x75, 0x88, 0x8B, 0xAB, 0x8B, 0x97, 0x37, 0x6F, 0x9A, 0x9D, 0x18, + 0x55, 0x01, 0x18, 0x32, 0x9F, 0x16, 0x79, 0x09, 0xD7, 0x75, 0x7D, 0x32, 0x19, 0x37, 0xAD, 0x66, + 0xF3, 0x9B, 0xF5, 0x93, 0x33, 0x2C, 0xDC, 0x14, 0x85, 0xD4, 0xDB, 0x3D, 0x22, 0xD6, 0xC2, 0x2A, + 0xA3, 0xC7, 0xBF, 0xE6, 0xD8, 0x26, 0xC8, 0xA8, 0x29, 0xE1, 0x7C, 0xDE, 0x04, 0x9F, 0x3A, 0x36, + 0x90, 0x6B, 0x1B, 0x35, 0xCF, 0x27, 0x10, 0x08, 0x88, 0xA7, 0x1B, 0x07, 0x7E, 0x81, 0xC2, 0xB1, + 0xC0, 0xC7, 0x1A, 0x95, 0x0B, 0x62, 0x46, 0xB5, 0x88, 0x3E, 0x6C, 0xD8, 0xA7, 0x42, 0xCA, 0x61, + 0x9F, 0xD2, 0x00, 0xD2, 0xE8, 0xC8, 0xD9, 0x17, 0xE1, 0xA5, 0x4A, 0x98, 0x87, 0x19, 0xFB, 0xCC, + 0xD1, 0x55, 0xBD, 0x10, 0xBB, 0x68, 0x50, 0x84, 0x21, 0x94, 0x59, 0xAB, 0x06, 0x43, 0x97, 0x33, + 0xA3, 0x6E, 0xB0, 0x2C, 0x79, 0xAC, 0xA7, 0x91, 0x4C, 0xF5, 0x90, 0xB3, 0x8F, 0xEA, 0x14, 0x1B, + 0xA8, 0xAB, 0x57, 0x35, 0xC9, 0x1D, 0xE2, 0x8F, 0xCE, 0x87, 0x84, 0x26, 0xB9, 0x59, 0x84, 0x7D, + 0xAA, 0x67, 0x92, 0x84, 0x59, 0x69, 0x36, 0xD1, 0x30, 0xCE, 0xCF, 0x28, 0x6B, 0x7C, 0xF3, 0xA2, + 0x5B, 0xC3, 0xB5, 0x58, 0x84, 0xAA, 0xD9, 0x45, 0xC3, 0xB8, 0x48, 0x86, 0xD2, 0x2C, 0xC3, 0x3E, + 0x37, 0x15, 0xFA, 0x8D, 0x7B, 0xE3, 0x90, 0x52, 0xCF, 0x0D, 0x76, 0x2A, 0x51, 0x79, 0x71, 0xF6, + 0x57, 0x18, 0x50, 0x32, 0xB9, 0xAE, 0xCB, 0x90, 0x86, 0x38, 0x5B, 0x20, 0x68, 0x21, 0xC7, 0x98, + 0xAE, 0x30, 0x2E, 0x6E, 0x37, 0x5C, 0xB4, 0x84, 0xBC, 0x33, 0x9D, 0x3A, 0x3A, 0xDF, 0xB3, 0x42, + 0x3F, 0x60, 0x7D, 0xDB, 0xC2, 0x23, 0xC0, 0xD8, 0x5F, 0x9F, 0x38, 0x1D, 0x83, 0x15, 0x27, 0xAA, + 0x5B, 0x63, 0xCD, 0x5C, 0x5E, 0x48, 0x99, 0x8D, 0xB5, 0x48, 0x78, 0xA0, 0x0E, 0xA1, 0xD7, 0xDA, + 0x73, 0x32, 0x12, 0x35, 0x67, 0xA2, 0x10, 0x2C, 0x2C, 0x0B, 0x69, 0xB9, 0xFA, 0xD6, 0x0C, 0x5B, + 0x1F, 0xB1, 0xFD, 0x6D, 0x69, 0x1B, 0x56, 0xD6, 0x1E, 0x36, 0x88, 0xBB, 0x08, 0x69, 0x9D, 0xB5, + 0x53, 0x8B, 0x5B, 0xC1, 0x9C, 0x3B, 0x64, 0xA4, 0x62, 0xBB, 0x5D, 0xD4, 0x54, 0x9C, 0x2D, 0xAE, + 0x8A, 0x8D, 0xA0, 0x0A, 0x3B, 0x72, 0xD0, 0x18, 0x3B, 0x45, 0x22, 0xCB, 0x60, 0xC8, 0x49, 0xBB, + 0x32, 0x57, 0xE5, 0xF7, 0x6E, 0x5C, 0xB2, 0xA4, 0x78, 0x75, 0x1F, 0x7E, 0x53, 0xD9, 0x8E, 0xFC, + 0xF8, 0x24, 0xF5, 0x53, 0x80, 0x1D, 0x08, 0xB0, 0xBC, 0xD6, 0x1B, 0xC6, 0xAC, 0x40, 0x86, 0xC2, + 0x09, 0x7C, 0xE4, 0x4E, 0x31, 0xE4, 0x82, 0xAB, 0x93, 0xE8, 0xB0, 0x78, 0x61, 0x50, 0x49, 0x7D, + 0x96, 0xAA, 0xCF, 0x8A, 0x17, 0x22, 0x22, 0x21, 0x6C, 0xD1, 0x8C, 0x28, 0xB0, 0x16, 0xCE, 0xDF, + 0xD2, 0x3A, 0x85, 0xE8, 0x47, 0xB4, 0x01, 0x93, 0x76, 0x29, 0x6D, 0x7F, 0x5F, 0x9A, 0x11, 0xA2, + 0x95, 0xDE, 0x64, 0x52, 0xB6, 0x56, 0x9C, 0x4C, 0x3A, 0xCD, 0x4E, 0xB7, 0xB4, 0x61, 0xD2, 0x6A, + 0x99, 0x59, 0x2F, 0x6A, 0x32, 0x46, 0x9C, 0x4D, 0xCA, 0x21, 0xE8, 0xCF, 0xBC, 0x25, 0xF6, 0x35, + 0x40, 0x64, 0xC4, 0xED, 0x3E, 0xEA, 0xDA, 0x15, 0xB8, 0x21, 0xC8, 0xF7, 0x4B, 0x5D, 0x36, 0x4D, + 0xB3, 0x6B, 0xB7, 0xAC, 0x76, 0xA1, 0x63, 0x0A, 0x76, 0x0D, 0xF0, 0x06, 0x34, 0x76, 0xB0, 0x5D, + 0x90, 0x9E, 0x6D, 0x3C, 0x41, 0xA1, 0x43, 0x4B, 0xEC, 0x8D, 0x9A, 0xEC, 0x4F, 0xD1, 0x8C, 0x3C, + 0xAE, 0xFE, 0x60, 0x1B, 0x1D, 0x43, 0x1E, 0x09, 0x7F, 0x6A, 0xE6, 0x8C, 0x6A, 0x27, 0x5A, 0x2C, + 0x30, 0x82, 0x51, 0x16, 0xCE, 0x5B, 0x92, 0x56, 0xEA, 0x99, 0xF5, 0x89, 0xAB, 0xD2, 0x42, 0xB4, + 0xD4, 0x15, 0xE3, 0x6E, 0x68, 0x23, 0x9D, 0xFB, 0x13, 0xCF, 0x0A, 0x75, 0x65, 0xBA, 0x9A, 0x4B, + 0xAD, 0xF3, 0xEB, 0x47, 0x26, 0x0B, 0x1C, 0xC2, 0x1D, 0x3B, 0x74, 0x5D, 0x86, 0x68, 0x9D, 0xFA, + 0xA0, 0xA6, 0x66, 0xA2, 0x6A, 0x86, 0xDB, 0x2A, 0x3A, 0x53, 0x86, 0xCD, 0xDB, 0x8C, 0xC9, 0x04, + 0xA0, 0x26, 0x51, 0xC4, 0x39, 0xC4, 0x08, 0x3C, 0x50, 0x2A, 0x62, 0xB5, 0x9B, 0x5D, 0xE8, 0x2C, + 0x9C, 0xEB, 0x1A, 0x83, 0x68, 0xB2, 0x16, 0x54, 0x31, 0x31, 0x9D, 0x3F, 0x1D, 0xA3, 0x5A, 0xF3, + 0xA4, 0x79, 0xD2, 0x81, 0xBF, 0x34, 0x0D, 0x7A, 0xB1, 0x73, 0x49, 0xF3, 0xE6, 0x78, 0x5E, 0x26, + 0xF9, 0x94, 0xEF, 0x93, 0xE4, 0xA5, 0xB1, 0x52, 0x2C, 0xAA, 0x47, 0x52, 0x7A, 0xC3, 0xA4, 0xD5, + 0x28, 0x29, 0x2C, 0x39, 0x2E, 0xBD, 0xB9, 0x23, 0x6A, 0xBC, 0x65, 0x53, 0x88, 0xE7, 0xDE, 0x3F, + 0x75, 0x51, 0x55, 0xFF, 0xEF, 0xBD, 0x5D, 0x31, 0xC5, 0x57, 0xED, 0xE9, 0x1B, 0xDB, 0x25, 0x38, + 0xB4, 0x6F, 0x34, 0xF3, 0x51, 0xAF, 0xCB, 0x7E, 0x06, 0x24, 0x74, 0x61, 0x51, 0xE5, 0xC3, 0xEA, + 0x2A, 0xB7, 0xE7, 0x51, 0xC6, 0x6C, 0x61, 0x83, 0x09, 0x71, 0x9C, 0xBA, 0xE3, 0xAD, 0xCA, 0x3B, + 0x91, 0x62, 0x4F, 0x5E, 0xF3, 0xD3, 0x72, 0x97, 0xDF, 0x56, 0xDA, 0x10, 0x32, 0xD7, 0xFF, 0x84, + 0xB4, 0x5F, 0x77, 0xC0, 0x15, 0x86, 0xC6, 0x76, 0x85, 0x62, 0x0B, 0x7F, 0xDC, 0x6D, 0xA2, 0x4A, + 0xAE, 0x24, 0x3A, 0xC1, 0xC2, 0xC5, 0x5C, 0xB0, 0x22, 0xD4, 0x9A, 0x6D, 0xB1, 0xA8, 0x5A, 0x78, + 0x01, 0x11, 0xD7, 0x68, 0x7C, 0xEC, 0x20, 0xD6, 0xC1, 0x6F, 0xB5, 0xE4, 0x2E, 0x5D, 0x98, 0xA8, + 0xE4, 0x55, 0x34, 0xE1, 0xA6, 0xFB, 0x72, 0xB6, 0x4B, 0x1A, 0xA2, 0x77, 0xC8, 0xCF, 0xD5, 0x7A, + 0xB7, 0x2E, 0x69, 0xF7, 0xD3, 0x91, 0xA1, 0x1F, 0xB4, 0x41, 0x46, 0x8F, 0x92, 0xF6, 0xD4, 0xC7, + 0xD7, 0x15, 0x94, 0x39, 0x91, 0xFF, 0xF6, 0xC5, 0x86, 0xE8, 0xF6, 0x6B, 0x7F, 0x5E, 0x00, 0xA4, + 0x17, 0x35, 0xBA, 0x41, 0x85, 0xA9, 0xF3, 0xA7, 0xAC, 0xE2, 0x8F, 0xF1, 0x76, 0x9F, 0x69, 0x56, + 0x48, 0x37, 0x05, 0x25, 0x54, 0xEF, 0xAA, 0x51, 0xF5, 0xD5, 0x9E, 0x74, 0xF0, 0x84, 0xE6, 0x5C, + 0xCD, 0xE0, 0x7D, 0x6A, 0xA7, 0x38, 0xBB, 0xD5, 0x95, 0x7D, 0x82, 0xD2, 0xCC, 0x11, 0xEF, 0xCA, + 0xE5, 0x7B, 0x9F, 0x96, 0x33, 0xCB, 0x9E, 0x1B, 0x33, 0xCF, 0x87, 0x24, 0x6A, 0x9F, 0x39, 0xCC, + 0x30, 0x66, 0x2E, 0x4B, 0x3E, 0xC0, 0x83, 0x7F, 0xAF, 0xB5, 0x7B, 0xDA, 0x8B, 0x05, 0x05, 0x83, + 0x8B, 0x44, 0xCB, 0xDD, 0xD6, 0x5A, 0x2F, 0x59, 0xB9, 0x0B, 0x64, 0x35, 0x17, 0x69, 0x81, 0x2A, + 0x8E, 0xCA, 0xA2, 0x0C, 0xB3, 0xBE, 0x47, 0x53, 0xE8, 0xEC, 0x64, 0x8E, 0xA0, 0xED, 0x65, 0xEE, + 0x8A, 0x80, 0xA3, 0x0E, 0xBF, 0x2A, 0xEE, 0xAE, 0x6C, 0x1A, 0xB6, 0x7A, 0xCD, 0x92, 0x29, 0x2D, + 0xC7, 0x0B, 0x8A, 0xE3, 0x0A, 0x8D, 0xC1, 0x7E, 0x21, 0xD5, 0x4C, 0x24, 0xB7, 0x2E, 0xB5, 0x3B, + 0x4F, 0xDC, 0xB9, 0xB5, 0x67, 0x2A, 0x95, 0xEE, 0xC2, 0x98, 0x2A, 0x0E, 0xC7, 0x8C, 0xCD, 0x5B, + 0x4D, 0x6D, 0xA6, 0x2D, 0xDC, 0x7F, 0xA3, 0xF8, 0x0A, 0xD6, 0x9B, 0xEC, 0x82, 0x5C, 0xDF, 0xB0, + 0xB0, 0x3E, 0x8D, 0xA6, 0x8A, 0x5C, 0xAB, 0xCA, 0x26, 0x60, 0x21, 0x0E, 0x33, 0x62, 0xDB, 0xB8, + 0x70, 0x97, 0x93, 0xAD, 0x79, 0x2B, 0x36, 0x0F, 0x4C, 0x7E, 0xDD, 0xA6, 0xD4, 0xAD, 0x04, 0x45, + 0xE1, 0x75, 0xFA, 0xD6, 0x6D, 0x47, 0x8C, 0x2C, 0x34, 0x79, 0x7B, 0xC4, 0xE9, 0x56, 0xA4, 0x50, + 0x54, 0x6D, 0x70, 0xC7, 0xDB, 0xC4, 0xCC, 0x64, 0x60, 0x07, 0x36, 0x6A, 0x3D, 0x9B, 0x2B, 0x52, + 0x0D, 0x4E, 0x95, 0x7B, 0x89, 0x06, 0xA7, 0xC9, 0x6D, 0x4F, 0x03, 0x76, 0x43, 0x91, 0x7A, 0xCB, + 0x91, 0xB8, 0xDE, 0x65, 0x58, 0x0E, 0x0A, 0x82, 0xA1, 0xC9, 0x6E, 0x8C, 0x31, 0xD3, 0x77, 0x20, + 0x0D, 0x6C, 0xB2, 0x34, 0x88, 0x3D, 0x34, 0x1D, 0x6F, 0xEA, 0x65, 0xCE, 0xF1, 0xF3, 0xE2, 0x0A, + 0x04, 0x24, 0xCD, 0xA1, 0x99, 0xBA, 0x3A, 0x63, 0x72, 0xAA, 0xE4, 0x27, 0x73, 0xF4, 0xE0, 0xDE, + 0xA3, 0x87, 0x0F, 0x7B, 0xDF, 0x3D, 0x70, 0xC7, 0xC1, 0x42, 0xFE, 0xFD, 0x8B, 0xB8, 0x98, 0x25, + 0xEE, 0x88, 0x82, 0x3C, 0x4A, 0x29, 0xE8, 0x19, 0x0C, 0x4E, 0x39, 0xD3, 0x8C, 0x20, 0xA7, 0x20, + 0x49, 0x8E, 0x6C, 0xB2, 0xB6, 0xEA, 0xC4, 0x8B, 0x86, 0x04, 0x50, 0x2E, 0xC6, 0xC8, 0xD7, 0x0C, + 0xE1, 0xC3, 0x44, 0xE7, 0xC6, 0xFD, 0xD6, 0xE4, 0x35, 0x66, 0xEC, 0x5D, 0x65, 0x35, 0xE0, 0x4A, + 0xC9, 0x02, 0x24, 0x47, 0x61, 0x3B, 0x8F, 0x21, 0x90, 0x71, 0x72, 0x76, 0x69, 0x2A, 0x67, 0x4C, + 0x2C, 0x9F, 0xB4, 0xBE, 0x72, 0xA5, 0x44, 0x4C, 0x3D, 0xF1, 0xD1, 0x1C, 0x33, 0xF7, 0x97, 0x3F, + 0xE6, 0xB3, 0xC9, 0x22, 0x11, 0x53, 0x9A, 0xA3, 0x37, 0x98, 0x67, 0x4E, 0x40, 0x59, 0x6B, 0xD6, + 0x35, 0x2E, 0xB2, 0x98, 0xA5, 0xE6, 0x37, 0x23, 0x11, 0xE5, 0xE6, 0x75, 0x1D, 0x71, 0xB7, 0x29, + 0x11, 0x88, 0xB3, 0xF3, 0x16, 0xDC, 0xC1, 0x96, 0xC8, 0x09, 0xC1, 0xB4, 0xAD, 0x96, 0x39, 0xFA, + 0xF9, 0xF7, 0xEF, 0x9F, 0xD4, 0xDA, 0xCD, 0xEE, 0xF9, 0x55, 0xEB, 0xAC, 0xD7, 0x3D, 0x1E, 0x9C, + 0x8A, 0x21, 0x9B, 0xF3, 0x6A, 0x9A, 0xA3, 0x5F, 0x19, 0x2F, 0xA8, 0x2F, 0xCD, 0xAB, 0x56, 0xBB, + 0xD9, 0xDC, 0x9E, 0xD7, 0x23, 0x73, 0xF4, 0x96, 0xB3, 0x6A, 0x9F, 0x03, 0xAB, 0x66, 0x7B, 0x07, + 0xB1, 0xCE, 0xCD, 0x11, 0xE7, 0x04, 0x4C, 0xAE, 0x1E, 0xF6, 0xCE, 0xB7, 0x67, 0xF4, 0x10, 0x64, + 0x7A, 0x07, 0x9C, 0xCE, 0x41, 0xBB, 0xDE, 0x2E, 0xCA, 0xF5, 0xCC, 0x11, 0xE3, 0xD3, 0xEB, 0x36, + 0xAF, 0xBA, 0xE7, 0x3B, 0xF0, 0x39, 0x33, 0x65, 0xA7, 0xC3, 0xDC, 0x3F, 0x3A, 0x32, 0x47, 0x17, + 0x3F, 0x3C, 0xAF, 0x75, 0x41, 0xC6, 0xF6, 0xA3, 0xDE, 0xF6, 0xBC, 0xBB, 0xE0, 0x17, 0x4C, 0xC8, + 0x4E, 0x1B, 0x18, 0x75, 0x77, 0x10, 0xB2, 0x63, 0x8E, 0x5E, 0x70, 0x4E, 0xC0, 0xE5, 0xAA, 0xF5, + 0x70, 0x07, 0x91, 0xC0, 0xBD, 0x7E, 0xE6, 0x9C, 0xC0, 0xBF, 0x98, 0x7B, 0x55, 0xE4, 0x04, 0xB9, + 0x97, 0x9B, 0xA6, 0x20, 0xE6, 0xD7, 0x33, 0x59, 0xEA, 0x74, 0x51, 0x4A, 0xF8, 0x3B, 0x84, 0x8E, + 0x80, 0x5E, 0x6F, 0x9C, 0x10, 0x24, 0x1D, 0xA8, 0x24, 0x0E, 0xAA, 0xE5, 0x02, 0x45, 0x92, 0xF8, + 0x6A, 0xAB, 0x39, 0xEA, 0x96, 0x28, 0xC0, 0x49, 0xD5, 0x84, 0xCA, 0x69, 0x53, 0xF2, 0x9B, 0xAC, + 0x3F, 0x64, 0xA8, 0xB3, 0xFB, 0x79, 0xC0, 0x43, 0x3B, 0xA6, 0x12, 0xD5, 0x5B, 0x25, 0x1B, 0x8D, + 0xAC, 0xE8, 0xCA, 0x1C, 0xF5, 0x3A, 0x65, 0xD6, 0xDE, 0x01, 0x8C, 0x31, 0xEF, 0x3D, 0x5D, 0x1C, + 0x04, 0x1B, 0xE3, 0x91, 0x90, 0x9A, 0xA3, 0xA7, 0xF1, 0xF1, 0x2E, 0xA8, 0xD4, 0xCB, 0x34, 0xE5, + 0xB4, 0x39, 0xB0, 0x28, 0xE2, 0x08, 0x64, 0xEA, 0x1D, 0x09, 0x4D, 0x82, 0xCC, 0xE7, 0x05, 0xE6, + 0x36, 0x71, 0x61, 0xED, 0x80, 0x8F, 0x02, 0xBA, 0x31, 0x2A, 0x11, 0x21, 0x24, 0x35, 0x79, 0x74, + 0x30, 0x44, 0x62, 0x51, 0xBE, 0x02, 0x3C, 0x02, 0x44, 0x43, 0x9F, 0xDF, 0xE5, 0xB8, 0x31, 0x22, + 0x09, 0x29, 0x54, 0xC3, 0xF8, 0x78, 0x27, 0x54, 0x76, 0x49, 0x5F, 0x8A, 0x38, 0x12, 0x97, 0x28, + 0x85, 0x75, 0x6F, 0x09, 0x97, 0x32, 0x69, 0x77, 0xC2, 0x65, 0x86, 0xFC, 0xC5, 0x56, 0xE9, 0x2B, + 0xA6, 0x04, 0x54, 0xA2, 0xC3, 0x83, 0x85, 0x4A, 0x22, 0xCC, 0x57, 0x10, 0x2B, 0xB0, 0xFE, 0xF6, + 0x48, 0xB0, 0x79, 0xC7, 0x2F, 0xE9, 0xCC, 0xD1, 0x33, 0x5C, 0x7F, 0xCD, 0x8E, 0x76, 0x81, 0xE3, + 0x49, 0x48, 0xBD, 0x1D, 0x00, 0x89, 0x64, 0x11, 0x70, 0x34, 0x25, 0x1A, 0xE7, 0xB7, 0x84, 0xC6, + 0xF9, 0x2D, 0xA2, 0x81, 0xF0, 0x7B, 0x07, 0x2F, 0xB1, 0xB3, 0x31, 0x1C, 0x11, 0xA1, 0x39, 0xBA, + 0xBC, 0x5A, 0x78, 0x01, 0xBB, 0x5B, 0xF8, 0x25, 0xFB, 0xBE, 0x53, 0x90, 0x9C, 0xED, 0x80, 0x49, + 0x2C, 0x90, 0x8C, 0x91, 0x33, 0x89, 0xCA, 0xD9, 0x2D, 0xA1, 0x52, 0x26, 0xEB, 0x2E, 0xA8, 0x4C, + 0x11, 0x71, 0x2D, 0x4C, 0x1C, 0x76, 0xE7, 0xE2, 0xA6, 0xC0, 0x28, 0xB4, 0xE6, 0xE8, 0xFB, 0xE4, + 0xCB, 0x2E, 0xC0, 0x34, 0x77, 0xC0, 0x45, 0x95, 0x27, 0x1D, 0x2F, 0x67, 0xB0, 0x58, 0xBE, 0x25, + 0x6C, 0x5A, 0xAD, 0xDB, 0xAC, 0x2A, 0x0B, 0x6C, 0x11, 0xE4, 0xBC, 0xC7, 0x93, 0x09, 0x2C, 0x83, + 0x36, 0x2F, 0x2D, 0x29, 0x72, 0xA8, 0x2F, 0xE2, 0xBB, 0x71, 0xC9, 0xBF, 0x6F, 0xBC, 0x87, 0x91, + 0x61, 0xF7, 0xB9, 0x36, 0x32, 0x9A, 0xFA, 0xB5, 0xF0, 0x6B, 0x2F, 0x96, 0x73, 0xDB, 0x5D, 0x0D, + 0x60, 0x82, 0xA7, 0x7C, 0x53, 0x7D, 0x6B, 0x1E, 0x6D, 0xF0, 0x6C, 0x1F, 0x5D, 0xF3, 0xC7, 0x10, + 0x77, 0x59, 0x48, 0xBF, 0xC1, 0xB6, 0xF1, 0x0B, 0x71, 0xB7, 0x57, 0xA6, 0xCB, 0x04, 0xC1, 0xD8, + 0xDD, 0x8D, 0xCB, 0x19, 0x2C, 0x91, 0xE0, 0x60, 0x37, 0x26, 0x3D, 0xF0, 0x24, 0xBC, 0x20, 0xE8, + 0x4B, 0x58, 0xC4, 0xA3, 0xD5, 0x78, 0xF3, 0x82, 0xB2, 0x1A, 0x43, 0x5D, 0xFE, 0xED, 0xA9, 0x71, + 0xC9, 0x6F, 0x03, 0xDB, 0x38, 0x5D, 0x89, 0x2B, 0xD4, 0x55, 0x1C, 0x5D, 0x24, 0x2A, 0x29, 0xA7, + 0xB9, 0xB6, 0x27, 0xAA, 0x0F, 0xA0, 0xAA, 0xFB, 0xA2, 0x1A, 0xF5, 0x22, 0x01, 0xF9, 0x05, 0x3D, + 0x53, 0xD1, 0xB6, 0x9A, 0x8E, 0xB7, 0xD8, 0x8A, 0x59, 0xAB, 0xCD, 0xDB, 0x30, 0x6B, 0x05, 0x30, + 0xD9, 0x4B, 0x76, 0x87, 0xA0, 0x6D, 0x00, 0x5E, 0x7B, 0x01, 0x8A, 0xCD, 0x7A, 0x18, 0xA0, 0xB8, + 0xBE, 0x87, 0x06, 0x0A, 0xBC, 0xE5, 0x3D, 0xAB, 0xA3, 0xDB, 0x04, 0x15, 0x27, 0x34, 0x47, 0xAF, + 0x90, 0x1B, 0x42, 0x91, 0xD9, 0x17, 0x60, 0xF1, 0xC4, 0x07, 0x0B, 0x2F, 0xA9, 0xF7, 0xA1, 0xA1, + 0x03, 0x41, 0xE6, 0x9E, 0xBD, 0xF9, 0x72, 0x47, 0xD2, 0x89, 0x94, 0xF8, 0x0A, 0x8E, 0x36, 0x6E, + 0x0C, 0x22, 0x0E, 0xB7, 0xDC, 0x11, 0x88, 0xA5, 0xD4, 0xF6, 0xCD, 0xC0, 0xDB, 0xD0, 0x75, 0xAF, + 0x77, 0xE9, 0x04, 0x2E, 0x1C, 0x2F, 0xB4, 0xB7, 0xE7, 0x00, 0x6D, 0xC0, 0x8F, 0x93, 0x09, 0xB1, + 0xB6, 0x6F, 0x24, 0xA0, 0x09, 0x78, 0xE1, 0xCD, 0x2B, 0xD2, 0xDF, 0x72, 0xE1, 0xC5, 0xD6, 0x16, + 0x2B, 0x39, 0x0B, 0x50, 0xBC, 0xBC, 0xD8, 0x6B, 0xE1, 0x85, 0x39, 0x0F, 0x94, 0x19, 0x98, 0xB6, + 0x87, 0x4E, 0x0A, 0x20, 0xC4, 0x7B, 0xEE, 0x3C, 0xDB, 0x80, 0x25, 0x28, 0xE3, 0x8C, 0x1E, 0x2D, + 0xBF, 0x0F, 0xB5, 0xBE, 0x4B, 0x24, 0x4A, 0xAF, 0xEE, 0x5A, 0x67, 0x9D, 0x5E, 0xBC, 0xBC, 0xEB, + 0xB4, 0x3F, 0xEF, 0x02, 0x8F, 0x31, 0xBF, 0x5D, 0x7C, 0xDA, 0xDB, 0x40, 0x03, 0xD9, 0xE8, 0x35, + 0xBB, 0xCE, 0xB0, 0x41, 0xC2, 0xDE, 0x3D, 0x90, 0xDA, 0x87, 0x8B, 0xA4, 0xF6, 0x17, 0x10, 0x4A, + 0xD3, 0x2D, 0x32, 0xDE, 0x94, 0x65, 0xBC, 0xEF, 0x2F, 0xF6, 0x83, 0xD0, 0xF4, 0x60, 0xA9, 0x6E, + 0x7A, 0xD0, 0x54, 0x67, 0x88, 0x9B, 0xAD, 0x62, 0x98, 0xB6, 0xEC, 0x60, 0x25, 0xA1, 0xD8, 0xCB, + 0xDA, 0x25, 0xC9, 0xB5, 0xAE, 0x76, 0xC9, 0x72, 0x91, 0x18, 0xE9, 0x24, 0xD7, 0x4B, 0xAE, 0x8A, + 0x9C, 0x7D, 0xDE, 0xCB, 0xBA, 0xDD, 0x32, 0x69, 0x77, 0x09, 0x1A, 0x1F, 0xAD, 0xDE, 0x4F, 0xE7, + 0x68, 0x63, 0x30, 0x24, 0x1D, 0x60, 0xF1, 0xEA, 0xC9, 0x3E, 0xDB, 0x85, 0x68, 0xDE, 0xC3, 0xC4, + 0x51, 0xAC, 0xF5, 0xA1, 0x73, 0x9D, 0x83, 0xDD, 0xCD, 0x93, 0x1D, 0x23, 0x32, 0x47, 0x2F, 0xB1, + 0x1B, 0x18, 0x17, 0x9E, 0x2F, 0xDF, 0xFD, 0xB4, 0x17, 0xD4, 0xF8, 0xCC, 0x87, 0x81, 0x4C, 0x28, + 0x7D, 0x68, 0xBC, 0x66, 0x73, 0xE2, 0xFB, 0x9E, 0xBF, 0x31, 0x64, 0x92, 0x0E, 0x96, 0x15, 0xF5, + 0x57, 0xFC, 0x68, 0x2F, 0x70, 0x45, 0xB3, 0x1E, 0x06, 0xB1, 0x58, 0xE7, 0x43, 0x83, 0xB6, 0x9C, + 0x38, 0x64, 0xB1, 0x31, 0x64, 0x9C, 0xCA, 0x1C, 0xBD, 0xAB, 0x3F, 0x87, 0x7F, 0xF7, 0x02, 0x97, + 0x98, 0xF1, 0x30, 0x60, 0x49, 0x6D, 0x0F, 0x0D, 0xD5, 0x78, 0xB1, 0x79, 0x3A, 0x04, 0x1A, 0x73, + 0xF4, 0xF4, 0xA7, 0xFD, 0xF4, 0x7E, 0x6C, 0xB2, 0x8A, 0x08, 0xED, 0x84, 0x07, 0x57, 0xEA, 0xD0, + 0x68, 0xAC, 0xB6, 0x40, 0x63, 0xC5, 0x04, 0xFF, 0x6D, 0x4F, 0x68, 0xAC, 0xAA, 0xA3, 0xF1, 0x99, + 0xE3, 0x65, 0xF5, 0x25, 0xE0, 0xC3, 0x9F, 0xC5, 0x18, 0xA3, 0xCD, 0xCB, 0x51, 0x44, 0xC8, 0x6E, + 0x1A, 0x83, 0x23, 0xE3, 0x29, 0xDA, 0x4F, 0x41, 0x8A, 0xE7, 0xDD, 0x47, 0x08, 0x25, 0x4A, 0x1E, + 0x1A, 0xA7, 0x09, 0xB2, 0xF0, 0x7B, 0x1B, 0xD3, 0x6D, 0xAE, 0x2D, 0x2B, 0xB4, 0xE6, 0xE8, 0x39, + 0x7C, 0x31, 0x9E, 0xF1, 0x2F, 0xFB, 0x6A, 0xF9, 0xD4, 0xF9, 0xF7, 0x81, 0x5A, 0x4A, 0xDF, 0x2F, + 0x02, 0x38, 0x68, 0xB0, 0xBD, 0xA9, 0xBB, 0xD5, 0x23, 0x0D, 0x29, 0x72, 0x09, 0xDF, 0x1B, 0xF1, + 0x7D, 0xBF, 0x00, 0x26, 0x42, 0xEC, 0x0D, 0x43, 0x45, 0xEF, 0x7D, 0xC0, 0x18, 0x3D, 0x16, 0xC4, + 0x8B, 0xB4, 0x78, 0x15, 0x5E, 0x19, 0x52, 0xF2, 0xE1, 0x27, 0x7E, 0x4B, 0x0B, 0xA6, 0xF5, 0x80, + 0x12, 0xC7, 0x81, 0x85, 0x30, 0xA6, 0xC6, 0x5B, 0x76, 0x38, 0x38, 0x15, 0x03, 0xAA, 0x73, 0x91, + 0xCF, 0xDC, 0xB0, 0x97, 0x50, 0xA2, 0xB9, 0x39, 0x7A, 0xCB, 0x5E, 0x12, 0x08, 0xBC, 0xD8, 0xB7, + 0xCD, 0x99, 0x71, 0x23, 0x62, 0xD7, 0xF7, 0x40, 0xA8, 0x18, 0x24, 0xF9, 0xAE, 0x26, 0xD3, 0x88, + 0x8E, 0x94, 0xDF, 0x46, 0x97, 0x7C, 0xB0, 0xC1, 0xBC, 0xAC, 0x7C, 0x3A, 0x76, 0xD5, 0xC2, 0xCA, + 0xBF, 0xB8, 0x31, 0x38, 0x75, 0x91, 0xC6, 0xDC, 0x39, 0x28, 0x0C, 0xC4, 0xDB, 0x25, 0x73, 0x58, + 0xC5, 0xCF, 0x33, 0x71, 0x4B, 0x24, 0x8F, 0x69, 0xC6, 0x6A, 0x65, 0x1F, 0xDF, 0x94, 0xDB, 0x4C, + 0xD5, 0x82, 0x96, 0x3F, 0x88, 0x29, 0xEB, 0x21, 0x3B, 0x8C, 0xCD, 0xFF, 0x9F, 0x7F, 0x97, 0xF9, + 0x0C, 0x7B, 0xF7, 0x67, 0x22, 0x98, 0x69, 0x04, 0xBE, 0x35, 0x34, 0xF3, 0x9E, 0x8E, 0xCA, 0xD1, + 0xFC, 0x54, 0xA7, 0x7A, 0x66, 0xB0, 0xC6, 0xD6, 0x83, 0xC0, 0xF2, 0xC9, 0x82, 0x8E, 0xEE, 0xD8, + 0x9E, 0x15, 0xCE, 0xB1, 0x4B, 0x1B, 0xC8, 0xB6, 0x2F, 0x97, 0x70, 0xF0, 0x92, 0x04, 0x14, 0x83, + 0x15, 0x6A, 0x47, 0xCF, 0x7E, 0x7C, 0x75, 0x21, 0x9E, 0x12, 0x7B, 0xE9, 0x21, 0x1B, 0xDB, 0x47, + 0x27, 0xC6, 0x24, 0x74, 0x85, 0x9B, 0xD7, 0x30, 0x1B, 0x2B, 0xDE, 0xBB, 0xBA, 0x44, 0xBE, 0x31, + 0x46, 0x01, 0x7E, 0xE1, 0x05, 0xD4, 0x18, 0x1A, 0x31, 0x47, 0xC7, 0xB3, 0xF8, 0x7D, 0xBF, 0x0D, + 0xCF, 0x27, 0x53, 0xE2, 0xCA, 0x91, 0x42, 0xD9, 0x5F, 0x7D, 0x07, 0x86, 0xC6, 0x54, 0xDF, 0x1A, + 0x47, 0xFD, 0xF3, 0xD6, 0x11, 0x7B, 0x1C, 0x0F, 0x60, 0x80, 0x1F, 0x00, 0x02, 0x0C, 0x03, 0x20, + 0xC0, 0x87, 0x23, 0xF9, 0x78, 0x20, 0x76, 0x1A, 0xDC, 0xE4, 0x4C, 0x40, 0x26, 0x6D, 0xED, 0x48, + 0xE0, 0x74, 0xC4, 0x1E, 0x34, 0xBE, 0x89, 0x29, 0x83, 0x99, 0xB7, 0x2A, 0xA2, 0xF4, 0xF1, 0xDC, + 0x5B, 0xE2, 0x0C, 0x71, 0x4C, 0x2D, 0xBD, 0xB9, 0x74, 0xEA, 0xC8, 0xEB, 0x8F, 0x8E, 0xA3, 0x01, + 0xF1, 0x7B, 0xCC, 0x86, 0x06, 0xF5, 0x43, 0x9C, 0x66, 0x8B, 0xDD, 0x32, 0xAE, 0x91, 0x58, 0x85, + 0x8C, 0x27, 0xC8, 0x09, 0x32, 0x9C, 0xC3, 0x85, 0x8D, 0x28, 0x7E, 0xC7, 0x76, 0x0C, 0x61, 0x40, + 0x0D, 0x3B, 0x27, 0x62, 0xFB, 0xF0, 0x44, 0x9E, 0x79, 0x03, 0x7C, 0x29, 0x3E, 0x4E, 0x66, 0x55, + 0x7F, 0x06, 0x8A, 0xF4, 0xD7, 0xA1, 0xE1, 0x86, 0x10, 0xC2, 0x8F, 0xB9, 0x0A, 0x46, 0x3F, 0x75, + 0x96, 0x53, 0x3B, 0x90, 0x9D, 0xE4, 0x3B, 0xDB, 0xF9, 0x9C, 0xFC, 0x47, 0x32, 0x61, 0x13, 0x37, + 0xF8, 0x1B, 0xE4, 0x87, 0xC0, 0xE3, 0x28, 0xCA, 0xEE, 0x47, 0xC9, 0x8B, 0x79, 0x55, 0x22, 0x6E, + 0x87, 0x86, 0xEC, 0x83, 0xE5, 0xF9, 0xA5, 0x3C, 0x71, 0xF7, 0xEE, 0x32, 0xE6, 0x6B, 0x28, 0xC3, + 0xE0, 0x54, 0x72, 0xE2, 0x06, 0x4E, 0x28, 0x4F, 0x3F, 0xAF, 0xF3, 0xCE, 0xF0, 0x88, 0x98, 0x2B, + 0x1C, 0xEE, 0xC4, 0x92, 0xA7, 0x2C, 0xF0, 0xE0, 0x41, 0x9A, 0xDB, 0xDD, 0xA1, 0xA4, 0x4A, 0x34, + 0x11, 0xE3, 0x21, 0x32, 0x20, 0xF2, 0x40, 0x6D, 0xF9, 0x4C, 0xBC, 0x14, 0x89, 0x4C, 0x6A, 0x77, + 0x53, 0x86, 0x8F, 0x65, 0x9C, 0x30, 0x13, 0x11, 0x9B, 0x1B, 0x88, 0x5F, 0x33, 0x3C, 0x4E, 0x9E, + 0x7A, 0x15, 0xF2, 0x3D, 0xE6, 0x5E, 0x5F, 0xC3, 0xF2, 0xF2, 0xDB, 0x31, 0xD8, 0x9F, 0x39, 0x73, + 0xF2, 0x83, 0x1C, 0x9F, 0x4C, 0xA5, 0x72, 0x9C, 0xA6, 0x38, 0x32, 0xC5, 0x32, 0x72, 0xB3, 0x0F, + 0x9F, 0x00, 0x86, 0xB2, 0x9D, 0xEF, 0xE4, 0xF9, 0xFC, 0x8C, 0x39, 0xD9, 0x87, 0x4F, 0xBC, 0x3E, + 0xB0, 0x50, 0x82, 0xE8, 0x0E, 0x09, 0x8D, 0x62, 0x9C, 0xDD, 0x6A, 0xCC, 0x54, 0xE2, 0x22, 0xC0, + 0x61, 0x11, 0xAB, 0x4C, 0x01, 0xD7, 0x30, 0x14, 0x01, 0x55, 0x13, 0xF5, 0xE9, 0x29, 0xAF, 0x35, + 0x8C, 0xB9, 0x8C, 0x95, 0xF4, 0xEF, 0x77, 0x54, 0xE1, 0x6F, 0xA2, 0xF0, 0x89, 0x53, 0x99, 0x8A, + 0x27, 0xF3, 0xE3, 0xC8, 0x62, 0xCC, 0xD5, 0x13, 0x87, 0x91, 0xAF, 0x2B, 0x89, 0xFC, 0x3C, 0x31, + 0xAB, 0x05, 0x39, 0x4C, 0xF1, 0xF8, 0x7E, 0x46, 0x54, 0xD5, 0xD5, 0x41, 0xEE, 0x96, 0xA1, 0xBE, + 0x80, 0x64, 0x0C, 0xA9, 0xF0, 0x63, 0x8A, 0x0F, 0xDF, 0xB0, 0x8F, 0x99, 0x88, 0xDF, 0xC4, 0xE5, + 0xFD, 0xBA, 0xE7, 0x62, 0x3D, 0x77, 0xD5, 0xD9, 0x75, 0x3C, 0x45, 0x29, 0xCE, 0x32, 0x0D, 0xC7, + 0x73, 0x42, 0x35, 0x0C, 0x8F, 0x20, 0x0D, 0xEB, 0x78, 0xC9, 0x06, 0x2D, 0x21, 0xF0, 0x31, 0x0D, + 0x7D, 0x57, 0x8D, 0x26, 0x91, 0x91, 0xFE, 0x0E, 0xB1, 0x7F, 0x0D, 0x8C, 0x3E, 0xDC, 0xFF, 0x14, + 0xE5, 0xF7, 0x9B, 0x53, 0xFE, 0x6C, 0x8E, 0xE7, 0x3C, 0x86, 0x0A, 0x30, 0xBC, 0xFF, 0x89, 0x43, + 0x7D, 0xF3, 0x00, 0xA6, 0x84, 0x2F, 0x7C, 0xE2, 0x9B, 0x0F, 0x82, 0xC5, 0x84, 0xBD, 0x3E, 0xBB, + 0xC6, 0x59, 0x44, 0xB8, 0x35, 0xE8, 0x0C, 0xBB, 0x35, 0x1F, 0x07, 0x0B, 0x60, 0x8F, 0x93, 0x44, + 0x16, 0xCD, 0xE8, 0x39, 0x18, 0x4A, 0xCD, 0xB4, 0xF6, 0xC1, 0xC7, 0x40, 0x07, 0x02, 0x50, 0xCF, + 0xB8, 0xFF, 0x89, 0xB3, 0xB8, 0x31, 0x26, 0x10, 0xCD, 0xC1, 0x0C, 0xDB, 0x27, 0x50, 0x77, 0x10, + 0x65, 0x4F, 0xA6, 0xDF, 0xFF, 0x14, 0xB1, 0x6A, 0x88, 0x9F, 0x6E, 0x3E, 0xC4, 0x1E, 0x12, 0x17, + 0x83, 0xA8, 0x86, 0xF1, 0x13, 0x0D, 0xCE, 0xEB, 0x2D, 0x47, 0xC1, 0xF3, 0x9F, 0x38, 0x4E, 0xED, + 0x48, 0xBC, 0x7E, 0x41, 0xE6, 0xE8, 0x06, 0x34, 0x9D, 0x97, 0x08, 0xC4, 0x56, 0x93, 0x3B, 0xCF, + 0x3B, 0x9E, 0x6B, 0x39, 0xC4, 0xFA, 0xC8, 0x12, 0xF3, 0x71, 0x5A, 0x70, 0x11, 0xE9, 0x4E, 0x43, + 0xBC, 0x4E, 0xEB, 0xB5, 0x67, 0xE3, 0x8C, 0x9B, 0x1E, 0x33, 0x31, 0x4E, 0x4F, 0xC1, 0xCA, 0xC8, + 0x8E, 0x52, 0x92, 0xC0, 0x88, 0xBD, 0x77, 0x45, 0x98, 0x29, 0x65, 0x61, 0xA1, 0x8C, 0xD4, 0x45, + 0xD8, 0x2C, 0xA9, 0xD6, 0x91, 0xCA, 0x89, 0xDB, 0x0A, 0xF4, 0x8C, 0xD8, 0x16, 0x7F, 0x05, 0x9E, + 0x5B, 0x3B, 0xBE, 0x13, 0x9B, 0x61, 0x9D, 0x07, 0x9B, 0x40, 0x61, 0x90, 0x32, 0x51, 0x9E, 0x99, + 0xD2, 0x5D, 0xFD, 0x51, 0x92, 0x49, 0x72, 0x6C, 0x26, 0x3E, 0x4A, 0x4D, 0xE3, 0x05, 0x8D, 0xCF, + 0xFC, 0x07, 0x77, 0x9A, 0x3F, 0x4F, 0x44, 0x11, 0x54, 0x72, 0xD2, 0xB1, 0x62, 0x30, 0xE1, 0x81, + 0xEC, 0xBF, 0x1E, 0x51, 0x1B, 0x11, 0xE8, 0xAE, 0x2F, 0x1D, 0xCC, 0x0E, 0x9F, 0x5E, 0xFF, 0x00, + 0xC5, 0x5B, 0xB4, 0x20, 0x5C, 0x9A, 0x84, 0xE0, 0x22, 0x6E, 0xFF, 0x4A, 0x29, 0x93, 0x56, 0x51, + 0xE1, 0xC1, 0xDB, 0x77, 0x91, 0x71, 0x8A, 0x38, 0xC4, 0x9D, 0x7E, 0x8A, 0x94, 0x71, 0x2D, 0xA7, + 0x4D, 0xF5, 0xF7, 0x0A, 0xBD, 0x9A, 0xED, 0x8A, 0xE8, 0x95, 0x96, 0x5E, 0xA1, 0xE6, 0xAE, 0x5C, + 0x4E, 0xAC, 0x36, 0xB7, 0x47, 0x8A, 0xB1, 0x03, 0xEA, 0x2D, 0xC4, 0x1A, 0x23, 0xE3, 0xE6, 0x2B, + 0xE2, 0xDA, 0xDE, 0xAA, 0xC1, 0xCE, 0xD7, 0x64, 0x91, 0x54, 0x15, 0x6D, 0x10, 0x17, 0x0C, 0xF8, + 0xE2, 0x97, 0x57, 0x2F, 0x59, 0xD2, 0x51, 0xD7, 0x2A, 0x47, 0xE9, 0x0E, 0x87, 0xBF, 0xEB, 0x5C, + 0x3B, 0x03, 0x83, 0xAD, 0x01, 0x4D, 0xB3, 0x48, 0x36, 0x71, 0x63, 0xC9, 0x62, 0x81, 0x1D, 0x7E, + 0x10, 0x73, 0xB2, 0xD2, 0x93, 0x02, 0xF8, 0xB8, 0x54, 0x16, 0x6F, 0x91, 0x15, 0x05, 0x22, 0xF1, + 0x09, 0xA5, 0xE0, 0xB0, 0x86, 0x70, 0xE5, 0x80, 0x65, 0x19, 0xB9, 0xCE, 0xBB, 0x63, 0xA8, 0xE0, + 0xE7, 0x04, 0x7D, 0x62, 0x26, 0x19, 0x65, 0x69, 0xE1, 0x95, 0x4C, 0x89, 0x16, 0x10, 0x99, 0xF8, + 0xF1, 0x7B, 0x6B, 0x0C, 0xC9, 0xF1, 0x19, 0x78, 0x7E, 0xC3, 0x05, 0x0D, 0x8E, 0x6F, 0x8A, 0xD4, + 0x11, 0xE6, 0x4A, 0x80, 0xAC, 0x2A, 0x04, 0x4F, 0x43, 0x7A, 0x6E, 0x29, 0xFB, 0xE8, 0xD9, 0xA9, + 0xDE, 0x2B, 0xAE, 0xDD, 0xB2, 0x36, 0x2D, 0xCF, 0xB0, 0xC3, 0x75, 0xD3, 0x8A, 0x3E, 0x25, 0xC5, + 0x20, 0x49, 0x30, 0x6B, 0xC2, 0x66, 0xDA, 0x14, 0xC5, 0x2F, 0xA2, 0x01, 0x91, 0xEC, 0x6A, 0x40, + 0xE4, 0xC8, 0x9E, 0xEE, 0xE2, 0x32, 0xED, 0x42, 0x06, 0x72, 0x99, 0xC5, 0x0C, 0xF6, 0xD6, 0x8F, + 0x19, 0x2B, 0xD0, 0xD2, 0x09, 0xAA, 0x14, 0x0A, 0x6D, 0x06, 0x2C, 0xAC, 0x18, 0x62, 0x86, 0x48, + 0xDA, 0x6C, 0xB7, 0x99, 0xAE, 0x0E, 0x17, 0x21, 0x58, 0x69, 0x1E, 0xF9, 0xA4, 0xF8, 0x8D, 0xB5, + 0x6C, 0x71, 0xF0, 0x40, 0x0B, 0x57, 0x14, 0xD4, 0x70, 0x5A, 0xC9, 0x04, 0xB2, 0xDF, 0x2B, 0x21, + 0x50, 0xEE, 0xBA, 0xE0, 0xB4, 0xF0, 0xD3, 0xBA, 0xD8, 0x1A, 0x23, 0xC3, 0xB8, 0xE3, 0x18, 0x73, + 0x46, 0x24, 0xBB, 0xA2, 0x04, 0xF1, 0xF5, 0xEE, 0x34, 0x0B, 0xF9, 0x5A, 0x57, 0x7A, 0xA3, 0xA0, + 0x15, 0xDD, 0xB7, 0x96, 0xE8, 0x83, 0x8B, 0x95, 0xC7, 0xAA, 0xF2, 0x51, 0x97, 0x5D, 0x42, 0xA1, + 0xDE, 0x65, 0x27, 0xD4, 0xC7, 0x15, 0xD5, 0xC7, 0x52, 0x7D, 0x46, 0x90, 0x34, 0x84, 0xE5, 0x2D, + 0x7F, 0xEC, 0x8C, 0xBF, 0x3D, 0x4D, 0x34, 0x5B, 0x8D, 0x0B, 0xE5, 0x94, 0xAD, 0xB8, 0xA2, 0x5E, + 0x31, 0x41, 0xEA, 0x9E, 0x62, 0xA1, 0xD6, 0x6A, 0x5C, 0x4D, 0xAD, 0xA8, 0x95, 0x67, 0x04, 0x89, + 0x5A, 0xFA, 0x86, 0x3F, 0x52, 0x25, 0xDE, 0x42, 0xE6, 0xFF, 0xA7, 0x4B, 0xFC, 0xCE, 0x94, 0x58, + 0x58, 0xB1, 0xFF, 0x5A, 0x5A, 0xCA, 0xC4, 0x30, 0x45, 0xC9, 0x78, 0xC9, 0x50, 0x4A, 0x1A, 0x8F, + 0x54, 0xA8, 0x63, 0x39, 0x0A, 0xA9, 0xA3, 0x41, 0xA2, 0x06, 0xC6, 0x5F, 0x2B, 0x19, 0x2B, 0x1E, + 0x9D, 0x04, 0x42, 0xC2, 0x40, 0x34, 0xE0, 0x23, 0xE3, 0x2C, 0xBB, 0xD4, 0x14, 0x8D, 0x90, 0x50, + 0x36, 0xD3, 0xFE, 0xA8, 0x03, 0x62, 0x95, 0x52, 0x63, 0xE2, 0x00, 0x11, 0xF4, 0x79, 0x62, 0x96, + 0x8A, 0x82, 0x1C, 0xEC, 0xD3, 0x9A, 0xF9, 0x93, 0x83, 0xD9, 0xF2, 0x41, 0xDE, 0x14, 0x7E, 0xF1, + 0xC3, 0x73, 0xC3, 0xF3, 0x0D, 0xF1, 0x16, 0x4D, 0x3F, 0x7E, 0x6B, 0x8E, 0x21, 0x5F, 0x31, 0xC7, + 0x17, 0x69, 0xC4, 0x9D, 0x1A, 0x74, 0x46, 0x02, 0xE8, 0x59, 0xD9, 0x93, 0xE0, 0xF8, 0xAE, 0x19, + 0xBF, 0x45, 0xAE, 0x54, 0x3D, 0xD1, 0xA4, 0x7E, 0x17, 0x2B, 0x92, 0x31, 0xA7, 0xA0, 0x49, 0x6C, + 0x79, 0x57, 0xEA, 0xB8, 0x96, 0x58, 0x8A, 0x96, 0x85, 0x1B, 0x98, 0x30, 0x3E, 0xFD, 0xC5, 0x5A, + 0x51, 0xAF, 0x40, 0xA9, 0x21, 0x63, 0xB2, 0xC4, 0x96, 0x89, 0xAE, 0x6B, 0xD6, 0xD4, 0xAD, 0xBD, + 0x0B, 0x10, 0x65, 0x5B, 0x49, 0xDA, 0x6C, 0x9E, 0x8F, 0x8A, 0xB0, 0xB8, 0xA8, 0x72, 0xE2, 0x33, + 0x38, 0x8D, 0x36, 0x2C, 0xC5, 0x37, 0xF1, 0x52, 0xAE, 0xC1, 0xA9, 0xF8, 0x9F, 0x0A, 0xFF, 0x0B, + 0x9B, 0xFC, 0x8E, 0x51, 0xC1, 0x70, 0x00, 0x00 +}; + diff --git a/libraries/ESP32/examples/Camera/CameraWebServer/camera_pins.h b/libraries/ESP32/examples/Camera/CameraWebServer/camera_pins.h new file mode 100644 index 00000000000..7855722a408 --- /dev/null +++ b/libraries/ESP32/examples/Camera/CameraWebServer/camera_pins.h @@ -0,0 +1,99 @@ + +#if defined(CAMERA_MODEL_WROVER_KIT) +#define PWDN_GPIO_NUM -1 +#define RESET_GPIO_NUM -1 +#define XCLK_GPIO_NUM 21 +#define SIOD_GPIO_NUM 26 +#define SIOC_GPIO_NUM 27 + +#define Y9_GPIO_NUM 35 +#define Y8_GPIO_NUM 34 +#define Y7_GPIO_NUM 39 +#define Y6_GPIO_NUM 36 +#define Y5_GPIO_NUM 19 +#define Y4_GPIO_NUM 18 +#define Y3_GPIO_NUM 5 +#define Y2_GPIO_NUM 4 +#define VSYNC_GPIO_NUM 25 +#define HREF_GPIO_NUM 23 +#define PCLK_GPIO_NUM 22 + +#elif defined(CAMERA_MODEL_ESP_EYE) +#define PWDN_GPIO_NUM -1 +#define RESET_GPIO_NUM -1 +#define XCLK_GPIO_NUM 4 +#define SIOD_GPIO_NUM 18 +#define SIOC_GPIO_NUM 23 + +#define Y9_GPIO_NUM 36 +#define Y8_GPIO_NUM 37 +#define Y7_GPIO_NUM 38 +#define Y6_GPIO_NUM 39 +#define Y5_GPIO_NUM 35 +#define Y4_GPIO_NUM 14 +#define Y3_GPIO_NUM 13 +#define Y2_GPIO_NUM 34 +#define VSYNC_GPIO_NUM 5 +#define HREF_GPIO_NUM 27 +#define PCLK_GPIO_NUM 25 + +#elif defined(CAMERA_MODEL_M5STACK_PSRAM) +#define PWDN_GPIO_NUM -1 +#define RESET_GPIO_NUM 15 +#define XCLK_GPIO_NUM 27 +#define SIOD_GPIO_NUM 25 +#define SIOC_GPIO_NUM 23 + +#define Y9_GPIO_NUM 19 +#define Y8_GPIO_NUM 36 +#define Y7_GPIO_NUM 18 +#define Y6_GPIO_NUM 39 +#define Y5_GPIO_NUM 5 +#define Y4_GPIO_NUM 34 +#define Y3_GPIO_NUM 35 +#define Y2_GPIO_NUM 32 +#define VSYNC_GPIO_NUM 22 +#define HREF_GPIO_NUM 26 +#define PCLK_GPIO_NUM 21 + +#elif defined(CAMERA_MODEL_M5STACK_WIDE) +#define PWDN_GPIO_NUM -1 +#define RESET_GPIO_NUM 15 +#define XCLK_GPIO_NUM 27 +#define SIOD_GPIO_NUM 22 +#define SIOC_GPIO_NUM 23 + +#define Y9_GPIO_NUM 19 +#define Y8_GPIO_NUM 36 +#define Y7_GPIO_NUM 18 +#define Y6_GPIO_NUM 39 +#define Y5_GPIO_NUM 5 +#define Y4_GPIO_NUM 34 +#define Y3_GPIO_NUM 35 +#define Y2_GPIO_NUM 32 +#define VSYNC_GPIO_NUM 25 +#define HREF_GPIO_NUM 26 +#define PCLK_GPIO_NUM 21 + +#elif defined(CAMERA_MODEL_AI_THINKER) +#define PWDN_GPIO_NUM 32 +#define RESET_GPIO_NUM -1 +#define XCLK_GPIO_NUM 0 +#define SIOD_GPIO_NUM 26 +#define SIOC_GPIO_NUM 27 + +#define Y9_GPIO_NUM 35 +#define Y8_GPIO_NUM 34 +#define Y7_GPIO_NUM 39 +#define Y6_GPIO_NUM 36 +#define Y5_GPIO_NUM 21 +#define Y4_GPIO_NUM 19 +#define Y3_GPIO_NUM 18 +#define Y2_GPIO_NUM 5 +#define VSYNC_GPIO_NUM 25 +#define HREF_GPIO_NUM 23 +#define PCLK_GPIO_NUM 22 + +#else +#error "Camera model not selected" +#endif diff --git a/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ExternalWakeUp.ino b/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ExternalWakeUp.ino index 09c88782ad6..8a13b77196d 100644 --- a/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ExternalWakeUp.ino +++ b/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ExternalWakeUp.ino @@ -36,12 +36,12 @@ void print_wakeup_reason(){ switch(wakeup_reason) { - case 1 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; - case 2 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; - case 3 : Serial.println("Wakeup caused by timer"); break; - case 4 : Serial.println("Wakeup caused by touchpad"); break; - case 5 : Serial.println("Wakeup caused by ULP program"); break; - default : Serial.println("Wakeup was not caused by deep sleep"); break; + case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; + case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; + case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; + case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; + case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; + default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; } } @@ -69,7 +69,7 @@ void setup(){ esp_sleep_enable_ext0_wakeup(GPIO_NUM_33,1); //1 = High, 0 = Low //If you were to use ext1, you would use it like - //esp_deep_sleep_enable_ext1_wakeup(BUTTON_PIN_BITMASK,ESP_EXT1_WAKEUP_ANY_HIGH); + //esp_sleep_enable_ext1_wakeup(BUTTON_PIN_BITMASK,ESP_EXT1_WAKEUP_ANY_HIGH); //Go to sleep now Serial.println("Going to sleep now"); diff --git a/libraries/ESP32/examples/DeepSleep/TimerWakeUp/TimerWakeUp.ino b/libraries/ESP32/examples/DeepSleep/TimerWakeUp/TimerWakeUp.ino index 423ef828556..ec43cf72ea7 100644 --- a/libraries/ESP32/examples/DeepSleep/TimerWakeUp/TimerWakeUp.ino +++ b/libraries/ESP32/examples/DeepSleep/TimerWakeUp/TimerWakeUp.ino @@ -19,7 +19,7 @@ Author: Pranav Cherukupalli */ -#define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */ +#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */ #define TIME_TO_SLEEP 5 /* Time ESP32 will go to sleep (in seconds) */ RTC_DATA_ATTR int bootCount = 0; @@ -35,12 +35,12 @@ void print_wakeup_reason(){ switch(wakeup_reason) { - case 1 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; - case 2 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; - case 3 : Serial.println("Wakeup caused by timer"); break; - case 4 : Serial.println("Wakeup caused by touchpad"); break; - case 5 : Serial.println("Wakeup caused by ULP program"); break; - default : Serial.println("Wakeup was not caused by deep sleep"); break; + case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; + case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; + case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; + case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; + case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; + default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; } } @@ -84,6 +84,7 @@ void setup(){ reset occurs. */ Serial.println("Going to sleep now"); + Serial.flush(); esp_deep_sleep_start(); Serial.println("This will never be printed"); } diff --git a/libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino b/libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino index e6784049983..76f48b757a4 100644 --- a/libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino +++ b/libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino @@ -26,12 +26,12 @@ void print_wakeup_reason(){ switch(wakeup_reason) { - case 1 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; - case 2 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; - case 3 : Serial.println("Wakeup caused by timer"); break; - case 4 : Serial.println("Wakeup caused by touchpad"); break; - case 5 : Serial.println("Wakeup caused by ULP program"); break; - default : Serial.println("Wakeup was not caused by deep sleep"); break; + case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; + case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; + case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; + case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; + case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; + default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; } } @@ -40,8 +40,6 @@ Method to print the touchpad by which ESP32 has been awaken from sleep */ void print_wakeup_touchpad(){ - touch_pad_t pin; - touchPin = esp_sleep_get_touchpad_wakeup_status(); switch(touchPin) diff --git a/libraries/ESP32/examples/ESPNow/Basic/Master/Master.ino b/libraries/ESP32/examples/ESPNow/Basic/Master/Master.ino index 26e020f68f0..1cb9fb98845 100644 --- a/libraries/ESP32/examples/ESPNow/Basic/Master/Master.ino +++ b/libraries/ESP32/examples/ESPNow/Basic/Master/Master.ino @@ -40,6 +40,7 @@ esp_now_peer_info_t slave; // Init ESP Now with fallback void InitESPNow() { + WiFi.disconnect(); if (esp_now_init() == ESP_OK) { Serial.println("ESPNow Init Success"); } @@ -87,7 +88,7 @@ void ScanForSlave() { Serial.print(i + 1); Serial.print(": "); Serial.print(SSID); Serial.print(" ["); Serial.print(BSSIDstr); Serial.print("]"); Serial.print(" ("); Serial.print(RSSI); Serial.print(")"); Serial.println(""); // Get BSSID => Mac Address of the Slave int mac[6]; - if ( 6 == sscanf(BSSIDstr.c_str(), "%x:%x:%x:%x:%x:%x%c", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5] ) ) { + if ( 6 == sscanf(BSSIDstr.c_str(), "%x:%x:%x:%x:%x:%x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5] ) ) { for (int ii = 0; ii < 6; ++ii ) { slave.peer_addr[ii] = (uint8_t) mac[ii]; } @@ -123,17 +124,15 @@ bool manageSlave() { } Serial.print("Slave Status: "); - const esp_now_peer_info_t *peer = &slave; - const uint8_t *peer_addr = slave.peer_addr; // check if the peer exists - bool exists = esp_now_is_peer_exist(peer_addr); + bool exists = esp_now_is_peer_exist(slave.peer_addr); if ( exists) { // Slave already paired. Serial.println("Already Paired"); return true; } else { // Slave not paired, attempt pair - esp_err_t addStatus = esp_now_add_peer(peer); + esp_err_t addStatus = esp_now_add_peer(&slave); if (addStatus == ESP_OK) { // Pair success Serial.println("Pair success"); @@ -167,9 +166,7 @@ bool manageSlave() { } void deletePeer() { - const esp_now_peer_info_t *peer = &slave; - const uint8_t *peer_addr = slave.peer_addr; - esp_err_t delStatus = esp_now_del_peer(peer_addr); + esp_err_t delStatus = esp_now_del_peer(slave.peer_addr); Serial.print("Slave Delete Status: "); if (delStatus == ESP_OK) { // Delete success @@ -259,4 +256,4 @@ void loop() { // wait for 3seconds to run the logic again delay(3000); -} \ No newline at end of file +} diff --git a/libraries/ESP32/examples/ESPNow/Basic/Slave/Slave.ino b/libraries/ESP32/examples/ESPNow/Basic/Slave/Slave.ino index 21e963b8b19..d9029e961e3 100644 --- a/libraries/ESP32/examples/ESPNow/Basic/Slave/Slave.ino +++ b/libraries/ESP32/examples/ESPNow/Basic/Slave/Slave.ino @@ -36,6 +36,7 @@ // Init ESP Now with fallback void InitESPNow() { + WiFi.disconnect(); if (esp_now_init() == ESP_OK) { Serial.println("ESPNow Init Success"); } @@ -50,7 +51,7 @@ void InitESPNow() { // config AP SSID void configDeviceAP() { - char* SSID = "Slave_1"; + const char *SSID = "Slave_1"; bool result = WiFi.softAP(SSID, "Slave_1_Password", CHANNEL, 0); if (!result) { Serial.println("AP Config failed."); @@ -87,4 +88,4 @@ void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) { void loop() { // Chill -} \ No newline at end of file +} diff --git a/libraries/ESP32/examples/ESPNow/Multi-Slave/Master/Master.ino b/libraries/ESP32/examples/ESPNow/Multi-Slave/Master/Master.ino index 87b8c331a1d..6e212dd1121 100644 --- a/libraries/ESP32/examples/ESPNow/Multi-Slave/Master/Master.ino +++ b/libraries/ESP32/examples/ESPNow/Multi-Slave/Master/Master.ino @@ -59,6 +59,7 @@ int SlaveCnt = 0; // Init ESP Now with fallback void InitESPNow() { + WiFi.disconnect(); if (esp_now_init() == ESP_OK) { Serial.println("ESPNow Init Success"); } @@ -99,7 +100,7 @@ void ScanForSlave() { // Get BSSID => Mac Address of the Slave int mac[6]; - if ( 6 == sscanf(BSSIDstr.c_str(), "%x:%x:%x:%x:%x:%x%c", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5] ) ) { + if ( 6 == sscanf(BSSIDstr.c_str(), "%x:%x:%x:%x:%x:%x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5] ) ) { for (int ii = 0; ii < 6; ++ii ) { slaves[SlaveCnt].peer_addr[ii] = (uint8_t) mac[ii]; } @@ -126,8 +127,6 @@ void ScanForSlave() { void manageSlave() { if (SlaveCnt > 0) { for (int i = 0; i < SlaveCnt; i++) { - const esp_now_peer_info_t *peer = &slaves[i]; - const uint8_t *peer_addr = slaves[i].peer_addr; Serial.print("Processing: "); for (int ii = 0; ii < 6; ++ii ) { Serial.print((uint8_t) slaves[i].peer_addr[ii], HEX); @@ -135,13 +134,13 @@ void manageSlave() { } Serial.print(" Status: "); // check if the peer exists - bool exists = esp_now_is_peer_exist(peer_addr); + bool exists = esp_now_is_peer_exist(slaves[i].peer_addr); if (exists) { // Slave already paired. Serial.println("Already Paired"); } else { // Slave not paired, attempt pair - esp_err_t addStatus = esp_now_add_peer(peer); + esp_err_t addStatus = esp_now_add_peer(&slaves[i]); if (addStatus == ESP_OK) { // Pair success Serial.println("Pair success"); @@ -242,4 +241,4 @@ void loop() { // wait for 3seconds to run the logic again delay(1000); -} \ No newline at end of file +} diff --git a/libraries/ESP32/examples/ESPNow/Multi-Slave/Slave/Slave.ino b/libraries/ESP32/examples/ESPNow/Multi-Slave/Slave/Slave.ino index 8837d9c1b8d..42ce40ba0d1 100644 --- a/libraries/ESP32/examples/ESPNow/Multi-Slave/Slave/Slave.ino +++ b/libraries/ESP32/examples/ESPNow/Multi-Slave/Slave/Slave.ino @@ -36,6 +36,7 @@ // Init ESP Now with fallback void InitESPNow() { + WiFi.disconnect(); if (esp_now_init() == ESP_OK) { Serial.println("ESPNow Init Success"); } @@ -90,4 +91,4 @@ void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) { void loop() { // Chill -} \ No newline at end of file +} diff --git a/libraries/ESP32/examples/FreeRTOS/FreeRTOS.ino b/libraries/ESP32/examples/FreeRTOS/FreeRTOS.ino new file mode 100644 index 00000000000..9f9fcdca349 --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/FreeRTOS.ino @@ -0,0 +1,97 @@ +#if CONFIG_FREERTOS_UNICORE +#define ARDUINO_RUNNING_CORE 0 +#else +#define ARDUINO_RUNNING_CORE 1 +#endif + +#ifndef LED_BUILTIN +#define LED_BUILTIN 13 +#endif + +// define two tasks for Blink & AnalogRead +void TaskBlink( void *pvParameters ); +void TaskAnalogReadA3( void *pvParameters ); + +// the setup function runs once when you press reset or power the board +void setup() { + + // initialize serial communication at 115200 bits per second: + Serial.begin(115200); + + // Now set up two tasks to run independently. + xTaskCreatePinnedToCore( + TaskBlink + , "TaskBlink" // A name just for humans + , 1024 // This stack size can be checked & adjusted by reading the Stack Highwater + , NULL + , 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest. + , NULL + , ARDUINO_RUNNING_CORE); + + xTaskCreatePinnedToCore( + TaskAnalogReadA3 + , "AnalogReadA3" + , 1024 // Stack size + , NULL + , 1 // Priority + , NULL + , ARDUINO_RUNNING_CORE); + + // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started. +} + +void loop() +{ + // Empty. Things are done in Tasks. +} + +/*--------------------------------------------------*/ +/*---------------------- Tasks ---------------------*/ +/*--------------------------------------------------*/ + +void TaskBlink(void *pvParameters) // This is a task. +{ + (void) pvParameters; + +/* + Blink + Turns on an LED on for one second, then off for one second, repeatedly. + + If you want to know what pin the on-board LED is connected to on your ESP32 model, check + the Technical Specs of your board. +*/ + + // initialize digital LED_BUILTIN on pin 13 as an output. + pinMode(LED_BUILTIN, OUTPUT); + + for (;;) // A Task shall never return or exit. + { + digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) + vTaskDelay(100); // one tick delay (15ms) in between reads for stability + digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW + vTaskDelay(100); // one tick delay (15ms) in between reads for stability + } +} + +void TaskAnalogReadA3(void *pvParameters) // This is a task. +{ + (void) pvParameters; + +/* + AnalogReadSerial + Reads an analog input on pin A3, prints the result to the serial monitor. + Graphical representation is available using serial plotter (Tools > Serial Plotter menu) + Attach the center pin of a potentiometer to pin A3, and the outside pins to +5V and ground. + + This example code is in the public domain. +*/ + + for (;;) + { + // read the input on analog pin A3: + int sensorValueA3 = analogRead(A3); + // print out the value you read: + Serial.println(sensorValueA3); + vTaskDelay(10); // one tick delay (15ms) in between reads for stability + } +} diff --git a/libraries/ESP32/examples/GPIO/FunctionalInterrupt/FunctionalInterrupt.ino b/libraries/ESP32/examples/GPIO/FunctionalInterrupt/FunctionalInterrupt.ino new file mode 100644 index 00000000000..0e9f97414bb --- /dev/null +++ b/libraries/ESP32/examples/GPIO/FunctionalInterrupt/FunctionalInterrupt.ino @@ -0,0 +1,47 @@ +#include +#include + +#define BUTTON1 16 +#define BUTTON2 17 + +class Button +{ +public: + Button(uint8_t reqPin) : PIN(reqPin){ + pinMode(PIN, INPUT_PULLUP); + attachInterrupt(PIN, std::bind(&Button::isr,this), FALLING); + }; + ~Button() { + detachInterrupt(PIN); + } + + void IRAM_ATTR isr() { + numberKeyPresses += 1; + pressed = true; + } + + void checkPressed() { + if (pressed) { + Serial.printf("Button on pin %u has been pressed %u times\n", PIN, numberKeyPresses); + pressed = false; + } + } + +private: + const uint8_t PIN; + volatile uint32_t numberKeyPresses; + volatile bool pressed; +}; + +Button button1(BUTTON1); +Button button2(BUTTON2); + + +void setup() { + Serial.begin(115200); +} + +void loop() { + button1.checkPressed(); + button2.checkPressed(); +} diff --git a/libraries/ESP32/examples/GPIO/GPIOInterrupt/GPIOInterrupt.ino b/libraries/ESP32/examples/GPIO/GPIOInterrupt/GPIOInterrupt.ino new file mode 100644 index 00000000000..c3d1245fa0c --- /dev/null +++ b/libraries/ESP32/examples/GPIO/GPIOInterrupt/GPIOInterrupt.ino @@ -0,0 +1,45 @@ +#include + +struct Button { + const uint8_t PIN; + uint32_t numberKeyPresses; + bool pressed; +}; + +Button button1 = {23, 0, false}; +Button button2 = {18, 0, false}; + +void IRAM_ATTR isr(void* arg) { + Button* s = static_cast(arg); + s->numberKeyPresses += 1; + s->pressed = true; +} + +void IRAM_ATTR isr() { + button2.numberKeyPresses += 1; + button2.pressed = true; +} + +void setup() { + Serial.begin(115200); + pinMode(button1.PIN, INPUT_PULLUP); + attachInterruptArg(button1.PIN, isr, &button1, FALLING); + pinMode(button2.PIN, INPUT_PULLUP); + attachInterrupt(button2.PIN, isr, FALLING); +} + +void loop() { + if (button1.pressed) { + Serial.printf("Button 1 has been pressed %u times\n", button1.numberKeyPresses); + button1.pressed = false; + } + if (button2.pressed) { + Serial.printf("Button 2 has been pressed %u times\n", button2.numberKeyPresses); + button2.pressed = false; + } + static uint32_t lastMillis = 0; + if (millis() - lastMillis > 10000) { + lastMillis = millis(); + detachInterrupt(button1.PIN); + } +} diff --git a/libraries/ESP32/examples/I2S/HiFreq_ADC/HiFreq_ADC.ino b/libraries/ESP32/examples/I2S/HiFreq_ADC/HiFreq_ADC.ino new file mode 100644 index 00000000000..df328d1d6b1 --- /dev/null +++ b/libraries/ESP32/examples/I2S/HiFreq_ADC/HiFreq_ADC.ino @@ -0,0 +1,83 @@ +/* + * This is an example to read analog data at high frequency using the I2S peripheral + * Run a wire between pins 27 & 32 + * The readings from the device will be 12bit (0-4096) + */ +#include + +#define I2S_SAMPLE_RATE 78125 +#define ADC_INPUT ADC1_CHANNEL_4 //pin 32 +#define OUTPUT_PIN 27 +#define OUTPUT_VALUE 3800 +#define READ_DELAY 9000 //microseconds + +uint16_t adc_reading; + +void i2sInit() +{ + i2s_config_t i2s_config = { + .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN), + .sample_rate = I2S_SAMPLE_RATE, // The format of the signal using ADC_BUILT_IN + .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, // is fixed at 12bit, stereo, MSB + .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, + .communication_format = I2S_COMM_FORMAT_I2S_MSB, + .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, + .dma_buf_count = 4, + .dma_buf_len = 8, + .use_apll = false, + .tx_desc_auto_clear = false, + .fixed_mclk = 0 + }; + i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL); + i2s_set_adc_mode(ADC_UNIT_1, ADC_INPUT); + i2s_adc_enable(I2S_NUM_0); +} + +void reader(void *pvParameters) { + uint32_t read_counter = 0; + uint64_t read_sum = 0; +// The 4 high bits are the channel, and the data is inverted + uint16_t offset = (int)ADC_INPUT * 0x1000 + 0xFFF; + size_t bytes_read; + while(1){ + uint16_t buffer[2] = {0}; + i2s_read(I2S_NUM_0, &buffer, sizeof(buffer), &bytes_read, 15); + //Serial.printf("%d %d\n", offset - buffer[0], offset - buffer[1]); + if (bytes_read == sizeof(buffer)) { + read_sum += offset - buffer[0]; + read_sum += offset - buffer[1]; + read_counter++; + } else { + Serial.println("buffer empty"); + } + if (read_counter == I2S_SAMPLE_RATE) { + adc_reading = read_sum / I2S_SAMPLE_RATE / 2; + //Serial.printf("avg: %d millis: ", adc_reading); + //Serial.println(millis()); + read_counter = 0; + read_sum = 0; + i2s_adc_disable(I2S_NUM_0); + delay(READ_DELAY); + i2s_adc_enable(I2S_NUM_0); + } + } +} + +void setup() { + Serial.begin(115200); + // Put a signal out on pin + uint32_t freq = ledcSetup(0, I2S_SAMPLE_RATE, 10); + Serial.printf("Output frequency: %d\n", freq); + ledcWrite(0, OUTPUT_VALUE/4); + ledcAttachPin(OUTPUT_PIN, 0); + // Initialize the I2S peripheral + i2sInit(); + // Create a task that will read the data + xTaskCreatePinnedToCore(reader, "ADC_reader", 2048, NULL, 1, NULL, 1); +} + +void loop() { + delay(1020); + Serial.printf("ADC reading: %d\n", adc_reading); + delay(READ_DELAY); +} diff --git a/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino b/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino new file mode 100644 index 00000000000..54f2d2c983c --- /dev/null +++ b/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino @@ -0,0 +1,61 @@ +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "Arduino.h" + +#include "esp32-hal.h" + +rmt_data_t my_data[256]; +rmt_data_t data[256]; + +rmt_obj_t* rmt_send = NULL; +rmt_obj_t* rmt_recv = NULL; + +static EventGroupHandle_t events; + +void setup() +{ + Serial.begin(115200); + + if ((rmt_send = rmtInit(18, true, RMT_MEM_64)) == NULL) + { + Serial.println("init sender failed\n"); + } + if ((rmt_recv = rmtInit(21, false, RMT_MEM_192)) == NULL) + { + Serial.println("init receiver failed\n"); + } + + float realTick = rmtSetTick(rmt_send, 100); + printf("real tick set to: %fns\n", realTick); + +} + +void loop() +{ + // Init data + int i; + for (i=0; i<255; i++) { + data[i].val = 0x80010001 + ((i%13)<<16) + 13-(i%13); + } + data[255].val = 0; + + // Start receiving + rmtReadAsync(rmt_recv, my_data, 100, events, false, 0); + + // Send in continous mode + rmtWrite(rmt_send, data, 100); + + // Wait for data + xEventGroupWaitBits(events, RMT_FLAG_RX_DONE, 1, 1, portMAX_DELAY); + + // Printout the received data plus the original values + for (i=0; i<60; i++) + { + Serial.printf("%08x=%08x ", my_data[i].val, data[i].val ); + if (!((i+1)%4)) Serial.println("\n"); + } + Serial.println("\n"); + + delay(2000); +} diff --git a/libraries/ESP32/examples/RMT/RMTReadXJT/RMTReadXJT.ino b/libraries/ESP32/examples/RMT/RMTReadXJT/RMTReadXJT.ino new file mode 100644 index 00000000000..29ab824d79d --- /dev/null +++ b/libraries/ESP32/examples/RMT/RMTReadXJT/RMTReadXJT.ino @@ -0,0 +1,203 @@ +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "Arduino.h" + +#include "esp32-hal.h" + +// +// Note: This example uses a FrSKY device communication +// using XJT D12 protocol +// +// ; 0 bit = 6us low/10us high +// ; 1 bit = 14us low/10us high +// ; +// ; --------+ +----------+ +----------+ +// ; | | | | | +// ; | 0 | | 1 | | +// ; | | | | | +// ; | | | | | +// ; +-------+ +-----------------+ +--------- +// ; +// ; | 6us 10us | 14us 10us | +// ; |-------|----------|-----------------|----------|-------- +// ; | 16us | 24us | + +// Typedef of received frame +// +// ; 0x00 - Sync, 0x7E (sync header ID) +// ; 0x01 - Rx ID, 0x?? (receiver ID number, 0x00-0x??) +// ; 0x02 - Flags 1, 0x?? (used for failsafe and binding) +// ; 0x03 - Flags 2, 0x00 (reserved) +// ; 0x04-0x06, Channels 1/9 and 2/10 +// ; 0x07-0x09, Channels 3/11 and 4/12 +// ; 0x0A-0x0C, Channels 5/13 and 6/14 +// ; 0x0D-0x0F, Channels 7/15 and 8/16 +// ; 0x10 - 0x00, always zero +// ; 0x11 - CRC-16 High +// ; 0x12 - CRC-16 Low +// ; 0x13 - Tail, 0x7E (tail ID) +typedef union { + struct { + uint8_t head;//0x7E + uint8_t rxid;//Receiver Number + uint8_t flags;//Range:0x20, Bind:0x01 + uint8_t reserved0;//0x00 + union { + struct { + uint8_t ch0_l; + uint8_t ch0_h:4; + uint8_t ch1_l:4; + uint8_t ch1_h; + }; + uint8_t bytes[3]; + } channels[4]; + uint8_t reserved1;//0x00 + uint8_t crc_h; + uint8_t crc_l; + uint8_t tail;//0x7E + }; + uint8_t buffer[20]; +} xjt_packet_t; + +#define XJT_VALID(i) (i->level0 && !i->level1 && i->duration0 >= 8 && i->duration0 <= 11) + +rmt_obj_t* rmt_recv = NULL; + +static uint32_t *s_channels; +static uint32_t channels[16]; +static uint8_t xjt_flags = 0x0; +static uint8_t xjt_rxid = 0x0; + +static bool xjtReceiveBit(size_t index, bool bit){ + static xjt_packet_t xjt; + static uint8_t xjt_bit_index = 8; + static uint8_t xht_byte_index = 0; + static uint8_t xht_ones = 0; + + if(!index){ + xjt_bit_index = 8; + xht_byte_index = 0; + xht_ones = 0; + } + + if(xht_byte_index > 19){ + //fail! + return false; + } + if(bit){ + xht_ones++; + if(xht_ones > 5 && xht_byte_index && xht_byte_index < 19){ + //fail! + return false; + } + //add bit + xjt.buffer[xht_byte_index] |= (1 << --xjt_bit_index); + } else if(xht_ones == 5 && xht_byte_index && xht_byte_index < 19){ + xht_ones = 0; + //skip bit + return true; + } else { + xht_ones = 0; + //add bit + xjt.buffer[xht_byte_index] &= ~(1 << --xjt_bit_index); + } + if ((!xjt_bit_index) || (xjt_bit_index==1 && xht_byte_index==19) ) { + xjt_bit_index = 8; + if(!xht_byte_index && xjt.buffer[0] != 0x7E){ + //fail! + return false; + } + xht_byte_index++; + if(xht_byte_index == 20){ + //done + if(xjt.buffer[19] != 0x7E){ + //fail! + return false; + } + //check crc? + + xjt_flags = xjt.flags; + xjt_rxid = xjt.rxid; + for(int i=0; i<4; i++){ + uint16_t ch0 = xjt.channels[i].ch0_l | ((uint16_t)(xjt.channels[i].ch0_h & 0x7) << 8); + ch0 = ((ch0 * 2) + 2452) / 3; + uint16_t ch1 = xjt.channels[i].ch1_l | ((uint16_t)(xjt.channels[i].ch1_h & 0x7F) << 4); + ch1 = ((ch1 * 2) + 2452) / 3; + uint8_t c0n = i*2; + if(xjt.channels[i].ch0_h & 0x8){ + c0n += 8; + } + uint8_t c1n = i*2+1; + if(xjt.channels[i].ch1_h & 0x80){ + c1n += 8; + } + s_channels[c0n] = ch0; + s_channels[c1n] = ch1; + } + } + } + return true; +} + +void parseRmt(rmt_data_t* items, size_t len, uint32_t* channels){ + bool valid = true; + rmt_data_t* it = NULL; + + if (!channels) { + log_e("Please provide data block for storing channel info"); + return; + } + s_channels = channels; + + it = &items[0]; + for(size_t i = 0; iduration1 >= 5 && it->duration1 <= 8){ + valid = xjtReceiveBit(i, false); + } else if(it->duration1 >= 13 && it->duration1 <= 16){ + valid = xjtReceiveBit(i, true); + } else { + valid = false; + } + } else if(!it->duration1 && !it->level1 && it->duration0 >= 5 && it->duration0 <= 8) { + valid = xjtReceiveBit(i, false); + + } + } +} + +extern "C" void receive_data(uint32_t *data, size_t len) +{ + parseRmt((rmt_data_t*) data, len, channels); +} + +void setup() +{ + Serial.begin(115200); + + // Initialize the channel to capture up to 192 items + if ((rmt_recv = rmtInit(21, false, RMT_MEM_192)) == NULL) + { + Serial.println("init receiver failed\n"); + } + + // Setup 1us tick + float realTick = rmtSetTick(rmt_recv, 1000); + Serial.printf("real tick set to: %fns\n", realTick); + + // Ask to start reading + rmtRead(rmt_recv, receive_data); +} + +void loop() +{ + // printout some of the channels + Serial.printf("%04x %04x %04x %04x\n", channels[0], channels[1], channels[2], channels[3]); + delay(500); +} diff --git a/libraries/ESP32/examples/RMT/RMTWriteNeoPixel/RMTWriteNeoPixel.ino b/libraries/ESP32/examples/RMT/RMTWriteNeoPixel/RMTWriteNeoPixel.ino new file mode 100644 index 00000000000..5067140fbd6 --- /dev/null +++ b/libraries/ESP32/examples/RMT/RMTWriteNeoPixel/RMTWriteNeoPixel.ino @@ -0,0 +1,89 @@ +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "Arduino.h" + +#include "esp32-hal.h" + +#define NR_OF_LEDS 8*4 +#define NR_OF_ALL_BITS 24*NR_OF_LEDS + +// +// Note: This example uses Neopixel LED board, 32 LEDs chained one +// after another, each RGB LED has its 24 bit value +// for color configuration (8b for each color) +// +// Bits encoded as pulses as follows: +// +// "0": +// +-------+ +-- +// | | | +// | | | +// | | | +// ---| |--------------| +// + + + +// | 0.4us | 0.85 0us | +// +// "1": +// +-------------+ +-- +// | | | +// | | | +// | | | +// | | | +// ---+ +-------+ +// | 0.8us | 0.4us | + +rmt_data_t led_data[NR_OF_ALL_BITS]; + +rmt_obj_t* rmt_send = NULL; + +void setup() +{ + Serial.begin(115200); + + if ((rmt_send = rmtInit(18, true, RMT_MEM_64)) == NULL) + { + Serial.println("init sender failed\n"); + } + + float realTick = rmtSetTick(rmt_send, 100); + Serial.printf("real tick set to: %fns\n", realTick); + +} + +int color[] = { 0x55, 0x11, 0x77 }; // RGB value +int led_index = 0; + +void loop() +{ + // Init data with only one led ON + int led, col, bit; + int i=0; + for (led=0; led=NR_OF_LEDS) { + led_index = 0; + } + + // Send the data + rmtWrite(rmt_send, led_data, NR_OF_ALL_BITS); + + delay(100); +} diff --git a/libraries/ESP32/examples/Timer/WatchdogTimer/WatchdogTimer.ino b/libraries/ESP32/examples/Timer/WatchdogTimer/WatchdogTimer.ino index bfe4a9f0e1c..056cab9640c 100644 --- a/libraries/ESP32/examples/Timer/WatchdogTimer/WatchdogTimer.ino +++ b/libraries/ESP32/examples/Timer/WatchdogTimer/WatchdogTimer.ino @@ -6,7 +6,7 @@ hw_timer_t *timer = NULL; void IRAM_ATTR resetModule() { ets_printf("reboot\n"); - esp_restart_noos(); + esp_restart(); } void setup() { diff --git a/libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino b/libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino index b25e33b9602..8763d8d6108 100644 --- a/libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino +++ b/libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino @@ -96,7 +96,6 @@ void loop(void) req = req.substring(addr_start + 1, addr_end); Serial.print("Request: "); Serial.println(req); - client.flush(); String s; if (req == "/") @@ -115,6 +114,7 @@ void loop(void) } client.print(s); + client.stop(); Serial.println("Done with client"); } diff --git a/libraries/ESPmDNS/src/ESPmDNS.cpp b/libraries/ESPmDNS/src/ESPmDNS.cpp index e7b05c9db10..2211f67b9c7 100644 --- a/libraries/ESPmDNS/src/ESPmDNS.cpp +++ b/libraries/ESPmDNS/src/ESPmDNS.cpp @@ -43,6 +43,14 @@ License (MIT license): #include #include "esp_wifi.h" +// Add quotes around defined value +#ifdef __IN_ECLIPSE__ +#define STR_EXPAND(tok) #tok +#define STR(tok) STR_EXPAND(tok) +#else +#define STR(tok) tok +#endif + static void _on_sys_event(system_event_t *event){ mdns_handle_system_event(NULL, event); } @@ -82,7 +90,7 @@ void MDNSResponder::setInstanceName(String name) { void MDNSResponder::enableArduino(uint16_t port, bool auth){ mdns_txt_item_t arduTxtData[4] = { - {(char*)"board" ,(char*)ARDUINO_VARIANT}, + {(char*)"board" ,(char*)STR(ARDUINO_VARIANT)}, {(char*)"tcp_check" ,(char*)"no"}, {(char*)"ssh_upload" ,(char*)"no"}, {(char*)"auth_upload" ,(char*)"no"} @@ -285,4 +293,51 @@ uint16_t MDNSResponder::port(int idx) { return result->port; } +int MDNSResponder::numTxt(int idx) { + mdns_result_t * result = _getResult(idx); + if(!result){ + log_e("Result %d not found", idx); + return 0; + } + return result->txt_count; +} + +bool MDNSResponder::hasTxt(int idx, const char * key) { + mdns_result_t * result = _getResult(idx); + if(!result){ + log_e("Result %d not found", idx); + return false; + } + int i = 0; + while(i < result->txt_count) { + if (strcmp(result->txt[i].key, key) == 0) return true; + i++; + } + return false; +} + +String MDNSResponder::txt(int idx, const char * key) { + mdns_result_t * result = _getResult(idx); + if(!result){ + log_e("Result %d not found", idx); + return ""; + } + int i = 0; + while(i < result->txt_count) { + if (strcmp(result->txt[i].key, key) == 0) return result->txt[i].value; + i++; + } + return ""; +} + +String MDNSResponder::txt(int idx, int txtIdx) { + mdns_result_t * result = _getResult(idx); + if(!result){ + log_e("Result %d not found", idx); + return ""; + } + if (txtIdx >= result->txt_count) return ""; + return result->txt[txtIdx].value; +} + MDNSResponder MDNS; diff --git a/libraries/ESPmDNS/src/ESPmDNS.h b/libraries/ESPmDNS/src/ESPmDNS.h index 083ec17eeac..e66fbdb7e62 100644 --- a/libraries/ESPmDNS/src/ESPmDNS.h +++ b/libraries/ESPmDNS/src/ESPmDNS.h @@ -107,6 +107,10 @@ class MDNSResponder { IPAddress IP(int idx); IPv6Address IPv6(int idx); uint16_t port(int idx); + int numTxt(int idx); + bool hasTxt(int idx, const char * key); + String txt(int idx, const char * key); + String txt(int idx, int txtIdx); private: String _hostname; diff --git a/libraries/FFat/examples/FFat_Test/FFat_Test.ino b/libraries/FFat/examples/FFat_Test/FFat_Test.ino new file mode 100644 index 00000000000..f36d922557e --- /dev/null +++ b/libraries/FFat/examples/FFat_Test/FFat_Test.ino @@ -0,0 +1,185 @@ +#include "FS.h" +#include "FFat.h" + +// This file should be compiled with 'Partition Scheme' (in Tools menu) +// set to 'Default with ffat' if you have a 4MB ESP32 dev module or +// set to '16M Fat' if you have a 16MB ESP32 dev module. + +// You only need to format FFat the first time you run a test +#define FORMAT_FFAT true + +void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ + Serial.printf("Listing directory: %s\r\n", dirname); + + File root = fs.open(dirname); + if(!root){ + Serial.println("- failed to open directory"); + return; + } + if(!root.isDirectory()){ + Serial.println(" - not a directory"); + return; + } + + File file = root.openNextFile(); + while(file){ + if(file.isDirectory()){ + Serial.print(" DIR : "); + Serial.println(file.name()); + if(levels){ + listDir(fs, file.name(), levels -1); + } + } else { + Serial.print(" FILE: "); + Serial.print(file.name()); + Serial.print("\tSIZE: "); + Serial.println(file.size()); + } + file = root.openNextFile(); + } +} + +void readFile(fs::FS &fs, const char * path){ + Serial.printf("Reading file: %s\r\n", path); + + File file = fs.open(path); + if(!file || file.isDirectory()){ + Serial.println("- failed to open file for reading"); + return; + } + + Serial.println("- read from file:"); + while(file.available()){ + Serial.write(file.read()); + } +} + +void writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Writing file: %s\r\n", path); + + File file = fs.open(path, FILE_WRITE); + if(!file){ + Serial.println("- failed to open file for writing"); + return; + } + if(file.print(message)){ + Serial.println("- file written"); + } else { + Serial.println("- write failed"); + } +} + +void appendFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Appending to file: %s\r\n", path); + + File file = fs.open(path, FILE_APPEND); + if(!file){ + Serial.println("- failed to open file for appending"); + return; + } + if(file.print(message)){ + Serial.println("- message appended"); + } else { + Serial.println("- append failed"); + } +} + +void renameFile(fs::FS &fs, const char * path1, const char * path2){ + Serial.printf("Renaming file %s to %s\r\n", path1, path2); + if (fs.rename(path1, path2)) { + Serial.println("- file renamed"); + } else { + Serial.println("- rename failed"); + } +} + +void deleteFile(fs::FS &fs, const char * path){ + Serial.printf("Deleting file: %s\r\n", path); + if(fs.remove(path)){ + Serial.println("- file deleted"); + } else { + Serial.println("- delete failed"); + } +} + +void testFileIO(fs::FS &fs, const char * path){ + Serial.printf("Testing file I/O with %s\r\n", path); + + static uint8_t buf[512]; + size_t len = 0; + File file = fs.open(path, FILE_WRITE); + if(!file){ + Serial.println("- failed to open file for writing"); + return; + } + + size_t i; + Serial.print("- writing" ); + uint32_t start = millis(); + for(i=0; i<2048; i++){ + if ((i & 0x001F) == 0x001F){ + Serial.print("."); + } + file.write(buf, 512); + } + Serial.println(""); + uint32_t end = millis() - start; + Serial.printf(" - %u bytes written in %u ms\r\n", 2048 * 512, end); + file.close(); + + file = fs.open(path); + start = millis(); + end = start; + i = 0; + if(file && !file.isDirectory()){ + len = file.size(); + size_t flen = len; + start = millis(); + Serial.print("- reading" ); + while(len){ + size_t toRead = len; + if(toRead > 512){ + toRead = 512; + } + file.read(buf, toRead); + if ((i++ & 0x001F) == 0x001F){ + Serial.print("."); + } + len -= toRead; + } + Serial.println(""); + end = millis() - start; + Serial.printf("- %u bytes read in %u ms\r\n", flen, end); + file.close(); + } else { + Serial.println("- failed to open file for reading"); + } +} + +void setup(){ + Serial.begin(115200); + Serial.setDebugOutput(true); + if (FORMAT_FFAT) FFat.format(); + if(!FFat.begin()){ + Serial.println("FFat Mount Failed"); + return; + } + + Serial.printf("Total space: %10u\n", FFat.totalBytes()); + Serial.printf("Free space: %10u\n", FFat.freeBytes()); + listDir(FFat, "/", 0); + writeFile(FFat, "/hello.txt", "Hello "); + appendFile(FFat, "/hello.txt", "World!\r\n"); + readFile(FFat, "/hello.txt"); + renameFile(FFat, "/hello.txt", "/foo.txt"); + readFile(FFat, "/foo.txt"); + deleteFile(FFat, "/foo.txt"); + testFileIO(FFat, "/test.txt"); + Serial.printf("Free space: %10u\n", FFat.freeBytes()); + deleteFile(FFat, "/test.txt"); + Serial.println( "Test complete" ); +} + +void loop(){ + +} diff --git a/libraries/FFat/examples/FFat_time/FFat_time.ino b/libraries/FFat/examples/FFat_time/FFat_time.ino new file mode 100644 index 00000000000..1e3794514c5 --- /dev/null +++ b/libraries/FFat/examples/FFat_time/FFat_time.ino @@ -0,0 +1,177 @@ +#include "FS.h" +#include "FFat.h" +#include +#include + +const char* ssid = "your-ssid"; +const char* password = "your-password"; + +long timezone = 1; +byte daysavetime = 1; + +void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ + Serial.printf("Listing directory: %s\n", dirname); + + File root = fs.open(dirname); + if(!root){ + Serial.println("Failed to open directory"); + return; + } + if(!root.isDirectory()){ + Serial.println("Not a directory"); + return; + } + + File file = root.openNextFile(); + while(file){ + if(file.isDirectory()){ + Serial.print(" DIR : "); + Serial.print (file.name()); + time_t t= file.getLastWrite(); + struct tm * tmstruct = localtime(&t); + Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); + if(levels){ + listDir(fs, file.name(), levels -1); + } + } else { + Serial.print(" FILE: "); + Serial.print(file.name()); + Serial.print(" SIZE: "); + Serial.print(file.size()); + time_t t= file.getLastWrite(); + struct tm * tmstruct = localtime(&t); + Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); + } + file = root.openNextFile(); + } +} + +void createDir(fs::FS &fs, const char * path){ + Serial.printf("Creating Dir: %s\n", path); + if(fs.mkdir(path)){ + Serial.println("Dir created"); + } else { + Serial.println("mkdir failed"); + } +} + +void removeDir(fs::FS &fs, const char * path){ + Serial.printf("Removing Dir: %s\n", path); + if(fs.rmdir(path)){ + Serial.println("Dir removed"); + } else { + Serial.println("rmdir failed"); + } +} + +void readFile(fs::FS &fs, const char * path){ + Serial.printf("Reading file: %s\n", path); + + File file = fs.open(path); + if(!file){ + Serial.println("Failed to open file for reading"); + return; + } + + Serial.print("Read from file: "); + while(file.available()){ + Serial.write(file.read()); + } + file.close(); +} + +void writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Writing file: %s\n", path); + + File file = fs.open(path, FILE_WRITE); + if(!file){ + Serial.println("Failed to open file for writing"); + return; + } + if(file.print(message)){ + Serial.println("File written"); + } else { + Serial.println("Write failed"); + } + file.close(); +} + +void appendFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Appending to file: %s\n", path); + + File file = fs.open(path, FILE_APPEND); + if(!file){ + Serial.println("Failed to open file for appending"); + return; + } + if(file.print(message)){ + Serial.println("Message appended"); + } else { + Serial.println("Append failed"); + } + file.close(); +} + +void renameFile(fs::FS &fs, const char * path1, const char * path2){ + Serial.printf("Renaming file %s to %s\n", path1, path2); + if (fs.rename(path1, path2)) { + Serial.println("File renamed"); + } else { + Serial.println("Rename failed"); + } +} + +void deleteFile(fs::FS &fs, const char * path){ + Serial.printf("Deleting file: %s\n", path); + if(fs.remove(path)){ + Serial.println("File deleted"); + } else { + Serial.println("Delete failed"); + } +} + +void setup(){ + Serial.begin(115200); + // We start by connecting to a WiFi network + Serial.println(); + Serial.println(); + Serial.print("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + Serial.println("Contacting Time Server"); + configTime(3600*timezone, daysavetime*3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org"); + struct tm tmstruct ; + delay(2000); + tmstruct.tm_year = 0; + getLocalTime(&tmstruct, 5000); + Serial.printf("\nNow is : %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct.tm_year)+1900,( tmstruct.tm_mon)+1, tmstruct.tm_mday,tmstruct.tm_hour , tmstruct.tm_min, tmstruct.tm_sec); + Serial.println(""); + + if(!FFat.begin(true)){ + Serial.println("FFat Mount Failed"); + return; + } + + listDir(FFat, "/", 0); + removeDir(FFat, "/mydir"); + createDir(FFat, "/mydir"); + deleteFile(FFat, "/hello.txt"); + writeFile(FFat, "/hello.txt", "Hello "); + appendFile(FFat, "/hello.txt", "World!\n"); + listDir(FFat, "/", 0); +} + +void loop(){ + +} + + diff --git a/libraries/FFat/library.properties b/libraries/FFat/library.properties new file mode 100644 index 00000000000..aebca39d950 --- /dev/null +++ b/libraries/FFat/library.properties @@ -0,0 +1,9 @@ +name=FFat +version=1.0 +author=Hristo Gochkov, Ivan Grokhtkov, Larry Bernstone +maintainer=Hristo Gochkov +sentence=ESP32 FAT on Flash File System +paragraph= +category=Data Storage +url= +architectures=esp32 diff --git a/libraries/FFat/src/FFat.cpp b/libraries/FFat/src/FFat.cpp new file mode 100644 index 00000000000..0d2b2cb26ab --- /dev/null +++ b/libraries/FFat/src/FFat.cpp @@ -0,0 +1,166 @@ +// 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. + +#include "vfs_api.h" +extern "C" { +#include "esp_vfs_fat.h" +#include "diskio.h" +#include "diskio_wl.h" +#include "vfs_fat_internal.h" +} +#include "FFat.h" + +using namespace fs; + +F_Fat::F_Fat(FSImplPtr impl) + : FS(impl) +{} + +const esp_partition_t *check_ffat_partition(const char* label) +{ + const esp_partition_t* ck_part = esp_partition_find_first( + ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, label); + if (!ck_part) { + log_e("No FAT partition found with label %s", label); + return NULL; + } + return ck_part; +} + +bool F_Fat::begin(bool formatOnFail, const char * basePath, uint8_t maxOpenFiles, const char * partitionLabel) +{ + if(_wl_handle != WL_INVALID_HANDLE){ + log_w("Already Mounted!"); + return true; + } + + if (!check_ffat_partition(partitionLabel)){ + log_e("No fat partition found on flash"); + return false; + } + + esp_vfs_fat_mount_config_t conf = { + .format_if_mount_failed = formatOnFail, + .max_files = maxOpenFiles, + .allocation_unit_size = CONFIG_WL_SECTOR_SIZE + }; + esp_err_t err = esp_vfs_fat_spiflash_mount(basePath, partitionLabel, &conf, &_wl_handle); + if(err){ + log_e("Mounting FFat partition failed! Error: %d", err); + esp_vfs_fat_spiflash_unmount(basePath, _wl_handle); + _wl_handle = WL_INVALID_HANDLE; + return false; + } + _impl->mountpoint(basePath); + return true; +} + +void F_Fat::end() +{ + if(_wl_handle != WL_INVALID_HANDLE){ + esp_err_t err = esp_vfs_fat_spiflash_unmount(_impl->mountpoint(), _wl_handle); + if(err){ + log_e("Unmounting FFat partition failed! Error: %d", err); + return; + } + _wl_handle = WL_INVALID_HANDLE; + _impl->mountpoint(NULL); + } +} + +bool F_Fat::format(bool full_wipe, char* partitionLabel) +{ + esp_err_t result; + bool res = true; + if(_wl_handle != WL_INVALID_HANDLE){ + log_w("Already Mounted!"); + return false; + } + wl_handle_t temp_handle; +// Attempt to mount to see if there is already data + const esp_partition_t *ffat_partition = check_ffat_partition(partitionLabel); + if (!ffat_partition){ + log_w("No partition!"); + return false; + } + result = wl_mount(ffat_partition, &temp_handle); + + if (result == ESP_OK) { +// Wipe disk- quick just wipes the FAT. Full zeroes the whole disk + uint32_t wipe_size = full_wipe ? wl_size(temp_handle) : 16384; + wl_erase_range(temp_handle, 0, wipe_size); + wl_unmount(temp_handle); + } else { + res = false; + log_w("wl_mount failed!"); + } +// Now do a mount with format_if_fail (which it will) + esp_vfs_fat_mount_config_t conf = { + .format_if_mount_failed = true, + .max_files = 1, + .allocation_unit_size = CONFIG_WL_SECTOR_SIZE + }; + result = esp_vfs_fat_spiflash_mount("/format_ffat", partitionLabel, &conf, &temp_handle); + esp_vfs_fat_spiflash_unmount("/format_ffat", temp_handle); + if (result != ESP_OK){ + res = false; + log_w("esp_vfs_fat_spiflash_mount failed!"); + } + return res; +} + +size_t F_Fat::totalBytes() +{ + FATFS *fs; + DWORD free_clust, tot_sect, sect_size; + + BYTE pdrv = ff_diskio_get_pdrv_wl(_wl_handle); + char drv[3] = {(char)(48+pdrv), ':', 0}; + if ( f_getfree(drv, &free_clust, &fs) != FR_OK){ + return 0; + } + tot_sect = (fs->n_fatent - 2) * fs->csize; + sect_size = CONFIG_WL_SECTOR_SIZE; + return tot_sect * sect_size; +} + +size_t F_Fat::freeBytes() +{ + + FATFS *fs; + DWORD free_clust, free_sect, sect_size; + + BYTE pdrv = ff_diskio_get_pdrv_wl(_wl_handle); + char drv[3] = {(char)(48+pdrv), ':', 0}; + if ( f_getfree(drv, &free_clust, &fs) != FR_OK){ + return 0; + } + free_sect = free_clust * fs->csize; + sect_size = CONFIG_WL_SECTOR_SIZE; + return free_sect * sect_size; +} + +bool F_Fat::exists(const char* path) +{ + File f = open(path, "r"); + return (f == true) && !f.isDirectory(); +} + +bool F_Fat::exists(const String& path) +{ + return exists(path.c_str()); +} + + +F_Fat FFat = F_Fat(FSImplPtr(new VFSImpl())); diff --git a/libraries/FFat/src/FFat.h b/libraries/FFat/src/FFat.h new file mode 100644 index 00000000000..a32c950bb6e --- /dev/null +++ b/libraries/FFat/src/FFat.h @@ -0,0 +1,47 @@ +// 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 _FFAT_H_ +#define _FFAT_H_ + +#include "FS.h" +#include "wear_levelling.h" + +#define FFAT_WIPE_QUICK 0 +#define FFAT_WIPE_FULL 1 +#define FFAT_PARTITION_LABEL "ffat" + +namespace fs +{ + +class F_Fat : public FS +{ +public: + F_Fat(FSImplPtr impl); + bool begin(bool formatOnFail=false, const char * basePath="/ffat", uint8_t maxOpenFiles=10, const char * partitionLabel = (char*)FFAT_PARTITION_LABEL); + bool format(bool full_wipe = FFAT_WIPE_QUICK, char* partitionLabel = (char*)FFAT_PARTITION_LABEL); + size_t totalBytes(); + size_t freeBytes(); + void end(); + bool exists(const char* path); + bool exists(const String& path); + +private: + wl_handle_t _wl_handle = WL_INVALID_HANDLE; +}; + +} + +extern fs::F_Fat FFat; + +#endif /* _FFAT_H_ */ diff --git a/libraries/FS/src/FS.h b/libraries/FS/src/FS.h index c27e3a64b89..d63fc5da305 100644 --- a/libraries/FS/src/FS.h +++ b/libraries/FS/src/FS.h @@ -47,7 +47,9 @@ enum SeekMode { class File : public Stream { public: - File(FileImplPtr p = FileImplPtr()) : _p(p) {} + File(FileImplPtr p = FileImplPtr()) : _p(p) { + _timeout = 0; + } size_t write(uint8_t) override; size_t write(const uint8_t *buf, size_t size) override; diff --git a/libraries/FS/src/vfs_api.cpp b/libraries/FS/src/vfs_api.cpp index 2b91eb82187..6502f760560 100644 --- a/libraries/FS/src/vfs_api.cpp +++ b/libraries/FS/src/vfs_api.cpp @@ -340,6 +340,8 @@ void VFSFileImpl::flush() return; } fflush(_f); + // workaround for https://github.com/espressif/arduino-esp32/issues/1293 + fsync(fileno(_f)); } bool VFSFileImpl::seek(uint32_t pos, SeekMode mode) diff --git a/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino new file mode 100644 index 00000000000..9ef2b44eadf --- /dev/null +++ b/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino @@ -0,0 +1,147 @@ +/** + BasicHTTPSClient.ino + + Created on: 14.10.2018 + +*/ + +#include + +#include +#include + +#include + +#include + +// This is GandiStandardSSLCA2.pem, the root Certificate Authority that signed +// the server certifcate for the demo server https://jigsaw.w3.org in this +// example. This certificate is valid until Sep 11 23:59:59 2024 GMT +const char* rootCACertificate = \ +"-----BEGIN CERTIFICATE-----\n" \ +"MIIF6TCCA9GgAwIBAgIQBeTcO5Q4qzuFl8umoZhQ4zANBgkqhkiG9w0BAQwFADCB\n" \ +"iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\n" \ +"cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\n" \ +"BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTQw\n" \ +"OTEyMDAwMDAwWhcNMjQwOTExMjM1OTU5WjBfMQswCQYDVQQGEwJGUjEOMAwGA1UE\n" \ +"CBMFUGFyaXMxDjAMBgNVBAcTBVBhcmlzMQ4wDAYDVQQKEwVHYW5kaTEgMB4GA1UE\n" \ +"AxMXR2FuZGkgU3RhbmRhcmQgU1NMIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IB\n" \ +"DwAwggEKAoIBAQCUBC2meZV0/9UAPPWu2JSxKXzAjwsLibmCg5duNyj1ohrP0pIL\n" \ +"m6jTh5RzhBCf3DXLwi2SrCG5yzv8QMHBgyHwv/j2nPqcghDA0I5O5Q1MsJFckLSk\n" \ +"QFEW2uSEEi0FXKEfFxkkUap66uEHG4aNAXLy59SDIzme4OFMH2sio7QQZrDtgpbX\n" \ +"bmq08j+1QvzdirWrui0dOnWbMdw+naxb00ENbLAb9Tr1eeohovj0M1JLJC0epJmx\n" \ +"bUi8uBL+cnB89/sCdfSN3tbawKAyGlLfOGsuRTg/PwSWAP2h9KK71RfWJ3wbWFmV\n" \ +"XooS/ZyrgT5SKEhRhWvzkbKGPym1bgNi7tYFAgMBAAGjggF1MIIBcTAfBgNVHSME\n" \ +"GDAWgBRTeb9aqitKz1SA4dibwJ3ysgNmyzAdBgNVHQ4EFgQUs5Cn2MmvTs1hPJ98\n" \ +"rV1/Qf1pMOowDgYDVR0PAQH/BAQDAgGGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYD\n" \ +"VR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMCIGA1UdIAQbMBkwDQYLKwYBBAGy\n" \ +"MQECAhowCAYGZ4EMAQIBMFAGA1UdHwRJMEcwRaBDoEGGP2h0dHA6Ly9jcmwudXNl\n" \ +"cnRydXN0LmNvbS9VU0VSVHJ1c3RSU0FDZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNy\n" \ +"bDB2BggrBgEFBQcBAQRqMGgwPwYIKwYBBQUHMAKGM2h0dHA6Ly9jcnQudXNlcnRy\n" \ +"dXN0LmNvbS9VU0VSVHJ1c3RSU0FBZGRUcnVzdENBLmNydDAlBggrBgEFBQcwAYYZ\n" \ +"aHR0cDovL29jc3AudXNlcnRydXN0LmNvbTANBgkqhkiG9w0BAQwFAAOCAgEAWGf9\n" \ +"crJq13xhlhl+2UNG0SZ9yFP6ZrBrLafTqlb3OojQO3LJUP33WbKqaPWMcwO7lWUX\n" \ +"zi8c3ZgTopHJ7qFAbjyY1lzzsiI8Le4bpOHeICQW8owRc5E69vrOJAKHypPstLbI\n" \ +"FhfFcvwnQPYT/pOmnVHvPCvYd1ebjGU6NSU2t7WKY28HJ5OxYI2A25bUeo8tqxyI\n" \ +"yW5+1mUfr13KFj8oRtygNeX56eXVlogMT8a3d2dIhCe2H7Bo26y/d7CQuKLJHDJd\n" \ +"ArolQ4FCR7vY4Y8MDEZf7kYzawMUgtN+zY+vkNaOJH1AQrRqahfGlZfh8jjNp+20\n" \ +"J0CT33KpuMZmYzc4ZCIwojvxuch7yPspOqsactIGEk72gtQjbz7Dk+XYtsDe3CMW\n" \ +"1hMwt6CaDixVBgBwAc/qOR2A24j3pSC4W/0xJmmPLQphgzpHphNULB7j7UTKvGof\n" \ +"KA5R2d4On3XNDgOVyvnFqSot/kGkoUeuDcL5OWYzSlvhhChZbH2UF3bkRYKtcCD9\n" \ +"0m9jqNf6oDP6N8v3smWe2lBvP+Sn845dWDKXcCMu5/3EFZucJ48y7RetWIExKREa\n" \ +"m9T8bJUox04FB6b9HbwZ4ui3uRGKLXASUoWNjDNKD/yZkuBjcNqllEdjB+dYxzFf\n" \ +"BT02Vf6Dsuimrdfp5gJ0iHRc2jTbkNJtUQoj1iM=\n" \ +"-----END CERTIFICATE-----\n"; + +// Not sure if WiFiClientSecure checks the validity date of the certificate. +// Setting clock just to be sure... +void setClock() { + configTime(0, 0, "pool.ntp.org", "time.nist.gov"); + + Serial.print(F("Waiting for NTP time sync: ")); + time_t nowSecs = time(nullptr); + while (nowSecs < 8 * 3600 * 2) { + delay(500); + Serial.print(F(".")); + yield(); + nowSecs = time(nullptr); + } + + Serial.println(); + struct tm timeinfo; + gmtime_r(&nowSecs, &timeinfo); + Serial.print(F("Current time: ")); + Serial.print(asctime(&timeinfo)); +} + + +WiFiMulti WiFiMulti; + +void setup() { + + Serial.begin(115200); + // Serial.setDebugOutput(true); + + Serial.println(); + Serial.println(); + Serial.println(); + + WiFi.mode(WIFI_STA); + WiFiMulti.addAP("SSID", "PASSWORD"); + + // wait for WiFi connection + Serial.print("Waiting for WiFi to connect..."); + while ((WiFiMulti.run() != WL_CONNECTED)) { + Serial.print("."); + } + Serial.println(" connected"); + + setClock(); +} + +void loop() { + WiFiClientSecure *client = new WiFiClientSecure; + if(client) { + client -> setCACert(rootCACertificate); + + { + // Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is + HTTPClient https; + + Serial.print("[HTTPS] begin...\n"); + if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) { // HTTPS + Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = https.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + Serial.printf("[HTTPS] GET... code: %d\n", httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + String payload = https.getString(); + Serial.println(payload); + } + } else { + Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); + } + + https.end(); + } else { + Serial.printf("[HTTPS] Unable to connect\n"); + } + + // End extra scoping block + } + + delete client; + } else { + Serial.println("Unable to create client"); + } + + Serial.println(); + Serial.println("Waiting 10s before the next round..."); + delay(10000); +} diff --git a/libraries/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino b/libraries/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino new file mode 100644 index 00000000000..b28501bb3ea --- /dev/null +++ b/libraries/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino @@ -0,0 +1,98 @@ +/*|----------------------------------------------------------|*/ +/*|WORKING EXAMPLE FOR HTTP/HTTPS CONNECTION |*/ +/*|TESTED BOARDS: Devkit v1 DOIT, Devkitc v4 |*/ +/*|CORE: June 2018 |*/ +/*|----------------------------------------------------------|*/ +#include +#include +#include "esp_wpa2.h" +#include +#define EAP_IDENTITY "identity" //if connecting from another corporation, use identity@organisation.domain in Eduroam +#define EAP_PASSWORD "password" //your Eduroam password +const char* ssid = "eduroam"; // Eduroam SSID +int counter = 0; +const char* test_root_ca= \ +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n"; +void setup() { + Serial.begin(115200); + delay(10); + Serial.println(); + Serial.print("Connecting to network: "); + Serial.println(ssid); + WiFi.disconnect(true); //disconnect form wifi to set new wifi connection + WiFi.mode(WIFI_STA); //init wifi mode + esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide identity + esp_wifi_sta_wpa2_ent_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide username --> identity and username is same + esp_wifi_sta_wpa2_ent_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD)); //provide password + esp_wpa2_config_t config = WPA2_CONFIG_INIT_DEFAULT(); //set config settings to default + esp_wifi_sta_wpa2_ent_enable(&config); //set config settings to enable function + WiFi.begin(ssid); //connect to wifi + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + counter++; + if(counter>=60){ //after 30 seconds timeout - reset board + ESP.restart(); + } + } + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address set: "); + Serial.println(WiFi.localIP()); //print LAN IP +} +void loop() { + if (WiFi.status() == WL_CONNECTED) { //if we are connected to Eduroam network + counter = 0; //reset counter + Serial.println("Wifi is still connected with IP: "); + Serial.println(WiFi.localIP()); //inform user about his IP address + }else if (WiFi.status() != WL_CONNECTED) { //if we lost connection, retry + WiFi.begin(ssid); + } + while (WiFi.status() != WL_CONNECTED) { //during lost connection, print dots + delay(500); + Serial.print("."); + counter++; + if(counter>=60){ //30 seconds timeout - reset board + ESP.restart(); + } + } + Serial.print("Connecting to website: "); + HTTPClient http; + http.begin("https://arduino.php5.sk/rele/rele1.txt", test_root_ca); //HTTPS example connection + //http.begin("http://www.arduino.php5.sk/rele/rele1.txt"); //HTTP example connection + //if uncomment HTTP example, you can comment root CA certificate too! + int httpCode = http.GET(); + if(httpCode > 0) { + Serial.printf("[HTTP] GET... code: %d\n", httpCode); + //file found at server --> on unsucessful connection code will be -1 + if(httpCode == HTTP_CODE_OK) { + String payload = http.getString(); + Serial.println(payload); + } + }else{ + Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); + } + http.end(); + delay(2000); +} diff --git a/libraries/HTTPClient/library.properties b/libraries/HTTPClient/library.properties index 2be999fedc7..153a2e2575d 100644 --- a/libraries/HTTPClient/library.properties +++ b/libraries/HTTPClient/library.properties @@ -1,9 +1,9 @@ name=HTTPClient -version=1.1 +version=1.2 author=Markus Sattler maintainer=Markus Sattler -sentence=http Client for ESP32 +sentence=HTTP Client for ESP32 paragraph= category=Communication -url=https://github.com/Links2004/Arduino/tree/libraries/ESP8266HTTPClient +url=https://github.com/espressif/arduino-esp32/tree/master/libraries/HTTPClient architectures=esp32 diff --git a/libraries/HTTPClient/src/HTTPClient.cpp b/libraries/HTTPClient/src/HTTPClient.cpp index d39e89ce7c7..f4b0ae54654 100644 --- a/libraries/HTTPClient/src/HTTPClient.cpp +++ b/libraries/HTTPClient/src/HTTPClient.cpp @@ -1,3 +1,4 @@ +#include /** * HTTPClient.cpp * @@ -22,17 +23,23 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * + * Adapted in October 2018 */ #include #include + +#ifdef HTTPCLIENT_1_1_COMPATIBLE #include #include +#endif + #include #include #include "HTTPClient.h" +#ifdef HTTPCLIENT_1_1_COMPATIBLE class TransportTraits { public: @@ -78,6 +85,7 @@ class TLSTraits : public TransportTraits const char* _clicert; const char* _clikey; }; +#endif // HTTPCLIENT_1_1_COMPATIBLE /** * constructor @@ -91,8 +99,8 @@ HTTPClient::HTTPClient() */ HTTPClient::~HTTPClient() { - if(_tcp) { - _tcp->stop(); + if(_client) { + _client->stop(); } if(_currentHeaders) { delete[] _currentHeaders; @@ -107,15 +115,92 @@ void HTTPClient::clear() } +/** + * parsing the url for all needed parameters + * @param client Client& + * @param url String + * @param https bool + * @return success bool + */ +bool HTTPClient::begin(WiFiClient &client, String url) { +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if(_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } +#endif + + _client = &client; + + // check for : (http: or https:) + int index = url.indexOf(':'); + if(index < 0) { + log_d("failed to parse protocol"); + return false; + } + + String protocol = url.substring(0, index); + if(protocol != "http" && protocol != "https") { + log_d("unknown protocol '%s'", protocol.c_str()); + return false; + } + + _port = (protocol == "https" ? 443 : 80); + return beginInternal(url, protocol.c_str()); +} + + +/** + * directly supply all needed parameters + * @param client Client& + * @param host String + * @param port uint16_t + * @param uri String + * @param https bool + * @return success bool + */ +bool HTTPClient::begin(WiFiClient &client, String host, uint16_t port, String uri, bool https) +{ +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if(_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } +#endif + + _client = &client; + + clear(); + _host = host; + _port = port; + _uri = uri; + _protocol = (https ? "https" : "http"); + return true; +} + + +#ifdef HTTPCLIENT_1_1_COMPATIBLE bool HTTPClient::begin(String url, const char* CAcert) { - _transportTraits.reset(nullptr); + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + _port = 443; if (!beginInternal(url, "https")) { return false; } _secure = true; _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert)); + if(!_transportTraits) { + log_e("could not create transport traits"); + return false; + } + return true; } @@ -125,15 +210,25 @@ bool HTTPClient::begin(String url, const char* CAcert) */ bool HTTPClient::begin(String url) { + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } - _transportTraits.reset(nullptr); _port = 80; if (!beginInternal(url, "http")) { return begin(url, (const char*)NULL); } _transportTraits = TransportTraitsPtr(new TransportTraits()); + if(!_transportTraits) { + log_e("could not create transport traits"); + return false; + } + return true; } +#endif // HTTPCLIENT_1_1_COMPATIBLE bool HTTPClient::beginInternal(String url, const char* expectedProtocol) { @@ -182,8 +277,15 @@ bool HTTPClient::beginInternal(String url, const char* expectedProtocol) return true; } +#ifdef HTTPCLIENT_1_1_COMPATIBLE bool HTTPClient::begin(String host, uint16_t port, String uri) { + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + clear(); _host = host; _port = port; @@ -195,6 +297,12 @@ bool HTTPClient::begin(String host, uint16_t port, String uri) bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcert) { + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + clear(); _host = host; _port = port; @@ -210,6 +318,12 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcer bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key) { + if(_client && !_tcpDeprecated) { + log_d("mix up of new and deprecated api"); + _canReuse = false; + end(); + } + clear(); _host = host; _port = port; @@ -222,37 +336,63 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcer _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert, cli_cert, cli_key)); return true; } +#endif // HTTPCLIENT_1_1_COMPATIBLE /** * end * called after the payload is handled */ void HTTPClient::end(void) +{ + disconnect(false); + clear(); +} + + + +/** + * disconnect + * close the TCP socket + */ +void HTTPClient::disconnect(bool preserveClient) { if(connected()) { - if(_tcp->available() > 0) { - log_d("still data in buffer (%d), clean up.", _tcp->available()); - _tcp->flush(); + if(_client->available() > 0) { + log_d("still data in buffer (%d), clean up.\n", _client->available()); + while(_client->available() > 0) { + _client->read(); + } } + if(_reuse && _canReuse) { - log_d("tcp keep open for reuse"); + log_d("tcp keep open for reuse\n"); } else { - log_d("tcp stop"); - _tcp->stop(); + log_d("tcp stop\n"); + _client->stop(); + if(!preserveClient) { + _client = nullptr; + } +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if(_tcpDeprecated) { + _transportTraits.reset(nullptr); + _tcpDeprecated.reset(nullptr); + } +#endif } } else { - log_v("tcp is closed"); + log_d("tcp is closed\n"); } } + /** * connected * @return connected status */ bool HTTPClient::connected() { - if(_tcp) { - return (_tcp->connected() || (_tcp->available() > 0)); + if(_client) { + return ((_client->available() > 0) || _client->connected()); } return false; } @@ -302,6 +442,15 @@ void HTTPClient::setAuthorization(const char * auth) } } +/** + * set the timeout (ms) for establishing a connection to the server + * @param connectTimeout int32_t + */ +void HTTPClient::setConnectTimeout(int32_t connectTimeout) +{ + _connectTimeout = connectTimeout; +} + /** * set the timeout for the TCP connection * @param timeout unsigned int @@ -309,18 +458,19 @@ void HTTPClient::setAuthorization(const char * auth) void HTTPClient::setTimeout(uint16_t timeout) { _tcpTimeout = timeout; - if(connected() && !_secure) { - _tcp->setTimeout(timeout); + if(connected()) { + _client->setTimeout((timeout + 500) / 1000); } } /** * use HTTP1.0 - * @param timeout + * @param use */ void HTTPClient::useHTTP10(bool useHTTP10) { _useHTTP10 = useHTTP10; + _reuse = !useHTTP10; } /** @@ -348,6 +498,22 @@ int HTTPClient::POST(String payload) return POST((uint8_t *) payload.c_str(), payload.length()); } +/** + * sends a patch request to the server + * @param payload uint8_t * + * @param size size_t + * @return http code + */ +int HTTPClient::PATCH(uint8_t * payload, size_t size) +{ + return sendRequest("PATCH", payload, size); +} + +int HTTPClient::PATCH(String payload) +{ + return PATCH((uint8_t *) payload.c_str(), payload.length()); +} + /** * sends a put request to the server * @param payload uint8_t * @@ -398,7 +564,7 @@ int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size) // send Payload if needed if(payload && size > 0) { - if(_tcp->write(&payload[0], size) != size) { + if(_client->write(&payload[0], size) != size) { return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); } } @@ -477,7 +643,7 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) int bytesRead = stream->readBytes(buff, readBytes); // write it to Stream - int bytesWrite = _tcp->write((const uint8_t *) buff, bytesRead); + int bytesWrite = _client->write((const uint8_t *) buff, bytesRead); bytesWritten += bytesWrite; // are all Bytes a writen to stream ? @@ -485,11 +651,11 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) log_d("short write, asked for %d but got %d retry...", bytesRead, bytesWrite); // check for write error - if(_tcp->getWriteError()) { - log_d("stream write error %d", _tcp->getWriteError()); + if(_client->getWriteError()) { + log_d("stream write error %d", _client->getWriteError()); //reset write error for retry - _tcp->clearWriteError(); + _client->clearWriteError(); } // some time for the stream @@ -498,7 +664,7 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) int leftBytes = (readBytes - bytesWrite); // retry to send the missed bytes - bytesWrite = _tcp->write((const uint8_t *) (buff + bytesWrite), leftBytes); + bytesWrite = _client->write((const uint8_t *) (buff + bytesWrite), leftBytes); bytesWritten += bytesWrite; if(bytesWrite != leftBytes) { @@ -510,8 +676,8 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) } // check for write error - if(_tcp->getWriteError()) { - log_d("stream write error %d", _tcp->getWriteError()); + if(_client->getWriteError()) { + log_d("stream write error %d", _client->getWriteError()); free(buff); return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); } @@ -561,8 +727,8 @@ int HTTPClient::getSize(void) */ WiFiClient& HTTPClient::getStream(void) { - if (connected() && !_secure) { - return *_tcp; + if (connected()) { + return *_client; } log_w("getStream: not connected"); @@ -577,7 +743,7 @@ WiFiClient& HTTPClient::getStream(void) WiFiClient* HTTPClient::getStreamPtr(void) { if(connected()) { - return _tcp.get(); + return _client; } log_w("getStreamPtr: not connected"); @@ -617,7 +783,7 @@ int HTTPClient::writeToStream(Stream * stream) if(!connected()) { return returnError(HTTPC_ERROR_CONNECTION_LOST); } - String chunkHeader = _tcp->readStringUntil('\n'); + String chunkHeader = _client->readStringUntil('\n'); if(chunkHeader.length() <= 0) { return returnError(HTTPC_ERROR_READ_TIMEOUT); @@ -654,7 +820,7 @@ int HTTPClient::writeToStream(Stream * stream) // read trailing \r\n at the end of the chunk char buf[2]; - auto trailing_seq_len = _tcp->readBytes((uint8_t*)buf, 2); + auto trailing_seq_len = _client->readBytes((uint8_t*)buf, 2); if (trailing_seq_len != 2 || buf[0] != '\r' || buf[1] != '\n') { return returnError(HTTPC_ERROR_READ_TIMEOUT); } @@ -665,7 +831,8 @@ int HTTPClient::writeToStream(Stream * stream) return returnError(HTTPC_ERROR_ENCODING); } - end(); +// end(); + disconnect(true); return ret; } @@ -819,41 +986,56 @@ bool HTTPClient::hasHeader(const char* name) */ bool HTTPClient::connect(void) { - if(connected()) { - log_d("already connected, try reuse!"); - while(_tcp->available() > 0) { - _tcp->read(); + if(_reuse) { + log_d("already connected, reusing connection"); + } else { + log_d("already connected, try reuse!"); + } + while(_client->available() > 0) { + _client->read(); } return true; } - if (!_transportTraits) { +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if(_transportTraits && !_client) { + _tcpDeprecated = _transportTraits->create(); + if(!_tcpDeprecated) { + log_e("failed to create client"); + return false; + } + _client = _tcpDeprecated.get(); + } +#endif + + if (!_client) { log_d("HTTPClient::begin was not called or returned error"); return false; } - _tcp = _transportTraits->create(); - - - if (!_transportTraits->verify(*_tcp, _host.c_str())) { - log_d("transport level verify failed"); - _tcp->stop(); - return false; - } - - if(!_tcp->connect(_host.c_str(), _port)) { + if(!_client->connect(_host.c_str(), _port, _connectTimeout)) { log_d("failed connect to %s:%u", _host.c_str(), _port); return false; } + // set Timeout for WiFiClient and for Stream::readBytesUntil() and Stream::readStringUntil() + _client->setTimeout((_tcpTimeout + 500) / 1000); + log_d(" connected to %s:%u", _host.c_str(), _port); - // set Timeout for readBytesUntil and readStringUntil - setTimeout(_tcpTimeout); +#ifdef HTTPCLIENT_1_1_COMPATIBLE + if (_tcpDeprecated && !_transportTraits->verify(*_client, _host.c_str())) { + log_d("transport level verify failed"); + _client->stop(); + return false; + } +#endif + + /* #ifdef ESP8266 - _tcp->setNoDelay(true); + _client->setNoDelay(true); #endif */ return connected(); @@ -907,7 +1089,7 @@ bool HTTPClient::sendHeader(const char * type) header += _headers + "\r\n"; - return (_tcp->write((const uint8_t *) header.c_str(), header.length()) == header.length()); + return (_client->write((const uint8_t *) header.c_str(), header.length()) == header.length()); } /** @@ -921,16 +1103,19 @@ int HTTPClient::handleHeaderResponse() return HTTPC_ERROR_NOT_CONNECTED; } + clear(); + + _canReuse = _reuse; + String transferEncoding; - _returnCode = -1; - _size = -1; + _transferEncoding = HTTPC_TE_IDENTITY; unsigned long lastDataTime = millis(); while(connected()) { - size_t len = _tcp->available(); + size_t len = _client->available(); if(len > 0) { - String headerLine = _tcp->readStringUntil('\n'); + String headerLine = _client->readStringUntil('\n'); headerLine.trim(); // remove \r lastDataTime = millis(); @@ -938,6 +1123,9 @@ int HTTPClient::handleHeaderResponse() log_v("RX: '%s'", headerLine.c_str()); if(headerLine.startsWith("HTTP/1.")) { + if(_canReuse) { + _canReuse = (headerLine[sizeof "HTTP/1." - 1] != '0'); + } _returnCode = headerLine.substring(9, headerLine.indexOf(' ', 9)).toInt(); } else if(headerLine.indexOf(':')) { String headerName = headerLine.substring(0, headerLine.indexOf(':')); @@ -948,8 +1136,10 @@ int HTTPClient::handleHeaderResponse() _size = headerValue.toInt(); } - if(headerName.equalsIgnoreCase("Connection")) { - _canReuse = headerValue.equalsIgnoreCase("keep-alive"); + if(_canReuse && headerName.equalsIgnoreCase("Connection")) { + if(headerValue.indexOf("close") >= 0 && headerValue.indexOf("keep-alive") < 0) { + _canReuse = false; + } } if(headerName.equalsIgnoreCase("Transfer-Encoding")) { @@ -1026,7 +1216,7 @@ int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) while(connected() && (len > 0 || len == -1)) { // get available data size - size_t sizeAvailable = _tcp->available(); + size_t sizeAvailable = _client->available(); if(sizeAvailable) { @@ -1041,9 +1231,13 @@ int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) if(readBytes > buff_size) { readBytes = buff_size; } + + // stop if no more reading + if (readBytes == 0) + break; // read data - int bytesRead = _tcp->readBytes(buff, readBytes); + int bytesRead = _client->readBytes(buff, readBytes); // write it to Stream int bytesWrite = stream->write(buff, bytesRead); @@ -1124,7 +1318,7 @@ int HTTPClient::returnError(int error) log_w("error(%d): %s", error, errorToString(error).c_str()); if(connected()) { log_d("tcp stop"); - _tcp->stop(); + _client->stop(); } } return error; diff --git a/libraries/HTTPClient/src/HTTPClient.h b/libraries/HTTPClient/src/HTTPClient.h index b1570e1dff2..e089bb54973 100644 --- a/libraries/HTTPClient/src/HTTPClient.h +++ b/libraries/HTTPClient/src/HTTPClient.h @@ -27,6 +27,8 @@ #ifndef HTTPClient_H_ #define HTTPClient_H_ +#define HTTPCLIENT_1_1_COMPATIBLE + #include #include #include @@ -117,8 +119,10 @@ typedef enum { HTTPC_TE_CHUNKED } transferEncoding_t; +#ifdef HTTPCLIENT_1_1_COMPATIBLE class TransportTraits; typedef std::unique_ptr TransportTraitsPtr; +#endif class HTTPClient { @@ -126,11 +130,20 @@ class HTTPClient HTTPClient(); ~HTTPClient(); +/* + * Since both begin() functions take a reference to client as a parameter, you need to + * ensure the client object lives the entire time of the HTTPClient + */ + bool begin(WiFiClient &client, String url); + bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false); + +#ifdef HTTPCLIENT_1_1_COMPATIBLE bool begin(String url); bool begin(String url, const char* CAcert); bool begin(String host, uint16_t port, String uri = "/"); bool begin(String host, uint16_t port, String uri, const char* CAcert); bool begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key); +#endif void end(void); @@ -140,12 +153,15 @@ class HTTPClient void setUserAgent(const String& userAgent); void setAuthorization(const char * user, const char * password); void setAuthorization(const char * auth); + void setConnectTimeout(int32_t connectTimeout); void setTimeout(uint16_t timeout); void useHTTP10(bool usehttp10 = true); /// request handling int GET(); + int PATCH(uint8_t * payload, size_t size); + int PATCH(String payload); int POST(uint8_t * payload, size_t size); int POST(String payload); int PUT(uint8_t * payload, size_t size); @@ -181,6 +197,7 @@ class HTTPClient }; bool beginInternal(String url, const char* expectedProtocol); + void disconnect(bool preserveClient = false); void clear(); int returnError(int error); bool connect(void); @@ -189,13 +206,18 @@ class HTTPClient int writeToStreamDataBlock(Stream * stream, int len); +#ifdef HTTPCLIENT_1_1_COMPATIBLE TransportTraitsPtr _transportTraits; - std::unique_ptr _tcp; + std::unique_ptr _tcpDeprecated; +#endif + + WiFiClient* _client = nullptr; /// request handling String _host; uint16_t _port = 0; - bool _reuse = false; + int32_t _connectTimeout = -1; + bool _reuse = true; uint16_t _tcpTimeout = HTTPCLIENT_DEFAULT_TCP_TIMEOUT; bool _useHTTP10 = false; bool _secure = false; diff --git a/libraries/HTTPUpdate/examples/httpUpdate/httpUpdate.ino b/libraries/HTTPUpdate/examples/httpUpdate/httpUpdate.ino new file mode 100644 index 00000000000..f646be04583 --- /dev/null +++ b/libraries/HTTPUpdate/examples/httpUpdate/httpUpdate.ino @@ -0,0 +1,72 @@ +/** + httpUpdate.ino + + Created on: 27.11.2015 + +*/ + +#include + +#include +#include + +#include +#include + +WiFiMulti WiFiMulti; + +void setup() { + + Serial.begin(115200); + // Serial.setDebugOutput(true); + + Serial.println(); + Serial.println(); + Serial.println(); + + for (uint8_t t = 4; t > 0; t--) { + Serial.printf("[SETUP] WAIT %d...\n", t); + Serial.flush(); + delay(1000); + } + + WiFi.mode(WIFI_STA); + WiFiMulti.addAP("SSID", "PASSWORD"); + + +} + +void loop() { + // wait for WiFi connection + if ((WiFiMulti.run() == WL_CONNECTED)) { + + WiFiClient client; + + // The line below is optional. It can be used to blink the LED on the board during flashing + // The LED will be on during download of one buffer of data from the network. The LED will + // be off during writing that buffer to flash + // On a good connection the LED should flash regularly. On a bad connection the LED will be + // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second + // value is used to put the LED on. If the LED is on with HIGH, that value should be passed + // httpUpdate.setLedPin(LED_BUILTIN, LOW); + + t_httpUpdate_return ret = httpUpdate.update(client, "http://server/file.bin"); + // Or: + //t_httpUpdate_return ret = httpUpdate.update(client, "server", 80, "file.bin"); + + switch (ret) { + case HTTP_UPDATE_FAILED: + Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); + break; + + case HTTP_UPDATE_NO_UPDATES: + Serial.println("HTTP_UPDATE_NO_UPDATES"); + break; + + case HTTP_UPDATE_OK: + Serial.println("HTTP_UPDATE_OK"); + break; + } + } +} + diff --git a/libraries/HTTPUpdate/examples/httpUpdateSPIFFS/httpUpdateSPIFFS.ino b/libraries/HTTPUpdate/examples/httpUpdateSPIFFS/httpUpdateSPIFFS.ino new file mode 100644 index 00000000000..a07e6d2f4aa --- /dev/null +++ b/libraries/HTTPUpdate/examples/httpUpdateSPIFFS/httpUpdateSPIFFS.ino @@ -0,0 +1,75 @@ +/** + httpUpdateSPIFFS.ino + + Created on: 05.12.2015 + +*/ + +#include + +#include +#include + +#include +#include + +WiFiMulti WiFiMulti; + +void setup() { + + Serial.begin(115200); + // Serial.setDebugOutput(true); + + Serial.println(); + Serial.println(); + Serial.println(); + + for (uint8_t t = 4; t > 0; t--) { + Serial.printf("[SETUP] WAIT %d...\n", t); + Serial.flush(); + delay(1000); + } + + WiFi.mode(WIFI_STA); + WiFiMulti.addAP("SSID", "PASSWORD"); + +} + +void loop() { + // wait for WiFi connection + if ((WiFiMulti.run() == WL_CONNECTED)) { + + Serial.println("Update SPIFFS..."); + + WiFiClient client; + + // The line below is optional. It can be used to blink the LED on the board during flashing + // The LED will be on during download of one buffer of data from the network. The LED will + // be off during writing that buffer to flash + // On a good connection the LED should flash regularly. On a bad connection the LED will be + // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second + // value is used to put the LED on. If the LED is on with HIGH, that value should be passed + // httpUpdate.setLedPin(LED_BUILTIN, LOW); + + t_httpUpdate_return ret = httpUpdate.updateSpiffs(client, "http://server/spiffs.bin"); + if (ret == HTTP_UPDATE_OK) { + Serial.println("Update sketch..."); + ret = httpUpdate.update(client, "http://server/file.bin"); + + switch (ret) { + case HTTP_UPDATE_FAILED: + Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); + break; + + case HTTP_UPDATE_NO_UPDATES: + Serial.println("HTTP_UPDATE_NO_UPDATES"); + break; + + case HTTP_UPDATE_OK: + Serial.println("HTTP_UPDATE_OK"); + break; + } + } + } +} + diff --git a/libraries/HTTPUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino b/libraries/HTTPUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino new file mode 100644 index 00000000000..5daa2a4f2a1 --- /dev/null +++ b/libraries/HTTPUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino @@ -0,0 +1,128 @@ +/** + httpUpdateSecure.ino + + Created on: 16.10.2018 as an adaptation of the ESP8266 version of httpUpdate.ino + +*/ + +#include +#include + +#include +#include + +#include + +WiFiMulti WiFiMulti; + +// Set time via NTP, as required for x.509 validation +void setClock() { + configTime(0, 0, "pool.ntp.org", "time.nist.gov"); // UTC + + Serial.print(F("Waiting for NTP time sync: ")); + time_t now = time(nullptr); + while (now < 8 * 3600 * 2) { + yield(); + delay(500); + Serial.print(F(".")); + now = time(nullptr); + } + + Serial.println(F("")); + struct tm timeinfo; + gmtime_r(&now, &timeinfo); + Serial.print(F("Current time: ")); + Serial.print(asctime(&timeinfo)); +} + +/** + * This is lets-encrypt-x3-cross-signed.pem + */ +const char* rootCACertificate = \ +"-----BEGIN CERTIFICATE-----\n" \ +"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \ +"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \ +"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \ +"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \ +"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \ +"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \ +"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \ +"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \ +"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \ +"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \ +"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \ +"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \ +"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \ +"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \ +"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \ +"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \ +"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \ +"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \ +"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \ +"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \ +"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \ +"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \ +"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \ +"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \ +"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \ +"-----END CERTIFICATE-----\n"; + +void setup() { + + Serial.begin(115200); + // Serial.setDebugOutput(true); + + Serial.println(); + Serial.println(); + Serial.println(); + + for (uint8_t t = 4; t > 0; t--) { + Serial.printf("[SETUP] WAIT %d...\n", t); + Serial.flush(); + delay(1000); + } + + WiFi.mode(WIFI_STA); + WiFiMulti.addAP("SSID", "PASSWORD"); +} + +void loop() { + // wait for WiFi connection + if ((WiFiMulti.run() == WL_CONNECTED)) { + + setClock(); + + WiFiClientSecure client; + client.setCACert(rootCACertificate); + + // Reading data over SSL may be slow, use an adequate timeout + client.setTimeout(12000 / 1000); // timeout argument is defined in seconds for setTimeout + + // The line below is optional. It can be used to blink the LED on the board during flashing + // The LED will be on during download of one buffer of data from the network. The LED will + // be off during writing that buffer to flash + // On a good connection the LED should flash regularly. On a bad connection the LED will be + // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second + // value is used to put the LED on. If the LED is on with HIGH, that value should be passed + // httpUpdate.setLedPin(LED_BUILTIN, HIGH); + + t_httpUpdate_return ret = httpUpdate.update(client, "https://server/file.bin"); + // Or: + //t_httpUpdate_return ret = httpUpdate.update(client, "server", 443, "file.bin"); + + + switch (ret) { + case HTTP_UPDATE_FAILED: + Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); + break; + + case HTTP_UPDATE_NO_UPDATES: + Serial.println("HTTP_UPDATE_NO_UPDATES"); + break; + + case HTTP_UPDATE_OK: + Serial.println("HTTP_UPDATE_OK"); + break; + } + } +} diff --git a/libraries/HTTPUpdate/keywords.txt b/libraries/HTTPUpdate/keywords.txt new file mode 100644 index 00000000000..78be600d420 --- /dev/null +++ b/libraries/HTTPUpdate/keywords.txt @@ -0,0 +1,42 @@ +####################################### +# Syntax Coloring Map For ESP8266httpUpdate +####################################### + +####################################### +# Library (KEYWORD3) +####################################### + +ESP8266httpUpdate KEYWORD3 RESERVED_WORD + +####################################### +# Datatypes (KEYWORD1) +####################################### + +HTTPUpdateResult KEYWORD1 DATA_TYPE +ESPhttpUpdate KEYWORD1 DATA_TYPE + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +rebootOnUpdate KEYWORD2 +update KEYWORD2 +updateSpiffs KEYWORD2 +getLastError KEYWORD2 +getLastErrorString KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +HTTP_UE_TOO_LESS_SPACE LITERAL1 RESERVED_WORD_2 +HTTP_UE_SERVER_NOT_REPORT_SIZE LITERAL1 RESERVED_WORD_2 +HTTP_UE_SERVER_FILE_NOT_FOUND LITERAL1 RESERVED_WORD_2 +HTTP_UE_SERVER_FORBIDDEN LITERAL1 RESERVED_WORD_2 +HTTP_UE_SERVER_WRONG_HTTP_CODE LITERAL1 RESERVED_WORD_2 +HTTP_UE_SERVER_FAULTY_MD5 LITERAL1 RESERVED_WORD_2 +HTTP_UE_BIN_VERIFY_HEADER_FAILED LITERAL1 RESERVED_WORD_2 +HTTP_UE_BIN_FOR_WRONG_FLASH LITERAL1 RESERVED_WORD_2 +HTTP_UPDATE_FAILED LITERAL1 RESERVED_WORD_2 +HTTP_UPDATE_NO_UPDATES LITERAL1 RESERVED_WORD_2 +HTTP_UPDATE_OK LITERAL1 RESERVED_WORD_2 diff --git a/libraries/HTTPUpdate/library.properties b/libraries/HTTPUpdate/library.properties new file mode 100644 index 00000000000..5147ddec2c9 --- /dev/null +++ b/libraries/HTTPUpdate/library.properties @@ -0,0 +1,9 @@ +name=HTTPUpdate +version=1.3 +author=Markus Sattler +maintainer=Markus Sattler +sentence=Http Update for ESP32 +paragraph= +category=Data Processing +url=https://github.com/Links2004/Arduino/tree/esp8266/hardware/esp8266com/esp8266/libraries/ESP8266httpUpdate +architectures=esp32 diff --git a/libraries/HTTPUpdate/src/HTTPUpdate.cpp b/libraries/HTTPUpdate/src/HTTPUpdate.cpp new file mode 100644 index 00000000000..f4c3d250fa7 --- /dev/null +++ b/libraries/HTTPUpdate/src/HTTPUpdate.cpp @@ -0,0 +1,417 @@ +/** + * + * @file HTTPUpdate.cpp based om ESP8266HTTPUpdate.cpp + * @date 16.10.2018 + * @author Markus Sattler + * + * Copyright (c) 2015 Markus Sattler. All rights reserved. + * This file is part of the ESP32 Http Updater. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include "HTTPUpdate.h" +#include + +#include +#include // get running partition + +// To do extern "C" uint32_t _SPIFFS_start; +// To do extern "C" uint32_t _SPIFFS_end; + +HTTPUpdate::HTTPUpdate(void) + : _httpClientTimeout(8000), _ledPin(-1) +{ +} + +HTTPUpdate::HTTPUpdate(int httpClientTimeout) + : _httpClientTimeout(httpClientTimeout), _ledPin(-1) +{ +} + +HTTPUpdate::~HTTPUpdate(void) +{ +} + +HTTPUpdateResult HTTPUpdate::update(WiFiClient& client, const String& url, const String& currentVersion) +{ + HTTPClient http; + if(!http.begin(client, url)) + { + return HTTP_UPDATE_FAILED; + } + return handleUpdate(http, currentVersion, false); +} + +HTTPUpdateResult HTTPUpdate::updateSpiffs(WiFiClient& client, const String& url, const String& currentVersion) +{ + HTTPClient http; + if(!http.begin(client, url)) + { + return HTTP_UPDATE_FAILED; + } + return handleUpdate(http, currentVersion, true); +} + +HTTPUpdateResult HTTPUpdate::update(WiFiClient& client, const String& host, uint16_t port, const String& uri, + const String& currentVersion) +{ + HTTPClient http; + if(!http.begin(client, host, port, uri)) + { + return HTTP_UPDATE_FAILED; + } + return handleUpdate(http, currentVersion, false); +} + +/** + * return error code as int + * @return int error code + */ +int HTTPUpdate::getLastError(void) +{ + return _lastError; +} + +/** + * return error code as String + * @return String error + */ +String HTTPUpdate::getLastErrorString(void) +{ + + if(_lastError == 0) { + return String(); // no error + } + + // error from Update class + if(_lastError > 0) { + StreamString error; + Update.printError(error); + error.trim(); // remove line ending + return String("Update error: ") + error; + } + + // error from http client + if(_lastError > -100) { + return String("HTTP error: ") + HTTPClient::errorToString(_lastError); + } + + switch(_lastError) { + case HTTP_UE_TOO_LESS_SPACE: + return "Not Enough space"; + case HTTP_UE_SERVER_NOT_REPORT_SIZE: + return "Server Did Not Report Size"; + case HTTP_UE_SERVER_FILE_NOT_FOUND: + return "File Not Found (404)"; + case HTTP_UE_SERVER_FORBIDDEN: + return "Forbidden (403)"; + case HTTP_UE_SERVER_WRONG_HTTP_CODE: + return "Wrong HTTP Code"; + case HTTP_UE_SERVER_FAULTY_MD5: + return "Wrong MD5"; + case HTTP_UE_BIN_VERIFY_HEADER_FAILED: + return "Verify Bin Header Failed"; + case HTTP_UE_BIN_FOR_WRONG_FLASH: + return "New Binary Does Not Fit Flash Size"; + case HTTP_UE_NO_PARTITION: + return "Partition Could Not be Found"; + } + + return String(); +} + + +String getSketchSHA256() { + const size_t HASH_LEN = 32; // SHA-256 digest length + + uint8_t sha_256[HASH_LEN] = { 0 }; + +// get sha256 digest for running partition + if(esp_partition_get_sha256(esp_ota_get_running_partition(), sha_256) == 0) { + char buffer[2 * HASH_LEN + 1]; + + for(size_t index = 0; index < HASH_LEN; index++) { + uint8_t nibble = (sha_256[index] & 0xf0) >> 4; + buffer[2 * index] = nibble < 10 ? char(nibble + '0') : char(nibble - 10 + 'A'); + + nibble = sha_256[index] & 0x0f; + buffer[2 * index + 1] = nibble < 10 ? char(nibble + '0') : char(nibble - 10 + 'A'); + } + + buffer[2 * HASH_LEN] = '\0'; + + return String(buffer); + } else { + + return String(); + } +} + +/** + * + * @param http HTTPClient * + * @param currentVersion const char * + * @return HTTPUpdateResult + */ +HTTPUpdateResult HTTPUpdate::handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs) +{ + + HTTPUpdateResult ret = HTTP_UPDATE_FAILED; + + // use HTTP/1.0 for update since the update handler not support any transfer Encoding + http.useHTTP10(true); + http.setTimeout(_httpClientTimeout); + http.setUserAgent("ESP32-http-Update"); + http.addHeader("Cache-Control", "no-cache"); + http.addHeader("x-ESP32-STA-MAC", WiFi.macAddress()); + http.addHeader("x-ESP32-AP-MAC", WiFi.softAPmacAddress()); + http.addHeader("x-ESP32-free-space", String(ESP.getFreeSketchSpace())); + http.addHeader("x-ESP32-sketch-size", String(ESP.getSketchSize())); + String sketchMD5 = ESP.getSketchMD5(); + if(sketchMD5.length() != 0) { + http.addHeader("x-ESP32-sketch-md5", sketchMD5); + } + // Add also a SHA256 + String sketchSHA256 = getSketchSHA256(); + if(sketchSHA256.length() != 0) { + http.addHeader("x-ESP32-sketch-sha256", sketchSHA256); + } + http.addHeader("x-ESP32-chip-size", String(ESP.getFlashChipSize())); + http.addHeader("x-ESP32-sdk-version", ESP.getSdkVersion()); + + if(spiffs) { + http.addHeader("x-ESP32-mode", "spiffs"); + } else { + http.addHeader("x-ESP32-mode", "sketch"); + } + + if(currentVersion && currentVersion[0] != 0x00) { + http.addHeader("x-ESP32-version", currentVersion); + } + + const char * headerkeys[] = { "x-MD5" }; + size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*); + + // track these headers + http.collectHeaders(headerkeys, headerkeyssize); + + + int code = http.GET(); + int len = http.getSize(); + + if(code <= 0) { + log_e("HTTP error: %s\n", http.errorToString(code).c_str()); + _lastError = code; + http.end(); + return HTTP_UPDATE_FAILED; + } + + + log_d("Header read fin.\n"); + log_d("Server header:\n"); + log_d(" - code: %d\n", code); + log_d(" - len: %d\n", len); + + if(http.hasHeader("x-MD5")) { + log_d(" - MD5: %s\n", http.header("x-MD5").c_str()); + } + + log_d("ESP32 info:\n"); + log_d(" - free Space: %d\n", ESP.getFreeSketchSpace()); + log_d(" - current Sketch Size: %d\n", ESP.getSketchSize()); + + if(currentVersion && currentVersion[0] != 0x00) { + log_d(" - current version: %s\n", currentVersion.c_str() ); + } + + switch(code) { + case HTTP_CODE_OK: ///< OK (Start Update) + if(len > 0) { + bool startUpdate = true; + if(spiffs) { + const esp_partition_t* _partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, NULL); + if(!_partition){ + _lastError = HTTP_UE_NO_PARTITION; + return HTTP_UPDATE_FAILED; + } + + if(len > _partition->size) { + log_e("spiffsSize to low (%d) needed: %d\n", _partition->size, len); + startUpdate = false; + } + } else { + int sketchFreeSpace = ESP.getFreeSketchSpace(); + if(!sketchFreeSpace){ + _lastError = HTTP_UE_NO_PARTITION; + return HTTP_UPDATE_FAILED; + } + + if(len > sketchFreeSpace) { + log_e("FreeSketchSpace to low (%d) needed: %d\n", sketchFreeSpace, len); + startUpdate = false; + } + } + + if(!startUpdate) { + _lastError = HTTP_UE_TOO_LESS_SPACE; + ret = HTTP_UPDATE_FAILED; + } else { + + WiFiClient * tcp = http.getStreamPtr(); + +// To do? WiFiUDP::stopAll(); +// To do? WiFiClient::stopAllExcept(tcp); + + delay(100); + + int command; + + if(spiffs) { + command = U_SPIFFS; + log_d("runUpdate spiffs...\n"); + } else { + command = U_FLASH; + log_d("runUpdate flash...\n"); + } + + if(!spiffs) { +/* To do + uint8_t buf[4]; + if(tcp->peekBytes(&buf[0], 4) != 4) { + log_e("peekBytes magic header failed\n"); + _lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED; + http.end(); + return HTTP_UPDATE_FAILED; + } +*/ + + // check for valid first magic byte +// if(buf[0] != 0xE9) { + if(tcp->peek() != 0xE9) { + log_e("Magic header does not start with 0xE9\n"); + _lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED; + http.end(); + return HTTP_UPDATE_FAILED; + + } +/* To do + uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4); + + // check if new bin fits to SPI flash + if(bin_flash_size > ESP.getFlashChipRealSize()) { + log_e("New binary does not fit SPI Flash size\n"); + _lastError = HTTP_UE_BIN_FOR_WRONG_FLASH; + http.end(); + return HTTP_UPDATE_FAILED; + } +*/ + } + if(runUpdate(*tcp, len, http.header("x-MD5"), command)) { + ret = HTTP_UPDATE_OK; + log_d("Update ok\n"); + http.end(); + + if(_rebootOnUpdate && !spiffs) { + ESP.restart(); + } + + } else { + ret = HTTP_UPDATE_FAILED; + log_e("Update failed\n"); + } + } + } else { + _lastError = HTTP_UE_SERVER_NOT_REPORT_SIZE; + ret = HTTP_UPDATE_FAILED; + log_e("Content-Length was 0 or wasn't set by Server?!\n"); + } + break; + case HTTP_CODE_NOT_MODIFIED: + ///< Not Modified (No updates) + ret = HTTP_UPDATE_NO_UPDATES; + break; + case HTTP_CODE_NOT_FOUND: + _lastError = HTTP_UE_SERVER_FILE_NOT_FOUND; + ret = HTTP_UPDATE_FAILED; + break; + case HTTP_CODE_FORBIDDEN: + _lastError = HTTP_UE_SERVER_FORBIDDEN; + ret = HTTP_UPDATE_FAILED; + break; + default: + _lastError = HTTP_UE_SERVER_WRONG_HTTP_CODE; + ret = HTTP_UPDATE_FAILED; + log_e("HTTP Code is (%d)\n", code); + break; + } + + http.end(); + return ret; +} + +/** + * write Update to flash + * @param in Stream& + * @param size uint32_t + * @param md5 String + * @return true if Update ok + */ +bool HTTPUpdate::runUpdate(Stream& in, uint32_t size, String md5, int command) +{ + + StreamString error; + + if(!Update.begin(size, command, _ledPin, _ledOn)) { + _lastError = Update.getError(); + Update.printError(error); + error.trim(); // remove line ending + log_e("Update.begin failed! (%s)\n", error.c_str()); + return false; + } + + if(md5.length()) { + if(!Update.setMD5(md5.c_str())) { + _lastError = HTTP_UE_SERVER_FAULTY_MD5; + log_e("Update.setMD5 failed! (%s)\n", md5.c_str()); + return false; + } + } + +// To do: the SHA256 could be checked if the server sends it + + if(Update.writeStream(in) != size) { + _lastError = Update.getError(); + Update.printError(error); + error.trim(); // remove line ending + log_e("Update.writeStream failed! (%s)\n", error.c_str()); + return false; + } + + if(!Update.end()) { + _lastError = Update.getError(); + Update.printError(error); + error.trim(); // remove line ending + log_e("Update.end failed! (%s)\n", error.c_str()); + return false; + } + + return true; +} + +#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_HTTPUPDATE) +HTTPUpdate httpUpdate; +#endif diff --git a/libraries/HTTPUpdate/src/HTTPUpdate.h b/libraries/HTTPUpdate/src/HTTPUpdate.h new file mode 100644 index 00000000000..f126cba0639 --- /dev/null +++ b/libraries/HTTPUpdate/src/HTTPUpdate.h @@ -0,0 +1,101 @@ +/** + * + * @file HTTPUpdate.h based on ESP8266HTTPUpdate.h + * @date 16.10.2018 + * @author Markus Sattler + * + * Copyright (c) 2015 Markus Sattler. All rights reserved. + * This file is part of the ESP32 Http Updater. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ___HTTP_UPDATE_H___ +#define ___HTTP_UPDATE_H___ + +#include +#include +#include +#include +#include +#include + +/// note we use HTTP client errors too so we start at 100 +#define HTTP_UE_TOO_LESS_SPACE (-100) +#define HTTP_UE_SERVER_NOT_REPORT_SIZE (-101) +#define HTTP_UE_SERVER_FILE_NOT_FOUND (-102) +#define HTTP_UE_SERVER_FORBIDDEN (-103) +#define HTTP_UE_SERVER_WRONG_HTTP_CODE (-104) +#define HTTP_UE_SERVER_FAULTY_MD5 (-105) +#define HTTP_UE_BIN_VERIFY_HEADER_FAILED (-106) +#define HTTP_UE_BIN_FOR_WRONG_FLASH (-107) +#define HTTP_UE_NO_PARTITION (-108) + +enum HTTPUpdateResult { + HTTP_UPDATE_FAILED, + HTTP_UPDATE_NO_UPDATES, + HTTP_UPDATE_OK +}; + +typedef HTTPUpdateResult t_httpUpdate_return; // backward compatibility + +class HTTPUpdate +{ +public: + HTTPUpdate(void); + HTTPUpdate(int httpClientTimeout); + ~HTTPUpdate(void); + + void rebootOnUpdate(bool reboot) + { + _rebootOnUpdate = reboot; + } + + void setLedPin(int ledPin = -1, uint8_t ledOn = HIGH) + { + _ledPin = ledPin; + _ledOn = ledOn; + } + + t_httpUpdate_return update(WiFiClient& client, const String& url, const String& currentVersion = ""); + + t_httpUpdate_return update(WiFiClient& client, const String& host, uint16_t port, const String& uri = "/", + const String& currentVersion = ""); + + t_httpUpdate_return updateSpiffs(WiFiClient& client, const String& url, const String& currentVersion = ""); + + + int getLastError(void); + String getLastErrorString(void); + +protected: + t_httpUpdate_return handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs = false); + bool runUpdate(Stream& in, uint32_t size, String md5, int command = U_FLASH); + + int _lastError; + bool _rebootOnUpdate = true; +private: + int _httpClientTimeout; + + int _ledPin; + uint8_t _ledOn; +}; + +#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_HTTPUPDATE) +extern HTTPUpdate httpUpdate; +#endif + +#endif /* ___HTTP_UPDATE_H___ */ diff --git a/libraries/NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino b/libraries/NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino new file mode 100755 index 00000000000..0f49e5aad6c --- /dev/null +++ b/libraries/NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino @@ -0,0 +1,31 @@ +#include +#include + +const char* ssid = "............"; +const char* password = ".............."; + +void setup() { + Serial.begin(115200); + + // Connect to WiFi network + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + Serial.println(""); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.print("Connected to "); + Serial.println(ssid); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + NBNS.begin("ESP"); +} + +void loop() { + +} diff --git a/libraries/NetBIOS/keywords.txt b/libraries/NetBIOS/keywords.txt new file mode 100755 index 00000000000..68bcbeee1a5 --- /dev/null +++ b/libraries/NetBIOS/keywords.txt @@ -0,0 +1,25 @@ +####################################### +# Syntax Coloring Map For ESPNBNS +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +NetBIOS KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 + +####################################### +# Instances (KEYWORD2) +####################################### + +NBNS KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/libraries/NetBIOS/library.properties b/libraries/NetBIOS/library.properties new file mode 100644 index 00000000000..50e6e79c099 --- /dev/null +++ b/libraries/NetBIOS/library.properties @@ -0,0 +1,9 @@ +name=NetBIOS +version=1.0 +author=Pablo@xpablo.cz +maintainer=Hristo Gochkov +sentence=Enables NBNS (NetBIOS) name resolution. +paragraph=With this library you can connect to your ESP from Windows using a short name +category=Communication +url=http://www.xpablo.cz/?p=751#more-751 +architectures=esp32 diff --git a/libraries/NetBIOS/src/NetBIOS.cpp b/libraries/NetBIOS/src/NetBIOS.cpp new file mode 100755 index 00000000000..22d3deca43b --- /dev/null +++ b/libraries/NetBIOS/src/NetBIOS.cpp @@ -0,0 +1,131 @@ +#include "NetBIOS.h" + +#include + +#define NBNS_PORT 137 +#define NBNS_MAX_HOSTNAME_LEN 32 + +typedef struct { + uint16_t id; + uint8_t flags1; + uint8_t flags2; + uint16_t qcount; + uint16_t acount; + uint16_t nscount; + uint16_t adcount; + uint8_t name_len; + char name[NBNS_MAX_HOSTNAME_LEN + 1]; + uint16_t type; + uint16_t clas; +} __attribute__((packed)) nbns_question_t; + +typedef struct { + uint16_t id; + uint8_t flags1; + uint8_t flags2; + uint16_t qcount; + uint16_t acount; + uint16_t nscount; + uint16_t adcount; + uint8_t name_len; + char name[NBNS_MAX_HOSTNAME_LEN + 1]; + uint16_t type; + uint16_t clas; + uint32_t ttl; + uint16_t data_len; + uint16_t flags; + uint32_t addr; +} __attribute__((packed)) nbns_answer_t; + +static void _getnbname(const char *nbname, char *name, uint8_t maxlen){ + uint8_t b; + uint8_t c = 0; + + while ((*nbname) && (c < maxlen)) { + b = (*nbname++ - 'A') << 4; + c++; + if (*nbname) { + b |= *nbname++ - 'A'; + c++; + } + if(!b || b == ' '){ + break; + } + *name++ = b; + } + *name = 0; +} + +static void append_16(void * dst, uint16_t value){ + uint8_t * d = (uint8_t *)dst; + *d++ = (value >> 8) & 0xFF; + *d++ = value & 0xFF; +} + +static void append_32(void * dst, uint32_t value){ + uint8_t * d = (uint8_t *)dst; + *d++ = (value >> 24) & 0xFF; + *d++ = (value >> 16) & 0xFF; + *d++ = (value >> 8) & 0xFF; + *d++ = value & 0xFF; +} + +void NetBIOS::_onPacket(AsyncUDPPacket& packet){ + if (packet.length() >= sizeof(nbns_question_t)) { + nbns_question_t * question = (nbns_question_t *)packet.data(); + if (0 == (question->flags1 & 0x80)) { + char name[ NBNS_MAX_HOSTNAME_LEN + 1 ]; + _getnbname(&question->name[0], (char *)&name, question->name_len); + if (_name.equals(name)) { + nbns_answer_t nbnsa; + nbnsa.id = question->id; + nbnsa.flags1 = 0x85; + nbnsa.flags2 = 0; + append_16((void *)&nbnsa.qcount, 0); + append_16((void *)&nbnsa.acount, 1); + append_16((void *)&nbnsa.nscount, 0); + append_16((void *)&nbnsa.adcount, 0); + nbnsa.name_len = question->name_len; + memcpy(&nbnsa.name[0], &question->name[0], question->name_len + 1); + append_16((void *)&nbnsa.type, 0x20); + append_16((void *)&nbnsa.clas, 1); + append_32((void *)&nbnsa.ttl, 300000); + append_16((void *)&nbnsa.data_len, 6); + append_16((void *)&nbnsa.flags, 0); + nbnsa.addr = WiFi.localIP(); + _udp.writeTo((uint8_t *)&nbnsa, sizeof(nbnsa), packet.remoteIP(), NBNS_PORT); + } + } + } +} + +NetBIOS::NetBIOS(){ + +} +NetBIOS::~NetBIOS(){ + end(); +} + +bool NetBIOS::begin(const char *name){ + _name = name; + _name.toUpperCase(); + + if(_udp.connected()){ + return true; + } + + _udp.onPacket([](void * arg, AsyncUDPPacket& packet){ ((NetBIOS*)(arg))->_onPacket(packet); }, this); + return _udp.listen(NBNS_PORT); +} + +void NetBIOS::end(){ + if(_udp.connected()){ + _udp.close(); + } +} + +#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_NETBIOS) +NetBIOS NBNS; +#endif + +// EOF diff --git a/libraries/NetBIOS/src/NetBIOS.h b/libraries/NetBIOS/src/NetBIOS.h new file mode 100755 index 00000000000..0321f6b8b91 --- /dev/null +++ b/libraries/NetBIOS/src/NetBIOS.h @@ -0,0 +1,26 @@ +// +#ifndef __ESPNBNS_h__ +#define __ESPNBNS_h__ + +#include +#include "AsyncUDP.h" + +class NetBIOS +{ +protected: + AsyncUDP _udp; + String _name; + void _onPacket(AsyncUDPPacket& packet); + +public: + NetBIOS(); + ~NetBIOS(); + bool begin(const char *name); + void end(); +}; + +#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_NETBIOS) +extern NetBIOS NBNS; +#endif + +#endif diff --git a/libraries/Preferences/examples/Prefs2Struct/Prefs2Struct.ino b/libraries/Preferences/examples/Prefs2Struct/Prefs2Struct.ino new file mode 100644 index 00000000000..7ed2a73bcbe --- /dev/null +++ b/libraries/Preferences/examples/Prefs2Struct/Prefs2Struct.ino @@ -0,0 +1,43 @@ +/* +This example shows how to use Preferences (nvs) to store a +structure. Note that the maximum size of a putBytes is 496K +or 97% of the nvs partition size. nvs has signifcant overhead, +so should not be used for data that will change often. +*/ +#include +Preferences prefs; + +typedef struct { + uint8_t hour; + uint8_t minute; + uint8_t setting1; + uint8_t setting2; +} schedule_t; + +void setup() { + Serial.begin(115200); + prefs.begin("schedule"); // use "schedule" namespace + uint8_t content[] = {9, 30, 235, 255, 20, 15, 0, 1}; // two entries + prefs.putBytes("schedule", content, sizeof(content)); + size_t schLen = prefs.getBytesLength("schedule"); + char buffer[schLen]; // prepare a buffer for the data + prefs.getBytes("schedule", buffer, schLen); + if (schLen % sizeof(schedule_t)) { // simple check that data fits + log_e("Data is not correct size!"); + return; + } + schedule_t *schedule = (schedule_t *) buffer; // cast the bytes into a struct ptr + Serial.printf("%02d:%02d %d/%d\n", + schedule[1].hour, schedule[1].minute, + schedule[1].setting1, schedule[1].setting2); + schedule[2] = {8, 30, 20, 21}; // add a third entry (unsafely) +// force the struct array into a byte array + prefs.putBytes("schedule", schedule, 3*sizeof(schedule_t)); + schLen = prefs.getBytesLength("schedule"); + char buffer2[schLen]; + prefs.getBytes("schedule", buffer2, schLen); + for (int x=0; x maxLen){ log_e("not enough space in buffer: %u < %u", maxLen, len); return 0; } - err = nvs_get_blob(_handle, key, buf, &len); + esp_err_t err = nvs_get_blob(_handle, key, buf, &len); if(err){ log_e("nvs_get_blob fail: %s %s", key, nvs_error(err)); return 0; } return len; } + +size_t Preferences::freeEntries() { + nvs_stats_t nvs_stats; + esp_err_t err = nvs_get_stats(NULL, &nvs_stats); + if(err){ + log_e("Failed to get nvs statistics"); + return 0; + } + return nvs_stats.free_entries; +} diff --git a/libraries/Preferences/src/Preferences.h b/libraries/Preferences/src/Preferences.h index cf98e8ef8cf..0ad94afbbad 100644 --- a/libraries/Preferences/src/Preferences.h +++ b/libraries/Preferences/src/Preferences.h @@ -63,7 +63,9 @@ class Preferences { bool getBool(const char* key, bool defaultValue = false); size_t getString(const char* key, char* value, size_t maxLen); String getString(const char* key, String defaultValue = String()); + size_t getBytesLength(const char* key); size_t getBytes(const char* key, void * buf, size_t maxLen); + size_t freeEntries(); }; #endif diff --git a/libraries/README.md b/libraries/README.md new file mode 100644 index 00000000000..89da3568ff0 --- /dev/null +++ b/libraries/README.md @@ -0,0 +1,95 @@ +# ESP32 Libraries + +arduino-esp32 includes libraries for Arduino compatibility along with some object wrappers around hardware specific devices. Examples are included in the examples folder under each library folder. The ESP32 includes additional examples which need no special drivers. + +### ArduinoOTA + Over The Air firmware update daemon. Use espota.py to upload to the device. + +### AsyncUDP + Asynchronous task driven UDP datagram client/server + +### AzureIoT + Library to interact with Microsoft Azure IoT services + +### BLE + Bluetooth Low Energy v4.2 client/server framework + +### BluetoothSerial + Serial to Bluetooth redirection server + +### DNSServer + A basic UDP DNS daemon (includes captive portal demo) + +### EEPROM + Arduino compatibility for EEPROM (using flash) + +### ESP32 + Additional examples + * AnalogOut + * Camera + * ChipID + * DeepSleep + * ESPNow + * FreeRTOS + * GPIO + * HallSensor + * I2S + * ResetReason + * RMT + * Time + * Timer + * Touch + +### ESPmDNS + mDNS service advertising + +### FFat + FAT indexed filesystem on SPI flash + +### FS + Filesystem virtualization framework + +### HTTPClient + A simple HTTP client, compatible with WiFiClientSecure + +### HTTPUpdate + Download a firmware update from HTTPd and apply it using Update + +### NetBIOS + NetBIOS name advertiser + +### Preferences + Flash keystore using ESP32 NVS + +### SD + Secure Digital card filesystem using SPI access + +### SD_MMC + Secure Digital card filesystem using 4-lane access + +### SimpleBLE + Minimal BLE advertiser + +### SPI + Arduino compatible Serial Peripheral Interface driver (master only) + +### SPIFFS + SPI Flash Filesystem (see [spiffs-plugin](https://github.com/me-no-dev/arduino-esp32fs-plugin) to upload to device) + +### Ticker + A timer to call functions on an interval + +### Update + Sketch Update using ESP32 OTA functionality + +### WebServer + A simple HTTP daemon + +### WiFi + Arduino compatible WiFi driver (includes Ethernet driver) + +### WiFiClientSecure + Arduino compatible WiFi client object using embedded encryption + +### Wire + Arduino compatible I2C driver (master only) diff --git a/libraries/SD/src/SD.cpp b/libraries/SD/src/SD.cpp index 40d16c869a0..d268aa0fb97 100644 --- a/libraries/SD/src/SD.cpp +++ b/libraries/SD/src/SD.cpp @@ -22,7 +22,7 @@ using namespace fs; SDFS::SDFS(FSImplPtr impl): FS(impl), _pdrv(0xFF) {} -bool SDFS::begin(uint8_t ssPin, SPIClass &spi, uint32_t frequency, const char * mountpoint) +bool SDFS::begin(uint8_t ssPin, SPIClass &spi, uint32_t frequency, const char * mountpoint, uint8_t max_files) { if(_pdrv != 0xFF) { return true; @@ -35,7 +35,7 @@ bool SDFS::begin(uint8_t ssPin, SPIClass &spi, uint32_t frequency, const char * return false; } - if(!sdcard_mount(_pdrv, mountpoint)){ + if(!sdcard_mount(_pdrv, mountpoint, max_files)){ sdcard_unmount(_pdrv); sdcard_uninit(_pdrv); _pdrv = 0xFF; diff --git a/libraries/SD/src/SD.h b/libraries/SD/src/SD.h index 54e41ce38ab..da66c386c88 100644 --- a/libraries/SD/src/SD.h +++ b/libraries/SD/src/SD.h @@ -28,7 +28,7 @@ class SDFS : public FS public: SDFS(FSImplPtr impl); - bool begin(uint8_t ssPin=SS, SPIClass &spi=SPI, uint32_t frequency=4000000, const char * mountpoint="/sd"); + bool begin(uint8_t ssPin=SS, SPIClass &spi=SPI, uint32_t frequency=4000000, const char * mountpoint="/sd", uint8_t max_files=5); void end(); sdcard_type_t cardType(); uint64_t cardSize(); diff --git a/libraries/SD/src/sd_diskio.cpp b/libraries/SD/src/sd_diskio.cpp index 3dfbc040c73..0a9c86cc5f0 100644 --- a/libraries/SD/src/sd_diskio.cpp +++ b/libraries/SD/src/sd_diskio.cpp @@ -16,7 +16,7 @@ extern "C" { #include "diskio.h" #include "ffconf.h" #include "ff.h" - #include "esp_vfs.h" + //#include "esp_vfs.h" #include "esp_vfs_fat.h" char CRC7(const char* data, int length); unsigned short CRC16(const char* data, int length); @@ -711,7 +711,7 @@ uint8_t sdcard_unmount(uint8_t pdrv) return 0; } -bool sdcard_mount(uint8_t pdrv, const char* path) +bool sdcard_mount(uint8_t pdrv, const char* path, uint8_t max_files) { ardu_sdcard_t * card = s_cards[pdrv]; if(pdrv >= FF_VOLUMES || card == NULL){ @@ -725,7 +725,7 @@ bool sdcard_mount(uint8_t pdrv, const char* path) FATFS* fs; char drv[3] = {(char)('0' + pdrv), ':', 0}; - esp_err_t err = esp_vfs_fat_register(path, drv, 5, &fs); + esp_err_t err = esp_vfs_fat_register(path, drv, max_files, &fs); if (err == ESP_ERR_INVALID_STATE) { log_e("esp_vfs_fat_register failed 0x(%x): SD is registered.", err); return false; diff --git a/libraries/SD/src/sd_diskio.h b/libraries/SD/src/sd_diskio.h index 177542575ad..143be683e63 100644 --- a/libraries/SD/src/sd_diskio.h +++ b/libraries/SD/src/sd_diskio.h @@ -21,7 +21,7 @@ uint8_t sdcard_init(uint8_t cs, SPIClass * spi, int hz); uint8_t sdcard_uninit(uint8_t pdrv); -bool sdcard_mount(uint8_t pdrv, const char* path); +bool sdcard_mount(uint8_t pdrv, const char* path, uint8_t max_files); uint8_t sdcard_unmount(uint8_t pdrv); sdcard_type_t sdcard_type(uint8_t pdrv); diff --git a/libraries/SD_MMC/src/SD_MMC.cpp b/libraries/SD_MMC/src/SD_MMC.cpp index 104769693ad..4de467304e5 100644 --- a/libraries/SD_MMC/src/SD_MMC.cpp +++ b/libraries/SD_MMC/src/SD_MMC.cpp @@ -42,7 +42,22 @@ bool SDMMCFS::begin(const char * mountpoint, bool mode1bit) } //mount sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); - sdmmc_host_t host = SDMMC_HOST_DEFAULT(); + sdmmc_host_t host = { + .flags = SDMMC_HOST_FLAG_4BIT, + .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 + }; host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; #ifdef BOARD_HAS_1BIT_SDMMC mode1bit = true; @@ -53,7 +68,8 @@ bool SDMMCFS::begin(const char * mountpoint, bool mode1bit) esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = false, - .max_files = 5 + .max_files = 5, + .allocation_unit_size = 0 }; esp_err_t ret = esp_vfs_fat_sdmmc_mount(mountpoint, &host, &slot_config, &mount_config, &_card); diff --git a/libraries/SPI/examples/SPI_Multiple_Buses/SPI_Multiple_Buses.ino b/libraries/SPI/examples/SPI_Multiple_Buses/SPI_Multiple_Buses.ino new file mode 100644 index 00000000000..76ead2d0a2e --- /dev/null +++ b/libraries/SPI/examples/SPI_Multiple_Buses/SPI_Multiple_Buses.ino @@ -0,0 +1,77 @@ + + +/* The ESP32 has four SPi buses, however as of right now only two of + * them are available to use, HSPI and VSPI. Simply using the SPI API + * as illustrated in Arduino examples will use VSPI, leaving HSPI unused. + * + * However if we simply intialise two instance of the SPI class for both + * of these buses both can be used. However when just using these the Arduino + * way only will actually be outputting at a time. + * + * Logic analyser capture is in the same folder as this example as + * "multiple_bus_output.png" + * + * created 30/04/2018 by Alistair Symonds + */ +#include + +static const int spiClk = 1000000; // 1 MHz + +//uninitalised pointers to SPI objects +SPIClass * vspi = NULL; +SPIClass * hspi = NULL; + +void setup() { + //initialise two instances of the SPIClass attached to VSPI and HSPI respectively + vspi = new SPIClass(VSPI); + hspi = new SPIClass(HSPI); + + //clock miso mosi ss + + //initialise vspi with default pins + //SCLK = 18, MISO = 19, MOSI = 23, SS = 5 + vspi->begin(); + //alternatively route through GPIO pins of your choice + //hspi->begin(0, 2, 4, 33); //SCLK, MISO, MOSI, SS + + //initialise hspi with default pins + //SCLK = 14, MISO = 12, MOSI = 13, SS = 15 + hspi->begin(); + //alternatively route through GPIO pins + //hspi->begin(25, 26, 27, 32); //SCLK, MISO, MOSI, SS + + //set up slave select pins as outputs as the Arduino API + //doesn't handle automatically pulling SS low + pinMode(5, OUTPUT); //VSPI SS + pinMode(15, OUTPUT); //HSPI SS + +} + +// the loop function runs over and over again until power down or reset +void loop() { + //use the SPI buses + vspiCommand(); + hspiCommand(); + delay(100); +} + +void vspiCommand() { + byte data = 0b01010101; // junk data to illustrate usage + + //use it as you would the regular arduino SPI API + vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0)); + digitalWrite(5, LOW); //pull SS slow to prep other end for transfer + vspi->transfer(data); + digitalWrite(5, HIGH); //pull ss high to signify end of data transfer + vspi->endTransaction(); +} + +void hspiCommand() { + byte stuff = 0b11001100; + + hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0)); + digitalWrite(15, LOW); + hspi->transfer(stuff); + digitalWrite(15, HIGH); + hspi->endTransaction(); +} diff --git a/libraries/SPI/examples/SPI_Multiple_Buses/multiple_bus_output.PNG b/libraries/SPI/examples/SPI_Multiple_Buses/multiple_bus_output.PNG new file mode 100644 index 00000000000..02b89f6a001 Binary files /dev/null and b/libraries/SPI/examples/SPI_Multiple_Buses/multiple_bus_output.PNG differ diff --git a/libraries/SPI/src/SPI.cpp b/libraries/SPI/src/SPI.cpp index 006987463f5..beebe0ea5a3 100644 --- a/libraries/SPI/src/SPI.cpp +++ b/libraries/SPI/src/SPI.cpp @@ -31,7 +31,7 @@ SPIClass::SPIClass(uint8_t spi_bus) ,_ss(-1) ,_div(0) ,_freq(1000000) - , _inTransaction(false) + ,_inTransaction(false) {} void SPIClass::begin(int8_t sck, int8_t miso, int8_t mosi, int8_t ss) @@ -109,6 +109,11 @@ void SPIClass::setClockDivider(uint32_t clockDiv) spiSetClockDiv(_spi, _div); } +uint32_t SPIClass::getClockDivider() +{ + return spiGetClockDiv(_spi); +} + void SPIClass::setDataMode(uint8_t dataMode) { spiSetDataMode(_spi, dataMode); @@ -199,7 +204,7 @@ void SPIClass::transferBits(uint32_t data, uint32_t * out, uint8_t bits) * @param data uint8_t * * @param size uint32_t */ -void SPIClass::writeBytes(uint8_t * data, uint32_t size) +void SPIClass::writeBytes(const uint8_t * data, uint32_t size) { if(_inTransaction){ return spiWriteNL(_spi, data, size); @@ -209,6 +214,11 @@ void SPIClass::writeBytes(uint8_t * data, uint32_t size) spiEndTransaction(_spi); } +void SPIClass::transfer(uint8_t * data, uint32_t size) +{ + transferBytes(data, data, size); +} + /** * @param data void * * @param size uint32_t @@ -228,7 +238,7 @@ void SPIClass::writePixels(const void * data, uint32_t size) * @param out uint8_t * output buffer. can be NULL for Write Only operation * @param size uint32_t */ -void SPIClass::transferBytes(uint8_t * data, uint8_t * out, uint32_t size) +void SPIClass::transferBytes(const uint8_t * data, uint8_t * out, uint32_t size) { if(_inTransaction){ return spiTransferBytesNL(_spi, data, out, size); @@ -241,7 +251,7 @@ void SPIClass::transferBytes(uint8_t * data, uint8_t * out, uint32_t size) * @param size uint8_t max for size is 64Byte * @param repeat uint32_t */ -void SPIClass::writePattern(uint8_t * data, uint8_t size, uint32_t repeat) +void SPIClass::writePattern(const uint8_t * data, uint8_t size, uint32_t repeat) { if(size > 64) { return; //max Hardware FIFO @@ -262,12 +272,12 @@ void SPIClass::writePattern(uint8_t * data, uint8_t size, uint32_t repeat) } } -void SPIClass::writePattern_(uint8_t * data, uint8_t size, uint8_t repeat) +void SPIClass::writePattern_(const uint8_t * data, uint8_t size, uint8_t repeat) { uint8_t bytes = (size * repeat); uint8_t buffer[64]; uint8_t * bufferPtr = &buffer[0]; - uint8_t * dataPtr; + const uint8_t * dataPtr; uint8_t dataSize = bytes; for(uint8_t i = 0; i < repeat; i++) { dataSize = size; diff --git a/libraries/SPI/src/SPI.h b/libraries/SPI/src/SPI.h index 0d1a83a8fe4..416fb363290 100644 --- a/libraries/SPI/src/SPI.h +++ b/libraries/SPI/src/SPI.h @@ -48,7 +48,7 @@ class SPIClass uint32_t _div; uint32_t _freq; bool _inTransaction; - void writePattern_(uint8_t * data, uint8_t size, uint8_t repeat); + void writePattern_(const uint8_t * data, uint8_t size, uint8_t repeat); public: SPIClass(uint8_t spi_bus=HSPI); @@ -60,22 +60,25 @@ class SPIClass void setDataMode(uint8_t dataMode); void setFrequency(uint32_t freq); void setClockDivider(uint32_t clockDiv); + + uint32_t getClockDivider(); void beginTransaction(SPISettings settings); void endTransaction(void); - + void transfer(uint8_t * data, uint32_t size); uint8_t transfer(uint8_t data); uint16_t transfer16(uint16_t data); uint32_t transfer32(uint32_t data); - void transferBytes(uint8_t * data, uint8_t * out, uint32_t size); + + void transferBytes(const uint8_t * data, uint8_t * out, uint32_t size); void transferBits(uint32_t data, uint32_t * out, uint8_t bits); void write(uint8_t data); void write16(uint16_t data); void write32(uint32_t data); - void writeBytes(uint8_t * data, uint32_t size); + void writeBytes(const uint8_t * data, uint32_t size); void writePixels(const void * data, uint32_t size);//ili9341 compatible - void writePattern(uint8_t * data, uint8_t size, uint32_t repeat); + void writePattern(const uint8_t * data, uint8_t size, uint32_t repeat); spi_t * bus(){ return _spi; } }; diff --git a/libraries/SPIFFS/examples/SPIFFS_Test/SPIFFS_Test.ino b/libraries/SPIFFS/examples/SPIFFS_Test/SPIFFS_Test.ino index 65b4859b6cf..730e90ebf50 100644 --- a/libraries/SPIFFS/examples/SPIFFS_Test/SPIFFS_Test.ino +++ b/libraries/SPIFFS/examples/SPIFFS_Test/SPIFFS_Test.ino @@ -1,6 +1,11 @@ #include "FS.h" #include "SPIFFS.h" +/* You only need to format SPIFFS the first time you run a + test or else use the SPIFFS plugin to create a partition + https://github.com/me-no-dev/arduino-esp32fs-plugin */ +#define FORMAT_SPIFFS_IF_FAILED true + void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ Serial.printf("Listing directory: %s\r\n", dirname); @@ -58,7 +63,7 @@ void writeFile(fs::FS &fs, const char * path, const char * message){ if(file.print(message)){ Serial.println("- file written"); } else { - Serial.println("- frite failed"); + Serial.println("- write failed"); } } @@ -151,7 +156,7 @@ void testFileIO(fs::FS &fs, const char * path){ void setup(){ Serial.begin(115200); - if(!SPIFFS.begin()){ + if(!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)){ Serial.println("SPIFFS Mount Failed"); return; } diff --git a/libraries/SPIFFS/src/SPIFFS.cpp b/libraries/SPIFFS/src/SPIFFS.cpp index adc9148ae54..db97fa2bf94 100644 --- a/libraries/SPIFFS/src/SPIFFS.cpp +++ b/libraries/SPIFFS/src/SPIFFS.cpp @@ -20,13 +20,33 @@ extern "C" { #include #include "esp_spiffs.h" } + #include "SPIFFS.h" using namespace fs; -SPIFFSFS::SPIFFSFS(FSImplPtr impl) - : FS(impl) -{} +class SPIFFSImpl : public VFSImpl +{ +public: + SPIFFSImpl(); + virtual ~SPIFFSImpl() { } + virtual bool exists(const char* path); +}; + +SPIFFSImpl::SPIFFSImpl() +{ +} + +bool SPIFFSImpl::exists(const char* path) +{ + File f = open(path, "r"); + return (f == true) && !f.isDirectory(); +} + +SPIFFSFS::SPIFFSFS() : FS(FSImplPtr(new SPIFFSImpl())) +{ + +} bool SPIFFSFS::begin(bool formatOnFail, const char * basePath, uint8_t maxOpenFiles) { @@ -39,11 +59,16 @@ bool SPIFFSFS::begin(bool formatOnFail, const char * basePath, uint8_t maxOpenFi .base_path = basePath, .partition_label = NULL, .max_files = maxOpenFiles, - .format_if_mount_failed = formatOnFail + .format_if_mount_failed = false }; esp_err_t err = esp_vfs_spiffs_register(&conf); - if(err){ + if(err == ESP_FAIL && formatOnFail){ + if(format()){ + err = esp_vfs_spiffs_register(&conf); + } + } + if(err != ESP_OK){ log_e("Mounting SPIFFS failed! Error: %d", err); return false; } @@ -65,7 +90,9 @@ void SPIFFSFS::end() bool SPIFFSFS::format() { + disableCore0WDT(); esp_err_t err = esp_spiffs_format(NULL); + enableCore0WDT(); if(err){ log_e("Formatting SPIFFS failed! Error: %d", err); return false; @@ -91,16 +118,5 @@ size_t SPIFFSFS::usedBytes() return used; } -bool SPIFFSFS::exists(const char* path) -{ - File f = open(path, "r"); - return (f == true) && !f.isDirectory(); -} - -bool SPIFFSFS::exists(const String& path) -{ - return exists(path.c_str()); -} - +SPIFFSFS SPIFFS; -SPIFFSFS SPIFFS = SPIFFSFS(FSImplPtr(new VFSImpl())); diff --git a/libraries/SPIFFS/src/SPIFFS.h b/libraries/SPIFFS/src/SPIFFS.h index fe697b78fc8..7d35da0439a 100644 --- a/libraries/SPIFFS/src/SPIFFS.h +++ b/libraries/SPIFFS/src/SPIFFS.h @@ -22,18 +22,17 @@ namespace fs class SPIFFSFS : public FS { public: - SPIFFSFS(FSImplPtr impl); + SPIFFSFS(); bool begin(bool formatOnFail=false, const char * basePath="/spiffs", uint8_t maxOpenFiles=10); bool format(); size_t totalBytes(); size_t usedBytes(); void end(); - bool exists(const char* path); - bool exists(const String& path); }; } extern fs::SPIFFSFS SPIFFS; -#endif /* _SPIFFS_H_ */ + +#endif diff --git a/libraries/SimpleBLE/src/SimpleBLE.cpp b/libraries/SimpleBLE/src/SimpleBLE.cpp index 68064723c24..d30a177fdf2 100644 --- a/libraries/SimpleBLE/src/SimpleBLE.cpp +++ b/libraries/SimpleBLE/src/SimpleBLE.cpp @@ -19,8 +19,7 @@ #include "SimpleBLE.h" #include "esp32-hal-log.h" -#include "bt.h" -#include "bta_api.h" +#include "esp_bt.h" #include "esp_gap_ble_api.h" #include "esp_gatts_api.h" #include "esp_bt_defs.h" diff --git a/libraries/SimpleBLE/src/SimpleBLE.h b/libraries/SimpleBLE/src/SimpleBLE.h index e43d90379a7..6e7b702da5a 100644 --- a/libraries/SimpleBLE/src/SimpleBLE.h +++ b/libraries/SimpleBLE/src/SimpleBLE.h @@ -25,7 +25,7 @@ #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" -#include "bt.h" +#include "esp_bt.h" #include "Arduino.h" diff --git a/libraries/Ticker/src/Ticker.cpp b/libraries/Ticker/src/Ticker.cpp index ce5cf69332c..1deeb7fb69f 100644 --- a/libraries/Ticker/src/Ticker.cpp +++ b/libraries/Ticker/src/Ticker.cpp @@ -43,9 +43,9 @@ void Ticker::_attach_ms(uint32_t milliseconds, bool repeat, callback_with_arg_t } esp_timer_create(&_timerConfig, &_timer); if (repeat) { - esp_timer_start_periodic(_timer, milliseconds * 1000); + esp_timer_start_periodic(_timer, milliseconds * 1000ULL); } else { - esp_timer_start_once(_timer, milliseconds * 1000); + esp_timer_start_once(_timer, milliseconds * 1000ULL); } } diff --git a/libraries/Update/examples/AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino b/libraries/Update/examples/AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino index 6da329676a9..8582874f129 100644 --- a/libraries/Update/examples/AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino +++ b/libraries/Update/examples/AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino @@ -26,7 +26,7 @@ WiFiClient client; // Variables to validate // response from S3 -int contentLength = 0; +long contentLength = 0; bool isValidContentType = false; // Your SSID and PSWD that the chip needs @@ -120,7 +120,7 @@ void execOTA() { // extract headers here // Start with content length if (line.startsWith("Content-Length: ")) { - contentLength = atoi((getHeaderValue(line, "Content-Length: ")).c_str()); + contentLength = atol((getHeaderValue(line, "Content-Length: ")).c_str()); Serial.println("Got " + String(contentLength) + " bytes from server"); } diff --git a/libraries/Update/src/Update.h b/libraries/Update/src/Update.h index 2bf4dc46106..9a46a784870 100644 --- a/libraries/Update/src/Update.h +++ b/libraries/Update/src/Update.h @@ -41,7 +41,7 @@ class UpdateClass { Call this to check the space needed for the update Will return false if there is not enough space */ - bool begin(size_t size=UPDATE_SIZE_UNKNOWN, int command = U_FLASH); + bool begin(size_t size=UPDATE_SIZE_UNKNOWN, int command = U_FLASH, int ledPin = -1, uint8_t ledOn = LOW); /* Writes a buffer to the flash and increments the address @@ -62,7 +62,7 @@ class UpdateClass { If all bytes are written this call will write the config to eboot and return true - If there is already an update running but is not finished and !evenIfRemainanig + If there is already an update running but is not finished and !evenIfRemaining or there is an error this will clear everything and return false the last error is available through getError() @@ -80,6 +80,8 @@ class UpdateClass { */ void printError(Stream &out); + const char * errorString(); + /* sets the expected MD5 for the firmware (hexString) */ @@ -174,6 +176,9 @@ class UpdateClass { String _target_md5; MD5Builder _md5; + + int _ledPin; + uint8_t _ledOn; }; extern UpdateClass Update; diff --git a/libraries/Update/src/Updater.cpp b/libraries/Update/src/Updater.cpp index d2ea1e9b41a..cfa28827e96 100644 --- a/libraries/Update/src/Updater.cpp +++ b/libraries/Update/src/Updater.cpp @@ -88,6 +88,10 @@ void UpdateClass::_reset() { _progress = 0; _size = 0; _command = U_FLASH; + + if(_ledPin != -1) { + digitalWrite(_ledPin, !_ledOn); // off + } } bool UpdateClass::canRollBack(){ @@ -106,12 +110,15 @@ bool UpdateClass::rollBack(){ return _partitionIsBootable(partition) && !esp_ota_set_boot_partition(partition); } -bool UpdateClass::begin(size_t size, int command) { +bool UpdateClass::begin(size_t size, int command, int ledPin, uint8_t ledOn) { if(_size > 0){ log_w("already running"); return false; } + _ledPin = ledPin; + _ledOn = !!ledOn; // 0(LOW) or 1(HIGH) + _reset(); _error = 0; @@ -182,6 +189,9 @@ bool UpdateClass::_writeBuffer(){ //this ensures that partially written firmware will not be bootable _buffer[0] = 0xFF; } + if (!_progress && _progress_callback) { + _progress_callback(0, _size); + } if(!ESP.flashEraseSector((_partition->address + _progress)/SPI_FLASH_SEC_SIZE)){ _abort(UPDATE_ERROR_ERASE); return false; @@ -197,6 +207,9 @@ bool UpdateClass::_writeBuffer(){ _md5.add(_buffer, _bufferLen); _progress += _bufferLen; _bufferLen = 0; + if (_progress_callback) { + _progress_callback(_progress, _size); + } return true; } @@ -312,29 +325,36 @@ size_t UpdateClass::writeStream(Stream &data) { _reset(); return 0; } - if (_progress_callback) { - _progress_callback(0, _size); + + if(_ledPin != -1) { + pinMode(_ledPin, OUTPUT); } + while(remaining()) { - toRead = data.readBytes(_buffer + _bufferLen, (SPI_FLASH_SEC_SIZE - _bufferLen)); + if(_ledPin != -1) { + digitalWrite(_ledPin, _ledOn); // Switch LED on + } + size_t bytesToRead = SPI_FLASH_SEC_SIZE - _bufferLen; + if(bytesToRead > remaining()) { + bytesToRead = remaining(); + } + + toRead = data.readBytes(_buffer + _bufferLen, bytesToRead); if(toRead == 0) { //Timeout delay(100); - toRead = data.readBytes(_buffer + _bufferLen, (SPI_FLASH_SEC_SIZE - _bufferLen)); + toRead = data.readBytes(_buffer + _bufferLen, bytesToRead); if(toRead == 0) { //Timeout _abort(UPDATE_ERROR_STREAM); return written; } } + if(_ledPin != -1) { + digitalWrite(_ledPin, !_ledOn); // Switch LED off + } _bufferLen += toRead; if((_bufferLen == remaining() || _bufferLen == SPI_FLASH_SEC_SIZE) && !_writeBuffer()) return written; written += toRead; - if(_progress_callback) { - _progress_callback(_progress, _size); - } - } - if(_progress_callback) { - _progress_callback(_size, _size); } return written; } @@ -343,4 +363,8 @@ void UpdateClass::printError(Stream &out){ out.println(_err2str(_error)); } +const char * UpdateClass::errorString(){ + return _err2str(_error); +} + UpdateClass Update; diff --git a/libraries/WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino b/libraries/WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino new file mode 100644 index 00000000000..88ad6c8a08d --- /dev/null +++ b/libraries/WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino @@ -0,0 +1,146 @@ +/* + Copyright (c) 2015, Majenko Technologies + 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 Majenko Technologies 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 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. +*/ + +#include +#include +#include +#include + +const char *ssid = "YourSSIDHere"; +const char *password = "YourPSKHere"; + +WebServer server(80); + +const int led = 13; + +void handleRoot() { + digitalWrite(led, 1); + char temp[400]; + int sec = millis() / 1000; + int min = sec / 60; + int hr = min / 60; + + snprintf(temp, 400, + + "\ + \ + \ + ESP32 Demo\ + \ + \ + \ +

Hello from ESP32!

\ +

Uptime: %02d:%02d:%02d

\ + \ + \ +", + + hr, min % 60, sec % 60 + ); + server.send(200, "text/html", temp); + digitalWrite(led, 0); +} + +void handleNotFound() { + digitalWrite(led, 1); + String message = "File Not Found\n\n"; + message += "URI: "; + message += server.uri(); + message += "\nMethod: "; + message += (server.method() == HTTP_GET) ? "GET" : "POST"; + message += "\nArguments: "; + message += server.args(); + message += "\n"; + + for (uint8_t i = 0; i < server.args(); i++) { + message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; + } + + server.send(404, "text/plain", message); + digitalWrite(led, 0); +} + +void setup(void) { + pinMode(led, OUTPUT); + digitalWrite(led, 0); + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + Serial.println(""); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.print("Connected to "); + Serial.println(ssid); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + if (MDNS.begin("esp32")) { + Serial.println("MDNS responder started"); + } + + server.on("/", handleRoot); + server.on("/test.svg", drawGraph); + server.on("/inline", []() { + server.send(200, "text/plain", "this works as well"); + }); + server.onNotFound(handleNotFound); + server.begin(); + Serial.println("HTTP server started"); +} + +void loop(void) { + server.handleClient(); +} + +void drawGraph() { + String out = ""; + char temp[100]; + out += "\n"; + out += "\n"; + out += "\n"; + int y = rand() % 130; + for (int x = 10; x < 390; x += 10) { + int y2 = rand() % 130; + sprintf(temp, "\n", x, 140 - y, x + 10, 140 - y2); + out += temp; + y = y2; + } + out += "\n\n"; + + server.send(200, "image/svg+xml", out); +} diff --git a/libraries/WebServer/examples/FSBrowser/FSBrowser.ino b/libraries/WebServer/examples/FSBrowser/FSBrowser.ino new file mode 100644 index 00000000000..f49ae81c158 --- /dev/null +++ b/libraries/WebServer/examples/FSBrowser/FSBrowser.ino @@ -0,0 +1,303 @@ +/* + FSWebServer - Example WebServer with FS backend for esp8266/esp32 + Copyright (c) 2015 Hristo Gochkov. All rights reserved. + This file is part of the WebServer library for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + upload the contents of the data folder with MkSPIFFS Tool ("ESP32 Sketch Data Upload" in Tools menu in Arduino IDE) + or you can upload the contents of a folder if you CD in that folder and run the following command: + for file in `ls -A1`; do curl -F "file=@$PWD/$file" esp32fs.local/edit; done + + access the sample web page at http://esp32fs.local + edit the page by going to http://esp32fs.local/edit +*/ +#include +#include +#include +#include + +#define FILESYSTEM SPIFFS +// You only need to format the filesystem once +#define FORMAT_FILESYSTEM false +#define DBG_OUTPUT_PORT Serial + +#if FILESYSTEM == FFat +#include +#endif +#if FILESYSTEM == SPIFFS +#include +#endif + +const char* ssid = "wifi-ssid"; +const char* password = "wifi-password"; +const char* host = "esp32fs"; +WebServer server(80); +//holds the current upload +File fsUploadFile; + +//format bytes +String formatBytes(size_t bytes) { + if (bytes < 1024) { + return String(bytes) + "B"; + } else if (bytes < (1024 * 1024)) { + return String(bytes / 1024.0) + "KB"; + } else if (bytes < (1024 * 1024 * 1024)) { + return String(bytes / 1024.0 / 1024.0) + "MB"; + } else { + return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB"; + } +} + +String getContentType(String filename) { + if (server.hasArg("download")) { + return "application/octet-stream"; + } else if (filename.endsWith(".htm")) { + return "text/html"; + } else if (filename.endsWith(".html")) { + return "text/html"; + } else if (filename.endsWith(".css")) { + return "text/css"; + } else if (filename.endsWith(".js")) { + return "application/javascript"; + } else if (filename.endsWith(".png")) { + return "image/png"; + } else if (filename.endsWith(".gif")) { + return "image/gif"; + } else if (filename.endsWith(".jpg")) { + return "image/jpeg"; + } else if (filename.endsWith(".ico")) { + return "image/x-icon"; + } else if (filename.endsWith(".xml")) { + return "text/xml"; + } else if (filename.endsWith(".pdf")) { + return "application/x-pdf"; + } else if (filename.endsWith(".zip")) { + return "application/x-zip"; + } else if (filename.endsWith(".gz")) { + return "application/x-gzip"; + } + return "text/plain"; +} + +bool exists(String path){ + bool yes = false; + File file = FILESYSTEM.open(path, "r"); + if(!file.isDirectory()){ + yes = true; + } + file.close(); + return yes; +} + +bool handleFileRead(String path) { + DBG_OUTPUT_PORT.println("handleFileRead: " + path); + if (path.endsWith("/")) { + path += "index.htm"; + } + String contentType = getContentType(path); + String pathWithGz = path + ".gz"; + if (exists(pathWithGz) || exists(path)) { + if (exists(pathWithGz)) { + path += ".gz"; + } + File file = FILESYSTEM.open(path, "r"); + server.streamFile(file, contentType); + file.close(); + return true; + } + return false; +} + +void handleFileUpload() { + if (server.uri() != "/edit") { + return; + } + HTTPUpload& upload = server.upload(); + if (upload.status == UPLOAD_FILE_START) { + String filename = upload.filename; + if (!filename.startsWith("/")) { + filename = "/" + filename; + } + DBG_OUTPUT_PORT.print("handleFileUpload Name: "); DBG_OUTPUT_PORT.println(filename); + fsUploadFile = FILESYSTEM.open(filename, "w"); + filename = String(); + } else if (upload.status == UPLOAD_FILE_WRITE) { + //DBG_OUTPUT_PORT.print("handleFileUpload Data: "); DBG_OUTPUT_PORT.println(upload.currentSize); + if (fsUploadFile) { + fsUploadFile.write(upload.buf, upload.currentSize); + } + } else if (upload.status == UPLOAD_FILE_END) { + if (fsUploadFile) { + fsUploadFile.close(); + } + DBG_OUTPUT_PORT.print("handleFileUpload Size: "); DBG_OUTPUT_PORT.println(upload.totalSize); + } +} + +void handleFileDelete() { + if (server.args() == 0) { + return server.send(500, "text/plain", "BAD ARGS"); + } + String path = server.arg(0); + DBG_OUTPUT_PORT.println("handleFileDelete: " + path); + if (path == "/") { + return server.send(500, "text/plain", "BAD PATH"); + } + if (!exists(path)) { + return server.send(404, "text/plain", "FileNotFound"); + } + FILESYSTEM.remove(path); + server.send(200, "text/plain", ""); + path = String(); +} + +void handleFileCreate() { + if (server.args() == 0) { + return server.send(500, "text/plain", "BAD ARGS"); + } + String path = server.arg(0); + DBG_OUTPUT_PORT.println("handleFileCreate: " + path); + if (path == "/") { + return server.send(500, "text/plain", "BAD PATH"); + } + if (exists(path)) { + return server.send(500, "text/plain", "FILE EXISTS"); + } + File file = FILESYSTEM.open(path, "w"); + if (file) { + file.close(); + } else { + return server.send(500, "text/plain", "CREATE FAILED"); + } + server.send(200, "text/plain", ""); + path = String(); +} + +void handleFileList() { + if (!server.hasArg("dir")) { + server.send(500, "text/plain", "BAD ARGS"); + return; + } + + String path = server.arg("dir"); + DBG_OUTPUT_PORT.println("handleFileList: " + path); + + + File root = FILESYSTEM.open(path); + path = String(); + + String output = "["; + if(root.isDirectory()){ + File file = root.openNextFile(); + while(file){ + if (output != "[") { + output += ','; + } + output += "{\"type\":\""; + output += (file.isDirectory()) ? "dir" : "file"; + output += "\",\"name\":\""; + output += String(file.name()).substring(1); + output += "\"}"; + file = root.openNextFile(); + } + } + output += "]"; + server.send(200, "text/json", output); +} + +void setup(void) { + DBG_OUTPUT_PORT.begin(115200); + DBG_OUTPUT_PORT.print("\n"); + DBG_OUTPUT_PORT.setDebugOutput(true); + if (FORMAT_FILESYSTEM) FILESYSTEM.format(); + FILESYSTEM.begin(); + { + File root = FILESYSTEM.open("/"); + File file = root.openNextFile(); + while(file){ + String fileName = file.name(); + size_t fileSize = file.size(); + DBG_OUTPUT_PORT.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str()); + file = root.openNextFile(); + } + DBG_OUTPUT_PORT.printf("\n"); + } + + + //WIFI INIT + DBG_OUTPUT_PORT.printf("Connecting to %s\n", ssid); + if (String(WiFi.SSID()) != String(ssid)) { + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + } + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + DBG_OUTPUT_PORT.print("."); + } + DBG_OUTPUT_PORT.println(""); + DBG_OUTPUT_PORT.print("Connected! IP address: "); + DBG_OUTPUT_PORT.println(WiFi.localIP()); + + MDNS.begin(host); + DBG_OUTPUT_PORT.print("Open http://"); + DBG_OUTPUT_PORT.print(host); + DBG_OUTPUT_PORT.println(".local/edit to see the file browser"); + + + //SERVER INIT + //list directory + server.on("/list", HTTP_GET, handleFileList); + //load editor + server.on("/edit", HTTP_GET, []() { + if (!handleFileRead("/edit.htm")) { + server.send(404, "text/plain", "FileNotFound"); + } + }); + //create file + server.on("/edit", HTTP_PUT, handleFileCreate); + //delete file + server.on("/edit", HTTP_DELETE, handleFileDelete); + //first callback is called after the request has ended with all parsed arguments + //second callback handles file uploads at that location + server.on("/edit", HTTP_POST, []() { + server.send(200, "text/plain", ""); + }, handleFileUpload); + + //called when the url is not defined here + //use it to load content from FILESYSTEM + server.onNotFound([]() { + if (!handleFileRead(server.uri())) { + server.send(404, "text/plain", "FileNotFound"); + } + }); + + //get heap status, analog input value and all GPIO statuses in one json call + server.on("/all", HTTP_GET, []() { + String json = "{"; + json += "\"heap\":" + String(ESP.getFreeHeap()); + json += ", \"analog\":" + String(analogRead(A0)); + json += ", \"gpio\":" + String((uint32_t)(0)); + json += "}"; + server.send(200, "text/json", json); + json = String(); + }); + server.begin(); + DBG_OUTPUT_PORT.println("HTTP server started"); + +} + +void loop(void) { + server.handleClient(); +} diff --git a/libraries/WebServer/examples/FSBrowser/data/edit.htm.gz b/libraries/WebServer/examples/FSBrowser/data/edit.htm.gz new file mode 100644 index 00000000000..69ce414f47f Binary files /dev/null and b/libraries/WebServer/examples/FSBrowser/data/edit.htm.gz differ diff --git a/libraries/WebServer/examples/FSBrowser/data/favicon.ico b/libraries/WebServer/examples/FSBrowser/data/favicon.ico new file mode 100644 index 00000000000..71b25fe6ee6 Binary files /dev/null and b/libraries/WebServer/examples/FSBrowser/data/favicon.ico differ diff --git a/libraries/WebServer/examples/FSBrowser/data/graphs.js.gz b/libraries/WebServer/examples/FSBrowser/data/graphs.js.gz new file mode 100644 index 00000000000..72435445a7e Binary files /dev/null and b/libraries/WebServer/examples/FSBrowser/data/graphs.js.gz differ diff --git a/libraries/WebServer/examples/FSBrowser/data/index.htm b/libraries/WebServer/examples/FSBrowser/data/index.htm new file mode 100644 index 00000000000..9cb560cb0b0 --- /dev/null +++ b/libraries/WebServer/examples/FSBrowser/data/index.htm @@ -0,0 +1,97 @@ + + + + + + ESP Monitor + + + + +
+ + + + +
+
+
+
+ + \ No newline at end of file diff --git a/libraries/WebServer/examples/HelloServer/HelloServer.ino b/libraries/WebServer/examples/HelloServer/HelloServer.ino new file mode 100644 index 00000000000..f67b049c3ce --- /dev/null +++ b/libraries/WebServer/examples/HelloServer/HelloServer.ino @@ -0,0 +1,73 @@ +#include +#include +#include +#include + +const char* ssid = "........"; +const char* password = "........"; + +WebServer server(80); + +const int led = 13; + +void handleRoot() { + digitalWrite(led, 1); + server.send(200, "text/plain", "hello from esp8266!"); + digitalWrite(led, 0); +} + +void handleNotFound() { + digitalWrite(led, 1); + String message = "File Not Found\n\n"; + message += "URI: "; + message += server.uri(); + message += "\nMethod: "; + message += (server.method() == HTTP_GET) ? "GET" : "POST"; + message += "\nArguments: "; + message += server.args(); + message += "\n"; + for (uint8_t i = 0; i < server.args(); i++) { + message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; + } + server.send(404, "text/plain", message); + digitalWrite(led, 0); +} + +void setup(void) { + pinMode(led, OUTPUT); + digitalWrite(led, 0); + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + Serial.println(""); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.print("Connected to "); + Serial.println(ssid); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + if (MDNS.begin("esp32")) { + Serial.println("MDNS responder started"); + } + + server.on("/", handleRoot); + + server.on("/inline", []() { + server.send(200, "text/plain", "this works as well"); + }); + + server.onNotFound(handleNotFound); + + server.begin(); + Serial.println("HTTP server started"); +} + +void loop(void) { + server.handleClient(); +} diff --git a/libraries/WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino b/libraries/WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino new file mode 100644 index 00000000000..567fd487863 --- /dev/null +++ b/libraries/WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino @@ -0,0 +1,59 @@ +/* + HTTP Advanced Authentication example + Created Mar 16, 2017 by Ahmed El-Sharnoby. + This example code is in the public domain. +*/ + +#include +#include +#include +#include + +const char* ssid = "........"; +const char* password = "........"; + +WebServer server(80); + +const char* www_username = "admin"; +const char* www_password = "esp32"; +// allows you to set the realm of authentication Default:"Login Required" +const char* www_realm = "Custom Auth Realm"; +// the Content of the HTML response in case of Unautherized Access Default:empty +String authFailResponse = "Authentication Failed"; + +void setup() { + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Connect Failed! Rebooting..."); + delay(1000); + ESP.restart(); + } + ArduinoOTA.begin(); + + server.on("/", []() { + if (!server.authenticate(www_username, www_password)) + //Basic Auth Method with Custom realm and Failure Response + //return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse); + //Digest Auth Method with realm="Login Required" and empty Failure Response + //return server.requestAuthentication(DIGEST_AUTH); + //Digest Auth Method with Custom realm and empty Failure Response + //return server.requestAuthentication(DIGEST_AUTH, www_realm); + //Digest Auth Method with Custom realm and Failure Response + { + return server.requestAuthentication(DIGEST_AUTH, www_realm, authFailResponse); + } + server.send(200, "text/plain", "Login OK"); + }); + server.begin(); + + Serial.print("Open http://"); + Serial.print(WiFi.localIP()); + Serial.println("/ in your browser to see it working"); +} + +void loop() { + ArduinoOTA.handle(); + server.handleClient(); +} diff --git a/libraries/WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino b/libraries/WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino new file mode 100644 index 00000000000..7a7dcc9a5e3 --- /dev/null +++ b/libraries/WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino @@ -0,0 +1,41 @@ +#include +#include +#include +#include + +const char* ssid = "........"; +const char* password = "........"; + +WebServer server(80); + +const char* www_username = "admin"; +const char* www_password = "esp32"; + +void setup() { + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Connect Failed! Rebooting..."); + delay(1000); + ESP.restart(); + } + ArduinoOTA.begin(); + + server.on("/", []() { + if (!server.authenticate(www_username, www_password)) { + return server.requestAuthentication(); + } + server.send(200, "text/plain", "Login OK"); + }); + server.begin(); + + Serial.print("Open http://"); + Serial.print(WiFi.localIP()); + Serial.println("/ in your browser to see it working"); +} + +void loop() { + ArduinoOTA.handle(); + server.handleClient(); +} diff --git a/libraries/WebServer/examples/PathArgServer/PathArgServer.ino b/libraries/WebServer/examples/PathArgServer/PathArgServer.ino new file mode 100644 index 00000000000..8f22f1bea92 --- /dev/null +++ b/libraries/WebServer/examples/PathArgServer/PathArgServer.ino @@ -0,0 +1,53 @@ +#include +#include +#include +#include + +const char *ssid = "........"; +const char *password = "........"; + +WebServer server(80); + +void setup(void) { + Serial.begin(9600); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + Serial.println(""); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.print("Connected to "); + Serial.println(ssid); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + if (MDNS.begin("esp32")) { + Serial.println("MDNS responder started"); + } + + server.on("/", []() { + server.send(200, "text/plain", "hello from esp32!"); + }); + + server.on("/users/{}", []() { + String user = server.pathArg(0); + server.send(200, "text/plain", "User: '" + user + "'"); + }); + + server.on("/users/{}/devices/{}", []() { + String user = server.pathArg(0); + String device = server.pathArg(1); + server.send(200, "text/plain", "User: '" + user + "' and Device: '" + device + "'"); + }); + + server.begin(); + Serial.println("HTTP server started"); +} + +void loop(void) { + server.handleClient(); +} diff --git a/libraries/WebServer/examples/SDWebServer/SDWebServer.ino b/libraries/WebServer/examples/SDWebServer/SDWebServer.ino new file mode 100644 index 00000000000..a3271a03740 --- /dev/null +++ b/libraries/WebServer/examples/SDWebServer/SDWebServer.ino @@ -0,0 +1,313 @@ +/* + SDWebServer - Example WebServer with SD Card backend for esp8266 + + Copyright (c) 2015 Hristo Gochkov. All rights reserved. + This file is part of the WebServer library for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Have a FAT Formatted SD Card connected to the SPI port of the ESP8266 + The web root is the SD Card root folder + File extensions with more than 3 charecters are not supported by the SD Library + File Names longer than 8 charecters will be truncated by the SD library, so keep filenames shorter + index.htm is the default index (works on subfolders as well) + + upload the contents of SdRoot to the root of the SDcard and access the editor by going to http://esp8266sd.local/edit + +*/ +#include +#include +#include +#include +#include +#include + +#define DBG_OUTPUT_PORT Serial + +const char* ssid = "**********"; +const char* password = "**********"; +const char* host = "esp32sd"; + +WebServer server(80); + +static bool hasSD = false; +File uploadFile; + + +void returnOK() { + server.send(200, "text/plain", ""); +} + +void returnFail(String msg) { + server.send(500, "text/plain", msg + "\r\n"); +} + +bool loadFromSdCard(String path) { + String dataType = "text/plain"; + if (path.endsWith("/")) { + path += "index.htm"; + } + + if (path.endsWith(".src")) { + path = path.substring(0, path.lastIndexOf(".")); + } else if (path.endsWith(".htm")) { + dataType = "text/html"; + } else if (path.endsWith(".css")) { + dataType = "text/css"; + } else if (path.endsWith(".js")) { + dataType = "application/javascript"; + } else if (path.endsWith(".png")) { + dataType = "image/png"; + } else if (path.endsWith(".gif")) { + dataType = "image/gif"; + } else if (path.endsWith(".jpg")) { + dataType = "image/jpeg"; + } else if (path.endsWith(".ico")) { + dataType = "image/x-icon"; + } else if (path.endsWith(".xml")) { + dataType = "text/xml"; + } else if (path.endsWith(".pdf")) { + dataType = "application/pdf"; + } else if (path.endsWith(".zip")) { + dataType = "application/zip"; + } + + File dataFile = SD.open(path.c_str()); + if (dataFile.isDirectory()) { + path += "/index.htm"; + dataType = "text/html"; + dataFile = SD.open(path.c_str()); + } + + if (!dataFile) { + return false; + } + + if (server.hasArg("download")) { + dataType = "application/octet-stream"; + } + + if (server.streamFile(dataFile, dataType) != dataFile.size()) { + DBG_OUTPUT_PORT.println("Sent less data than expected!"); + } + + dataFile.close(); + return true; +} + +void handleFileUpload() { + if (server.uri() != "/edit") { + return; + } + HTTPUpload& upload = server.upload(); + if (upload.status == UPLOAD_FILE_START) { + if (SD.exists((char *)upload.filename.c_str())) { + SD.remove((char *)upload.filename.c_str()); + } + uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE); + DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename); + } else if (upload.status == UPLOAD_FILE_WRITE) { + if (uploadFile) { + uploadFile.write(upload.buf, upload.currentSize); + } + DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize); + } else if (upload.status == UPLOAD_FILE_END) { + if (uploadFile) { + uploadFile.close(); + } + DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize); + } +} + +void deleteRecursive(String path) { + File file = SD.open((char *)path.c_str()); + if (!file.isDirectory()) { + file.close(); + SD.remove((char *)path.c_str()); + return; + } + + file.rewindDirectory(); + while (true) { + File entry = file.openNextFile(); + if (!entry) { + break; + } + String entryPath = path + "/" + entry.name(); + if (entry.isDirectory()) { + entry.close(); + deleteRecursive(entryPath); + } else { + entry.close(); + SD.remove((char *)entryPath.c_str()); + } + yield(); + } + + SD.rmdir((char *)path.c_str()); + file.close(); +} + +void handleDelete() { + if (server.args() == 0) { + return returnFail("BAD ARGS"); + } + String path = server.arg(0); + if (path == "/" || !SD.exists((char *)path.c_str())) { + returnFail("BAD PATH"); + return; + } + deleteRecursive(path); + returnOK(); +} + +void handleCreate() { + if (server.args() == 0) { + return returnFail("BAD ARGS"); + } + String path = server.arg(0); + if (path == "/" || SD.exists((char *)path.c_str())) { + returnFail("BAD PATH"); + return; + } + + if (path.indexOf('.') > 0) { + File file = SD.open((char *)path.c_str(), FILE_WRITE); + if (file) { + file.write(0); + file.close(); + } + } else { + SD.mkdir((char *)path.c_str()); + } + returnOK(); +} + +void printDirectory() { + if (!server.hasArg("dir")) { + return returnFail("BAD ARGS"); + } + String path = server.arg("dir"); + if (path != "/" && !SD.exists((char *)path.c_str())) { + return returnFail("BAD PATH"); + } + File dir = SD.open((char *)path.c_str()); + path = String(); + if (!dir.isDirectory()) { + dir.close(); + return returnFail("NOT DIR"); + } + dir.rewindDirectory(); + server.setContentLength(CONTENT_LENGTH_UNKNOWN); + server.send(200, "text/json", ""); + WiFiClient client = server.client(); + + server.sendContent("["); + for (int cnt = 0; true; ++cnt) { + File entry = dir.openNextFile(); + if (!entry) { + break; + } + + String output; + if (cnt > 0) { + output = ','; + } + + output += "{\"type\":\""; + output += (entry.isDirectory()) ? "dir" : "file"; + output += "\",\"name\":\""; + output += entry.name(); + output += "\""; + output += "}"; + server.sendContent(output); + entry.close(); + } + server.sendContent("]"); + dir.close(); +} + +void handleNotFound() { + if (hasSD && loadFromSdCard(server.uri())) { + return; + } + String message = "SDCARD Not Detected\n\n"; + message += "URI: "; + message += server.uri(); + message += "\nMethod: "; + message += (server.method() == HTTP_GET) ? "GET" : "POST"; + message += "\nArguments: "; + message += server.args(); + message += "\n"; + for (uint8_t i = 0; i < server.args(); i++) { + message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n"; + } + server.send(404, "text/plain", message); + DBG_OUTPUT_PORT.print(message); +} + +void setup(void) { + DBG_OUTPUT_PORT.begin(115200); + DBG_OUTPUT_PORT.setDebugOutput(true); + DBG_OUTPUT_PORT.print("\n"); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + DBG_OUTPUT_PORT.print("Connecting to "); + DBG_OUTPUT_PORT.println(ssid); + + // Wait for connection + uint8_t i = 0; + while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds + delay(500); + } + if (i == 21) { + DBG_OUTPUT_PORT.print("Could not connect to"); + DBG_OUTPUT_PORT.println(ssid); + while (1) { + delay(500); + } + } + DBG_OUTPUT_PORT.print("Connected! IP address: "); + DBG_OUTPUT_PORT.println(WiFi.localIP()); + + if (MDNS.begin(host)) { + MDNS.addService("http", "tcp", 80); + DBG_OUTPUT_PORT.println("MDNS responder started"); + DBG_OUTPUT_PORT.print("You can now connect to http://"); + DBG_OUTPUT_PORT.print(host); + DBG_OUTPUT_PORT.println(".local"); + } + + + server.on("/list", HTTP_GET, printDirectory); + server.on("/edit", HTTP_DELETE, handleDelete); + server.on("/edit", HTTP_PUT, handleCreate); + server.on("/edit", HTTP_POST, []() { + returnOK(); + }, handleFileUpload); + server.onNotFound(handleNotFound); + + server.begin(); + DBG_OUTPUT_PORT.println("HTTP server started"); + + if (SD.begin(SS)) { + DBG_OUTPUT_PORT.println("SD Card initialized."); + hasSD = true; + } +} + +void loop(void) { + server.handleClient(); +} diff --git a/libraries/WebServer/examples/SDWebServer/SdRoot/edit/index.htm b/libraries/WebServer/examples/SDWebServer/SdRoot/edit/index.htm new file mode 100644 index 00000000000..f535601e7d7 --- /dev/null +++ b/libraries/WebServer/examples/SDWebServer/SdRoot/edit/index.htm @@ -0,0 +1,674 @@ + + + + SD Editor + + + + + +
+
+
+ + + + diff --git a/libraries/WebServer/examples/SDWebServer/SdRoot/index.htm b/libraries/WebServer/examples/SDWebServer/SdRoot/index.htm new file mode 100644 index 00000000000..55fe5a66c45 --- /dev/null +++ b/libraries/WebServer/examples/SDWebServer/SdRoot/index.htm @@ -0,0 +1,22 @@ + + + + + ESP Index + + + + +

ESP8266 Pin Functions

+ + + diff --git a/libraries/WebServer/examples/SDWebServer/SdRoot/pins.png b/libraries/WebServer/examples/SDWebServer/SdRoot/pins.png new file mode 100644 index 00000000000..ac7fc0f9cb6 Binary files /dev/null and b/libraries/WebServer/examples/SDWebServer/SdRoot/pins.png differ diff --git a/libraries/WebServer/examples/SimpleAuthentification/SimpleAuthentification.ino b/libraries/WebServer/examples/SimpleAuthentification/SimpleAuthentification.ino new file mode 100644 index 00000000000..1adf20613ad --- /dev/null +++ b/libraries/WebServer/examples/SimpleAuthentification/SimpleAuthentification.ino @@ -0,0 +1,132 @@ +#include +#include +#include + +const char* ssid = "........"; +const char* password = "........"; + +WebServer server(80); + +//Check if header is present and correct +bool is_authentified() { + Serial.println("Enter is_authentified"); + if (server.hasHeader("Cookie")) { + Serial.print("Found cookie: "); + String cookie = server.header("Cookie"); + Serial.println(cookie); + if (cookie.indexOf("ESPSESSIONID=1") != -1) { + Serial.println("Authentification Successful"); + return true; + } + } + Serial.println("Authentification Failed"); + return false; +} + +//login page, also called for disconnect +void handleLogin() { + String msg; + if (server.hasHeader("Cookie")) { + Serial.print("Found cookie: "); + String cookie = server.header("Cookie"); + Serial.println(cookie); + } + if (server.hasArg("DISCONNECT")) { + Serial.println("Disconnection"); + server.sendHeader("Location", "/login"); + server.sendHeader("Cache-Control", "no-cache"); + server.sendHeader("Set-Cookie", "ESPSESSIONID=0"); + server.send(301); + return; + } + if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")) { + if (server.arg("USERNAME") == "admin" && server.arg("PASSWORD") == "admin") { + server.sendHeader("Location", "/"); + server.sendHeader("Cache-Control", "no-cache"); + server.sendHeader("Set-Cookie", "ESPSESSIONID=1"); + server.send(301); + Serial.println("Log in Successful"); + return; + } + msg = "Wrong username/password! try again."; + Serial.println("Log in Failed"); + } + String content = "
To log in, please use : admin/admin
"; + content += "User:
"; + content += "Password:
"; + content += "
" + msg + "
"; + content += "You also can go here"; + server.send(200, "text/html", content); +} + +//root page can be accessed only if authentification is ok +void handleRoot() { + Serial.println("Enter handleRoot"); + String header; + if (!is_authentified()) { + server.sendHeader("Location", "/login"); + server.sendHeader("Cache-Control", "no-cache"); + server.send(301); + return; + } + String content = "

hello, you successfully connected to esp8266!


"; + if (server.hasHeader("User-Agent")) { + content += "the user agent used is : " + server.header("User-Agent") + "

"; + } + content += "You can access this page until you disconnect"; + server.send(200, "text/html", content); +} + +//no need authentification +void handleNotFound() { + String message = "File Not Found\n\n"; + message += "URI: "; + message += server.uri(); + message += "\nMethod: "; + message += (server.method() == HTTP_GET) ? "GET" : "POST"; + message += "\nArguments: "; + message += server.args(); + message += "\n"; + for (uint8_t i = 0; i < server.args(); i++) { + message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; + } + server.send(404, "text/plain", message); +} + +void setup(void) { + Serial.begin(115200); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + Serial.println(""); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.print("Connected to "); + Serial.println(ssid); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + + server.on("/", handleRoot); + server.on("/login", handleLogin); + server.on("/inline", []() { + server.send(200, "text/plain", "this works without need of authentification"); + }); + + server.onNotFound(handleNotFound); + //here the list of headers to be recorded + const char * headerkeys[] = {"User-Agent", "Cookie"} ; + size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*); + //ask server to track these headers + server.collectHeaders(headerkeys, headerkeyssize); + server.begin(); + Serial.println("HTTP server started"); +} + +void loop(void) { + server.handleClient(); +} diff --git a/libraries/WebServer/examples/WebUpdate/WebUpdate.ino b/libraries/WebServer/examples/WebUpdate/WebUpdate.ino new file mode 100644 index 00000000000..843867d5f3b --- /dev/null +++ b/libraries/WebServer/examples/WebUpdate/WebUpdate.ino @@ -0,0 +1,69 @@ +/* + To upload through terminal you can use: curl -F "image=@firmware.bin" esp8266-webupdate.local/update +*/ + +#include +#include +#include +#include +#include + +const char* host = "esp32-webupdate"; +const char* ssid = "........"; +const char* password = "........"; + +WebServer server(80); +const char* serverIndex = "
"; + +void setup(void) { + Serial.begin(115200); + Serial.println(); + Serial.println("Booting Sketch..."); + WiFi.mode(WIFI_AP_STA); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() == WL_CONNECTED) { + MDNS.begin(host); + server.on("/", HTTP_GET, []() { + server.sendHeader("Connection", "close"); + server.send(200, "text/html", serverIndex); + }); + server.on("/update", HTTP_POST, []() { + server.sendHeader("Connection", "close"); + server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); + ESP.restart(); + }, []() { + HTTPUpload& upload = server.upload(); + if (upload.status == UPLOAD_FILE_START) { + Serial.setDebugOutput(true); + Serial.printf("Update: %s\n", upload.filename.c_str()); + if (!Update.begin()) { //start with max available size + Update.printError(Serial); + } + } else if (upload.status == UPLOAD_FILE_WRITE) { + if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + Update.printError(Serial); + } + } else if (upload.status == UPLOAD_FILE_END) { + if (Update.end(true)) { //true to set the size to the current progress + Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); + } else { + Update.printError(Serial); + } + Serial.setDebugOutput(false); + } else { + Serial.printf("Update Failed Unexpectedly (likely broken connection): status=%d\n", upload.status); + } + }); + server.begin(); + MDNS.addService("http", "tcp", 80); + + Serial.printf("Ready! Open http://%s.local in your browser\n", host); + } else { + Serial.println("WiFi Failed"); + } +} + +void loop(void) { + server.handleClient(); + delay(1); +} diff --git a/libraries/WebServer/keywords.txt b/libraries/WebServer/keywords.txt new file mode 100644 index 00000000000..df20ff7b414 --- /dev/null +++ b/libraries/WebServer/keywords.txt @@ -0,0 +1,38 @@ +####################################### +# Syntax Coloring Map For Ultrasound +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +WebServer KEYWORD1 +WebServerSecure KEYWORD1 +HTTPMethod KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +handleClient KEYWORD2 +on KEYWORD2 +addHandler KEYWORD2 +uri KEYWORD2 +method KEYWORD2 +client KEYWORD2 +send KEYWORD2 +arg KEYWORD2 +argName KEYWORD2 +args KEYWORD2 +hasArg KEYWORD2 +onNotFound KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +HTTP_GET LITERAL1 +HTTP_POST LITERAL1 +HTTP_ANY LITERAL1 +CONTENT_LENGTH_UNKNOWN LITERAL1 diff --git a/libraries/WebServer/library.properties b/libraries/WebServer/library.properties new file mode 100644 index 00000000000..a2ac5f5317c --- /dev/null +++ b/libraries/WebServer/library.properties @@ -0,0 +1,9 @@ +name=WebServer +version=1.0 +author=Ivan Grokhotkov +maintainer=Ivan Grokhtkov +sentence=Simple web server library +paragraph=The library supports HTTP GET and POST requests, provides argument parsing, handles one client at a time. +category=Communication +url= +architectures=esp32 diff --git a/libraries/WebServer/src/HTTP_Method.h b/libraries/WebServer/src/HTTP_Method.h new file mode 100644 index 00000000000..4532332bc88 --- /dev/null +++ b/libraries/WebServer/src/HTTP_Method.h @@ -0,0 +1,15 @@ +#ifndef _HTTP_Method_H_ +#define _HTTP_Method_H_ + +typedef enum { + HTTP_GET = 0b00000001, + HTTP_POST = 0b00000010, + HTTP_DELETE = 0b00000100, + HTTP_PUT = 0b00001000, + HTTP_PATCH = 0b00010000, + HTTP_HEAD = 0b00100000, + HTTP_OPTIONS = 0b01000000, + HTTP_ANY = 0b01111111, +} HTTPMethod; + +#endif /* _HTTP_Method_H_ */ diff --git a/libraries/WebServer/src/Parsing.cpp b/libraries/WebServer/src/Parsing.cpp new file mode 100644 index 00000000000..e2e9cc43b7e --- /dev/null +++ b/libraries/WebServer/src/Parsing.cpp @@ -0,0 +1,562 @@ +/* + Parsing.cpp - HTTP request parsing. + + Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling) +*/ + +#include +#include +#include "WiFiServer.h" +#include "WiFiClient.h" +#include "WebServer.h" +#include "detail/mimetable.h" + +#ifndef WEBSERVER_MAX_POST_ARGS +#define WEBSERVER_MAX_POST_ARGS 32 +#endif + +static const char Content_Type[] PROGMEM = "Content-Type"; +static const char filename[] PROGMEM = "filename"; + +static char* readBytesWithTimeout(WiFiClient& client, size_t maxLength, size_t& dataLength, int timeout_ms) +{ + char *buf = nullptr; + dataLength = 0; + while (dataLength < maxLength) { + int tries = timeout_ms; + size_t newLength; + while (!(newLength = client.available()) && tries--) delay(1); + if (!newLength) { + break; + } + if (!buf) { + buf = (char *) malloc(newLength + 1); + if (!buf) { + return nullptr; + } + } + else { + char* newBuf = (char *) realloc(buf, dataLength + newLength + 1); + if (!newBuf) { + free(buf); + return nullptr; + } + buf = newBuf; + } + client.readBytes(buf + dataLength, newLength); + dataLength += newLength; + buf[dataLength] = '\0'; + } + return buf; +} + +bool WebServer::_parseRequest(WiFiClient& client) { + // Read the first line of HTTP request + String req = client.readStringUntil('\r'); + client.readStringUntil('\n'); + //reset header value + for (int i = 0; i < _headerKeysCount; ++i) { + _currentHeaders[i].value =String(); + } + + // First line of HTTP request looks like "GET /path HTTP/1.1" + // Retrieve the "/path" part by finding the spaces + int addr_start = req.indexOf(' '); + int addr_end = req.indexOf(' ', addr_start + 1); + if (addr_start == -1 || addr_end == -1) { + log_e("Invalid request: %s", req.c_str()); + return false; + } + + String methodStr = req.substring(0, addr_start); + String url = req.substring(addr_start + 1, addr_end); + String versionEnd = req.substring(addr_end + 8); + _currentVersion = atoi(versionEnd.c_str()); + String searchStr = ""; + int hasSearch = url.indexOf('?'); + if (hasSearch != -1){ + searchStr = url.substring(hasSearch + 1); + url = url.substring(0, hasSearch); + } + _currentUri = url; + _chunked = false; + + HTTPMethod method = HTTP_GET; + if (methodStr == F("POST")) { + method = HTTP_POST; + } else if (methodStr == F("DELETE")) { + method = HTTP_DELETE; + } else if (methodStr == F("OPTIONS")) { + method = HTTP_OPTIONS; + } else if (methodStr == F("PUT")) { + method = HTTP_PUT; + } else if (methodStr == F("PATCH")) { + method = HTTP_PATCH; + } + _currentMethod = method; + + log_v("method: %s url: %s search: %s", methodStr.c_str(), url.c_str(), searchStr.c_str()); + + //attach handler + RequestHandler* handler; + for (handler = _firstHandler; handler; handler = handler->next()) { + if (handler->canHandle(_currentMethod, _currentUri)) + break; + } + _currentHandler = handler; + + String formData; + // below is needed only when POST type request + if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){ + String boundaryStr; + String headerName; + String headerValue; + bool isForm = false; + bool isEncoded = false; + uint32_t contentLength = 0; + //parse headers + while(1){ + req = client.readStringUntil('\r'); + client.readStringUntil('\n'); + if (req == "") break;//no moar headers + int headerDiv = req.indexOf(':'); + if (headerDiv == -1){ + break; + } + headerName = req.substring(0, headerDiv); + headerValue = req.substring(headerDiv + 1); + headerValue.trim(); + _collectHeader(headerName.c_str(),headerValue.c_str()); + + log_v("headerName: %s", headerName.c_str()); + log_v("headerValue: %s", headerValue.c_str()); + + if (headerName.equalsIgnoreCase(FPSTR(Content_Type))){ + using namespace mime; + if (headerValue.startsWith(FPSTR(mimeTable[txt].mimeType))){ + isForm = false; + } else if (headerValue.startsWith(F("application/x-www-form-urlencoded"))){ + isForm = false; + isEncoded = true; + } else if (headerValue.startsWith(F("multipart/"))){ + boundaryStr = headerValue.substring(headerValue.indexOf('=') + 1); + boundaryStr.replace("\"",""); + isForm = true; + } + } else if (headerName.equalsIgnoreCase(F("Content-Length"))){ + contentLength = headerValue.toInt(); + } else if (headerName.equalsIgnoreCase(F("Host"))){ + _hostHeader = headerValue; + } + } + + if (!isForm){ + size_t plainLength; + char* plainBuf = readBytesWithTimeout(client, contentLength, plainLength, HTTP_MAX_POST_WAIT); + if (plainLength < contentLength) { + free(plainBuf); + return false; + } + if (contentLength > 0) { + if(isEncoded){ + //url encoded form + if (searchStr != "") searchStr += '&'; + searchStr += plainBuf; + } + _parseArguments(searchStr); + if(!isEncoded){ + //plain post json or other data + RequestArgument& arg = _currentArgs[_currentArgCount++]; + arg.key = F("plain"); + arg.value = String(plainBuf); + } + + log_v("Plain: %s", plainBuf); + free(plainBuf); + } else { + // No content - but we can still have arguments in the URL. + _parseArguments(searchStr); + } + } + + if (isForm){ + _parseArguments(searchStr); + if (!_parseForm(client, boundaryStr, contentLength)) { + return false; + } + } + } else { + String headerName; + String headerValue; + //parse headers + while(1){ + req = client.readStringUntil('\r'); + client.readStringUntil('\n'); + if (req == "") break;//no moar headers + int headerDiv = req.indexOf(':'); + if (headerDiv == -1){ + break; + } + headerName = req.substring(0, headerDiv); + headerValue = req.substring(headerDiv + 2); + _collectHeader(headerName.c_str(),headerValue.c_str()); + + log_v("headerName: %s", headerName.c_str()); + log_v("headerValue: %s", headerValue.c_str()); + + if (headerName.equalsIgnoreCase("Host")){ + _hostHeader = headerValue; + } + } + _parseArguments(searchStr); + } + client.flush(); + + log_v("Request: %s", url.c_str()); + log_v(" Arguments: %s", searchStr.c_str()); + + return true; +} + +bool WebServer::_collectHeader(const char* headerName, const char* headerValue) { + for (int i = 0; i < _headerKeysCount; i++) { + if (_currentHeaders[i].key.equalsIgnoreCase(headerName)) { + _currentHeaders[i].value=headerValue; + return true; + } + } + return false; +} + +void WebServer::_parseArguments(String data) { + log_v("args: %s", data.c_str()); + if (_currentArgs) + delete[] _currentArgs; + _currentArgs = 0; + if (data.length() == 0) { + _currentArgCount = 0; + _currentArgs = new RequestArgument[1]; + return; + } + _currentArgCount = 1; + + for (int i = 0; i < (int)data.length(); ) { + i = data.indexOf('&', i); + if (i == -1) + break; + ++i; + ++_currentArgCount; + } + log_v("args count: %d", _currentArgCount); + + _currentArgs = new RequestArgument[_currentArgCount+1]; + int pos = 0; + int iarg; + for (iarg = 0; iarg < _currentArgCount;) { + int equal_sign_index = data.indexOf('=', pos); + int next_arg_index = data.indexOf('&', pos); + log_v("pos %d =@%d &@%d", pos, equal_sign_index, next_arg_index); + if ((equal_sign_index == -1) || ((equal_sign_index > next_arg_index) && (next_arg_index != -1))) { + log_e("arg missing value: %d", iarg); + if (next_arg_index == -1) + break; + pos = next_arg_index + 1; + continue; + } + RequestArgument& arg = _currentArgs[iarg]; + arg.key = urlDecode(data.substring(pos, equal_sign_index)); + arg.value = urlDecode(data.substring(equal_sign_index + 1, next_arg_index)); + log_v("arg %d key: %s value: %s", iarg, arg.key.c_str(), arg.value.c_str()); + ++iarg; + if (next_arg_index == -1) + break; + pos = next_arg_index + 1; + } + _currentArgCount = iarg; + log_v("args count: %d", _currentArgCount); + +} + +void WebServer::_uploadWriteByte(uint8_t b){ + if (_currentUpload->currentSize == HTTP_UPLOAD_BUFLEN){ + if(_currentHandler && _currentHandler->canUpload(_currentUri)) + _currentHandler->upload(*this, _currentUri, *_currentUpload); + _currentUpload->totalSize += _currentUpload->currentSize; + _currentUpload->currentSize = 0; + } + _currentUpload->buf[_currentUpload->currentSize++] = b; +} + +int WebServer::_uploadReadByte(WiFiClient& client){ + if (!client.connected()) return -1; + int res = client.read(); + if(res < 0) { + // keep trying until you either read a valid byte or timeout + unsigned long startMillis = millis(); + long timeoutIntervalMillis = client.getTimeout(); + boolean timedOut = false; + for(;;) { + // loosely modeled after blinkWithoutDelay pattern + while(!timedOut && !client.available() && client.connected()){ + delay(2); + timedOut = millis() - startMillis >= timeoutIntervalMillis; + } + + res = client.read(); + if(res >= 0) { + return res; // exit on a valid read + } + // NOTE: it is possible to get here and have all of the following + // assertions hold true + // + // -- client.available() > 0 + // -- client.connected == true + // -- res == -1 + // + // a simple retry strategy overcomes this which is to say the + // assertion is not permanent, but the reason that this works + // is elusive, and possibly indicative of a more subtle underlying + // issue + + timedOut = millis() - startMillis >= timeoutIntervalMillis; + if(timedOut) { + return res; // exit on a timeout + } + } + } + + return res; +} + +bool WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){ + (void) len; + log_v("Parse Form: Boundary: %s Length: %d", boundary.c_str(), len); + String line; + int retry = 0; + do { + line = client.readStringUntil('\r'); + ++retry; + } while (line.length() == 0 && retry < 3); + + client.readStringUntil('\n'); + //start reading the form + if (line == ("--"+boundary)){ + if(_postArgs) delete[] _postArgs; + _postArgs = new RequestArgument[WEBSERVER_MAX_POST_ARGS]; + _postArgsLen = 0; + while(1){ + String argName; + String argValue; + String argType; + String argFilename; + bool argIsFile = false; + + line = client.readStringUntil('\r'); + client.readStringUntil('\n'); + if (line.length() > 19 && line.substring(0, 19).equalsIgnoreCase(F("Content-Disposition"))){ + int nameStart = line.indexOf('='); + if (nameStart != -1){ + argName = line.substring(nameStart+2); + nameStart = argName.indexOf('='); + if (nameStart == -1){ + argName = argName.substring(0, argName.length() - 1); + } else { + argFilename = argName.substring(nameStart+2, argName.length() - 1); + argName = argName.substring(0, argName.indexOf('"')); + argIsFile = true; + log_v("PostArg FileName: %s",argFilename.c_str()); + //use GET to set the filename if uploading using blob + if (argFilename == F("blob") && hasArg(FPSTR(filename))) + argFilename = arg(FPSTR(filename)); + } + log_v("PostArg Name: %s", argName.c_str()); + using namespace mime; + argType = FPSTR(mimeTable[txt].mimeType); + line = client.readStringUntil('\r'); + client.readStringUntil('\n'); + if (line.length() > 12 && line.substring(0, 12).equalsIgnoreCase(FPSTR(Content_Type))){ + argType = line.substring(line.indexOf(':')+2); + //skip next line + client.readStringUntil('\r'); + client.readStringUntil('\n'); + } + log_v("PostArg Type: %s", argType.c_str()); + if (!argIsFile){ + while(1){ + line = client.readStringUntil('\r'); + client.readStringUntil('\n'); + if (line.startsWith("--"+boundary)) break; + if (argValue.length() > 0) argValue += "\n"; + argValue += line; + } + log_v("PostArg Value: %s", argValue.c_str()); + + RequestArgument& arg = _postArgs[_postArgsLen++]; + arg.key = argName; + arg.value = argValue; + + if (line == ("--"+boundary+"--")){ + log_v("Done Parsing POST"); + break; + } + } else { + _currentUpload.reset(new HTTPUpload()); + _currentUpload->status = UPLOAD_FILE_START; + _currentUpload->name = argName; + _currentUpload->filename = argFilename; + _currentUpload->type = argType; + _currentUpload->totalSize = 0; + _currentUpload->currentSize = 0; + log_v("Start File: %s Type: %s", _currentUpload->filename.c_str(), _currentUpload->type.c_str()); + if(_currentHandler && _currentHandler->canUpload(_currentUri)) + _currentHandler->upload(*this, _currentUri, *_currentUpload); + _currentUpload->status = UPLOAD_FILE_WRITE; + int argByte = _uploadReadByte(client); +readfile: + + while(argByte != 0x0D){ + if(argByte < 0) return _parseFormUploadAborted(); + _uploadWriteByte(argByte); + argByte = _uploadReadByte(client); + } + + argByte = _uploadReadByte(client); + if(argByte < 0) return _parseFormUploadAborted(); + if (argByte == 0x0A){ + argByte = _uploadReadByte(client); + if(argByte < 0) return _parseFormUploadAborted(); + if ((char)argByte != '-'){ + //continue reading the file + _uploadWriteByte(0x0D); + _uploadWriteByte(0x0A); + goto readfile; + } else { + argByte = _uploadReadByte(client); + if(argByte < 0) return _parseFormUploadAborted(); + if ((char)argByte != '-'){ + //continue reading the file + _uploadWriteByte(0x0D); + _uploadWriteByte(0x0A); + _uploadWriteByte((uint8_t)('-')); + goto readfile; + } + } + + uint8_t endBuf[boundary.length()]; + client.readBytes(endBuf, boundary.length()); + + if (strstr((const char*)endBuf, boundary.c_str()) != NULL){ + if(_currentHandler && _currentHandler->canUpload(_currentUri)) + _currentHandler->upload(*this, _currentUri, *_currentUpload); + _currentUpload->totalSize += _currentUpload->currentSize; + _currentUpload->status = UPLOAD_FILE_END; + if(_currentHandler && _currentHandler->canUpload(_currentUri)) + _currentHandler->upload(*this, _currentUri, *_currentUpload); + log_v("End File: %s Type: %s Size: %d", _currentUpload->filename.c_str(), _currentUpload->type.c_str(), _currentUpload->totalSize); + line = client.readStringUntil(0x0D); + client.readStringUntil(0x0A); + if (line == "--"){ + log_v("Done Parsing POST"); + break; + } + continue; + } else { + _uploadWriteByte(0x0D); + _uploadWriteByte(0x0A); + _uploadWriteByte((uint8_t)('-')); + _uploadWriteByte((uint8_t)('-')); + uint32_t i = 0; + while(i < boundary.length()){ + _uploadWriteByte(endBuf[i++]); + } + argByte = _uploadReadByte(client); + goto readfile; + } + } else { + _uploadWriteByte(0x0D); + goto readfile; + } + break; + } + } + } + } + + int iarg; + int totalArgs = ((WEBSERVER_MAX_POST_ARGS - _postArgsLen) < _currentArgCount)?(WEBSERVER_MAX_POST_ARGS - _postArgsLen):_currentArgCount; + for (iarg = 0; iarg < totalArgs; iarg++){ + RequestArgument& arg = _postArgs[_postArgsLen++]; + arg.key = _currentArgs[iarg].key; + arg.value = _currentArgs[iarg].value; + } + if (_currentArgs) delete[] _currentArgs; + _currentArgs = new RequestArgument[_postArgsLen]; + for (iarg = 0; iarg < _postArgsLen; iarg++){ + RequestArgument& arg = _currentArgs[iarg]; + arg.key = _postArgs[iarg].key; + arg.value = _postArgs[iarg].value; + } + _currentArgCount = iarg; + if (_postArgs) { + delete[] _postArgs; + _postArgs=nullptr; + _postArgsLen = 0; + } + return true; + } + log_e("Error: line: %s", line.c_str()); + return false; +} + +String WebServer::urlDecode(const String& text) +{ + String decoded = ""; + char temp[] = "0x00"; + unsigned int len = text.length(); + unsigned int i = 0; + while (i < len) + { + char decodedChar; + char encodedChar = text.charAt(i++); + if ((encodedChar == '%') && (i + 1 < len)) + { + temp[2] = text.charAt(i++); + temp[3] = text.charAt(i++); + + decodedChar = strtol(temp, NULL, 16); + } + else { + if (encodedChar == '+') + { + decodedChar = ' '; + } + else { + decodedChar = encodedChar; // normal ascii char + } + } + decoded += decodedChar; + } + return decoded; +} + +bool WebServer::_parseFormUploadAborted(){ + _currentUpload->status = UPLOAD_FILE_ABORTED; + if(_currentHandler && _currentHandler->canUpload(_currentUri)) + _currentHandler->upload(*this, _currentUri, *_currentUpload); + return false; +} diff --git a/libraries/WebServer/src/WebServer.cpp b/libraries/WebServer/src/WebServer.cpp new file mode 100644 index 00000000000..a510f109235 --- /dev/null +++ b/libraries/WebServer/src/WebServer.cpp @@ -0,0 +1,691 @@ +/* + WebServer.cpp - Dead simple web-server. + Supports only one simultaneous client, knows how to handle GET and POST. + + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling) +*/ + + +#include +#include +#include +#include "WiFiServer.h" +#include "WiFiClient.h" +#include "WebServer.h" +#include "FS.h" +#include "detail/RequestHandlersImpl.h" +#include "mbedtls/md5.h" + + +static const char AUTHORIZATION_HEADER[] = "Authorization"; +static const char qop_auth[] = "qop=\"auth\""; +static const char WWW_Authenticate[] = "WWW-Authenticate"; +static const char Content_Length[] = "Content-Length"; + + +WebServer::WebServer(IPAddress addr, int port) +: _corsEnabled(false) +, _server(addr, port) +, _currentMethod(HTTP_ANY) +, _currentVersion(0) +, _currentStatus(HC_NONE) +, _statusChange(0) +, _currentHandler(nullptr) +, _firstHandler(nullptr) +, _lastHandler(nullptr) +, _currentArgCount(0) +, _currentArgs(nullptr) +, _postArgsLen(0) +, _postArgs(nullptr) +, _headerKeysCount(0) +, _currentHeaders(nullptr) +, _contentLength(0) +, _chunked(false) +{ +} + +WebServer::WebServer(int port) +: _corsEnabled(false) +, _server(port) +, _currentMethod(HTTP_ANY) +, _currentVersion(0) +, _currentStatus(HC_NONE) +, _statusChange(0) +, _currentHandler(nullptr) +, _firstHandler(nullptr) +, _lastHandler(nullptr) +, _currentArgCount(0) +, _currentArgs(nullptr) +, _postArgsLen(0) +, _postArgs(nullptr) +, _headerKeysCount(0) +, _currentHeaders(nullptr) +, _contentLength(0) +, _chunked(false) +{ +} + +WebServer::~WebServer() { + _server.close(); + if (_currentHeaders) + delete[]_currentHeaders; + RequestHandler* handler = _firstHandler; + while (handler) { + RequestHandler* next = handler->next(); + delete handler; + handler = next; + } +} + +void WebServer::begin() { + close(); + _server.begin(); + _server.setNoDelay(true); +} + +void WebServer::begin(uint16_t port) { + close(); + _server.begin(port); + _server.setNoDelay(true); +} + +String WebServer::_extractParam(String& authReq,const String& param,const char delimit){ + int _begin = authReq.indexOf(param); + if (_begin == -1) + return ""; + return authReq.substring(_begin+param.length(),authReq.indexOf(delimit,_begin+param.length())); +} + +static String md5str(String &in){ + char out[33] = {0}; + mbedtls_md5_context _ctx; + uint8_t i; + uint8_t * _buf = (uint8_t*)malloc(16); + if(_buf == NULL) + return String(out); + memset(_buf, 0x00, 16); + mbedtls_md5_init(&_ctx); + mbedtls_md5_starts(&_ctx); + mbedtls_md5_update(&_ctx, (const uint8_t *)in.c_str(), in.length()); + mbedtls_md5_finish(&_ctx, _buf); + for(i = 0; i < 16; i++) { + sprintf(out + (i * 2), "%02x", _buf[i]); + } + out[32] = 0; + free(_buf); + return String(out); +} + +bool WebServer::authenticate(const char * username, const char * password){ + if(hasHeader(FPSTR(AUTHORIZATION_HEADER))) { + String authReq = header(FPSTR(AUTHORIZATION_HEADER)); + if(authReq.startsWith(F("Basic"))){ + authReq = authReq.substring(6); + authReq.trim(); + char toencodeLen = strlen(username)+strlen(password)+1; + char *toencode = new char[toencodeLen + 1]; + if(toencode == NULL){ + authReq = ""; + return false; + } + char *encoded = new char[base64_encode_expected_len(toencodeLen)+1]; + if(encoded == NULL){ + authReq = ""; + delete[] toencode; + return false; + } + sprintf(toencode, "%s:%s", username, password); + if(base64_encode_chars(toencode, toencodeLen, encoded) > 0 && authReq.equalsConstantTime(encoded)) { + authReq = ""; + delete[] toencode; + delete[] encoded; + return true; + } + delete[] toencode; + delete[] encoded; + } else if(authReq.startsWith(F("Digest"))) { + authReq = authReq.substring(7); + log_v("%s", authReq.c_str()); + String _username = _extractParam(authReq,F("username=\""),'\"'); + if(!_username.length() || _username != String(username)) { + authReq = ""; + return false; + } + // extracting required parameters for RFC 2069 simpler Digest + String _realm = _extractParam(authReq, F("realm=\""),'\"'); + String _nonce = _extractParam(authReq, F("nonce=\""),'\"'); + String _uri = _extractParam(authReq, F("uri=\""),'\"'); + String _response = _extractParam(authReq, F("response=\""),'\"'); + String _opaque = _extractParam(authReq, F("opaque=\""),'\"'); + + if((!_realm.length()) || (!_nonce.length()) || (!_uri.length()) || (!_response.length()) || (!_opaque.length())) { + authReq = ""; + return false; + } + if((_opaque != _sopaque) || (_nonce != _snonce) || (_realm != _srealm)) { + authReq = ""; + return false; + } + // parameters for the RFC 2617 newer Digest + String _nc,_cnonce; + if(authReq.indexOf(FPSTR(qop_auth)) != -1) { + _nc = _extractParam(authReq, F("nc="), ','); + _cnonce = _extractParam(authReq, F("cnonce=\""),'\"'); + } + String _H1 = md5str(String(username) + ':' + _realm + ':' + String(password)); + log_v("Hash of user:realm:pass=%s", _H1.c_str()); + String _H2 = ""; + if(_currentMethod == HTTP_GET){ + _H2 = md5str(String(F("GET:")) + _uri); + }else if(_currentMethod == HTTP_POST){ + _H2 = md5str(String(F("POST:")) + _uri); + }else if(_currentMethod == HTTP_PUT){ + _H2 = md5str(String(F("PUT:")) + _uri); + }else if(_currentMethod == HTTP_DELETE){ + _H2 = md5str(String(F("DELETE:")) + _uri); + }else{ + _H2 = md5str(String(F("GET:")) + _uri); + } + log_v("Hash of GET:uri=%s", _H2.c_str()); + String _responsecheck = ""; + if(authReq.indexOf(FPSTR(qop_auth)) != -1) { + _responsecheck = md5str(_H1 + ':' + _nonce + ':' + _nc + ':' + _cnonce + F(":auth:") + _H2); + } else { + _responsecheck = md5str(_H1 + ':' + _nonce + ':' + _H2); + } + log_v("The Proper response=%s", _responsecheck.c_str()); + if(_response == _responsecheck){ + authReq = ""; + return true; + } + } + authReq = ""; + } + return false; +} + +String WebServer::_getRandomHexString() { + char buffer[33]; // buffer to hold 32 Hex Digit + /0 + int i; + for(i = 0; i < 4; i++) { + sprintf (buffer + (i*8), "%08x", esp_random()); + } + return String(buffer); +} + +void WebServer::requestAuthentication(HTTPAuthMethod mode, const char* realm, const String& authFailMsg) { + if(realm == NULL) { + _srealm = String(F("Login Required")); + } else { + _srealm = String(realm); + } + if(mode == BASIC_AUTH) { + sendHeader(String(FPSTR(WWW_Authenticate)), String(F("Basic realm=\"")) + _srealm + String(F("\""))); + } else { + _snonce=_getRandomHexString(); + _sopaque=_getRandomHexString(); + sendHeader(String(FPSTR(WWW_Authenticate)), String(F("Digest realm=\"")) +_srealm + String(F("\", qop=\"auth\", nonce=\"")) + _snonce + String(F("\", opaque=\"")) + _sopaque + String(F("\""))); + } + using namespace mime; + send(401, String(FPSTR(mimeTable[html].mimeType)), authFailMsg); +} + +void WebServer::on(const String &uri, WebServer::THandlerFunction handler) { + on(uri, HTTP_ANY, handler); +} + +void WebServer::on(const String &uri, HTTPMethod method, WebServer::THandlerFunction fn) { + on(uri, method, fn, _fileUploadHandler); +} + +void WebServer::on(const String &uri, HTTPMethod method, WebServer::THandlerFunction fn, WebServer::THandlerFunction ufn) { + _addRequestHandler(new FunctionRequestHandler(fn, ufn, uri, method)); +} + +void WebServer::addHandler(RequestHandler* handler) { + _addRequestHandler(handler); +} + +void WebServer::_addRequestHandler(RequestHandler* handler) { + if (!_lastHandler) { + _firstHandler = handler; + _lastHandler = handler; + } + else { + _lastHandler->next(handler); + _lastHandler = handler; + } +} + +void WebServer::serveStatic(const char* uri, FS& fs, const char* path, const char* cache_header) { + _addRequestHandler(new StaticRequestHandler(fs, path, uri, cache_header)); +} + +void WebServer::handleClient() { + if (_currentStatus == HC_NONE) { + WiFiClient client = _server.available(); + if (!client) { + return; + } + + log_v("New client"); + + _currentClient = client; + _currentStatus = HC_WAIT_READ; + _statusChange = millis(); + } + + bool keepCurrentClient = false; + bool callYield = false; + + if (_currentClient.connected()) { + switch (_currentStatus) { + case HC_NONE: + // No-op to avoid C++ compiler warning + break; + case HC_WAIT_READ: + // Wait for data from client to become available + if (_currentClient.available()) { + if (_parseRequest(_currentClient)) { + // because HTTP_MAX_SEND_WAIT is expressed in milliseconds, + // it must be divided by 1000 + _currentClient.setTimeout(HTTP_MAX_SEND_WAIT / 1000); + _contentLength = CONTENT_LENGTH_NOT_SET; + _handleRequest(); + + if (_currentClient.connected()) { + _currentStatus = HC_WAIT_CLOSE; + _statusChange = millis(); + keepCurrentClient = true; + } + } + } else { // !_currentClient.available() + if (millis() - _statusChange <= HTTP_MAX_DATA_WAIT) { + keepCurrentClient = true; + } + callYield = true; + } + break; + case HC_WAIT_CLOSE: + // Wait for client to close the connection + if (millis() - _statusChange <= HTTP_MAX_CLOSE_WAIT) { + keepCurrentClient = true; + callYield = true; + } + } + } + + if (!keepCurrentClient) { + _currentClient = WiFiClient(); + _currentStatus = HC_NONE; + _currentUpload.reset(); + } + + if (callYield) { + yield(); + } +} + +void WebServer::close() { + _server.close(); + _currentStatus = HC_NONE; + if(!_headerKeysCount) + collectHeaders(0, 0); +} + +void WebServer::stop() { + close(); +} + +void WebServer::sendHeader(const String& name, const String& value, bool first) { + String headerLine = name; + headerLine += F(": "); + headerLine += value; + headerLine += "\r\n"; + + if (first) { + _responseHeaders = headerLine + _responseHeaders; + } + else { + _responseHeaders += headerLine; + } +} + +void WebServer::setContentLength(const size_t contentLength) { + _contentLength = contentLength; +} + +void WebServer::enableCORS(boolean value) { + _corsEnabled = value; +} + +void WebServer::enableCrossOrigin(boolean value) { + enableCORS(value); +} + +void WebServer::_prepareHeader(String& response, int code, const char* content_type, size_t contentLength) { + response = String(F("HTTP/1.")) + String(_currentVersion) + ' '; + response += String(code); + response += ' '; + response += _responseCodeToString(code); + response += "\r\n"; + + using namespace mime; + if (!content_type) + content_type = mimeTable[html].mimeType; + + sendHeader(String(F("Content-Type")), String(FPSTR(content_type)), true); + if (_contentLength == CONTENT_LENGTH_NOT_SET) { + sendHeader(String(FPSTR(Content_Length)), String(contentLength)); + } else if (_contentLength != CONTENT_LENGTH_UNKNOWN) { + sendHeader(String(FPSTR(Content_Length)), String(_contentLength)); + } else if(_contentLength == CONTENT_LENGTH_UNKNOWN && _currentVersion){ //HTTP/1.1 or above client + //let's do chunked + _chunked = true; + sendHeader(String(F("Accept-Ranges")),String(F("none"))); + sendHeader(String(F("Transfer-Encoding")),String(F("chunked"))); + } + if (_corsEnabled) { + sendHeader(String(FPSTR("Access-Control-Allow-Origin")), String("*")); + } + sendHeader(String(F("Connection")), String(F("close"))); + + response += _responseHeaders; + response += "\r\n"; + _responseHeaders = ""; +} + +void WebServer::send(int code, const char* content_type, const String& content) { + String header; + // Can we asume the following? + //if(code == 200 && content.length() == 0 && _contentLength == CONTENT_LENGTH_NOT_SET) + // _contentLength = CONTENT_LENGTH_UNKNOWN; + _prepareHeader(header, code, content_type, content.length()); + _currentClientWrite(header.c_str(), header.length()); + if(content.length()) + sendContent(content); +} + +void WebServer::send_P(int code, PGM_P content_type, PGM_P content) { + size_t contentLength = 0; + + if (content != NULL) { + contentLength = strlen_P(content); + } + + String header; + char type[64]; + memccpy_P((void*)type, (PGM_VOID_P)content_type, 0, sizeof(type)); + _prepareHeader(header, code, (const char* )type, contentLength); + _currentClientWrite(header.c_str(), header.length()); + sendContent_P(content); +} + +void WebServer::send_P(int code, PGM_P content_type, PGM_P content, size_t contentLength) { + String header; + char type[64]; + memccpy_P((void*)type, (PGM_VOID_P)content_type, 0, sizeof(type)); + _prepareHeader(header, code, (const char* )type, contentLength); + sendContent(header); + sendContent_P(content, contentLength); +} + +void WebServer::send(int code, char* content_type, const String& content) { + send(code, (const char*)content_type, content); +} + +void WebServer::send(int code, const String& content_type, const String& content) { + send(code, (const char*)content_type.c_str(), content); +} + +void WebServer::sendContent(const String& content) { + const char * footer = "\r\n"; + size_t len = content.length(); + if(_chunked) { + char * chunkSize = (char *)malloc(11); + if(chunkSize){ + sprintf(chunkSize, "%x%s", len, footer); + _currentClientWrite(chunkSize, strlen(chunkSize)); + free(chunkSize); + } + } + _currentClientWrite(content.c_str(), len); + if(_chunked){ + _currentClient.write(footer, 2); + if (len == 0) { + _chunked = false; + } + } +} + +void WebServer::sendContent_P(PGM_P content) { + sendContent_P(content, strlen_P(content)); +} + +void WebServer::sendContent_P(PGM_P content, size_t size) { + const char * footer = "\r\n"; + if(_chunked) { + char * chunkSize = (char *)malloc(11); + if(chunkSize){ + sprintf(chunkSize, "%x%s", size, footer); + _currentClientWrite(chunkSize, strlen(chunkSize)); + free(chunkSize); + } + } + _currentClientWrite_P(content, size); + if(_chunked){ + _currentClient.write(footer, 2); + if (size == 0) { + _chunked = false; + } + } +} + + +void WebServer::_streamFileCore(const size_t fileSize, const String & fileName, const String & contentType) +{ + using namespace mime; + setContentLength(fileSize); + if (fileName.endsWith(String(FPSTR(mimeTable[gz].endsWith))) && + contentType != String(FPSTR(mimeTable[gz].mimeType)) && + contentType != String(FPSTR(mimeTable[none].mimeType))) { + sendHeader(F("Content-Encoding"), F("gzip")); + } + send(200, contentType, ""); +} + +String WebServer::pathArg(unsigned int i) { + if (_currentHandler != nullptr) + return _currentHandler->pathArg(i); + return ""; +} + +String WebServer::arg(String name) { + for (int j = 0; j < _postArgsLen; ++j) { + if ( _postArgs[j].key == name ) + return _postArgs[j].value; + } + for (int i = 0; i < _currentArgCount; ++i) { + if ( _currentArgs[i].key == name ) + return _currentArgs[i].value; + } + return ""; +} + +String WebServer::arg(int i) { + if (i < _currentArgCount) + return _currentArgs[i].value; + return ""; +} + +String WebServer::argName(int i) { + if (i < _currentArgCount) + return _currentArgs[i].key; + return ""; +} + +int WebServer::args() { + return _currentArgCount; +} + +bool WebServer::hasArg(String name) { + for (int j = 0; j < _postArgsLen; ++j) { + if (_postArgs[j].key == name) + return true; + } + for (int i = 0; i < _currentArgCount; ++i) { + if (_currentArgs[i].key == name) + return true; + } + return false; +} + + +String WebServer::header(String name) { + for (int i = 0; i < _headerKeysCount; ++i) { + if (_currentHeaders[i].key.equalsIgnoreCase(name)) + return _currentHeaders[i].value; + } + return ""; +} + +void WebServer::collectHeaders(const char* headerKeys[], const size_t headerKeysCount) { + _headerKeysCount = headerKeysCount + 1; + if (_currentHeaders) + delete[]_currentHeaders; + _currentHeaders = new RequestArgument[_headerKeysCount]; + _currentHeaders[0].key = FPSTR(AUTHORIZATION_HEADER); + for (int i = 1; i < _headerKeysCount; i++){ + _currentHeaders[i].key = headerKeys[i-1]; + } +} + +String WebServer::header(int i) { + if (i < _headerKeysCount) + return _currentHeaders[i].value; + return ""; +} + +String WebServer::headerName(int i) { + if (i < _headerKeysCount) + return _currentHeaders[i].key; + return ""; +} + +int WebServer::headers() { + return _headerKeysCount; +} + +bool WebServer::hasHeader(String name) { + for (int i = 0; i < _headerKeysCount; ++i) { + if ((_currentHeaders[i].key.equalsIgnoreCase(name)) && (_currentHeaders[i].value.length() > 0)) + return true; + } + return false; +} + +String WebServer::hostHeader() { + return _hostHeader; +} + +void WebServer::onFileUpload(THandlerFunction fn) { + _fileUploadHandler = fn; +} + +void WebServer::onNotFound(THandlerFunction fn) { + _notFoundHandler = fn; +} + +void WebServer::_handleRequest() { + bool handled = false; + if (!_currentHandler){ + log_e("request handler not found"); + } + else { + handled = _currentHandler->handle(*this, _currentMethod, _currentUri); + if (!handled) { + log_e("request handler failed to handle request"); + } + } + if (!handled && _notFoundHandler) { + _notFoundHandler(); + handled = true; + } + if (!handled) { + using namespace mime; + send(404, String(FPSTR(mimeTable[html].mimeType)), String(F("Not found: ")) + _currentUri); + handled = true; + } + if (handled) { + _finalizeResponse(); + } + _currentUri = ""; +} + + +void WebServer::_finalizeResponse() { + if (_chunked) { + sendContent(""); + } +} + +String WebServer::_responseCodeToString(int code) { + switch (code) { + case 100: return F("Continue"); + case 101: return F("Switching Protocols"); + case 200: return F("OK"); + case 201: return F("Created"); + case 202: return F("Accepted"); + case 203: return F("Non-Authoritative Information"); + case 204: return F("No Content"); + case 205: return F("Reset Content"); + case 206: return F("Partial Content"); + case 300: return F("Multiple Choices"); + case 301: return F("Moved Permanently"); + case 302: return F("Found"); + case 303: return F("See Other"); + case 304: return F("Not Modified"); + case 305: return F("Use Proxy"); + case 307: return F("Temporary Redirect"); + case 400: return F("Bad Request"); + case 401: return F("Unauthorized"); + case 402: return F("Payment Required"); + case 403: return F("Forbidden"); + case 404: return F("Not Found"); + case 405: return F("Method Not Allowed"); + case 406: return F("Not Acceptable"); + case 407: return F("Proxy Authentication Required"); + case 408: return F("Request Time-out"); + case 409: return F("Conflict"); + case 410: return F("Gone"); + case 411: return F("Length Required"); + case 412: return F("Precondition Failed"); + case 413: return F("Request Entity Too Large"); + case 414: return F("Request-URI Too Large"); + case 415: return F("Unsupported Media Type"); + case 416: return F("Requested range not satisfiable"); + case 417: return F("Expectation Failed"); + case 500: return F("Internal Server Error"); + case 501: return F("Not Implemented"); + case 502: return F("Bad Gateway"); + case 503: return F("Service Unavailable"); + case 504: return F("Gateway Time-out"); + case 505: return F("HTTP Version not supported"); + default: return F(""); + } +} diff --git a/libraries/WebServer/src/WebServer.h b/libraries/WebServer/src/WebServer.h new file mode 100644 index 00000000000..97aa032e1f4 --- /dev/null +++ b/libraries/WebServer/src/WebServer.h @@ -0,0 +1,207 @@ +/* + WebServer.h - Dead simple web-server. + Supports only one simultaneous client, knows how to handle GET and POST. + + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling) +*/ + + +#ifndef WEBSERVER_H +#define WEBSERVER_H + +#include +#include +#include +#include "HTTP_Method.h" + +enum HTTPUploadStatus { UPLOAD_FILE_START, UPLOAD_FILE_WRITE, UPLOAD_FILE_END, + UPLOAD_FILE_ABORTED }; +enum HTTPClientStatus { HC_NONE, HC_WAIT_READ, HC_WAIT_CLOSE }; +enum HTTPAuthMethod { BASIC_AUTH, DIGEST_AUTH }; + +#define HTTP_DOWNLOAD_UNIT_SIZE 1436 + +#ifndef HTTP_UPLOAD_BUFLEN +#define HTTP_UPLOAD_BUFLEN 1436 +#endif + +#define HTTP_MAX_DATA_WAIT 5000 //ms to wait for the client to send the request +#define HTTP_MAX_POST_WAIT 5000 //ms to wait for POST data to arrive +#define HTTP_MAX_SEND_WAIT 5000 //ms to wait for data chunk to be ACKed +#define HTTP_MAX_CLOSE_WAIT 2000 //ms to wait for the client to close the connection + +#define CONTENT_LENGTH_UNKNOWN ((size_t) -1) +#define CONTENT_LENGTH_NOT_SET ((size_t) -2) + +class WebServer; + +typedef struct { + HTTPUploadStatus status; + String filename; + String name; + String type; + size_t totalSize; // file size + size_t currentSize; // size of data currently in buf + uint8_t buf[HTTP_UPLOAD_BUFLEN]; +} HTTPUpload; + +#include "detail/RequestHandler.h" + +namespace fs { +class FS; +} + +class WebServer +{ +public: + WebServer(IPAddress addr, int port = 80); + WebServer(int port = 80); + virtual ~WebServer(); + + virtual void begin(); + virtual void begin(uint16_t port); + virtual void handleClient(); + + virtual void close(); + void stop(); + + bool authenticate(const char * username, const char * password); + void requestAuthentication(HTTPAuthMethod mode = BASIC_AUTH, const char* realm = NULL, const String& authFailMsg = String("") ); + + typedef std::function THandlerFunction; + void on(const String &uri, THandlerFunction handler); + void on(const String &uri, HTTPMethod method, THandlerFunction fn); + void on(const String &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn); + void addHandler(RequestHandler* handler); + void serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_header = NULL ); + void onNotFound(THandlerFunction fn); //called when handler is not assigned + void onFileUpload(THandlerFunction fn); //handle file uploads + + String uri() { return _currentUri; } + HTTPMethod method() { return _currentMethod; } + virtual WiFiClient client() { return _currentClient; } + HTTPUpload& upload() { return *_currentUpload; } + + String pathArg(unsigned int i); // get request path argument by number + String arg(String name); // get request argument value by name + String arg(int i); // get request argument value by number + String argName(int i); // get request argument name by number + int args(); // get arguments count + bool hasArg(String name); // check if argument exists + void collectHeaders(const char* headerKeys[], const size_t headerKeysCount); // set the request headers to collect + String header(String name); // get request header value by name + String header(int i); // get request header value by number + String headerName(int i); // get request header name by number + int headers(); // get header count + bool hasHeader(String name); // check if header exists + + String hostHeader(); // get request host header if available or empty String if not + + // send response to the client + // code - HTTP response code, can be 200 or 404 + // content_type - HTTP content type, like "text/plain" or "image/png" + // content - actual content body + void send(int code, const char* content_type = NULL, const String& content = String("")); + void send(int code, char* content_type, const String& content); + void send(int code, const String& content_type, const String& content); + void send_P(int code, PGM_P content_type, PGM_P content); + void send_P(int code, PGM_P content_type, PGM_P content, size_t contentLength); + + void enableCORS(boolean value = true); + void enableCrossOrigin(boolean value = true); + + void setContentLength(const size_t contentLength); + void sendHeader(const String& name, const String& value, bool first = false); + void sendContent(const String& content); + void sendContent_P(PGM_P content); + void sendContent_P(PGM_P content, size_t size); + + static String urlDecode(const String& text); + + template + size_t streamFile(T &file, const String& contentType) { + _streamFileCore(file.size(), file.name(), contentType); + return _currentClient.write(file); + } + +protected: + virtual size_t _currentClientWrite(const char* b, size_t l) { return _currentClient.write( b, l ); } + virtual size_t _currentClientWrite_P(PGM_P b, size_t l) { return _currentClient.write_P( b, l ); } + void _addRequestHandler(RequestHandler* handler); + void _handleRequest(); + void _finalizeResponse(); + bool _parseRequest(WiFiClient& client); + void _parseArguments(String data); + static String _responseCodeToString(int code); + bool _parseForm(WiFiClient& client, String boundary, uint32_t len); + bool _parseFormUploadAborted(); + void _uploadWriteByte(uint8_t b); + int _uploadReadByte(WiFiClient& client); + void _prepareHeader(String& response, int code, const char* content_type, size_t contentLength); + bool _collectHeader(const char* headerName, const char* headerValue); + + void _streamFileCore(const size_t fileSize, const String & fileName, const String & contentType); + + String _getRandomHexString(); + // for extracting Auth parameters + String _extractParam(String& authReq,const String& param,const char delimit = '"'); + + struct RequestArgument { + String key; + String value; + }; + + boolean _corsEnabled; + WiFiServer _server; + + WiFiClient _currentClient; + HTTPMethod _currentMethod; + String _currentUri; + uint8_t _currentVersion; + HTTPClientStatus _currentStatus; + unsigned long _statusChange; + + RequestHandler* _currentHandler; + RequestHandler* _firstHandler; + RequestHandler* _lastHandler; + THandlerFunction _notFoundHandler; + THandlerFunction _fileUploadHandler; + + int _currentArgCount; + RequestArgument* _currentArgs; + int _postArgsLen; + RequestArgument* _postArgs; + + std::unique_ptr _currentUpload; + + int _headerKeysCount; + RequestArgument* _currentHeaders; + size_t _contentLength; + String _responseHeaders; + + String _hostHeader; + bool _chunked; + + String _snonce; // Store noance and opaque for future comparison + String _sopaque; + String _srealm; // Store the Auth realm between Calls + +}; + + +#endif //ESP8266WEBSERVER_H diff --git a/libraries/WebServer/src/detail/RequestHandler.h b/libraries/WebServer/src/detail/RequestHandler.h new file mode 100644 index 00000000000..871ae5c8b3d --- /dev/null +++ b/libraries/WebServer/src/detail/RequestHandler.h @@ -0,0 +1,31 @@ +#ifndef REQUESTHANDLER_H +#define REQUESTHANDLER_H + +#include +#include + +class RequestHandler { +public: + virtual ~RequestHandler() { } + virtual bool canHandle(HTTPMethod method, String uri) { (void) method; (void) uri; return false; } + virtual bool canUpload(String uri) { (void) uri; return false; } + virtual bool handle(WebServer& server, HTTPMethod requestMethod, String requestUri) { (void) server; (void) requestMethod; (void) requestUri; return false; } + virtual void upload(WebServer& server, String requestUri, HTTPUpload& upload) { (void) server; (void) requestUri; (void) upload; } + + RequestHandler* next() { return _next; } + void next(RequestHandler* r) { _next = r; } + +private: + RequestHandler* _next = nullptr; + +protected: + std::vector pathArgs; + +public: + const String& pathArg(unsigned int i) { + assert(i < pathArgs.size()); + return pathArgs[i]; + } +}; + +#endif //REQUESTHANDLER_H diff --git a/libraries/WebServer/src/detail/RequestHandlersImpl.h b/libraries/WebServer/src/detail/RequestHandlersImpl.h new file mode 100644 index 00000000000..babca4e27e3 --- /dev/null +++ b/libraries/WebServer/src/detail/RequestHandlersImpl.h @@ -0,0 +1,187 @@ +#ifndef REQUESTHANDLERSIMPL_H +#define REQUESTHANDLERSIMPL_H + +#include "RequestHandler.h" +#include "mimetable.h" +#include "WString.h" + +using namespace mime; + +class FunctionRequestHandler : public RequestHandler { +public: + FunctionRequestHandler(WebServer::THandlerFunction fn, WebServer::THandlerFunction ufn, const String &uri, HTTPMethod method) + : _fn(fn) + , _ufn(ufn) + , _uri(uri) + , _method(method) + { + int numParams = 0, start = 0; + do { + start = _uri.indexOf("{}", start); + if (start > 0) { + numParams++; + start += 2; + } + } while (start > 0); + pathArgs.resize(numParams); + } + + bool canHandle(HTTPMethod requestMethod, String requestUri) override { + if (_method != HTTP_ANY && _method != requestMethod) + return false; + + if (_uri == requestUri) + return true; + + size_t uriLength = _uri.length(); + unsigned int pathArgIndex = 0; + unsigned int requestUriIndex = 0; + for (unsigned int i = 0; i < uriLength; i++, requestUriIndex++) { + char uriChar = _uri[i]; + char requestUriChar = requestUri[requestUriIndex]; + + if (uriChar == requestUriChar) + continue; + if (uriChar != '{') + return false; + + i += 2; // index of char after '}' + if (i >= uriLength) { + // there is no char after '}' + pathArgs[pathArgIndex] = requestUri.substring(requestUriIndex); + return pathArgs[pathArgIndex].indexOf("/") == -1; // path argument may not contain a '/' + } + else + { + char charEnd = _uri[i]; + int uriIndex = requestUri.indexOf(charEnd, requestUriIndex); + if (uriIndex < 0) + return false; + pathArgs[pathArgIndex] = requestUri.substring(requestUriIndex, uriIndex); + requestUriIndex = (unsigned int) uriIndex; + } + pathArgIndex++; + } + + return requestUriIndex >= requestUri.length(); + } + + bool canUpload(String requestUri) override { + if (!_ufn || !canHandle(HTTP_POST, requestUri)) + return false; + + return true; + } + + bool handle(WebServer& server, HTTPMethod requestMethod, String requestUri) override { + (void) server; + if (!canHandle(requestMethod, requestUri)) + return false; + + _fn(); + return true; + } + + void upload(WebServer& server, String requestUri, HTTPUpload& upload) override { + (void) server; + (void) upload; + if (canUpload(requestUri)) + _ufn(); + } + +protected: + WebServer::THandlerFunction _fn; + WebServer::THandlerFunction _ufn; + String _uri; + HTTPMethod _method; +}; + +class StaticRequestHandler : public RequestHandler { +public: + StaticRequestHandler(FS& fs, const char* path, const char* uri, const char* cache_header) + : _fs(fs) + , _uri(uri) + , _path(path) + , _cache_header(cache_header) + { + _isFile = fs.exists(path); + log_v("StaticRequestHandler: path=%s uri=%s isFile=%d, cache_header=%s\r\n", path, uri, _isFile, cache_header); + _baseUriLength = _uri.length(); + } + + bool canHandle(HTTPMethod requestMethod, String requestUri) override { + if (requestMethod != HTTP_GET) + return false; + + if ((_isFile && requestUri != _uri) || !requestUri.startsWith(_uri)) + return false; + + return true; + } + + bool handle(WebServer& server, HTTPMethod requestMethod, String requestUri) override { + if (!canHandle(requestMethod, requestUri)) + return false; + + log_v("StaticRequestHandler::handle: request=%s _uri=%s\r\n", requestUri.c_str(), _uri.c_str()); + + String path(_path); + + if (!_isFile) { + // Base URI doesn't point to a file. + // If a directory is requested, look for index file. + if (requestUri.endsWith("/")) + requestUri += "index.htm"; + + // Append whatever follows this URI in request to get the file path. + path += requestUri.substring(_baseUriLength); + } + log_v("StaticRequestHandler::handle: path=%s, isFile=%d\r\n", path.c_str(), _isFile); + + String contentType = getContentType(path); + + // look for gz file, only if the original specified path is not a gz. So part only works to send gzip via content encoding when a non compressed is asked for + // if you point the the path to gzip you will serve the gzip as content type "application/x-gzip", not text or javascript etc... + if (!path.endsWith(FPSTR(mimeTable[gz].endsWith)) && !_fs.exists(path)) { + String pathWithGz = path + FPSTR(mimeTable[gz].endsWith); + if(_fs.exists(pathWithGz)) + path += FPSTR(mimeTable[gz].endsWith); + } + + File f = _fs.open(path, "r"); + if (!f) + return false; + + if (_cache_header.length() != 0) + server.sendHeader("Cache-Control", _cache_header); + + server.streamFile(f, contentType); + return true; + } + + static String getContentType(const String& path) { + char buff[sizeof(mimeTable[0].mimeType)]; + // Check all entries but last one for match, return if found + for (size_t i=0; i < sizeof(mimeTable)/sizeof(mimeTable[0])-1; i++) { + strcpy_P(buff, mimeTable[i].endsWith); + if (path.endsWith(buff)) { + strcpy_P(buff, mimeTable[i].mimeType); + return String(buff); + } + } + // Fall-through and just return default type + strcpy_P(buff, mimeTable[sizeof(mimeTable)/sizeof(mimeTable[0])-1].mimeType); + return String(buff); + } + +protected: + FS _fs; + String _uri; + String _path; + String _cache_header; + bool _isFile; + size_t _baseUriLength; +}; + + +#endif //REQUESTHANDLERSIMPL_H diff --git a/libraries/WebServer/src/detail/mimetable.cpp b/libraries/WebServer/src/detail/mimetable.cpp new file mode 100644 index 00000000000..563556a6358 --- /dev/null +++ b/libraries/WebServer/src/detail/mimetable.cpp @@ -0,0 +1,35 @@ +#include "mimetable.h" +#include "pgmspace.h" + +namespace mime +{ + +// Table of extension->MIME strings stored in PROGMEM, needs to be global due to GCC section typing rules +const Entry mimeTable[maxType] = +{ + { ".html", "text/html" }, + { ".htm", "text/html" }, + { ".css", "text/css" }, + { ".txt", "text/plain" }, + { ".js", "application/javascript" }, + { ".json", "application/json" }, + { ".png", "image/png" }, + { ".gif", "image/gif" }, + { ".jpg", "image/jpeg" }, + { ".ico", "image/x-icon" }, + { ".svg", "image/svg+xml" }, + { ".ttf", "application/x-font-ttf" }, + { ".otf", "application/x-font-opentype" }, + { ".woff", "application/font-woff" }, + { ".woff2", "application/font-woff2" }, + { ".eot", "application/vnd.ms-fontobject" }, + { ".sfnt", "application/font-sfnt" }, + { ".xml", "text/xml" }, + { ".pdf", "application/pdf" }, + { ".zip", "application/zip" }, + { ".gz", "application/x-gzip" }, + { ".appcache", "text/cache-manifest" }, + { "", "application/octet-stream" } +}; + +} diff --git a/libraries/WebServer/src/detail/mimetable.h b/libraries/WebServer/src/detail/mimetable.h new file mode 100644 index 00000000000..191356c489a --- /dev/null +++ b/libraries/WebServer/src/detail/mimetable.h @@ -0,0 +1,47 @@ +#ifndef __MIMETABLE_H__ +#define __MIMETABLE_H__ + + +namespace mime +{ + +enum type +{ + html, + htm, + css, + txt, + js, + json, + png, + gif, + jpg, + ico, + svg, + ttf, + otf, + woff, + woff2, + eot, + sfnt, + xml, + pdf, + zip, + gz, + appcache, + none, + maxType +}; + +struct Entry +{ + const char endsWith[16]; + const char mimeType[32]; +}; + + +extern const Entry mimeTable[maxType]; +} + + +#endif diff --git a/libraries/WiFi/examples/ETH_LAN8720/ETH_LAN8720.ino b/libraries/WiFi/examples/ETH_LAN8720/ETH_LAN8720.ino index af462b02f92..44bd1f965a0 100644 --- a/libraries/WiFi/examples/ETH_LAN8720/ETH_LAN8720.ino +++ b/libraries/WiFi/examples/ETH_LAN8720/ETH_LAN8720.ino @@ -1,81 +1,81 @@ -/* - This sketch shows the Ethernet event usage - -*/ - -#include - -static bool eth_connected = false; - -void WiFiEvent(WiFiEvent_t event) -{ - switch (event) { - case SYSTEM_EVENT_ETH_START: - Serial.println("ETH Started"); - //set eth hostname here - ETH.setHostname("esp32-ethernet"); - break; - case SYSTEM_EVENT_ETH_CONNECTED: - Serial.println("ETH Connected"); - break; - case SYSTEM_EVENT_ETH_GOT_IP: - Serial.print("ETH MAC: "); - Serial.print(ETH.macAddress()); - Serial.print(", IPv4: "); - Serial.print(ETH.localIP()); - if (ETH.fullDuplex()) { - Serial.print(", FULL_DUPLEX"); - } - Serial.print(", "); - Serial.print(ETH.linkSpeed()); - Serial.println("Mbps"); - eth_connected = true; - break; - case SYSTEM_EVENT_ETH_DISCONNECTED: - Serial.println("ETH Disconnected"); - eth_connected = false; - break; - case SYSTEM_EVENT_ETH_STOP: - Serial.println("ETH Stopped"); - eth_connected = false; - break; - default: - break; - } -} - -void testClient(const char * host, uint16_t port) -{ - Serial.print("\nconnecting to "); - Serial.println(host); - - WiFiClient client; - if (!client.connect(host, port)) { - Serial.println("connection failed"); - return; - } - client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host); - while (client.connected() && !client.available()); - while (client.available()) { - Serial.write(client.read()); - } - - Serial.println("closing connection\n"); - client.stop(); -} - -void setup() -{ - Serial.begin(115200); - WiFi.onEvent(WiFiEvent); - ETH.begin(); -} - - -void loop() -{ - if (eth_connected) { - testClient("google.com", 80); - } - delay(10000); -} +/* + This sketch shows the Ethernet event usage + +*/ + +#include + +static bool eth_connected = false; + +void WiFiEvent(WiFiEvent_t event) +{ + switch (event) { + case SYSTEM_EVENT_ETH_START: + Serial.println("ETH Started"); + //set eth hostname here + ETH.setHostname("esp32-ethernet"); + break; + case SYSTEM_EVENT_ETH_CONNECTED: + Serial.println("ETH Connected"); + break; + case SYSTEM_EVENT_ETH_GOT_IP: + Serial.print("ETH MAC: "); + Serial.print(ETH.macAddress()); + Serial.print(", IPv4: "); + Serial.print(ETH.localIP()); + if (ETH.fullDuplex()) { + Serial.print(", FULL_DUPLEX"); + } + Serial.print(", "); + Serial.print(ETH.linkSpeed()); + Serial.println("Mbps"); + eth_connected = true; + break; + case SYSTEM_EVENT_ETH_DISCONNECTED: + Serial.println("ETH Disconnected"); + eth_connected = false; + break; + case SYSTEM_EVENT_ETH_STOP: + Serial.println("ETH Stopped"); + eth_connected = false; + break; + default: + break; + } +} + +void testClient(const char * host, uint16_t port) +{ + Serial.print("\nconnecting to "); + Serial.println(host); + + WiFiClient client; + if (!client.connect(host, port)) { + Serial.println("connection failed"); + return; + } + client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host); + while (client.connected() && !client.available()); + while (client.available()) { + Serial.write(client.read()); + } + + Serial.println("closing connection\n"); + client.stop(); +} + +void setup() +{ + Serial.begin(115200); + WiFi.onEvent(WiFiEvent); + ETH.begin(); +} + + +void loop() +{ + if (eth_connected) { + testClient("google.com", 80); + } + delay(10000); +} diff --git a/libraries/WiFi/examples/ETH_LAN8720_internal_clock/ETH_LAN8720_internal_clock.ino b/libraries/WiFi/examples/ETH_LAN8720_internal_clock/ETH_LAN8720_internal_clock.ino index 482ee8142f8..6e726b7080e 100644 --- a/libraries/WiFi/examples/ETH_LAN8720_internal_clock/ETH_LAN8720_internal_clock.ino +++ b/libraries/WiFi/examples/ETH_LAN8720_internal_clock/ETH_LAN8720_internal_clock.ino @@ -10,6 +10,9 @@ * ETH_CLOCK_GPIO16_OUT - 50MHz clock from internal APLL output on GPIO16 - possibly an inverter is needed for LAN8720 * ETH_CLOCK_GPIO17_OUT - 50MHz clock from internal APLL inverted output on GPIO17 - tested with LAN8720 */ +#ifdef ETH_CLK_MODE +#undef ETH_CLK_MODE +#endif #define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT // Pin# of the enable signal for the external crystal oscillator (-1 to disable for internal APLL source) diff --git a/libraries/WiFi/examples/ETH_TLK110/ETH_TLK110.ino b/libraries/WiFi/examples/ETH_TLK110/ETH_TLK110.ino index 093efb3ebb0..f2c127945ad 100644 --- a/libraries/WiFi/examples/ETH_TLK110/ETH_TLK110.ino +++ b/libraries/WiFi/examples/ETH_TLK110/ETH_TLK110.ino @@ -1,87 +1,87 @@ -/* - This sketch shows the Ethernet event usage - -*/ - -#include - -#define ETH_ADDR 31 -#define ETH_POWER_PIN 17 -#define ETH_MDC_PIN 23 -#define ETH_MDIO_PIN 18 -#define ETH_TYPE ETH_PHY_TLK110 - -static bool eth_connected = false; - -void WiFiEvent(WiFiEvent_t event) -{ - switch (event) { - case SYSTEM_EVENT_ETH_START: - Serial.println("ETH Started"); - //set eth hostname here - ETH.setHostname("esp32-ethernet"); - break; - case SYSTEM_EVENT_ETH_CONNECTED: - Serial.println("ETH Connected"); - break; - case SYSTEM_EVENT_ETH_GOT_IP: - Serial.print("ETH MAC: "); - Serial.print(ETH.macAddress()); - Serial.print(", IPv4: "); - Serial.print(ETH.localIP()); - if (ETH.fullDuplex()) { - Serial.print(", FULL_DUPLEX"); - } - Serial.print(", "); - Serial.print(ETH.linkSpeed()); - Serial.println("Mbps"); - eth_connected = true; - break; - case SYSTEM_EVENT_ETH_DISCONNECTED: - Serial.println("ETH Disconnected"); - eth_connected = false; - break; - case SYSTEM_EVENT_ETH_STOP: - Serial.println("ETH Stopped"); - eth_connected = false; - break; - default: - break; - } -} - -void testClient(const char * host, uint16_t port) -{ - Serial.print("\nconnecting to "); - Serial.println(host); - - WiFiClient client; - if (!client.connect(host, port)) { - Serial.println("connection failed"); - return; - } - client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host); - while (client.connected() && !client.available()); - while (client.available()) { - Serial.write(client.read()); - } - - Serial.println("closing connection\n"); - client.stop(); -} - -void setup() -{ - Serial.begin(115200); - WiFi.onEvent(WiFiEvent); - ETH.begin(ETH_ADDR, ETH_POWER_PIN, ETH_MDC_PIN, ETH_MDIO_PIN, ETH_TYPE); -} - - -void loop() -{ - if (eth_connected) { - testClient("google.com", 80); - } - delay(10000); -} +/* + This sketch shows the Ethernet event usage + +*/ + +#include + +#define ETH_ADDR 31 +#define ETH_POWER_PIN 17 +#define ETH_MDC_PIN 23 +#define ETH_MDIO_PIN 18 +#define ETH_TYPE ETH_PHY_TLK110 + +static bool eth_connected = false; + +void WiFiEvent(WiFiEvent_t event) +{ + switch (event) { + case SYSTEM_EVENT_ETH_START: + Serial.println("ETH Started"); + //set eth hostname here + ETH.setHostname("esp32-ethernet"); + break; + case SYSTEM_EVENT_ETH_CONNECTED: + Serial.println("ETH Connected"); + break; + case SYSTEM_EVENT_ETH_GOT_IP: + Serial.print("ETH MAC: "); + Serial.print(ETH.macAddress()); + Serial.print(", IPv4: "); + Serial.print(ETH.localIP()); + if (ETH.fullDuplex()) { + Serial.print(", FULL_DUPLEX"); + } + Serial.print(", "); + Serial.print(ETH.linkSpeed()); + Serial.println("Mbps"); + eth_connected = true; + break; + case SYSTEM_EVENT_ETH_DISCONNECTED: + Serial.println("ETH Disconnected"); + eth_connected = false; + break; + case SYSTEM_EVENT_ETH_STOP: + Serial.println("ETH Stopped"); + eth_connected = false; + break; + default: + break; + } +} + +void testClient(const char * host, uint16_t port) +{ + Serial.print("\nconnecting to "); + Serial.println(host); + + WiFiClient client; + if (!client.connect(host, port)) { + Serial.println("connection failed"); + return; + } + client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host); + while (client.connected() && !client.available()); + while (client.available()) { + Serial.write(client.read()); + } + + Serial.println("closing connection\n"); + client.stop(); +} + +void setup() +{ + Serial.begin(115200); + WiFi.onEvent(WiFiEvent); + ETH.begin(ETH_ADDR, ETH_POWER_PIN, ETH_MDC_PIN, ETH_MDIO_PIN, ETH_TYPE); +} + + +void loop() +{ + if (eth_connected) { + testClient("google.com", 80); + } + delay(10000); +} diff --git a/libraries/WiFi/examples/WPS/WPS.ino b/libraries/WiFi/examples/WPS/WPS.ino index 79e11e8a611..06ccbb38438 100644 --- a/libraries/WiFi/examples/WPS/WPS.ino +++ b/libraries/WiFi/examples/WPS/WPS.ino @@ -16,16 +16,28 @@ Pranav Cherukupalli #include "WiFi.h" #include "esp_wps.h" - /* Change the definition of the WPS mode from WPS_TYPE_PBC to WPS_TYPE_PIN in the case that you are using pin type WPS */ -#define ESP_WPS_MODE WPS_TYPE_PBC +#define ESP_WPS_MODE WPS_TYPE_PBC +#define ESP_MANUFACTURER "ESPRESSIF" +#define ESP_MODEL_NUMBER "ESP32" +#define ESP_MODEL_NAME "ESPRESSIF IOT" +#define ESP_DEVICE_NAME "ESP STATION" + +static esp_wps_config_t config; -esp_wps_config_t config = WPS_CONFIG_INIT_DEFAULT(ESP_WPS_MODE); +void wpsInitConfig(){ + config.crypto_funcs = &g_wifi_default_wps_crypto_funcs; + config.wps_type = ESP_WPS_MODE; + strcpy(config.factory_info.manufacturer, ESP_MANUFACTURER); + strcpy(config.factory_info.model_number, ESP_MODEL_NUMBER); + strcpy(config.factory_info.model_name, ESP_MODEL_NAME); + strcpy(config.factory_info.device_name, ESP_DEVICE_NAME); +} String wpspin2string(uint8_t a[]){ char wps_pin[9]; @@ -39,40 +51,40 @@ String wpspin2string(uint8_t a[]){ void WiFiEvent(WiFiEvent_t event, system_event_info_t info){ switch(event){ case SYSTEM_EVENT_STA_START: - Serial.println("Station Mode Started"); - break; + Serial.println("Station Mode Started"); + break; case SYSTEM_EVENT_STA_GOT_IP: - Serial.println("Connected to :" + String(WiFi.SSID())); - Serial.print("Got IP: "); - Serial.println(WiFi.localIP()); - break; + Serial.println("Connected to :" + String(WiFi.SSID())); + Serial.print("Got IP: "); + Serial.println(WiFi.localIP()); + break; case SYSTEM_EVENT_STA_DISCONNECTED: - Serial.println("Disconnected from station, attempting reconnection"); - WiFi.reconnect(); - break; + Serial.println("Disconnected from station, attempting reconnection"); + WiFi.reconnect(); + break; case SYSTEM_EVENT_STA_WPS_ER_SUCCESS: - Serial.println("WPS Successfull, stopping WPS and connecting to: " + String(WiFi.SSID())); - esp_wifi_wps_disable(); - delay(10); - WiFi.begin(); - break; + Serial.println("WPS Successfull, stopping WPS and connecting to: " + String(WiFi.SSID())); + esp_wifi_wps_disable(); + delay(10); + WiFi.begin(); + break; case SYSTEM_EVENT_STA_WPS_ER_FAILED: - Serial.println("WPS Failed, retrying"); - esp_wifi_wps_disable(); - esp_wifi_wps_enable(&config); - esp_wifi_wps_start(0); - break; + Serial.println("WPS Failed, retrying"); + esp_wifi_wps_disable(); + esp_wifi_wps_enable(&config); + esp_wifi_wps_start(0); + break; case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT: - Serial.println("WPS Timedout, retrying"); - esp_wifi_wps_disable(); - esp_wifi_wps_enable(&config); - esp_wifi_wps_start(0); - break; + Serial.println("WPS Timedout, retrying"); + esp_wifi_wps_disable(); + esp_wifi_wps_enable(&config); + esp_wifi_wps_start(0); + break; case SYSTEM_EVENT_STA_WPS_ER_PIN: - Serial.println("WPS_PIN = " + wpspin2string(info.sta_er_pin.pin_code)); - break; + Serial.println("WPS_PIN = " + wpspin2string(info.sta_er_pin.pin_code)); + break; default: - break; + break; } } @@ -87,10 +99,11 @@ void setup(){ Serial.println("Starting WPS"); + wpsInitConfig(); esp_wifi_wps_enable(&config); esp_wifi_wps_start(0); } void loop(){ //nothing to do here -} +} \ No newline at end of file diff --git a/libraries/WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino b/libraries/WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino new file mode 100644 index 00000000000..4e654d12c79 --- /dev/null +++ b/libraries/WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino @@ -0,0 +1,93 @@ +/* + WiFiAccessPoint.ino creates a WiFi access point and provides a web server on it. + + Steps: + 1. Connect to the access point "yourAp" + 2. Point your web browser to http://192.168.4.1/H to turn the LED on or http://192.168.4.1/L to turn it off + OR + Run raw TCP "GET /H" and "GET /L" on PuTTY terminal with 192.168.4.1 as IP address and 80 as port + + Created for arduino-esp32 on 04 July, 2018 + by Elochukwu Ifediora (fedy0) +*/ + +#include +#include +#include + +#define LED_BUILTIN 2 // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED + +// Set these to your desired credentials. +const char *ssid = "yourAP"; +const char *password = "yourPassword"; + +WiFiServer server(80); + + +void setup() { + pinMode(LED_BUILTIN, OUTPUT); + + Serial.begin(115200); + Serial.println(); + Serial.println("Configuring access point..."); + + // You can remove the password parameter if you want the AP to be open. + WiFi.softAP(ssid, password); + IPAddress myIP = WiFi.softAPIP(); + Serial.print("AP IP address: "); + Serial.println(myIP); + server.begin(); + + Serial.println("Server started"); +} + +void loop() { + WiFiClient client = server.available(); // listen for incoming clients + + if (client) { // if you get a client, + Serial.println("New Client."); // print a message out the serial port + String currentLine = ""; // make a String to hold incoming data from the client + while (client.connected()) { // loop while the client's connected + if (client.available()) { // if there's bytes to read from the client, + char c = client.read(); // read a byte, then + Serial.write(c); // print it out the serial monitor + if (c == '\n') { // if the byte is a newline character + + // if the current line is blank, you got two newline characters in a row. + // that's the end of the client HTTP request, so send a response: + if (currentLine.length() == 0) { + // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) + // and a content-type so the client knows what's coming, then a blank line: + client.println("HTTP/1.1 200 OK"); + client.println("Content-type:text/html"); + client.println(); + + // the content of the HTTP response follows the header: + client.print("Click here to turn ON the LED.
"); + client.print("Click here to turn OFF the LED.
"); + + // The HTTP response ends with another blank line: + client.println(); + // break out of the while loop: + break; + } else { // if you got a newline, then clear currentLine: + currentLine = ""; + } + } else if (c != '\r') { // if you got anything else but a carriage return character, + currentLine += c; // add it to the end of the currentLine + } + + // Check to see if the client request was "GET /H" or "GET /L": + if (currentLine.endsWith("GET /H")) { + digitalWrite(LED_BUILTIN, HIGH); // GET /H turns the LED on + } + if (currentLine.endsWith("GET /L")) { + digitalWrite(LED_BUILTIN, LOW); // GET /L turns the LED off + } + } + } + // close the connection: + client.stop(); + Serial.println("Client Disconnected."); + } +} diff --git a/libraries/WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino b/libraries/WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino index 27901521eb8..ecfed5e1957 100644 --- a/libraries/WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino +++ b/libraries/WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino @@ -18,7 +18,7 @@ void setup() Serial.println(); Serial.println(); - Serial.print("Wait for WiFi... "); + Serial.print("Waiting for WiFi... "); while(WiFiMulti.run() != WL_CONNECTED) { Serial.print("."); @@ -36,35 +36,52 @@ void setup() void loop() { - const uint16_t port = 80; - const char * host = "192.168.1.1"; // ip or dns +// const uint16_t port = 80; +// const char * host = "192.168.1.1"; // ip or dns + const uint16_t port = 1337; + const char * host = "192.168.1.10"; // ip or dns - - - Serial.print("connecting to "); + Serial.print("Connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; if (!client.connect(host, port)) { - Serial.println("connection failed"); - Serial.println("wait 5 sec..."); + Serial.println("Connection failed."); + Serial.println("Waiting 5 seconds before retrying..."); delay(5000); return; } - // This will send the request to the server - client.print("Send this data to server"); - - //read back one line from server + // This will send a request to the server + //uncomment this line to send an arbitrary string to the server + //client.print("Send this data to the server"); + //uncomment this line to send a basic document request to the server + client.print("GET /index.html HTTP/1.1\n\n"); + + int maxloops = 0; + + //wait for the server's reply to become available + while (!client.available() && maxloops < 1000) + { + maxloops++; + delay(1); //delay 1 msec + } + if (client.available() > 0) + { + //read back one line from the server String line = client.readStringUntil('\r'); - client.println(line); - - Serial.println("closing connection"); + Serial.println(line); + } + else + { + Serial.println("client.available() timed out "); + } + + Serial.println("Closing connection."); client.stop(); - Serial.println("wait 5 sec..."); + Serial.println("Waiting 5 seconds before restarting..."); delay(5000); } - diff --git a/libraries/WiFi/examples/WiFiClientEnterprise/README.md b/libraries/WiFi/examples/WiFiClientEnterprise/README.md new file mode 100644 index 00000000000..8160ddabccc --- /dev/null +++ b/libraries/WiFi/examples/WiFiClientEnterprise/README.md @@ -0,0 +1,43 @@ +# ESP32-Eduroam +* Eduroam wifi connection with university login identity +* Working under Eduroam networks worldwide +* Methods: PEAP + MsCHAPv2 + +# Format +* IDENTITY = youridentity --> if connecting from different university, use youridentity@youruniversity.domain format +* PASSWORD = yourpassword + +# Usage +* Change IDENTITY +* Change password +* Upload sketch and enjoy! +* After sucessful assign of IP address, board will connect to HTTP page on internet to verify your authentification +* Board will auto reconnect to Eduroam if it lost connection + +# Tested locations +|University|Board|Method|Result| +|-------------|-------------| -----|------| +|Technical University in Košice (Slovakia)|ESP32 Devkit v1|PEAP + MsCHAPv2|Working| +|Technical University in Košice (Slovakia)|ESP32 Devmodule v4|PEAP + MsCHAPv2|Working on 6th attempt in loop| +|Slovak Technical University in Bratislava (Slovakia)|ESP32 Devkit v1|PEAP + MsCHAPv2|Working| +|University of Antwerp (Belgium)|Lolin32|PEAP + MsCHAPv2|Working| +|UPV Universitat Politècnica de València (Spain)|ESP32 Devmodule v4|PEAP + MsCHAPv2|Working| +|Local Zeroshell powered network|ESP32 Devkit v1|PEAP + MsCHAPv2|*Not working*| +|Hasselt University (Belgium)|xxx|PEAP + MsCHAPv2|Working with fix sketch| +|Universidad de Granada (Spain)|Lolin D32 Pro|PEAP + MsCHAPv2|Working| +|Universidad de Granada (Spain)|Lolin D32|PEAP + MsCHAPv2|Working| +|Universidade Federal de Santa Catarina (Brazil)|xxx|EAP-TTLS + MsCHAPv2|Working| +|University of Central Florida (Orlando, Florida)|ESP32 Built-in OLED – Heltec WiFi Kit 32|PEAP + MsCHAPv2|Working| +|Université de Montpellier (France)|NodeMCU-32S|PEAP + MsCHAPv2|Working| + +# Common errors - Switch to Debug mode for Serial monitor prints +|Error|Appearance|Solution| +|-------------|-------------|-------------| +|wifi: Set status to INIT|Frequent|Hold EN button for few seconds| +|HANDSHAKE_TIMEOUT|Rare|Bug was found under Zeroshell RADIUS authentization - Unsucessful connection| +|AUTH_EXPIRE|Common|In the case of weak wifi network signal, this error is quite common, bring your device closer to AP| +|ASSOC_EXPIRE|Rare|-| +# Sucessful connection example + ![alt text](https://i.nahraj.to/f/24Kc.png) +# Unsucessful connection example + ![alt text](https://camo.githubusercontent.com/87e47d1b27f4e8ace87423e40e8edbce7983bafa/68747470733a2f2f692e6e616872616a2e746f2f662f323435572e504e47) diff --git a/libraries/WiFi/examples/WiFiClientEnterprise/WiFiClientEnterprise.ino b/libraries/WiFi/examples/WiFiClientEnterprise/WiFiClientEnterprise.ino new file mode 100644 index 00000000000..0c861cddcf0 --- /dev/null +++ b/libraries/WiFi/examples/WiFiClientEnterprise/WiFiClientEnterprise.ino @@ -0,0 +1,69 @@ +#include //Wifi library +#include "esp_wpa2.h" //wpa2 library for connections to Enterprise networks +#define EAP_IDENTITY "login" //if connecting from another corporation, use identity@organisation.domain in Eduroam +#define EAP_PASSWORD "password" //your Eduroam password +const char* ssid = "eduroam"; // Eduroam SSID +const char* host = "arduino.php5.sk"; //external server domain for HTTP connection after authentification +int counter = 0; +void setup() { + Serial.begin(115200); + delay(10); + Serial.println(); + Serial.print("Connecting to network: "); + Serial.println(ssid); + WiFi.disconnect(true); //disconnect form wifi to set new wifi connection + WiFi.mode(WIFI_STA); //init wifi mode + esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide identity + esp_wifi_sta_wpa2_ent_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide username --> identity and username is same + esp_wifi_sta_wpa2_ent_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD)); //provide password + esp_wpa2_config_t config = WPA2_CONFIG_INIT_DEFAULT(); //set config settings to default + esp_wifi_sta_wpa2_ent_enable(&config); //set config settings to enable function + WiFi.begin(ssid); //connect to wifi + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + counter++; + if(counter>=60){ //after 30 seconds timeout - reset board + ESP.restart(); + } + } + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address set: "); + Serial.println(WiFi.localIP()); //print LAN IP +} +void loop() { + if (WiFi.status() == WL_CONNECTED) { //if we are connected to Eduroam network + counter = 0; //reset counter + Serial.println("Wifi is still connected with IP: "); + Serial.println(WiFi.localIP()); //inform user about his IP address + }else if (WiFi.status() != WL_CONNECTED) { //if we lost connection, retry + WiFi.begin(ssid); + } + while (WiFi.status() != WL_CONNECTED) { //during lost connection, print dots + delay(500); + Serial.print("."); + counter++; + if(counter>=60){ //30 seconds timeout - reset board + ESP.restart(); + } + } + Serial.print("Connecting to website: "); + Serial.println(host); + WiFiClient client; + if (client.connect(host, 80)) { + String url = "/rele/rele1.txt"; + client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "User-Agent: ESP32\r\n" + "Connection: close\r\n\r\n"); + + while (client.connected()) { + String line = client.readStringUntil('\n'); + if (line == "\r") { + break; + } + } + String line = client.readStringUntil('\n'); + Serial.println(line); + }else{ + Serial.println("Connection unsucessful"); + } +} diff --git a/libraries/WiFi/examples/WiFiClientEvents/WiFiClientEvents.ino b/libraries/WiFi/examples/WiFiClientEvents/WiFiClientEvents.ino index 6971e269be0..a7b029481e5 100644 --- a/libraries/WiFi/examples/WiFiClientEvents/WiFiClientEvents.ino +++ b/libraries/WiFi/examples/WiFiClientEvents/WiFiClientEvents.ino @@ -1,51 +1,166 @@ -/* - * This sketch shows the WiFi event usage - * - */ - -#include - -const char* ssid = "your-ssid"; -const char* password = "your-password"; - - -void WiFiEvent(WiFiEvent_t event) -{ - Serial.printf("[WiFi-event] event: %d\n", event); - - switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - Serial.println("WiFi lost connection"); - break; - } -} - -void setup() -{ - Serial.begin(115200); - - // delete old config - WiFi.disconnect(true); - - delay(1000); - - WiFi.onEvent(WiFiEvent); - - WiFi.begin(ssid, password); - - Serial.println(); - Serial.println(); - Serial.println("Wait for WiFi... "); -} - - -void loop() -{ - delay(1000); -} - +/* + * This sketch shows the WiFi event usage + * +*/ + +/* +* WiFi Events + +0 SYSTEM_EVENT_WIFI_READY < ESP32 WiFi ready +1 SYSTEM_EVENT_SCAN_DONE < ESP32 finish scanning AP +2 SYSTEM_EVENT_STA_START < ESP32 station start +3 SYSTEM_EVENT_STA_STOP < ESP32 station stop +4 SYSTEM_EVENT_STA_CONNECTED < ESP32 station connected to AP +5 SYSTEM_EVENT_STA_DISCONNECTED < ESP32 station disconnected from AP +6 SYSTEM_EVENT_STA_AUTHMODE_CHANGE < the auth mode of AP connected by ESP32 station changed +7 SYSTEM_EVENT_STA_GOT_IP < ESP32 station got IP from connected AP +8 SYSTEM_EVENT_STA_LOST_IP < ESP32 station lost IP and the IP is reset to 0 +9 SYSTEM_EVENT_STA_WPS_ER_SUCCESS < ESP32 station wps succeeds in enrollee mode +10 SYSTEM_EVENT_STA_WPS_ER_FAILED < ESP32 station wps fails in enrollee mode +11 SYSTEM_EVENT_STA_WPS_ER_TIMEOUT < ESP32 station wps timeout in enrollee mode +12 SYSTEM_EVENT_STA_WPS_ER_PIN < ESP32 station wps pin code in enrollee mode +13 SYSTEM_EVENT_AP_START < ESP32 soft-AP start +14 SYSTEM_EVENT_AP_STOP < ESP32 soft-AP stop +15 SYSTEM_EVENT_AP_STACONNECTED < a station connected to ESP32 soft-AP +16 SYSTEM_EVENT_AP_STADISCONNECTED < a station disconnected from ESP32 soft-AP +17 SYSTEM_EVENT_AP_STAIPASSIGNED < ESP32 soft-AP assign an IP to a connected station +18 SYSTEM_EVENT_AP_PROBEREQRECVED < Receive probe request packet in soft-AP interface +19 SYSTEM_EVENT_GOT_IP6 < ESP32 station or ap or ethernet interface v6IP addr is preferred +20 SYSTEM_EVENT_ETH_START < ESP32 ethernet start +21 SYSTEM_EVENT_ETH_STOP < ESP32 ethernet stop +22 SYSTEM_EVENT_ETH_CONNECTED < ESP32 ethernet phy link up +23 SYSTEM_EVENT_ETH_DISCONNECTED < ESP32 ethernet phy link down +24 SYSTEM_EVENT_ETH_GOT_IP < ESP32 ethernet got IP from connected AP +25 SYSTEM_EVENT_MAX +*/ + +#include + +const char* ssid = "your-ssid"; +const char* password = "your-password"; + + +void WiFiEvent(WiFiEvent_t event) +{ + Serial.printf("[WiFi-event] event: %d\n", event); + + switch (event) { + case SYSTEM_EVENT_WIFI_READY: + Serial.println("WiFi interface ready"); + break; + case SYSTEM_EVENT_SCAN_DONE: + Serial.println("Completed scan for access points"); + break; + case SYSTEM_EVENT_STA_START: + Serial.println("WiFi client started"); + break; + case SYSTEM_EVENT_STA_STOP: + Serial.println("WiFi clients stopped"); + break; + case SYSTEM_EVENT_STA_CONNECTED: + Serial.println("Connected to access point"); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + Serial.println("Disconnected from WiFi access point"); + break; + case SYSTEM_EVENT_STA_AUTHMODE_CHANGE: + Serial.println("Authentication mode of access point has changed"); + break; + case SYSTEM_EVENT_STA_GOT_IP: + Serial.print("Obtained IP address: "); + Serial.println(WiFi.localIP()); + break; + case SYSTEM_EVENT_STA_LOST_IP: + Serial.println("Lost IP address and IP address is reset to 0"); + break; + case SYSTEM_EVENT_STA_WPS_ER_SUCCESS: + Serial.println("WiFi Protected Setup (WPS): succeeded in enrollee mode"); + break; + case SYSTEM_EVENT_STA_WPS_ER_FAILED: + Serial.println("WiFi Protected Setup (WPS): failed in enrollee mode"); + break; + case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT: + Serial.println("WiFi Protected Setup (WPS): timeout in enrollee mode"); + break; + case SYSTEM_EVENT_STA_WPS_ER_PIN: + Serial.println("WiFi Protected Setup (WPS): pin code in enrollee mode"); + break; + case SYSTEM_EVENT_AP_START: + Serial.println("WiFi access point started"); + break; + case SYSTEM_EVENT_AP_STOP: + Serial.println("WiFi access point stopped"); + break; + case SYSTEM_EVENT_AP_STACONNECTED: + Serial.println("Client connected"); + break; + case SYSTEM_EVENT_AP_STADISCONNECTED: + Serial.println("Client disconnected"); + break; + case SYSTEM_EVENT_AP_STAIPASSIGNED: + Serial.println("Assigned IP address to client"); + break; + case SYSTEM_EVENT_AP_PROBEREQRECVED: + Serial.println("Received probe request"); + break; + case SYSTEM_EVENT_GOT_IP6: + Serial.println("IPv6 is preferred"); + break; + case SYSTEM_EVENT_ETH_START: + Serial.println("Ethernet started"); + break; + case SYSTEM_EVENT_ETH_STOP: + Serial.println("Ethernet stopped"); + break; + case SYSTEM_EVENT_ETH_CONNECTED: + Serial.println("Ethernet connected"); + break; + case SYSTEM_EVENT_ETH_DISCONNECTED: + Serial.println("Ethernet disconnected"); + break; + case SYSTEM_EVENT_ETH_GOT_IP: + Serial.println("Obtained IP address"); + break; + default: break; + }} + +void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info) +{ + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(IPAddress(info.got_ip.ip_info.ip.addr)); +} + +void setup() +{ + Serial.begin(115200); + + // delete old config + WiFi.disconnect(true); + + delay(1000); + + // Examples of different ways to register wifi events + WiFi.onEvent(WiFiEvent); + WiFi.onEvent(WiFiGotIP, WiFiEvent_t::SYSTEM_EVENT_STA_GOT_IP); + WiFiEventId_t eventID = WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){ + Serial.print("WiFi lost connection. Reason: "); + Serial.println(info.disconnected.reason); + }, WiFiEvent_t::SYSTEM_EVENT_STA_DISCONNECTED); + + // Remove WiFi event + Serial.print("WiFi Event ID: "); + Serial.println(eventID); + // WiFi.removeEvent(eventID); + + WiFi.begin(ssid, password); + + Serial.println(); + Serial.println(); + Serial.println("Wait for WiFi... "); +} + +void loop() +{ + delay(1000); +} diff --git a/libraries/WiFi/examples/WiFiClientStaticIP/WiFiClientStaticIP.ino b/libraries/WiFi/examples/WiFiClientStaticIP/WiFiClientStaticIP.ino index 17559560551..1f4032f0640 100644 --- a/libraries/WiFi/examples/WiFiClientStaticIP/WiFiClientStaticIP.ino +++ b/libraries/WiFi/examples/WiFiClientStaticIP/WiFiClientStaticIP.ino @@ -89,4 +89,4 @@ void loop() Serial.println(); Serial.println("closing connection"); } - + diff --git a/libraries/WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino b/libraries/WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino index 6821b057853..63bdf6c13b6 100644 --- a/libraries/WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino +++ b/libraries/WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino @@ -31,8 +31,6 @@ const char* password = "**********"; WiFiServer server(23); WiFiClient serverClients[MAX_SRV_CLIENTS]; -HardwareSerial Serial1(2); // UART1/Serial1 pins 16,17 - void setup() { Serial.begin(115200); Serial.println("\nConnecting"); @@ -62,7 +60,7 @@ void setup() { } //start UART and the server - Serial1.begin(9600); + Serial2.begin(9600); server.begin(); server.setNoDelay(true); @@ -98,7 +96,7 @@ void loop() { if (serverClients[i] && serverClients[i].connected()){ if(serverClients[i].available()){ //get data from the telnet client and push it to the UART - while(serverClients[i].available()) Serial1.write(serverClients[i].read()); + while(serverClients[i].available()) Serial2.write(serverClients[i].read()); } } else { @@ -108,10 +106,10 @@ void loop() { } } //check UART for data - if(Serial1.available()){ - size_t len = Serial1.available(); + if(Serial2.available()){ + size_t len = Serial2.available(); uint8_t sbuf[len]; - Serial1.readBytes(sbuf, len); + Serial2.readBytes(sbuf, len); //push UART data to all connected telnet clients for(i = 0; i < MAX_SRV_CLIENTS; i++){ if (serverClients[i] && serverClients[i].connected()){ diff --git a/libraries/WiFi/examples/WiFiUDPClient/WiFiUDPClient.ino b/libraries/WiFi/examples/WiFiUDPClient/WiFiUDPClient.ino index 04d4effd0a8..310989f0c1f 100644 --- a/libraries/WiFi/examples/WiFiUDPClient/WiFiUDPClient.ino +++ b/libraries/WiFi/examples/WiFiUDPClient/WiFiUDPClient.ino @@ -34,7 +34,7 @@ void loop(){ if(connected){ //Send a packet udp.beginPacket(udpAddress,udpPort); - udp.printf("Seconds since boot: %u", millis()/1000); + udp.printf("Seconds since boot: %lu", millis()/1000); udp.endPacket(); } //Wait for 1 second @@ -71,5 +71,6 @@ void WiFiEvent(WiFiEvent_t event){ Serial.println("WiFi lost connection"); connected = false; break; + default: break; } } diff --git a/libraries/WiFi/src/ETH.cpp b/libraries/WiFi/src/ETH.cpp index b9caddb1130..2ffea758ded 100644 --- a/libraries/WiFi/src/ETH.cpp +++ b/libraries/WiFi/src/ETH.cpp @@ -197,6 +197,33 @@ IPAddress ETHClass::dnsIP(uint8_t dns_no) return IPAddress(dns_ip.u_addr.ip4.addr); } +IPAddress ETHClass::broadcastIP() +{ + tcpip_adapter_ip_info_t ip; + if(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_ETH, &ip)){ + return IPAddress(); + } + return WiFiGenericClass::calculateBroadcast(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr)); +} + +IPAddress ETHClass::networkID() +{ + tcpip_adapter_ip_info_t ip; + if(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_ETH, &ip)){ + return IPAddress(); + } + return WiFiGenericClass::calculateNetworkID(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr)); +} + +uint8_t ETHClass::subnetCIDR() +{ + tcpip_adapter_ip_info_t ip; + if(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_ETH, &ip)){ + return (uint8_t)0; + } + return WiFiGenericClass::calculateSubnetCIDR(IPAddress(ip.netmask.addr)); +} + const char * ETHClass::getHostname() { const char * hostname; diff --git a/libraries/WiFi/src/ETH.h b/libraries/WiFi/src/ETH.h index 8dcd85b9cbd..f5441a9d0ed 100644 --- a/libraries/WiFi/src/ETH.h +++ b/libraries/WiFi/src/ETH.h @@ -79,6 +79,10 @@ class ETHClass { IPAddress gatewayIP(); IPAddress dnsIP(uint8_t dns_no = 0); + IPAddress broadcastIP(); + IPAddress networkID(); + uint8_t subnetCIDR(); + uint8_t * macAddress(uint8_t* mac); String macAddress(); diff --git a/libraries/WiFi/src/WiFi.cpp b/libraries/WiFi/src/WiFi.cpp index 87dc2a2f45d..a78e0c3ebc2 100644 --- a/libraries/WiFi/src/WiFi.cpp +++ b/libraries/WiFi/src/WiFi.cpp @@ -56,9 +56,6 @@ void WiFiClass::printDiag(Print& p) wifi_second_chan_t secondChan; esp_wifi_get_channel(&primaryChan, &secondChan); - bool autoConnect; - esp_wifi_get_auto_connect(&autoConnect); - p.print("Mode: "); p.println(modes[mode]); @@ -71,8 +68,6 @@ void WiFiClass::printDiag(Print& p) p.print("Status: "); p.println(wifi_station_get_connect_status()); */ - p.print("Auto connect: "); - p.println(autoConnect); wifi_config_t conf; esp_wifi_get_config(WIFI_IF_STA, &conf); diff --git a/libraries/WiFi/src/WiFi.h b/libraries/WiFi/src/WiFi.h index b53b6619aaf..ad6c327427c 100644 --- a/libraries/WiFi/src/WiFi.h +++ b/libraries/WiFi/src/WiFi.h @@ -1,5 +1,5 @@ /* - ESP8266WiFi.h - esp8266 Wifi support. + WiFi.h - esp32 Wifi support. Based on WiFi.h from Arduino WiFi shield library. Copyright (c) 2011-2014 Arduino. All right reserved. Modified by Ivan Grokhotkov, December 2014 diff --git a/libraries/WiFi/src/WiFiAP.cpp b/libraries/WiFi/src/WiFiAP.cpp index a726f6762f9..1f8af5852ee 100644 --- a/libraries/WiFi/src/WiFiAP.cpp +++ b/libraries/WiFi/src/WiFiAP.cpp @@ -1,293 +1,365 @@ -/* - ESP8266WiFiSTA.cpp - WiFi library for esp8266 - - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Reworked on 28 Dec 2015 by Markus Sattler - - */ - -#include "WiFi.h" -#include "WiFiGeneric.h" -#include "WiFiAP.h" - -extern "C" { -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "apps/dhcpserver_options.h" -} - - - -// ----------------------------------------------------------------------------------------------------------------------- -// ---------------------------------------------------- Private functions ------------------------------------------------ -// ----------------------------------------------------------------------------------------------------------------------- - -static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs); - - - -/** - * compare two AP configurations - * @param lhs softap_config - * @param rhs softap_config - * @return equal - */ -static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs) -{ - if(strcmp(reinterpret_cast(lhs.ap.ssid), reinterpret_cast(rhs.ap.ssid)) != 0) { - return false; - } - if(strcmp(reinterpret_cast(lhs.ap.password), reinterpret_cast(rhs.ap.password)) != 0) { - return false; - } - if(lhs.ap.channel != rhs.ap.channel) { - return false; - } - if(lhs.ap.ssid_hidden != rhs.ap.ssid_hidden) { - return false; - } - if(lhs.ap.max_connection != rhs.ap.max_connection) { - return false; - } - return true; -} - -// ----------------------------------------------------------------------------------------------------------------------- -// ----------------------------------------------------- AP function ----------------------------------------------------- -// ----------------------------------------------------------------------------------------------------------------------- - - -/** - * Set up an access point - * @param ssid Pointer to the SSID (max 63 char). - * @param passphrase (for WPA2 min 8 char, for open use NULL) - * @param channel WiFi channel number, 1 - 13. - * @param ssid_hidden Network cloaking (0 = broadcast SSID, 1 = hide SSID) - * @param max_connection Max simultaneous connected clients, 1 - 4. -*/ -bool WiFiAPClass::softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection) -{ - - if(!WiFi.enableAP(true)) { - // enable AP failed - return false; - } - - if(!ssid || *ssid == 0 || strlen(ssid) > 31) { - // fail SSID too long or missing! - return false; - } - - if(passphrase && (strlen(passphrase) > 63 || strlen(passphrase) < 8)) { - // fail passphrase to long or short! - return false; - } - - esp_wifi_start(); - - wifi_config_t conf; - strcpy(reinterpret_cast(conf.ap.ssid), ssid); - conf.ap.channel = channel; - conf.ap.ssid_len = strlen(ssid); - conf.ap.ssid_hidden = ssid_hidden; - conf.ap.max_connection = max_connection; - conf.ap.beacon_interval = 100; - - if(!passphrase || strlen(passphrase) == 0) { - conf.ap.authmode = WIFI_AUTH_OPEN; - *conf.ap.password = 0; - } else { - conf.ap.authmode = WIFI_AUTH_WPA2_PSK; - strcpy(reinterpret_cast(conf.ap.password), passphrase); - } - - wifi_config_t conf_current; - esp_wifi_get_config(WIFI_IF_AP, &conf_current); - if(!softap_config_equal(conf, conf_current) && esp_wifi_set_config(WIFI_IF_AP, &conf) != ESP_OK) { - return false; - } - - return true; -} - - -/** - * Configure access point - * @param local_ip access point IP - * @param gateway gateway IP - * @param subnet subnet mask - */ -bool WiFiAPClass::softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet) -{ - - if(!WiFi.enableAP(true)) { - // enable AP failed - return false; - } - - esp_wifi_start(); - - tcpip_adapter_ip_info_t info; - info.ip.addr = static_cast(local_ip); - info.gw.addr = static_cast(gateway); - info.netmask.addr = static_cast(subnet); - tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP); - if(tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_AP, &info) == ESP_OK) { - dhcps_lease_t lease; - lease.enable = true; - lease.start_ip.addr = static_cast(local_ip) + (1 << 24); - lease.end_ip.addr = static_cast(local_ip) + (11 << 24); - - tcpip_adapter_dhcps_option( - (tcpip_adapter_option_mode_t)TCPIP_ADAPTER_OP_SET, - (tcpip_adapter_option_id_t)REQUESTED_IP_ADDRESS, - (void*)&lease, sizeof(dhcps_lease_t) - ); - - return tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP) == ESP_OK; - } - return false; -} - - - -/** - * Disconnect from the network (close AP) - * @param wifioff disable mode? - * @return one value of wl_status_t enum - */ -bool WiFiAPClass::softAPdisconnect(bool wifioff) -{ - bool ret; - wifi_config_t conf; - *conf.ap.ssid = 0; - *conf.ap.password = 0; - conf.ap.authmode = WIFI_AUTH_OPEN; // auth must be open if pass=0 - ret = esp_wifi_set_config(WIFI_IF_AP, &conf) == ESP_OK; - - if(wifioff) { - ret = WiFi.enableAP(false) == ESP_OK; - } - - return ret; -} - - -/** - * Get the count of the Station / client that are connected to the softAP interface - * @return Stations count - */ -uint8_t WiFiAPClass::softAPgetStationNum() -{ - wifi_sta_list_t clients; - if(esp_wifi_ap_get_sta_list(&clients) == ESP_OK) { - return clients.num; - } - return 0; -} - -/** - * Get the softAP interface IP address. - * @return IPAddress softAP IP - */ -IPAddress WiFiAPClass::softAPIP() -{ - tcpip_adapter_ip_info_t ip; - tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip); - return IPAddress(ip.ip.addr); -} - - -/** - * Get the softAP interface MAC address. - * @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH - * @return pointer to uint8_t* - */ -uint8_t* WiFiAPClass::softAPmacAddress(uint8_t* mac) -{ - esp_wifi_get_mac(WIFI_IF_AP, mac); - return mac; -} - -/** - * Get the softAP interface MAC address. - * @return String mac - */ -String WiFiAPClass::softAPmacAddress(void) -{ - uint8_t mac[6]; - char macStr[18] = { 0 }; - esp_wifi_get_mac(WIFI_IF_AP, mac); - - sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - return String(macStr); -} - -/** - * Get the softAP interface Host name. - * @return char array hostname - */ -const char * WiFiAPClass::softAPgetHostname() -{ - const char * hostname; - if(tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_AP, &hostname)) { - return NULL; - } - return hostname; -} - -/** - * Set the softAP interface Host name. - * @param hostname pointer to const string - * @return true on success - */ -bool WiFiAPClass::softAPsetHostname(const char * hostname) -{ - return tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_AP, hostname) == ESP_OK; -} - -/** - * Enable IPv6 on the softAP interface. - * @return true on success - */ -bool WiFiAPClass::softAPenableIpV6() -{ - return tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_AP) == ESP_OK; -} - -/** - * Get the softAP interface IPv6 address. - * @return IPv6Address softAP IPv6 - */ -IPv6Address WiFiAPClass::softAPIPv6() -{ - static ip6_addr_t addr; - if(tcpip_adapter_get_ip6_linklocal(TCPIP_ADAPTER_IF_AP, &addr)) { - return IPv6Address(); - } - return IPv6Address(addr.addr); -} +/* + ESP8266WiFiSTA.cpp - WiFi library for esp8266 + + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Reworked on 28 Dec 2015 by Markus Sattler + + */ + +#include "WiFi.h" +#include "WiFiGeneric.h" +#include "WiFiAP.h" + +extern "C" { +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "dhcpserver/dhcpserver_options.h" +} + + + +// ----------------------------------------------------------------------------------------------------------------------- +// ---------------------------------------------------- Private functions ------------------------------------------------ +// ----------------------------------------------------------------------------------------------------------------------- + +static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs); + + + +/** + * compare two AP configurations + * @param lhs softap_config + * @param rhs softap_config + * @return equal + */ +static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs) +{ + if(strcmp(reinterpret_cast(lhs.ap.ssid), reinterpret_cast(rhs.ap.ssid)) != 0) { + return false; + } + if(strcmp(reinterpret_cast(lhs.ap.password), reinterpret_cast(rhs.ap.password)) != 0) { + return false; + } + if(lhs.ap.channel != rhs.ap.channel) { + return false; + } + if(lhs.ap.ssid_hidden != rhs.ap.ssid_hidden) { + return false; + } + if(lhs.ap.max_connection != rhs.ap.max_connection) { + return false; + } + return true; +} + +// ----------------------------------------------------------------------------------------------------------------------- +// ----------------------------------------------------- AP function ----------------------------------------------------- +// ----------------------------------------------------------------------------------------------------------------------- + + +/** + * Set up an access point + * @param ssid Pointer to the SSID (max 63 char). + * @param passphrase (for WPA2 min 8 char, for open use NULL) + * @param channel WiFi channel number, 1 - 13. + * @param ssid_hidden Network cloaking (0 = broadcast SSID, 1 = hide SSID) + * @param max_connection Max simultaneous connected clients, 1 - 4. +*/ +bool WiFiAPClass::softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection) +{ + + if(!WiFi.enableAP(true)) { + // enable AP failed + log_e("enable AP first!"); + return false; + } + + if(!ssid || *ssid == 0) { + // fail SSID missing + log_e("SSID missing!"); + return false; + } + + if(passphrase && (strlen(passphrase) > 0 && strlen(passphrase) < 8)) { + // fail passphrase too short + log_e("passphrase too short!"); + return false; + } + + esp_wifi_start(); + + wifi_config_t conf; + strlcpy(reinterpret_cast(conf.ap.ssid), ssid, sizeof(conf.ap.ssid)); + conf.ap.channel = channel; + conf.ap.ssid_len = strlen(reinterpret_cast(conf.ap.ssid)); + conf.ap.ssid_hidden = ssid_hidden; + conf.ap.max_connection = max_connection; + conf.ap.beacon_interval = 100; + + if(!passphrase || strlen(passphrase) == 0) { + conf.ap.authmode = WIFI_AUTH_OPEN; + *conf.ap.password = 0; + } else { + conf.ap.authmode = WIFI_AUTH_WPA2_PSK; + strlcpy(reinterpret_cast(conf.ap.password), passphrase, sizeof(conf.ap.password)); + } + + wifi_config_t conf_current; + esp_wifi_get_config(WIFI_IF_AP, &conf_current); + if(!softap_config_equal(conf, conf_current) && esp_wifi_set_config(WIFI_IF_AP, &conf) != ESP_OK) { + return false; + } + + return true; +} + + +/** + * Configure access point + * @param local_ip access point IP + * @param gateway gateway IP + * @param subnet subnet mask + */ +bool WiFiAPClass::softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet) +{ + + if(!WiFi.enableAP(true)) { + // enable AP failed + return false; + } + + esp_wifi_start(); + + tcpip_adapter_ip_info_t info; + info.ip.addr = static_cast(local_ip); + info.gw.addr = static_cast(gateway); + info.netmask.addr = static_cast(subnet); + tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP); + if(tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_AP, &info) == ESP_OK) { + dhcps_lease_t lease; + lease.enable = true; + lease.start_ip.addr = static_cast(local_ip) + (1 << 24); + lease.end_ip.addr = static_cast(local_ip) + (11 << 24); + + tcpip_adapter_dhcps_option( + (tcpip_adapter_option_mode_t)TCPIP_ADAPTER_OP_SET, + (tcpip_adapter_option_id_t)REQUESTED_IP_ADDRESS, + (void*)&lease, sizeof(dhcps_lease_t) + ); + + return tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP) == ESP_OK; + } + return false; +} + + + +/** + * Disconnect from the network (close AP) + * @param wifioff disable mode? + * @return one value of wl_status_t enum + */ +bool WiFiAPClass::softAPdisconnect(bool wifioff) +{ + bool ret; + wifi_config_t conf; + + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return ESP_ERR_INVALID_STATE; + } + + *conf.ap.ssid = 0; + *conf.ap.password = 0; + conf.ap.authmode = WIFI_AUTH_OPEN; // auth must be open if pass=0 + ret = esp_wifi_set_config(WIFI_IF_AP, &conf) == ESP_OK; + + if(wifioff) { + ret = WiFi.enableAP(false) == ESP_OK; + } + + return ret; +} + + +/** + * Get the count of the Station / client that are connected to the softAP interface + * @return Stations count + */ +uint8_t WiFiAPClass::softAPgetStationNum() +{ + wifi_sta_list_t clients; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return 0; + } + if(esp_wifi_ap_get_sta_list(&clients) == ESP_OK) { + return clients.num; + } + return 0; +} + +/** + * Get the softAP interface IP address. + * @return IPAddress softAP IP + */ +IPAddress WiFiAPClass::softAPIP() +{ + tcpip_adapter_ip_info_t ip; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip); + return IPAddress(ip.ip.addr); +} + +/** + * Get the softAP broadcast IP address. + * @return IPAddress softAP broadcastIP + */ +IPAddress WiFiAPClass::softAPBroadcastIP() +{ + tcpip_adapter_ip_info_t ip; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip); + return WiFiGenericClass::calculateBroadcast(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr)); +} + +/** + * Get the softAP network ID. + * @return IPAddress softAP networkID + */ +IPAddress WiFiAPClass::softAPNetworkID() +{ + tcpip_adapter_ip_info_t ip; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip); + return WiFiGenericClass::calculateNetworkID(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr)); +} + +/** + * Get the softAP subnet CIDR. + * @return uint8_t softAP subnetCIDR + */ +uint8_t WiFiAPClass::softAPSubnetCIDR() +{ + tcpip_adapter_ip_info_t ip; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return (uint8_t)0; + } + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip); + return WiFiGenericClass::calculateSubnetCIDR(IPAddress(ip.netmask.addr)); +} + +/** + * Get the softAP interface MAC address. + * @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH + * @return pointer to uint8_t* + */ +uint8_t* WiFiAPClass::softAPmacAddress(uint8_t* mac) +{ + if(WiFiGenericClass::getMode() != WIFI_MODE_NULL){ + esp_wifi_get_mac(WIFI_IF_AP, mac); + } + return mac; +} + +/** + * Get the softAP interface MAC address. + * @return String mac + */ +String WiFiAPClass::softAPmacAddress(void) +{ + uint8_t mac[6]; + char macStr[18] = { 0 }; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + esp_wifi_get_mac(WIFI_IF_AP, mac); + + sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + return String(macStr); +} + +/** + * Get the softAP interface Host name. + * @return char array hostname + */ +const char * WiFiAPClass::softAPgetHostname() +{ + const char * hostname = NULL; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return hostname; + } + if(tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_AP, &hostname)) { + return hostname; + } + return hostname; +} + +/** + * Set the softAP interface Host name. + * @param hostname pointer to const string + * @return true on success + */ +bool WiFiAPClass::softAPsetHostname(const char * hostname) +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return false; + } + return tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_AP, hostname) == ESP_OK; +} + +/** + * Enable IPv6 on the softAP interface. + * @return true on success + */ +bool WiFiAPClass::softAPenableIpV6() +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return false; + } + return tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_AP) == ESP_OK; +} + +/** + * Get the softAP interface IPv6 address. + * @return IPv6Address softAP IPv6 + */ +IPv6Address WiFiAPClass::softAPIPv6() +{ + static ip6_addr_t addr; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPv6Address(); + } + if(tcpip_adapter_get_ip6_linklocal(TCPIP_ADAPTER_IF_AP, &addr)) { + return IPv6Address(); + } + return IPv6Address(addr.addr); +} diff --git a/libraries/WiFi/src/WiFiAP.h b/libraries/WiFi/src/WiFiAP.h index 9a29621e9ea..f1533cc3611 100644 --- a/libraries/WiFi/src/WiFiAP.h +++ b/libraries/WiFi/src/WiFiAP.h @@ -1,61 +1,65 @@ -/* - ESP8266WiFiAP.h - esp8266 Wifi support. - Based on WiFi.h from Arduino WiFi shield library. - Copyright (c) 2011-2014 Arduino. All right reserved. - Modified by Ivan Grokhotkov, December 2014 - Reworked by Markus Sattler, December 2015 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef ESP32WIFIAP_H_ -#define ESP32WIFIAP_H_ - - -#include "WiFiType.h" -#include "WiFiGeneric.h" - - -class WiFiAPClass -{ - - // ---------------------------------------------------------------------------------------------- - // ----------------------------------------- AP function ---------------------------------------- - // ---------------------------------------------------------------------------------------------- - -public: - - bool softAP(const char* ssid, const char* passphrase = NULL, int channel = 1, int ssid_hidden = 0, int max_connection = 4); - bool softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet); - bool softAPdisconnect(bool wifioff = false); - - uint8_t softAPgetStationNum(); - - IPAddress softAPIP(); - - bool softAPenableIpV6(); - IPv6Address softAPIPv6(); - - const char * softAPgetHostname(); - bool softAPsetHostname(const char * hostname); - - uint8_t* softAPmacAddress(uint8_t* mac); - String softAPmacAddress(void); - -protected: - -}; - -#endif /* ESP32WIFIAP_H_*/ +/* + ESP8266WiFiAP.h - esp8266 Wifi support. + Based on WiFi.h from Arduino WiFi shield library. + Copyright (c) 2011-2014 Arduino. All right reserved. + Modified by Ivan Grokhotkov, December 2014 + Reworked by Markus Sattler, December 2015 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef ESP32WIFIAP_H_ +#define ESP32WIFIAP_H_ + + +#include "WiFiType.h" +#include "WiFiGeneric.h" + + +class WiFiAPClass +{ + + // ---------------------------------------------------------------------------------------------- + // ----------------------------------------- AP function ---------------------------------------- + // ---------------------------------------------------------------------------------------------- + +public: + + bool softAP(const char* ssid, const char* passphrase = NULL, int channel = 1, int ssid_hidden = 0, int max_connection = 4); + bool softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet); + bool softAPdisconnect(bool wifioff = false); + + uint8_t softAPgetStationNum(); + + IPAddress softAPIP(); + + IPAddress softAPBroadcastIP(); + IPAddress softAPNetworkID(); + uint8_t softAPSubnetCIDR(); + + bool softAPenableIpV6(); + IPv6Address softAPIPv6(); + + const char * softAPgetHostname(); + bool softAPsetHostname(const char * hostname); + + uint8_t* softAPmacAddress(uint8_t* mac); + String softAPmacAddress(void); + +protected: + +}; + +#endif /* ESP32WIFIAP_H_*/ diff --git a/libraries/WiFi/src/WiFiClient.cpp b/libraries/WiFi/src/WiFiClient.cpp index 5b8c0fb65a3..616b5de90f2 100644 --- a/libraries/WiFi/src/WiFiClient.cpp +++ b/libraries/WiFi/src/WiFiClient.cpp @@ -18,6 +18,7 @@ */ #include "WiFiClient.h" +#include "WiFi.h" #include #include #include @@ -30,6 +31,125 @@ #undef write #undef read +class WiFiClientRxBuffer { +private: + size_t _size; + uint8_t *_buffer; + size_t _pos; + size_t _fill; + int _fd; + bool _failed; + + size_t r_available() + { + if(_fd < 0){ + return 0; + } + int count; + int res = lwip_ioctl_r(_fd, FIONREAD, &count); + if(res < 0) { + _failed = true; + return 0; + } + return count; + } + + size_t fillBuffer() + { + if(!_buffer){ + _buffer = (uint8_t *)malloc(_size); + if(!_buffer) { + log_e("Not enough memory to allocate buffer"); + _failed = true; + return 0; + } + } + if(_fill && _pos == _fill){ + _fill = 0; + _pos = 0; + } + if(!_buffer || _size <= _fill || !r_available()) { + return 0; + } + int res = recv(_fd, _buffer + _fill, _size - _fill, MSG_DONTWAIT); + if(res < 0) { + if(errno != EWOULDBLOCK) { + _failed = true; + } + return 0; + } + _fill += res; + return res; + } + +public: + WiFiClientRxBuffer(int fd, size_t size=1436) + :_size(size) + ,_buffer(NULL) + ,_pos(0) + ,_fill(0) + ,_fd(fd) + ,_failed(false) + { + //_buffer = (uint8_t *)malloc(_size); + } + + ~WiFiClientRxBuffer() + { + free(_buffer); + } + + bool failed(){ + return _failed; + } + + int read(uint8_t * dst, size_t len){ + if(!dst || !len || (_pos == _fill && !fillBuffer())){ + return -1; + } + size_t a = _fill - _pos; + if(len <= a || ((len - a) <= (_size - _fill) && fillBuffer() >= (len - a))){ + if(len == 1){ + *dst = _buffer[_pos]; + } else { + memcpy(dst, _buffer + _pos, len); + } + _pos += len; + return len; + } + size_t left = len; + size_t toRead = a; + uint8_t * buf = dst; + memcpy(buf, _buffer + _pos, toRead); + _pos += toRead; + left -= toRead; + buf += toRead; + while(left){ + if(!fillBuffer()){ + return len - left; + } + a = _fill - _pos; + toRead = (a > left)?left:a; + memcpy(buf, _buffer + _pos, toRead); + _pos += toRead; + left -= toRead; + buf += toRead; + } + return len; + } + + int peek(){ + if(_pos == _fill && !fillBuffer()){ + return -1; + } + return _buffer[_pos]; + } + + size_t available(){ + return _fill - _pos + r_available(); + } +}; + class WiFiClientSocketHandle { private: int sockfd; @@ -57,6 +177,7 @@ WiFiClient::WiFiClient():_connected(false),next(NULL) WiFiClient::WiFiClient(int fd):_connected(true),next(NULL) { clientSocketHandle.reset(new WiFiClientSocketHandle(fd)); + _rxBuffer.reset(new WiFiClientRxBuffer(fd)); } WiFiClient::~WiFiClient() @@ -68,6 +189,7 @@ WiFiClient & WiFiClient::operator=(const WiFiClient &other) { stop(); clientSocketHandle = other.clientSocketHandle; + _rxBuffer = other._rxBuffer; _connected = other._connected; return *this; } @@ -75,16 +197,22 @@ WiFiClient & WiFiClient::operator=(const WiFiClient &other) void WiFiClient::stop() { clientSocketHandle = NULL; + _rxBuffer = NULL; _connected = false; } int WiFiClient::connect(IPAddress ip, uint16_t port) +{ + return connect(ip,port,-1); +} +int WiFiClient::connect(IPAddress ip, uint16_t port, int32_t timeout) { int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { log_e("socket: %d", errno); return 0; } + fcntl( sockfd, F_SETFL, fcntl( sockfd, F_GETFL, 0 ) | O_NONBLOCK ); uint32_t ip_addr = ip; struct sockaddr_in serveraddr; @@ -92,26 +220,65 @@ int WiFiClient::connect(IPAddress ip, uint16_t port) serveraddr.sin_family = AF_INET; bcopy((const void *)(&ip_addr), (void *)&serveraddr.sin_addr.s_addr, 4); serveraddr.sin_port = htons(port); + fd_set fdset; + struct timeval tv; + FD_ZERO(&fdset); + FD_SET(sockfd, &fdset); + tv.tv_sec = 0; + tv.tv_usec = timeout * 1000; + int res = lwip_connect_r(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); + if (res < 0 && errno != EINPROGRESS) { + log_e("connect on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno)); + close(sockfd); + return 0; + } + + res = select(sockfd + 1, nullptr, &fdset, nullptr, timeout<0 ? nullptr : &tv); if (res < 0) { - log_e("lwip_connect_r: %d", errno); + log_e("select on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno)); close(sockfd); return 0; + } else if (res == 0) { + log_i("select returned due to timeout %d ms for fd %d", timeout, sockfd); + close(sockfd); + return 0; + } else { + int sockerr; + socklen_t len = (socklen_t)sizeof(int); + res = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &sockerr, &len); + + if (res < 0) { + log_e("getsockopt on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno)); + close(sockfd); + return 0; + } + + if (sockerr != 0) { + log_e("socket error on fd %d, errno: %d, \"%s\"", sockfd, sockerr, strerror(sockerr)); + close(sockfd); + return 0; + } } + + fcntl( sockfd, F_SETFL, fcntl( sockfd, F_GETFL, 0 ) & (~O_NONBLOCK) ); clientSocketHandle.reset(new WiFiClientSocketHandle(sockfd)); + _rxBuffer.reset(new WiFiClientRxBuffer(sockfd)); _connected = true; return 1; } int WiFiClient::connect(const char *host, uint16_t port) { - struct hostent *server; - server = gethostbyname(host); - if (server == NULL) { + return connect(host,port,-1); +} +int WiFiClient::connect(const char *host, uint16_t port, int32_t timeout) +{ + IPAddress srv((uint32_t)0); + if(!WiFiGenericClass::hostByName(host, srv)){ return 0; } - IPAddress srv((const uint8_t *)(server->h_addr)); - return connect(srv, port); + return connect(srv, port, timeout); } int WiFiClient::setSocketOption(int option, char* value, size_t len) @@ -125,6 +292,7 @@ int WiFiClient::setSocketOption(int option, char* value, size_t len) int WiFiClient::setTimeout(uint32_t seconds) { + Client::setTimeout(seconds * 1000); struct timeval tv; tv.tv_sec = seconds; tv.tv_usec = 0; @@ -138,7 +306,7 @@ int WiFiClient::setOption(int option, int *value) { int res = setsockopt(fd(), IPPROTO_TCP, option, (char *) value, sizeof(int)); if(res < 0) { - log_e("%d", errno); + log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno)); } return res; } @@ -148,7 +316,7 @@ int WiFiClient::getOption(int option, int *value) size_t size = sizeof(int); int res = getsockopt(fd(), IPPROTO_TCP, option, (char *)value, &size); if(res < 0) { - log_e("%d", errno); + log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno)); } return res; } @@ -217,10 +385,11 @@ size_t WiFiClient::write(const uint8_t *buf, size_t size) } else { buf += res; bytesRemaining -= res; + retry = WIFI_CLIENT_MAX_WRITE_RETRY; } } else if(res < 0) { - log_e("%d", errno); + log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno)); if(errno != EAGAIN) { //if resource was busy, can try again, otherwise give up stop(); @@ -241,14 +410,30 @@ size_t WiFiClient::write_P(PGM_P buf, size_t size) return write(buf, size); } -int WiFiClient::read(uint8_t *buf, size_t size) +size_t WiFiClient::write(Stream &stream) { - if(!available()) { - return -1; + uint8_t * buf = (uint8_t *)malloc(1360); + if(!buf){ + return 0; + } + size_t toRead = 0, toWrite = 0, written = 0; + size_t available = stream.available(); + while(available){ + toRead = (available > 1360)?1360:available; + toWrite = stream.readBytes(buf, toRead); + written += write(buf, toWrite); + available = stream.available(); } - int res = recv(fd(), buf, size, MSG_DONTWAIT); - if(res < 0 && errno != EWOULDBLOCK) { - log_e("%d", errno); + free(buf); + return written; +} + +int WiFiClient::read(uint8_t *buf, size_t size) +{ + int res = -1; + res = _rxBuffer->read(buf, size); + if(_rxBuffer->failed()) { + log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno)); stop(); } return res; @@ -256,31 +441,26 @@ int WiFiClient::read(uint8_t *buf, size_t size) int WiFiClient::peek() { - if(!available()) { - return -1; - } - uint8_t data = 0; - int res = recv(fd(), &data, 1, MSG_PEEK); - if(res < 0 && errno != EWOULDBLOCK) { - log_e("%d", errno); + int res = _rxBuffer->peek(); + if(_rxBuffer->failed()) { + log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno)); stop(); } - return data; + return res; } int WiFiClient::available() { - if(!_connected) { + if(!_rxBuffer) + { return 0; } - int count; - int res = lwip_ioctl_r(fd(), FIONREAD, &count); - if(res < 0) { - log_e("%d", errno); + int res = _rxBuffer->available(); + if(_rxBuffer->failed()) { + log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno)); stop(); - return 0; } - return count; + return res; } // Though flushing means to send all pending data, @@ -299,7 +479,7 @@ void WiFiClient::flush() { toRead = (a>WIFI_CLIENT_FLUSH_BUFFER_SIZE)?WIFI_CLIENT_FLUSH_BUFFER_SIZE:a; res = recv(fd(), buf, toRead, MSG_DONTWAIT); if(res < 0) { - log_e("%d", errno); + log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno)); stop(); break; } @@ -313,23 +493,25 @@ uint8_t WiFiClient::connected() if (_connected) { uint8_t dummy; int res = recv(fd(), &dummy, 0, MSG_DONTWAIT); - if (res <= 0) { - switch (errno) { - case ENOTCONN: - case EPIPE: - case ECONNRESET: - case ECONNREFUSED: - case ECONNABORTED: - _connected = false; - break; - default: - _connected = true; - break; - } - } - else { - // Should never happen since requested 0 bytes - _connected = true; + // avoid unused var warning by gcc + (void)res; + switch (errno) { + case EWOULDBLOCK: + case ENOENT: //caused by vfs + _connected = true; + break; + case ENOTCONN: + case EPIPE: + case ECONNRESET: + case ECONNREFUSED: + case ECONNABORTED: + _connected = false; + log_d("Disconnected: RES: %d, ERR: %d", res, errno); + break; + default: + log_i("Unexpected: RES: %d, ERR: %d", res, errno); + _connected = true; + break; } } return _connected; diff --git a/libraries/WiFi/src/WiFiClient.h b/libraries/WiFi/src/WiFiClient.h index 595c8bf57a1..4915cfd5203 100644 --- a/libraries/WiFi/src/WiFiClient.h +++ b/libraries/WiFi/src/WiFiClient.h @@ -23,16 +23,24 @@ #include "Arduino.h" #include "Client.h" -#undef min -#undef max #include class WiFiClientSocketHandle; +class WiFiClientRxBuffer; -class WiFiClient : public Client +class ESPLwIPClient : public Client +{ +public: + virtual int connect(IPAddress ip, uint16_t port, int32_t timeout) = 0; + virtual int connect(const char *host, uint16_t port, int32_t timeout) = 0; + virtual int setTimeout(uint32_t seconds) = 0; +}; + +class WiFiClient : public ESPLwIPClient { protected: std::shared_ptr clientSocketHandle; + std::shared_ptr _rxBuffer; bool _connected; public: @@ -41,10 +49,13 @@ class WiFiClient : public Client WiFiClient(int fd); ~WiFiClient(); int connect(IPAddress ip, uint16_t port); + int connect(IPAddress ip, uint16_t port, int32_t timeout); int connect(const char *host, uint16_t port); + int connect(const char *host, uint16_t port, int32_t timeout); size_t write(uint8_t data); size_t write(const uint8_t *buf, size_t size); size_t write_P(PGM_P buf, size_t size); + size_t write(Stream &stream); int available(); int read(); int read(uint8_t *buf, size_t size); diff --git a/libraries/WiFi/src/WiFiGeneric.cpp b/libraries/WiFi/src/WiFiGeneric.cpp index a6f7316b5d3..e56292127c8 100644 --- a/libraries/WiFi/src/WiFiGeneric.cpp +++ b/libraries/WiFi/src/WiFiGeneric.cpp @@ -1,497 +1,724 @@ -/* - ESP8266WiFiGeneric.cpp - WiFi library for esp8266 - - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Reworked on 28 Dec 2015 by Markus Sattler - - */ - -#include "WiFi.h" -#include "WiFiGeneric.h" - -extern "C" { -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include "lwip/ip_addr.h" -#include "lwip/opt.h" -#include "lwip/err.h" -#include "lwip/dns.h" -#include "esp_ipc.h" - - -} //extern "C" - -#include "esp32-hal-log.h" - -#undef min -#undef max -#include - -#include "sdkconfig.h" - -#if CONFIG_FREERTOS_UNICORE -#define ARDUINO_RUNNING_CORE 0 -#else -#define ARDUINO_RUNNING_CORE 1 -#endif - -static xQueueHandle _network_event_queue; -static TaskHandle_t _network_event_task_handle = NULL; - -static void _network_event_task(void * arg){ - system_event_t *event = NULL; - for (;;) { - if(xQueueReceive(_network_event_queue, &event, portMAX_DELAY) == pdTRUE){ - WiFiGenericClass::_eventCallback(arg, event); - } - } - vTaskDelete(NULL); - _network_event_task_handle = NULL; -} - -static esp_err_t _network_event_cb(void *arg, system_event_t *event){ - if (xQueueSend(_network_event_queue, &event, portMAX_DELAY) != pdPASS) { - log_w("Network Event Queue Send Failed!"); - return ESP_FAIL; - } - return ESP_OK; -} - -static void _start_network_event_task(){ - if(!_network_event_queue){ - _network_event_queue = xQueueCreate(32, sizeof(system_event_t *)); - if(!_network_event_queue){ - log_e("Network Event Queue Create Failed!"); - return; - } - } - if(!_network_event_task_handle){ - xTaskCreatePinnedToCore(_network_event_task, "network_event", 4096, NULL, 2, &_network_event_task_handle, ARDUINO_RUNNING_CORE); - if(!_network_event_task_handle){ - log_e("Network Event Task Start Failed!"); - return; - } - } - esp_event_loop_init(&_network_event_cb, NULL); -} - -void tcpipInit(){ - static bool initialized = false; - if(!initialized){ - initialized = true; - _start_network_event_task(); - tcpip_adapter_init(); - } -} - -static bool wifiLowLevelInit(){ - static bool lowLevelInitDone = false; - if(!lowLevelInitDone){ - tcpipInit(); - wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); - esp_err_t err = esp_wifi_init(&cfg); - if(err){ - log_e("esp_wifi_init %d", err); - return false; - } - esp_wifi_set_storage(WIFI_STORAGE_FLASH); - esp_wifi_set_mode(WIFI_MODE_NULL); - lowLevelInitDone = true; - } - return true; -} - -static bool wifiLowLevelDeinit(){ - //deinit not working yet! - //esp_wifi_deinit(); - return true; -} - -static bool _esp_wifi_started = false; - -static bool espWiFiStart(){ - if(_esp_wifi_started){ - return true; - } - if(!wifiLowLevelInit()){ - return false; - } - esp_err_t err = esp_wifi_start(); - if (err != ESP_OK) { - log_e("esp_wifi_start %d", err); - wifiLowLevelDeinit(); - return false; - } - _esp_wifi_started = true; - return true; -} - -static bool espWiFiStop(){ - esp_err_t err; - if(!_esp_wifi_started){ - return true; - } - err = esp_wifi_stop(); - if(err){ - log_e("Could not stop WiFi! %u", err); - return false; - } - _esp_wifi_started = false; - return wifiLowLevelDeinit(); -} - -// ----------------------------------------------------------------------------------------------------------------------- -// ------------------------------------------------- Generic WiFi function ----------------------------------------------- -// ----------------------------------------------------------------------------------------------------------------------- - -typedef struct { - WiFiEventCb cb; - WiFiEventFullCb fcb; - WiFiEventSysCb scb; - system_event_id_t event; -} WiFiEventCbList_t; - -// arduino dont like std::vectors move static here -static std::vector cbEventList; - -bool WiFiGenericClass::_persistent = true; -wifi_mode_t WiFiGenericClass::_forceSleepLastMode = WIFI_MODE_NULL; - -WiFiGenericClass::WiFiGenericClass() -{ - -} - -/** - * set callback function - * @param cbEvent WiFiEventCb - * @param event optional filter (WIFI_EVENT_MAX is all events) - */ -void WiFiGenericClass::onEvent(WiFiEventCb cbEvent, system_event_id_t event) -{ - if(!cbEvent) { - return; - } - WiFiEventCbList_t newEventHandler; - newEventHandler.cb = cbEvent; - newEventHandler.fcb = NULL; - newEventHandler.scb = NULL; - newEventHandler.event = event; - cbEventList.push_back(newEventHandler); -} - -void WiFiGenericClass::onEvent(WiFiEventFullCb cbEvent, system_event_id_t event) -{ - if(!cbEvent) { - return; - } - WiFiEventCbList_t newEventHandler; - newEventHandler.cb = NULL; - newEventHandler.fcb = cbEvent; - newEventHandler.scb = NULL; - newEventHandler.event = event; - cbEventList.push_back(newEventHandler); -} - -void WiFiGenericClass::onEvent(WiFiEventSysCb cbEvent, system_event_id_t event) -{ - if(!cbEvent) { - return; - } - WiFiEventCbList_t newEventHandler; - newEventHandler.cb = NULL; - newEventHandler.fcb = NULL; - newEventHandler.scb = cbEvent; - newEventHandler.event = event; - cbEventList.push_back(newEventHandler); -} - -/** - * removes a callback form event handler - * @param cbEvent WiFiEventCb - * @param event optional filter (WIFI_EVENT_MAX is all events) - */ -void WiFiGenericClass::removeEvent(WiFiEventCb cbEvent, system_event_id_t event) -{ - if(!cbEvent) { - return; - } - - for(uint32_t i = 0; i < cbEventList.size(); i++) { - WiFiEventCbList_t entry = cbEventList[i]; - if(entry.cb == cbEvent && entry.event == event) { - cbEventList.erase(cbEventList.begin() + i); - } - } -} - -void WiFiGenericClass::removeEvent(WiFiEventFullCb cbEvent, system_event_id_t event) -{ - if(!cbEvent) { - return; - } - - for(uint32_t i = 0; i < cbEventList.size(); i++) { - WiFiEventCbList_t entry = cbEventList[i]; - if(entry.fcb == cbEvent && entry.event == event) { - cbEventList.erase(cbEventList.begin() + i); - } - } -} - -void WiFiGenericClass::removeEvent(WiFiEventSysCb cbEvent, system_event_id_t event) -{ - if(!cbEvent) { - return; - } - - for(uint32_t i = 0; i < cbEventList.size(); i++) { - WiFiEventCbList_t entry = cbEventList[i]; - if(entry.scb == cbEvent && entry.event == event) { - cbEventList.erase(cbEventList.begin() + i); - } - } -} - -/** - * callback for WiFi events - * @param arg - */ -#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG -const char * system_event_names[] = { "WIFI_READY", "SCAN_DONE", "STA_START", "STA_STOP", "STA_CONNECTED", "STA_DISCONNECTED", "STA_AUTHMODE_CHANGE", "STA_GOT_IP", "STA_LOST_IP", "STA_WPS_ER_SUCCESS", "STA_WPS_ER_FAILED", "STA_WPS_ER_TIMEOUT", "STA_WPS_ER_PIN", "AP_START", "AP_STOP", "AP_STACONNECTED", "AP_STADISCONNECTED", "AP_PROBEREQRECVED", "GOT_IP6", "ETH_START", "ETH_STOP", "ETH_CONNECTED", "ETH_DISCONNECTED", "ETH_GOT_IP", "MAX"}; -#endif -#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN -const char * system_event_reasons[] = { "UNSPECIFIED", "AUTH_EXPIRE", "AUTH_LEAVE", "ASSOC_EXPIRE", "ASSOC_TOOMANY", "NOT_AUTHED", "NOT_ASSOCED", "ASSOC_LEAVE", "ASSOC_NOT_AUTHED", "DISASSOC_PWRCAP_BAD", "DISASSOC_SUPCHAN_BAD", "IE_INVALID", "MIC_FAILURE", "4WAY_HANDSHAKE_TIMEOUT", "GROUP_KEY_UPDATE_TIMEOUT", "IE_IN_4WAY_DIFFERS", "GROUP_CIPHER_INVALID", "PAIRWISE_CIPHER_INVALID", "AKMP_INVALID", "UNSUPP_RSN_IE_VERSION", "INVALID_RSN_IE_CAP", "802_1X_AUTH_FAILED", "CIPHER_SUITE_REJECTED", "BEACON_TIMEOUT", "NO_AP_FOUND", "AUTH_FAIL", "ASSOC_FAIL", "HANDSHAKE_TIMEOUT" }; -#define reason2str(r) ((r>176)?system_event_reasons[r-177]:system_event_reasons[r-1]) -#endif -esp_err_t WiFiGenericClass::_eventCallback(void *arg, system_event_t *event) -{ - log_d("Event: %d - %s", event->event_id, system_event_names[event->event_id]); - if(event->event_id == SYSTEM_EVENT_SCAN_DONE) { - WiFiScanClass::_scanDone(); - } else if(event->event_id == SYSTEM_EVENT_STA_DISCONNECTED) { - uint8_t reason = event->event_info.disconnected.reason; - log_w("Reason: %u - %s", reason, reason2str(reason)); - if(reason == WIFI_REASON_NO_AP_FOUND) { - WiFiSTAClass::_setStatus(WL_NO_SSID_AVAIL); - } else if(reason == WIFI_REASON_AUTH_FAIL || reason == WIFI_REASON_ASSOC_FAIL) { - WiFiSTAClass::_setStatus(WL_CONNECT_FAILED); - } else if(reason == WIFI_REASON_BEACON_TIMEOUT || reason == WIFI_REASON_HANDSHAKE_TIMEOUT) { - WiFiSTAClass::_setStatus(WL_CONNECTION_LOST); - } else if(reason == WIFI_REASON_AUTH_EXPIRE) { - if(WiFi.getAutoReconnect()){ - WiFi.begin(); - } - } else { - WiFiSTAClass::_setStatus(WL_DISCONNECTED); - } - } else if(event->event_id == SYSTEM_EVENT_STA_START) { - WiFiSTAClass::_setStatus(WL_DISCONNECTED); - } else if(event->event_id == SYSTEM_EVENT_STA_STOP) { - WiFiSTAClass::_setStatus(WL_NO_SHIELD); - } else if(event->event_id == SYSTEM_EVENT_STA_CONNECTED) { - WiFiSTAClass::_setStatus(WL_IDLE_STATUS); - } else if(event->event_id == SYSTEM_EVENT_STA_GOT_IP) { -//#1081 https://github.com/espressif/arduino-esp32/issues/1081 -// if(WiFiSTAClass::status() == WL_IDLE_STATUS) - { - WiFiSTAClass::_setStatus(WL_CONNECTED); - } - } - - for(uint32_t i = 0; i < cbEventList.size(); i++) { - WiFiEventCbList_t entry = cbEventList[i]; - if(entry.cb || entry.fcb || entry.scb) { - if(entry.event == (system_event_id_t) event->event_id || entry.event == SYSTEM_EVENT_MAX) { - if(entry.cb){ - entry.cb((system_event_id_t) event->event_id); - } else if(entry.fcb){ - entry.fcb((system_event_id_t) event->event_id, (system_event_info_t) event->event_info); - } else { - entry.scb(event); - } - } - } - } - return ESP_OK; -} - -/** - * Return the current channel associated with the network - * @return channel (1-13) - */ -int32_t WiFiGenericClass::channel(void) -{ - uint8_t primaryChan; - wifi_second_chan_t secondChan; - esp_wifi_get_channel(&primaryChan, &secondChan); - return primaryChan; -} - - -/** - * store WiFi config in SDK flash area - * @param persistent - */ -void WiFiGenericClass::persistent(bool persistent) -{ - _persistent = persistent; -} - - -/** - * set new mode - * @param m WiFiMode_t - */ -bool WiFiGenericClass::mode(wifi_mode_t m) -{ - wifi_mode_t cm = getMode(); - if(cm == WIFI_MODE_MAX){ - return false; - } - if(cm == m) { - return true; - } - esp_err_t err; - err = esp_wifi_set_mode(m); - if(err){ - log_e("Could not set mode! %u", err); - return false; - } - if(m){ - return espWiFiStart(); - } - return espWiFiStop(); -} - -/** - * get WiFi mode - * @return WiFiMode - */ -wifi_mode_t WiFiGenericClass::getMode() -{ - if(!wifiLowLevelInit()){ - return WIFI_MODE_MAX; - } - uint8_t mode; - esp_wifi_get_mode((wifi_mode_t*)&mode); - return (wifi_mode_t)mode; -} - -/** - * control STA mode - * @param enable bool - * @return ok - */ -bool WiFiGenericClass::enableSTA(bool enable) -{ - - wifi_mode_t currentMode = getMode(); - bool isEnabled = ((currentMode & WIFI_MODE_STA) != 0); - - if(isEnabled != enable) { - if(enable) { - return mode((wifi_mode_t)(currentMode | WIFI_MODE_STA)); - } else { - return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_STA))); - } - } else { - return true; - } -} - -/** - * control AP mode - * @param enable bool - * @return ok - */ -bool WiFiGenericClass::enableAP(bool enable) -{ - - wifi_mode_t currentMode = getMode(); - bool isEnabled = ((currentMode & WIFI_MODE_AP) != 0); - - if(isEnabled != enable) { - if(enable) { - return mode((wifi_mode_t)(currentMode | WIFI_MODE_AP)); - } else { - return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_AP))); - } - } else { - return true; - } -} - - -// ----------------------------------------------------------------------------------------------------------------------- -// ------------------------------------------------ Generic Network function --------------------------------------------- -// ----------------------------------------------------------------------------------------------------------------------- - -static bool _dns_busy = false; - -/** - * DNS callback - * @param name - * @param ipaddr - * @param callback_arg - */ -static void wifi_dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg) -{ - if(ipaddr) { - (*reinterpret_cast(callback_arg)) = ipaddr->u_addr.ip4.addr; - } - _dns_busy = false; -} - -/** - * Resolve the given hostname to an IP address. - * @param aHostname Name to be resolved - * @param aResult IPAddress structure to store the returned IP address - * @return 1 if aIPAddrString was successfully converted to an IP address, - * else error code - */ -int WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult) -{ - ip_addr_t addr; - aResult = static_cast(0); - - _dns_busy = true; - err_t err = dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult); - if(err == ERR_OK && addr.u_addr.ip4.addr) { - aResult = addr.u_addr.ip4.addr; - _dns_busy = false; - } else if(err == ERR_INPROGRESS) { - while(_dns_busy){ - delay(1); - } - } else { - _dns_busy = false; - return 0; - } - return 1; -} - +/* + ESP8266WiFiGeneric.cpp - WiFi library for esp8266 + + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Reworked on 28 Dec 2015 by Markus Sattler + + */ + +#include "WiFi.h" +#include "WiFiGeneric.h" + +extern "C" { +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include "lwip/ip_addr.h" +#include "lwip/opt.h" +#include "lwip/err.h" +#include "lwip/dns.h" +#include "esp_ipc.h" + + +} //extern "C" + +#include "esp32-hal-log.h" +#include +#include "sdkconfig.h" + +static xQueueHandle _network_event_queue; +static TaskHandle_t _network_event_task_handle = NULL; +static EventGroupHandle_t _network_event_group = NULL; + +static void _network_event_task(void * arg){ + system_event_t event; + for (;;) { + if(xQueueReceive(_network_event_queue, &event, portMAX_DELAY) == pdTRUE){ + WiFiGenericClass::_eventCallback(arg, &event); + } + } + vTaskDelete(NULL); + _network_event_task_handle = NULL; +} + +static esp_err_t _network_event_cb(void *arg, system_event_t *event){ + if (xQueueSend(_network_event_queue, event, portMAX_DELAY) != pdPASS) { + log_w("Network Event Queue Send Failed!"); + return ESP_FAIL; + } + return ESP_OK; +} + +static bool _start_network_event_task(){ + if(!_network_event_group){ + _network_event_group = xEventGroupCreate(); + if(!_network_event_group){ + log_e("Network Event Group Create Failed!"); + return false; + } + xEventGroupSetBits(_network_event_group, WIFI_DNS_IDLE_BIT); + } + if(!_network_event_queue){ + _network_event_queue = xQueueCreate(32, sizeof(system_event_t)); + if(!_network_event_queue){ + log_e("Network Event Queue Create Failed!"); + return false; + } + } + if(!_network_event_task_handle){ + xTaskCreateUniversal(_network_event_task, "network_event", 4096, NULL, ESP_TASKD_EVENT_PRIO - 1, &_network_event_task_handle, CONFIG_ARDUINO_EVENT_RUNNING_CORE); + if(!_network_event_task_handle){ + log_e("Network Event Task Start Failed!"); + return false; + } + } + return esp_event_loop_init(&_network_event_cb, NULL) == ESP_OK; +} + +void tcpipInit(){ + static bool initialized = false; + if(!initialized && _start_network_event_task()){ + initialized = true; + tcpip_adapter_init(); + } +} + +static bool lowLevelInitDone = false; +static bool wifiLowLevelInit(bool persistent){ + if(!lowLevelInitDone){ + tcpipInit(); + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + esp_err_t err = esp_wifi_init(&cfg); + if(err){ + log_e("esp_wifi_init %d", err); + return false; + } + if(!persistent){ + esp_wifi_set_storage(WIFI_STORAGE_RAM); + } + lowLevelInitDone = true; + } + return true; +} + +static bool wifiLowLevelDeinit(){ + //deinit not working yet! + //esp_wifi_deinit(); + return true; +} + +static bool _esp_wifi_started = false; + +static bool espWiFiStart(){ + if(_esp_wifi_started){ + return true; + } + esp_err_t err = esp_wifi_start(); + if (err != ESP_OK) { + log_e("esp_wifi_start %d", err); + return false; + } + _esp_wifi_started = true; + system_event_t event; + event.event_id = SYSTEM_EVENT_WIFI_READY; + WiFiGenericClass::_eventCallback(nullptr, &event); + return true; +} + +static bool espWiFiStop(){ + esp_err_t err; + if(!_esp_wifi_started){ + return true; + } + _esp_wifi_started = false; + err = esp_wifi_stop(); + if(err){ + log_e("Could not stop WiFi! %d", err); + _esp_wifi_started = true; + return false; + } + return wifiLowLevelDeinit(); +} + +// ----------------------------------------------------------------------------------------------------------------------- +// ------------------------------------------------- Generic WiFi function ----------------------------------------------- +// ----------------------------------------------------------------------------------------------------------------------- + +typedef struct WiFiEventCbList { + static wifi_event_id_t current_id; + wifi_event_id_t id; + WiFiEventCb cb; + WiFiEventFuncCb fcb; + WiFiEventSysCb scb; + system_event_id_t event; + + WiFiEventCbList() : id(current_id++), cb(NULL), fcb(NULL), scb(NULL), event(SYSTEM_EVENT_WIFI_READY) {} +} WiFiEventCbList_t; +wifi_event_id_t WiFiEventCbList::current_id = 1; + + +// arduino dont like std::vectors move static here +static std::vector cbEventList; + +bool WiFiGenericClass::_persistent = true; +bool WiFiGenericClass::_long_range = false; +wifi_mode_t WiFiGenericClass::_forceSleepLastMode = WIFI_MODE_NULL; + +WiFiGenericClass::WiFiGenericClass() +{ + +} + +int WiFiGenericClass::setStatusBits(int bits){ + if(!_network_event_group){ + return 0; + } + return xEventGroupSetBits(_network_event_group, bits); +} + +int WiFiGenericClass::clearStatusBits(int bits){ + if(!_network_event_group){ + return 0; + } + return xEventGroupClearBits(_network_event_group, bits); +} + +int WiFiGenericClass::getStatusBits(){ + if(!_network_event_group){ + return 0; + } + return xEventGroupGetBits(_network_event_group); +} + +int WiFiGenericClass::waitStatusBits(int bits, uint32_t timeout_ms){ + if(!_network_event_group){ + return 0; + } + return xEventGroupWaitBits( + _network_event_group, // The event group being tested. + bits, // The bits within the event group to wait for. + pdFALSE, // BIT_0 and BIT_4 should be cleared before returning. + pdTRUE, // Don't wait for both bits, either bit will do. + timeout_ms / portTICK_PERIOD_MS ) & bits; // Wait a maximum of 100ms for either bit to be set. +} + +/** + * set callback function + * @param cbEvent WiFiEventCb + * @param event optional filter (WIFI_EVENT_MAX is all events) + */ +wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventCb cbEvent, system_event_id_t event) +{ + if(!cbEvent) { + return 0; + } + WiFiEventCbList_t newEventHandler; + newEventHandler.cb = cbEvent; + newEventHandler.fcb = NULL; + newEventHandler.scb = NULL; + newEventHandler.event = event; + cbEventList.push_back(newEventHandler); + return newEventHandler.id; +} + +wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventFuncCb cbEvent, system_event_id_t event) +{ + if(!cbEvent) { + return 0; + } + WiFiEventCbList_t newEventHandler; + newEventHandler.cb = NULL; + newEventHandler.fcb = cbEvent; + newEventHandler.scb = NULL; + newEventHandler.event = event; + cbEventList.push_back(newEventHandler); + return newEventHandler.id; +} + +wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventSysCb cbEvent, system_event_id_t event) +{ + if(!cbEvent) { + return 0; + } + WiFiEventCbList_t newEventHandler; + newEventHandler.cb = NULL; + newEventHandler.fcb = NULL; + newEventHandler.scb = cbEvent; + newEventHandler.event = event; + cbEventList.push_back(newEventHandler); + return newEventHandler.id; +} + +/** + * removes a callback form event handler + * @param cbEvent WiFiEventCb + * @param event optional filter (WIFI_EVENT_MAX is all events) + */ +void WiFiGenericClass::removeEvent(WiFiEventCb cbEvent, system_event_id_t event) +{ + if(!cbEvent) { + return; + } + + for(uint32_t i = 0; i < cbEventList.size(); i++) { + WiFiEventCbList_t entry = cbEventList[i]; + if(entry.cb == cbEvent && entry.event == event) { + cbEventList.erase(cbEventList.begin() + i); + } + } +} + +void WiFiGenericClass::removeEvent(WiFiEventSysCb cbEvent, system_event_id_t event) +{ + if(!cbEvent) { + return; + } + + for(uint32_t i = 0; i < cbEventList.size(); i++) { + WiFiEventCbList_t entry = cbEventList[i]; + if(entry.scb == cbEvent && entry.event == event) { + cbEventList.erase(cbEventList.begin() + i); + } + } +} + +void WiFiGenericClass::removeEvent(wifi_event_id_t id) +{ + for(uint32_t i = 0; i < cbEventList.size(); i++) { + WiFiEventCbList_t entry = cbEventList[i]; + if(entry.id == id) { + cbEventList.erase(cbEventList.begin() + i); + } + } +} + +/** + * callback for WiFi events + * @param arg + */ +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG +const char * system_event_names[] = { "WIFI_READY", "SCAN_DONE", "STA_START", "STA_STOP", "STA_CONNECTED", "STA_DISCONNECTED", "STA_AUTHMODE_CHANGE", "STA_GOT_IP", "STA_LOST_IP", "STA_WPS_ER_SUCCESS", "STA_WPS_ER_FAILED", "STA_WPS_ER_TIMEOUT", "STA_WPS_ER_PIN", "STA_WPS_ER_PBC_OVERLAP", "AP_START", "AP_STOP", "AP_STACONNECTED", "AP_STADISCONNECTED", "AP_STAIPASSIGNED", "AP_PROBEREQRECVED", "GOT_IP6", "ETH_START", "ETH_STOP", "ETH_CONNECTED", "ETH_DISCONNECTED", "ETH_GOT_IP", "MAX"}; +#endif +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN +const char * system_event_reasons[] = { "UNSPECIFIED", "AUTH_EXPIRE", "AUTH_LEAVE", "ASSOC_EXPIRE", "ASSOC_TOOMANY", "NOT_AUTHED", "NOT_ASSOCED", "ASSOC_LEAVE", "ASSOC_NOT_AUTHED", "DISASSOC_PWRCAP_BAD", "DISASSOC_SUPCHAN_BAD", "UNSPECIFIED", "IE_INVALID", "MIC_FAILURE", "4WAY_HANDSHAKE_TIMEOUT", "GROUP_KEY_UPDATE_TIMEOUT", "IE_IN_4WAY_DIFFERS", "GROUP_CIPHER_INVALID", "PAIRWISE_CIPHER_INVALID", "AKMP_INVALID", "UNSUPP_RSN_IE_VERSION", "INVALID_RSN_IE_CAP", "802_1X_AUTH_FAILED", "CIPHER_SUITE_REJECTED", "BEACON_TIMEOUT", "NO_AP_FOUND", "AUTH_FAIL", "ASSOC_FAIL", "HANDSHAKE_TIMEOUT" }; +#define reason2str(r) ((r>176)?system_event_reasons[r-176]:system_event_reasons[r-1]) +#endif +esp_err_t WiFiGenericClass::_eventCallback(void *arg, system_event_t *event) +{ + if(event->event_id < 26) { + log_d("Event: %d - %s", event->event_id, system_event_names[event->event_id]); + } + if(event->event_id == SYSTEM_EVENT_SCAN_DONE) { + WiFiScanClass::_scanDone(); + + } else if(event->event_id == SYSTEM_EVENT_STA_START) { + WiFiSTAClass::_setStatus(WL_DISCONNECTED); + setStatusBits(STA_STARTED_BIT); + } else if(event->event_id == SYSTEM_EVENT_STA_STOP) { + WiFiSTAClass::_setStatus(WL_NO_SHIELD); + clearStatusBits(STA_STARTED_BIT | STA_CONNECTED_BIT | STA_HAS_IP_BIT | STA_HAS_IP6_BIT); + } else if(event->event_id == SYSTEM_EVENT_STA_CONNECTED) { + WiFiSTAClass::_setStatus(WL_IDLE_STATUS); + setStatusBits(STA_CONNECTED_BIT); + } else if(event->event_id == SYSTEM_EVENT_STA_DISCONNECTED) { + uint8_t reason = event->event_info.disconnected.reason; + log_w("Reason: %u - %s", reason, reason2str(reason)); + if(reason == WIFI_REASON_NO_AP_FOUND) { + WiFiSTAClass::_setStatus(WL_NO_SSID_AVAIL); + } else if(reason == WIFI_REASON_AUTH_FAIL || reason == WIFI_REASON_ASSOC_FAIL) { + WiFiSTAClass::_setStatus(WL_CONNECT_FAILED); + } else if(reason == WIFI_REASON_BEACON_TIMEOUT || reason == WIFI_REASON_HANDSHAKE_TIMEOUT) { + WiFiSTAClass::_setStatus(WL_CONNECTION_LOST); + } else if(reason == WIFI_REASON_AUTH_EXPIRE) { + + } else { + WiFiSTAClass::_setStatus(WL_DISCONNECTED); + } + clearStatusBits(STA_CONNECTED_BIT | STA_HAS_IP_BIT | STA_HAS_IP6_BIT); + if(((reason == WIFI_REASON_AUTH_EXPIRE) || + (reason >= WIFI_REASON_BEACON_TIMEOUT && reason != WIFI_REASON_AUTH_FAIL)) && + WiFi.getAutoReconnect()) + { + WiFi.disconnect(); + WiFi.begin(); + } + } else if(event->event_id == SYSTEM_EVENT_STA_GOT_IP) { +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG + uint8_t * ip = (uint8_t *)&(event->event_info.got_ip.ip_info.ip.addr); + uint8_t * mask = (uint8_t *)&(event->event_info.got_ip.ip_info.netmask.addr); + uint8_t * gw = (uint8_t *)&(event->event_info.got_ip.ip_info.gw.addr); + log_d("STA IP: %u.%u.%u.%u, MASK: %u.%u.%u.%u, GW: %u.%u.%u.%u", + ip[0], ip[1], ip[2], ip[3], + mask[0], mask[1], mask[2], mask[3], + gw[0], gw[1], gw[2], gw[3]); +#endif + WiFiSTAClass::_setStatus(WL_CONNECTED); + setStatusBits(STA_HAS_IP_BIT | STA_CONNECTED_BIT); + } else if(event->event_id == SYSTEM_EVENT_STA_LOST_IP) { + WiFiSTAClass::_setStatus(WL_IDLE_STATUS); + clearStatusBits(STA_HAS_IP_BIT); + + } else if(event->event_id == SYSTEM_EVENT_AP_START) { + setStatusBits(AP_STARTED_BIT); + } else if(event->event_id == SYSTEM_EVENT_AP_STOP) { + clearStatusBits(AP_STARTED_BIT | AP_HAS_CLIENT_BIT); + } else if(event->event_id == SYSTEM_EVENT_AP_STACONNECTED) { + setStatusBits(AP_HAS_CLIENT_BIT); + } else if(event->event_id == SYSTEM_EVENT_AP_STADISCONNECTED) { + wifi_sta_list_t clients; + if(esp_wifi_ap_get_sta_list(&clients) != ESP_OK || !clients.num){ + clearStatusBits(AP_HAS_CLIENT_BIT); + } + + } else if(event->event_id == SYSTEM_EVENT_ETH_START) { + setStatusBits(ETH_STARTED_BIT); + } else if(event->event_id == SYSTEM_EVENT_ETH_STOP) { + clearStatusBits(ETH_STARTED_BIT | ETH_CONNECTED_BIT | ETH_HAS_IP_BIT | ETH_HAS_IP6_BIT); + } else if(event->event_id == SYSTEM_EVENT_ETH_CONNECTED) { + setStatusBits(ETH_CONNECTED_BIT); + } else if(event->event_id == SYSTEM_EVENT_ETH_DISCONNECTED) { + clearStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP_BIT | ETH_HAS_IP6_BIT); + } else if(event->event_id == SYSTEM_EVENT_ETH_GOT_IP) { +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG + uint8_t * ip = (uint8_t *)&(event->event_info.got_ip.ip_info.ip.addr); + uint8_t * mask = (uint8_t *)&(event->event_info.got_ip.ip_info.netmask.addr); + uint8_t * gw = (uint8_t *)&(event->event_info.got_ip.ip_info.gw.addr); + log_d("ETH IP: %u.%u.%u.%u, MASK: %u.%u.%u.%u, GW: %u.%u.%u.%u", + ip[0], ip[1], ip[2], ip[3], + mask[0], mask[1], mask[2], mask[3], + gw[0], gw[1], gw[2], gw[3]); +#endif + setStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP_BIT); + + } else if(event->event_id == SYSTEM_EVENT_GOT_IP6) { + if(event->event_info.got_ip6.if_index == TCPIP_ADAPTER_IF_AP){ + setStatusBits(AP_HAS_IP6_BIT); + } else if(event->event_info.got_ip6.if_index == TCPIP_ADAPTER_IF_STA){ + setStatusBits(STA_CONNECTED_BIT | STA_HAS_IP6_BIT); + } else if(event->event_info.got_ip6.if_index == TCPIP_ADAPTER_IF_ETH){ + setStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP6_BIT); + } + } + + for(uint32_t i = 0; i < cbEventList.size(); i++) { + WiFiEventCbList_t entry = cbEventList[i]; + if(entry.cb || entry.fcb || entry.scb) { + if(entry.event == (system_event_id_t) event->event_id || entry.event == SYSTEM_EVENT_MAX) { + if(entry.cb) { + entry.cb((system_event_id_t) event->event_id); + } else if(entry.fcb) { + entry.fcb((system_event_id_t) event->event_id, (system_event_info_t) event->event_info); + } else { + entry.scb(event); + } + } + } + } + return ESP_OK; +} + +/** + * Return the current channel associated with the network + * @return channel (1-13) + */ +int32_t WiFiGenericClass::channel(void) +{ + uint8_t primaryChan = 0; + wifi_second_chan_t secondChan = WIFI_SECOND_CHAN_NONE; + if(!lowLevelInitDone){ + return primaryChan; + } + esp_wifi_get_channel(&primaryChan, &secondChan); + return primaryChan; +} + + +/** + * store WiFi config in SDK flash area + * @param persistent + */ +void WiFiGenericClass::persistent(bool persistent) +{ + _persistent = persistent; +} + + +/** + * enable WiFi long range mode + * @param enable + */ +void WiFiGenericClass::enableLongRange(bool enable) +{ + _long_range = enable; +} + + +/** + * set new mode + * @param m WiFiMode_t + */ +bool WiFiGenericClass::mode(wifi_mode_t m) +{ + wifi_mode_t cm = getMode(); + if(cm == m) { + return true; + } + if(!cm && m){ + if(!wifiLowLevelInit(_persistent)){ + return false; + } + } else if(cm && !m){ + return espWiFiStop(); + } + + esp_err_t err; + err = esp_wifi_set_mode(m); + if(err){ + log_e("Could not set mode! %d", err); + return false; + } + if(_long_range){ + if(m & WIFI_MODE_STA){ + err = esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_LR); + if(err != ESP_OK){ + log_e("Could not enable long range on STA! %d", err); + return false; + } + } + if(m & WIFI_MODE_AP){ + err = esp_wifi_set_protocol(WIFI_IF_AP, WIFI_PROTOCOL_LR); + if(err != ESP_OK){ + log_e("Could not enable long range on AP! %d", err); + return false; + } + } + } + if(!espWiFiStart()){ + return false; + } + return true; +} + +/** + * get WiFi mode + * @return WiFiMode + */ +wifi_mode_t WiFiGenericClass::getMode() +{ + if(!lowLevelInitDone){ + return WIFI_MODE_NULL; + } + wifi_mode_t mode; + if(esp_wifi_get_mode(&mode) == ESP_ERR_WIFI_NOT_INIT){ + log_w("WiFi not started"); + return WIFI_MODE_NULL; + } + return mode; +} + +/** + * control STA mode + * @param enable bool + * @return ok + */ +bool WiFiGenericClass::enableSTA(bool enable) +{ + + wifi_mode_t currentMode = getMode(); + bool isEnabled = ((currentMode & WIFI_MODE_STA) != 0); + + if(isEnabled != enable) { + if(enable) { + return mode((wifi_mode_t)(currentMode | WIFI_MODE_STA)); + } + return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_STA))); + } + return true; +} + +/** + * control AP mode + * @param enable bool + * @return ok + */ +bool WiFiGenericClass::enableAP(bool enable) +{ + + wifi_mode_t currentMode = getMode(); + bool isEnabled = ((currentMode & WIFI_MODE_AP) != 0); + + if(isEnabled != enable) { + if(enable) { + return mode((wifi_mode_t)(currentMode | WIFI_MODE_AP)); + } + return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_AP))); + } + return true; +} + +/** + * control modem sleep when only in STA mode + * @param enable bool + * @return ok + */ +bool WiFiGenericClass::setSleep(bool enable) +{ + if((getMode() & WIFI_MODE_STA) == 0){ + log_w("STA has not been started"); + return false; + } + return esp_wifi_set_ps(enable?WIFI_PS_MIN_MODEM:WIFI_PS_NONE) == ESP_OK; +} + +/** + * get modem sleep enabled + * @return true if modem sleep is enabled + */ +bool WiFiGenericClass::getSleep() +{ + wifi_ps_type_t ps; + if((getMode() & WIFI_MODE_STA) == 0){ + log_w("STA has not been started"); + return false; + } + if(esp_wifi_get_ps(&ps) == ESP_OK){ + return ps == WIFI_PS_MIN_MODEM; + } + return false; +} + +/** + * control wifi tx power + * @param power enum maximum wifi tx power + * @return ok + */ +bool WiFiGenericClass::setTxPower(wifi_power_t power){ + if((getStatusBits() & (STA_STARTED_BIT | AP_STARTED_BIT)) == 0){ + log_w("Neither AP or STA has been started"); + return false; + } + return esp_wifi_set_max_tx_power(power) == ESP_OK; +} + +wifi_power_t WiFiGenericClass::getTxPower(){ + int8_t power; + if((getStatusBits() & (STA_STARTED_BIT | AP_STARTED_BIT)) == 0){ + log_w("Neither AP or STA has been started"); + return WIFI_POWER_19_5dBm; + } + if(esp_wifi_get_max_tx_power(&power)){ + return WIFI_POWER_19_5dBm; + } + return (wifi_power_t)power; +} + +// ----------------------------------------------------------------------------------------------------------------------- +// ------------------------------------------------ Generic Network function --------------------------------------------- +// ----------------------------------------------------------------------------------------------------------------------- + +/** + * DNS callback + * @param name + * @param ipaddr + * @param callback_arg + */ +static void wifi_dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg) +{ + if(ipaddr) { + (*reinterpret_cast(callback_arg)) = ipaddr->u_addr.ip4.addr; + } + xEventGroupSetBits(_network_event_group, WIFI_DNS_DONE_BIT); +} + +/** + * Resolve the given hostname to an IP address. + * @param aHostname Name to be resolved + * @param aResult IPAddress structure to store the returned IP address + * @return 1 if aIPAddrString was successfully converted to an IP address, + * else error code + */ +int WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult) +{ + ip_addr_t addr; + aResult = static_cast(0); + waitStatusBits(WIFI_DNS_IDLE_BIT, 5000); + clearStatusBits(WIFI_DNS_IDLE_BIT); + err_t err = dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult); + if(err == ERR_OK && addr.u_addr.ip4.addr) { + aResult = addr.u_addr.ip4.addr; + } else if(err == ERR_INPROGRESS) { + waitStatusBits(WIFI_DNS_DONE_BIT, 4000); + clearStatusBits(WIFI_DNS_DONE_BIT); + } + setStatusBits(WIFI_DNS_IDLE_BIT); + if((uint32_t)aResult == 0){ + log_e("DNS Failed for %s", aHostname); + } + return (uint32_t)aResult != 0; +} + +IPAddress WiFiGenericClass::calculateNetworkID(IPAddress ip, IPAddress subnet) { + IPAddress networkID; + + for (size_t i = 0; i < 4; i++) + networkID[i] = subnet[i] & ip[i]; + + return networkID; +} + +IPAddress WiFiGenericClass::calculateBroadcast(IPAddress ip, IPAddress subnet) { + IPAddress broadcastIp; + + for (int i = 0; i < 4; i++) + broadcastIp[i] = ~subnet[i] | ip[i]; + + return broadcastIp; +} + +uint8_t WiFiGenericClass::calculateSubnetCIDR(IPAddress subnetMask) { + uint8_t CIDR = 0; + + for (uint8_t i = 0; i < 4; i++) { + if (subnetMask[i] == 0x80) // 128 + CIDR += 1; + else if (subnetMask[i] == 0xC0) // 192 + CIDR += 2; + else if (subnetMask[i] == 0xE0) // 224 + CIDR += 3; + else if (subnetMask[i] == 0xF0) // 242 + CIDR += 4; + else if (subnetMask[i] == 0xF8) // 248 + CIDR += 5; + else if (subnetMask[i] == 0xFC) // 252 + CIDR += 6; + else if (subnetMask[i] == 0xFE) // 254 + CIDR += 7; + else if (subnetMask[i] == 0xFF) // 255 + CIDR += 8; + } + + return CIDR; +} diff --git a/libraries/WiFi/src/WiFiGeneric.h b/libraries/WiFi/src/WiFiGeneric.h index 415bb68176e..65f5d23b464 100644 --- a/libraries/WiFi/src/WiFiGeneric.h +++ b/libraries/WiFi/src/WiFiGeneric.h @@ -1,74 +1,123 @@ -/* - ESP8266WiFiGeneric.h - esp8266 Wifi support. - Based on WiFi.h from Ardiono WiFi shield library. - Copyright (c) 2011-2014 Arduino. All right reserved. - Modified by Ivan Grokhotkov, December 2014 - Reworked by Markus Sattler, December 2015 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef ESP32WIFIGENERIC_H_ -#define ESP32WIFIGENERIC_H_ - -#include "WiFiType.h" -#include -#include - -typedef void (*WiFiEventCb)(system_event_id_t event); -typedef void (*WiFiEventFullCb)(system_event_id_t event, system_event_info_t info); -typedef void (*WiFiEventSysCb)(system_event_t *event); - -class WiFiGenericClass -{ -public: - - WiFiGenericClass(); - - void onEvent(WiFiEventCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); - void onEvent(WiFiEventFullCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); - void onEvent(WiFiEventSysCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); - void removeEvent(WiFiEventCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); - void removeEvent(WiFiEventFullCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); - void removeEvent(WiFiEventSysCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); - - int32_t channel(void); - - void persistent(bool persistent); - - static bool mode(wifi_mode_t); - static wifi_mode_t getMode(); - - bool enableSTA(bool enable); - bool enableAP(bool enable); - - static esp_err_t _eventCallback(void *arg, system_event_t *event); - -protected: - static bool _persistent; - static wifi_mode_t _forceSleepLastMode; - -public: - - int hostByName(const char* aHostname, IPAddress& aResult); - -protected: - - friend class WiFiSTAClass; - friend class WiFiScanClass; - friend class WiFiAPClass; -}; - -#endif /* ESP32WIFIGENERIC_H_ */ +/* + ESP8266WiFiGeneric.h - esp8266 Wifi support. + Based on WiFi.h from Ardiono WiFi shield library. + Copyright (c) 2011-2014 Arduino. All right reserved. + Modified by Ivan Grokhotkov, December 2014 + Reworked by Markus Sattler, December 2015 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef ESP32WIFIGENERIC_H_ +#define ESP32WIFIGENERIC_H_ + +#include +#include +#include +#include "WiFiType.h" + +typedef void (*WiFiEventCb)(system_event_id_t event); +typedef std::function WiFiEventFuncCb; +typedef void (*WiFiEventSysCb)(system_event_t *event); + +typedef size_t wifi_event_id_t; + +typedef enum { + WIFI_POWER_19_5dBm = 78,// 19.5dBm + WIFI_POWER_19dBm = 76,// 19dBm + WIFI_POWER_18_5dBm = 74,// 18.5dBm + WIFI_POWER_17dBm = 68,// 17dBm + WIFI_POWER_15dBm = 60,// 15dBm + WIFI_POWER_13dBm = 52,// 13dBm + WIFI_POWER_11dBm = 44,// 11dBm + WIFI_POWER_8_5dBm = 34,// 8.5dBm + WIFI_POWER_7dBm = 28,// 7dBm + WIFI_POWER_5dBm = 20,// 5dBm + WIFI_POWER_2dBm = 8,// 2dBm + WIFI_POWER_MINUS_1dBm = -4// -1dBm +} wifi_power_t; + +static const int AP_STARTED_BIT = BIT0; +static const int AP_HAS_IP6_BIT = BIT1; +static const int AP_HAS_CLIENT_BIT = BIT2; +static const int STA_STARTED_BIT = BIT3; +static const int STA_CONNECTED_BIT = BIT4; +static const int STA_HAS_IP_BIT = BIT5; +static const int STA_HAS_IP6_BIT = BIT6; +static const int ETH_STARTED_BIT = BIT7; +static const int ETH_CONNECTED_BIT = BIT8; +static const int ETH_HAS_IP_BIT = BIT9; +static const int ETH_HAS_IP6_BIT = BIT10; +static const int WIFI_SCANNING_BIT = BIT11; +static const int WIFI_SCAN_DONE_BIT= BIT12; +static const int WIFI_DNS_IDLE_BIT = BIT13; +static const int WIFI_DNS_DONE_BIT = BIT14; + +class WiFiGenericClass +{ + public: + WiFiGenericClass(); + + wifi_event_id_t onEvent(WiFiEventCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); + wifi_event_id_t onEvent(WiFiEventFuncCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); + wifi_event_id_t onEvent(WiFiEventSysCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); + void removeEvent(WiFiEventCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); + void removeEvent(WiFiEventSysCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX); + void removeEvent(wifi_event_id_t id); + + static int getStatusBits(); + static int waitStatusBits(int bits, uint32_t timeout_ms); + + int32_t channel(void); + + void persistent(bool persistent); + void enableLongRange(bool enable); + + static bool mode(wifi_mode_t); + static wifi_mode_t getMode(); + + bool enableSTA(bool enable); + bool enableAP(bool enable); + + bool setSleep(bool enable); + bool getSleep(); + + bool setTxPower(wifi_power_t power); + wifi_power_t getTxPower(); + + static esp_err_t _eventCallback(void *arg, system_event_t *event); + + protected: + static bool _persistent; + static bool _long_range; + static wifi_mode_t _forceSleepLastMode; + + static int setStatusBits(int bits); + static int clearStatusBits(int bits); + + public: + static int hostByName(const char *aHostname, IPAddress &aResult); + + static IPAddress calculateNetworkID(IPAddress ip, IPAddress subnet); + static IPAddress calculateBroadcast(IPAddress ip, IPAddress subnet); + static uint8_t calculateSubnetCIDR(IPAddress subnetMask); + + protected: + friend class WiFiSTAClass; + friend class WiFiScanClass; + friend class WiFiAPClass; +}; + +#endif /* ESP32WIFIGENERIC_H_ */ diff --git a/libraries/WiFi/src/WiFiMulti.cpp b/libraries/WiFi/src/WiFiMulti.cpp index 5a36cd6ea9f..730850333f1 100644 --- a/libraries/WiFi/src/WiFiMulti.cpp +++ b/libraries/WiFi/src/WiFiMulti.cpp @@ -1,219 +1,204 @@ -/** - * - * @file ESP8266WiFiMulti.cpp - * @date 16.05.2015 - * @author Markus Sattler - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the esp8266 core for Arduino environment. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#include "WiFiMulti.h" -#include -#include -#include - -WiFiMulti::WiFiMulti() -{ -} - -WiFiMulti::~WiFiMulti() -{ - APlistClean(); -} - -bool WiFiMulti::addAP(const char* ssid, const char *passphrase) -{ - return APlistAdd(ssid, passphrase); -} - -uint8_t WiFiMulti::run(uint32_t connectTimeout) -{ - - int8_t scanResult; - uint8_t status = WiFi.status(); - if(status != WL_CONNECTED || status == WL_NO_SSID_AVAIL || status == WL_IDLE_STATUS || status == WL_CONNECT_FAILED) { - - scanResult = WiFi.scanNetworks(); - if(scanResult == WIFI_SCAN_RUNNING) { - // scan is running - return WL_NO_SSID_AVAIL; - } else if(scanResult > 0) { - // scan done analyze - WifiAPlist_t bestNetwork { NULL, NULL }; - int bestNetworkDb = INT_MIN; - uint8_t bestBSSID[6]; - int32_t bestChannel = 0; - - DEBUG_WIFI_MULTI("[WIFI] scan done\n"); - delay(0); - - if(scanResult <= 0) { - DEBUG_WIFI_MULTI("[WIFI] no networks found\n"); - } else { - DEBUG_WIFI_MULTI("[WIFI] %d networks found\n", scanResult); - for(int8_t i = 0; i < scanResult; ++i) { - - String ssid_scan; - int32_t rssi_scan; - uint8_t sec_scan; - uint8_t* BSSID_scan; - int32_t chan_scan; - - WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan); - - bool known = false; - for(uint32_t x = 0; x < APlist.size(); x++) { - WifiAPlist_t entry = APlist[x]; - - if(ssid_scan == entry.ssid) { // SSID match - known = true; - if(rssi_scan > bestNetworkDb) { // best network - if(sec_scan == WIFI_AUTH_OPEN || entry.passphrase) { // check for passphrase if not open wlan - bestNetworkDb = rssi_scan; - bestChannel = chan_scan; - memcpy((void*) &bestNetwork, (void*) &entry, sizeof(bestNetwork)); - memcpy((void*) &bestBSSID, (void*) BSSID_scan, sizeof(bestBSSID)); - } - } - break; - } - } - - if(known) { - DEBUG_WIFI_MULTI(" ---> "); - } else { - DEBUG_WIFI_MULTI(" "); - } - - DEBUG_WIFI_MULTI(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c\n", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == WIFI_AUTH_OPEN) ? ' ' : '*'); - delay(0); - } - } - - // clean up ram - WiFi.scanDelete(); - - DEBUG_WIFI_MULTI("\n\n"); - delay(0); - - if(bestNetwork.ssid) { - DEBUG_WIFI_MULTI("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channal: %d (%d)\n", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb); - - WiFi.begin(bestNetwork.ssid, bestNetwork.passphrase, bestChannel, bestBSSID); - status = WiFi.status(); - - auto startTime = millis(); - // wait for connection, fail, or timeout - while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED && (millis() - startTime) <= connectTimeout) { - delay(10); - status = WiFi.status(); - } - - IPAddress ip; - uint8_t * mac; - switch(status) { - case 3: - ip = WiFi.localIP(); - mac = WiFi.BSSID(); - DEBUG_WIFI_MULTI("[WIFI] Connecting done.\n"); - DEBUG_WIFI_MULTI("[WIFI] SSID: %s\n", WiFi.SSID()); - DEBUG_WIFI_MULTI("[WIFI] IP: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]); - DEBUG_WIFI_MULTI("[WIFI] MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - DEBUG_WIFI_MULTI("[WIFI] Channel: %d\n", WiFi.channel()); - break; - case 1: - DEBUG_WIFI_MULTI("[WIFI] Connecting Failed AP not found.\n"); - break; - case 4: - DEBUG_WIFI_MULTI("[WIFI] Connecting Failed.\n"); - break; - default: - DEBUG_WIFI_MULTI("[WIFI] Connecting Failed (%d).\n", status); - break; - } - } else { - DEBUG_WIFI_MULTI("[WIFI] no matching wifi found!\n"); - } - } else { - // start scan - DEBUG_WIFI_MULTI("[WIFI] delete old wifi config...\n"); - WiFi.disconnect(); - - DEBUG_WIFI_MULTI("[WIFI] start scan\n"); - // scan wifi async mode - WiFi.scanNetworks(true); - } - } - return status; -} - -// ################################################################################## - -bool WiFiMulti::APlistAdd(const char* ssid, const char *passphrase) -{ - - WifiAPlist_t newAP; - - if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) { - // fail SSID to long or missing! - DEBUG_WIFI_MULTI("[WIFI][APlistAdd] no ssid or ssid to long\n"); - return false; - } - - if(passphrase && strlen(passphrase) > 63) { - // fail passphrase to long! - DEBUG_WIFI_MULTI("[WIFI][APlistAdd] passphrase to long\n"); - return false; - } - - newAP.ssid = strdup(ssid); - - if(!newAP.ssid) { - DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.ssid == 0\n"); - return false; - } - - if(passphrase && *passphrase != 0x00) { - newAP.passphrase = strdup(passphrase); - if(!newAP.passphrase) { - DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.passphrase == 0\n"); - free(newAP.ssid); - return false; - } - } - - APlist.push_back(newAP); - DEBUG_WIFI_MULTI("[WIFI][APlistAdd] add SSID: %s\n", newAP.ssid); - return true; -} - -void WiFiMulti::APlistClean(void) -{ - for(uint32_t i = 0; i < APlist.size(); i++) { - WifiAPlist_t entry = APlist[i]; - if(entry.ssid) { - free(entry.ssid); - } - if(entry.passphrase) { - free(entry.passphrase); - } - } - APlist.clear(); -} - +/** + * + * @file WiFiMulti.cpp + * @date 16.05.2015 + * @author Markus Sattler + * + * Copyright (c) 2015 Markus Sattler. All rights reserved. + * This file is part of the esp8266 core for Arduino environment. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include "WiFiMulti.h" +#include +#include +#include + +WiFiMulti::WiFiMulti() +{ +} + +WiFiMulti::~WiFiMulti() +{ + for(uint32_t i = 0; i < APlist.size(); i++) { + WifiAPlist_t entry = APlist[i]; + if(entry.ssid) { + free(entry.ssid); + } + if(entry.passphrase) { + free(entry.passphrase); + } + } + APlist.clear(); +} + +bool WiFiMulti::addAP(const char* ssid, const char *passphrase) +{ + WifiAPlist_t newAP; + + if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) { + // fail SSID too long or missing! + log_e("[WIFI][APlistAdd] no ssid or ssid too long"); + return false; + } + + if(passphrase && strlen(passphrase) > 63) { + // fail passphrase too long! + log_e("[WIFI][APlistAdd] passphrase too long"); + return false; + } + + newAP.ssid = strdup(ssid); + + if(!newAP.ssid) { + log_e("[WIFI][APlistAdd] fail newAP.ssid == 0"); + return false; + } + + if(passphrase && *passphrase != 0x00) { + newAP.passphrase = strdup(passphrase); + if(!newAP.passphrase) { + log_e("[WIFI][APlistAdd] fail newAP.passphrase == 0"); + free(newAP.ssid); + return false; + } + } else { + newAP.passphrase = NULL; + } + + APlist.push_back(newAP); + log_i("[WIFI][APlistAdd] add SSID: %s", newAP.ssid); + return true; +} + +uint8_t WiFiMulti::run(uint32_t connectTimeout) +{ + int8_t scanResult; + uint8_t status = WiFi.status(); + if(status == WL_CONNECTED) { + for(uint32_t x = 0; x < APlist.size(); x++) { + if(WiFi.SSID()==APlist[x].ssid) { + return status; + } + } + WiFi.disconnect(false,false); + delay(10); + status = WiFi.status(); + } + + scanResult = WiFi.scanNetworks(); + if(scanResult == WIFI_SCAN_RUNNING) { + // scan is running + return WL_NO_SSID_AVAIL; + } else if(scanResult >= 0) { + // scan done analyze + WifiAPlist_t bestNetwork { NULL, NULL }; + int bestNetworkDb = INT_MIN; + uint8_t bestBSSID[6]; + int32_t bestChannel = 0; + + log_i("[WIFI] scan done"); + + if(scanResult == 0) { + log_e("[WIFI] no networks found"); + } else { + log_i("[WIFI] %d networks found", scanResult); + for(int8_t i = 0; i < scanResult; ++i) { + + String ssid_scan; + int32_t rssi_scan; + uint8_t sec_scan; + uint8_t* BSSID_scan; + int32_t chan_scan; + + WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan); + + bool known = false; + for(uint32_t x = 0; x < APlist.size(); x++) { + WifiAPlist_t entry = APlist[x]; + + if(ssid_scan == entry.ssid) { // SSID match + known = true; + if(rssi_scan > bestNetworkDb) { // best network + if(sec_scan == WIFI_AUTH_OPEN || entry.passphrase) { // check for passphrase if not open wlan + bestNetworkDb = rssi_scan; + bestChannel = chan_scan; + memcpy((void*) &bestNetwork, (void*) &entry, sizeof(bestNetwork)); + memcpy((void*) &bestBSSID, (void*) BSSID_scan, sizeof(bestBSSID)); + } + } + break; + } + } + + if(known) { + log_d(" ---> %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == WIFI_AUTH_OPEN) ? ' ' : '*'); + } else { + log_d(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == WIFI_AUTH_OPEN) ? ' ' : '*'); + } + } + } + + // clean up ram + WiFi.scanDelete(); + + if(bestNetwork.ssid) { + log_i("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channal: %d (%d)", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb); + + WiFi.begin(bestNetwork.ssid, bestNetwork.passphrase, bestChannel, bestBSSID); + status = WiFi.status(); + + auto startTime = millis(); + // wait for connection, fail, or timeout + while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED && (millis() - startTime) <= connectTimeout) { + delay(10); + status = WiFi.status(); + } + + switch(status) { + case WL_CONNECTED: + log_i("[WIFI] Connecting done."); + log_d("[WIFI] SSID: %s", WiFi.SSID().c_str()); + log_d("[WIFI] IP: %s", WiFi.localIP().toString().c_str()); + log_d("[WIFI] MAC: %s", WiFi.BSSIDstr().c_str()); + log_d("[WIFI] Channel: %d", WiFi.channel()); + break; + case WL_NO_SSID_AVAIL: + log_e("[WIFI] Connecting Failed AP not found."); + break; + case WL_CONNECT_FAILED: + log_e("[WIFI] Connecting Failed."); + break; + default: + log_e("[WIFI] Connecting Failed (%d).", status); + break; + } + } else { + log_e("[WIFI] no matching wifi found!"); + } + } else { + // start scan + log_d("[WIFI] delete old wifi config..."); + WiFi.disconnect(); + + log_d("[WIFI] start scan"); + // scan wifi async mode + WiFi.scanNetworks(true); + } + + return status; +} diff --git a/libraries/WiFi/src/WiFiMulti.h b/libraries/WiFi/src/WiFiMulti.h index d9939953ae7..38ddb5d9f95 100644 --- a/libraries/WiFi/src/WiFiMulti.h +++ b/libraries/WiFi/src/WiFiMulti.h @@ -1,66 +1,51 @@ -/** - * - * @file ESP8266WiFiMulti.h - * @date 16.05.2015 - * @author Markus Sattler - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the esp8266 core for Arduino environment. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#ifndef WIFICLIENTMULTI_H_ -#define WIFICLIENTMULTI_H_ - -#include "WiFi.h" -#undef min -#undef max -#include - -#ifdef DEBUG_ESP_WIFI -#ifdef DEBUG_ESP_PORT -#define DEBUG_WIFI_MULTI(...) DEBUG_ESP_PORT.printf( __VA_ARGS__ ) -#endif -#endif - -#ifndef DEBUG_WIFI_MULTI -#define DEBUG_WIFI_MULTI(...) -#endif - -typedef struct { - char * ssid; - char * passphrase; -} WifiAPlist_t; - -class WiFiMulti -{ -public: - WiFiMulti(); - ~WiFiMulti(); - - bool addAP(const char* ssid, const char *passphrase = NULL); - - uint8_t run(uint32_t connectTimeout=5000); - -private: - std::vector APlist; - bool APlistAdd(const char* ssid, const char *passphrase = NULL); - void APlistClean(void); - -}; - -#endif /* WIFICLIENTMULTI_H_ */ +/** + * + * @file ESP8266WiFiMulti.h + * @date 16.05.2015 + * @author Markus Sattler + * + * Copyright (c) 2015 Markus Sattler. All rights reserved. + * This file is part of the esp8266 core for Arduino environment. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef WIFICLIENTMULTI_H_ +#define WIFICLIENTMULTI_H_ + +#include "WiFi.h" +#include + +typedef struct { + char * ssid; + char * passphrase; +} WifiAPlist_t; + +class WiFiMulti +{ +public: + WiFiMulti(); + ~WiFiMulti(); + + bool addAP(const char* ssid, const char *passphrase = NULL); + + uint8_t run(uint32_t connectTimeout=5000); + +private: + std::vector APlist; +}; + +#endif /* WIFICLIENTMULTI_H_ */ diff --git a/libraries/WiFi/src/WiFiSTA.cpp b/libraries/WiFi/src/WiFiSTA.cpp index 6089e7a49e2..db5e019af31 100644 --- a/libraries/WiFi/src/WiFiSTA.cpp +++ b/libraries/WiFi/src/WiFiSTA.cpp @@ -1,642 +1,760 @@ -/* - ESP8266WiFiSTA.cpp - WiFi library for esp8266 - - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Reworked on 28 Dec 2015 by Markus Sattler - - */ - -#include "WiFi.h" -#include "WiFiGeneric.h" -#include "WiFiSTA.h" - -extern "C" { -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "lwip/err.h" -#include "lwip/dns.h" -#include -#include -} - -// ----------------------------------------------------------------------------------------------------------------------- -// ---------------------------------------------------- Private functions ------------------------------------------------ -// ----------------------------------------------------------------------------------------------------------------------- - -static bool sta_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs); - - -/** - * compare two STA configurations - * @param lhs station_config - * @param rhs station_config - * @return equal - */ -static bool sta_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs) -{ - if(strcmp(reinterpret_cast(lhs.sta.ssid), reinterpret_cast(rhs.sta.ssid)) != 0) { - return false; - } - - if(strcmp(reinterpret_cast(lhs.sta.password), reinterpret_cast(rhs.sta.password)) != 0) { - return false; - } - - if(lhs.sta.bssid_set != rhs.sta.bssid_set) { - return false; - } - - if(lhs.sta.bssid_set) { - if(memcmp(lhs.sta.bssid, rhs.sta.bssid, 6) != 0) { - return false; - } - } - - return true; -} - -// ----------------------------------------------------------------------------------------------------------------------- -// ---------------------------------------------------- STA function ----------------------------------------------------- -// ----------------------------------------------------------------------------------------------------------------------- - -bool WiFiSTAClass::_autoReconnect = true; -bool WiFiSTAClass::_useStaticIp = false; -wl_status_t WiFiSTAClass::_status = WL_NO_SHIELD; -/** - * Start Wifi connection - * if passphrase is set the most secure supported mode will be automatically selected - * @param ssid const char* Pointer to the SSID string. - * @param passphrase const char * Optional. Passphrase. Valid characters in a passphrase must be between ASCII 32-126 (decimal). - * @param bssid uint8_t[6] Optional. BSSID / MAC of AP - * @param channel Optional. Channel of AP - * @param connect Optional. call connect - * @return - */ -wl_status_t WiFiSTAClass::begin(const char* ssid, const char *passphrase, int32_t channel, const uint8_t* bssid, bool connect) -{ - - if(!WiFi.enableSTA(true)) { - // enable STA failed - return WL_CONNECT_FAILED; - } - - if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) { - // fail SSID too long or missing! - return WL_CONNECT_FAILED; - } - - if(passphrase && strlen(passphrase) > 64) { - // fail passphrase too long! - return WL_CONNECT_FAILED; - } - - wifi_config_t conf; - strcpy(reinterpret_cast(conf.sta.ssid), ssid); - - if(passphrase) { - if (strlen(passphrase) == 64) // it's not a passphrase, is the PSK - memcpy(reinterpret_cast(conf.sta.password), passphrase, 64); - else - strcpy(reinterpret_cast(conf.sta.password), passphrase); - } else { - *conf.sta.password = 0; - } - - if(bssid) { - conf.sta.bssid_set = 1; - memcpy((void *) &conf.sta.bssid[0], (void *) bssid, 6); - } else { - conf.sta.bssid_set = 0; - } - - wifi_config_t current_conf; - esp_wifi_get_config(WIFI_IF_STA, ¤t_conf); - if(!sta_config_equal(current_conf, conf)) { - esp_wifi_set_config(WIFI_IF_STA, &conf); - } - - if(channel > 0 && channel <= 13) { - esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE); - } - - esp_wifi_start(); - if(connect) { - esp_wifi_connect(); - } - - if(!_useStaticIp) { - tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA); - } else { - tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); - } - - return status(); -} - -wl_status_t WiFiSTAClass::begin(char* ssid, char *passphrase, int32_t channel, const uint8_t* bssid, bool connect) -{ - return begin((const char*) ssid, (const char*) passphrase, channel, bssid, connect); -} - -/** - * Use to connect to SDK config. - * @return wl_status_t - */ -wl_status_t WiFiSTAClass::begin() -{ - - if(!WiFi.enableSTA(true)) { - // enable STA failed - return WL_CONNECT_FAILED; - } - esp_wifi_start(); - esp_wifi_connect(); - - if(!_useStaticIp) { - tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA); - } else { - tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); - } - - return status(); -} - -void WiFiSTAClass::_setStatus(wl_status_t status) -{ - _status = status; - //log_i("wifi status: %d", status); -} - -/** - * Change IP configuration settings disabling the dhcp client - * @param local_ip Static ip configuration - * @param gateway Static gateway configuration - * @param subnet Static Subnet mask - * @param dns1 Static DNS server 1 - * @param dns2 Static DNS server 2 - */ -bool WiFiSTAClass::config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2) -{ - esp_err_t err = ESP_OK; - - if(!WiFi.enableSTA(true)) { - return false; - } - esp_wifi_start(); - - tcpip_adapter_ip_info_t info; - - if(local_ip != (uint32_t)0x00000000){ - info.ip.addr = static_cast(local_ip); - info.gw.addr = static_cast(gateway); - info.netmask.addr = static_cast(subnet); - } else { - info.ip.addr = 0; - info.gw.addr = 0; - info.netmask.addr = 0; - } - - err = tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); - if(err != ESP_OK && err != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED){ - log_e("DHCP could not be stopped! Error: %d", err); - return false; - } - - err = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &info); - if(err != ERR_OK){ - log_e("STA IP could not be configured! Error: %d", err); - return false; - } - - if(info.ip.addr){ - _useStaticIp = true; - } else { - err = tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA); - if(err != ESP_OK && err != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STARTED){ - log_w("DHCP could not be started! Error: %d", err); - return false; - } - _useStaticIp = false; - } - - ip_addr_t d; - d.type = IPADDR_TYPE_V4; - - if(dns1 != (uint32_t)0x00000000) { - // Set DNS1-Server - d.u_addr.ip4.addr = static_cast(dns1); - dns_setserver(0, &d); - } - - if(dns2 != (uint32_t)0x00000000) { - // Set DNS2-Server - d.u_addr.ip4.addr = static_cast(dns2); - dns_setserver(1, &d); - } - - return true; -} - -/** - * will force a disconnect an then start reconnecting to AP - * @return ok - */ -bool WiFiSTAClass::reconnect() -{ - if((WiFi.getMode() & WIFI_MODE_STA) != 0) { - if(esp_wifi_disconnect() == ESP_OK) { - return esp_wifi_connect() == ESP_OK; - } - } - return false; -} - -/** - * Disconnect from the network - * @param wifioff - * @return one value of wl_status_t enum - */ -bool WiFiSTAClass::disconnect(bool wifioff) -{ - bool ret; - wifi_config_t conf; - *conf.sta.ssid = 0; - *conf.sta.password = 0; - - WiFi.getMode(); - esp_wifi_start(); - esp_wifi_set_config(WIFI_IF_STA, &conf); - ret = esp_wifi_disconnect() == ESP_OK; - - if(wifioff) { - WiFi.enableSTA(false); - } - - return ret; -} - -/** - * is STA interface connected? - * @return true if STA is connected to an AD - */ -bool WiFiSTAClass::isConnected() -{ - return (status() == WL_CONNECTED); -} - - -/** - * Setting the ESP32 station to connect to the AP (which is recorded) - * automatically or not when powered on. Enable auto-connect by default. - * @param autoConnect bool - * @return if saved - */ -bool WiFiSTAClass::setAutoConnect(bool autoConnect) -{ - bool ret; - ret = esp_wifi_set_auto_connect(autoConnect); - return ret; -} - -/** - * Checks if ESP32 station mode will connect to AP - * automatically or not when it is powered on. - * @return auto connect - */ -bool WiFiSTAClass::getAutoConnect() -{ - bool autoConnect; - esp_wifi_get_auto_connect(&autoConnect); - return autoConnect; -} - -bool WiFiSTAClass::setAutoReconnect(bool autoReconnect) -{ - _autoReconnect = autoReconnect; - return true; -} - -bool WiFiSTAClass::getAutoReconnect() -{ - return _autoReconnect; -} - -/** - * Wait for WiFi connection to reach a result - * returns the status reached or disconnect if STA is off - * @return wl_status_t - */ -uint8_t WiFiSTAClass::waitForConnectResult() -{ - //1 and 3 have STA enabled - if((WiFiGenericClass::getMode() & WIFI_MODE_STA) == 0) { - return WL_DISCONNECTED; - } - int i = 0; - while((!status() || status() >= WL_DISCONNECTED) && i++ < 100) { - delay(100); - } - return status(); -} - -/** - * Get the station interface IP address. - * @return IPAddress station IP - */ -IPAddress WiFiSTAClass::localIP() -{ - tcpip_adapter_ip_info_t ip; - tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); - return IPAddress(ip.ip.addr); -} - - -/** - * Get the station interface MAC address. - * @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH - * @return pointer to uint8_t * - */ -uint8_t* WiFiSTAClass::macAddress(uint8_t* mac) -{ - esp_wifi_get_mac(WIFI_IF_STA, mac); - return mac; -} - -/** - * Get the station interface MAC address. - * @return String mac - */ -String WiFiSTAClass::macAddress(void) -{ - uint8_t mac[6]; - char macStr[18] = { 0 }; - esp_wifi_get_mac(WIFI_IF_STA, mac); - - sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - return String(macStr); -} - -/** - * Get the interface subnet mask address. - * @return IPAddress subnetMask - */ -IPAddress WiFiSTAClass::subnetMask() -{ - tcpip_adapter_ip_info_t ip; - tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); - return IPAddress(ip.netmask.addr); -} - -/** - * Get the gateway ip address. - * @return IPAddress gatewayIP - */ -IPAddress WiFiSTAClass::gatewayIP() -{ - tcpip_adapter_ip_info_t ip; - tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); - return IPAddress(ip.gw.addr); -} - -/** - * Get the DNS ip address. - * @param dns_no - * @return IPAddress DNS Server IP - */ -IPAddress WiFiSTAClass::dnsIP(uint8_t dns_no) -{ - ip_addr_t dns_ip = dns_getserver(dns_no); - return IPAddress(dns_ip.u_addr.ip4.addr); -} - -/** - * Return Connection status. - * @return one of the value defined in wl_status_t - * - */ -wl_status_t WiFiSTAClass::status() -{ - return WiFiSTAClass::_status; -} - -/** - * Return the current SSID associated with the network - * @return SSID - */ -String WiFiSTAClass::SSID() const -{ - wifi_ap_record_t info; - if(!esp_wifi_sta_get_ap_info(&info)) { - return String(reinterpret_cast(info.ssid)); - } - return String(); -} - -/** - * Return the current pre shared key associated with the network - * @return psk string - */ -String WiFiSTAClass::psk() const -{ - wifi_config_t conf; - esp_wifi_get_config(WIFI_IF_STA, &conf); - return String(reinterpret_cast(conf.sta.password)); -} - -/** - * Return the current bssid / mac associated with the network if configured - * @return bssid uint8_t * - */ -uint8_t* WiFiSTAClass::BSSID(void) -{ - static uint8_t bssid[6]; - wifi_ap_record_t info; - if(!esp_wifi_sta_get_ap_info(&info)) { - memcpy(bssid, info.bssid, 6); - return reinterpret_cast(bssid); - } - return NULL; -} - -/** - * Return the current bssid / mac associated with the network if configured - * @return String bssid mac - */ -String WiFiSTAClass::BSSIDstr(void) -{ - uint8_t* bssid = BSSID(); - if(!bssid){ - return String(); - } - char mac[18] = { 0 }; - sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]); - return String(mac); -} - -/** - * Return the current network RSSI. - * @return RSSI value - */ -int8_t WiFiSTAClass::RSSI(void) -{ - wifi_ap_record_t info; - if(!esp_wifi_sta_get_ap_info(&info)) { - return info.rssi; - } - return 0; -} - -/** - * Get the station interface Host name. - * @return char array hostname - */ -const char * WiFiSTAClass::getHostname() -{ - const char * hostname; - if(tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_STA, &hostname)){ - return NULL; - } - return hostname; -} - -/** - * Set the station interface Host name. - * @param hostname pointer to const string - * @return true on success - */ -bool WiFiSTAClass::setHostname(const char * hostname) -{ - return tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, hostname) == 0; -} - -/** - * Enable IPv6 on the station interface. - * @return true on success - */ -bool WiFiSTAClass::enableIpV6() -{ - return tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_STA) == 0; -} - -/** - * Get the station interface IPv6 address. - * @return IPv6Address - */ -IPv6Address WiFiSTAClass::localIPv6() -{ - static ip6_addr_t addr; - if(tcpip_adapter_get_ip6_linklocal(TCPIP_ADAPTER_IF_STA, &addr)){ - return IPv6Address(); - } - return IPv6Address(addr.addr); -} - - -bool WiFiSTAClass::_smartConfigStarted = false; -bool WiFiSTAClass::_smartConfigDone = false; - - -bool WiFiSTAClass::beginSmartConfig() { - if (_smartConfigStarted) { - return false; - } - - if (!WiFi.mode(WIFI_STA)) { - return false; - } - - esp_wifi_disconnect(); - - esp_err_t err; - err = esp_smartconfig_start(reinterpret_cast(&WiFiSTAClass::_smartConfigCallback), 1); - if (err == ESP_OK) { - _smartConfigStarted = true; - _smartConfigDone = false; - return true; - } - return false; -} - -bool WiFiSTAClass::stopSmartConfig() { - if (!_smartConfigStarted) { - return true; - } - - if (esp_smartconfig_stop() == ESP_OK) { - _smartConfigStarted = false; - return true; - } - - return false; -} - -bool WiFiSTAClass::smartConfigDone() { - if (!_smartConfigStarted) { - return false; - } - - return _smartConfigDone; -} - -#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG -const char * sc_status_strings[] = { - "WAIT", - "FIND_CHANNEL", - "GETTING_SSID_PSWD", - "LINK", - "LINK_OVER" -}; - -const char * sc_type_strings[] = { - "ESPTOUCH", - "AIRKISS", - "ESPTOUCH_AIRKISS" -}; -#endif - -void WiFiSTAClass::_smartConfigCallback(uint32_t st, void* result) { - smartconfig_status_t status = (smartconfig_status_t) st; - log_d("Status: %s", sc_status_strings[st % 5]); - if (status == SC_STATUS_GETTING_SSID_PSWD) { - smartconfig_type_t * type = (smartconfig_type_t *)result; - log_d("Type: %s", sc_type_strings[*type % 3]); - } else if (status == SC_STATUS_LINK) { - wifi_sta_config_t *sta_conf = reinterpret_cast(result); - log_d("SSID: %s", (char *)(sta_conf->ssid)); - sta_conf->bssid_set = 0; - esp_wifi_set_config(WIFI_IF_STA, (wifi_config_t *)sta_conf); - esp_wifi_connect(); - _smartConfigDone = true; - } else if (status == SC_STATUS_LINK_OVER) { - if(result){ - ip4_addr_t * ip = (ip4_addr_t *)result; - log_d("Sender IP: " IPSTR, IP2STR(ip)); - } - WiFi.stopSmartConfig(); - } -} +/* + WiFiSTA.cpp - WiFi library for esp32 + + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Reworked on 28 Dec 2015 by Markus Sattler + + */ + +#include "WiFi.h" +#include "WiFiGeneric.h" +#include "WiFiSTA.h" + +extern "C" { +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "lwip/err.h" +#include "lwip/dns.h" +#include +#include +} + +// ----------------------------------------------------------------------------------------------------------------------- +// ---------------------------------------------------- Private functions ------------------------------------------------ +// ----------------------------------------------------------------------------------------------------------------------- + +static bool sta_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs); + + +/** + * compare two STA configurations + * @param lhs station_config + * @param rhs station_config + * @return equal + */ +static bool sta_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs) +{ + if(memcmp(&lhs, &rhs, sizeof(wifi_config_t)) != 0) { + return false; + } + return true; +} + +// ----------------------------------------------------------------------------------------------------------------------- +// ---------------------------------------------------- STA function ----------------------------------------------------- +// ----------------------------------------------------------------------------------------------------------------------- + +bool WiFiSTAClass::_autoReconnect = true; +bool WiFiSTAClass::_useStaticIp = false; + +static wl_status_t _sta_status = WL_NO_SHIELD; +static EventGroupHandle_t _sta_status_group = NULL; + +void WiFiSTAClass::_setStatus(wl_status_t status) +{ + if(!_sta_status_group){ + _sta_status_group = xEventGroupCreate(); + if(!_sta_status_group){ + log_e("STA Status Group Create Failed!"); + _sta_status = status; + return; + } + } + xEventGroupClearBits(_sta_status_group, 0x00FFFFFF); + xEventGroupSetBits(_sta_status_group, status); +} + +/** + * Return Connection status. + * @return one of the value defined in wl_status_t + * + */ +wl_status_t WiFiSTAClass::status() +{ + if(!_sta_status_group){ + return _sta_status; + } + return (wl_status_t)xEventGroupClearBits(_sta_status_group, 0); +} + +/** + * Start Wifi connection + * if passphrase is set the most secure supported mode will be automatically selected + * @param ssid const char* Pointer to the SSID string. + * @param passphrase const char * Optional. Passphrase. Valid characters in a passphrase must be between ASCII 32-126 (decimal). + * @param bssid uint8_t[6] Optional. BSSID / MAC of AP + * @param channel Optional. Channel of AP + * @param connect Optional. call connect + * @return + */ +wl_status_t WiFiSTAClass::begin(const char* ssid, const char *passphrase, int32_t channel, const uint8_t* bssid, bool connect) +{ + + if(!WiFi.enableSTA(true)) { + log_e("STA enable failed!"); + return WL_CONNECT_FAILED; + } + + if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) { + log_e("SSID too long or missing!"); + return WL_CONNECT_FAILED; + } + + if(passphrase && strlen(passphrase) > 64) { + log_e("passphrase too long!"); + return WL_CONNECT_FAILED; + } + + wifi_config_t conf; + memset(&conf, 0, sizeof(wifi_config_t)); + strcpy(reinterpret_cast(conf.sta.ssid), ssid); + + if(passphrase) { + if (strlen(passphrase) == 64){ // it's not a passphrase, is the PSK + memcpy(reinterpret_cast(conf.sta.password), passphrase, 64); + } else { + strcpy(reinterpret_cast(conf.sta.password), passphrase); + } + } + + if(bssid) { + conf.sta.bssid_set = 1; + memcpy((void *) &conf.sta.bssid[0], (void *) bssid, 6); + } + + if(channel > 0 && channel <= 13) { + conf.sta.channel = channel; + } + + wifi_config_t current_conf; + esp_wifi_get_config(WIFI_IF_STA, ¤t_conf); + if(!sta_config_equal(current_conf, conf)) { + if(esp_wifi_disconnect()){ + log_e("disconnect failed!"); + return WL_CONNECT_FAILED; + } + + esp_wifi_set_config(WIFI_IF_STA, &conf); + } else if(status() == WL_CONNECTED){ + return WL_CONNECTED; + } else { + esp_wifi_set_config(WIFI_IF_STA, &conf); + } + + if(!_useStaticIp) { + if(tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA) == ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED){ + log_e("dhcp client start failed!"); + return WL_CONNECT_FAILED; + } + } else { + tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); + } + + if(connect && esp_wifi_connect()) { + log_e("connect failed!"); + return WL_CONNECT_FAILED; + } + + return status(); +} + +wl_status_t WiFiSTAClass::begin(char* ssid, char *passphrase, int32_t channel, const uint8_t* bssid, bool connect) +{ + return begin((const char*) ssid, (const char*) passphrase, channel, bssid, connect); +} + +/** + * Use to connect to SDK config. + * @return wl_status_t + */ +wl_status_t WiFiSTAClass::begin() +{ + + if(!WiFi.enableSTA(true)) { + log_e("STA enable failed!"); + return WL_CONNECT_FAILED; + } + + wifi_config_t current_conf; + if(esp_wifi_get_config(WIFI_IF_STA, ¤t_conf) != ESP_OK || esp_wifi_set_config(WIFI_IF_STA, ¤t_conf) != ESP_OK) { + log_e("config failed"); + return WL_CONNECT_FAILED; + } + + if(!_useStaticIp) { + if(tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA) == ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED){ + log_e("dhcp client start failed!"); + return WL_CONNECT_FAILED; + } + } else { + tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); + } + + if(status() != WL_CONNECTED && esp_wifi_connect()){ + log_e("connect failed!"); + return WL_CONNECT_FAILED; + } + + return status(); +} + +/** + * will force a disconnect an then start reconnecting to AP + * @return ok + */ +bool WiFiSTAClass::reconnect() +{ + if(WiFi.getMode() & WIFI_MODE_STA) { + if(esp_wifi_disconnect() == ESP_OK) { + return esp_wifi_connect() == ESP_OK; + } + } + return false; +} + +/** + * Disconnect from the network + * @param wifioff + * @return one value of wl_status_t enum + */ +bool WiFiSTAClass::disconnect(bool wifioff, bool eraseap) +{ + wifi_config_t conf; + + if(WiFi.getMode() & WIFI_MODE_STA){ + if(eraseap){ + memset(&conf, 0, sizeof(wifi_config_t)); + if(esp_wifi_set_config(WIFI_IF_STA, &conf)){ + log_e("clear config failed!"); + } + } + if(esp_wifi_disconnect()){ + log_e("disconnect failed!"); + return false; + } + if(wifioff) { + return WiFi.enableSTA(false); + } + return true; + } + + return false; +} + +/** + * Change IP configuration settings disabling the dhcp client + * @param local_ip Static ip configuration + * @param gateway Static gateway configuration + * @param subnet Static Subnet mask + * @param dns1 Static DNS server 1 + * @param dns2 Static DNS server 2 + */ +bool WiFiSTAClass::config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2) +{ + esp_err_t err = ESP_OK; + + if(!WiFi.enableSTA(true)) { + return false; + } + + tcpip_adapter_ip_info_t info; + + if(local_ip != (uint32_t)0x00000000){ + info.ip.addr = static_cast(local_ip); + info.gw.addr = static_cast(gateway); + info.netmask.addr = static_cast(subnet); + } else { + info.ip.addr = 0; + info.gw.addr = 0; + info.netmask.addr = 0; + } + + err = tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); + if(err != ESP_OK && err != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED){ + log_e("DHCP could not be stopped! Error: %d", err); + return false; + } + + err = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &info); + if(err != ERR_OK){ + log_e("STA IP could not be configured! Error: %d", err); + return false; + } + + if(info.ip.addr){ + _useStaticIp = true; + } else { + err = tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA); + if(err == ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED){ + log_e("dhcp client start failed!"); + return false; + } + _useStaticIp = false; + } + + ip_addr_t d; + d.type = IPADDR_TYPE_V4; + + if(dns1 != (uint32_t)0x00000000) { + // Set DNS1-Server + d.u_addr.ip4.addr = static_cast(dns1); + dns_setserver(0, &d); + } + + if(dns2 != (uint32_t)0x00000000) { + // Set DNS2-Server + d.u_addr.ip4.addr = static_cast(dns2); + dns_setserver(1, &d); + } + + return true; +} + +/** + * is STA interface connected? + * @return true if STA is connected to an AD + */ +bool WiFiSTAClass::isConnected() +{ + return (status() == WL_CONNECTED); +} + + +/** + * Setting the ESP32 station to connect to the AP (which is recorded) + * automatically or not when powered on. Enable auto-connect by default. + * @param autoConnect bool + * @return if saved + */ +bool WiFiSTAClass::setAutoConnect(bool autoConnect) +{ + /*bool ret; + ret = esp_wifi_set_auto_connect(autoConnect); + return ret;*/ + return false;//now deprecated +} + +/** + * Checks if ESP32 station mode will connect to AP + * automatically or not when it is powered on. + * @return auto connect + */ +bool WiFiSTAClass::getAutoConnect() +{ + /*bool autoConnect; + esp_wifi_get_auto_connect(&autoConnect); + return autoConnect;*/ + return false;//now deprecated +} + +bool WiFiSTAClass::setAutoReconnect(bool autoReconnect) +{ + _autoReconnect = autoReconnect; + return true; +} + +bool WiFiSTAClass::getAutoReconnect() +{ + return _autoReconnect; +} + +/** + * Wait for WiFi connection to reach a result + * returns the status reached or disconnect if STA is off + * @return wl_status_t + */ +uint8_t WiFiSTAClass::waitForConnectResult() +{ + //1 and 3 have STA enabled + if((WiFiGenericClass::getMode() & WIFI_MODE_STA) == 0) { + return WL_DISCONNECTED; + } + int i = 0; + while((!status() || status() >= WL_DISCONNECTED) && i++ < 100) { + delay(100); + } + return status(); +} + +/** + * Get the station interface IP address. + * @return IPAddress station IP + */ +IPAddress WiFiSTAClass::localIP() +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + tcpip_adapter_ip_info_t ip; + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); + return IPAddress(ip.ip.addr); +} + + +/** + * Get the station interface MAC address. + * @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH + * @return pointer to uint8_t * + */ +uint8_t* WiFiSTAClass::macAddress(uint8_t* mac) +{ + if(WiFiGenericClass::getMode() != WIFI_MODE_NULL){ + esp_wifi_get_mac(WIFI_IF_STA, mac); + } + else{ + esp_read_mac(mac, ESP_MAC_WIFI_STA); + } + return mac; +} + +/** + * Get the station interface MAC address. + * @return String mac + */ +String WiFiSTAClass::macAddress(void) +{ + uint8_t mac[6]; + char macStr[18] = { 0 }; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + esp_read_mac(mac, ESP_MAC_WIFI_STA); + } + else{ + esp_wifi_get_mac(WIFI_IF_STA, mac); + } + sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + return String(macStr); +} + +/** + * Get the interface subnet mask address. + * @return IPAddress subnetMask + */ +IPAddress WiFiSTAClass::subnetMask() +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + tcpip_adapter_ip_info_t ip; + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); + return IPAddress(ip.netmask.addr); +} + +/** + * Get the gateway ip address. + * @return IPAddress gatewayIP + */ +IPAddress WiFiSTAClass::gatewayIP() +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + tcpip_adapter_ip_info_t ip; + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); + return IPAddress(ip.gw.addr); +} + +/** + * Get the DNS ip address. + * @param dns_no + * @return IPAddress DNS Server IP + */ +IPAddress WiFiSTAClass::dnsIP(uint8_t dns_no) +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + ip_addr_t dns_ip = dns_getserver(dns_no); + return IPAddress(dns_ip.u_addr.ip4.addr); +} + +/** + * Get the broadcast ip address. + * @return IPAddress broadcastIP + */ +IPAddress WiFiSTAClass::broadcastIP() +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + tcpip_adapter_ip_info_t ip; + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); + return WiFiGenericClass::calculateBroadcast(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr)); +} + +/** + * Get the network id. + * @return IPAddress networkID + */ +IPAddress WiFiSTAClass::networkID() +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPAddress(); + } + tcpip_adapter_ip_info_t ip; + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); + return WiFiGenericClass::calculateNetworkID(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr)); +} + +/** + * Get the subnet CIDR. + * @return uint8_t subnetCIDR + */ +uint8_t WiFiSTAClass::subnetCIDR() +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return (uint8_t)0; + } + tcpip_adapter_ip_info_t ip; + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip); + return WiFiGenericClass::calculateSubnetCIDR(IPAddress(ip.netmask.addr)); +} + +/** + * Return the current SSID associated with the network + * @return SSID + */ +String WiFiSTAClass::SSID() const +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_ap_record_t info; + if(!esp_wifi_sta_get_ap_info(&info)) { + return String(reinterpret_cast(info.ssid)); + } + return String(); +} + +/** + * Return the current pre shared key associated with the network + * @return psk string + */ +String WiFiSTAClass::psk() const +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.password)); +} + +/** + * Return the current bssid / mac associated with the network if configured + * @return bssid uint8_t * + */ +uint8_t* WiFiSTAClass::BSSID(void) +{ + static uint8_t bssid[6]; + wifi_ap_record_t info; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return NULL; + } + if(!esp_wifi_sta_get_ap_info(&info)) { + memcpy(bssid, info.bssid, 6); + return reinterpret_cast(bssid); + } + return NULL; +} + +/** + * Return the current bssid / mac associated with the network if configured + * @return String bssid mac + */ +String WiFiSTAClass::BSSIDstr(void) +{ + uint8_t* bssid = BSSID(); + if(!bssid){ + return String(); + } + char mac[18] = { 0 }; + sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]); + return String(mac); +} + +/** + * Return the current network RSSI. + * @return RSSI value + */ +int8_t WiFiSTAClass::RSSI(void) +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return 0; + } + wifi_ap_record_t info; + if(!esp_wifi_sta_get_ap_info(&info)) { + return info.rssi; + } + return 0; +} + +/** + * Get the station interface Host name. + * @return char array hostname + */ +const char * WiFiSTAClass::getHostname() +{ + const char * hostname = NULL; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return hostname; + } + if(tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_STA, &hostname)){ + return NULL; + } + return hostname; +} + +/** + * Set the station interface Host name. + * @param hostname pointer to const string + * @return true on success + */ +bool WiFiSTAClass::setHostname(const char * hostname) +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return false; + } + return tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, hostname) == 0; +} + +/** + * Enable IPv6 on the station interface. + * @return true on success + */ +bool WiFiSTAClass::enableIpV6() +{ + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return false; + } + return tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_STA) == 0; +} + +/** + * Get the station interface IPv6 address. + * @return IPv6Address + */ +IPv6Address WiFiSTAClass::localIPv6() +{ + static ip6_addr_t addr; + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return IPv6Address(); + } + if(tcpip_adapter_get_ip6_linklocal(TCPIP_ADAPTER_IF_STA, &addr)){ + return IPv6Address(); + } + return IPv6Address(addr.addr); +} + + +bool WiFiSTAClass::_smartConfigStarted = false; +bool WiFiSTAClass::_smartConfigDone = false; + + +bool WiFiSTAClass::beginSmartConfig() { + if (_smartConfigStarted) { + return false; + } + + if (!WiFi.mode(WIFI_STA)) { + return false; + } + + esp_wifi_disconnect(); + + esp_err_t err; + err = esp_smartconfig_start(reinterpret_cast(&WiFiSTAClass::_smartConfigCallback), 1); + if (err == ESP_OK) { + _smartConfigStarted = true; + _smartConfigDone = false; + return true; + } + return false; +} + +bool WiFiSTAClass::stopSmartConfig() { + if (!_smartConfigStarted) { + return true; + } + + if (esp_smartconfig_stop() == ESP_OK) { + _smartConfigStarted = false; + return true; + } + + return false; +} + +bool WiFiSTAClass::smartConfigDone() { + if (!_smartConfigStarted) { + return false; + } + + return _smartConfigDone; +} + +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG +const char * sc_status_strings[] = { + "WAIT", + "FIND_CHANNEL", + "GETTING_SSID_PSWD", + "LINK", + "LINK_OVER" +}; + +const char * sc_type_strings[] = { + "ESPTOUCH", + "AIRKISS", + "ESPTOUCH_AIRKISS" +}; +#endif + +void WiFiSTAClass::_smartConfigCallback(uint32_t st, void* result) { + smartconfig_status_t status = (smartconfig_status_t) st; + log_d("Status: %s", sc_status_strings[st % 5]); + if (status == SC_STATUS_GETTING_SSID_PSWD) { +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG + smartconfig_type_t * type = (smartconfig_type_t *)result; + log_d("Type: %s", sc_type_strings[*type % 3]); +#endif + } else if (status == SC_STATUS_LINK) { + wifi_sta_config_t *sta_conf = reinterpret_cast(result); + log_d("SSID: %s", (char *)(sta_conf->ssid)); + sta_conf->bssid_set = 0; + esp_wifi_set_config(WIFI_IF_STA, (wifi_config_t *)sta_conf); + esp_wifi_connect(); + _smartConfigDone = true; + } else if (status == SC_STATUS_LINK_OVER) { + if(result){ +#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG + ip4_addr_t * ip = (ip4_addr_t *)result; + log_d("Sender IP: " IPSTR, IP2STR(ip)); +#endif + } + WiFi.stopSmartConfig(); + } +} diff --git a/libraries/WiFi/src/WiFiSTA.h b/libraries/WiFi/src/WiFiSTA.h index a8137e09396..d9140101593 100644 --- a/libraries/WiFi/src/WiFiSTA.h +++ b/libraries/WiFi/src/WiFiSTA.h @@ -1,103 +1,106 @@ -/* - ESP8266WiFiSTA.h - esp8266 Wifi support. - Based on WiFi.h from Ardiono WiFi shield library. - Copyright (c) 2011-2014 Arduino. All right reserved. - Modified by Ivan Grokhotkov, December 2014 - Reworked by Markus Sattler, December 2015 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef ESP32WIFISTA_H_ -#define ESP32WIFISTA_H_ - - -#include "WiFiType.h" -#include "WiFiGeneric.h" - - -class WiFiSTAClass -{ - // ---------------------------------------------------------------------------------------------- - // ---------------------------------------- STA function ---------------------------------------- - // ---------------------------------------------------------------------------------------------- - -public: - - wl_status_t begin(const char* ssid, const char *passphrase = NULL, int32_t channel = 0, const uint8_t* bssid = NULL, bool connect = true); - wl_status_t begin(char* ssid, char *passphrase = NULL, int32_t channel = 0, const uint8_t* bssid = NULL, bool connect = true); - wl_status_t begin(); - - bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = (uint32_t)0x00000000, IPAddress dns2 = (uint32_t)0x00000000); - - bool reconnect(); - bool disconnect(bool wifioff = false); - - bool isConnected(); - - bool setAutoConnect(bool autoConnect); - bool getAutoConnect(); - - bool setAutoReconnect(bool autoReconnect); - bool getAutoReconnect(); - - uint8_t waitForConnectResult(); - - // STA network info - IPAddress localIP(); - - uint8_t * macAddress(uint8_t* mac); - String macAddress(); - - IPAddress subnetMask(); - IPAddress gatewayIP(); - IPAddress dnsIP(uint8_t dns_no = 0); - - bool enableIpV6(); - IPv6Address localIPv6(); - - const char * getHostname(); - bool setHostname(const char * hostname); - - // STA WiFi info - static wl_status_t status(); - String SSID() const; - String psk() const; - - uint8_t * BSSID(); - String BSSIDstr(); - - int8_t RSSI(); - - static void _setStatus(wl_status_t status); -protected: - static wl_status_t _status; - static bool _useStaticIp; - static bool _autoReconnect; - -public: - bool beginSmartConfig(); - bool stopSmartConfig(); - bool smartConfigDone(); - -protected: - static bool _smartConfigStarted; - static bool _smartConfigDone; - static void _smartConfigCallback(uint32_t status, void* result); - -}; - - -#endif /* ESP32WIFISTA_H_ */ +/* + ESP8266WiFiSTA.h - esp8266 Wifi support. + Based on WiFi.h from Ardiono WiFi shield library. + Copyright (c) 2011-2014 Arduino. All right reserved. + Modified by Ivan Grokhotkov, December 2014 + Reworked by Markus Sattler, December 2015 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef ESP32WIFISTA_H_ +#define ESP32WIFISTA_H_ + + +#include "WiFiType.h" +#include "WiFiGeneric.h" + + +class WiFiSTAClass +{ + // ---------------------------------------------------------------------------------------------- + // ---------------------------------------- STA function ---------------------------------------- + // ---------------------------------------------------------------------------------------------- + +public: + + wl_status_t begin(const char* ssid, const char *passphrase = NULL, int32_t channel = 0, const uint8_t* bssid = NULL, bool connect = true); + wl_status_t begin(char* ssid, char *passphrase = NULL, int32_t channel = 0, const uint8_t* bssid = NULL, bool connect = true); + wl_status_t begin(); + + bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = (uint32_t)0x00000000, IPAddress dns2 = (uint32_t)0x00000000); + + bool reconnect(); + bool disconnect(bool wifioff = false, bool eraseap = false); + + bool isConnected(); + + bool setAutoConnect(bool autoConnect); + bool getAutoConnect(); + + bool setAutoReconnect(bool autoReconnect); + bool getAutoReconnect(); + + uint8_t waitForConnectResult(); + + // STA network info + IPAddress localIP(); + + uint8_t * macAddress(uint8_t* mac); + String macAddress(); + + IPAddress subnetMask(); + IPAddress gatewayIP(); + IPAddress dnsIP(uint8_t dns_no = 0); + + IPAddress broadcastIP(); + IPAddress networkID(); + uint8_t subnetCIDR(); + + bool enableIpV6(); + IPv6Address localIPv6(); + + const char * getHostname(); + bool setHostname(const char * hostname); + + // STA WiFi info + static wl_status_t status(); + String SSID() const; + String psk() const; + + uint8_t * BSSID(); + String BSSIDstr(); + + int8_t RSSI(); + + static void _setStatus(wl_status_t status); +protected: + static bool _useStaticIp; + static bool _autoReconnect; + +public: + bool beginSmartConfig(); + bool stopSmartConfig(); + bool smartConfigDone(); + +protected: + static bool _smartConfigStarted; + static bool _smartConfigDone; + static void _smartConfigCallback(uint32_t status, void* result); + +}; + + +#endif /* ESP32WIFISTA_H_ */ diff --git a/libraries/WiFi/src/WiFiScan.cpp b/libraries/WiFi/src/WiFiScan.cpp index deddbd56d66..cabedbb8661 100644 --- a/libraries/WiFi/src/WiFiScan.cpp +++ b/libraries/WiFi/src/WiFiScan.cpp @@ -1,276 +1,281 @@ -/* - ESP8266WiFiScan.cpp - WiFi library for esp8266 - - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Reworked on 28 Dec 2015 by Markus Sattler - - */ - -#include "WiFi.h" -#include "WiFiGeneric.h" -#include "WiFiScan.h" - -extern "C" { -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "lwip/err.h" -} - -bool WiFiScanClass::_scanAsync = false; -bool WiFiScanClass::_scanStarted = false; -bool WiFiScanClass::_scanComplete = false; - -uint16_t WiFiScanClass::_scanCount = 0; -void* WiFiScanClass::_scanResult = 0; - -/** - * Start scan WiFi networks available - * @param async run in async mode - * @param show_hidden show hidden networks - * @return Number of discovered networks - */ -int8_t WiFiScanClass::scanNetworks(bool async, bool show_hidden, bool passive, uint32_t max_ms_per_chan) -{ - if(WiFiScanClass::_scanStarted) { - return WIFI_SCAN_RUNNING; - } - - WiFiScanClass::_scanAsync = async; - - WiFi.enableSTA(true); - - scanDelete(); - - wifi_scan_config_t config; - config.ssid = 0; - config.bssid = 0; - config.channel = 0; - config.show_hidden = show_hidden; - if(passive){ - config.scan_type = WIFI_SCAN_TYPE_PASSIVE; - config.scan_time.passive = max_ms_per_chan; - } else { - config.scan_type = WIFI_SCAN_TYPE_ACTIVE; - config.scan_time.active.min = 100; - config.scan_time.active.max = max_ms_per_chan; - } - if(esp_wifi_scan_start(&config, false) == ESP_OK) { - WiFiScanClass::_scanComplete = false; - WiFiScanClass::_scanStarted = true; - - if(WiFiScanClass::_scanAsync) { - return WIFI_SCAN_RUNNING; - } - while(!(WiFiScanClass::_scanComplete)) { - delay(10); - } - return WiFiScanClass::_scanCount; - } else { - return WIFI_SCAN_FAILED; - } - -} - - -/** - * private - * scan callback - * @param result void *arg - * @param status STATUS - */ -void WiFiScanClass::_scanDone() -{ - WiFiScanClass::_scanComplete = true; - WiFiScanClass::_scanStarted = false; - esp_wifi_scan_get_ap_num(&(WiFiScanClass::_scanCount)); - if(WiFiScanClass::_scanCount) { - WiFiScanClass::_scanResult = new wifi_ap_record_t[WiFiScanClass::_scanCount]; - if(WiFiScanClass::_scanResult) { - esp_wifi_scan_get_ap_records(&(WiFiScanClass::_scanCount), (wifi_ap_record_t*)_scanResult); - } else { - //no memory - WiFiScanClass::_scanCount = 0; - } - } -} - -/** - * - * @param i specify from which network item want to get the information - * @return bss_info * - */ -void * WiFiScanClass::_getScanInfoByIndex(int i) -{ - if(!WiFiScanClass::_scanResult || (size_t) i > WiFiScanClass::_scanCount) { - return 0; - } - return reinterpret_cast(WiFiScanClass::_scanResult) + i; -} - -/** - * called to get the scan state in Async mode - * @return scan result or status - * -1 if scan not fin - * -2 if scan not triggered - */ -int8_t WiFiScanClass::scanComplete() -{ - - if(_scanStarted) { - return WIFI_SCAN_RUNNING; - } - - if(_scanComplete) { - return WiFiScanClass::_scanCount; - } - - return WIFI_SCAN_FAILED; -} - -/** - * delete last scan result from RAM - */ -void WiFiScanClass::scanDelete() -{ - if(WiFiScanClass::_scanResult) { - delete[] reinterpret_cast(WiFiScanClass::_scanResult); - WiFiScanClass::_scanResult = 0; - WiFiScanClass::_scanCount = 0; - } - _scanComplete = false; -} - - -/** - * loads all infos from a scanned wifi in to the ptr parameters - * @param networkItem uint8_t - * @param ssid const char** - * @param encryptionType uint8_t * - * @param RSSI int32_t * - * @param BSSID uint8_t ** - * @param channel int32_t * - * @return (true if ok) - */ -bool WiFiScanClass::getNetworkInfo(uint8_t i, String &ssid, uint8_t &encType, int32_t &rssi, uint8_t* &bssid, int32_t &channel) -{ - wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); - if(!it) { - return false; - } - ssid = (const char*) it->ssid; - encType = it->authmode; - rssi = it->rssi; - bssid = it->bssid; - channel = it->primary; - return true; -} - - -/** - * Return the SSID discovered during the network scan. - * @param i specify from which network item want to get the information - * @return ssid string of the specified item on the networks scanned list - */ -String WiFiScanClass::SSID(uint8_t i) -{ - wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); - if(!it) { - return String(); - } - return String(reinterpret_cast(it->ssid)); -} - - -/** - * Return the encryption type of the networks discovered during the scanNetworks - * @param i specify from which network item want to get the information - * @return encryption type (enum wl_enc_type) of the specified item on the networks scanned list - */ -wifi_auth_mode_t WiFiScanClass::encryptionType(uint8_t i) -{ - wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); - if(!it) { - return WIFI_AUTH_OPEN; - } - return it->authmode; -} - -/** - * Return the RSSI of the networks discovered during the scanNetworks - * @param i specify from which network item want to get the information - * @return signed value of RSSI of the specified item on the networks scanned list - */ -int32_t WiFiScanClass::RSSI(uint8_t i) -{ - wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); - if(!it) { - return 0; - } - return it->rssi; -} - - -/** - * return MAC / BSSID of scanned wifi - * @param i specify from which network item want to get the information - * @return uint8_t * MAC / BSSID of scanned wifi - */ -uint8_t * WiFiScanClass::BSSID(uint8_t i) -{ - wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); - if(!it) { - return 0; - } - return it->bssid; -} - -/** - * return MAC / BSSID of scanned wifi - * @param i specify from which network item want to get the information - * @return String MAC / BSSID of scanned wifi - */ -String WiFiScanClass::BSSIDstr(uint8_t i) -{ - char mac[18] = { 0 }; - wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); - if(!it) { - return String(); - } - sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]); - return String(mac); -} - -int32_t WiFiScanClass::channel(uint8_t i) -{ - wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); - if(!it) { - return 0; - } - return it->primary; -} - +/* + ESP8266WiFiScan.cpp - WiFi library for esp8266 + + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Reworked on 28 Dec 2015 by Markus Sattler + + */ + + +#include "WiFi.h" +#include "WiFiGeneric.h" +#include "WiFiScan.h" + +extern "C" { +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "lwip/err.h" +} + +bool WiFiScanClass::_scanAsync = false; +uint32_t WiFiScanClass::_scanStarted = 0; +uint32_t WiFiScanClass::_scanTimeout = 10000; +uint16_t WiFiScanClass::_scanCount = 0; +void* WiFiScanClass::_scanResult = 0; + +/** + * Start scan WiFi networks available + * @param async run in async mode + * @param show_hidden show hidden networks + * @return Number of discovered networks + */ +int16_t WiFiScanClass::scanNetworks(bool async, bool show_hidden, bool passive, uint32_t max_ms_per_chan) +{ + if(WiFiGenericClass::getStatusBits() & WIFI_SCANNING_BIT) { + return WIFI_SCAN_RUNNING; + } + + WiFiScanClass::_scanTimeout = max_ms_per_chan * 20; + WiFiScanClass::_scanAsync = async; + + WiFi.enableSTA(true); + + scanDelete(); + + wifi_scan_config_t config; + config.ssid = 0; + config.bssid = 0; + config.channel = 0; + config.show_hidden = show_hidden; + if(passive){ + config.scan_type = WIFI_SCAN_TYPE_PASSIVE; + config.scan_time.passive = max_ms_per_chan; + } else { + config.scan_type = WIFI_SCAN_TYPE_ACTIVE; + config.scan_time.active.min = 100; + config.scan_time.active.max = max_ms_per_chan; + } + if(esp_wifi_scan_start(&config, false) == ESP_OK) { + _scanStarted = millis(); + if (!_scanStarted) { //Prevent 0 from millis overflow + ++_scanStarted; + } + + WiFiGenericClass::clearStatusBits(WIFI_SCAN_DONE_BIT); + WiFiGenericClass::setStatusBits(WIFI_SCANNING_BIT); + + if(WiFiScanClass::_scanAsync) { + return WIFI_SCAN_RUNNING; + } + if(WiFiGenericClass::waitStatusBits(WIFI_SCAN_DONE_BIT, 10000)){ + return (int16_t) WiFiScanClass::_scanCount; + } + } + return WIFI_SCAN_FAILED; +} + + +/** + * private + * scan callback + * @param result void *arg + * @param status STATUS + */ +void WiFiScanClass::_scanDone() +{ + esp_wifi_scan_get_ap_num(&(WiFiScanClass::_scanCount)); + if(WiFiScanClass::_scanCount) { + WiFiScanClass::_scanResult = new wifi_ap_record_t[WiFiScanClass::_scanCount]; + if(!WiFiScanClass::_scanResult || esp_wifi_scan_get_ap_records(&(WiFiScanClass::_scanCount), (wifi_ap_record_t*)_scanResult) != ESP_OK) { + WiFiScanClass::_scanCount = 0; + } + } + WiFiScanClass::_scanStarted=0; //Reset after a scan is completed for normal behavior + WiFiGenericClass::setStatusBits(WIFI_SCAN_DONE_BIT); + WiFiGenericClass::clearStatusBits(WIFI_SCANNING_BIT); +} + +/** + * + * @param i specify from which network item want to get the information + * @return bss_info * + */ +void * WiFiScanClass::_getScanInfoByIndex(int i) +{ + if(!WiFiScanClass::_scanResult || (size_t) i >= WiFiScanClass::_scanCount) { + return 0; + } + return reinterpret_cast(WiFiScanClass::_scanResult) + i; +} + +/** + * called to get the scan state in Async mode + * @return scan result or status + * -1 if scan not fin + * -2 if scan not triggered + */ +int16_t WiFiScanClass::scanComplete() +{ + if (WiFiScanClass::_scanStarted && (millis()-WiFiScanClass::_scanStarted) > WiFiScanClass::_scanTimeout) { //Check is scan was started and if the delay expired, return WIFI_SCAN_FAILED in this case + WiFiGenericClass::clearStatusBits(WIFI_SCANNING_BIT); + return WIFI_SCAN_FAILED; + } + + if(WiFiGenericClass::getStatusBits() & WIFI_SCAN_DONE_BIT) { + return WiFiScanClass::_scanCount; + } + + if(WiFiGenericClass::getStatusBits() & WIFI_SCANNING_BIT) { + return WIFI_SCAN_RUNNING; + } + + return WIFI_SCAN_FAILED; +} + +/** + * delete last scan result from RAM + */ +void WiFiScanClass::scanDelete() +{ + WiFiGenericClass::clearStatusBits(WIFI_SCAN_DONE_BIT); + if(WiFiScanClass::_scanResult) { + delete[] reinterpret_cast(WiFiScanClass::_scanResult); + WiFiScanClass::_scanResult = 0; + WiFiScanClass::_scanCount = 0; + } +} + + +/** + * loads all infos from a scanned wifi in to the ptr parameters + * @param networkItem uint8_t + * @param ssid const char** + * @param encryptionType uint8_t * + * @param RSSI int32_t * + * @param BSSID uint8_t ** + * @param channel int32_t * + * @return (true if ok) + */ +bool WiFiScanClass::getNetworkInfo(uint8_t i, String &ssid, uint8_t &encType, int32_t &rssi, uint8_t* &bssid, int32_t &channel) +{ + wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); + if(!it) { + return false; + } + ssid = (const char*) it->ssid; + encType = it->authmode; + rssi = it->rssi; + bssid = it->bssid; + channel = it->primary; + return true; +} + + +/** + * Return the SSID discovered during the network scan. + * @param i specify from which network item want to get the information + * @return ssid string of the specified item on the networks scanned list + */ +String WiFiScanClass::SSID(uint8_t i) +{ + wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); + if(!it) { + return String(); + } + return String(reinterpret_cast(it->ssid)); +} + + +/** + * Return the encryption type of the networks discovered during the scanNetworks + * @param i specify from which network item want to get the information + * @return encryption type (enum wl_enc_type) of the specified item on the networks scanned list + */ +wifi_auth_mode_t WiFiScanClass::encryptionType(uint8_t i) +{ + wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); + if(!it) { + return WIFI_AUTH_OPEN; + } + return it->authmode; +} + +/** + * Return the RSSI of the networks discovered during the scanNetworks + * @param i specify from which network item want to get the information + * @return signed value of RSSI of the specified item on the networks scanned list + */ +int32_t WiFiScanClass::RSSI(uint8_t i) +{ + wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); + if(!it) { + return 0; + } + return it->rssi; +} + + +/** + * return MAC / BSSID of scanned wifi + * @param i specify from which network item want to get the information + * @return uint8_t * MAC / BSSID of scanned wifi + */ +uint8_t * WiFiScanClass::BSSID(uint8_t i) +{ + wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); + if(!it) { + return 0; + } + return it->bssid; +} + +/** + * return MAC / BSSID of scanned wifi + * @param i specify from which network item want to get the information + * @return String MAC / BSSID of scanned wifi + */ +String WiFiScanClass::BSSIDstr(uint8_t i) +{ + char mac[18] = { 0 }; + wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); + if(!it) { + return String(); + } + sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]); + return String(mac); +} + +int32_t WiFiScanClass::channel(uint8_t i) +{ + wifi_ap_record_t* it = reinterpret_cast(_getScanInfoByIndex(i)); + if(!it) { + return 0; + } + return it->primary; +} + diff --git a/libraries/WiFi/src/WiFiScan.h b/libraries/WiFi/src/WiFiScan.h index 38feaa15147..3ddcbeac692 100644 --- a/libraries/WiFi/src/WiFiScan.h +++ b/libraries/WiFi/src/WiFiScan.h @@ -1,64 +1,66 @@ -/* - ESP8266WiFiScan.h - esp8266 Wifi support. - Based on WiFi.h from Ardiono WiFi shield library. - Copyright (c) 2011-2014 Arduino. All right reserved. - Modified by Ivan Grokhotkov, December 2014 - Reworked by Markus Sattler, December 2015 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef ESP32WIFISCAN_H_ -#define ESP32WIFISCAN_H_ - -#include "WiFiType.h" -#include "WiFiGeneric.h" - -class WiFiScanClass -{ - -public: - - int8_t scanNetworks(bool async = false, bool show_hidden = false, bool passive = false, uint32_t max_ms_per_chan = 300); - - int8_t scanComplete(); - void scanDelete(); - - // scan result - bool getNetworkInfo(uint8_t networkItem, String &ssid, uint8_t &encryptionType, int32_t &RSSI, uint8_t* &BSSID, int32_t &channel); - - String SSID(uint8_t networkItem); - wifi_auth_mode_t encryptionType(uint8_t networkItem); - int32_t RSSI(uint8_t networkItem); - uint8_t * BSSID(uint8_t networkItem); - String BSSIDstr(uint8_t networkItem); - int32_t channel(uint8_t networkItem); - - static void _scanDone(); -protected: - - static bool _scanAsync; - static bool _scanStarted; - static bool _scanComplete; - - static uint16_t _scanCount; - static void* _scanResult; - - static void * _getScanInfoByIndex(int i); - -}; - - -#endif /* ESP32WIFISCAN_H_ */ +/* + ESP8266WiFiScan.h - esp8266 Wifi support. + Based on WiFi.h from Ardiono WiFi shield library. + Copyright (c) 2011-2014 Arduino. All right reserved. + Modified by Ivan Grokhotkov, December 2014 + Reworked by Markus Sattler, December 2015 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef ESP32WIFISCAN_H_ +#define ESP32WIFISCAN_H_ + +#include "WiFiType.h" +#include "WiFiGeneric.h" + +class WiFiScanClass +{ + +public: + + int16_t scanNetworks(bool async = false, bool show_hidden = false, bool passive = false, uint32_t max_ms_per_chan = 300); + + int16_t scanComplete(); + void scanDelete(); + + // scan result + bool getNetworkInfo(uint8_t networkItem, String &ssid, uint8_t &encryptionType, int32_t &RSSI, uint8_t* &BSSID, int32_t &channel); + + String SSID(uint8_t networkItem); + wifi_auth_mode_t encryptionType(uint8_t networkItem); + int32_t RSSI(uint8_t networkItem); + uint8_t * BSSID(uint8_t networkItem); + String BSSIDstr(uint8_t networkItem); + int32_t channel(uint8_t networkItem); + static void * getScanInfoByIndex(int i) { return _getScanInfoByIndex(i); }; + + static void _scanDone(); +protected: + + static bool _scanAsync; + + static uint32_t _scanStarted; + static uint32_t _scanTimeout; + static uint16_t _scanCount; + + static void* _scanResult; + + static void * _getScanInfoByIndex(int i); + +}; + + +#endif /* ESP32WIFISCAN_H_ */ diff --git a/libraries/WiFi/src/WiFiServer.cpp b/libraries/WiFi/src/WiFiServer.cpp index ef326765f63..75c2872bb78 100644 --- a/libraries/WiFi/src/WiFiServer.cpp +++ b/libraries/WiFi/src/WiFiServer.cpp @@ -62,9 +62,12 @@ WiFiClient WiFiServer::available(){ return WiFiClient(); } -void WiFiServer::begin(){ +void WiFiServer::begin(uint16_t port){ if(_listening) return; + if(port){ + _port = port; + } struct sockaddr_in server; sockfd = socket(AF_INET , SOCK_STREAM, 0); if (sockfd < 0) diff --git a/libraries/WiFi/src/WiFiServer.h b/libraries/WiFi/src/WiFiServer.h index 0c3cac9547a..34952cc694b 100644 --- a/libraries/WiFi/src/WiFiServer.h +++ b/libraries/WiFi/src/WiFiServer.h @@ -39,7 +39,7 @@ class WiFiServer : public Server { ~WiFiServer(){ end();} WiFiClient available(); WiFiClient accept(){return available();} - void begin(); + void begin(uint16_t port=0); void setNoDelay(bool nodelay); bool getNoDelay(); bool hasClient(); diff --git a/libraries/WiFi/src/WiFiType.h b/libraries/WiFi/src/WiFiType.h index c4b0910648d..cce29eea4a2 100644 --- a/libraries/WiFi/src/WiFiType.h +++ b/libraries/WiFi/src/WiFiType.h @@ -1,48 +1,51 @@ -/* - ESP8266WiFiType.h - esp8266 Wifi support. - Copyright (c) 2011-2014 Arduino. All right reserved. - Modified by Ivan Grokhotkov, December 2014 - Reworked by Markus Sattler, December 2015 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#ifndef ESP32WIFITYPE_H_ -#define ESP32WIFITYPE_H_ - -#define WIFI_SCAN_RUNNING (-1) -#define WIFI_SCAN_FAILED (-2) - -#define WiFiMode_t wifi_mode_t -#define WIFI_OFF WIFI_MODE_NULL -#define WIFI_STA WIFI_MODE_STA -#define WIFI_AP WIFI_MODE_AP -#define WIFI_AP_STA WIFI_MODE_APSTA - -#define WiFiEvent_t system_event_id_t - -typedef enum { - WL_NO_SHIELD = 255, // for compatibility with WiFi Shield library - WL_IDLE_STATUS = 0, - WL_NO_SSID_AVAIL = 1, - WL_SCAN_COMPLETED = 2, - WL_CONNECTED = 3, - WL_CONNECT_FAILED = 4, - WL_CONNECTION_LOST = 5, - WL_DISCONNECTED = 6 -} wl_status_t; - -#endif /* ESP32WIFITYPE_H_ */ +/* + ESP8266WiFiType.h - esp8266 Wifi support. + Copyright (c) 2011-2014 Arduino. All right reserved. + Modified by Ivan Grokhotkov, December 2014 + Reworked by Markus Sattler, December 2015 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + +#ifndef ESP32WIFITYPE_H_ +#define ESP32WIFITYPE_H_ + +#define WIFI_SCAN_RUNNING (-1) +#define WIFI_SCAN_FAILED (-2) + +#define WiFiMode_t wifi_mode_t +#define WIFI_OFF WIFI_MODE_NULL +#define WIFI_STA WIFI_MODE_STA +#define WIFI_AP WIFI_MODE_AP +#define WIFI_AP_STA WIFI_MODE_APSTA + +#define WiFiEvent_t system_event_id_t +#define WiFiEventInfo_t system_event_info_t +#define WiFiEventId_t wifi_event_id_t + + +typedef enum { + WL_NO_SHIELD = 255, // for compatibility with WiFi Shield library + WL_IDLE_STATUS = 0, + WL_NO_SSID_AVAIL = 1, + WL_SCAN_COMPLETED = 2, + WL_CONNECTED = 3, + WL_CONNECT_FAILED = 4, + WL_CONNECTION_LOST = 5, + WL_DISCONNECTED = 6 +} wl_status_t; + +#endif /* ESP32WIFITYPE_H_ */ diff --git a/libraries/WiFi/src/WiFiUdp.cpp b/libraries/WiFi/src/WiFiUdp.cpp index 4e6db72a614..476b5a4a8b5 100644 --- a/libraries/WiFi/src/WiFiUdp.cpp +++ b/libraries/WiFi/src/WiFiUdp.cpp @@ -221,8 +221,10 @@ int WiFiUDP::parsePacket(){ } remote_ip = IPAddress(si_other.sin_addr.s_addr); remote_port = ntohs(si_other.sin_port); - rx_buffer = new cbuf(len); - rx_buffer->write(buf, len); + if (len > 0) { + rx_buffer = new cbuf(len); + rx_buffer->write(buf, len); + } delete[] buf; return len; } @@ -264,6 +266,7 @@ int WiFiUDP::peek(){ } void WiFiUDP::flush(){ + if(!rx_buffer) return; cbuf *b = rx_buffer; rx_buffer = 0; delete b; diff --git a/libraries/WiFiClientSecure/README.md b/libraries/WiFiClientSecure/README.md new file mode 100644 index 00000000000..10ac26ccaa5 --- /dev/null +++ b/libraries/WiFiClientSecure/README.md @@ -0,0 +1,67 @@ +WiFiClientSecure +================ + +The WiFiClientSecure class implements support for secure connections using TLS (SSL). +It inherits from WiFiClient and thus implements a superset of that class' interface. +There are three ways to establish a secure connection using the WiFiClientSecure class: +using a root certificate authority (CA) cert, using a root CA cert plus a client cert and key, +and using a pre-shared key (PSK). + +Using a root certificate authority cert +--------------------------------------- +This method authenticates the server and negotiates an encrypted connection. +It is the same functionality as implemented in your web browser when you connect to HTTPS sites. + +If you are accessing your own server: +- Generate a root certificate for your own certificate authority +- Generate a cert & private key using your root certificate ("self-signed cert") for your server +If you are accessing a public server: +- Obtain the cert of the public CA that signed that server's cert +Then: +- In WiFiClientSecure use setCACert (or the appropriate connect method) to set the root cert of your + CA or of the public CA +- When WiFiClientSecure connects to the target server it uses the CA cert to verify the certificate + presented by the server, and then negotiates encryption for the connection + +Please see the WiFiClientSecure example. + +Using a root CA cert and client cert/keys +----------------------------------------- +This method authenticates the server and additionally also authenticates +the client to the server, then negotiates an encrypted connection. + +- Follow steps above +- Using your root CA generate cert/key for your client +- Register the keys with the server you will be accessing so the server can authenticate your client +- In WiFiClientSecure use setCACert (or the appropriate connect method) to set the root cert of your + CA or of the public CA, this is used to authenticate the server +- In WiFiClientSecure use setCertificate, and setPrivateKey (or the appropriate connect method) to + set your client's cert & key, this will be used to authenticate your client to the server +- When WiFiClientSecure connects to the target server it uses the CA cert to verify the certificate + presented by the server, it will use the cert/key to authenticate your client to the server, and + it will then negotiate encryption for the connection + +Using Pre-Shared Keys (PSK) +--------------------------- + +TLS supports authentication and encryption using a pre-shared key (i.e. a key that both client and +server know) as an alternative to the public key cryptography commonly used on the web for HTTPS. +PSK is starting to be used for MQTT, e.g. in mosquitto, to simplify the set-up and avoid having to +go through the whole CA, cert, and private key process. + +A pre-shared key is a binary string of up to 32 bytes and is commonly represented in hex form. In +addition to the key, clients can also present an id and typically the server allows a different key +to be associated with each client id. In effect this is very similar to username and password pairs, +except that unlike a password the key is not directly transmitted to the server, thus a connection to a +malicious server does not divulge the password. Plus the server is also authenticated to the client. + +To use PSK: +- Generate a random hex string (generating an MD5 or SHA for some file is one way to do this) +- Come up with a string id for your client and configure your server to accept the id/key pair +- In WiFiClientSecure use setPreSharedKey (or the appropriate connect method) to + set the id/key combo +- When WiFiClientSecure connects to the target server it uses the id/key combo to authenticate the + server (it must prove that it has the key too), authenticate the client and then negotiate + encryption for the connection + +Please see the WiFiClientPSK example. diff --git a/libraries/WiFiClientSecure/examples/WiFiClientPSK/WiFiClientPSK.ino b/libraries/WiFiClientSecure/examples/WiFiClientPSK/WiFiClientPSK.ino new file mode 100644 index 00000000000..bd3ffbeda05 --- /dev/null +++ b/libraries/WiFiClientSecure/examples/WiFiClientPSK/WiFiClientPSK.ino @@ -0,0 +1,85 @@ +/* + Wifi secure connection example for ESP32 using a pre-shared key (PSK) + This is useful with MQTT servers instead of using a self-signed cert, tested with mosquitto. + Running on TLS 1.2 using mbedTLS + + To test run a test server using: openssl s_server -accept 8443 -psk 1a2b3c4d -nocert + It will show the http request made, but there's no easy way to send a reply back... + + 2017 - Evandro Copercini - Apache 2.0 License. + 2018 - Adapted for PSK by Thorsten von Eicken +*/ + +#include + +#if 0 +const char* ssid = "your-ssid"; // your network SSID (name of wifi network) +const char* password = "your-password"; // your network password +#else +const char* ssid = "test"; // your network SSID (name of wifi network) +const char* password = "securetest"; // your network password +#endif + +//const char* server = "server.local"; // Server hostname +const IPAddress server = IPAddress(192, 168, 0, 14); // Server IP address +const int port = 8443; // server's port (8883 for MQTT) + +const char* pskIdent = "Client_identity"; // PSK identity (sometimes called key hint) +const char* psKey = "1a2b3c4d"; // PSK Key (must be hex string without 0x) + +WiFiClientSecure client; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(115200); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + client.setPreSharedKey(pskIdent, psKey); + + Serial.println("\nStarting connection to server..."); + if (!client.connect(server, port)) + Serial.println("Connection failed!"); + else { + Serial.println("Connected to server!"); + // Make a HTTP request: + client.println("GET /a/check HTTP/1.0"); + client.print("Host: "); + client.println(server); + client.println("Connection: close"); + client.println(); + + while (client.connected()) { + String line = client.readStringUntil('\n'); + if (line == "\r") { + Serial.println("headers received"); + break; + } + } + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + client.stop(); + } +} + +void loop() { + // do nothing +} diff --git a/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino b/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino index 030693c2915..a49ec21e19f 100644 --- a/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino +++ b/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino @@ -107,4 +107,4 @@ void setup() { void loop() { // do nothing -} +} diff --git a/libraries/WiFiClientSecure/examples/WiFiClientSecureEnterprise/WiFiClientSecureEnterprise.ino b/libraries/WiFiClientSecure/examples/WiFiClientSecureEnterprise/WiFiClientSecureEnterprise.ino new file mode 100644 index 00000000000..d4e389c2440 --- /dev/null +++ b/libraries/WiFiClientSecure/examples/WiFiClientSecureEnterprise/WiFiClientSecureEnterprise.ino @@ -0,0 +1,117 @@ +/*|-----------------------------------------------------------|*/ +/*|WORKING EXAMPLE FOR HTTPS CONNECTION |*/ +/*|Author: Bc. Martin Chlebovec |*/ +/*|Technical University of Košice |*/ +/*|TESTED BOARDS: Devkit v1 DOIT, Devkitc v4 |*/ +/*|CORE: 0.9x, 1.0.0, 1.0.1 tested, working (newer not tested)|*/ +/*|Supported methods: PEAP + MsCHAPv2, EAP-TTLS + MsCHAPv2 |*/ +/*|-----------------------------------------------------------|*/ + +#include +#include +#include "esp_wpa2.h" +#include +#define EAP_ANONYMOUS_IDENTITY "anonymous@example.com" //anonymous identity +#define EAP_IDENTITY "id@example.com" //user identity +#define EAP_PASSWORD "password" //eduroam user password +const char* ssid = "eduroam"; // eduroam SSID +const char* host = "arduino.php5.sk"; //external server domain for HTTPS connection +int counter = 0; +const char* test_root_ca = \ + "-----BEGIN CERTIFICATE-----\n" \ + "MIIEsTCCA5mgAwIBAgIQCKWiRs1LXIyD1wK0u6tTSTANBgkqhkiG9w0BAQsFADBh\n" \ + "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ + "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ + "QTAeFw0xNzExMDYxMjIzMzNaFw0yNzExMDYxMjIzMzNaMF4xCzAJBgNVBAYTAlVT\n" \ + "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ + "b20xHTAbBgNVBAMTFFJhcGlkU1NMIFJTQSBDQSAyMDE4MIIBIjANBgkqhkiG9w0B\n" \ + "AQEFAAOCAQ8AMIIBCgKCAQEA5S2oihEo9nnpezoziDtx4WWLLCll/e0t1EYemE5n\n" \ + "+MgP5viaHLy+VpHP+ndX5D18INIuuAV8wFq26KF5U0WNIZiQp6mLtIWjUeWDPA28\n" \ + "OeyhTlj9TLk2beytbtFU6ypbpWUltmvY5V8ngspC7nFRNCjpfnDED2kRyJzO8yoK\n" \ + "MFz4J4JE8N7NA1uJwUEFMUvHLs0scLoPZkKcewIRm1RV2AxmFQxJkdf7YN9Pckki\n" \ + "f2Xgm3b48BZn0zf0qXsSeGu84ua9gwzjzI7tbTBjayTpT+/XpWuBVv6fvarI6bik\n" \ + "KB859OSGQuw73XXgeuFwEPHTIRoUtkzu3/EQ+LtwznkkdQIDAQABo4IBZjCCAWIw\n" \ + "HQYDVR0OBBYEFFPKF1n8a8ADIS8aruSqqByCVtp1MB8GA1UdIwQYMBaAFAPeUDVW\n" \ + "0Uy7ZvCj4hsbw5eyPdFVMA4GA1UdDwEB/wQEAwIBhjAdBgNVHSUEFjAUBggrBgEF\n" \ + "BQcDAQYIKwYBBQUHAwIwEgYDVR0TAQH/BAgwBgEB/wIBADA0BggrBgEFBQcBAQQo\n" \ + "MCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBCBgNVHR8E\n" \ + "OzA5MDegNaAzhjFodHRwOi8vY3JsMy5kaWdpY2VydC5jb20vRGlnaUNlcnRHbG9i\n" \ + "YWxSb290Q0EuY3JsMGMGA1UdIARcMFowNwYJYIZIAYb9bAECMCowKAYIKwYBBQUH\n" \ + "AgEWHGh0dHBzOi8vd3d3LmRpZ2ljZXJ0LmNvbS9DUFMwCwYJYIZIAYb9bAEBMAgG\n" \ + "BmeBDAECATAIBgZngQwBAgIwDQYJKoZIhvcNAQELBQADggEBAH4jx/LKNW5ZklFc\n" \ + "YWs8Ejbm0nyzKeZC2KOVYR7P8gevKyslWm4Xo4BSzKr235FsJ4aFt6yAiv1eY0tZ\n" \ + "/ZN18bOGSGStoEc/JE4ocIzr8P5Mg11kRYHbmgYnr1Rxeki5mSeb39DGxTpJD4kG\n" \ + "hs5lXNoo4conUiiJwKaqH7vh2baryd8pMISag83JUqyVGc2tWPpO0329/CWq2kry\n" \ + "qv66OSMjwulUz0dXf4OHQasR7CNfIr+4KScc6ABlQ5RDF86PGeE6kdwSQkFiB/cQ\n" \ + "ysNyq0jEDQTkfa2pjmuWtMCNbBnhFXBYejfubIhaUbEv2FOQB3dCav+FPg5eEveX\n" \ + "TVyMnGo=\n" \ + "-----END CERTIFICATE-----\n"; +// You can use x.509 client certificates if you want +//const char* test_client_key = ""; //to verify the client +//const char* test_client_cert = ""; //to verify the client +WiFiClientSecure client; +void setup() { + Serial.begin(115200); + delay(10); + Serial.println(); + Serial.print("Connecting to network: "); + Serial.println(ssid); + WiFi.disconnect(true); //disconnect form wifi to set new wifi connection + WiFi.mode(WIFI_STA); //init wifi mode + esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)EAP_ANONYMOUS_IDENTITY, strlen(EAP_ANONYMOUS_IDENTITY)); //provide identity + esp_wifi_sta_wpa2_ent_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide username + esp_wifi_sta_wpa2_ent_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD)); //provide password + esp_wpa2_config_t config = WPA2_CONFIG_INIT_DEFAULT(); + esp_wifi_sta_wpa2_ent_enable(&config); + WiFi.begin(ssid); //connect to wifi + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + counter++; + if (counter >= 60) { //after 30 seconds timeout - reset board (on unsucessful connection) + ESP.restart(); + } + } + client.setCACert(test_root_ca); + //client.setCertificate(test_client_key); // for client verification - certificate + //client.setPrivateKey(test_client_cert); // for client verification - private key + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address set: "); + Serial.println(WiFi.localIP()); //print LAN IP +} +void loop() { + if (WiFi.status() == WL_CONNECTED) { //if we are connected to eduroam network + counter = 0; //reset counter + Serial.println("Wifi is still connected with IP: "); + Serial.println(WiFi.localIP()); //inform user about his IP address + } else if (WiFi.status() != WL_CONNECTED) { //if we lost connection, retry + WiFi.begin(ssid); + } + while (WiFi.status() != WL_CONNECTED) { //during lost connection, print dots + delay(500); + Serial.print("."); + counter++; + if (counter >= 60) { //30 seconds timeout - reset board + ESP.restart(); + } + } + Serial.print("Connecting to website: "); + Serial.println(host); + if (client.connect(host, 443)) { + String url = "/rele/rele1.txt"; + client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "User-Agent: ESP32\r\n" + "Connection: close\r\n\r\n"); + while (client.connected()) { + String header = client.readStringUntil('\n'); + Serial.println(header); + if (header == "\r") { + break; + } + } + String line = client.readStringUntil('\n'); + Serial.println(line); + } else { + Serial.println("Connection unsucessful"); + } + delay(5000); +} diff --git a/libraries/WiFiClientSecure/src/WiFiClientSecure.cpp b/libraries/WiFiClientSecure/src/WiFiClientSecure.cpp index f40e4707fc5..3f545c6723c 100644 --- a/libraries/WiFiClientSecure/src/WiFiClientSecure.cpp +++ b/libraries/WiFiClientSecure/src/WiFiClientSecure.cpp @@ -1,222 +1,336 @@ -/* - WiFiClientSecure.cpp - Client Secure class for ESP32 - Copyright (c) 2016 Hristo Gochkov All right reserved. - Additions Copyright (C) 2017 Evandro Luis Copercini. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "WiFiClientSecure.h" -#include -#include -#include - -#undef connect -#undef write -#undef read - - -WiFiClientSecure::WiFiClientSecure() -{ - _connected = false; - - sslclient = new sslclient_context; - ssl_init(sslclient); - sslclient->socket = -1; - - _CA_cert = NULL; - _cert = NULL; - _private_key = NULL; - next = NULL; -} - - -WiFiClientSecure::WiFiClientSecure(int sock) -{ - _connected = false; - - sslclient = new sslclient_context; - ssl_init(sslclient); - sslclient->socket = sock; - - if (sock >= 0) { - _connected = true; - } - - _CA_cert = NULL; - _cert = NULL; - _private_key = NULL; - next = NULL; -} - -WiFiClientSecure::~WiFiClientSecure() -{ - stop(); - delete sslclient; -} - -WiFiClientSecure &WiFiClientSecure::operator=(const WiFiClientSecure &other) -{ - stop(); - sslclient->socket = other.sslclient->socket; - _connected = other._connected; - return *this; -} - -void WiFiClientSecure::stop() -{ - if (sslclient->socket >= 0) { - close(sslclient->socket); - sslclient->socket = -1; - _connected = false; - } - stop_ssl_socket(sslclient, _CA_cert, _cert, _private_key); -} - -int WiFiClientSecure::connect(IPAddress ip, uint16_t port) -{ - return connect(ip, port, _CA_cert, _cert, _private_key); -} - -int WiFiClientSecure::connect(const char *host, uint16_t port) -{ - return connect(host, port, _CA_cert, _cert, _private_key); -} - -int WiFiClientSecure::connect(IPAddress ip, uint16_t port, const char *_CA_cert, const char *_cert, const char *_private_key) -{ - return connect(ip.toString().c_str(), port, _CA_cert, _cert, _private_key); -} - -int WiFiClientSecure::connect(const char *host, uint16_t port, const char *_CA_cert, const char *_cert, const char *_private_key) -{ - int ret = start_ssl_client(sslclient, host, port, _CA_cert, _cert, _private_key); - _lastError = ret; - if (ret < 0) { - log_e("lwip_connect_r: %d", errno); - stop(); - return 0; - } - _connected = true; - return 1; -} - -int WiFiClientSecure::peek(){ - if(_peek >= 0){ - return _peek; - } - _peek = read(); - return _peek; -} - -size_t WiFiClientSecure::write(uint8_t data) -{ - return write(&data, 1); -} - -int WiFiClientSecure::read() -{ - uint8_t data = -1; - - if(_peek >= 0){ - data = _peek; - _peek = -1; - return data; - } - - int res = read(&data, 1); - if (res < 0) { - return res; - } - return data; -} - -size_t WiFiClientSecure::write(const uint8_t *buf, size_t size) -{ - if (!_connected) { - return 0; - } - int res = send_ssl_data(sslclient, buf, size); - if (res < 0) { - stop(); - res = 0; - } - return res; -} - -int WiFiClientSecure::read(uint8_t *buf, size_t size) -{ - if(_peek >= 0){ - uint8_t data = -1; - data = _peek; - _peek = -1; - return data; - } - - if (!available()) { - return -1; - } - int res = get_ssl_receive(sslclient, buf, size); - if (res < 0) { - stop(); - } - return res; -} - -int WiFiClientSecure::available() -{ - if (!_connected) { - return 0; - } - int res = data_to_read(sslclient); - if (res < 0 ) { - stop(); - } - return res; -} - -uint8_t WiFiClientSecure::connected() -{ - uint8_t dummy = 0; - read(&dummy, 0); - - return _connected; -} - -void WiFiClientSecure::setCACert (const char *rootCA) -{ - _CA_cert = rootCA; -} - -void WiFiClientSecure::setCertificate (const char *client_ca) -{ - _cert = client_ca; -} - -void WiFiClientSecure::setPrivateKey (const char *private_key) -{ - _private_key = private_key; -} - -int WiFiClientSecure::lastError(char *buf, const size_t size) -{ - if (!_lastError) { - return 0; - } - char error_buf[100]; - mbedtls_strerror(_lastError, error_buf, 100); - snprintf(buf, size, "%s", error_buf); - return _lastError; -} +/* + WiFiClientSecure.cpp - Client Secure class for ESP32 + Copyright (c) 2016 Hristo Gochkov All right reserved. + Additions Copyright (C) 2017 Evandro Luis Copercini. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "WiFiClientSecure.h" +#include +#include +#include + +#undef connect +#undef write +#undef read + + +WiFiClientSecure::WiFiClientSecure() +{ + _connected = false; + + sslclient = new sslclient_context; + ssl_init(sslclient); + sslclient->socket = -1; + sslclient->handshake_timeout = 120000; + _CA_cert = NULL; + _cert = NULL; + _private_key = NULL; + _pskIdent = NULL; + _psKey = NULL; + next = NULL; +} + + +WiFiClientSecure::WiFiClientSecure(int sock) +{ + _connected = false; + _timeout = 0; + + sslclient = new sslclient_context; + ssl_init(sslclient); + sslclient->socket = sock; + sslclient->handshake_timeout = 120000; + + if (sock >= 0) { + _connected = true; + } + + _CA_cert = NULL; + _cert = NULL; + _private_key = NULL; + _pskIdent = NULL; + _psKey = NULL; + next = NULL; +} + +WiFiClientSecure::~WiFiClientSecure() +{ + stop(); + delete sslclient; +} + +WiFiClientSecure &WiFiClientSecure::operator=(const WiFiClientSecure &other) +{ + stop(); + sslclient->socket = other.sslclient->socket; + _connected = other._connected; + return *this; +} + +void WiFiClientSecure::stop() +{ + if (sslclient->socket >= 0) { + close(sslclient->socket); + sslclient->socket = -1; + _connected = false; + _peek = -1; + } + stop_ssl_socket(sslclient, _CA_cert, _cert, _private_key); +} + +int WiFiClientSecure::connect(IPAddress ip, uint16_t port) +{ + if (_pskIdent && _psKey) + return connect(ip, port, _pskIdent, _psKey); + return connect(ip, port, _CA_cert, _cert, _private_key); +} + +int WiFiClientSecure::connect(IPAddress ip, uint16_t port, int32_t timeout){ + _timeout = timeout; + return connect(ip, port); +} + +int WiFiClientSecure::connect(const char *host, uint16_t port) +{ + if (_pskIdent && _psKey) + return connect(host, port, _pskIdent, _psKey); + return connect(host, port, _CA_cert, _cert, _private_key); +} + +int WiFiClientSecure::connect(const char *host, uint16_t port, int32_t timeout){ + _timeout = timeout; + return connect(host, port); +} + +int WiFiClientSecure::connect(IPAddress ip, uint16_t port, const char *_CA_cert, const char *_cert, const char *_private_key) +{ + return connect(ip.toString().c_str(), port, _CA_cert, _cert, _private_key); +} + +int WiFiClientSecure::connect(const char *host, uint16_t port, const char *_CA_cert, const char *_cert, const char *_private_key) +{ + if(_timeout > 0){ + sslclient->handshake_timeout = _timeout; + } + int ret = start_ssl_client(sslclient, host, port, _timeout, _CA_cert, _cert, _private_key, NULL, NULL); + _lastError = ret; + if (ret < 0) { + log_e("start_ssl_client: %d", ret); + stop(); + return 0; + } + _connected = true; + return 1; +} + +int WiFiClientSecure::connect(IPAddress ip, uint16_t port, const char *pskIdent, const char *psKey) { + return connect(ip.toString().c_str(), port,_pskIdent, _psKey); +} + +int WiFiClientSecure::connect(const char *host, uint16_t port, const char *pskIdent, const char *psKey) { + log_v("start_ssl_client with PSK"); + if(_timeout > 0){ + sslclient->handshake_timeout = _timeout; + } + int ret = start_ssl_client(sslclient, host, port, _timeout, NULL, NULL, NULL, _pskIdent, _psKey); + _lastError = ret; + if (ret < 0) { + log_e("start_ssl_client: %d", ret); + stop(); + return 0; + } + _connected = true; + return 1; +} + +int WiFiClientSecure::peek(){ + if(_peek >= 0){ + return _peek; + } + _peek = timedRead(); + return _peek; +} + +size_t WiFiClientSecure::write(uint8_t data) +{ + return write(&data, 1); +} + +int WiFiClientSecure::read() +{ + uint8_t data = -1; + int res = read(&data, 1); + if (res < 0) { + return res; + } + return data; +} + +size_t WiFiClientSecure::write(const uint8_t *buf, size_t size) +{ + if (!_connected) { + return 0; + } + int res = send_ssl_data(sslclient, buf, size); + if (res < 0) { + stop(); + res = 0; + } + return res; +} + +int WiFiClientSecure::read(uint8_t *buf, size_t size) +{ + int peeked = 0; + int avail = available(); + if ((!buf && size) || avail <= 0) { + return -1; + } + if(!size){ + return 0; + } + if(_peek >= 0){ + buf[0] = _peek; + _peek = -1; + size--; + avail--; + if(!size || !avail){ + return 1; + } + buf++; + peeked = 1; + } + + int res = get_ssl_receive(sslclient, buf, size); + if (res < 0) { + stop(); + return peeked?peeked:res; + } + return res + peeked; +} + +int WiFiClientSecure::available() +{ + int peeked = (_peek >= 0); + if (!_connected) { + return peeked; + } + int res = data_to_read(sslclient); + if (res < 0) { + stop(); + return peeked?peeked:res; + } + return res+peeked; +} + +uint8_t WiFiClientSecure::connected() +{ + uint8_t dummy = 0; + read(&dummy, 0); + + return _connected; +} + +void WiFiClientSecure::setCACert (const char *rootCA) +{ + _CA_cert = rootCA; +} + +void WiFiClientSecure::setCertificate (const char *client_ca) +{ + _cert = client_ca; +} + +void WiFiClientSecure::setPrivateKey (const char *private_key) +{ + _private_key = private_key; +} + +void WiFiClientSecure::setPreSharedKey(const char *pskIdent, const char *psKey) { + _pskIdent = pskIdent; + _psKey = psKey; +} + +bool WiFiClientSecure::verify(const char* fp, const char* domain_name) +{ + if (!sslclient) + return false; + + return verify_ssl_fingerprint(sslclient, fp, domain_name); +} + +char *WiFiClientSecure::_streamLoad(Stream& stream, size_t size) { + static char *dest = nullptr; + if(dest) { + free(dest); + } + dest = (char*)malloc(size); + if (!dest) { + return nullptr; + } + if (size != stream.readBytes(dest, size)) { + free(dest); + dest = nullptr; + } + return dest; +} + +bool WiFiClientSecure::loadCACert(Stream& stream, size_t size) { + char *dest = _streamLoad(stream, size); + bool ret = false; + if (dest) { + setCACert(dest); + ret = true; + } + return ret; +} + +bool WiFiClientSecure::loadCertificate(Stream& stream, size_t size) { + char *dest = _streamLoad(stream, size); + bool ret = false; + if (dest) { + setCertificate(dest); + ret = true; + } + return ret; +} + +bool WiFiClientSecure::loadPrivateKey(Stream& stream, size_t size) { + char *dest = _streamLoad(stream, size); + bool ret = false; + if (dest) { + setPrivateKey(dest); + ret = true; + } + return ret; +} + +int WiFiClientSecure::lastError(char *buf, const size_t size) +{ + if (!_lastError) { + return 0; + } + char error_buf[100]; + mbedtls_strerror(_lastError, error_buf, 100); + snprintf(buf, size, "%s", error_buf); + return _lastError; +} + +void WiFiClientSecure::setHandshakeTimeout(unsigned long handshake_timeout) +{ + sslclient->handshake_timeout = handshake_timeout * 1000; +} diff --git a/libraries/WiFiClientSecure/src/WiFiClientSecure.h b/libraries/WiFiClientSecure/src/WiFiClientSecure.h index f4e88021b74..cd4f20e0f1c 100644 --- a/libraries/WiFiClientSecure/src/WiFiClientSecure.h +++ b/libraries/WiFiClientSecure/src/WiFiClientSecure.h @@ -1,90 +1,108 @@ -/* - WiFiClientSecure.h - Base class that provides Client SSL to ESP32 - Copyright (c) 2011 Adrian McEwen. All right reserved. - Additions Copyright (C) 2017 Evandro Luis Copercini. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WiFiClientSecure_h -#define WiFiClientSecure_h -#include "Arduino.h" -#include "IPAddress.h" -#include -#include "ssl_client.h" - -class WiFiClientSecure : public WiFiClient -{ -protected: - sslclient_context *sslclient; - - int _lastError = 0; - int _peek = -1; - const char *_CA_cert; - const char *_cert; - const char *_private_key; - -public: - WiFiClientSecure *next; - WiFiClientSecure(); - WiFiClientSecure(int socket); - ~WiFiClientSecure(); - int connect(IPAddress ip, uint16_t port); - int connect(const char *host, uint16_t port); - int connect(IPAddress ip, uint16_t port, const char *rootCABuff, const char *cli_cert, const char *cli_key); - int connect(const char *host, uint16_t port, const char *rootCABuff, const char *cli_cert, const char *cli_key); - int peek(); - size_t write(uint8_t data); - size_t write(const uint8_t *buf, size_t size); - int available(); - int read(); - int read(uint8_t *buf, size_t size); - void flush() {} - void stop(); - uint8_t connected(); - int lastError(char *buf, const size_t size); - void setCACert(const char *rootCA); - void setCertificate(const char *client_ca); - void setPrivateKey (const char *private_key); - - operator bool() - { - return connected(); - } - WiFiClientSecure &operator=(const WiFiClientSecure &other); - bool operator==(const bool value) - { - return bool() == value; - } - bool operator!=(const bool value) - { - return bool() != value; - } - bool operator==(const WiFiClientSecure &); - bool operator!=(const WiFiClientSecure &rhs) - { - return !this->operator==(rhs); - }; - - int socket() - { - return sslclient->socket = -1; - } - - //friend class WiFiServer; - using Print::write; -}; - -#endif /* _WIFICLIENT_H_ */ +/* + WiFiClientSecure.h - Base class that provides Client SSL to ESP32 + Copyright (c) 2011 Adrian McEwen. All right reserved. + Additions Copyright (C) 2017 Evandro Luis Copercini. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WiFiClientSecure_h +#define WiFiClientSecure_h +#include "Arduino.h" +#include "IPAddress.h" +#include +#include "ssl_client.h" + +class WiFiClientSecure : public WiFiClient +{ +protected: + sslclient_context *sslclient; + + int _lastError = 0; + int _peek = -1; + int _timeout = 0; + const char *_CA_cert; + const char *_cert; + const char *_private_key; + const char *_pskIdent; // identity for PSK cipher suites + const char *_psKey; // key in hex for PSK cipher suites + +public: + WiFiClientSecure *next; + WiFiClientSecure(); + WiFiClientSecure(int socket); + ~WiFiClientSecure(); + int connect(IPAddress ip, uint16_t port); + int connect(IPAddress ip, uint16_t port, int32_t timeout); + int connect(const char *host, uint16_t port); + int connect(const char *host, uint16_t port, int32_t timeout); + int connect(IPAddress ip, uint16_t port, const char *rootCABuff, const char *cli_cert, const char *cli_key); + int connect(const char *host, uint16_t port, const char *rootCABuff, const char *cli_cert, const char *cli_key); + int connect(IPAddress ip, uint16_t port, const char *pskIdent, const char *psKey); + int connect(const char *host, uint16_t port, const char *pskIdent, const char *psKey); + int peek(); + size_t write(uint8_t data); + size_t write(const uint8_t *buf, size_t size); + int available(); + int read(); + int read(uint8_t *buf, size_t size); + void flush() {} + void stop(); + uint8_t connected(); + int lastError(char *buf, const size_t size); + void setPreSharedKey(const char *pskIdent, const char *psKey); // psKey in Hex + void setCACert(const char *rootCA); + void setCertificate(const char *client_ca); + void setPrivateKey (const char *private_key); + bool loadCACert(Stream& stream, size_t size); + bool loadCertificate(Stream& stream, size_t size); + bool loadPrivateKey(Stream& stream, size_t size); + bool verify(const char* fingerprint, const char* domain_name); + void setHandshakeTimeout(unsigned long handshake_timeout); + + int setTimeout(uint32_t seconds){ return 0; } + + operator bool() + { + return connected(); + } + WiFiClientSecure &operator=(const WiFiClientSecure &other); + bool operator==(const bool value) + { + return bool() == value; + } + bool operator!=(const bool value) + { + return bool() != value; + } + bool operator==(const WiFiClientSecure &); + bool operator!=(const WiFiClientSecure &rhs) + { + return !this->operator==(rhs); + }; + + int socket() + { + return sslclient->socket = -1; + } + +private: + char *_streamLoad(Stream& stream, size_t size); + + //friend class WiFiServer; + using Print::write; +}; + +#endif /* _WIFICLIENT_H_ */ diff --git a/libraries/WiFiClientSecure/src/ssl_client.cpp b/libraries/WiFiClientSecure/src/ssl_client.cpp index c55da2d5f99..3fa6138f558 100644 --- a/libraries/WiFiClientSecure/src/ssl_client.cpp +++ b/libraries/WiFiClientSecure/src/ssl_client.cpp @@ -1,264 +1,448 @@ -/* Provide SSL/TLS functions to ESP32 with Arduino IDE -* -* Adapted from the ssl_client1 example of mbedtls. -* -* Original Copyright (C) 2006-2015, ARM Limited, All Rights Reserved, Apache 2.0 License. -* Additions Copyright (C) 2017 Evandro Luis Copercini, Apache 2.0 License. -*/ - -#include "Arduino.h" -#include -#include -#include -#include -#include -#include "ssl_client.h" - - -const char *pers = "esp32-tls"; - -static int handle_error(int err) -{ - if(err == -30848){ - return err; - } -#ifdef MBEDTLS_ERROR_C - char error_buf[100]; - mbedtls_strerror(err, error_buf, 100); - log_e("%s", error_buf); -#endif - log_e("MbedTLS message code: %d", err); - return err; -} - - -void ssl_init(sslclient_context *ssl_client) -{ - mbedtls_ssl_init(&ssl_client->ssl_ctx); - mbedtls_ssl_config_init(&ssl_client->ssl_conf); - mbedtls_ctr_drbg_init(&ssl_client->drbg_ctx); -} - - -int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t port, const char *rootCABuff, const char *cli_cert, const char *cli_key) -{ - char buf[512]; - int ret, flags, timeout; - int enable = 1; - log_v("Free heap before TLS %u", xPortGetFreeHeapSize()); - - log_v("Starting socket"); - ssl_client->socket = -1; - - ssl_client->socket = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (ssl_client->socket < 0) { - log_e("ERROR opening socket"); - return ssl_client->socket; - } - - struct hostent *server; - server = gethostbyname(host); - if (server == NULL) { - log_e("gethostbyname failed"); - return -1; - } - IPAddress srv((const uint8_t *)(server->h_addr)); - - struct sockaddr_in serv_addr; - memset(&serv_addr, 0, sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = srv; - serv_addr.sin_port = htons(port); - - if (lwip_connect(ssl_client->socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == 0) { - timeout = 30000; - lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); - lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); - lwip_setsockopt(ssl_client->socket, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable)); - lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)); - } else { - log_e("Connect to Server failed!"); - return -1; - } - - fcntl( ssl_client->socket, F_SETFL, fcntl( ssl_client->socket, F_GETFL, 0 ) | O_NONBLOCK ); - - log_v("Seeding the random number generator"); - mbedtls_entropy_init(&ssl_client->entropy_ctx); - - ret = mbedtls_ctr_drbg_seed(&ssl_client->drbg_ctx, mbedtls_entropy_func, - &ssl_client->entropy_ctx, (const unsigned char *) pers, strlen(pers)); - if (ret < 0) { - return handle_error(ret); - } - - log_v("Setting up the SSL/TLS structure..."); - - if ((ret = mbedtls_ssl_config_defaults(&ssl_client->ssl_conf, - MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { - return handle_error(ret); - } - - // MBEDTLS_SSL_VERIFY_REQUIRED if a CA certificate is defined on Arduino IDE and - // MBEDTLS_SSL_VERIFY_NONE if not. - - if (rootCABuff != NULL) { - log_v("Loading CA cert"); - mbedtls_x509_crt_init(&ssl_client->ca_cert); - mbedtls_ssl_conf_authmode(&ssl_client->ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED); - ret = mbedtls_x509_crt_parse(&ssl_client->ca_cert, (const unsigned char *)rootCABuff, strlen(rootCABuff) + 1); - mbedtls_ssl_conf_ca_chain(&ssl_client->ssl_conf, &ssl_client->ca_cert, NULL); - //mbedtls_ssl_conf_verify(&ssl_client->ssl_ctx, my_verify, NULL ); - if (ret < 0) { - return handle_error(ret); - } - } else { - mbedtls_ssl_conf_authmode(&ssl_client->ssl_conf, MBEDTLS_SSL_VERIFY_NONE); - log_i("WARNING: Use certificates for a more secure communication!"); - } - - if (cli_cert != NULL && cli_key != NULL) { - mbedtls_x509_crt_init(&ssl_client->client_cert); - mbedtls_pk_init(&ssl_client->client_key); - - log_v("Loading CRT cert"); - - ret = mbedtls_x509_crt_parse(&ssl_client->client_cert, (const unsigned char *)cli_cert, strlen(cli_cert) + 1); - if (ret < 0) { - return handle_error(ret); - } - - log_v("Loading private key"); - ret = mbedtls_pk_parse_key(&ssl_client->client_key, (const unsigned char *)cli_key, strlen(cli_key) + 1, NULL, 0); - - if (ret != 0) { - return handle_error(ret); - } - - mbedtls_ssl_conf_own_cert(&ssl_client->ssl_conf, &ssl_client->client_cert, &ssl_client->client_key); - } - - log_v("Setting hostname for TLS session..."); - - // Hostname set here should match CN in server certificate - if((ret = mbedtls_ssl_set_hostname(&ssl_client->ssl_ctx, host)) != 0){ - return handle_error(ret); - } - - mbedtls_ssl_conf_rng(&ssl_client->ssl_conf, mbedtls_ctr_drbg_random, &ssl_client->drbg_ctx); - - if ((ret = mbedtls_ssl_setup(&ssl_client->ssl_ctx, &ssl_client->ssl_conf)) != 0) { - return handle_error(ret); - } - - mbedtls_ssl_set_bio(&ssl_client->ssl_ctx, &ssl_client->socket, mbedtls_net_send, mbedtls_net_recv, NULL ); - - log_v("Performing the SSL/TLS handshake..."); - - while ((ret = mbedtls_ssl_handshake(&ssl_client->ssl_ctx)) != 0) { - if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - return handle_error(ret); - } - vTaskDelay(10 / portTICK_PERIOD_MS); - } - - - if (cli_cert != NULL && cli_key != NULL) { - log_d("Protocol is %s Ciphersuite is %s", mbedtls_ssl_get_version(&ssl_client->ssl_ctx), mbedtls_ssl_get_ciphersuite(&ssl_client->ssl_ctx)); - if ((ret = mbedtls_ssl_get_record_expansion(&ssl_client->ssl_ctx)) >= 0) { - log_d("Record expansion is %d", ret); - } else { - log_w("Record expansion is unknown (compression)"); - } - } - - log_v("Verifying peer X.509 certificate..."); - - if ((flags = mbedtls_ssl_get_verify_result(&ssl_client->ssl_ctx)) != 0) { - bzero(buf, sizeof(buf)); - mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags); - log_e("Failed to verify peer certificate! verification info: %s", buf); - stop_ssl_socket(ssl_client, rootCABuff, cli_cert, cli_key); //It's not safe continue. - return handle_error(ret); - } else { - log_v("Certificate verified."); - } - - if (rootCABuff != NULL) { - mbedtls_x509_crt_free(&ssl_client->ca_cert); - } - - if (cli_cert != NULL) { - mbedtls_x509_crt_free(&ssl_client->client_cert); - } - - if (cli_key != NULL) { - mbedtls_pk_free(&ssl_client->client_key); - } - - log_v("Free heap after TLS %u", xPortGetFreeHeapSize()); - - return ssl_client->socket; -} - - -void stop_ssl_socket(sslclient_context *ssl_client, const char *rootCABuff, const char *cli_cert, const char *cli_key) -{ - log_v("Cleaning SSL connection."); - - if (ssl_client->socket >= 0) { - close(ssl_client->socket); - ssl_client->socket = -1; - } - - mbedtls_ssl_free(&ssl_client->ssl_ctx); - mbedtls_ssl_config_free(&ssl_client->ssl_conf); - mbedtls_ctr_drbg_free(&ssl_client->drbg_ctx); - mbedtls_entropy_free(&ssl_client->entropy_ctx); -} - - -int data_to_read(sslclient_context *ssl_client) -{ - int ret, res; - ret = mbedtls_ssl_read(&ssl_client->ssl_ctx, NULL, 0); - //log_e("RET: %i",ret); //for low level debug - res = mbedtls_ssl_get_bytes_avail(&ssl_client->ssl_ctx); - //log_e("RES: %i",res); //for low level debug - if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret < 0) { - return handle_error(ret); - } - - return res; -} - - -int send_ssl_data(sslclient_context *ssl_client, const uint8_t *data, uint16_t len) -{ - log_v("Writing HTTP request..."); //for low level debug - int ret = -1; - - while ((ret = mbedtls_ssl_write(&ssl_client->ssl_ctx, data, len)) <= 0) { - if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - return handle_error(ret); - } - } - - len = ret; - //log_v("%d bytes written", len); //for low level debug - return ret; -} - - -int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length) -{ - //log_d( "Reading HTTP response..."); //for low level debug - int ret = -1; - - ret = mbedtls_ssl_read(&ssl_client->ssl_ctx, data, length); - - //log_v( "%d bytes read", ret); //for low level debug - return ret; -} +/* Provide SSL/TLS functions to ESP32 with Arduino IDE +* +* Adapted from the ssl_client1 example of mbedtls. +* +* Original Copyright (C) 2006-2015, ARM Limited, All Rights Reserved, Apache 2.0 License. +* Additions Copyright (C) 2017 Evandro Luis Copercini, Apache 2.0 License. +*/ + +#include "Arduino.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ssl_client.h" +#include "WiFi.h" + +#ifndef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED +# error "Please configure IDF framework to include mbedTLS -> Enable pre-shared-key ciphersuites and activate at least one cipher" +#endif + +const char *pers = "esp32-tls"; + +static int _handle_error(int err, const char * file, int line) +{ + if(err == -30848){ + return err; + } +#ifdef MBEDTLS_ERROR_C + char error_buf[100]; + mbedtls_strerror(err, error_buf, 100); + log_e("[%s():%d]: (%d) %s", file, line, err, error_buf); +#else + log_e("[%s():%d]: code %d", file, line, err); +#endif + return err; +} + +#define handle_error(e) _handle_error(e, __FUNCTION__, __LINE__) + + +void ssl_init(sslclient_context *ssl_client) +{ + mbedtls_ssl_init(&ssl_client->ssl_ctx); + mbedtls_ssl_config_init(&ssl_client->ssl_conf); + mbedtls_ctr_drbg_init(&ssl_client->drbg_ctx); +} + + +int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t port, int timeout, const char *rootCABuff, const char *cli_cert, const char *cli_key, const char *pskIdent, const char *psKey) +{ + char buf[512]; + int ret, flags; + int enable = 1; + log_v("Free internal heap before TLS %u", ESP.getFreeHeap()); + + log_v("Starting socket"); + ssl_client->socket = -1; + + ssl_client->socket = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (ssl_client->socket < 0) { + log_e("ERROR opening socket"); + return ssl_client->socket; + } + + IPAddress srv((uint32_t)0); + if(!WiFiGenericClass::hostByName(host, srv)){ + return -1; + } + + struct sockaddr_in serv_addr; + memset(&serv_addr, 0, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = srv; + serv_addr.sin_port = htons(port); + + if (lwip_connect(ssl_client->socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == 0) { + if(timeout <= 0){ + timeout = 30000; + } + lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); + lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); + lwip_setsockopt(ssl_client->socket, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable)); + lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)); + } else { + log_e("Connect to Server failed!"); + return -1; + } + + fcntl( ssl_client->socket, F_SETFL, fcntl( ssl_client->socket, F_GETFL, 0 ) | O_NONBLOCK ); + + log_v("Seeding the random number generator"); + mbedtls_entropy_init(&ssl_client->entropy_ctx); + + ret = mbedtls_ctr_drbg_seed(&ssl_client->drbg_ctx, mbedtls_entropy_func, + &ssl_client->entropy_ctx, (const unsigned char *) pers, strlen(pers)); + if (ret < 0) { + return handle_error(ret); + } + + log_v("Setting up the SSL/TLS structure..."); + + if ((ret = mbedtls_ssl_config_defaults(&ssl_client->ssl_conf, + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { + return handle_error(ret); + } + + // MBEDTLS_SSL_VERIFY_REQUIRED if a CA certificate is defined on Arduino IDE and + // MBEDTLS_SSL_VERIFY_NONE if not. + + if (rootCABuff != NULL) { + log_v("Loading CA cert"); + mbedtls_x509_crt_init(&ssl_client->ca_cert); + mbedtls_ssl_conf_authmode(&ssl_client->ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED); + ret = mbedtls_x509_crt_parse(&ssl_client->ca_cert, (const unsigned char *)rootCABuff, strlen(rootCABuff) + 1); + mbedtls_ssl_conf_ca_chain(&ssl_client->ssl_conf, &ssl_client->ca_cert, NULL); + //mbedtls_ssl_conf_verify(&ssl_client->ssl_ctx, my_verify, NULL ); + if (ret < 0) { + return handle_error(ret); + } + } else if (pskIdent != NULL && psKey != NULL) { + log_v("Setting up PSK"); + // convert PSK from hex to binary + if ((strlen(psKey) & 1) != 0 || strlen(psKey) > 2*MBEDTLS_PSK_MAX_LEN) { + log_e("pre-shared key not valid hex or too long"); + return -1; + } + unsigned char psk[MBEDTLS_PSK_MAX_LEN]; + size_t psk_len = strlen(psKey)/2; + for (int j=0; j= '0' && c <= '9') c -= '0'; + else if (c >= 'A' && c <= 'F') c -= 'A' - 10; + else if (c >= 'a' && c <= 'f') c -= 'a' - 10; + else return -1; + psk[j/2] = c<<4; + c = psKey[j+1]; + if (c >= '0' && c <= '9') c -= '0'; + else if (c >= 'A' && c <= 'F') c -= 'A' - 10; + else if (c >= 'a' && c <= 'f') c -= 'a' - 10; + else return -1; + psk[j/2] |= c; + } + // set mbedtls config + ret = mbedtls_ssl_conf_psk(&ssl_client->ssl_conf, psk, psk_len, + (const unsigned char *)pskIdent, strlen(pskIdent)); + if (ret != 0) { + log_e("mbedtls_ssl_conf_psk returned %d", ret); + return handle_error(ret); + } + } else { + mbedtls_ssl_conf_authmode(&ssl_client->ssl_conf, MBEDTLS_SSL_VERIFY_NONE); + log_i("WARNING: Use certificates for a more secure communication!"); + } + + if (cli_cert != NULL && cli_key != NULL) { + mbedtls_x509_crt_init(&ssl_client->client_cert); + mbedtls_pk_init(&ssl_client->client_key); + + log_v("Loading CRT cert"); + + ret = mbedtls_x509_crt_parse(&ssl_client->client_cert, (const unsigned char *)cli_cert, strlen(cli_cert) + 1); + if (ret < 0) { + return handle_error(ret); + } + + log_v("Loading private key"); + ret = mbedtls_pk_parse_key(&ssl_client->client_key, (const unsigned char *)cli_key, strlen(cli_key) + 1, NULL, 0); + + if (ret != 0) { + return handle_error(ret); + } + + mbedtls_ssl_conf_own_cert(&ssl_client->ssl_conf, &ssl_client->client_cert, &ssl_client->client_key); + } + + log_v("Setting hostname for TLS session..."); + + // Hostname set here should match CN in server certificate + if((ret = mbedtls_ssl_set_hostname(&ssl_client->ssl_ctx, host)) != 0){ + return handle_error(ret); + } + + mbedtls_ssl_conf_rng(&ssl_client->ssl_conf, mbedtls_ctr_drbg_random, &ssl_client->drbg_ctx); + + if ((ret = mbedtls_ssl_setup(&ssl_client->ssl_ctx, &ssl_client->ssl_conf)) != 0) { + return handle_error(ret); + } + + mbedtls_ssl_set_bio(&ssl_client->ssl_ctx, &ssl_client->socket, mbedtls_net_send, mbedtls_net_recv, NULL ); + + log_v("Performing the SSL/TLS handshake..."); + unsigned long handshake_start_time=millis(); + while ((ret = mbedtls_ssl_handshake(&ssl_client->ssl_ctx)) != 0) { + if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + return handle_error(ret); + } + if((millis()-handshake_start_time)>ssl_client->handshake_timeout) + return -1; + vTaskDelay(10 / portTICK_PERIOD_MS); + } + + + if (cli_cert != NULL && cli_key != NULL) { + log_d("Protocol is %s Ciphersuite is %s", mbedtls_ssl_get_version(&ssl_client->ssl_ctx), mbedtls_ssl_get_ciphersuite(&ssl_client->ssl_ctx)); + if ((ret = mbedtls_ssl_get_record_expansion(&ssl_client->ssl_ctx)) >= 0) { + log_d("Record expansion is %d", ret); + } else { + log_w("Record expansion is unknown (compression)"); + } + } + + log_v("Verifying peer X.509 certificate..."); + + if ((flags = mbedtls_ssl_get_verify_result(&ssl_client->ssl_ctx)) != 0) { + bzero(buf, sizeof(buf)); + mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags); + log_e("Failed to verify peer certificate! verification info: %s", buf); + stop_ssl_socket(ssl_client, rootCABuff, cli_cert, cli_key); //It's not safe continue. + return handle_error(ret); + } else { + log_v("Certificate verified."); + } + + if (rootCABuff != NULL) { + mbedtls_x509_crt_free(&ssl_client->ca_cert); + } + + if (cli_cert != NULL) { + mbedtls_x509_crt_free(&ssl_client->client_cert); + } + + if (cli_key != NULL) { + mbedtls_pk_free(&ssl_client->client_key); + } + + log_v("Free internal heap after TLS %u", ESP.getFreeHeap()); + + return ssl_client->socket; +} + + +void stop_ssl_socket(sslclient_context *ssl_client, const char *rootCABuff, const char *cli_cert, const char *cli_key) +{ + log_v("Cleaning SSL connection."); + + if (ssl_client->socket >= 0) { + close(ssl_client->socket); + ssl_client->socket = -1; + } + + mbedtls_ssl_free(&ssl_client->ssl_ctx); + mbedtls_ssl_config_free(&ssl_client->ssl_conf); + mbedtls_ctr_drbg_free(&ssl_client->drbg_ctx); + mbedtls_entropy_free(&ssl_client->entropy_ctx); +} + + +int data_to_read(sslclient_context *ssl_client) +{ + int ret, res; + ret = mbedtls_ssl_read(&ssl_client->ssl_ctx, NULL, 0); + //log_e("RET: %i",ret); //for low level debug + res = mbedtls_ssl_get_bytes_avail(&ssl_client->ssl_ctx); + //log_e("RES: %i",res); //for low level debug + if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret < 0) { + return handle_error(ret); + } + + return res; +} + + +int send_ssl_data(sslclient_context *ssl_client, const uint8_t *data, uint16_t len) +{ + log_v("Writing HTTP request..."); //for low level debug + int ret = -1; + + while ((ret = mbedtls_ssl_write(&ssl_client->ssl_ctx, data, len)) <= 0) { + if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + return handle_error(ret); + } + } + + len = ret; + //log_v("%d bytes written", len); //for low level debug + return ret; +} + + +int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length) +{ + //log_d( "Reading HTTP response..."); //for low level debug + int ret = -1; + + ret = mbedtls_ssl_read(&ssl_client->ssl_ctx, data, length); + + //log_v( "%d bytes read", ret); //for low level debug + return ret; +} + +static bool parseHexNibble(char pb, uint8_t* res) +{ + if (pb >= '0' && pb <= '9') { + *res = (uint8_t) (pb - '0'); return true; + } else if (pb >= 'a' && pb <= 'f') { + *res = (uint8_t) (pb - 'a' + 10); return true; + } else if (pb >= 'A' && pb <= 'F') { + *res = (uint8_t) (pb - 'A' + 10); return true; + } + return false; +} + +// Compare a name from certificate and domain name, return true if they match +static bool matchName(const std::string& name, const std::string& domainName) +{ + size_t wildcardPos = name.find('*'); + if (wildcardPos == std::string::npos) { + // Not a wildcard, expect an exact match + return name == domainName; + } + + size_t firstDotPos = name.find('.'); + if (wildcardPos > firstDotPos) { + // Wildcard is not part of leftmost component of domain name + // Do not attempt to match (rfc6125 6.4.3.1) + return false; + } + if (wildcardPos != 0 || firstDotPos != 1) { + // Matching of wildcards such as baz*.example.com and b*z.example.com + // is optional. Maybe implement this in the future? + return false; + } + size_t domainNameFirstDotPos = domainName.find('.'); + if (domainNameFirstDotPos == std::string::npos) { + return false; + } + return domainName.substr(domainNameFirstDotPos) == name.substr(firstDotPos); +} + +// Verifies certificate provided by the peer to match specified SHA256 fingerprint +bool verify_ssl_fingerprint(sslclient_context *ssl_client, const char* fp, const char* domain_name) +{ + // Convert hex string to byte array + uint8_t fingerprint_local[32]; + int len = strlen(fp); + int pos = 0; + for (size_t i = 0; i < sizeof(fingerprint_local); ++i) { + while (pos < len && ((fp[pos] == ' ') || (fp[pos] == ':'))) { + ++pos; + } + if (pos > len - 2) { + log_d("pos:%d len:%d fingerprint too short", pos, len); + return false; + } + uint8_t high, low; + if (!parseHexNibble(fp[pos], &high) || !parseHexNibble(fp[pos+1], &low)) { + log_d("pos:%d len:%d invalid hex sequence: %c%c", pos, len, fp[pos], fp[pos+1]); + return false; + } + pos += 2; + fingerprint_local[i] = low | (high << 4); + } + + // Get certificate provided by the peer + const mbedtls_x509_crt* crt = mbedtls_ssl_get_peer_cert(&ssl_client->ssl_ctx); + + if (!crt) + { + log_d("could not fetch peer certificate"); + return false; + } + + // Calculate certificate's SHA256 fingerprint + uint8_t fingerprint_remote[32]; + mbedtls_sha256_context sha256_ctx; + mbedtls_sha256_init(&sha256_ctx); + mbedtls_sha256_starts(&sha256_ctx, false); + mbedtls_sha256_update(&sha256_ctx, crt->raw.p, crt->raw.len); + mbedtls_sha256_finish(&sha256_ctx, fingerprint_remote); + + // Check if fingerprints match + if (memcmp(fingerprint_local, fingerprint_remote, 32)) + { + log_d("fingerprint doesn't match"); + return false; + } + + // Additionally check if certificate has domain name if provided + if (domain_name) + return verify_ssl_dn(ssl_client, domain_name); + else + return true; +} + +// Checks if peer certificate has specified domain in CN or SANs +bool verify_ssl_dn(sslclient_context *ssl_client, const char* domain_name) +{ + log_d("domain name: '%s'", (domain_name)?domain_name:"(null)"); + std::string domain_name_str(domain_name); + std::transform(domain_name_str.begin(), domain_name_str.end(), domain_name_str.begin(), ::tolower); + + // Get certificate provided by the peer + const mbedtls_x509_crt* crt = mbedtls_ssl_get_peer_cert(&ssl_client->ssl_ctx); + + // Check for domain name in SANs + const mbedtls_x509_sequence* san = &crt->subject_alt_names; + while (san != nullptr) + { + std::string san_str((const char*)san->buf.p, san->buf.len); + std::transform(san_str.begin(), san_str.end(), san_str.begin(), ::tolower); + + if (matchName(san_str, domain_name_str)) + return true; + + log_d("SAN '%s': no match", san_str.c_str()); + + // Fetch next SAN + san = san->next; + } + + // Check for domain name in CN + const mbedtls_asn1_named_data* common_name = &crt->subject; + while (common_name != nullptr) + { + // While iterating through DN objects, check for CN object + if (!MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &common_name->oid)) + { + std::string common_name_str((const char*)common_name->val.p, common_name->val.len); + + if (matchName(common_name_str, domain_name_str)) + return true; + + log_d("CN '%s': not match", common_name_str.c_str()); + } + + // Fetch next DN object + common_name = common_name->next; + } + + return false; +} diff --git a/libraries/WiFiClientSecure/src/ssl_client.h b/libraries/WiFiClientSecure/src/ssl_client.h index 531db188487..dd57a0ff45f 100644 --- a/libraries/WiFiClientSecure/src/ssl_client.h +++ b/libraries/WiFiClientSecure/src/ssl_client.h @@ -1,36 +1,40 @@ -/* Provide SSL/TLS functions to ESP32 with Arduino IDE - * by Evandro Copercini - 2017 - Apache 2.0 License - */ - -#ifndef ARD_SSL_H -#define ARD_SSL_H -#include "mbedtls/platform.h" -#include "mbedtls/net.h" -#include "mbedtls/debug.h" -#include "mbedtls/ssl.h" -#include "mbedtls/entropy.h" -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/error.h" - -typedef struct sslclient_context { - int socket; - mbedtls_ssl_context ssl_ctx; - mbedtls_ssl_config ssl_conf; - - mbedtls_ctr_drbg_context drbg_ctx; - mbedtls_entropy_context entropy_ctx; - - mbedtls_x509_crt ca_cert; - mbedtls_x509_crt client_cert; - mbedtls_pk_context client_key; -} sslclient_context; - - -void ssl_init(sslclient_context *ssl_client); -int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t port, const char *rootCABuff, const char *cli_cert, const char *cli_key); -void stop_ssl_socket(sslclient_context *ssl_client, const char *rootCABuff, const char *cli_cert, const char *cli_key); -int data_to_read(sslclient_context *ssl_client); -int send_ssl_data(sslclient_context *ssl_client, const uint8_t *data, uint16_t len); -int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length); - -#endif +/* Provide SSL/TLS functions to ESP32 with Arduino IDE + * by Evandro Copercini - 2017 - Apache 2.0 License + */ + +#ifndef ARD_SSL_H +#define ARD_SSL_H +#include "mbedtls/platform.h" +#include "mbedtls/net.h" +#include "mbedtls/debug.h" +#include "mbedtls/ssl.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/error.h" + +typedef struct sslclient_context { + int socket; + mbedtls_ssl_context ssl_ctx; + mbedtls_ssl_config ssl_conf; + + mbedtls_ctr_drbg_context drbg_ctx; + mbedtls_entropy_context entropy_ctx; + + mbedtls_x509_crt ca_cert; + mbedtls_x509_crt client_cert; + mbedtls_pk_context client_key; + + unsigned long handshake_timeout; +} sslclient_context; + + +void ssl_init(sslclient_context *ssl_client); +int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t port, int timeout, const char *rootCABuff, const char *cli_cert, const char *cli_key, const char *pskIdent, const char *psKey); +void stop_ssl_socket(sslclient_context *ssl_client, const char *rootCABuff, const char *cli_cert, const char *cli_key); +int data_to_read(sslclient_context *ssl_client); +int send_ssl_data(sslclient_context *ssl_client, const uint8_t *data, uint16_t len); +int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length); +bool verify_ssl_fingerprint(sslclient_context *ssl_client, const char* fp, const char* domain_name); +bool verify_ssl_dn(sslclient_context *ssl_client, const char* domain_name); + +#endif diff --git a/libraries/Wire/doc/i2c_debugging.md b/libraries/Wire/doc/i2c_debugging.md new file mode 100644 index 00000000000..35c6e2e7f17 --- /dev/null +++ b/libraries/Wire/doc/i2c_debugging.md @@ -0,0 +1,276 @@ +# Debugging I2C + +With the release of Arduino-ESP32 V1.0.1 the I2C subsystem contains code to exhaustively report communication errors. +* Basic debugging can be enable by setting the *CORE DEBUG LEVEL* at or above *ERROR*. All errors will be directed the the *DEBUG OUTPUT* normally connected to `Serial()`. +* Enhanced debugging can be used to generate specified information at specific positions during the i2c communication sequence. Increase *CORE DEBUG LEVEL* to ***DEBUG*** + +## Enable Debug Buffer +The Enhanced debug features are enabled by uncommenting the `\\#define ENABLE_I2C_DEBUG_BUFFER` at line 45 of `esp32-hal-i2c.c`. +* When Arduino-Esp32 is installed in Windows with Arduino Boards Manager, `esp32-hal-i2c.c` can be found in: +`C:\Users\{user}\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.1\cores\esp32\` +* When Arduino-Esp32 Development version is installed from GitHub, `esp32-hal-i2c.c` can be found in: +`{arduino Sketch}\hardware\espressif\esp32\cores\esp32\` + + +```c++ +//#define ENABLE_I2C_DEBUG_BUFFER +``` +Change it to: +```c++ +#define ENABLE_I2C_DEBUG_BUFFER +``` +and recompile/upload the resulting code to your ESP32. + +Enabling this `#define` will consume an additional 2570 bytes of RAM and include a commensurate amount of code FLASH. If you see the message `"Debug Buffer not Enabled"` in your console log I would suggest you un-comment the line and regenerate the error. Additional information will be supplied on the log console. + +## Manually controlled Debugging +Manual logging of the i2c control data buffers can be accomplished by using the debug control function of `Wire()`: +```c++ + uint32_t setDebugFlags( uint32_t setBits, uint32_t resetBits); +``` +`setBits`, and `resetBits` manually cause output of the control structures to the log console. They are bit fields that enable/disable the reporting of individual control structures during specific phases of the i2c communications sequence. The 32bit values are divided into four 8bit fields. Currently only five bits are defined. ***If an error is detected during normal operations, the relevant control structure will bit added to the log irrespective of the current debug flags.*** + +* **bit 0** causes DumpI2c to execute +header information about current communications event, +and the dataQueue elements showing the logical i2c transaction commands +* **bit 1** causes DumpInts to execute +Actual sequence of interrupts handled during last communications event, cleared on entry into `ProcQueue()`. +* **bit 2** causes DumpCmdqueue to execute +The last block of commands to the i2c peripheral. +* **bit 3** causes DumpStatus to execute +A descriptive display of the 32bit i2c peripheral status word. +* **bit 4** causes DumpFifo to execute +A buffer listing the sequence of data added to the txFifo of the i2c peripheral. + +Of the four division, only three are currently implemented: +* 0xXX - - - - - - : at entry of ProcQueue (`bitFlags << 24`) +* 0x - - XX - - - - : at exit of ProcQueue (`bitFlags << 16`) +* 0x - - - - - - XX : at entry of Flush (`bitFlags`) + +For example, to display the sequence of Interrupts processed during the i2c communication transaction, **bit 1** would be set, and, since this information on Interrupt usage would only be valid after the communications have completed, the locus would be *at exit of ProcQueue*. The following code would be necessary. +### code +```c++ +uint8_t flag = 1 << 1; // turn on bit 1 +uint32_t debugFlag = flag << 16; // correctly position the 8bits of flag as the second byte of setBits. +Wire.setDebugFlags(debugFlag,0);// resetBits=0 says leave all current setBits as is. + +Wire.requestFrom(id,byteCount); // read byteCount bytes from slave at id + +Wire.setDebugFlags(0,debugFlag); // don't add any new debug, remove debugFlag +``` +### output of log console +``` +[I][esp32-hal-i2c.c:437] i2cTriggerDumps(): after ProcQueue +[I][esp32-hal-i2c.c:346] i2cDumpInts(): 0 row count INTR TX RX Tick +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [01] 0x0001 0x0002 0x0003 0x0000 0x005baac5 +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [02] 0x0001 0x0200 0x0000 0x0000 0x005baac5 +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [03] 0x0001 0x0080 0x0000 0x0008 0x005baac6 +``` +# Debug Log example +### Code +To read eight bytes of data from a DS1307 RTCC +``` + uint32_t debugFlag = 0x001F0000; + uint8_t ID = 0x68; + uint8_t block=8; + + if(debugFlag >0){ + Wire.setDebugFlags(debugFlag,0); + } + + Wire.beginTransmission(ID); + Wire.write(lowByte(addr)); + if((err=Wire.endTransmission(false))!=0) { + Serial.printf(" EndTransmission=%d(%s)",Wire.lastError(),Wire.getErrorText(Wire.lastError())); + + if(err!=2) { + Serial.printf(", resetting\n"); + if( !Wire.begin()) Serial.printf(" Reset Failed\n"); + if(debugFlag >0) Wire.setDebugFlags(0,debugFlag); + return; + } else { + Serial.printf(", No Device present, aborting\n"); + currentCommand= NO_COMMAND; + return; + } + } + err = Wire.requestFrom(ID,block,true); + if(debugFlag >0){ + Wire.setDebugFlags(0,debugFlag); + } +``` +### output of log console +``` +[I][esp32-hal-i2c.c:437] i2cTriggerDumps(): after ProcQueue +[E][esp32-hal-i2c.c:318] i2cDumpI2c(): i2c=0x3ffbdc78 +[I][esp32-hal-i2c.c:319] i2cDumpI2c(): dev=0x60013000 date=0x16042000 +[I][esp32-hal-i2c.c:321] i2cDumpI2c(): lock=0x3ffb843c +[I][esp32-hal-i2c.c:323] i2cDumpI2c(): num=0 +[I][esp32-hal-i2c.c:324] i2cDumpI2c(): mode=1 +[I][esp32-hal-i2c.c:325] i2cDumpI2c(): stage=3 +[I][esp32-hal-i2c.c:326] i2cDumpI2c(): error=1 +[I][esp32-hal-i2c.c:327] i2cDumpI2c(): event=0x3ffb85c4 bits=10 +[I][esp32-hal-i2c.c:328] i2cDumpI2c(): intr_handle=0x3ffb85f4 +[I][esp32-hal-i2c.c:329] i2cDumpI2c(): dq=0x3ffb858c +[I][esp32-hal-i2c.c:330] i2cDumpI2c(): queueCount=2 +[I][esp32-hal-i2c.c:331] i2cDumpI2c(): queuePos=1 +[I][esp32-hal-i2c.c:332] i2cDumpI2c(): errorByteCnt=0 +[I][esp32-hal-i2c.c:333] i2cDumpI2c(): errorQueue=0 +[I][esp32-hal-i2c.c:334] i2cDumpI2c(): debugFlags=0x001F0000 +[I][esp32-hal-i2c.c:288] i2cDumpDqData(): [0] 7bit 68 W buf@=0x3ffc04b2, len=1, pos=1, ctrl=11101 +[I][esp32-hal-i2c.c:306] i2cDumpDqData(): 0x0000: . 00 +[I][esp32-hal-i2c.c:288] i2cDumpDqData(): [1] 7bit 68 R STOP buf@=0x3ffc042c, len=8, pos=8, ctrl=11111 +[I][esp32-hal-i2c.c:306] i2cDumpDqData(): 0x0000: 5P...... 35 50 07 06 13 09 18 00 +[I][esp32-hal-i2c.c:346] i2cDumpInts(): 0 row count INTR TX RX Tick +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [01] 0x0001 0x0002 0x0003 0x0000 0x000073d5 +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [02] 0x0001 0x0200 0x0000 0x0000 0x000073d5 +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [03] 0x0001 0x0080 0x0000 0x0008 0x000073d6 +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 0] Y RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 1] Y WRITE val[0] exp[0] en[1] bytes[1] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 2] Y WRITE val[0] exp[0] en[1] bytes[1] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 3] Y RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 4] Y WRITE val[0] exp[0] en[1] bytes[1] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 5] Y READ val[0] exp[0] en[0] bytes[7] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 6] Y READ val[1] exp[0] en[0] bytes[1] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 7] Y STOP val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 8] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 9] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [10] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [11] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [12] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [13] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [14] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [15] N RSTART val[0] exp[0] en[0] bytes[0] +[I][esp32-hal-i2c.c:385] i2cDumpStatus(): ack(0) sl_rw(0) to(0) arb(0) busy(0) sl(1) trans(0) rx(0) tx(0) sclMain(5) scl(6) +[I][esp32-hal-i2c.c:424] i2cDumpFifo(): WRITE 0x68 0 +[I][esp32-hal-i2c.c:424] i2cDumpFifo(): READ 0x68 +``` +## Explaination of log output +### DumpI2c +``` +[I][esp32-hal-i2c.c:437] i2cTriggerDumps(): after ProcQueue +[E][esp32-hal-i2c.c:318] i2cDumpI2c(): i2c=0x3ffbdc78 +[I][esp32-hal-i2c.c:319] i2cDumpI2c(): dev=0x60013000 date=0x16042000 +[I][esp32-hal-i2c.c:321] i2cDumpI2c(): lock=0x3ffb843c +[I][esp32-hal-i2c.c:323] i2cDumpI2c(): num=0 +[I][esp32-hal-i2c.c:324] i2cDumpI2c(): mode=1 +[I][esp32-hal-i2c.c:325] i2cDumpI2c(): stage=3 +[I][esp32-hal-i2c.c:326] i2cDumpI2c(): error=1 +[I][esp32-hal-i2c.c:327] i2cDumpI2c(): event=0x3ffb85c4 bits=10 +[I][esp32-hal-i2c.c:328] i2cDumpI2c(): intr_handle=0x3ffb85f4 +[I][esp32-hal-i2c.c:329] i2cDumpI2c(): dq=0x3ffb858c +[I][esp32-hal-i2c.c:330] i2cDumpI2c(): queueCount=2 +[I][esp32-hal-i2c.c:331] i2cDumpI2c(): queuePos=1 +[I][esp32-hal-i2c.c:332] i2cDumpI2c(): errorByteCnt=0 +[I][esp32-hal-i2c.c:333] i2cDumpI2c(): errorQueue=0 +[I][esp32-hal-i2c.c:334] i2cDumpI2c(): debugFlags=0x001F0000 +``` +variable | description +---- | ---- +**i2c** | *memory address for control block* +**dev** | *memory address for access to i2c peripheral registers* +**date** | *revision date of peripheral silicon 2016, 42 week* +**lock** | *hal lock handle* +**num** | *0,1 which peripheral is being controlled* +**mode** | *configuration of driver 0=none, 1=MASTER, 2=SLAVE, 3=MASTER and SLAVE* +**stage** | *internal STATE of driver 0=not configured, 1=startup, 2=running, 3=done* +**error** | *internal ERROR status 0=not configured, 1=ok, 2=error, 3=address NAK, 4=data NAK, 5=arbitration loss, 6=timeout* +**event** | *handle for interprocess FreeRTOS eventSemaphore for communication between ISR and APP* +**intr_handle** | *FreeRTOS handle for allocated interrupt* +**dq** | *memory address for data queue control block* +**queueCount** | *number of data operations in queue control block* +**queuePos** | *last executed data block* +**errorByteCnt** | *position in current data block when error occured -1=address byte* +**errorQueue** | *queue that was executing when error occurred* +**debugFlags** | *current specified error bits* + +### DQ data +``` +[I][esp32-hal-i2c.c:288] i2cDumpDqData(): [0] 7bit 68 W buf@=0x3ffc04b2, len=1, pos=1, ctrl=11101 +[I][esp32-hal-i2c.c:306] i2cDumpDqData(): 0x0000: . 00 +[I][esp32-hal-i2c.c:288] i2cDumpDqData(): [1] 7bit 68 R STOP buf@=0x3ffc042c, len=8, pos=8, ctrl=11111 +[I][esp32-hal-i2c.c:306] i2cDumpDqData(): 0x0000: 5P...... 35 50 07 06 13 09 18 00 +``` +variable | description +--- | --- +**[n]** | *index of data queue element* +**i2c address** | *7bit= 7bit i2c slave address, 10bit= 10bit i2c slave address* +**direction** | *W=Write, R=READ* +**STOP** | *command issued a I2C STOP, else if blank, a RESTART was issued by next dq element.* +**buf@** | *pointer to data buffer* +**len** | *length of data buffer* +**pos** | *last position used in buffer* +**ctrl** | *bit field for data queue control, this bits describe if all necessary commands have been added to peripheral command buffer. in order(START,ADDRESS_Write,DATA,STOP,ADDRESS_value* +**0xnnnn** | *data buffer content, displayable followed by HEX, 32 bytes on a line.* + +### DumpInts +``` +[I][esp32-hal-i2c.c:346] i2cDumpInts(): 0 row count INTR TX RX Tick +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [01] 0x0001 0x0002 0x0003 0x0000 0x000073d5 +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [02] 0x0001 0x0200 0x0000 0x0000 0x000073d5 +[I][esp32-hal-i2c.c:350] i2cDumpInts(): [03] 0x0001 0x0080 0x0000 0x0008 0x000073d6 +``` +variable | description +---- | ---- +**row** | *array index* +**count** | *number of consecutive, duplicate interrupts* +**INTR** | *bit value of active interrupt (from ..\esp32\tools\sdk\include\soc\soc\i2c_struct.h)* +**TX** | *number of bytes added to txFifo* +**RX** | *number of bytes read from rxFifo* +**Tick** | *current tick counter from xTaskGetTickCountFromISR()* + +### DumpCmdQueue +``` +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 0] Y RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 1] Y WRITE val[0] exp[0] en[1] bytes[1] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 2] Y WRITE val[0] exp[0] en[1] bytes[1] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 3] Y RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 4] Y WRITE val[0] exp[0] en[1] bytes[1] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 5] Y READ val[0] exp[0] en[0] bytes[7] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 6] Y READ val[1] exp[0] en[0] bytes[1] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 7] Y STOP val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 8] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [ 9] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [10] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [11] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [12] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [13] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [14] N RSTART val[0] exp[0] en[0] bytes[0] +[E][esp32-hal-i2c.c:243] i2cDumpCmdQueue(): [15] N RSTART val[0] exp[0] en[0] bytes[0] +``` +Column | description +---- | ---- +**command** | *RSTART= generate i2c START sequence, WRITE= output byte(s), READ= input byte(s), STOP= generate i2c STOP sequence, END= continuation flag for peripheral to pause execution waiting for a refilled command list* +**val** | *value for ACK bit, 0 = LOW, 1= HIGH* +**exp** | *test of ACK bit 0=no, 1=yes* +**en** | *output of val, 0=no, 1=yes* +**bytes** | *number of byte to send(WRITE) or receive(READ) 1..255* + +### DumpStatus +``` +[I][esp32-hal-i2c.c:385] i2cDumpStatus(): ack(0) sl_rw(0) to(0) arb(0) busy(0) sl(1) trans(0) rx(0) tx(0) sclMain(5) scl(6) +``` +variable | description +---- | ---- +**ack** | *last value for ACK bit* +**sl_rw** | *mode for SLAVE operation 0=write, 1=read* +**to** | *timeout* +**arb** | *arbitration loss* +**busy** | *bus is inuse by other Master, or SLAVE is holding SCL,SDA* +**sl** | *last address on bus was equal to slave_addr* +**trans** | *a byte has moved though peripheral* +**rx** | *count of bytes in rxFifo* +**tx** | *count of bytes in txFifo* +**sclMain** | *state machine for i2c module. 0: SCL_MAIN_IDLE, 1: SCL_ADDRESS_SHIFT, 2: SCL_ACK_ADDRESS, 3: SCL_RX_DATA, 4: SCL_TX_DATA, 5: SCL_SEND_ACK, 6 :SCL_WAIT_ACK* +**scl** | *SCL clock state. 0: SCL_IDLE, 1: SCL_START, 2: SCL_LOW_EDGE, 3: SCL_LOW, 4: SCL_HIGH_EDGE, 5: SCL_HIGH, 6:SCL_STOP* + +### DumpFifo +``` +[I][esp32-hal-i2c.c:424] i2cDumpFifo(): WRITE 0x68 0 +[I][esp32-hal-i2c.c:424] i2cDumpFifo(): READ 0x68 +``` +Mode | datavalues +--- | --- +**WRITE** | the following bytes added to the txFifo are in response to a WRITE command +**READ** | the following bytes added to the txFifo are in response to a READ command + diff --git a/libraries/Wire/library.properties b/libraries/Wire/library.properties index ef29154c8e7..099cf6f0bac 100644 --- a/libraries/Wire/library.properties +++ b/libraries/Wire/library.properties @@ -1,5 +1,5 @@ name=Wire -version=1.0 +version=1.0.1 author=Hristo Gochkov maintainer=Hristo Gochkov sentence=Allows the communication between devices or sensors connected via Two Wire Interface Bus. For esp8266 boards. diff --git a/libraries/Wire/src/Wire.cpp b/libraries/Wire/src/Wire.cpp index aeebf7a73e0..bc580147800 100644 --- a/libraries/Wire/src/Wire.cpp +++ b/libraries/Wire/src/Wire.cpp @@ -19,7 +19,8 @@ Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts Modified December 2014 by Ivan Grokhotkov (ivan@esp8266.com) - esp8266 support Modified April 2015 by Hrsto Gochkov (ficeto@ficeto.com) - alternative esp8266 support -*/ + Modified Nov 2017 by Chuck Todd (ctodd@cableone.net) - ESP32 ISR Support + */ extern "C" { #include @@ -38,152 +39,200 @@ TwoWire::TwoWire(uint8_t bus_num) ,i2c(NULL) ,rxIndex(0) ,rxLength(0) + ,rxQueued(0) ,txIndex(0) ,txLength(0) ,txAddress(0) + ,txQueued(0) ,transmitting(0) + ,last_error(I2C_ERROR_OK) + ,_timeOutMillis(50) {} -void TwoWire::begin(int sdaPin, int sclPin, uint32_t frequency) +TwoWire::~TwoWire() +{ + flush(); + if(i2c) { + i2cRelease(i2c); + i2c=NULL; + } +} + +bool TwoWire::begin(int sdaPin, int sclPin, uint32_t frequency) { if(sdaPin < 0) { // default param passed if(num == 0) { - if(sda==-1) sdaPin = SDA; //use Default Pin - else sdaPin = sda; // reuse prior pin + if(sda==-1) { + sdaPin = SDA; //use Default Pin + } else { + sdaPin = sda; // reuse prior pin + } } else { if(sda==-1) { log_e("no Default SDA Pin for Second Peripheral"); - return; //no Default pin for Second Peripheral - } else sdaPin = sda; // reuse prior pin + return false; //no Default pin for Second Peripheral + } else { + sdaPin = sda; // reuse prior pin + } } } if(sclPin < 0) { // default param passed if(num == 0) { - if(scl==-1) sclPin = SCL; // use Default pin - else sclPin = scl; // reuse prior pin + if(scl == -1) { + sclPin = SCL; // use Default pin + } else { + sclPin = scl; // reuse prior pin + } } else { - if(scl==-1){ + if(scl == -1) { log_e("no Default SCL Pin for Second Peripheral"); - return; //no Default pin for Second Peripheral - } else sclPin = scl; // reuse prior pin - } - } - - if(i2c == NULL) { - i2c = i2cInit(num, 0, false); - if(i2c == NULL) { - return; + return false; //no Default pin for Second Peripheral + } else { + sclPin = scl; // reuse prior pin + } } } - i2cSetFrequency(i2c, frequency); - - if(sda >= 0 && sda != sdaPin) { - i2cDetachSDA(i2c, sda); - } - - if(scl >= 0 && scl != sclPin) { - i2cDetachSCL(i2c, scl); - } - sda = sdaPin; scl = sclPin; - - i2cAttachSDA(i2c, sda); - i2cAttachSCL(i2c, scl); + i2c = i2cInit(num, sdaPin, sclPin, frequency); + if(!i2c) { + return false; + } flush(); + return true; - i2cInitFix(i2c); } -void TwoWire::setClock(uint32_t frequency) +void TwoWire::setTimeOut(uint16_t timeOutMillis) { - i2cSetFrequency(i2c, frequency); + _timeOutMillis = timeOutMillis; } -size_t TwoWire::requestFrom(uint8_t address, size_t size, bool sendStop) +uint16_t TwoWire::getTimeOut() { - if(size > I2C_BUFFER_LENGTH) { - size = I2C_BUFFER_LENGTH; - } - size_t read = (i2cRead(i2c, address, false, rxBuffer, size, sendStop) == 0)?size:0; - rxIndex = 0; - rxLength = read; - return read; + return _timeOutMillis; } -uint8_t TwoWire::endTransmission(uint8_t sendStop) +void TwoWire::setClock(uint32_t frequency) { - int8_t ret = i2cWrite(i2c, txAddress, false, txBuffer, txLength, sendStop); - txIndex = 0; - txLength = 0; - transmitting = 0; - return ret; + i2cSetFrequency(i2c, frequency); } -uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop) +size_t TwoWire::getClock() { - return requestFrom(address, static_cast(quantity), static_cast(sendStop)); + return i2cGetFrequency(i2c); } -uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity) +/* stickBreaker Nov 2017 ISR, and bigblock 64k-1 + */ +i2c_err_t TwoWire::writeTransmission(uint16_t address, uint8_t *buff, uint16_t size, bool sendStop) { - return requestFrom(address, static_cast(quantity), true); + last_error = i2cWrite(i2c, address, buff, size, sendStop, _timeOutMillis); + return last_error; } -uint8_t TwoWire::requestFrom(int address, int quantity) +i2c_err_t TwoWire::readTransmission(uint16_t address, uint8_t *buff, uint16_t size, bool sendStop, uint32_t *readCount) { - return requestFrom(static_cast(address), static_cast(quantity), true); + last_error = i2cRead(i2c, address, buff, size, sendStop, _timeOutMillis, readCount); + return last_error; } -uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop) +void TwoWire::beginTransmission(uint16_t address) { - return requestFrom(static_cast(address), static_cast(quantity), static_cast(sendStop)); + transmitting = 1; + txAddress = address; + txIndex = txQueued; // allow multiple beginTransmission(),write(),endTransmission(false) until endTransmission(true) + txLength = txQueued; + last_error = I2C_ERROR_OK; } -void TwoWire::beginTransmission(uint8_t address) +/*stickbreaker isr + */ +uint8_t TwoWire::endTransmission(bool sendStop) // Assumes Wire.beginTransaction(), Wire.write() { - transmitting = 1; - txAddress = address; + if(transmitting == 1) { + // txlength is howmany bytes in txbuffer have been use + last_error = writeTransmission(txAddress, &txBuffer[txQueued], txLength - txQueued, sendStop); + if(last_error == I2C_ERROR_CONTINUE){ + txQueued = txLength; + } else if( last_error == I2C_ERROR_OK){ + rxIndex = 0; + rxLength = rxQueued; + rxQueued = 0; + txQueued = 0; // the SendStop=true will restart all Queueing + } + } else { + last_error = I2C_ERROR_NO_BEGIN; + flush(); + } txIndex = 0; txLength = 0; + transmitting = 0; + return (last_error == I2C_ERROR_CONTINUE)?I2C_ERROR_OK:last_error; // Don't return Continue for compatibility. } -void TwoWire::beginTransmission(int address) +/* @stickBreaker 11/2017 fix for ReSTART timeout, ISR + */ +uint8_t TwoWire::requestFrom(uint16_t address, uint8_t size, bool sendStop) { - beginTransmission((uint8_t)address); -} + //use internal Wire rxBuffer, multiple requestFrom()'s may be pending, try to share rxBuffer + uint32_t cnt = rxQueued; // currently queued reads, next available position in rxBuffer + if(cnt < (I2C_BUFFER_LENGTH-1) && (size + cnt) <= I2C_BUFFER_LENGTH) { // any room left in rxBuffer + rxQueued += size; + } else { // no room to receive more! + log_e("rxBuff overflow %d", cnt + size); + cnt = 0; + last_error = I2C_ERROR_MEMORY; + flush(); + return cnt; + } -uint8_t TwoWire::endTransmission(void) -{ - return endTransmission(true); + last_error = readTransmission(address, &rxBuffer[cnt], size, sendStop, &cnt); + rxIndex = 0; + + rxLength = cnt; + + if( last_error != I2C_ERROR_CONTINUE){ // not a buffered ReSTART operation + // so this operation actually moved data, queuing is done. + rxQueued = 0; + txQueued = 0; // the SendStop=true will restart all Queueing or error condition + } + + if(last_error != I2C_ERROR_OK){ // ReSTART on read does not return any data + cnt = 0; + } + + return cnt; } size_t TwoWire::write(uint8_t data) { if(transmitting) { if(txLength >= I2C_BUFFER_LENGTH) { + last_error = I2C_ERROR_MEMORY; return 0; } txBuffer[txIndex] = data; ++txIndex; txLength = txIndex; + return 1; } - return 1; + last_error = I2C_ERROR_NO_BEGIN; // no begin, not transmitting + return 0; } size_t TwoWire::write(const uint8_t *data, size_t quantity) { - if(transmitting) { - for(size_t i = 0; i < quantity; ++i) { - if(!write(data[i])) { - return i; - } + for(size_t i = 0; i < quantity; ++i) { + if(!write(data[i])) { + return i; } } return quantity; + } int TwoWire::available(void) @@ -217,13 +266,106 @@ void TwoWire::flush(void) rxLength = 0; txIndex = 0; txLength = 0; + rxQueued = 0; + txQueued = 0; + i2cFlush(i2c); // cleanup +} + +uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop) +{ + return requestFrom(static_cast(address), static_cast(quantity), static_cast(sendStop)); +} + +uint8_t TwoWire::requestFrom(uint16_t address, uint8_t quantity, uint8_t sendStop) +{ + return requestFrom(address, static_cast(quantity), static_cast(sendStop)); +} + +uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity) +{ + return requestFrom(static_cast(address), static_cast(quantity), true); +} + +uint8_t TwoWire::requestFrom(uint16_t address, uint8_t quantity) +{ + return requestFrom(address, static_cast(quantity), true); +} + +uint8_t TwoWire::requestFrom(int address, int quantity) +{ + return requestFrom(static_cast(address), static_cast(quantity), true); +} + +uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop) +{ + return static_cast(requestFrom(static_cast(address), static_cast(quantity), static_cast(sendStop))); +} + +void TwoWire::beginTransmission(int address) +{ + beginTransmission(static_cast(address)); +} + +void TwoWire::beginTransmission(uint8_t address) +{ + beginTransmission(static_cast(address)); +} + +uint8_t TwoWire::endTransmission(void) +{ + return endTransmission(true); } -void TwoWire::reset(void) +/* stickbreaker Nov2017 better error reporting + */ +uint8_t TwoWire::lastError() { - i2cReset( i2c ); - i2c = NULL; - begin( sda, scl ); + return (uint8_t)last_error; +} + +const char ERRORTEXT[] = + "OK\0" + "DEVICE\0" + "ACK\0" + "TIMEOUT\0" + "BUS\0" + "BUSY\0" + "MEMORY\0" + "CONTINUE\0" + "NO_BEGIN\0" + "\0"; + + +char * TwoWire::getErrorText(uint8_t err) +{ + uint8_t t = 0; + bool found = false; + char * message = (char*)&ERRORTEXT; + + while(!found && message[0]) { + found = t == err; + if(!found) { + message = message + strlen(message) + 1; + t++; + } + } + if(!found) { + return NULL; + } else { + return message; + } +} + +/*stickbreaker Dump i2c Interrupt buffer, i2c isr Debugging + */ + +uint32_t TwoWire::setDebugFlags( uint32_t setBits, uint32_t resetBits){ + return i2cDebug(i2c,setBits,resetBits); +} + +bool TwoWire::busy(void){ + return ((i2cGetStatus(i2c) & 16 )==16); } TwoWire Wire = TwoWire(0); +TwoWire Wire1 = TwoWire(1); diff --git a/libraries/Wire/src/Wire.h b/libraries/Wire/src/Wire.h index d9a7a752088..37288beb686 100644 --- a/libraries/Wire/src/Wire.h +++ b/libraries/Wire/src/Wire.h @@ -19,6 +19,7 @@ Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts Modified December 2014 by Ivan Grokhotkov (ivan@esp8266.com) - esp8266 support Modified April 2015 by Hrsto Gochkov (ficeto@ficeto.com) - alternative esp8266 support + Modified November 2017 by Chuck Todd to use ISR and increase stability. */ #ifndef TwoWire_h @@ -29,7 +30,10 @@ #include "freertos/queue.h" #include "Stream.h" +#define STICKBREAKER 'V1.1.0' #define I2C_BUFFER_LENGTH 128 +typedef void(*user_onRequest)(void); +typedef void(*user_onReceive)(uint8_t*, int); class TwoWire: public Stream { @@ -42,28 +46,57 @@ class TwoWire: public Stream uint8_t rxBuffer[I2C_BUFFER_LENGTH]; uint16_t rxIndex; uint16_t rxLength; + uint16_t rxQueued; //@stickBreaker uint8_t txBuffer[I2C_BUFFER_LENGTH]; uint16_t txIndex; uint16_t txLength; - uint8_t txAddress; + uint16_t txAddress; + uint16_t txQueued; //@stickbreaker uint8_t transmitting; + /* slave Mode, not yet Stickbreaker + static user_onRequest uReq[2]; + static user_onReceive uRcv[2]; + void onRequestService(void); + void onReceiveService(uint8_t*, int); + */ + i2c_err_t last_error; // @stickBreaker from esp32-hal-i2c.h + uint16_t _timeOutMillis; public: TwoWire(uint8_t bus_num); - void begin(int sda=-1, int scl=-1, uint32_t frequency=100000); - void setClock(uint32_t); - void beginTransmission(uint8_t); - void beginTransmission(int); + ~TwoWire(); + bool begin(int sda=-1, int scl=-1, uint32_t frequency=0); // returns true, if successful init of i2c bus + // calling will attemp to recover hung bus + + void setClock(uint32_t frequency); // change bus clock without initing hardware + size_t getClock(); // current bus clock rate in hz + + void setTimeOut(uint16_t timeOutMillis); // default timeout of i2c transactions is 50ms + uint16_t getTimeOut(); + + uint8_t lastError(); + char * getErrorText(uint8_t err); + + //@stickBreaker for big blocks and ISR model + i2c_err_t writeTransmission(uint16_t address, uint8_t* buff, uint16_t size, bool sendStop=true); + i2c_err_t readTransmission(uint16_t address, uint8_t* buff, uint16_t size, bool sendStop=true, uint32_t *readCount=NULL); + + void beginTransmission(uint16_t address); + void beginTransmission(uint8_t address); + void beginTransmission(int address); + + uint8_t endTransmission(bool sendStop); uint8_t endTransmission(void); - uint8_t endTransmission(uint8_t); - size_t requestFrom(uint8_t address, size_t size, bool sendStop); - uint8_t requestFrom(uint8_t, uint8_t); - uint8_t requestFrom(uint8_t, uint8_t, uint8_t); - uint8_t requestFrom(int, int); - uint8_t requestFrom(int, int, int); + uint8_t requestFrom(uint16_t address, uint8_t size, bool sendStop); + uint8_t requestFrom(uint16_t address, uint8_t size, uint8_t sendStop); + uint8_t requestFrom(uint16_t address, uint8_t size); + uint8_t requestFrom(uint8_t address, uint8_t size, uint8_t sendStop); + uint8_t requestFrom(uint8_t address, uint8_t size); + uint8_t requestFrom(int address, int size, int sendStop); + uint8_t requestFrom(int address, int size); size_t write(uint8_t); size_t write(const uint8_t *, size_t); @@ -72,8 +105,6 @@ class TwoWire: public Stream int peek(void); void flush(void); - void reset(void); - inline size_t write(const char * s) { return write((uint8_t*) s, strlen(s)); @@ -94,8 +125,25 @@ class TwoWire: public Stream { return write((uint8_t)n); } + + void onReceive( void (*)(int) ); + void onRequest( void (*)(void) ); + + uint32_t setDebugFlags( uint32_t setBits, uint32_t resetBits); + bool busy(); }; extern TwoWire Wire; +extern TwoWire Wire1; + +/* +V1.1.0 08JAN2019 Support CPU Clock frequency changes +V1.0.2 30NOV2018 stop returning I2C_ERROR_CONTINUE on ReSTART operations, regain compatibility with Arduino libs +V1.0.1 02AUG2018 First Fix after release, Correct ReSTART handling, change Debug control, change begin() + to a function, this allow reporting if bus cannot be initialized, Wire.begin() can be used to recover + a hung bus busy condition. +V0.2.2 13APR2018 preserve custom SCL,SDA,Frequency when no parameters passed to begin() +V0.2.1 15MAR2018 Hardware reset, Glitch prevention, adding destructor for second i2c testing +*/ #endif diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json index d68918f1257..2e6533eda9d 100644 --- a/package/package_esp32_index.template.json +++ b/package/package_esp32_index.template.json @@ -27,6 +27,9 @@ }, { "name": "WEMOS LoLin32" + }, + { + "name": "WEMOS D1 MINI ESP32" } ], "toolsDependencies": [ @@ -37,13 +40,13 @@ }, { "packager": "esp32", - "name": "esptool", - "version": "da31d9d" + "name": "esptool_py", + "version": "2.6.1" }, { "packager": "esp32", "name": "mkspiffs", - "version": "0.2.2" + "version": "0.2.3" } ] } @@ -80,74 +83,102 @@ "archiveFileName": "xtensa-esp32-elf-linux32-1.22.0-80-g6c4433a-5.2.0.tar.gz", "checksum": "SHA-256:b4055695ffc2dfc0bcb6dafdc2572a6e01151c4179ef5fa972b3fcb2183eb155", "size": "45566336" + }, + { + "host": "arm-linux-gnueabihf", + "url": "https://dl.espressif.com/dl/xtensa-esp32-elf-linux-armel-1.22.0-87-gb57bad3-5.2.0.tar.gz", + "archiveFileName": "xtensa-esp32-elf-linux-armel-1.22.0-87-gb57bad3-5.2.0.tar.gz", + "checksum": "SHA-256:9c68c87bb23b1256dc0a1859b515946763e5292dcab4a4159a52fae5618ce861", + "size": "50655584" } ] }, { - "name": "esptool", - "version": "da31d9d", + "name": "esptool_py", + "version": "2.6.1", "systems": [ { "host": "i686-mingw32", - "url": "https://dl.espressif.com/dl/esptool-da31d9d-windows.zip", - "archiveFileName": "esptool-da31d9d-windows.zip", - "checksum": "SHA-256:6476f4d6e33a59167dea364e177d97167316253d2c9ac75f81b469ecb3ed3875", - "size": "3395925" + "url": "https://dl.espressif.com/dl/esptool-2.6.1-windows.zip", + "archiveFileName": "esptool-2.6.1-windows.zip", + "checksum": "SHA-256:84cf0b369a7707fe566434faba148852fc464992111d5baa95b658b374802f96", + "size": "3422445" }, { "host": "x86_64-apple-darwin", - "url": "https://dl.espressif.com/dl/esptool-da31d9d-macos.tar.gz", - "archiveFileName": "esptool-da31d9d-macos.tar.gz", - "checksum": "SHA-256:76d53298366a294235356bb8d197a81b2afbfd62642851bfbaee252cc593faa9", - "size": "3810904" + "url": "https://dl.espressif.com/dl/esptool-2.6.1-macos.tar.gz", + "archiveFileName": "esptool-2.6.1-macos.tar.gz", + "checksum": "SHA-256:f4eb758a301d6902cc9dfcd49d36345d2f075ad123da7cf8132d15cfb7533457", + "size": "3837085" + }, + { + "host": "x86_64-pc-linux-gnu", + "url": "https://dl.espressif.com/dl/esptool-2.6.1-linux.tar.gz", + "archiveFileName": "esptool-2.6.1-linux.tar.gz", + "checksum": "SHA-256:eaf82ff4070d9792f6a42ae1e485375de5a87bec59ef01dfb95de901519ec7fb", + "size": "44762" + }, + { + "host": "i686-pc-linux-gnu", + "url": "https://dl.espressif.com/dl/esptool-2.6.1-linux.tar.gz", + "archiveFileName": "esptool-2.6.1-linux.tar.gz", + "checksum": "SHA-256:eaf82ff4070d9792f6a42ae1e485375de5a87bec59ef01dfb95de901519ec7fb", + "size": "44762" + }, + { + "host": "arm-linux-gnueabihf", + "url": "https://dl.espressif.com/dl/esptool-2.6.1-linux.tar.gz", + "archiveFileName": "esptool-2.6.1-linux.tar.gz", + "checksum": "SHA-256:eaf82ff4070d9792f6a42ae1e485375de5a87bec59ef01dfb95de901519ec7fb", + "size": "44762" } ] }, { "name": "mkspiffs", - "version": "0.2.2", + "version": "0.2.3", "systems": [ { "host": "i686-mingw32", - "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.2/mkspiffs-0.2.2-arduino-esp32-win32.zip", - "archiveFileName": "mkspiffs-0.2.2-arduino-esp32-win32.zip", - "checksum": "SHA-256:988baa2827005a20a7c7028f0c2d45d19df2e0a7d42319f4a7a5776a3f0dff2e", - "size": "347207" + "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.3/mkspiffs-0.2.3-arduino-esp32-win32.zip", + "archiveFileName": "mkspiffs-0.2.3-arduino-esp32-win32.zip", + "checksum": "SHA-256:b647f2c2efe6949819c85ea9404271b55c7c9c25bcb98d3b98a1d0ba771adf56", + "size": "249809" }, { "host": "x86_64-apple-darwin", - "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.2/mkspiffs-0.2.2-arduino-esp32-osx.tar.gz", - "archiveFileName": "mkspiffs-0.2.2-arduino-esp32-osx.tar.gz", - "checksum": "SHA-256:7aee138be9a73fe7fd1f75cf3f3695f0afae812d04fcbf74b17da330f66ae4cd", - "size": "130211" + "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.3/mkspiffs-0.2.3-arduino-esp32-osx.tar.gz", + "archiveFileName": "mkspiffs-0.2.3-arduino-esp32-osx.tar.gz", + "checksum": "SHA-256:9f43fc74a858cf564966b5035322c3e5e61c31a647c5a1d71b388ed6efc48423", + "size": "130270" }, { "host": "i386-apple-darwin", - "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.2/mkspiffs-0.2.2-arduino-esp32-osx.tar.gz", - "archiveFileName": "mkspiffs-0.2.2-arduino-esp32-osx.tar.gz", - "checksum": "SHA-256:7aee138be9a73fe7fd1f75cf3f3695f0afae812d04fcbf74b17da330f66ae4cd", - "size": "130211" + "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.3/mkspiffs-0.2.3-arduino-esp32-osx.tar.gz", + "archiveFileName": "mkspiffs-0.2.3-arduino-esp32-osx.tar.gz", + "checksum": "SHA-256:9f43fc74a858cf564966b5035322c3e5e61c31a647c5a1d71b388ed6efc48423", + "size": "130270" }, { "host": "x86_64-pc-linux-gnu", - "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.2/mkspiffs-0.2.2-arduino-esp32-linux64.tar.gz", - "archiveFileName": "mkspiffs-0.2.2-arduino-esp32-linux64.tar.gz", - "checksum": "SHA-256:17f89d9b38d4f68f2f03f7561b951d1d3b6d6f5b74d35b6d3eb8da3440be3400", - "size": "50611" + "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.3/mkspiffs-0.2.3-arduino-esp32-linux64.tar.gz", + "archiveFileName": "mkspiffs-0.2.3-arduino-esp32-linux64.tar.gz", + "checksum": "SHA-256:5e1a4ff41385e842f389f6b5254102a547e566a06b49babeffa93ef37115cb5d", + "size": "50646" }, { "host": "i686-pc-linux-gnu", - "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.2/mkspiffs-0.2.2-arduino-esp32-linux32.tar.gz", - "archiveFileName": "mkspiffs-0.2.2-arduino-esp32-linux32.tar.gz", - "checksum": "SHA-256:181fca76210de04a23eb7af028d9886de5a73e638c63d351a691a24cfb9f03d3", - "size": "48730" + "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.3/mkspiffs-0.2.3-arduino-esp32-linux32.tar.gz", + "archiveFileName": "mkspiffs-0.2.3-arduino-esp32-linux32.tar.gz", + "checksum": "SHA-256:464463a93e8833209cdc29ba65e1a12fec31718dc10075c195a2445b2c3f6cb0", + "size": "48751" }, { "host": "arm-linux-gnueabihf", - "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.2/mkspiffs-0.2.2-arduino-esp32-linux-armhf.tar.gz", - "archiveFileName": "mkspiffs-0.2.2-arduino-esp32-linux-armhf.tar.gz", - "checksum": "SHA-256:2e99cbdf5ee60b27d6ade096d4caf03a90edfd5f4edf4da2a8674d770aa4ca1b", - "size": "40658" + "url": "https://github.com/igrr/mkspiffs/releases/download/0.2.3/mkspiffs-0.2.3-arduino-esp32-linux-armhf.tar.gz", + "archiveFileName": "mkspiffs-0.2.3-arduino-esp32-linux-armhf.tar.gz", + "checksum": "SHA-256:ade3dc00117912ac08a1bdbfbfe76b12d21a34bc5fa1de0cfc45fe7a8d0a0185", + "size": "40665" } ] } diff --git a/platform.txt b/platform.txt index 974cabf6128..aad26366171 100644 --- a/platform.txt +++ b/platform.txt @@ -3,13 +3,13 @@ version=0.0.1 runtime.tools.xtensa-esp32-elf-gcc.path={runtime.platform.path}/tools/xtensa-esp32-elf -tools.esptool.path={runtime.platform.path}/tools -tools.esptool.cmd=esptool -tools.esptool.cmd.linux=esptool.py -tools.esptool.cmd.windows=esptool.exe +tools.esptool_py.path={runtime.platform.path}/tools/esptool +tools.esptool_py.cmd=esptool +tools.esptool_py.cmd.linux=esptool.py +tools.esptool_py.cmd.windows=esptool.exe -tools.esptool.network_cmd=python "{runtime.platform.path}/tools/espota.py" -tools.esptool.network_cmd.windows="{runtime.platform.path}/tools/espota.exe" +tools.esptool_py.network_cmd=python "{runtime.platform.path}/tools/espota.py" +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" @@ -22,20 +22,20 @@ compiler.warning_flags.all=-Wall -Werror=all -Wextra compiler.path={runtime.tools.xtensa-esp32-elf-gcc.path}/bin/ compiler.sdk.path={runtime.platform.path}/tools/sdk -compiler.cpreprocessor.flags=-DESP_PLATFORM -DMBEDTLS_CONFIG_FILE="mbedtls/esp_config.h" -DHAVE_CONFIG_H "-I{compiler.sdk.path}/include/config" "-I{compiler.sdk.path}/include/bluedroid" "-I{compiler.sdk.path}/include/app_trace" "-I{compiler.sdk.path}/include/app_update" "-I{compiler.sdk.path}/include/bootloader_support" "-I{compiler.sdk.path}/include/bt" "-I{compiler.sdk.path}/include/driver" "-I{compiler.sdk.path}/include/esp32" "-I{compiler.sdk.path}/include/esp_adc_cal" "-I{compiler.sdk.path}/include/ethernet" "-I{compiler.sdk.path}/include/fatfs" "-I{compiler.sdk.path}/include/freertos" "-I{compiler.sdk.path}/include/heap" "-I{compiler.sdk.path}/include/jsmn" "-I{compiler.sdk.path}/include/log" "-I{compiler.sdk.path}/include/mdns" "-I{compiler.sdk.path}/include/mbedtls" "-I{compiler.sdk.path}/include/mbedtls_port" "-I{compiler.sdk.path}/include/newlib" "-I{compiler.sdk.path}/include/nvs_flash" "-I{compiler.sdk.path}/include/openssl" "-I{compiler.sdk.path}/include/spi_flash" "-I{compiler.sdk.path}/include/sdmmc" "-I{compiler.sdk.path}/include/spiffs" "-I{compiler.sdk.path}/include/tcpip_adapter" "-I{compiler.sdk.path}/include/ulp" "-I{compiler.sdk.path}/include/vfs" "-I{compiler.sdk.path}/include/wear_levelling" "-I{compiler.sdk.path}/include/xtensa-debug-module" "-I{compiler.sdk.path}/include/coap" "-I{compiler.sdk.path}/include/console" "-I{compiler.sdk.path}/include/expat" "-I{compiler.sdk.path}/include/json" "-I{compiler.sdk.path}/include/lwip" "-I{compiler.sdk.path}/include/newlib" "-I{compiler.sdk.path}/include/nghttp" "-I{compiler.sdk.path}/include/soc" "-I{compiler.sdk.path}/include/wpa_supplicant" +compiler.cpreprocessor.flags=-DESP_PLATFORM -DMBEDTLS_CONFIG_FILE="mbedtls/esp_config.h" -DHAVE_CONFIG_H -DGCC_NOT_5_2_0=0 -DWITH_POSIX "-I{compiler.sdk.path}/include/config" "-I{compiler.sdk.path}/include/app_trace" "-I{compiler.sdk.path}/include/app_update" "-I{compiler.sdk.path}/include/asio" "-I{compiler.sdk.path}/include/bootloader_support" "-I{compiler.sdk.path}/include/bt" "-I{compiler.sdk.path}/include/coap" "-I{compiler.sdk.path}/include/console" "-I{compiler.sdk.path}/include/driver" "-I{compiler.sdk.path}/include/esp-tls" "-I{compiler.sdk.path}/include/esp32" "-I{compiler.sdk.path}/include/esp_adc_cal" "-I{compiler.sdk.path}/include/esp_event" "-I{compiler.sdk.path}/include/esp_http_client" "-I{compiler.sdk.path}/include/esp_http_server" "-I{compiler.sdk.path}/include/esp_https_ota" "-I{compiler.sdk.path}/include/esp_ringbuf" "-I{compiler.sdk.path}/include/ethernet" "-I{compiler.sdk.path}/include/expat" "-I{compiler.sdk.path}/include/fatfs" "-I{compiler.sdk.path}/include/freemodbus" "-I{compiler.sdk.path}/include/freertos" "-I{compiler.sdk.path}/include/heap" "-I{compiler.sdk.path}/include/idf_test" "-I{compiler.sdk.path}/include/jsmn" "-I{compiler.sdk.path}/include/json" "-I{compiler.sdk.path}/include/libsodium" "-I{compiler.sdk.path}/include/log" "-I{compiler.sdk.path}/include/lwip" "-I{compiler.sdk.path}/include/mbedtls" "-I{compiler.sdk.path}/include/mdns" "-I{compiler.sdk.path}/include/micro-ecc" "-I{compiler.sdk.path}/include/mqtt" "-I{compiler.sdk.path}/include/newlib" "-I{compiler.sdk.path}/include/nghttp" "-I{compiler.sdk.path}/include/nvs_flash" "-I{compiler.sdk.path}/include/openssl" "-I{compiler.sdk.path}/include/protobuf-c" "-I{compiler.sdk.path}/include/protocomm" "-I{compiler.sdk.path}/include/pthread" "-I{compiler.sdk.path}/include/sdmmc" "-I{compiler.sdk.path}/include/smartconfig_ack" "-I{compiler.sdk.path}/include/soc" "-I{compiler.sdk.path}/include/spi_flash" "-I{compiler.sdk.path}/include/spiffs" "-I{compiler.sdk.path}/include/tcp_transport" "-I{compiler.sdk.path}/include/tcpip_adapter" "-I{compiler.sdk.path}/include/ulp" "-I{compiler.sdk.path}/include/vfs" "-I{compiler.sdk.path}/include/wear_levelling" "-I{compiler.sdk.path}/include/wifi_provisioning" "-I{compiler.sdk.path}/include/wpa_supplicant" "-I{compiler.sdk.path}/include/xtensa-debug-module" "-I{compiler.sdk.path}/include/esp-face" "-I{compiler.sdk.path}/include/esp32-camera" "-I{compiler.sdk.path}/include/esp-face" "-I{compiler.sdk.path}/include/fb_gfx" compiler.c.cmd=xtensa-esp32-elf-gcc -compiler.c.flags=-std=gnu99 -Os -g3 -fstack-protector -ffunction-sections -fdata-sections -fstrict-volatile-bitfields -mlongcalls -nostdlib -Wpointer-arith {compiler.warning_flags} -Wno-error=unused-function -Wno-error=unused-but-set-variable -Wno-error=unused-variable -Wno-error=deprecated-declarations -Wno-unused-parameter -Wno-sign-compare -Wno-old-style-declaration -MMD -c +compiler.c.flags=-std=gnu99 -Os -g3 -fstack-protector -ffunction-sections -fdata-sections -fstrict-volatile-bitfields -mlongcalls -nostdlib -Wpointer-arith {compiler.warning_flags} -Wno-maybe-uninitialized -Wno-unused-function -Wno-unused-but-set-variable -Wno-unused-variable -Wno-deprecated-declarations -Wno-unused-parameter -Wno-sign-compare -Wno-old-style-declaration -MMD -c compiler.cpp.cmd=xtensa-esp32-elf-g++ -compiler.cpp.flags=-std=gnu++11 -fno-exceptions -Os -g3 -Wpointer-arith -fexceptions -fstack-protector -ffunction-sections -fdata-sections -fstrict-volatile-bitfields -mlongcalls -nostdlib {compiler.warning_flags} -Wno-error=unused-function -Wno-error=unused-but-set-variable -Wno-error=unused-variable -Wno-error=deprecated-declarations -Wno-unused-parameter -Wno-sign-compare -fno-rtti -MMD -c +compiler.cpp.flags=-std=gnu++11 -Os -g3 -Wpointer-arith -fexceptions -fstack-protector -ffunction-sections -fdata-sections -fstrict-volatile-bitfields -mlongcalls -nostdlib {compiler.warning_flags} -Wno-error=maybe-uninitialized -Wno-error=unused-function -Wno-error=unused-but-set-variable -Wno-error=unused-variable -Wno-error=deprecated-declarations -Wno-unused-parameter -Wno-unused-but-set-parameter -Wno-missing-field-initializers -Wno-sign-compare -fno-rtti -MMD -c compiler.S.cmd=xtensa-esp32-elf-gcc compiler.S.flags=-c -g3 -x assembler-with-cpp -MMD -mlongcalls compiler.c.elf.cmd=xtensa-esp32-elf-gcc -compiler.c.elf.flags=-nostdlib "-L{compiler.sdk.path}/lib" "-L{compiler.sdk.path}/ld" -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.rom.spiram_incompatible_fns.ld -u ld_include_panic_highint_hdl -u call_user_start_cpu0 -Wl,--gc-sections -Wl,-static -Wl,--undefined=uxTopUsedPriority -u __cxa_guard_dummy -u __cxx_fatal_exception -compiler.c.elf.libs=-lgcc -lopenssl -lbtdm_app -lfatfs -lwps -lcoexist -lwear_levelling -lhal -lnewlib -ldriver -lbootloader_support -lpp -lmesh -lsmartconfig -ljsmn -lwpa -lethernet -lphy -lapp_trace -lconsole -lulp -lwpa_supplicant -lfreertos -lbt -lmicro-ecc -lcxx -lxtensa-debug-module -lmdns -lvfs -lsoc -lcore -lsdmmc -lcoap -ltcpip_adapter -lc_nano -lrtc -lspi_flash -lwpa2 -lesp32 -lapp_update -lnghttp -lspiffs -lespnow -lnvs_flash -lesp_adc_cal -llog -lexpat -lm -lc -lheap -lmbedtls -llwip -lnet80211 -lpthread -ljson -lstdc++ +compiler.c.elf.flags=-nostdlib "-L{compiler.sdk.path}/lib" "-L{compiler.sdk.path}/ld" -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.rom.libgcc.ld -T esp32.rom.spiram_incompatible_fns.ld -u ld_include_panic_highint_hdl -u call_user_start_cpu0 -Wl,--gc-sections -Wl,-static -Wl,--undefined=uxTopUsedPriority -u __cxa_guard_dummy -u __cxx_fatal_exception +compiler.c.elf.libs=-lgcc -lesp32 -lphy -lesp_http_client -lmbedtls -lrtc -lesp_http_server -lbtdm_app -lspiffs -lbootloader_support -lmdns -lnvs_flash -lfatfs -lpp -lnet80211 -ljsmn -lface_detection -llibsodium -lvfs -ldl_lib -llog -lfreertos -lcxx -lsmartconfig_ack -lxtensa-debug-module -lheap -ltcpip_adapter -lmqtt -lulp -lfd -lfb_gfx -lnghttp -lprotocomm -lsmartconfig -lm -lethernet -limage_util -lc_nano -lsoc -ltcp_transport -lc -lmicro-ecc -lface_recognition -ljson -lwpa_supplicant -lmesh -lesp_https_ota -lwpa2 -lexpat -llwip -lwear_levelling -lapp_update -ldriver -lbt -lespnow -lcoap -lasio -lnewlib -lconsole -lapp_trace -lesp32-camera -lhal -lprotobuf-c -lsdmmc -lcore -lpthread -lcoexist -lfreemodbus -lspi_flash -lesp-tls -lwpa -lwifi_provisioning -lwps -lesp_adc_cal -lesp_event -lopenssl -lesp_ringbuf -lfr -lstdc++ compiler.as.cmd=xtensa-esp32-elf-as @@ -49,7 +49,8 @@ build.flash_size=4MB build.flash_mode=dio build.boot=bootloader build.code_debug=0 -build.extra_flags=-DESP32 -DCORE_DEBUG_LEVEL={build.code_debug} +build.defines= +build.extra_flags=-DESP32 -DCORE_DEBUG_LEVEL={build.code_debug} {build.defines} # These can be overridden in platform.local.txt compiler.c.extra_flags= @@ -60,6 +61,13 @@ compiler.ar.extra_flags= compiler.objcopy.eep.extra_flags= compiler.elf2hex.extra_flags= +# Build Dir: {build.path} +# Sketch Dir: {build.source.path} +recipe.hooks.prebuild.1.pattern=bash -c "[ ! -f {build.source.path}/partitions.csv ] || cp -f {build.source.path}/partitions.csv {build.path}/partitions.csv" +recipe.hooks.prebuild.2.pattern=bash -c "[ -f {build.path}/partitions.csv ] || cp {runtime.platform.path}/tools/partitions/{build.partitions}.csv {build.path}/partitions.csv" +recipe.hooks.prebuild.1.pattern.windows=cmd /c if exist "{build.source.path}\partitions.csv" copy /y "{build.source.path}\partitions.csv" "{build.path}\partitions.csv" +recipe.hooks.prebuild.2.pattern.windows=cmd /c if not exist "{build.path}\partitions.csv" copy "{runtime.platform.path}\tools\partitions\{build.partitions}.csv" "{build.path}\partitions.csv" + ## Compile c files recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.cpreprocessor.flags} {compiler.c.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BOARD="{build.board}" -DARDUINO_VARIANT="{build.variant}" {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}" @@ -70,17 +78,17 @@ recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor recipe.S.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.cpreprocessor.flags} {compiler.S.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BOARD="{build.board}" -DARDUINO_VARIANT="{build.variant}" {compiler.S.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}" ## Create archives -recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/arduino.ar" "{object_file}" +recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}" ## Combine gc-sections, archives, and objects -recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} -Wl,--start-group {object_files} "{build.path}/arduino.ar" {compiler.c.elf.libs} -Wl,--end-group -Wl,-EL -o "{build.path}/{build.project_name}.elf" +recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} -Wl,--start-group {object_files} "{archive_file_path}" {compiler.c.elf.libs} -Wl,--end-group -Wl,-EL -o "{build.path}/{build.project_name}.elf" ## Create eeprom -recipe.objcopy.eep.pattern={tools.gen_esp32part.cmd} -q "{runtime.platform.path}/tools/partitions/{build.partitions}.csv" "{build.path}/{build.project_name}.partitions.bin" +recipe.objcopy.eep.pattern={tools.gen_esp32part.cmd} -q "{build.path}/partitions.csv" "{build.path}/{build.project_name}.partitions.bin" ## Create hex -recipe.objcopy.hex.pattern="{tools.esptool.path}/{tools.esptool.cmd}" --chip esp32 elf2image --flash_mode "{build.flash_mode}" --flash_freq "{build.flash_freq}" --flash_size "{build.flash_size}" -o "{build.path}/{build.project_name}.bin" "{build.path}/{build.project_name}.elf" -recipe.objcopy.hex.pattern.linux=python "{tools.esptool.path}/{tools.esptool.cmd}" --chip esp32 elf2image --flash_mode "{build.flash_mode}" --flash_freq "{build.flash_freq}" --flash_size "{build.flash_size}" -o "{build.path}/{build.project_name}.bin" "{build.path}/{build.project_name}.elf" +recipe.objcopy.hex.pattern="{tools.esptool_py.path}/{tools.esptool_py.cmd}" --chip esp32 elf2image --flash_mode "{build.flash_mode}" --flash_freq "{build.flash_freq}" --flash_size "{build.flash_size}" -o "{build.path}/{build.project_name}.bin" "{build.path}/{build.project_name}.elf" +recipe.objcopy.hex.pattern.linux=python "{tools.esptool_py.path}/{tools.esptool_py.cmd}" --chip esp32 elf2image --flash_mode "{build.flash_mode}" --flash_freq "{build.flash_freq}" --flash_size "{build.flash_size}" -o "{build.path}/{build.project_name}.bin" "{build.path}/{build.project_name}.elf" ## Save hex recipe.output.tmp_file={build.project_name}.bin @@ -88,14 +96,14 @@ recipe.output.save_file={build.project_name}.{build.variant}.bin ## Compute size recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf" -recipe.size.regex=^(?:\.iram0\.text|\.dram0\.text|\.flash\.text|\.dram0\.data|\.flash\.rodata|)\s+([0-9]+).* -recipe.size.regex.data=^(?:\.dram0\.data|\.dram0\.bss)\s+([0-9]+).* +recipe.size.regex=^(?:\.iram0\.text|\.iram0\.vectors|\.dram0\.data|\.flash\.text|\.flash\.rodata|)\s+([0-9]+).* +recipe.size.regex.data=^(?:\.dram0\.data|\.dram0\.bss|\.noinit)\s+([0-9]+).* # ------------------------------ -tools.esptool.upload.protocol=esp32 -tools.esptool.upload.params.verbose= -tools.esptool.upload.params.quiet= -tools.esptool.upload.pattern="{path}/{cmd}" --chip esp32 --port "{serial.port}" --baud {upload.speed} --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/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.upload.pattern.linux=python "{path}/{cmd}" --chip esp32 --port "{serial.port}" --baud {upload.speed} --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/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.upload.network_pattern={network_cmd} -i "{serial.port}" -p "{network.port}" "--auth={network.password}" -f "{build.path}/{build.project_name}.bin" +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 esp32 --port "{serial.port}" --baud {upload.speed} --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/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 esp32 --port "{serial.port}" --baud {upload.speed} --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/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/build.py b/tools/build.py deleted file mode 100755 index dde5a2e9d5a..00000000000 --- a/tools/build.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# build.py — build a sketch using arduino-builder -# -# Wrapper script around arduino-builder which accepts some ESP8266-specific -# options and translates them into FQBN -# -# Copyright © 2016 Ivan Grokhotkov -# -# 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. -# -# - - -from __future__ import print_function -import sys -import os -import argparse -import subprocess -import tempfile -import shutil - -def compile(tmp_dir, sketch, tools_dir, hardware_dir, ide_path, f, args): - cmd = ide_path + '/arduino-builder ' - cmd += '-compile -logger=human ' - cmd += '-build-path "' + tmp_dir + '" ' - cmd += '-tools "' + ide_path + '/tools-builder" ' - if args.library_path: - for lib_dir in args.library_path: - cmd += '-libraries "' + lib_dir + '" ' - cmd += '-hardware "' + ide_path + '/hardware" ' - if args.hardware_dir: - for hw_dir in args.hardware_dir: - cmd += '-hardware "' + hw_dir + '" ' - else: - cmd += '-hardware "' + hardware_dir + '" ' - # Debug=Serial,DebugLevel=Core____ - cmd += '-fqbn=espressif:esp32:{board_name}:' \ - 'FlashFreq={flash_freq},' \ - 'UploadSpeed=921600'.format(**vars(args)) - cmd += ' ' - cmd += '-ide-version=10607 ' - cmd += '-warnings={warnings} '.format(**vars(args)) - if args.verbose: - cmd += '-verbose ' - cmd += sketch - - if args.verbose: - print('Building: ' + cmd, file=f) - - cmds = cmd.split(' ') - p = subprocess.Popen(cmds, stdout=f, stderr=subprocess.STDOUT) - p.wait() - return p.returncode - -def parse_args(): - parser = argparse.ArgumentParser(description='Sketch build helper') - parser.add_argument('-v', '--verbose', help='Enable verbose output', - action='store_true') - parser.add_argument('-i', '--ide_path', help='Arduino IDE path') - parser.add_argument('-p', '--build_path', help='Build directory') - parser.add_argument('-l', '--library_path', help='Additional library path', - action='append') - parser.add_argument('-d', '--hardware_dir', help='Additional hardware path', - action='append') - parser.add_argument('-b', '--board_name', help='Board name', default='esp32') - parser.add_argument('-w', '--warnings', help='Compilation warnings level', - default='none', choices=['none', 'all', 'more']) - parser.add_argument('-o', '--output_binary', help='File name for output binary') - parser.add_argument('-k', '--keep', action='store_true', - help='Don\'t delete temporary build directory') - parser.add_argument('--flash_freq', help='Flash frequency', default=40, - type=int, choices=[40, 80]) - parser.add_argument('sketch_path', help='Sketch file path') - return parser.parse_args() - -def main(): - args = parse_args() - - ide_path = args.ide_path - if not ide_path: - ide_path = os.environ.get('ARDUINO_IDE_PATH') - if not ide_path: - print("Please specify Arduino IDE path via --ide_path option" - "or ARDUINO_IDE_PATH environment variable.", file=sys.stderr) - return 2 - - sketch_path = args.sketch_path - tmp_dir = args.build_path - created_tmp_dir = False - if not tmp_dir: - tmp_dir = tempfile.mkdtemp() - created_tmp_dir = True - - tools_dir = os.path.dirname(os.path.realpath(__file__)) + '/../tools' - # this is not the correct hardware folder to add. - hardware_dir = os.path.dirname(os.path.realpath(__file__)) + '/../cores' - - output_name = tmp_dir + '/' + os.path.basename(sketch_path) + '.bin' - if args.verbose: - print("Sketch: ", sketch_path) - print("Build dir: ", tmp_dir) - print("Output: ", output_name) - - if args.verbose: - f = sys.stdout - else: - f = open(tmp_dir + '/build.log', 'w') - - res = compile(tmp_dir, sketch_path, tools_dir, hardware_dir, ide_path, f, args) - if res != 0: - return res - - if args.output_binary is not None: - shutil.copy(output_name, args.output_binary) - - if created_tmp_dir and not args.keep: - shutil.rmtree(tmp_dir, ignore_errors=True) - -if __name__ == '__main__': - sys.exit(main()) diff --git a/tools/common.sh b/tools/common.sh deleted file mode 100755 index 0cb50a10465..00000000000 --- a/tools/common.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env bash - -function print_size_info() -{ - elf_file=$1 - - if [ -z "$elf_file" ]; then - printf "sketch iram0.text flash.text flash.rodata dram0.data dram0.bss dram flash\n" - return 0 - fi - - elf_name=$(basename $elf_file) - sketch_name="${elf_name%.*}" - # echo $sketch_name - declare -A segments - while read -a tokens; do - seg=${tokens[0]} - seg=${seg//./} - size=${tokens[1]} - addr=${tokens[2]} - if [ "$addr" -eq "$addr" -a "$addr" -ne "0" ] 2>/dev/null; then - segments[$seg]=$size - fi - done < <(xtensa-esp32-elf-size --format=sysv $elf_file) - - total_ram=$((${segments[dram0data]} + ${segments[dram0bss]})) - total_flash=$((${segments[iram0text]} + ${segments[flashtext]} + ${segments[dram0data]} + ${segments[flashrodata]})) - printf "%-28s %-8d %-8d %-8d %-8d %-8d %-8d %-8d\n" $sketch_name ${segments[iram0text]} ${segments[flashtext]} ${segments[flashrodata]} ${segments[dram0data]} ${segments[dram0bss]} $total_ram $total_flash - return 0 -} - -function build_sketches() -{ - #set +e - local arduino=$1 - local srcpath=$2 - local build_arg=$3 - local build_dir=build.tmp - mkdir -p $build_dir - local build_cmd="python tools/build.py -b esp32 -v -k -p $PWD/$build_dir $build_arg " - local sketches=$(find $srcpath -name *.ino) - print_size_info >size.log - export ARDUINO_IDE_PATH=$arduino - for sketch in $sketches; do - rm -rf $build_dir/* - local sketchdir=$(dirname $sketch) - local sketchdirname=$(basename $sketchdir) - local sketchname=$(basename $sketch) - if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then - echo "Skipping $sketch, beacause it is not the main sketch file"; - continue - fi; - if [[ -f "$sketchdir/.test.skip" ]]; then - echo -e "\n ------------ Skipping $sketch ------------ \n"; - continue - fi - echo -e "\n ------------ Building $sketch ------------ \n"; - # $arduino --verify $sketch; - #echo "$build_cmd $sketch" - time ($build_cmd $sketch >build.log) - local result=$? - if [ $result -ne 0 ]; then - echo "Build failed ($1)" - echo "Build log:" - cat build.log - return $result - fi - rm build.log - print_size_info $build_dir/*.elf >>size.log - done - #set -e -} diff --git a/tools/espota.exe b/tools/espota.exe index 1885898a639..3de37913ce0 100644 Binary files a/tools/espota.exe and b/tools/espota.exe differ diff --git a/tools/espota.py b/tools/espota.py index e662e611cf2..77fcfd75c64 100755 --- a/tools/espota.py +++ b/tools/espota.py @@ -106,7 +106,7 @@ def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, comm sock2.close() logging.error('Host %s Not Found', remoteAddr) return 1 - sock2.settimeout(1) + sock2.settimeout(TIMEOUT) try: data = sock2.recv(37).decode() break; @@ -162,7 +162,6 @@ def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, comm logging.error('No response from device') sock.close() return 1 - try: f = open(filename, "rb") if (PROGRESS): @@ -180,6 +179,7 @@ def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, comm try: connection.sendall(chunk) res = connection.recv(10) + lastResponseContainedOK = 'OK' in res.decode() except: sys.stderr.write('\n') logging.error('Error Uploading') @@ -188,21 +188,36 @@ def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, comm sock.close() return 1 - sys.stderr.write('\n') - logging.info('Waiting for result...') - try: - connection.settimeout(60) - data = connection.recv(32).decode() - logging.info('Result: %s' ,data) + if lastResponseContainedOK: + logging.info('Success') connection.close() f.close() sock.close() - if (data != "OK"): - sys.stderr.write('\n') - logging.error('%s', data) - return 1; return 0 - except: + + sys.stderr.write('\n') + logging.info('Waiting for result...') + try: + count = 0 + while True: + count=count+1 + connection.settimeout(60) + data = connection.recv(32).decode() + logging.info('Result: %s' ,data) + + if "OK" in data: + logging.info('Success') + connection.close() + f.close() + sock.close() + return 0; + if count == 5: + logging.error('Error response from device') + connection.close() + f.close() + sock.close() + return 1 + except e: logging.error('No Result!') connection.close() f.close() @@ -221,7 +236,7 @@ def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, comm def parser(unparsed_args): parser = optparse.OptionParser( usage = "%prog [options]", - description = "Transmit image over the air to the esp8266 module with OTA support." + description = "Transmit image over the air to the esp32 module with OTA support." ) # destination ip and port @@ -229,7 +244,7 @@ def parser(unparsed_args): group.add_option("-i", "--ip", dest = "esp_ip", action = "store", - help = "ESP8266 IP Address.", + help = "ESP32 IP Address.", default = False ) group.add_option("-I", "--host_ip", @@ -241,8 +256,8 @@ def parser(unparsed_args): group.add_option("-p", "--port", dest = "esp_port", type = "int", - help = "ESP8266 ota Port. Default 8266", - default = 8266 + help = "ESP32 ota Port. Default 3232", + default = 3232 ) group.add_option("-P", "--host_port", dest = "host_port", @@ -292,6 +307,12 @@ def parser(unparsed_args): action = "store_true", default = False ) + group.add_option("-t", "--timeout", + dest = "timeout", + type = "int", + help = "Timeout to wait for the ESP32 to accept invitation", + default = 10 + ) parser.add_option_group(group) (options, args) = parser.parse_args(unparsed_args) @@ -312,6 +333,10 @@ def main(args): # check options global PROGRESS PROGRESS = options.progress + + global TIMEOUT + TIMEOUT = options.timeout + if (not options.esp_ip or not options.image): logging.critical("Not enough arguments.") return 1 diff --git a/tools/esptool.py b/tools/esptool.py index 36f95002c77..d6ceb6f9b39 100755 --- a/tools/esptool.py +++ b/tools/esptool.py @@ -20,6 +20,7 @@ import argparse import base64 +import binascii import copy import hashlib import inspect @@ -30,10 +31,36 @@ import sys import time import zlib +import string -import serial +try: + import serial +except ImportError: + print("Pyserial is not installed for %s. Check the README for installation instructions." % (sys.executable)) + raise + +# check 'serial' is 'pyserial' and not 'serial' https://github.com/espressif/esptool/issues/269 +try: + if "serialization" in serial.__doc__ and "deserialization" in serial.__doc__: + raise ImportError(""" +esptool.py depends on pyserial, but there is a conflict with a currently installed package named 'serial'. + +You may be able to work around this by 'pip uninstall serial; pip install pyserial' \ +but this may break other installed Python software that depends on 'serial'. + +There is no good fix for this right now, apart from configuring virtualenvs. \ +See https://github.com/espressif/esptool/issues/269#issuecomment-385298196 for discussion of the underlying issue(s).""") +except TypeError: + pass # __doc__ returns None for pyserial -__version__ = "2.3.1" +try: + import serial.tools.list_ports as list_ports +except ImportError: + print("The installed version (%s) of pyserial appears to be too old for esptool.py (Python interpreter %s). " + "Check the README for installation instructions." % (sys.VERSION, sys.executable)) + raise + +__version__ = "2.8-dev" MAX_UINT32 = 0xffffffff MAX_UINT24 = 0xffffff @@ -45,6 +72,8 @@ SYNC_TIMEOUT = 0.1 # timeout for syncing with bootloader MD5_TIMEOUT_PER_MB = 8 # timeout (per megabyte) for calculating md5sum ERASE_REGION_TIMEOUT_PER_MB = 30 # timeout (per megabyte) for erasing a region +MEM_END_ROM_TIMEOUT = 0.05 # special short timeout for ESP_MEM_END, as it may never respond +DEFAULT_SERIAL_WRITE_TIMEOUT = 10 # timeout for serial port write def timeout_per_mb(seconds_per_mb, size_bytes): @@ -106,13 +135,22 @@ def byte(bitstr, index): basestring = str +def _mask_to_shift(mask): + """ Return the index of the least significant bit in the mask """ + shift = 0 + while mask & 0x1 == 0: + shift += 1 + mask >>= 1 + return shift + + def esp8266_function_only(func): """ Attribute for a function only supported on ESP8266 """ return check_supported_function(func, lambda o: o.CHIP_NAME == "ESP8266") class ESPLoader(object): - """ Base class providing access to ESP ROM & softtware stub bootloaders. + """ Base class providing access to ESP ROM & software stub bootloaders. Subclasses provide ESP8266 & ESP32 specific functionality. Don't instantiate this base class directly, either instantiate a subclass or @@ -151,6 +189,9 @@ class ESPLoader(object): ESP_READ_FLASH = 0xD2 ESP_RUN_USER_CODE = 0xD3 + # Flash encryption debug more command + ESP_FLASH_ENCRYPT_DATA = 0xD4 + # Maximum block sized for RAM and Flash writes, respectively. ESP_RAM_BLOCK = 0x1800 @@ -168,8 +209,11 @@ class ESPLoader(object): # Flash sector size, minimum unit of erase. FLASH_SECTOR_SIZE = 0x1000 + # This register happens to exist on both ESP8266 & ESP32 UART_DATA_REG_ADDR = 0x60000078 + UART_CLKDIV_MASK = 0xFFFFF + # Memory addresses IROM_MAP_START = 0x40200000 IROM_MAP_END = 0x40300000 @@ -200,6 +244,13 @@ def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False): # https://github.com/espressif/esptool/issues/44#issuecomment-107094446 self._set_port_baudrate(baud) self._trace_enabled = trace_enabled + # set write timeout, to prevent esptool blocked at write forever. + try: + self._port.write_timeout = DEFAULT_SERIAL_WRITE_TIMEOUT + except NotImplementedError: + # no write timeout for RFC2217 ports + # need to set the property back to None or it will continue to fail + self._port.write_timeout = None def _set_port_baudrate(self, baud): try: @@ -221,17 +272,19 @@ def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_rese """ detect_port = ESPLoader(port, baud, trace_enabled=trace_enabled) detect_port.connect(connect_mode) - print('Detecting chip type...', end='') - sys.stdout.flush() - date_reg = detect_port.read_reg(ESPLoader.UART_DATA_REG_ADDR) - - for cls in [ESP8266ROM, ESP32ROM]: - if date_reg == cls.DATE_REG_VALUE: - # don't connect a second time - inst = cls(detect_port._port, baud, trace_enabled=trace_enabled) - print(' %s' % inst.CHIP_NAME) - return inst - print('') + try: + print('Detecting chip type...', end='') + sys.stdout.flush() + date_reg = detect_port.read_reg(ESPLoader.UART_DATA_REG_ADDR) + + for cls in [ESP8266ROM, ESP32ROM]: + if date_reg == cls.DATE_REG_VALUE: + # don't connect a second time + inst = cls(detect_port._port, baud, trace_enabled=trace_enabled) + print(' %s' % inst.CHIP_NAME, end='') + return inst + finally: + print('') # end line raise FatalError("Unexpected UART datecode value 0x%08x. Failed to autodetect chip type." % date_reg) """ Read a SLIP packet from the serial port """ @@ -243,7 +296,7 @@ def write(self, packet): buf = b'\xc0' \ + (packet.replace(b'\xdb',b'\xdb\xdd').replace(b'\xc0',b'\xdb\xdc')) \ + b'\xc0' - self.trace("Write %d bytes: %r", len(buf), buf) + self.trace("Write %d bytes: %s", len(buf), HexFormatter(buf)) self._port.write(buf) def trace(self, message, *format_args): @@ -278,8 +331,8 @@ def command(self, op=None, data=b"", chk=0, wait_response=True, timeout=DEFAULT_ try: if op is not None: - self.trace("command op=0x%02x data len=%s wait_response=%d timeout=%.3f data=%r", - op, len(data), 1 if wait_response else 0, timeout, data) + self.trace("command op=0x%02x data len=%s wait_response=%d timeout=%.3f data=%s", + op, len(data), 1 if wait_response else 0, timeout, HexFormatter(data)) pkt = struct.pack(b' start: + raise FatalError(("Software loader is resident at 0x%08x-0x%08x. " + + "Can't load binary at overlapping address range 0x%08x-0x%08x. " + + "Either change binary loading address, or use the --no-stub " + + "option to disable the software loader.") % (start, end, load_start, load_end)) + return self.check_command("enter RAM download mode", self.ESP_MEM_BEGIN, struct.pack(' length: raise FatalError('Read more than expected') + digest_frame = self.read() if len(digest_frame) != 16: raise FatalError('Expected digest, got: %s' % hexify(digest_frame)) @@ -821,10 +940,26 @@ def write_status(self, new_status, num_bytes=2, set_non_volatile=False): self.run_spiflash_command(SPIFLASH_WRDI) + def get_crystal_freq(self): + # Figure out the crystal frequency from the UART clock divider + # Returns a normalized value in integer MHz (40 or 26 are the only supported values) + # + # The logic here is: + # - We know that our baud rate and the ESP UART baud rate are roughly the same, or we couldn't communicate + # - We can read the UART clock divider register to know how the ESP derives this from the APB bus frequency + # - Multiplying these two together gives us the bus frequency which is either the crystal frequency (ESP32) + # or double the crystal frequency (ESP8266). See the self.XTAL_CLK_DIVIDER parameter for this factor. + uart_div = self.read_reg(self.UART_CLKDIV_REG) & self.UART_CLKDIV_MASK + est_xtal = (self._port.baudrate * uart_div) / 1e6 / self.XTAL_CLK_DIVIDER + norm_xtal = 40 if est_xtal > 33 else 26 + if abs(norm_xtal - est_xtal) > 1: + print("WARNING: Detected crystal freq %.2fMHz is quite different to normalized freq %dMHz. Unsupported crystal in use?" % (est_xtal, norm_xtal)) + return norm_xtal + def hard_reset(self): - self._port.setRTS(True) # EN->LOW + self._setRTS(True) # EN->LOW time.sleep(0.1) - self._port.setRTS(False) + self._setRTS(False) def soft_reset(self, stay_in_bootloader): if not self.IS_STUB: @@ -865,6 +1000,10 @@ class ESP8266ROM(ESPLoader): SPI_W0_OFFS = 0x40 SPI_HAS_MOSI_DLEN_REG = False + UART_CLKDIV_REG = 0x60000014 + + XTAL_CLK_DIVIDER = 2 + FLASH_SIZES = { '512KB':0x00, '256KB':0x10, @@ -879,6 +1018,11 @@ class ESP8266ROM(ESPLoader): BOOTLOADER_FLASH_OFFSET = 0 + MEMORY_MAP = [[0x3FF00000, 0x3FF00010, "DPORT"], + [0x3FFE8000, 0x40000000, "DRAM"], + [0x40100000, 0x40108000, "IRAM"], + [0x40201010, 0x402E1010, "IROM"]] + def get_efuses(self): # Return the 128 bits of ESP8266 efuse as a single Python integer return (self.read_reg(0x3ff0005c) << 96 | @@ -892,7 +1036,7 @@ def get_chip_description(self): return "ESP8285" if is_8285 else "ESP8266EX" def get_chip_features(self): - features = [ "WiFi" ] + features = ["WiFi"] if self.get_chip_description() == "ESP8285": features += ["Embedded Flash"] return features @@ -911,7 +1055,7 @@ def flash_set_parameters(self, size): super(ESP8266ROM, self).flash_set_parameters(size) def chip_id(self): - """ Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29 """ + """ Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function """ id0 = self.read_reg(self.ESP_OTP_MAC0) id1 = self.read_reg(self.ESP_OTP_MAC1) return (id0 >> 24) | ((id1 & MAX_UINT24) << 8) @@ -950,6 +1094,9 @@ def get_erase_size(self, offset, size): else: return (num_sectors - head_sectors) * sector_size + def override_vddsdio(self, new_voltage): + raise NotImplementedInROMError("Overriding VDDSDIO setting only applies to ESP32") + class ESP8266StubLoader(ESP8266ROM): """ Access class for ESP8266 stub loader, runs on top of ROM. @@ -974,6 +1121,7 @@ class ESP32ROM(ESPLoader): """ CHIP_NAME = "ESP32" + IMAGE_CHIP_ID = 0 IS_STUB = False DATE_REG_VALUE = 0x15122500 @@ -989,9 +1137,15 @@ class ESP32ROM(ESPLoader): SPI_REG_BASE = 0x60002000 EFUSE_REG_BASE = 0x6001a000 + DR_REG_SYSCON_BASE = 0x3ff66000 + SPI_W0_OFFS = 0x80 SPI_HAS_MOSI_DLEN_REG = True + UART_CLKDIV_REG = 0x3ff40014 + + XTAL_CLK_DIVIDER = 1 + FLASH_SIZES = { '1MB':0x00, '2MB':0x10, @@ -1002,17 +1156,81 @@ class ESP32ROM(ESPLoader): BOOTLOADER_FLASH_OFFSET = 0x1000 + OVERRIDE_VDDSDIO_CHOICES = ["1.8V", "1.9V", "OFF"] + + MEMORY_MAP = [[0x3F400000, 0x3F800000, "DROM"], + [0x3F800000, 0x3FC00000, "EXTRAM_DATA"], + [0x3FF80000, 0x3FF82000, "RTC_DRAM"], + [0x3FF90000, 0x40000000, "BYTE_ACCESSIBLE"], + [0x3FFAE000, 0x40000000, "DRAM"], + [0x3FFAE000, 0x40000000, "DMA"], + [0x3FFE0000, 0x3FFFFFFC, "DIRAM_DRAM"], + [0x40000000, 0x40070000, "IROM"], + [0x40070000, 0x40078000, "CACHE_PRO"], + [0x40078000, 0x40080000, "CACHE_APP"], + [0x40080000, 0x400A0000, "IRAM"], + [0x400A0000, 0x400BFFFC, "DIRAM_IRAM"], + [0x400C0000, 0x400C2000, "RTC_IRAM"], + [0x400D0000, 0x40400000, "IROM"], + [0x50000000, 0x50002000, "RTC_DATA"]] + + """ Try to read the BLOCK1 (encryption key) and check if it is valid """ + + def is_flash_encryption_key_valid(self): + + """ Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 + this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """ + word0 = self.read_efuse(0) + rd_disable = (word0 >> 16) & 0x1 + + # reading of BLOCK1 is NOT ALLOWED so we assume valid key is programmed + if rd_disable: + return True + else: + """ reading of BLOCK1 is ALLOWED so we will read and verify for non-zero. + When ESP32 has not generated AES/encryption key in BLOCK1, the contents will be readable and 0. + If the flash encryption is enabled it is expected to have a valid non-zero key. We break out on + first occurance of non-zero value """ + key_word = [0] * 7 + for i in range(len(key_word)): + key_word[i] = self.read_efuse(14 + i) + # key is non-zero so break & return + if key_word[i] != 0: + return True + return False + + """ For flash encryption related commands we need to make sure + user has programmed all the relevant efuse correctly so at + the end of write_flash_encrypt esptool will verify the values + of flash_crypt_config to be non zero if they are not read + protected. If the values are zero a warning will be printed + """ + + def get_flash_crypt_config(self): + """ bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config + this bit is at position 19 in EFUSE_BLK0_RDATA0_REG """ + word0 = self.read_efuse(0) + rd_disable = (word0 >> 19) & 0x1 + + if rd_disable == 0: + """ we can read the flash_crypt_config efuse value + so go & read it (EFUSE_BLK0_RDATA5_REG[31:28]) """ + word5 = self.read_efuse(5) + word5 = (word5 >> 28) & 0xF + return word5 + else: + # if read of the efuse is disabled we assume it is set correctly + return 0xF + def get_chip_description(self): word3 = self.read_efuse(3) - chip_version = (word3 >> 12) & 0xF + word5 = self.read_efuse(5) + apb_ctl_date = self.read_reg(self.DR_REG_SYSCON_BASE + 0x7C) + rev_bit0 = (word3 >> 15) & 0x1 + rev_bit1 = (word5 >> 20) & 0x1 + rev_bit2 = (apb_ctl_date >> 31) & 0x1 pkg_version = (word3 >> 9) & 0x07 - silicon_rev = { - 0x0: "0", - 0x8: "1", - 0xc: "1", # Silicon rev 1 w/ BLK3_PART_RESERVE bit set - }.get(chip_version, "(unknown 0x%x)" % chip_version) - chip_name = { 0: "ESP32D0WDQ6", 1: "ESP32D0WDQ5", @@ -1020,29 +1238,64 @@ def get_chip_description(self): 5: "ESP32-PICO-D4", }.get(pkg_version, "unknown ESP32") - return "%s (revision %s)" % (chip_name, silicon_rev) + chip_revision = 0 + if rev_bit0: + if rev_bit1: + if rev_bit2: + chip_revision = 3 + else: + chip_revision = 2 + else: + chip_revision = 1 + return "%s (revision %d)" % (chip_name, chip_revision) def get_chip_features(self): features = ["WiFi"] word3 = self.read_efuse(3) - if word3 & (1 << 1) == 0: # RD_CHIP_VER_DIS_BT + # names of variables in this section are lowercase + # versions of EFUSE names as documented in TRM and + # ESP-IDF efuse_reg.h + + chip_ver_dis_bt = word3 & (1 << 1) + if chip_ver_dis_bt == 0: features += ["BT"] - if word3 & (1 << 0): # RD_CHIP_VER_DIS_APP_CPU + chip_ver_dis_app_cpu = word3 & (1 << 0) + if chip_ver_dis_app_cpu: features += ["Single Core"] else: features += ["Dual Core"] + chip_cpu_freq_rated = word3 & (1 << 13) + if chip_cpu_freq_rated: + chip_cpu_freq_low = word3 & (1 << 12) + if chip_cpu_freq_low: + features += ["160MHz"] + else: + features += ["240MHz"] + pkg_version = (word3 >> 9) & 0x07 - if pkg_version != 0: + if pkg_version in [2, 4, 5]: features += ["Embedded Flash"] word4 = self.read_efuse(4) - vref = (word4 >> 8) & 0x1F - if vref != 0: + adc_vref = (word4 >> 8) & 0x1F + if adc_vref: features += ["VRef calibration in efuse"] + blk3_part_res = word3 >> 14 & 0x1 + if blk3_part_res: + features += ["BLK3 partially reserved"] + + word6 = self.read_efuse(6) + coding_scheme = word6 & 0x3 + features += ["Coding Scheme %s" % { + 0: "None", + 1: "3/4", + 2: "Repeat (UNSUPPORTED)", + 3: "Invalid"}[coding_scheme]] + return features def read_efuse(self, n): @@ -1050,9 +1303,7 @@ def read_efuse(self, n): return self.read_reg(self.EFUSE_REG_BASE + (4 * n)) def chip_id(self): - word16 = self.read_efuse(1) - word17 = self.read_efuse(2) - return ((word17 & MAX_UINT24) << 24) | (word16 >> 8) & MAX_UINT24 + raise NotSupportedError(self, "chip_id") def read_mac(self): """ Read MAC from EFUSE region """ @@ -1067,6 +1318,28 @@ def read_mac(self): def get_erase_size(self, offset, size): return size + def override_vddsdio(self, new_voltage): + new_voltage = new_voltage.upper() + if new_voltage not in self.OVERRIDE_VDDSDIO_CHOICES: + raise FatalError("The only accepted VDDSDIO overrides are '1.8V', '1.9V' and 'OFF'") + RTC_CNTL_SDIO_CONF_REG = 0x3ff48074 + RTC_CNTL_XPD_SDIO_REG = (1 << 31) + RTC_CNTL_DREFH_SDIO_M = (3 << 29) + RTC_CNTL_DREFM_SDIO_M = (3 << 27) + RTC_CNTL_DREFL_SDIO_M = (3 << 25) + # RTC_CNTL_SDIO_TIEH = (1 << 23) # not used here, setting TIEH=1 would set 3.3V output, not safe for esptool.py to do + RTC_CNTL_SDIO_FORCE = (1 << 22) + RTC_CNTL_SDIO_PD_EN = (1 << 21) + + reg_val = RTC_CNTL_SDIO_FORCE # override efuse setting + reg_val |= RTC_CNTL_SDIO_PD_EN + if new_voltage != "OFF": + reg_val |= RTC_CNTL_XPD_SDIO_REG # enable internal LDO + if new_voltage == "1.9V": + reg_val |= (RTC_CNTL_DREFH_SDIO_M | RTC_CNTL_DREFM_SDIO_M | RTC_CNTL_DREFL_SDIO_M) # boost voltage + self.write_reg(RTC_CNTL_SDIO_CONF_REG, reg_val) + print("VDDSDIO regulator set to %s" % new_voltage) + class ESP32StubLoader(ESP32ROM): """ Access class for ESP32 stub loader, runs on top of ROM. @@ -1096,20 +1369,20 @@ class ESPBOOTLOADER(object): def LoadFirmwareImage(chip, filename): """ Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are - original ROM firmware images (ESPFirmwareImage) or "v2" OTA bootloader images. + original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images. - Returns a BaseFirmwareImage subclass, either ESPFirmwareImage (v1) or OTAFirmwareImage (v2). + Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2). """ with open(filename, 'rb') as f: - if chip == 'esp32': + if chip.lower() == 'esp32': return ESP32FirmwareImage(f) else: # Otherwise, ESP8266 so look at magic to determine the image type magic = ord(f.read(1)) f.seek(0) if magic == ESPLoader.ESP_IMAGE_MAGIC: - return ESPFirmwareImage(f) + return ESP8266ROMFirmwareImage(f) elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC: - return OTAFirmwareImage(f) + return ESP8266V2FirmwareImage(f) else: raise FatalError("Invalid image magic number: %d" % magic) @@ -1119,10 +1392,11 @@ class ImageSegment(object): (very similar to a section in an ELFImage also) """ def __init__(self, addr, data, file_offs=None): self.addr = addr - # pad all ImageSegments to at least 4 bytes length - self.data = pad_to(data, 4, b'\x00') + self.data = data self.file_offs = file_offs self.include_in_checksum = True + if self.addr != 0: + self.pad_to_alignment(4) # pad all "real" ImageSegments 4 byte aligned length def copy_with_new_addr(self, new_addr): """ Return a new ImageSegment with same data, but mapped at @@ -1147,6 +1421,9 @@ def __repr__(self): r += " file_offs 0x%08x" % (self.file_offs) return r + def pad_to_alignment(self, alignment): + self.data = pad_to(self.data, alignment, b'\x00') + class ELFSection(ImageSegment): """ Wrapper class for a section in an ELF image, has a section @@ -1161,18 +1438,25 @@ def __repr__(self): class BaseFirmwareImage(object): SEG_HEADER_LEN = 8 + SHA256_DIGEST_LEN = 32 """ Base class with common firmware image functions """ def __init__(self): self.segments = [] self.entrypoint = 0 + self.elf_sha256 = None + self.elf_sha256_offset = 0 def load_common_header(self, load_file, expected_magic): - (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack(' 16: - raise FatalError('Invalid firmware image magic=%d segments=%d' % (magic, segments)) - return segments + def verify(self): + if len(self.segments) > 16: + raise FatalError('Invalid segment count %d (max 16). Usually this indicates a linker script problem.' % len(self.segments)) def load_segment(self, f, is_irom_segment=False): """ Load the next segment from the image file """ @@ -1191,12 +1475,36 @@ def warn_if_unusual_segment(self, offset, size, is_irom_segment): if offset > 0x40200000 or offset < 0x3ffe0000 or size > 65536: print('WARNING: Suspicious segment 0x%x, length %d' % (offset, size)) + def maybe_patch_segment_data(self, f, segment_data): + """If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data.""" + segment_len = len(segment_data) + file_pos = f.tell() # file_pos is position in the .bin file + if self.elf_sha256_offset >= file_pos and self.elf_sha256_offset < file_pos + segment_len: + # SHA256 digest needs to be patched into this binary segment, + # calculate offset of the digest inside the binary segment. + patch_offset = self.elf_sha256_offset - file_pos + # Sanity checks + if patch_offset < self.SEG_HEADER_LEN or patch_offset + self.SHA256_DIGEST_LEN > segment_len: + raise FatalError('Cannot place SHA256 digest on segment boundary' + + '(elf_sha256_offset=%d, file_pos=%d, segment_size=%d)' % + (self.elf_sha256_offset, file_pos, segment_len)) + if segment_data[patch_offset:patch_offset + self.SHA256_DIGEST_LEN] != b'\x00' * self.SHA256_DIGEST_LEN: + raise FatalError('Contents of segment at SHA256 digest offset 0x%x are not all zero. Refusing to overwrite.' % + self.elf_sha256_offset) + assert(len(self.elf_sha256) == self.SHA256_DIGEST_LEN) + # offset relative to the data part + patch_offset -= self.SEG_HEADER_LEN + segment_data = segment_data[0:patch_offset] + self.elf_sha256 + \ + segment_data[patch_offset + self.SHA256_DIGEST_LEN:] + return segment_data + def save_segment(self, f, segment, checksum=None): """ Save the next segment to the image file, return next checksum value if provided """ - f.write(struct.pack(' 0: - if len(irom_segments) != 1: - raise FatalError('Found %d segments that could be irom0. Bad ELF file?' % len(irom_segments)) - return irom_segments[0] - return None + irom_segments = [s for s in self.segments if self.is_irom_addr(s.addr)] + if len(irom_segments) > 0: + if len(irom_segments) != 1: + raise FatalError('Found %d segments that could be irom0. Bad ELF file?' % len(irom_segments)) + return irom_segments[0] + return None def get_non_irom_segments(self): irom_segment = self.get_irom_segment() return [s for s in self.segments if s != irom_segment] -class ESPFirmwareImage(BaseFirmwareImage): +class ESP8266ROMFirmwareImage(BaseFirmwareImage): """ 'Version 1' firmware image, segments loaded directly by the ROM bootloader. """ ROM_LOADER = ESP8266ROM def __init__(self, load_file=None): - super(ESPFirmwareImage, self).__init__() + super(ESP8266ROMFirmwareImage, self).__init__() self.flash_mode = 0 self.flash_size_freq = 0 self.version = 1 @@ -1261,6 +1569,8 @@ def __init__(self, load_file=None): self.load_segment(load_file) self.checksum = self.read_checksum(load_file) + self.verify() + def default_output_name(self, input_file): """ Derive a default output name from the ELF name. """ return input_file + '-' @@ -1283,7 +1593,10 @@ def save(self, basename): self.append_checksum(f, checksum) -class OTAFirmwareImage(BaseFirmwareImage): +ESP8266ROM.BOOTLOADER_IMAGE = ESP8266ROMFirmwareImage + + +class ESP8266V2FirmwareImage(BaseFirmwareImage): """ 'Version 2' firmware image, segments loaded by software bootloader stub (ie Espressif bootloader or rboot) """ @@ -1291,7 +1604,7 @@ class OTAFirmwareImage(BaseFirmwareImage): ROM_LOADER = ESP8266ROM def __init__(self, load_file=None): - super(OTAFirmwareImage, self).__init__() + super(ESP8266V2FirmwareImage, self).__init__() self.version = 2 if load_file is not None: segments = self.load_common_header(load_file, ESPBOOTLOADER.IMAGE_V2_MAGIC) @@ -1304,8 +1617,7 @@ def __init__(self, load_file=None): # the file is saved in the image with a zero load address # in the header, so we need to calculate a load address irom_segment = self.load_segment(load_file, True) - # for actual mapped addr, add ESP8266ROM.IROM_MAP_START + flashing_Addr + 8 - irom_segment.addr = 0 + irom_segment.addr = 0 # for actual mapped addr, add ESP8266ROM.IROM_MAP_START + flashing_addr + 8 irom_segment.include_in_checksum = False first_flash_mode = self.flash_mode @@ -1330,6 +1642,8 @@ def __init__(self, load_file=None): self.load_segment(load_file) self.checksum = self.read_checksum(load_file) + self.verify() + def default_output_name(self, input_file): """ Derive a default output name from the ELF name. """ irom_segment = self.get_irom_segment() @@ -1350,6 +1664,7 @@ def save(self, filename): if irom_segment is not None: # save irom0 segment, make sure it has load addr 0 in the file irom_segment = irom_segment.copy_with_new_addr(0) + irom_segment.pad_to_alignment(16) # irom_segment must end on a 16 byte boundary self.save_segment(f, irom_segment) # second header, matches V1 header and contains loadable segments @@ -1360,6 +1675,29 @@ def save(self, filename): checksum = self.save_segment(f, segment, checksum) self.append_checksum(f, checksum) + # calculate a crc32 of entire file and append + # (algorithm used by recent 8266 SDK bootloaders) + with open(filename, 'rb') as f: + crc = esp8266_crc32(f.read()) + with open(filename, 'ab') as f: + f.write(struct.pack(b' 0: last_addr = flash_segments[0].addr for segment in flash_segments[1:]: - if segment.addr // IROM_ALIGN == last_addr // IROM_ALIGN: + if segment.addr // self.IROM_ALIGN == last_addr // self.IROM_ALIGN: raise FatalError(("Segment loaded at 0x%08x lands in same 64KB flash mapping as segment loaded at 0x%08x. " + "Can't generate binary. Suggest changing linker script or ELF to merge sections.") % (segment.addr, last_addr)) @@ -1459,15 +1801,15 @@ def get_alignment_data_needed(segment): # # (this is because the segment's vaddr may not be IROM_ALIGNed, more likely is aligned # IROM_ALIGN+0x18 to account for the binary file header - align_past = (segment.addr % IROM_ALIGN) - self.SEG_HEADER_LEN - pad_len = (IROM_ALIGN - (f.tell() % IROM_ALIGN)) + align_past - if pad_len == 0 or pad_len == IROM_ALIGN: + align_past = (segment.addr % self.IROM_ALIGN) - self.SEG_HEADER_LEN + pad_len = (self.IROM_ALIGN - (f.tell() % self.IROM_ALIGN)) + align_past + if pad_len == 0 or pad_len == self.IROM_ALIGN: return 0 # already aligned # subtract SEG_HEADER_LEN a second time, as the padding block has a header as well pad_len -= self.SEG_HEADER_LEN if pad_len < 0: - pad_len += IROM_ALIGN + pad_len += self.IROM_ALIGN return pad_len # try to fit each flash segment on a 64kB aligned boundary @@ -1486,8 +1828,8 @@ def get_alignment_data_needed(segment): total_segments += 1 else: # write the flash segment - assert (f.tell() + 8) % IROM_ALIGN == segment.addr % IROM_ALIGN - checksum = self.save_segment(f, segment, checksum) + assert (f.tell() + 8) % self.IROM_ALIGN == segment.addr % self.IROM_ALIGN + checksum = self.save_flash_segment(f, segment, checksum) flash_segments.pop(0) total_segments += 1 @@ -1496,11 +1838,31 @@ def get_alignment_data_needed(segment): checksum = self.save_segment(f, segment, checksum) total_segments += 1 + if self.secure_pad: + # pad the image so that after signing it will end on a a 64KB boundary. + # This ensures all mapped flash content will be verified. + if not self.append_digest: + raise FatalError("secure_pad only applies if a SHA-256 digest is also appended to the image") + align_past = (f.tell() + self.SEG_HEADER_LEN) % self.IROM_ALIGN + # 16 byte aligned checksum (force the alignment to simplify calculations) + checksum_space = 16 + # after checksum: SHA-256 digest + (to be added by signing process) version, signature + 12 trailing bytes due to alignment + space_after_checksum = 32 + 4 + 64 + 12 + pad_len = (self.IROM_ALIGN - align_past - checksum_space - space_after_checksum) % self.IROM_ALIGN + pad_segment = ImageSegment(0, b'\x00' * pad_len, f.tell()) + + checksum = self.save_segment(f, pad_segment, checksum) + total_segments += 1 + # done writing segments self.append_checksum(f, checksum) + image_length = f.tell() + + if self.secure_pad: + assert ((image_length + space_after_checksum) % self.IROM_ALIGN) == 0 + # kinda hacky: go back to the initial header and write the new segment count # that includes padding segments. This header is not checksummed - image_length = f.tell() f.seek(1) try: f.write(chr(total_segments)) @@ -1517,6 +1879,16 @@ def get_alignment_data_needed(segment): with open(filename, 'wb') as real_file: real_file.write(f.getvalue()) + def save_flash_segment(self, f, segment, checksum=None): + """ Save the next segment to the image file, return next checksum value if provided """ + segment_end_pos = f.tell() + len(segment.data) + self.SEG_HEADER_LEN + segment_len_remainder = segment_end_pos % self.IROM_ALIGN + if segment_len_remainder < 0x24: + # Work around a bug in ESP-IDF 2nd stage bootloader, that it didn't map the + # last MMU page, if an IROM/DROM segment was < 0x24 bytes over the page boundary. + segment.data += b'\x00' * (0x24 - segment_len_remainder) + return self.save_segment(f, segment, checksum) + def load_extended_header(self, load_file): def split_byte(n): return (n & 0x0F, (n >> 4) & 0x0F) @@ -1530,15 +1902,21 @@ def split_byte(n): self.d_drv, self.cs_drv = split_byte(fields[2]) self.hd_drv, self.wp_drv = split_byte(fields[3]) - if fields[15] in [0, 1]: - self.append_digest = (fields[15] == 1) - else: - raise RuntimeError("Invalid value for append_digest field (0x%02x). Should be 0 or 1.", fields[15]) + chip_id = fields[4] + if chip_id != self.ROM_LOADER.IMAGE_CHIP_ID: + print("Unexpected chip id in image. Expected %d but value was %d. Is this image for a different chip model?" % (self.ROM_LOADER.IMAGE_CHIP_ID, chip_id)) - # remaining fields in the middle should all be zero - if any(f for f in fields[4:15] if f != 0): + # reserved fields in the middle should all be zero + if any(f for f in fields[6:-1] if f != 0): print("Warning: some reserved header fields have non-zero values. This image may be from a newer esptool.py?") + append_digest = fields[-1] # last byte is append_digest + if append_digest in [0, 1]: + self.append_digest = (append_digest == 1) + else: + raise RuntimeError("Invalid value for append_digest field (0x%02x). Should be 0 or 1.", append_digest) + + def save_extended_header(self, save_file): def join_byte(ln,hn): return (ln & 0x0F) + ((hn & 0x0F) << 4) @@ -1548,14 +1926,19 @@ def join_byte(ln,hn): fields = [self.wp_pin, join_byte(self.clk_drv, self.q_drv), join_byte(self.d_drv, self.cs_drv), - join_byte(self.hd_drv, self.wp_drv)] - fields += [0] * 11 + join_byte(self.hd_drv, self.wp_drv), + self.ROM_LOADER.IMAGE_CHIP_ID, + self.min_rev] + fields += [0] * 8 # padding fields += [append_digest] packed = struct.pack(self.EXTENDED_HEADER_STRUCT_FMT, *fields) save_file.write(packed) +ESP32ROM.BOOTLOADER_IMAGE = ESP32FirmwareImage + + class ELFFile(object): SEC_TYPE_PROGBITS = 0x01 SEC_TYPE_STRTAB = 0x03 @@ -1633,9 +2016,16 @@ def read_data(offs,size): return f.read(size) prog_sections = [ELFSection(lookup_string(n_offs), lma, read_data(offs, size)) for (n_offs, _type, lma, size, offs) in prog_sections - if lma != 0] + if lma != 0 and size > 0] self.sections = prog_sections + def sha256(self): + # return SHA256 hash of the input ELF file + sha256 = hashlib.sha256() + with open(self.name, 'rb') as f: + sha256.update(f.read()) + return sha256.digest() + def slip_reader(port, trace_function): """Generator to read SLIP packets from a serial port. @@ -1653,7 +2043,7 @@ def slip_reader(port, trace_function): waiting_for = "header" if partial_packet is None else "content" trace_function("Timed out waiting for packet %s", waiting_for) raise FatalError("Timed out waiting for packet %s" % waiting_for) - trace_function("Read %d bytes: %r", len(read_bytes), read_bytes) + trace_function("Read %d bytes: %s", len(read_bytes), HexFormatter(read_bytes)) for b in read_bytes: if type(b) is int: b = bytes([b]) # python 2/3 compat @@ -1662,9 +2052,9 @@ def slip_reader(port, trace_function): if b == b'\xc0': partial_packet = b"" else: - trace_function("Read invalid data: %r", read_bytes) - trace_function("Remaining data in serial buffer: %r", port.read(port.inWaiting())) - raise FatalError('Invalid head of packet (%r)' % b) + trace_function("Read invalid data: %s", HexFormatter(read_bytes)) + trace_function("Remaining data in serial buffer: %s", HexFormatter(port.read(port.inWaiting()))) + raise FatalError('Invalid head of packet (0x%s)' % hexify(b)) elif in_escape: # part-way through escape sequence in_escape = False if b == b'\xdc': @@ -1672,13 +2062,13 @@ def slip_reader(port, trace_function): elif b == b'\xdd': partial_packet += b'\xdb' else: - trace_function("Read invalid data: %r", read_bytes) - trace_function("Remaining data in serial buffer: %r", port.read(port.inWaiting())) - raise FatalError('Invalid SLIP escape (%r%r)' % (b'\xdb', b)) + trace_function("Read invalid data: %s", HexFormatter(read_bytes)) + trace_function("Remaining data in serial buffer: %s", HexFormatter(port.read(port.inWaiting()))) + raise FatalError('Invalid SLIP escape (0xdb, 0x%s)' % (hexify(b))) elif b == b'\xdb': # start of escape sequence in_escape = True elif b == b'\xc0': # end of packet - trace_function("Full packet: %r", partial_packet) + trace_function("Received full packet: %s", HexFormatter(partial_packet)) yield partial_packet partial_packet = None else: # normal byte in packet @@ -1715,25 +2105,47 @@ def flash_size_bytes(size): raise FatalError("Unknown size %s" % size) -def hexify(s): +def hexify(s, uppercase=True): + format_str = '%02X' if uppercase else '%02x' if not PYTHON2: - return ''.join('%02X' % c for c in s) + return ''.join(format_str % c for c in s) else: - return ''.join('%02X' % ord(c) for c in s) + return ''.join(format_str % ord(c) for c in s) + +class HexFormatter(object): + """ + Wrapper class which takes binary data in its constructor + and returns a hex string as it's __str__ method. -def unhexify(hs): - s = bytes() + This is intended for "lazy formatting" of trace() output + in hex format. Avoids overhead (significant on slow computers) + of generating long hex strings even if tracing is disabled. - for i in range(0, len(hs) - 1, 2): - hex_string = hs[i:i + 2] + Note that this doesn't save any overhead if passed as an + argument to "%", only when passed to trace() - if not PYTHON2: - s += bytes([int(hex_string, 16)]) + If auto_split is set (default), any long line (> 16 bytes) will be + printed as separately indented lines, with ASCII decoding at the end + of each line. + """ + def __init__(self, binary_string, auto_split=True): + self._s = binary_string + self._auto_split = auto_split + + def __str__(self): + if self._auto_split and len(self._s) > 16: + result = "" + s = self._s + while len(s) > 0: + line = s[:16] + ascii_line = "".join(c if (c == ' ' or (c in string.printable and c not in string.whitespace)) + else '.' for c in line.decode('ascii', 'replace')) + s = s[16:] + result += "\n %-16s %-16s | %s" % (hexify(line[:8], False), hexify(line[8:], False), ascii_line) + return result else: - s += chr(int(hex_string, 16)) - - return s + return hexify(self._s, False) def pad_to(data, alignment, pad_character=b'\xFF'): @@ -1770,6 +2182,11 @@ class NotImplementedInROMError(FatalError): def __init__(self, bootloader, func): FatalError.__init__(self, "%s ROM does not support function %s." % (bootloader.CHIP_NAME, func.__name__)) + +class NotSupportedError(FatalError): + def __init__(self, esp, function_name): + FatalError.__init__(self, "Function %s is not supported for %s." % (function_name, esp.CHIP_NAME)) + # "Operation" commands, executable at command line. One function each # # Each function takes either two args (, ) or a single @@ -1777,18 +2194,19 @@ def __init__(self, bootloader, func): def load_ram(esp, args): - image = LoadFirmwareImage(esp, args.filename) + image = LoadFirmwareImage(esp.CHIP_NAME, args.filename) print('RAM boot...') - for (offset, size, data) in image.segments: - print('Downloading %d bytes at %08x...' % (size, offset), end=' ') + for seg in image.segments: + size = len(seg.data) + print('Downloading %d bytes at %08x...' % (size, seg.addr), end=' ') sys.stdout.flush() - esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, offset) + esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, seg.addr) seq = 0 - while len(data) > 0: - esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq) - data = data[esp.ESP_RAM_BLOCK:] + while len(seg.data) > 0: + esp.mem_block(seg.data[0:esp.ESP_RAM_BLOCK], seq) + seg.data = seg.data[esp.ESP_RAM_BLOCK:] seq += 1 print('done!') @@ -1806,15 +2224,15 @@ def write_mem(esp, args): def dump_mem(esp, args): - f = open(args.filename, 'wb') - for i in range(args.size // 4): - d = esp.read_reg(args.address + (i * 4)) - f.write(struct.pack(b' flash_end: - raise FatalError(("File %s (length %d) at offset %d will not fit in %d bytes of flash. " + - "Use --flash-size argument, or change flashing address.") - % (argfile.name, argfile.tell(), address, flash_end)) - argfile.seek(0) + if args.flash_size != 'keep': # TODO: check this even with 'keep' + flash_end = flash_size_bytes(args.flash_size) + for address, argfile in args.addr_filename: + argfile.seek(0,2) # seek to end + if address + argfile.tell() > flash_end: + raise FatalError(("File %s (length %d) at offset %d will not fit in %d bytes of flash. " + + "Use --flash-size argument, or change flashing address.") + % (argfile.name, argfile.tell(), address, flash_end)) + argfile.seek(0) + + if args.erase_all: + erase_flash(esp, args) + + if args.encrypt and args.compress: + print('\nWARNING: - compress and encrypt options are mutually exclusive ') + print('Will flash uncompressed') + args.compress = False for address, argfile in args.addr_filename: if args.no_stub: print('Erasing flash...') - image = pad_to(argfile.read(), 4) + image = pad_to(argfile.read(), 32 if args.encrypt else 4) if len(image) == 0: print('WARNING: File %s is empty' % argfile.name) continue @@ -1902,11 +2371,14 @@ def write_flash(esp, args): sys.stdout.flush() block = image[0:esp.FLASH_WRITE_SIZE] if args.compress: - esp.flash_defl_block(block, seq, timeout=DEFAULT_TIMEOUT * ratio) + esp.flash_defl_block(block, seq, timeout=DEFAULT_TIMEOUT * ratio * 2) else: # Pad the last block block = block + b'\xff' * (esp.FLASH_WRITE_SIZE - len(block)) - esp.flash_block(block, seq) + if args.encrypt: + esp.flash_encrypt_block(block, seq) + else: + esp.flash_block(block, seq) image = image[esp.FLASH_WRITE_SIZE:] seq += 1 written += len(block) @@ -1920,17 +2392,19 @@ def write_flash(esp, args): if t > 0.0: speed_msg = " (%.1f kbit/s)" % (written / t * 8 / 1000) print('\rWrote %d bytes at 0x%08x in %.1f seconds%s...' % (written, address, t, speed_msg)) - try: - res = esp.flash_md5sum(address, uncsize) - if res != calcmd5: - print('File md5: %s' % calcmd5) - print('Flash md5: %s' % res) - print('MD5 of 0xFF is %s' % (hashlib.md5(b'\xFF' * uncsize).hexdigest())) - raise FatalError("MD5 of file does not match data in flash!") - else: - print('Hash of data verified.') - except NotImplementedInROMError: - pass + + if not args.encrypt: + try: + res = esp.flash_md5sum(address, uncsize) + if res != calcmd5: + print('File md5: %s' % calcmd5) + print('Flash md5: %s' % res) + print('MD5 of 0xFF is %s' % (hashlib.md5(b'\xFF' * uncsize).hexdigest())) + raise FatalError("MD5 of file does not match data in flash!") + else: + print('Hash of data verified.') + except NotImplementedInROMError: + pass print('\nLeaving...') @@ -1954,11 +2428,12 @@ def image_info(args): print('Image version: %d' % image.version) print('Entry point: %08x' % image.entrypoint if image.entrypoint != 0 else 'Entry point not set') print('%d segments' % len(image.segments)) - print + print() idx = 0 for seg in image.segments: idx += 1 - print('Segment %d: %r' % (idx, seg)) + seg_name = ", ".join([seg_range[2] for seg_range in image.ROM_LOADER.MEMORY_MAP if seg_range[0] <= seg.addr < seg_range[1]]) + print('Segment %d: %r [%s]' % (idx, seg, seg_name)) calc_checksum = image.calculate_checksum() print('Checksum: %02x (%s)' % (image.checksum, 'valid' if image.checksum == calc_checksum else 'invalid - calculated %02x' % calc_checksum)) @@ -1974,14 +2449,15 @@ def image_info(args): def make_image(args): - image = ESPFirmwareImage() + image = ESP8266ROMFirmwareImage() if len(args.segfile) == 0: raise FatalError('No segments specified') if len(args.segfile) != len(args.segaddr): raise FatalError('Number of specified files does not match number of specified addresses') for (seg, addr) in zip(args.segfile, args.segaddr): - data = open(seg, 'rb').read() - image.segments.append(ImageSegment(addr, data)) + with open(seg, 'rb') as f: + data = f.read() + image.segments.append(ImageSegment(addr, data)) image.entrypoint = args.entrypoint image.save(args.output) @@ -1994,16 +2470,24 @@ def elf2image(args): if args.chip == 'esp32': image = ESP32FirmwareImage() + image.secure_pad = args.secure_pad + image.min_rev = int(args.min_rev) elif args.version == '1': # ESP8266 - image = ESPFirmwareImage() + image = ESP8266ROMFirmwareImage() else: - image = OTAFirmwareImage() + image = ESP8266V2FirmwareImage() image.entrypoint = e.entrypoint image.segments = e.sections # ELFSection is a subclass of ImageSegment image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode] image.flash_size_freq = image.ROM_LOADER.FLASH_SIZES[args.flash_size] image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq] + if args.elf_sha256_offset: + image.elf_sha256 = e.sha256() + image.elf_sha256_offset = args.elf_sha256_offset + + image.verify() + if args.output is None: args.output = image.default_output_name(args.input) image.save(args.output) @@ -2018,8 +2502,12 @@ def print_mac(label, mac): def chip_id(esp, args): - chipid = esp.chip_id() - print('Chip ID: 0x%08x' % chipid) + try: + chipid = esp.chip_id() + print('Chip ID: 0x%08x' % chipid) + except NotSupportedError: + print('Warning: %s has no Chip ID. Reading MAC instead.' % esp.CHIP_NAME) + read_mac(esp, args) def erase_flash(esp, args): @@ -2064,7 +2552,8 @@ def flash_progress(progress, length): t = time.time() - t print('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...' % (len(data), args.address, t, len(data) / t * 8 / 1000)) - open(args.filename, 'wb').write(data) + with open(args.filename, 'wb') as f: + f.write(data) def verify_flash(esp, args): @@ -2126,7 +2615,14 @@ def version(args): # -def main(): +def main(custom_commandline=None): + """ + Main function for esptool + + custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments + as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus + becomes ['-b', '115200']. + """ parser = argparse.ArgumentParser(description='esptool.py v%s - ESP8266 ROM Bootloader Utility' % __version__, prog='esptool') parser.add_argument('--chip', '-c', @@ -2137,7 +2633,7 @@ def main(): parser.add_argument( '--port', '-p', help='Serial port device', - default=os.environ.get('ESPTOOL_PORT', ESPLoader.DEFAULT_PORT)) + default=os.environ.get('ESPTOOL_PORT', None)) parser.add_argument( '--baud', '-b', @@ -2148,7 +2644,7 @@ def main(): parser.add_argument( '--before', help='What to do before connecting to the chip', - choices=['default_reset', 'no_reset'], + choices=['default_reset', 'no_reset', 'no_reset_no_sync'], default=os.environ.get('ESPTOOL_BEFORE', 'default_reset')) parser.add_argument( @@ -2167,6 +2663,12 @@ def main(): help="Enable trace-level output of esptool.py interactions.", action='store_true') + parser.add_argument( + '--override-vddsdio', + help="Override ESP32 VDDSDIO internal voltage regulator (use with care)", + choices=ESP32ROM.OVERRIDE_VDDSDIO_CHOICES, + nargs='?') + subparsers = parser.add_subparsers( dest='operation', help='Run esptool {command} -h for additional help') @@ -2205,6 +2707,11 @@ def add_spi_flash_subparsers(parent, is_elf2image): extra_keep_args = [] if is_elf2image else ['keep'] auto_detect = not is_elf2image + if auto_detect: + extra_fs_message = ", detect, or keep" + else: + extra_fs_message = "" + parent.add_argument('--flash_freq', '-ff', help='SPI Flash frequency', choices=extra_keep_args + ['40m', '26m', '20m', '80m'], default=os.environ.get('ESPTOOL_FF', '40m' if is_elf2image else 'keep')) @@ -2212,7 +2719,7 @@ def add_spi_flash_subparsers(parent, is_elf2image): choices=extra_keep_args + ['qio', 'qout', 'dio', 'dout'], default=os.environ.get('ESPTOOL_FM', 'qio' if is_elf2image else 'keep')) parent.add_argument('--flash_size', '-fs', help='SPI Flash size in MegaBytes (1MB, 2MB, 4MB, 8MB, 16M)' - ' plus ESP8266-only (256KB, 512KB, 2MB-c1, 4MB-c1)', + ' plus ESP8266-only (256KB, 512KB, 2MB-c1, 4MB-c1)' + extra_fs_message, action=FlashSizeAction, auto_detect=auto_detect, default=os.environ.get('ESPTOOL_FS', 'detect' if auto_detect else '1MB')) add_spi_connection_arg(parent) @@ -2220,12 +2727,22 @@ def add_spi_flash_subparsers(parent, is_elf2image): parser_write_flash = subparsers.add_parser( 'write_flash', help='Write a binary blob to flash') + parser_write_flash.add_argument('addr_filename', metavar='
', help='Address followed by binary filename, separated by space', action=AddrFilenamePairAction) + parser_write_flash.add_argument('--erase-all', '-e', + help='Erase all regions of flash (not just write areas) before programming', + action="store_true") + add_spi_flash_subparsers(parser_write_flash, is_elf2image=False) parser_write_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true") parser_write_flash.add_argument('--verify', help='Verify just-written data on flash ' + '(mostly superfluous, data is read back during flashing)', action='store_true') + parser_write_flash.add_argument('--encrypt', help='Encrypt before write ', + action='store_true') + parser_write_flash.add_argument('--ignore-flash-encryption-efuse-setting', help='Ignore flash encryption efuse settings ', + action='store_true') + compress_args = parser_write_flash.add_mutually_exclusive_group(required=False) compress_args.add_argument('--compress', '-z', help='Compress data in transfer (default unless --no-stub is specified)',action="store_true", default=None) compress_args.add_argument('--no-compress', '-u', help='Disable data compression during transfer (default if --no-stub is specified)',action="store_true") @@ -2253,6 +2770,10 @@ def add_spi_flash_subparsers(parent, is_elf2image): parser_elf2image.add_argument('input', help='Input ELF file') parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str) parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1','2'], default='1') + parser_elf2image.add_argument('--min-rev', '-r', help='Minimum chip revision', choices=['0','1','2','3'], default='0') + parser_elf2image.add_argument('--secure-pad', action='store_true', help='Pad image so once signed it will end on a 64KB boundary. For ESP32 images only.') + parser_elf2image.add_argument('--elf-sha256-offset', help='If set, insert SHA256 hash (32 bytes) of the input ELF file at specified offset in the binary.', + type=arg_auto_int, default=None) add_spi_flash_subparsers(parser_elf2image, is_elf2image=True) @@ -2324,7 +2845,7 @@ def add_spi_flash_subparsers(parent, is_elf2image): expand_file_arguments() - args = parser.parse_args() + args = parser.parse_args(custom_commandline) print('esptool.py v%s' % __version__) @@ -2344,24 +2865,52 @@ def add_spi_flash_subparsers(parent, is_elf2image): operation_args = inspect.getfullargspec(operation_func).args if operation_args[0] == 'esp': # operation function takes an ESPLoader connection object - initial_baud = min(ESPLoader.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate - if args.chip == 'auto': - esp = ESPLoader.detect_chip(args.port, initial_baud, args.before, args.trace) + if args.before != "no_reset_no_sync": + initial_baud = min(ESPLoader.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate else: - chip_class = { - 'esp8266': ESP8266ROM, - 'esp32': ESP32ROM, - }[args.chip] - esp = chip_class(args.port, initial_baud, args.trace) - esp.connect(args.before) + initial_baud = args.baud + + if args.port is None: + ser_list = sorted(ports.device for ports in list_ports.comports()) + print("Found %d serial ports" % len(ser_list)) + else: + ser_list = [args.port] + esp = None + for each_port in reversed(ser_list): + print("Serial port %s" % each_port) + try: + if args.chip == 'auto': + esp = ESPLoader.detect_chip(each_port, initial_baud, args.before, args.trace) + else: + chip_class = { + 'esp8266': ESP8266ROM, + 'esp32': ESP32ROM, + }[args.chip] + esp = chip_class(each_port, initial_baud, args.trace) + esp.connect(args.before) + break + except (FatalError, OSError) as err: + if args.port is not None: + raise + print("%s failed to connect: %s" % (each_port, err)) + esp = None + if esp is None: + raise FatalError("Could not connect to an Espressif device on any of the %d available serial ports." % len(ser_list)) print("Chip is %s" % (esp.get_chip_description())) print("Features: %s" % ", ".join(esp.get_chip_features())) + print("Crystal is %dMHz" % esp.get_crystal_freq()) + + read_mac(esp, args) + if not args.no_stub: esp = esp.run_stub() + if args.override_vddsdio: + esp.override_vddsdio(args.override_vddsdio) + if args.baud > initial_baud: try: esp.change_baud(args.baud) @@ -2382,12 +2931,23 @@ def add_spi_flash_subparsers(parent, is_elf2image): if hasattr(args, "flash_size"): print("Configuring flash size...") detect_flash_size(esp, args) - esp.flash_set_parameters(flash_size_bytes(args.flash_size)) + if args.flash_size != 'keep': # TODO: should set this even with 'keep' + esp.flash_set_parameters(flash_size_bytes(args.flash_size)) - operation_func(esp, args) + try: + operation_func(esp, args) + finally: + try: # Clean up AddrFilenamePairAction files + for address, argfile in args.addr_filename: + argfile.close() + except AttributeError: + pass - # finish execution based on args.after - if args.after == 'hard_reset': + # Handle post-operation behaviour (reset or other) + if operation_func == load_ram: + # the ESP is now running the loaded image, so let it run + print('Exiting immediately.') + elif args.after == 'hard_reset': print('Hard resetting via RTS pin...') esp.hard_reset() elif args.after == 'soft_reset': @@ -2399,6 +2959,8 @@ def add_spi_flash_subparsers(parent, is_elf2image): if esp.IS_STUB: esp.soft_reset(True) # exit stub back to ROM loader + esp._port.close() + else: operation_func(args) @@ -2453,6 +3015,7 @@ def __call__(self, parser, namespace, values, option_string=None): known_sizes.update(ESP32ROM.FLASH_SIZES) if self._auto_detect: known_sizes['detect'] = 'detect' + known_sizes['keep'] = 'keep' if value not in known_sizes: raise argparse.ArgumentError(self, '%s is not a known flash size. Known sizes: %s' % (value, ", ".join(known_sizes.keys()))) setattr(namespace, self.dest, value) @@ -2497,7 +3060,7 @@ def __call__(self, parser, namespace, values, option_string=None): for i in range(0,len(values),2): try: address = int(values[i],0) - except ValueError as e: + except ValueError: raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i]) try: argfile = open(values[i + 1], 'rb') @@ -2524,104 +3087,105 @@ def __call__(self, parser, namespace, values, option_string=None): # Binary stub code (see flasher_stub dir for source & details) ESP8266ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b""" -eNrNPXt/1Da2X2XshJCEASzb40cIy2QShkdhG6BJQ3/TbWzZhlJgkyG7SVn2fvbr85Jkz4RA2e69f4SObFk6Ou9zdKT+6/pZfXF2fWtQXp9dFNnsQgWziyAYt/+o2UXTwN/0Pjzq/mXtX1Pf+/7hzqP2u7j9K6Hr\ -vfat5kZ9j7plzme67alymGVMPenFcW8Ctfy3cvoQaA5AujsTzdCD2n40Xrqc2UWub/A6ikB+tdNedwaOHajNgAxJBxO9hgxXdrDVQdBgw4G1JUZWIVhHDoBAI/N1Do3aaeQG8bHzBj5WpR26CGbzHnIyA8LsTH7u\ -t//UTkOFzhDaAaMMnIZqzCK228c5AxS4oAKxisqBLnCgCzovNc1l5lEjB0WqywNB4LAeNmT2UguNWsJnmdMobOMIvxoPn+B/gjv4n4uHhl0e868yfsS/tL7Fv1Q7QR1yo8py/PXaPGsHqWTGvAWsRq4eP1kTkHhI\ -j0CFReXtl4UipodPVPtbB36x4iMBacFhsds+DYtJO35Y7MB8RTtcExb3SHTqlEbTBkUwRQgP27dlxAgE9ABfJ67AAUjhd34KvTOeNdObHvRvpw1aSpTQWXlC2nYeJcRT8nBzCNMPWAEAZsKJLEHWMqJ5q2IJtEjE\ -hrERKDMYECYM4oF5gEMP4R8eLe6PdtlzgBVxsiM/nrU/EDmn8oOxFJYMCA+mm2WDoa7xSCabZis0MK63/7TDqWQunwliMnpDk5gXG/apisId4JSQOyn/2S4+GfmFDwwD4wKd8G0U2rEywLNSgT9oJrOz9WEHmrD9\ -msmgeU1l2V+TUB/UNzQyGBYpl90nBKG5kDkj352cBlNqAD8GLVYyZsomJV5UKbFAXuGyaOS6ZmDUJcAItEWzSGbdMnJVMd8Qtui/VQi6HFCFSE4AffBJGj5rBOD2Yc56r0k+rDTYefqzPNmdvW9WpOsTnjNh6A0M\ -zS5+dYq/XzjTRRbCPOtqvbwDXJB8JMgAy80HZwgxWgl3Dhr5anphRyud0abv4Pm0/YbVpdI9ROQ013pDWoFWN5bO8KAF5D2N3PTgvGWRAKSVT5QLwESe+87DlwJV6NC1UtBDRcN2wjN5FtAz4HCA9t89XuiSNUuu\ -ue+i7jtSrcHIxZWqQJmD8UIUz1glJcYWNow64gN8d+pqld8XebBulVldgUtBpjNL3hkjO9yBj/7Z/+iQYFMFrog4GFd/i3pl+ukAeDA+fAGGjRVmCPbkLuuohDW59SlA7FC/vl+Y7jnhsw5oLo1z3eYf6V9oDTAH\ -mrHFoWkZzWXLSJYu45AtRA2o/tHSAHyNKhTZXjMIPxJuLxnzQpCyEZIeC03uLLy6R6908leX2mvSZfoUHmdPvA1Hx7uAhMJ4jrxP7/B8MFbM06mwHWXly0aZig7YooEAQ0E83XGR2+pJVbvDhSxugTNuQhbeijG6\ -MNkQfJDnxBpooIBpwI5oqzx5mBwMBbK+mPi6mdqZ6mJ3YskOTmRdj30YLr0F4z9n6EaleBET/oGK6gD0vqjg9PgArc4ePNzfG0AHtBzjaABwaTEqWsmaByi+LZDTGw5eAGWAF4sGBzcqiWZnoFDM2+yQdVoWshZC\ -5OhkYHVVRgqEeGJgyYsOMLLMdGBY73vstSpMRwLb4bsANdCIKNQJZ/hr4ILV7jSW90lLqbTzmeFY35kXRwa3ryGBsgS/IKppnXbZpdF/V6SXGnfO/DU5Gk2aDOHzAQU6Lky5YRRyy3PWpgHCudk2cvats+98agWj\ -zR8H1Esjz4Cqal4SaNghmgoDGQ3Lq48dGasslhYRStpJXGKBGPkjGIACH31gXxibejR3vAzthJgLSqwEnViKL6NkFnBbVNhaqQjFfyIkRzPVLq0pnSewhHgN+XMKLNaAdBG/AOetpGyO2rcXGh7HoZg0nOYR29Io\ -5QAMB/YY2sSOhZIBXmRTW28MlayrUpAFauMAArVCeAwSVQ8idO/AhY4GKyAUrjtd6/54d+HlTYwlFdmK7nufXMM64w5Jv4PlYhvG4fQ0cTSBf+MjsMfZ6B8wCrMLdV/ubkboa0YDYFfgaFQtyLf3f2JiJ/TXjR0/\ -7zn7qMVJk1qNWdxgDq0ddyyWoAWiPEF4GfrMoIqCzqYumZ8iH93JuXejLK5RlMvW+HrKulfELsQOYQFcNXrCDnLojU6Z6WvgJu/GyXdsw4s9iq3Bca+K38piAwcZjo84sCzIfwZ5Vqiu3sKM5xQDkEl5SzCAs1rr\ -+ZA+zIBAarT+FiYs1ubFKg68uf0CtOsnkEnoEL8GjQN8X0ZWKCADFMSK4tqmJpu0Tu8RIyFzK4Dd1D1NDByVk9TAf7MwB2HJKXIr0ns5RsGr7+iT9ucaezhgTVrsgGbWKwFmobx/MdI00w4t+qPyZ0Kbrig50JL2\ -PWGhSEkP1xiGIf94/6AxwDjqJidvFtXUiKNSfMBDWS8qtGmjzqcLwKN3UMPc2xtTJ8bBEee0nmv7Ka7nV7seFb2kdUxvOekRgX9k4a968OehcQBEFAKvcDpp7OT9wo9AHiPIUYWv2SoE10Bq3viTInhexGVxG4gD\ -qoBZV5H2X1AGCPXEC557cenhR15EDE4SV5M+GjTEhFr/c38Qi2RmAwyv9n+AmLg84OHC00PmIUweYUSDIfyr1OI/GI3HkJkRvyMZg8xEQQMco1nnqGQB+d4ujD3czRnR5K0EkatWmJWa5O6YSMjM4b40fMbc6Q/W\ -WT41LS7QkYc6Iy+FSWkYzKdEDl1DIaQvy+M5bG7Ht6lXIif/rsaitCFUr0FcspLZL2EfA0c8vUUobQ3qarucMh14O7CslAStjnbIDsOymuoQqLCC1ngVNUF1BxGx+hlE5AYRG5z21S8OyQA2BbsdcY+js+Urn7r+\ -wh9YetZZOi+Ds29jXjBQSn0C+g3oIxVYL1glT9llBf6sclz8yqWLn8vKMWTAcfQhW/N4+uXr/kaKw7IbSWMFMVszUENN/cbf8oHVJmSVDKk5lKyzHVl5Lzebbu98OfeDVwBKgkNoyuTMNzSNUHJsZBWyR3FuU3EY\ -1dRGxb3xH/uCJYKap7b+a/sR+G1N9SZ6HPm70Mcg22PnB0YG56+pjF6EkQUPgloF8DTJ1PECQ87pKrAjYPnPcr+NUkBVUmqsaR2Mszvh7GzLdTokJVoFPiZAcnZc0EHWCygcfphKxlmSVcBx24j5a1/KcdvRIdlS\ -8Nf0QtDvoDz503RNE1iBq3GL5Az9izWHwyzbOfFqEGzvTmnhQbioVFptkgP0wCfB3IP0e9nM7wuAB9bzI1v0lBpVsAv+wfEKegnXyTGBVBcSoupl8SCmqcslAGQIQGYAYERxnGd03hAcpjOMCT5aP38J4YZgpNrJ\ -ymyJNCGVIOPZ0ndjH4DWGO98hH/OKfEaKEikhdBKpJXcBG0Frr2G1adkwOfoXPVseJWQeFobPvdCsd1ktcGCw4z648FJw9kfIE6TcfYC0d3K9nzaj+t668FtoYgTp8gaazYiyiAiEn7yX4H4DMUTB1aqJvAsFP9y\ -9JlFQfJhYVGSGsk2zxWxEHSxS2xX3K4bMJfK3kY22RW2is7Ju8T4V4cntLEnef08nkhytPQ5HGxSX7YZZBsIaKzP+gHw5KH5lCQsy2QI8PBgB6bOtjguhzxHKuM1mw/ne/ZjdtExU4iJSuVk5gC74Jq22hH2CljY\ -HFt+7WucGkxOi5LR+v9MydRoQrwTIiYJvLO+nff8AoYKcShwtNR4yhQGfNUYbgYDm0Bd4hk8RFY8guEeR4M1+By2kSDuRVtRJgmiqbKQtLEvgv0cN5H7vnPUZ1GhU8uErtc8Zb5xt8CTu9tXkmyJ+wVu3SFZFx3+\ -P7AL3hM0yFt9pmxRHqxurkJZAqDIuqHWThsftUW+h6gE+VZRmpCFVTpC8kQ4J2z9q9MdlzQncyAXCvr45AKs0xy83yOIRNSeRDytuVIu7eYFjXW0qF9m13dQpdC6N2fXnYRWoF70P/CY/i2ZcEgEanNjQiUHuD2k\ -/rrIIi2HqZZB1iFNhCoaqzN4qiwE6VR+cRMhv2UtoRuEZYmbgxfgN3GPKnI1EYpKMFkRLt+baPrZAnGLbCAG8LHMA4ymYLdTPXUNMJt/zOnMEb1tqyAVnGdgJaGVgVIufE720IzRBlE7L/Z4T6se2eWid4kZ2NB5\ -GLDux61A3TpjvsAxIA0Of4C1HLMHn8grBTe3yTkkvcRSRx67jhoiONzFy2RyJGJeZLwPJnhMWHgx2IXqCdzxli3idFKgmO3BLn00L7KTdMBJfqXCIg29ZOKlCEo895KwWB9Hg4mXnZwi4+/Ni2RSZA8orwOGHO0r\ -uDRpGpw8JCzmwZ7N2I/HalKs2/ATgcx4ixDrTTA7h+BP2jWNP8AAE28daBRNfoTWXHbTQVWk5CahD9XIV8EJWMTxOX7LdMZQv/JxBOQOCfnrIN8RfDDusZAkbFd+Ais/2QMRADql4wfIq/AER67i2Vm7HpgjlnQC\ -CFALsP8D6vSJSfrVLQYBa+ct1tqfgdppMQySr405S9mzLOdeCvNlJ4h6zMEHQRawcOYIxBjZ6CSiteXhC6sJ89yVEcyUsbotKykM8W6ubdhMeZHa7eCsstYAVHXFO+zUV7aeIVkPkBeJL682JD8cEvfX6JHGp1xQ\ -ozdXTnxGnNnPYbYAockl96nGj5TIzAOCWbbe3eoG7JCOaWM25Wdm34QXY4qCNLkKtJgNytOgB60/kSfp2FxM44C46ABSOkH8GLBcRITs0Kb5gOfriAPVcnKjdYHA6UUnLub4N5EYE5IV3eKYz8fsGJxFhzDd6L8X\ -s1uqh07smToxhNlSMjSc2PqIrLzZmSOylS7s/6zirCsDmvgGQSUmVgH/AGlc/vndZZ7QZR5UVMFAmAetd5ArGDujUqT31s7kkjHUzA4xU16V4oTElvzgaBry+2gaCACfJ0Lyw9YlqhMOKppUfAsf4sxWCNdMuQNN\ -EXW8OmfTHL1qpTzorNU7+JdyJOglKMkJaNqfRhFe64eaE0rmNQGGZKA8s+g4FPlISeciX2XvxHIUa1dFTUobR2aG3u5bQiJBkGPpD+1rGBfKLzhNd++KNN0Srl/hJF0WL7qIhvnTKxJ1DudrjhAC8hxWF2XA8l+Q\ -GXlI78JU6HFroWROn2vaWM0K3o5ROY51DmMt4gLgOgeCn8MKN8+9CQy5g/uom2uPaYyzDluQTifO4AGVFg3YYLB+ph4ji+xt7YWEI3VVrD2jpVh3rnXgKNj+2PQ8/m5EcApekZ4giRSGeSrcJAInUhnUNK9YMDi/\ -RItfYKUXoBZ9LO5D7QtobfRihh8XEKgHfZhbgKWqgSsi1IQhij6Ch6RKeoUbd4g1Ne4Pshh2e+AGNrD1ianyMsrpF3iFAfpc67QzCiofQCvRk31hRcdYxDqZsJbUZB3Q5kRcfZmMjPhu7OdiQ1dE135vtzQbLmQ0\ -FlYn65g55yxjiclz0JAds1r+SWY1E7OqLzWrm6xQsew0pl3IP2pWEaS0Y1ZHS8wqp4SvfY2C+cB7lewTAaRNtczCJv8dC6v/JAvLGiVcNLKQQe+y0Fhsm2UhjIIGx8xC6EwFgw11fMypy8RUeWNW7RNZv8yhvSpX\ -OlYPddvxK/Rm0dxuQWqnaMbgkQJe80QYYGpqA/qGdSEzMnA0JVVtvBKHdfrIipOp7dEUC2LmMF6ea+pkWEs3tZslNqGDhISN4xQCt9zW1FqekEqClcFlfLFAG44jy8DQBgqKAZJyy++QKXDIFKiWNKydIivIQAlV\ -rn7ibHbPxwkSVxbnlnBogUD9lB9RNhcF9IU4PkKfkdDnnbN5eQmhuMTTFJyt9gMOsHf5ZCk+UbENVr8cn5MFfJ5y9XD52L80IIHHCusS2kjrkeSpcwezqcmdqPLBJ8fDS3HRJ2LHsSjtBCPJjzCbgnKB0iD7o3Eq\ -rWfpY5anQjuCrhzs2TVYce63M4buWZq4g+JxD8VSLFEevLO04m15GUndOJi+EuqRdDey+wEbA4VgmCrxG6mpQOXR0CY9F4GvSo63fFPCo6QEf0kl4KgmIJXVHsMhOwsBSnp2mdpeQRPAm9gFG/Q8mnqOFC51C8Oe\ -xrYZ77CvsY27c5M3xvo+ImtY0t9Bxz8sOj5h1HEHRTE7KV7Xr1vi9kmqyHUaiGix+BhbPY9BJ5voE+wJQTBkMhYVSwkaSURqLgJU6njMah2YMFDHv4pnEL9iz8Cer+i6CCo9xmLRB1aAM6TvMs/ArGMTlvcDwOhG\ -22QVjpFxH8LCgPuC+M0eZtxMliWPRevsiU+gb0TpXdljSvouwQKPuXb1SjbLmM0K3IPT5DsaDsv/AxzW561gmYeAuHPOGFSjz3oIpeshPL3UQ4jHXC5fYMXscpV5ylUSlzLUxGWorqtJZxNalSkZPesn5FiU3zCk\ -RWLCb8FPYvmB3ETmh0vdxF2hdrzES7hEM+5wtVEpUqm29nBzZVKs7lApJLwDLbAV44Ea3DJWyWt7OqGsJl/OYwsFY102Kzl/VCb/cU4rr1Zkr0CL6fmCCks7H1CqwVFkshto7Z3g+cSxQIg4sILgZzVFiSE09IJS\ -rDaSg9J/qAhpimOMhE5wbIwKwmIz2B38KDpw//6AHLPNvQdwWgiLVqXCr8Ihhi8oK47nQLdfQB6ypiAq0Kt5Of1lOWGc3fw6n3ubTqg/xDw9bnorOxq5X8HmihPgq/LcR6M8LzbR2oqgl6VUHLUBhjkvOREXqeRk\ -QTW57z5X2FTSDO9E+CC8cwBik0iGUfReKnEiJ/wxKMHxCagGiDeShwofqjcH7Ksrq7uLwpa50bE5cAQgX4/udMqFISFv7wK32oKsv2AghntJX5zkHBJMFI1Nf+NUy2U5n9GfEo5ps4v7h2uzeHWxFMvcRVSsffl+\ -9pB3hQgPh4t4uCok/dYCNd0rUKMy9yVFWVNr4b9u/3dI7oANvKHsUf+nom51TsKpyuYhT8R2CafH/SL0NFNOaJey1g7U3ilqkpW8tOdZs8u5GQxYjNnQAuuAyHNsF94qgSqfg7iA6xX/Dr9+pRAhw0eYAIIfo098\ -6AI4j3NUEKroESeTUvZ/EGdIwCMgjGJHu9gn0jSoEfT+PoRiVDLb2e2vCD82BfZv9t1kQ1r/TjWznAJc723LO5uKeCatcJ6pn/5GugPEyDyFndniYMmL6LIX8WUvRpe9SC57kfZeYCNDP7SIztGJPlnZAVT7hG88\ -fh4cd6rA3ANBpb9lRtrcEh/5HNbSoMsAe95B3WIeE5e0b99asdtEhefkZ7/pU6FFuHpJD+uKTkLwQeam33Xu0UYvV+ufkAWmQzXe7dNn0L8l4c9MV/36LrFqCed/tRz0kmPIdKoKGBXnLg5ekrjXrMgqTh7ALlMR\ -fiLNjzpAGJP3/UFv4UcZC2jUyx6LJgt6hc9yZA3236oa9uTBQ7ixjlW+jRwk9OUQAp/GUXA6rthYyWbz0xVGEfxFJ9t2J1WNSjlUgUUyFeqD42vsnZZ/2//bYP8XPlyVz+b7PqhCPWfI0pvEQdkoMgfOsVrDu8Hn\ -yoQ4+iElBrJazpXgF+vbYBUmjlmuRYJr8i61ye/KGaJ0A/Lz2sEgVjXVMJY2ShPK5Qv5JGPMGoaFvmxDMNlveubt4NOf2BsK4PA2d4PdjcLjqh54qTb7fAcPby8+1JAC4vE6ID5z+iJk033puHT8AV1rkDlleciS\ -dABxGzjt5gB29GCXLjPnYEmJCi5zdM7Wh9C/VZ0zJx4N+1d4OIeDgP6j3qEve4jAHBxkzs44eCHlgN/7fLap4rNGVBl4m8tA0LfNW6EUrwGe5RrDqBtgIlYGf6WVw3rwxDyu4eGTo9ns9duLTwgJH43CupIeEUhn\ -yCkFPqISWpCRxQr+VlMCq1fwNeeeseUORKJzHYJzvJBPkeAXEfMOOsb5w9ksGz6So2A4V24TUBSb75CwYhoNZfPIOaumM6gfiLm4u8n3QxZXPLyH73h1grBaYA7hDIV714UOPbzNwsPbLDy8zcK7RznNlghzLpzl\ -G1KIRY7Zqwvdy2TCZTfLZILNpnslw2Cwejjhayuw6hwW3BSdjngXg2eddn78qHNhA95KcXjW6eFc7aBCim8HK4FZSuZcKKOW34kDcbW5QCaL3TtjxuYqmydUT4MXnqjOpxl96sCO8q7Yd8nldpGBHI/FJZ3Bs9zz\ -mF86t1XIaTaqKT4DnfkJP2hUpysebUN5Qg91AK5pNvpeClv52GoO12EEkeLkLhT10I+2/3iXVssDHjGj1XizxuNI0hmIhwZT5hWkHprYfFJiwvvxfQvUHs9PX3os7Q0yVUy7Z9veBQCgLhgedNTcmzzwwOwzsrbt\ -gqU6n7M8TbPAOhagl3LwNRQkmsdxl9uUnB3Y8m0qjzvg2Wu+OwePiOA9ObyDiylvSPdWUjGZdSgsdUWZR+TGmjnmCRW4UuZekdRVxmO7TJu4cUXS4TEdFjyjei3J+ALPPg55B5z3ZoP0PrNxw4YYS7tGfL60oZ5Y\ -4AzLw5OUyHNxB+F5RyiRnw8/QI/1J1zUEc2ur9i9XhXuvGC4jBlfHw4GsRy9qXccCEgBDgveaWnGBx0JCjGnGgSrhxFDV2MCEB23wDS7/KAoWHAeT3SHPbD6jzRL9mSAfJA/yYZb/sZQyAvUvIyKT+T6IulQo3cB\ -Vknt0NKr/NlDMNotv5+dIvdbM4XmA/aUseAGousKrt5Ryc8cPWecmyu4hDLASomuAwl3rZAuATLUlAh6T8+rpk/evovE/s910hs1h4ONCQchHNfgOddPzZlkvXgvR6alnF/HrW+FX23ehEBXgzdUsaVC1zXfBtSe\ -AmrhJozsGZ89aTIjLwNBs3sPWBDsXOOiUCsErE/Fz32OWiiYzXZerj4TYwNfxBsxljnEP/lG7DXetaHzHzbgK3V/iT+QqbtcG4lrGwVD9sw+xxUugHJfSomQBmq7P4l0wFx1vhSEL5upncBcLCAH4Ef3mXHkkOxI\ -jATCJN3wLHlwGWRYF3HrqyHrQUdUYrOIVEMh2GLG+FzGCjmcORK2T/DkWuzK59XadlFAK5ewLfZOw8LeQKUWnEPE0U0CThuAejceQG3xIpqE1Xu8TR2OXL/itds4cRtnbuPCbXzq3uGX9e70y/tt96I2rOXOzHVr\ -3+Gv2Dyr7jjX+uW53LVm3DkXrXxpDioGwC8oPNR2oPVaJeheuAa7CnijHZyBkVwjhgHsr6rCR2Mjt2o0HFYoTFw5gQmF58+ZYZrwLd/dsFRNeXScFrN3nRreJ7JDwBtGdb7k06pmD5ZyBpvPYKo98S+SbelayC1Z\ -uMrX9oxFlcglQHTSEk97YQChSDDwhjR2fWCpcq9ZcfC7bO0po4WrheUVtmqmnfiCE+LaXiLzlnOziThpO+IJ3WT2LfZgpvjuDI7vkXeJaOlNHfanfsa3ZDQ2M9FCfcRZjaJ+xjJDz3+F5wUTw4HW48sl8BFtoWMq\ -HQr8CjlF1pzcFhaKMjGfoa3crmq7LVgLUuVgazv5pHbumQuX4LA0C2g4hQP6h26FeUbnAuX+IEXUecj39uF2rDkPhxXyo8FBgJmVmK9jCzBTaPnjceKbI2177sFoSDFFrKDLfG0PQoYCHdC7PDlWWy69zM2z9+sp\ -LUwE2xzkIzn3j+C32cI9b7hBiddSFOZsx7lclmMWuMN5hsYG3C0HTXC34EHqqNcggJtPUAulpUOqmK9uqStzlJdu22xMaPrFngJ+q/pa6YuUUS2mQNSPlpOEzpguhhr1mzltyXu5sk2tOWtvhBsFqO4KULbEg2oQ\ -gwaIuzxE8HTg3O3Q+6bibG4l2bHgEE9weR/5lj5Hn/IoowVeOV9gFBJW0iU3+xlLJCkUnaizP0Yo6x88F+OJXviP7IyUlptyOJtpjjIFEaVdcZw1uc1obZXPQJlai4m4N3AQJ9zEPZcNiQ47J/ekp8aeszOZGXtT\ -5rkDtPSvlvW3np75hqqgsHl9OMBbgX/5cFbM4W5gFaRxmgetV9q+qd+fzX93H8btw6o4K+ASYd+96BZ1yMjZEHQy/FRDwn+ICnbnVTB+a37xBaPU+DsXkIhdV9JH9u6VuAkB3mM8fm9+dT4oZmf8sJU5+Zk3EIcs\ -ju007hCki32QuLWM2ZjGdTm89ZlB+Yaopd0qPpfUNv7FPiPOwHxK+IlYteMtsnwy64oZL2+UJV0DtPgmC0yDNwbaX7mDd5RH+TRLDWKrxFDhf8xDRBCNdvT1UH5zg/Ih2BgZmPBaallA/4axhUx01Gv3jsJ2z0i6\ -RT9UOtZp9e5iVr258QyYay8D96pZ2+jcHlj0kje9MbVacuO26vXv38Id9tpRrx332kmvnfXauttWPXg6J5fVwG10erpXeavjxUu//7Q/dUU7/EoeuoqnruKxfju5op1e0c4+2z77TOv9Z1rdu76XtfVn2/PPyc6V\ -f18rt8lX4ejsK9bdh7y5Qgv0IFc9SFQPi6oz3orbuOE2OsPecRu7buOF2+gQ5ENP0/TgLHpt3WvX0RIpUf9FKf6ztcC3aolv1SLfqmW+VQtd1f7KPxXY9JmRQHQ3+MToiCUtNhsmc8Ya5zGMpKnL/08Tiyv12ct1\ -neIoDdsQM/v3/wLWvxs5\ +eNrFPHl/2zaWX4WkHV+RE4CUKNC1G0s+ck/qpHHTXXdbEiQmnaPrKN5fMp10P/vyXSBIyXHSzmT/kE2QOB4e3o0H/HPzqnl/tbkXVZsX70tz8V6ri/dKHbZ/9MV75+B3evHeTOBt8DPy/FPbxAaFrlZbKNoHg/3c\ +4zZSMIp+Ut2Mw/LhoTw9mHED3et37PuN278TglSnF+8tvG2r1UVbbp+tiqhdDaOnF1fwroihFc/P17BUo30Bv6u2fd6+sBe/nK6H02qbNU2vabIm7y28j6K2rW1hanDCbY8loLFtU+SL9k121n4qoWY7t6aCB2hb\ +cFs1AUw8eum7fw1t5i04uAaHLRCunb6ujgBL8Mj15i/h717ewXWEf6UlDKJoEGg3beFJ91tE1AICPbRA1bjse2kfhDOpcbEJU2lfAQpyoRJfebv900H1PTQ9JcwilrvX416TDCDANdlLEO/tK18hfc7obwGwdoO/\ +pzR+XTCV1mMCRKl2WpYXSZkeGRTczsREE0AkQjgtjS2IfKBqiSVZ+MKEpCx03dx79mD2sK3bjlzi6t8zhGaNPBRyhqAp5COtBnyliEdWvTO2zzI0wqBiN8jgI4NLaPeFdvzNoMfxKnAZ5GCKxMu+k6r3pcfYZjvA\ +IHxxYQdZwNu+AELI9wZYL6kN9FCL9Bj711RHV9fLpyt5/Kb90wQFnUphPwATxvbjVyooAHmVyLj3vgoauKGQ85DBipVNIPFUCGbvIxTqYFAdCFyRVCEp9jFUSksr69WuvjFBoewKr3CVDo9P8d/oCf57/8DTzCN+\ +qsYP+cnaO/wEor5JuVCbAp9e+3cPSHbgV1juBkn58MmGgMRdtrxXMXsWIB+J97AJCe2kXEuQA2nSadmKMpuWrRSs0xLEZlqC8EvLe8QbzVREkKApJrpEwVaxgkB2BBrPQy4DkNLHybQFxAGWJrSCSjMEsDbKHu3E\ +pAYBWGw8ofVTOv6FB9d/4wFpdXZGoXZhweNhsM+pH5JeIeialsu5pBuN+4FVyqL1qC85EdCIu8uG3fH79FPfv2kXAin4jOaPKoEetDxUDJnqJDFCWa9YhgJXWp8jStY85Kxtdf52oIdZUw9VQIA/nSYzIKYEBTTA\ +YdfxzWR+dpSWyQaSFWhwm02hetuByUOpQIoRtXGK/1JgUFCVWiWRA22rt3b92FtQIymTPulomyRnR0wVaUgxoJ9L1mImO2nBmdDnBU3JDQclKeLSKBZZ0v5a0CvAUMbdIlYnxCZ+LLBFAADjeAkmtHxKg0K0oeRI\ +O3ThuoMazxirOXerpumfXKBbS27t8reRy+R9LS/BwjBuTd6j6DhlvlDuSDr/FYsveMptt4blMDyD9BJCKpagIssTmLMd6G0HmKmCHrCOk4anpE2kzyro8/S9QOjXsDeizQ0Nt9X2VlGTudSEUgvIL9StG4C6yyMC\ +Jouuie5VM4QipJ0AqoqhKsZsscHKtsbQJqz+qB3zSt4petf+DOPBdfRMVQYDroffsmBQppMJoCtYAgDawn8Hrd8QyeFK5DLSBg8rS5HJUkht/T/LwsaV1G/RzhybTXu2UDSaQcPFsOE56WmApsU4maaodEdsqXtQ\ +gcgmEZrH52tkcDdahGtOjMdjReQ0KP2XFcOBREQ9p7qPfjg3/Zqsd+N7ZMjtUlfPyS5ZAfa5+ASnf2WMWbJNbCqs7nGMVRC7UlcxtVdO1vhnWaX7S59e0ieb8xLLCEpvdNVUjp5bCjQ8jm/RTJq008AerlTojxb/\ +v1CS/wCi0kzesgTKnwaAwvKMEaI75mkr3XQd6OLm+p7Pu56tOZiX2QkQVyspr6D9PM4iXnv0naCXOrsNanYt+hORJCgjNHaJ52IWvX7sNHBKBIicTImOe9BeMQjEc1pK65cSdZOXzdxNAdIahtbmADqpWEwLEaLc\ +mXfUqKvs0KnoSMhrHew9ktST5/iP1RwwGjTSWrw6/c1RdJhG9HnaoRR1igJFFm1AtzI5DSjLAMTTcaCf0RdtPgMrNr+LWEmDKoaq6KE4bNK5eNdg7+S3O8lo0g5kFjybxMvUw1Yn4NG8JyH/DHkiFoKPBwSv8kQI\ +fuhJUVPoML6O6Xi0ptdMOj9l4FgcatQUZ8zbHn8Pur51FlLMLg3m1Bpg8vBr+IvLuArT6fOSLUOQYkDI6Xsa1leFj9PpCfQortuK+YB5TdQYLFCDXaFzu7eNts3jDL32x8diYAEqpkKTGcGA7AZoQDtq8pBmik6A\ +qId8IKKMl0OoNiedivHA5sse7yrJwyYiOHOTn9joVxRp+VEM8kt4OG8dGjtNQlvHkRXY6lPgnwmYdz52ADQzBntWTJMaOGm8kXZ1tLgP8FwE7rJdmxKGpaZF4z4VRYyjnrAdQDAwISkJrFF/MVl6SEVgkzf03Pdm\ +0N1+cNA3oGNyF10TrWFEIAG+QjnOJjlY0/2+UCzt8gpAjXxYA2RaJvErdhGavjb3cZ/m1Q8PnpqDBIc8+SsjHb5anhDbnVnS2bwoxqIsSkkgOZV0VGomj0SPcGiv+TSrPSFicRgjws6ScocJjqUvGmbjmOxx17wh\ +Gw8GqFKQG2p2REUjFJihmQYDFWm8Ax/KW4TyGsNXF5uF+HPtMNNFeasq0W4v85N9mkeVxjC0JpvVNVUMVKMeE0Lr8hh6hb5VdbUob5M1VubvuF8ky7dUKKDrSiTdgvWbochjkY6ABBbwd7L1N4QVPaFyfVFu778A\ +WvgAzDUicQHOrkOZW3mpDYQ11v8EMEmzbdEXxAWqhdiG0q4TdBC/BFaA/yYtgGoKcovKaX4PPfZ1tqmaCIsbVKyh2CLgFvSVRFswB/0fHDC1zF9oRTy0P3AEEARifsq6EKIygBeQnWP2Glo4v6UuQHXYvGB1k7Om\ +BL/Z2wi5dLDP/N6LqfkeB33RhFxNaKD51Fwqp/u7ocHMPMODFTLZFvfgpE7AVXMNTm4b0JoH8tBPbSrje4BO+8EklcUQE6GF8BFXUbIqPggQYrFSvM+vUEYSRZj0FeHcqLtoY4BEUa399bycIGmXKUQCgcCBvN8u\ +iwaiiNZCex5PkNbLNB4LG1j0nEYAXfQSUH3ebS60ZtBYmNhEE44JokE/Y+Zxop/efN0JBu0wbvUcvLrvpsH6OYyQK2I+xAKEidQCelbvIgg+fNdpCe1Oh2sVs+PRjI6KiolPiY7IwtXljy4/eMBEMeW142EVacCw\ +Mo2xEMpH64fjjbRsWcyc2hSVMEGgaLIBhWihEIlT+IG8jk26mDTRgZ/yb12kV9eHogXAZGyQQSuibrRQ2NWBQIVi9dLq4vWWpyoTxbNttgdBk2cz0h8YGarPWdDWbW0UPDDSErbEkDBLuFoSFPD44pzkjCv6BojH\ +i/kCeIF+ZVsIZ8eBy0PGAxLhB4A/ogZauBY2rvLfCGwHM6z3UYDcYvjUCix4CRJtS08W3E3H5KHGfcnjUZFfhwp1PSo+bfJOBXsvGHeqg5UHKilT2XWrIQzoPQPEj5mxfZUPId+fXYsIZp01hUwf8/5RTXoDo1X2\ +LYnhioVHhwjZIaoD+e7KOfhDGXVCiNpZJzhDPPXCiLJfBtMsk0cJVT+VRYBxxjKODcdB817GsTIOxwygx/wZW4u17hgO8Vx/ALM8IYMJPeqUn230Tl1eAiW84/gOcxM5NT30jd6edrtdFM8D8putEmCn4bQ/To37\ +GTNkk/8/MqQJGLLBPakrsYg8wfXIs/ZymjXn/hFTNhravTnHJTbY5K0F9LPiDaoxxU2NE4H9JdG0hq7NOe/ycOzOO5qWnGuE2S2NFqglgjL+Lhy+EcR5Jmn5YoTm6J/FrvtnEAZbXsIRKMRT+TxYXaEBUC9GPyUY\ +rPoV/nyzBX/fkfeiNCxN+o79ZSw5CAVNweOwuxjRQCNiAd5F345gV7MOTYkFmhBiOYAV0ZoTlySSjLp8iX8J4RhSs1M2YTwaBWHozeXeJhrMEHfiYP5lPbCo3Ib4bEKtTGzJa7CNRuxNgKfs6vlrrmxfBNNsSU4v\ +T7YshpNF1abDybbTb+fbYgDQZzjOVDBoZjw/egXTSDCEhMIf94sAI0RP6QN24agOOApUjQw+zKHAzbdXIJa/Z1zZfwSb9QgWbGQ4+FOQhNol00NX6X0iW6dj2PiqcfurFvhCnTL3oi1hj9khq73H7bOfvfRM/NBo\ +HPwuRQjuDMwTqCTUhTdLH7MUividulDkTiv9kVNn3/kZBuE1MmS5x6zr8fAZ+1uwbg2FiBRbXwJZ1rMrHqDXhtS+s65gD10lHBoVZVKBD2Z0/BgplQEnr2G1Yf+XZQIlllhl1RuRcKhEDr7CdVu/SW93Ji/03GTn\ +czL+zcCCWXaB/oXWy2nPdEEczjh0N6TJFttqfec4vjswbupOd3ubl/Aec/ypBqNXZ9N75MJrm0FcWGcoIk9lQ1k96UIJuKlr9fG1AnO+UoDg9o4mk9xZnC6nYWH+Sjpjc6He2Wam7gZjE6JIaS9zb3mAltvAhtNG\ +iAiTtq7vSqHz0utki8Kh0FNS7nLopyVX3gUtMJMhKe887UitlYN9alM9+oCB3auO0jX1mCbCAIRrncZ3Du8CKFMxTdDPArmht3FDtRwF4Qx1RO0xyq2PH4FqmZdbbA64eTxChMOL8njn7hwaO9nMNSWSAARVafMj\ +A3NPkxJ1FhKcjJ0n0IfLk1HMMTaOdtjiFS/mDoSsYDo5ehXiobMuqCSMmu3cTcs9XLoRWIZZgrvQ+ZMlzlsyJUbgY8KesbMFisD/9dEunKBkz7RqDJk15xRBDakIFB5CPQKYgRUo2mXF2EIdbDu2CiAuPHowuW+M\ +Q2wlpYnWI/wKQBbF4WyG89ial8U5R7lZpUC/Zlo8xpZ7lw+YYtQxRkOPqWs9RzjbGqrzmFECmEOuVrIVjbv0eoeigjQDU8N8C0nAsJy0ZOh/uIlYEK+1q3T3EarGV/79FpGxwaUq77KWzSRzrjKdZYz7CbCukBxU\ +QJQDkyUsxQCNpMcoijhSr4cC0JyYWuF+bY0A2KcUG6WoahNtzzoLJ/SqCknS4qxLg7HM3YurD+RG4zscAUWOCuDRLGDsow4xnwqPF1GobQ1TVQQ9zhL6YAlBhs0EzGbAcPc4OgYYEcDDh0hZCNqjZ61EJhw7C3UK\ +lcR7ybfQ1zzewyEh4FkdixE0L/EtMGy7Wnfa2kjZRRfGp8ShNN7dWJOd8iBfIcwtgJ2KmvM0KFIr8SO1Q2KvzBP5tCEJMRmtcaNo1cFdsztrELsvkEW8q5hiaDvSlG+JLqRS22Al2ucXmwdi3d8Sj7MKUssyhizb\ +4kUNDIdLQDm4iS1at1tIN99QFA6gQiRlvyYeHAnA1rz7hIFnKzukykRg8de00/BRtb8ieoM7QeAvwvoV6gvr/nANZWemLrvNnmG+kN8yMdVBz25DM9oPf/uasdciGV5MB63ipkcLb2ZEC5eI/DSkhaxHC4ZoodDQ\ +p5GwD8Nb6B+oVySE8QfSG7oSvI6RCCBHj4VxtKV21kHAJJf9VX9KEq8ArPt9mL7x6U3TpNyQ7baLTdiNGse7otTAOYYA0LOOxigZrBDLSeU5+XwboC+nJLhr3rtBMiF5sXE6NNIHNKZZg6v8PzHv7JQw6neHvD2X\ +lByD/Frotp8XeJOroe0aBzpMF+75FD/jIxS7iNeXCaejl5bZkILeHfBudRqv6zREMm1D9VTeO+qjAImgqnd+zw0XEA3wxSCabXoLvPMONqccZx/TWu/cFdMDVqu4WDDWcNOvPMLMJWdJvaTSO8YCrjVoC2o9dP9/\ +xXTDvsMx3PiQ0Bj8qjmIFr2Av+mvV+/87v27Lquu4DiPza+JCGj7AkTR2nLCNoyBm7c25rw9e4Cm6uppkfePyXr9yZG7H3PsqUoRaAQ93eOcVjTUB41WRAdkj7faYqlcJdu8xPAJpDprWzC82Y6rOa5VpV3ky2D2\ +EEZi9nhUlo4l5vk1M3bdq2/GotvWRAX9SfTjOr3plOLpXeaLrvIGx03Ruqtw8wCEX08BVisUoFutAO2yAlSrFOHGJyjChdgVKxQgaUZCHoWNb7/F2IwowBIFCdoxH5MkK7TgW0oz1pKKSfHF67Xh5EtoQ86Q+LIK\ +EYisuoks0I8Ad0iJOiRDelsC5GpZKRItoC5cdHatrtZ6BEEqjU1j7Mpw7qLLUBQdctq6InLEELtlQiwgMcqryf7eT+TVZJfP4qacOIyoPukSSENpjKlSHByu7fDERz8sfYKIk7gw7gt0gehT2h/qm67AYELfSgc0\ +I0kaa9F1dMOr2i1d4Krw0s0gD7TaS1aYtrSESuOa1XnWZXeXeLpp/QMHCVcaLGqq9sazvxCdtJrtMGN7CXPU0GxJ2WiWSE4doPWapSG/Q2VhKhkoR/RhG0AX2CVwCmEFutABxdT869gM7A/Lm7sd1uZLWHsDAdnq\ +Edti8xBr5OVG+vAhJ+4Q+RCMvwDe7vMUp0P5tmgFP+I0uthsdSsEFzbfPBEMDg2/39hHB1vf1UJFwWII8g4HyEuJ43DjA3GeDuLJLVKgN30bMlNzPjrhAFIzZp7wfthEcIgB1dYQcSIZ3gEifk04MX89rlnNtQbR\ +r4tEDjVpTCLMCbSqPhaQws3m02t2msXeW4OTB3g6hZWJ5t0aNBRYUH9CtsbSFld67RYXRNjd0BTMyIwjWa28GViVNOsudBWYftxGVRjRyvik1TCY3Df35PRd4/WmLIh3bfcG6t+SRn/DocHKuzOXwpbAhQqPVWR9\ +UhYBjru1Csm6st/e/zTNPmYIx6jZ3YA+DSd++KOmY3VP7eHBNTaKMGAFNmqZXfYFCCv5jFNWzfgpBIaIilglLhESr+30U2nJMC0BTVl2GMDe8zRU/GEaWiYgtUrl40pnQQokZ80bP5/59aoeI2rp9aqehh1HaknV\ +k9WO6celJxnWPJ9GNUaoRq1Q+K35u6B1RmKZsvX3ERGpCrUHW3m4b6f6FOEF4lqg4q8RhTNONa+E6/TeMe7RzMv1GR+Crlr+3hsbjI+B46xZSqkcrcn5Z1KY8RRmlimsYvOhyv4NFFakNwsqcLlAVoF/688fcKNp\ +rxFvo3fyisOL/kjptIfyy0D7ULajZreiXEBPuPMx8c7ybc4lceVlwS9plEcZRp238eTClDWPxujHm/+G+jvH96f3T0XAxnzmshy9KKpTPFmx/yImxAItK7teIBZ/vN5Wc1hVbDWMd8bbCDQAegk+HGWPUpeU56ow\ +kCHqFOVXkZxI6LncRsUrrI9nT/j8jPcm7GAHAPNeWWv4ZPWa+pRPmjS2FNOvMnyRfvUSQtn3SIKUHM/WvhkpeuXAAZwM+oJJveTwtoSY0+5Ylmh/18j2OoTn0aGc8mlTVA8/E0F3+WTz1flkJr9By3NUZ0RQii9m\ +8tccSFuVxpJ/qTSW+nfnlZG+Ql/mk1LLBjuzI85LYXTYHPIH7Kpg15dILJOM/zBth3N5AgvhhoyBgfM9Iv3bLfjhv3KG+hkxL8U7H/BY3lXY5n0hTPSCFKtaclwHsuIhypo1yQJVYx8E7dUDDTeOj2lMiAeiDdnO\ +eBt0+oL0n8Pc5YoCrLD11aSLitUxvobjFbXtEnIU86dFOeokLf0Uj5Hrn9k7NrAueKpgXmY+B17OApaDs4BMum78A6fp8EvI9zdslij7jzkGubp9Xz4SVPosCj4EAD+wI+DnP7JtUfIPkzL4qJM/5ZTx96kcoudy\ +WGf8kW+Tj3zLP/JtMB7A1nDZVMkezOI7tLK/WZsB9hNaAryOAG9ZycP8bq8OoGXX184es3/6HehTB3kirsRzSEE+N4UoaddfluxsuGRg27gS8/Yx7HI3Yv3Yr4bpWl0e0zccd+TUgTPMAm0XdB5nnXlj7OtdIuJK\ +Fd0hrCbr2B639bUc4ON1hgyvpuCdcybT2n5LpFgyTTUNbxo2nAaIG+jZkksaBJNtZxg7ubsFUkr1bR6bzMpyq1XWOyCUYWcBdUuzDXkEFSQZYNARnFSrgjzpMrobQfyxWZQ70V0inxoGMHSWkFPbYEukztjmAcE0\ +ObzFMSCJ20i4vWyXcPdicYKRCmQVvOCkkeMqcKsJ+hUFNy629vm2CcTQXS2nb8AppIAH2y1gvdb+mK4cc5xuX1xAhT0+LIuBtwY65dNhDzkZRE4Fdocg5GXBXZwgFnfDyCeKrrgDGcPg2bL8wPdm+b0BYwRfwuFL\ +K6eZ8wMBqjvVtFhuLSFvisLtsSmnOc7fqxxxNJ3DAHg2QQ7YwmlRB+M7NYogwgn7bv7snGF3x7Ix5iqUmlkiZ7YmIwmghucpLJ/dJNpFL/v9b6//ToevtnY72kXTKif0hZNr6vD+BGIGm3aRDLQRKm6vltv7/vm0\ +GE13a9ccrLqhAU/21f6oIedSxXw/U/HgB7P7UI6vAYMVRSc0EXq4fAJkF1IBqjy+mqM7caoos9pABksFiq046MDU9qGcUUx9xSA7rxxEuZWcccvxgDFSNJhPwG2OD6MpmXYaH/UvLrFpjFeTxHg1CR7DSeN7FMfX\ +OrxUSClJKJbLs1RQUEsFH6OJeXPN9c//KbV+fsSpZqjd4bIOV/YqIm41hdaC1w9712vgzSLnV70aWwHJZBFmYahEDadjlu4wOuxuD+qiMuGcg4u6bFryKmjOQUBwS+SJETXUeNQNz7ryzDClmhUp7qDg2eaJ4AAq\ +SAIeKRJNwe8hVvrIPMerSMwT5kw5rQpZc7i/CPuGeNdEZUbfcDTNWkj3E+VNl0SYUclbbO7wRe8eMhgm92umyax0Dghbw1niZrIEI27wqU9bOfMkwvfFEzPaWdseye1XQD2rLrl6Inf9yEeUCkC1Vv/IyMRsH7MP\ +umN2cfUGNMxZJ06cRAh1F2LXfDcYamRDSIGQWe1oJrWdDXfIWHRO+Bya23rCDiUaYFsjcEdKPucARCIZtjrnPUm3xcfY1DOwUtTXfB1Od1VbQLBWMujsuNVF2PLBPqsIpzDPaBtFCJzgNG8AgQC+OeNzA874S8Mi\ +QWZ4VZZSZyccbOoo/UqOmY3n6BarJ7OHtzyzQt3J9gT3eMePkp21aDTbPpEkxaSRizXerpDMRotMnERrJNFX32hGP/XVYNEROH9mnDOvtFwwU4tSqIaYlAqhu9Q7N0nN5Yy0CZTTyn5qrjBecVOR0R+f1ECoFLG/\ +AvCK7yVS6R6I6J7pFzhsfnOG79ARSQMBZn+cKGUb1OJDetMNckq9Ck+TXvaPlmKyrfEXaz3Gp3HwDoM6hVynFSzBErcCayKnev7srtISXk3IbNRyuFGYdrLiqhYxuwpRiJKAjsl9Uznhwe/c04sFqF7NVxx4E2LY\ +rU2fAnq00lEADbJpvVy9ZseoZrvYKjja7+pYxGTa9UG3LYmxO7yBqkkD6Zxh7ROZ+W5n1izl/pd4kEIO5Duvzz9ZKPTpsrvG6YpTvqvqd5D665CMrsLC+7DwoU9tZnDbYDEsdxfE1V+FNFcPaa7kCKtj4kN6E+JD\ +SgyJT5dum4/SOl6Gur9w3jzBU24jvhYMd0UCK5hcvOeeW/9Om2+raU2OIJruFi3a27hPgWu+G6IqV90al8vVnGgu7ZzBQMfMRfZ7uVPmq+GdoHKdaM2xtzIzRG2NWpOLNOSglEikM9naPGBHo3wJNtfkjDjL4fEp\ +i+/lih9/u9zgxjjZs2nHfd0FMf0dK2nyd9KWtu4sbTpsOeMsIeiRWa6d8M8s0yeybv4QFwvIhsU02myaWAkSQ9WTiFicqhZuCOwZZ3ggsC9fsVlf3jojIuT3QDSTmHxIepVUCc/VZn6uiOMpXSdYwqohq7mf7gj1\ +0cbLfZ+NFATZ8u7eQOxVr4C0snKqAI+bpbf420T2YWhZG07VdJhzD7qjGktDR8xny5wuZO3Cn/6GCwcRiowVZZ1uPLnYjKkV4H0RyDezpBxP5O7Y+MOSlKOVkgmbicjHUXBln+HziD03WqLdMRm8zlW7xG9tp+QV\ +bBKn2PLPXwe5QjVfaxIGbTGdfvx7BCgGB+ciNWHc7D7fpQeumg3c2e5mh+Bgh8rwvgvqTI7yTTcSin2apcT4uZgseFYRh7qNseJtucTWLNk+eNpggjoSQcGqeI9WX3JL33h0N5VpVL1mncW1EH1B3NPraXMU4aXN\ +P769KhdwdbNW07EZT6fjcful+eVq8Y/wpWlf1uVVyXc8925uxUWeBNab5GoKJjP+yWV7Kac24P2gJiiI7sWCrYKCCOG2sMVbjvB66oIC3KXiC0ED3hwrsbBHR12pTh0Wwga9AggfuK1gRb8VxQSxIPdM+Gn5wnVd\ +l2wkDV7/J5/EVnzExaGTePg9X9ksN6i6iTTVYeHaaVxXiK6r0/QKfIWUFpXOS/OabHFaAOfRfMc/kQ/LhXdBj6LMfifYv6fwKoAKHBxfMCqYxtLVycMgbzYoD72W4TXn0175qldaDPyPwdjhTVF0+1yornv3B3SF\ +cvnS5p6DrFdcFa0H9fXgezooZ4PyeFDOB2UzKNtBHHZFXLYrR2GhVzO8n1r/tCIY/+/66RvK6WfS0E00dRONDcv5DeXpDWXz0fLVR0q/fKS0nIG1IiPrI+XFx3jnxt/n8m3+WTi6+ox5DyF3N0iBAeR6AMnw4nLd\ +628tLNwOC71ue77IUVh4ERZ6C/J2IGkGcJaDsh2Um2wFl+gvyMX/binwR6XEH5Uif1TK/FEpdFP5M39adYEyz4FT5LzuasgqPP8uF/xJRMlz2iodd+1MN9n6DY3lbJqq1jb+7f8APK6wwQ==\ """))) ESP32ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b""" -eNqNWnt31LgV/yqOIU/I1rI9tsQ5W5JAhxC2XcKWEOic3bFkO4EtKWSnm7BL+9mr+7LkmUnbPybYsnR1dR+/+xC/by+628X2o8Ruz257nfg/5WN4yvCpOpzdZv7RKP/a+l8/u3VZQoNazxb+Lzxl98+O6SvObP6f\ -mQroZTRBfioTDrLoKfpp4aib+M+OKGnY09Jz5seyfNh7F9bEXG2ssJe+J4r8ujNbnF2v8o9kgLjK5ST+vUx2svUnybIDYrULfKrKc9IEnrs2kplb2tMY2jMMIBNnX+6W3vBT4Vln0WpQavuYCMgvo3NE6t4QbvIU\ -PgHfT/zDBE6iw0m6hr42E5H++RGJqBdRFYdAFj698fNg1J6nwNNrULU/m5vAjJyJguoKkHZ6cO5f1aYfLyIVZ/wMx5oAhdMwGHQFcpvQijYffTy6HGn6GOW5YKL66DhlVbvsUQmEjky6JGgRItglspstGSm+mCyS\ -NaxBb3KPI8MR7ZTx+8GBPB0DE7xGjUiXA+mgLJQwCKiGh0N5GA56Di5x8gQsT40+7Pg/VZIsWKE5eKmr7sEnP7nraLJV4XkQc5Nv8QP+FuSRYAtobZ6cY/sA6+5iq7cRWRup1NC/Fn78PGzn2AON16iySzsblioI\ -Aj6CrcOY4bHgQvnfWO6eH+1GxznmL9EGyLmKOGR6poY9/hgv13RWPF8WvLpFD6/J7ZWZEjZl2Vc/DezCf1Egaf9lMfZhJr0CAjBQDnTuxgsTGGrVAI0LPnoxEso5b2vTLSYMAOpV2BrWOjyXghfe5NzYHN7SkjEm\ -vdwH62IU9H8aJHBeZhPH9laAv4Onl+9+eDmb+Tm6ktUdSYhc86lf7b8okbK+T7JD6MnJ9ETsMciCWlQJUioSz6jNE0YSxoUu8mntHqVkU67c/Sty9ej1W/gHWIajgu+N0WAcotB7P6Ef+Rjz+Pg+nh/mpySJJoQu\ -kWzTElzrKAQErr6dXYWg0znyI0RyRZba5AHlwX+UAKAi4bRdFGHyCEqLZXcOEbpJYjTNOTrafINngon3q6gcy7LJ7pGRLUcpNCAJOpnE8kbdRmxyUMTjZXLUE5iZf4BX1NVhCs8FcgYe2UBYMXt7tK2mOSEb0OZk\ -9x3bC1rV/uyK6bsJ82tG/D4krBnCeGAIgBnVlpMR4rSOdAHfWzvOSEaCkTmObb0Y08a1QlMznfq/0Gl5Trk6ZzVDoJM8AtpVQBChJ+/KppxeWQGvnLF1bcYmz+fxiwe4Fsx94u2/1d+wJxgXDUP8hPP6l2pjg3gA\ -qEIFR1nkyEmrgJMQ/CsOJehFL58AoreclYiGVJgWUwJvgh1kvmVHXOGiWF57kh4gfJ45MlZ0CHZdG60GYG8ajgndGh3CuIlSHytrNoOVooWQ3BGd3LIWBh+KrBN2dO3/sojLWF+f4pdF/HIbvwBIXTDWAZ6zi8AW\ -l+wsG6A2E+GDHLHp6XxaPwdzuA6SQi+tHs6uII5oe8Hz7tAcng4B6JkXOAzmUw4bqPQ6nhIv/TPsciroBbq3wtrrD7RIkses2o+StEFRB44ETMcIdQEZz/xS7K9KQCEcbABgVoMNY3mUYaAUJq/g9NVHYsM0p9PZ\ -tXCyKfKY+x1xC7ZZDH9sgQhxvCPxQjK2KvE6bmpmyq4414f0w9Oa0NQ5Thxwt5ft+kPr2n9uCtqii6sJlllbrlee5COK021M+vIdPOIvbGU1ygfqsGo6u4IDT2hik78QmOppa8LHr5RMWs612nprOtsmJ0OR9J/g\ -YzJ2y2YFWrtwFFyarfNPlvgkSJz8+yGEa1R5cZfzvQKmFOwLB2rVG5K47ijJGkqhO6o7XxB8f3z4HJzvARYBJVrA4oDNh8oEfSBl/JJWlgtEMEM9AvODUQW7lgHCyywqT7YjCmVUrAzbMwvCdFRIAQUbyqWvl7xv\ -xzBzLjnhwd/3MIjonGOJcw/x6Tv6p6SaEBeD/VINdpCRPn2MOR/Q6juKtzhVlbQc6hXFya1kkl6iVylEK33EqYiAwQq0bFAowyqsZU/EGIs0j7CeeJHWoN264wwRd3hByO1UshklhRNBhUPmphO2OqqbhmQclO72\ -INN074a07XkIfd1Kpgur8YApmTgMRHVi4Y042UxGDZSCwfEuf7ZrxOHMKMPUXFQ4gh7wJ5cn98B8UniMmwYJwQokchn73V1wAvJ2fMRWveIto0Er/s9Sb6Q14gZf7ddICGuVztNriwcbTK3zyrCo2xM7rqABscct\ -o1tW/2ozikdVZQ/h8JYCVqbS09kCh9TuaU8FtKpT/lrINOw9QVNCzdOkh3aL3gH3i7jJd085958EG9FW7Aw27UgRaAJEnz1ivAXn0XmyEZASklNIcpQapxywoeM5Mt4BKtIgGDdi4lRMcjg4MdjmcAwjaWlFoTHL\ -LvK/4Bm4IB2govo16SsZ72QQ6mLdb8k4Rgo/1iD+9FI1V7/j6xkf1pPR/ZBe3jZ2sBAAjCWuCIwuMD3vfw2MaRdRwDm9LJyS5whNG9GcfhEOJfd2ox1dZWi7HTDlYfCJTIYBzwsXif0St9/wplwQyxI1mqYriacu\ -jRhzzJhBTOXC2AduiF7Vvt9zIWMZjVF1DqIwQ7iQKUsbbsbfimhTqDDVlKxVxAWVL1H/VpL6fXTdQRlbnJKILlnWGE7LOHptEhz4/GmazFOyblXtcYnpp9dRqMTmEpSQWt0sA8QZJQIKHBBRCdPhnDzBuftEDWqD\ -QG0O3JzRWfqu+YndKaoBG/712Lz8x5pNW0TO+VPYaNjxGbdiV0gR85crdN5B7rTK+Zmg3pTSmWxIzKUtEiQ9/TlY+zA3Y6u3kTI6Jzb4bM3XthZVNZFJZGorTMuquXSpMM3AltZzBpAmtjLH5bgy4iY/cudCU/N5\ -m1CqsaGn5dblRmB0JXL6ENY9gx0PonBbLW/YoEjO5KqgjrZMSGKKSwsHLe3G8D0EOCPEJWw5q/dQdrf5A5iJO4AjFPt85uoktCRVTeuIG9TfIhZEdcEOj2J+TrXe9s5bAnnopPbYMurJYM0A4/Nd6IJYAm1wZ8MF\ -hBVEZ7lJ/ig7c9vV0CxrwdrhmFiM1nsUp4cIM2G8g+dS4kDF0Yal1eCVRcJGAyPY5K0SmV9HjCs+TUYPyZwgBHfPdqmzQ8KaluMSBcSIfsqilL7LkjAHk/qDXKZo+a4vgslx1WixlbwD2VT1IOCuJhjUHBNMH/uY\ -gN00JNP9Mc9sCnGijSUnQu1PAt7FFz9CgGNSudaj6aNa78JRXMqk+8rizorYIbj/7aILssjQxIg02xpoowEsMZDpGcM5YCTtVwzUUAR1H8HEWrw7kllwOVB/+yci2UnVMT4ZEOoeDba8Tz06N/S99ijqeHUsXqTI\ -xtULqu3wDCah6zmy4JxeFLbEU7JtmAZdAUxPK24dxEIcBaV2HNFEbqtKW4a1vk/4lgMUbWqu//1IJ6+bZCI9ZDSI5XopuerlqqFSF+BfE0qFpq+RU0yvpngxsiUJi7KhhpHbkNUk4fuVIK8gmwhJhqpChqTKgLuq\ -CS0wbDJ0XK0UnKkP0arhPJYnyDPnu5cMT3A4LcYsho1IMm8nDA50tcSNZUvYjD0avG+qGM8VV2Hdmn5rwZc2EdNhzpSAOq62SSR4dzAEL8r+wH0gPGySd0gmgPVyJ/12yc3TODEHdIVzAd82oWnYxmImydo3/825\ -dm+Eor0r1e8l1e+TVNZbTp/EYg1bQsdXORbJfqYmBrhpl9/HTRqi3GU3oIRreK1uId9z5qYKBgkEwfFb7qw5NVyFaxj9zADAl0CAOGAqVipg7u0avunopbLR1BEHFpyMcS/L1qta9bK/AlsAB9KfJXiR+VgDoxIj\ -Ld88NXDP0GjuAsFcdFgOfA2ghuWbNxzA1sOnQBU7Ew1xh71+kXAb7hXw3qRiLIqamiSwzX/GgvrC6QHUFdUt6NbdUKise4yZNxzjqxtqlLUDUglS1rs/gLa12O0ZWs31DnMBaGWLIdrFV3QDHBMFRvyOTPuMslLL\ -d1t4I9etNsC1Ds5tJqtzcHyN6jQ3bMi4d+qANZZjglxnwEzbBceiPIwp52soi8HxtQyGK1CBnpIe+t6X3Jf1HEvjcDFsS+ZBs/FVdNfK1wLi9fSU85GpCxNnntUQHKcRKOgb8IQLCIRvQM7PGPQorR2irvpt+Twf\ -uTi8mvPVGEbifLge3Y57LItVaUgHA4tmAjc8/QDB7/m7k/QHRFD9himulfz2zSVshHaXb0Al1L0PCYz0+I36Mcpr9eVQYjo93wHmP+Lyd0zU4IWlCdurnKYB1Z9RTWjCrwgfQJSmCGaw/hbFyK3RkBPvMGayA1Lv\ -JA8yxwhexcLCjtlX6nPQLlsc9CdbKT9VoV87uvrLdu/JXkDGpdx+y6qlvLR1GIdN/P+ScO4+jcTHG3Zov7Is5DB2tDQNjITlvGQsru2HCf6/sZ9+WTTX8L/HVFaXRaGqUvsv3dXi+sswWGQ5DLbNouH/ZhY1f7f5\ -S0yomEyqQut//QdAk8Ky\ +eNqNWntX3DYW/yrGCQxQ6JFsj0dmT8uj6YQk3d2QbghJZ0/Hlm0I27ApnRPIabqffXVfkjwzbPcPQNbz6j5+9yF+Hy26+8XoIGlGs/veJO5XcQgtha3yeHavXLPS7rN1P/3s3qqEOo2ZLdxvaKnH56c0ijPr/2em\ +hv0UTZAfrYQCFbWiHyMUdWM3bGknA2c21FauT2X+7B1YE1O1sUJe+p525M/t2eL8dpV+3AY215ncxH0XybZafxOljojULtCpS0dJHWju2ohndunMqqIzQwcScf75Ye75Hx3aRoXVFoTaH9IG8qPoHpG4N4SaLIUh\ +oPs71xjDTUy4SVfTaD0W7l+cEIt6YVV+DNvC0Bs3D3qbixRoeg2idgTZMczIeFMQXQ7cTo8u3KfedP15JGLFbbjWGHY4C51BVsC3Ma1os8HgydVA0qfIzwVvak5OUxa1VQcFbHRSpUuMNvQX9RLJVUtKih+Vinit\ +zBG3TCQOpLSIv4+OpHVK3bhGD/Yt/L5BUshe4M4EGsfS8Le8AHt4/h2onR4MbLtfZZIsWJoZmKgtH8GQm9x1NLnRoe15XGdb3MCfhRNUI3rm9rKsGaDXXazvTbRnEwmzor+wR8Ntf5Zl26ucLHUzOJY4TVBFg6Dl\ +0FdxXzCe7CdmuqPH2MFdTnkkOgAp1xGFvF81gTO+jZcbuiveTwV7btG2J2TwupoSKin1xU1zS4wb0cBmN7IYWi9vvWL+0FH4fR5GiioQ1GoPigu+ej5gygUf26RbvDFApxNhW7HIoV0IUjh9s0NdeEtLhmj0ch9U\ +i/HP/apxg4tCjS0rWw6WDjZevPvx5Wzm5phSVnfEITLKJ261G9HCZfOYeIegk5EbELbH8Api0QVwKU8coU2WMIYwInSRNRt7kJJO2WLnH0jVweu38AdIhquC4Q1xYOic0HQ/ohE573J4+hjvD/NT4kQdnJZwtm4J\ +qE0E/oGqb2Y3wd10luwIPYAmTa2zgO9gP1qgTxNz2i7yLVkEovmyLQffXCcxjmbsF5tsg2eCivereBzzslaPSMmW/RMqkLgbJV681vcRmewO8XpKrvocZmbX8ImyOk6hnSNlYJE1OJRqd5eONTQnxAGmer7zjvUF\ +tWp/dsP72zHTWw3o3SOs8Q48EATYi2LLSAlxWkeygPG2GcYiA8bIHMu6ng/3xrWyp+F9Jv9jn5bnFKtzVmMDuskB7F0GBJH95Fs3KQdWjYBXxti6NlaT9kX84QCuBXUfO/1vzddsCZWNusFzwn3dR7mxQTQAVKGA\ +o/hxYKRlwElw+yW7ErSil98Borccj4iEdJgW7wTWBCfI/IYNcYWKfHnt8/QI4fPckrKiQbDpNtFqAPa6Zp/QrZEh9FdR0NPIms2gpaghxHdEJ7ssBW9DkXbCibb9M424iuX1Mf5YxB/38QeA1CVjHeA5mwgcccXG\ +sgFiqyJ8kCvWPd3PmGegDreBU2il5d7sBvyIaS553gOSw9shAD11DIfObMpuA4U+iafES/8Kp5wJeoHsGyHt9TUtkrBRlftRhOYFdWSJwXSNkBGQ8syvRP/KBATCzgYAZtXZMJZHEQZyYfwKbl9+IDKq+mw6uxVK\ +NoUfc3ciHsE6i+6PNRAhjk8kWojHjU6cjOsJE9WsGNd1ev1kQmhqLQcOeNrLdv2lzcQN1zkd0cV5BPOsLdYLT+IRzYE2Bn3ZNnr9P1jLJsgfyMDK6ewGLjymiXX2QmCqp6MJH79QMNlwrNVOtqazERkZsqT/CIPJ\ +0CzrFWjtwlVwqVpnn8zxceA42fceuGsUef6Q8b0CojScCxdq9RviuOkoyPJJ0BqkxZi/O/z76fEzMj4Kng8LjOkXR6xBlCZgulEcLiV4a7JD0EQzwPOjQfq6lgaCTP/hBDmKdiiiZMUfzyREdEu4yps0IV36csVH\ +dww2FxIZHv2yi67EZOxRrN3D1g/0p6CcEBeDFld0iXtyQIqE6xzOhYeuH8j54gpd0C6QvGiOdNveW+dNCq7LnHBcoh6C9g1ycpiPtVKQKIXlJ5hcvEgnIOrJJoeLeMILgnGrEw4S0Ql0AhHHTE0nZHWURLV5BCB2\ +F8JO+87HcM+CHxSkCaR6nExJ37EjZIy50+hkMxnUUXJGyvwB467XsMOaQbhpOMOwhENgXDZLHoEipdCMawcJYQwcp9gITXTn+Hjgt+UrtvqMj4w6gVmYhXTE9VoqJNYbbreGQ3B+372CQ7865t0AvBuU7fVjf68r\ +ToPKT4Pr3nNsZUkNuPd96NVZesyXB++FemK3sQ+D37PZ4v3ZVogKtS0vKSfQ/TTcX/kN8oYbWKWC8oWep0l/Ao1tsNUo+c92zqbDYpG2aeqO3IxyPgCJRrSTkBsU1NasO3Qqm9LwYI7Gs2SDGI5xwYRCJa3jwGWT\ +MbAPnWBceFCEteQ+ppJcNzHTsNgzovqD4ji3whj7Mvsb3oQz24bv25efkr6U/kvpRK72W9IPkYOaSnmjl/S7RG/Vn/N9S8EbatfWaxdIbokq9KKOKjzoUyDMtNEOE9w/LMQJ47BtE207/Z2JrHMR4+BQW/6FTtwG\ +S/Cd38tk6HDkcMLZLxEsPgDu2IQlejDNEKNQgyLCOiYMPxUn2bGcpnueF50Mo0uBXF630qWp6xExx/TxbvmQjiegEDJWDMcOmRxTB0aiLZUX30vesI+A4Lm9xfJiKRvmMIhDj2PjcSpcI57Op8k8JdXX5S5nseV/\ +oowLfiBFNfrfy5hzTjCquxM2QQy3M/KP1j4mKnQXTq7VHBzuObHModMbNrQox6z5p8ey6OWaQ7FIZedP4CB/4lMu8q5sRcTP1+wDUZJuVok/F/idckCgBRWl8hI4Pb0OduDnKraHJgjjVng7XR0jN4KCmkfKovRW\ +mKbKn6UMhkEM1syOGVhqFS2znO/rSmznn1waMVTXHhE+1VHRbG1tHvStQEr3YN1TONFELrxcPrBGhryWV4hJdGRC/NKcu1iollNUu0GRGPg6rGbr95DXt9lXMBNPABvI9/nO5bNQ81QcXIjHqjPKuoUuwMmqFjaf\ +kusbbb8l/EdnjzWpnjS28gg/3wE4doy1E6rmVZyhNIL3zDev15nk+1jXrWhW04C6A58x253sku/3zmfMBQ1oF+IfSnZEzK0aX0MSVhrowSpymcj8SUS45tsoaiRzcod4utphF4PMmubDHAgTtjawUlz4EjO9Sn0t\ +7zRGxs1lUDlIkt14gyzfhggNsYXB2BCkkvkQdUqFownnplvejk5lYiHgnizZEIYrJeMlyYRWxUMrNsxJZzfYbHAOl3KZtVj3jNXNSCzL72yRUonC1KxXVO0D1IBIsao4jIo4+4qcPQqi+wDq1OITlMyCl4bJN9+T\ +dnSSvwxvBBt1B15v96ngZ30RbZf8i2P94kWKZNy8oEQR71Al9MpH2prRhy7ffkVKDHOgvoCxLdytiQGjH/qeuh96LR9VlsMgTqll/Or7hN9LIKKqxlxJwJ7a93QSpZ1DKD5Ziq56ebQojy7BkMYhFvoNifUh1j36\ +zZJFr8chDSLFWBMowPAHHwnYdRGGKqvgelUXp7aDuEKXTwfeX5fkz2/CCrilZc3DjMJwYuA9Wc0BLk/AalE3CPYBuYAdhh2VlgIcgsy8BU8LAmsUF7Qb8hJcm8SXrpKBXlKxbk2lN+fnoojkeA5WQZg65XmAjxbe\ +qVGoCA48eCr/Cl2KfUitXyL6NA7nKePRkJ02TULTkClMpoB6Pf6dI3R8G+iWlHLNzojASQ8pAlRCesiaxX0a4FvV+qn4eLRFmSPyOeM3LQT4H46Hxe0qq2e38spYZRsQL9TZDteIS3au0DY75DmlQlGP3z3woJTN\ +gTphAF8ay0ndqmyMPbiVZ6XPr6CYml3ffYY/99n8EtTlPRgIltq65qFMqpdMqk9SOTPiEaHMNLatYzbo7tfwrNJlj1EGNW3dqTs4/xY+y/tN2Ka6K4Oxg9cBRG25/ml19xMz0kDvr5St9PxUB1AORmVYQxuWWcXv\ +Ub0kj4ZSNyDBSh9XHKtilYNO9jdgORDZmF8lAiBDayrolUCj4ffBGl6DasO1OpiLYMjRQw1w3PD7KHZgTehj2BUrRzVRhy8ywuI2vP7g61bJIB+Vnolhm7/EjPrMMRZkbOU9CNfeUbwx6THwuONAqbyjciZoA5ai\ +vS+b7PwIUvpWxHsO4Vq/jUS8khvLO/mKK/C+bufHKddDO//uNzqnl5AatfjTGgjSraDgxzUKrn9b7QTFrHDV1YTtFUvPXBS/+TOcu1qd0DHQSVJQRYBFoS8svF5DoOgmv7NBsIbSMo4XHe6yPRtdTeZYpQgv/U1B\ +EgaWgrrY8so/8giUUivbvJMaWhzjY5gCZZt8yo8xvbmDG16Ct3kDOz9lB0KY7AMeLF4NrvGBE/ObOT9xqnLuIWkU18ZerPEPVrznW/F/eON1tSh6+QA+lxeYRlSSQ7y5goNQLbMNSDG69yEUlIeaSo+jYM5czRZe\ +MefbQPkHXK550wpfnau4FEbTYNdnnlhU8xSi/Om/aOX6RzDvJnzGsc1oypaJYZvNAqsxjojDWPQN+RcqENIpWxxpjbdSbpWh1j54uVU7j+Qs2MamXDDFBXHU31qMaqr4H8pw7j5X+KLr+RPaLwSi/jLNYGkaCAnL\ +ecmQXaO9BP/h7+ffFvUt/NufVpMir3JljBvpbha3n31nUUwy19nWi5r/PzCq2o94JN4on+RlqbM//gt1kVkF\ """))) diff --git a/tools/gen_esp32part.exe b/tools/gen_esp32part.exe index 495e2185366..f81ac71c56a 100644 Binary files a/tools/gen_esp32part.exe and b/tools/gen_esp32part.exe differ diff --git a/tools/gen_esp32part.py b/tools/gen_esp32part.py index a8607f360cc..e3c8a6dc433 100755 --- a/tools/gen_esp32part.py +++ b/tools/gen_esp32part.py @@ -4,7 +4,7 @@ # # Converts partition tables to/from CSV and binary formats. # -# See http://esp-idf.readthedocs.io/en/latest/api-guides/partition-tables.html +# See https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/partition-tables.html # for explanation of partition table structure and uses. # # Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD @@ -21,6 +21,7 @@ # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function, division +from __future__ import unicode_literals import argparse import os import re @@ -31,11 +32,40 @@ MAX_PARTITION_LENGTH = 0xC00 # 3K for partition data (96 entries) leaves 1K in a 4K sector for signature MD5_PARTITION_BEGIN = b"\xEB\xEB" + b"\xFF" * 14 # The first 2 bytes are like magic numbers for MD5 sum - -__version__ = '1.0' +PARTITION_TABLE_SIZE = 0x1000 # Size of partition table + +__version__ = '1.2' + +APP_TYPE = 0x00 +DATA_TYPE = 0x01 + +TYPES = { + "app" : APP_TYPE, + "data" : DATA_TYPE, +} + +# Keep this map in sync with esp_partition_subtype_t enum in esp_partition.h +SUBTYPES = { + APP_TYPE : { + "factory" : 0x00, + "test" : 0x20, + }, + DATA_TYPE : { + "ota" : 0x00, + "phy" : 0x01, + "nvs" : 0x02, + "coredump" : 0x03, + "nvs_keys" : 0x04, + "esphttpd" : 0x80, + "fat" : 0x81, + "spiffs" : 0x82, + }, +} quiet = False md5sum = True +secure = False +offset_part_table = 0 def status(msg): """ Print status message to stderr """ @@ -44,9 +74,8 @@ def status(msg): def critical(msg): """ Print critical message to stderr """ - if not quiet: - sys.stderr.write(msg) - sys.stderr.write('\n') + sys.stderr.write(msg) + sys.stderr.write('\n') class PartitionTable(list): def __init__(self): @@ -69,18 +98,25 @@ def expand_vars(f): if line.startswith("#") or len(line) == 0: continue try: - res.append(PartitionDefinition.from_csv(line)) + res.append(PartitionDefinition.from_csv(line, line_no+1)) except InputError as e: raise InputError("Error at line %d: %s" % (line_no+1, e)) except Exception: - critical("Unexpected error parsing line %d: %s" % (line_no+1, line)) + critical("Unexpected error parsing CSV line %d: %s" % (line_no+1, line)) raise # fix up missing offsets & negative sizes - last_end = 0x5000 # first offset after partition table + last_end = offset_part_table + PARTITION_TABLE_SIZE # first offset after partition table for e in res: + if e.offset is not None and e.offset < last_end: + if e == res[0]: + raise InputError("CSV Error: First partition offset 0x%x overlaps end of partition table 0x%x" + % (e.offset, last_end)) + else: + raise InputError("CSV Error: Partitions overlap. Partition at line %d sets offset 0x%x. Previous partition ends 0x%x" + % (e.line_no, e.offset, last_end)) if e.offset is None: - pad_to = 0x10000 if e.type == PartitionDefinition.APP_TYPE else 4 + pad_to = 0x10000 if e.type == APP_TYPE else 4 if last_end % pad_to != 0: last_end += pad_to - (last_end % pad_to) e.offset = last_end @@ -101,19 +137,72 @@ def __getitem__(self, item): else: return super(PartitionTable, self).__getitem__(item) + def find_by_type(self, ptype, subtype): + """ Return a partition by type & subtype, returns + None if not found """ + # convert ptype & subtypes names (if supplied this way) to integer values + try: + ptype = TYPES[ptype] + except KeyError: + try: + ptypes = int(ptype, 0) + except TypeError: + pass + try: + subtype = SUBTYPES[int(ptype)][subtype] + except KeyError: + try: + ptypes = int(ptype, 0) + except TypeError: + pass + + for p in self: + if p.type == ptype and p.subtype == subtype: + return p + return None + + def find_by_name(self, name): + for p in self: + if p.name == name: + return p + return None + def verify(self): # verify each partition individually for p in self: p.verify() + + # check on duplicate name + names = [ p.name for p in self ] + duplicates = set( n for n in names if names.count(n) > 1 ) + + # print sorted duplicate partitions by name + if len(duplicates) != 0: + print("A list of partitions that have the same name:") + for p in sorted(self, key=lambda x:x.name): + if len(duplicates.intersection([p.name])) != 0: + print("%s" % (p.to_csv())) + raise InputError("Partition names must be unique") + # check for overlaps last = None for p in sorted(self, key=lambda x:x.offset): - if p.offset < 0x5000: - raise InputError("Partition offset 0x%x is below 0x5000" % p.offset) + if p.offset < offset_part_table + PARTITION_TABLE_SIZE: + raise InputError("Partition offset 0x%x is below 0x%x" % (p.offset, offset_part_table + PARTITION_TABLE_SIZE)) if last is not None and p.offset < last.offset + last.size: raise InputError("Partition at 0x%x overlaps 0x%x-0x%x" % (p.offset, last.offset, last.offset+last.size-1)) last = p + def flash_size(self): + """ Return the size that partitions will occupy in flash + (ie the offset the last partition ends at) + """ + try: + last = sorted(self, reverse=True)[0] + except IndexError: + return 0 # empty table! + return last.offset + last.size + @classmethod def from_binary(cls, b): md5 = hashlib.md5(); @@ -150,30 +239,6 @@ def to_csv(self, simple_formatting=False): return "\n".join(rows) + "\n" class PartitionDefinition(object): - APP_TYPE = 0x00 - DATA_TYPE = 0x01 - TYPES = { - "app" : APP_TYPE, - "data" : DATA_TYPE, - } - - # Keep this map in sync with esp_partition_subtype_t enum in esp_partition.h - SUBTYPES = { - APP_TYPE : { - "factory" : 0x00, - "test" : 0x20, - }, - DATA_TYPE : { - "ota" : 0x00, - "phy" : 0x01, - "nvs" : 0x02, - "coredump" : 0x03, - "esphttpd" : 0x80, - "fat" : 0x81, - "spiffs" : 0x82, - }, - } - MAGIC_BYTES = b"\xAA\x50" ALIGNMENT = { @@ -187,7 +252,7 @@ class PartitionDefinition(object): "encrypted" : 0 } - # add subtypes for the 16 OTA slot values ("ota_XXX, etc.") + # add subtypes for the 16 OTA slot values ("ota_XX, etc.") for ota_slot in range(16): SUBTYPES[TYPES["app"]]["ota_%d" % ota_slot] = 0x10 + ota_slot @@ -200,12 +265,13 @@ def __init__(self): self.encrypted = False @classmethod - def from_csv(cls, line): + def from_csv(cls, line, line_no): """ Parse a line from the CSV """ line_w_defaults = line + ",,,," # lazy way to support default fields fields = [ f.strip() for f in line_w_defaults.split(",") ] res = PartitionDefinition() + res.line_no = line_no res.name = fields[0] res.type = res.parse_type(fields[1]) res.subtype = res.parse_subtype(fields[2]) @@ -240,15 +306,27 @@ def __str__(self): def __cmp__(self, other): return self.offset - other.offset + def __lt__(self, other): + return self.offset < other.offset + + def __gt__(self, other): + return self.offset > other.offset + + def __le__(self, other): + return self.offset <= other.offset + + def __ge__(self, other): + return self.offset >= other.offset + def parse_type(self, strval): if strval == "": raise InputError("Field 'type' can't be left empty.") - return parse_int(strval, self.TYPES) + return parse_int(strval, TYPES) def parse_subtype(self, strval): if strval == "": return 0 # default - return parse_int(strval, self.SUBTYPES.get(self.type, {})) + return parse_int(strval, SUBTYPES.get(self.type, {})) def parse_address(self, strval): if strval == "": @@ -265,10 +343,20 @@ def verify(self): align = self.ALIGNMENT.get(self.type, 4) if self.offset % align: raise ValidationError(self, "Offset 0x%x is not aligned to 0x%x" % (self.offset, align)) + if self.size % align and secure: + raise ValidationError(self, "Size 0x%x is not aligned to 0x%x" % (self.size, align)) if self.size is None: raise ValidationError(self, "Size field is not set") - STRUCT_FORMAT = "<2sBBLL16sL" + if self.name in TYPES and TYPES.get(self.name, "") != self.type: + critical("WARNING: Partition has name '%s' which is a partition type, but does not match this partition's type (0x%x). Mistake in partition table?" % (self.name, self.type)) + all_subtype_names = [] + for names in (t.keys() for t in SUBTYPES.values()): + all_subtype_names += names + if self.name in all_subtype_names and SUBTYPES.get(self.type, {}).get(self.name, "") != self.subtype: + critical("WARNING: Partition has name '%s' which is a partition subtype, but this partition has non-matching type 0x%x and subtype 0x%x. Mistake in partition table?" % (self.name, self.type, self.subtype)) + + STRUCT_FORMAT = b"<2sBBLL16sL" @classmethod def from_binary(cls, b): @@ -321,8 +409,8 @@ def generate_text_flags(): return ":".join(self.get_flags_list()) return ",".join([ self.name, - lookup_keyword(self.type, self.TYPES), - lookup_keyword(self.subtype, self.SUBTYPES.get(self.type, {})), + lookup_keyword(self.type, TYPES), + lookup_keyword(self.subtype, SUBTYPES.get(self.type, {})), addr_format(self.offset, False), addr_format(self.size, True), generate_text_flags()]) @@ -348,21 +436,28 @@ def parse_int(v, keywords={}): def main(): global quiet global md5sum + global offset_part_table + global secure parser = argparse.ArgumentParser(description='ESP32 partition table utility') + parser.add_argument('--flash-size', help='Optional flash size limit, checks partition table fits in flash', + nargs='?', choices=[ '1MB', '2MB', '4MB', '8MB', '16MB' ]) parser.add_argument('--disable-md5sum', help='Disable md5 checksum for the partition table', default=False, action='store_true') - parser.add_argument('--verify', '-v', help='Verify partition table fields', default=True, action='store_false') - parser.add_argument('--quiet', '-q', help="Don't print status messages to stderr", action='store_true') - - parser.add_argument('input', help='Path to CSV or binary file to parse. Will use stdin if omitted.', type=argparse.FileType('rb'), default=sys.stdin) - parser.add_argument('output', help='Path to output converted binary or CSV file. Will use stdout if omitted, unless the --display argument is also passed (in which case only the summary is printed.)', - nargs='?', - default='-') + parser.add_argument('--no-verify', help="Don't verify partition table fields", action='store_true') + parser.add_argument('--verify', '-v', help="Verify partition table fields (deprecated, this behaviour is enabled by default and this flag does nothing.", action='store_true') + parser.add_argument('--quiet', '-q', help="Don't print non-critical status messages to stderr", action='store_true') + parser.add_argument('--offset', '-o', help='Set offset partition table', default='0x8000') + parser.add_argument('--secure', help="Require app partitions to be suitable for secure boot", action='store_true') + parser.add_argument('input', help='Path to CSV or binary file to parse.', type=argparse.FileType('rb')) + parser.add_argument('output', help='Path to output converted binary or CSV file. Will use stdout if omitted.', + nargs='?', default='-') args = parser.parse_args() quiet = args.quiet md5sum = not args.disable_md5sum + secure = args.secure + offset_part_table = int(args.offset, 0) input = args.input.read() input_is_binary = input[0:2] == PartitionDefinition.MAGIC_BYTES if input_is_binary: @@ -373,17 +468,29 @@ def main(): status("Parsing CSV input...") table = PartitionTable.from_csv(input) - if args.verify: + if not args.no_verify: status("Verifying table...") table.verify() + if args.flash_size: + size_mb = int(args.flash_size.replace("MB", "")) + size = size_mb * 1024 * 1024 # flash memory uses honest megabytes! + table_size = table.flash_size() + if size < table_size: + raise InputError("Partitions defined in '%s' occupy %.1fMB of flash (%d bytes) which does not fit in configured flash size %dMB. Change the flash size in menuconfig under the 'Serial Flasher Config' menu." % + (args.input.name, table_size / 1024.0 / 1024.0, table_size, size_mb)) + if input_is_binary: output = table.to_csv() with sys.stdout if args.output == '-' else open(args.output, 'w') as f: f.write(output) else: output = table.to_binary() - with sys.stdout.buffer if args.output == '-' else open(args.output, 'wb') as f: + try: + stdout_binary = sys.stdout.buffer # Python 3 + except AttributeError: + stdout_binary = sys.stdout + with stdout_binary if args.output == '-' else open(args.output, 'wb') as f: f.write(output) diff --git a/tools/get.py b/tools/get.py index 31ea0ad978f..cb1cfb95cb9 100755 --- a/tools/get.py +++ b/tools/get.py @@ -25,10 +25,12 @@ if sys.version_info[0] == 3: from urllib.request import urlretrieve + from urllib.request import urlopen unicode = lambda s: str(s) else: # Not Python 3 - today, it is most likely to be Python 2 from urllib import urlretrieve + from urllib import urlopen if 'Windows' in platform.system(): import requests @@ -58,7 +60,7 @@ def report_progress(count, blockSize, totalSize): def unpack(filename, destination): dirname = '' - print('Extracting {0}'.format(os.path.basename(filename))) + print('Extracting {0} ...'.format(os.path.basename(filename))) sys.stdout.flush() if filename.endswith('tar.gz'): tfile = tarfile.open(filename, 'r:gz') @@ -74,19 +76,38 @@ def unpack(filename, destination): # a little trick to rename tool directories so they don't contain version number rename_to = re.match(r'^([a-z][^\-]*\-*)+', dirname).group(0).strip('-') if rename_to != dirname: - print('Renaming {0} to {1}'.format(dirname, rename_to)) + print('Renaming {0} to {1} ...'.format(dirname, rename_to)) if os.path.isdir(rename_to): shutil.rmtree(rename_to) shutil.move(dirname, rename_to) +def download_file(url,filename): + import ssl + import contextlib + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + with contextlib.closing(urlopen(url,context=ctx)) as fp: + block_size = 1024 * 8 + block = fp.read(block_size) + if block: + with open(filename,'wb') as out_file: + out_file.write(block) + while True: + block = fp.read(block_size) + if not block: + break + out_file.write(block) + else: + raise Exception ('nonexisting file or connection error') + def get_tool(tool): sys_name = platform.system() archive_name = tool['archiveFileName'] local_path = dist_dir + archive_name url = tool['url'] - #real_hash = tool['checksum'].split(':')[1] if not os.path.isfile(local_path): - print('Downloading ' + archive_name) + print('Downloading ' + archive_name + ' ...') sys.stdout.flush() if 'CYGWIN_NT' in sys_name: import ssl @@ -100,16 +121,16 @@ def get_tool(tool): f.write(r.content) f.close() else: - urlretrieve(url, local_path, report_progress) - sys.stdout.write("\rDone\n") - sys.stdout.flush() + is_ci = os.environ.get('GITHUB_WORKSPACE'); + if is_ci: + download_file(url, local_path) + else: + urlretrieve(url, local_path, report_progress) + sys.stdout.write("\rDone\n") + sys.stdout.flush() else: print('Tool {0} already downloaded'.format(archive_name)) sys.stdout.flush() - #local_hash = sha256sum(local_path) - #if local_hash != real_hash: - # print('Hash mismatch for {0}, delete the file and try again'.format(local_path)) - # raise RuntimeError() unpack(local_path, '.') def load_tools_list(filename, platform): @@ -132,11 +153,11 @@ def identify_platform(): bits = 64 sys_name = platform.system() sys_platform = platform.platform() - print('System: %s, Info: %s' % (sys_name, sys_platform)) - if 'Linux' in sys_name and sys_platform.find('arm') > 0: + if 'Linux' in sys_name and (sys_platform.find('arm') > 0 or sys_platform.find('aarch64') > 0): sys_name = 'LinuxARM' if 'CYGWIN_NT' in sys_name: sys_name = 'Windows' + print('System: %s, Bits: %d, Info: %s' % (sys_name, bits, sys_platform)) return arduino_platform_names[sys_name][bits] if __name__ == '__main__': @@ -146,4 +167,4 @@ def identify_platform(): mkdir_p(dist_dir) for tool in tools_to_download: get_tool(tool) - print('Done') + print('Platform Tools Installed') diff --git a/tools/partitions/app3M_fat9M_16MB.csv b/tools/partitions/app3M_fat9M_16MB.csv new file mode 100644 index 00000000000..0f67e69fbfe --- /dev/null +++ b/tools/partitions/app3M_fat9M_16MB.csv @@ -0,0 +1,7 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x300000, +app1, app, ota_1, 0x310000,0x300000, +ffat, data, fat, 0x610000,0x9F0000, +# to create/use ffat, see https://github.com/marcmerlin/esp32_fatfsimage diff --git a/tools/partitions/default.csv b/tools/partitions/default.csv index 3e4235d739f..e9772b6f891 100644 --- a/tools/partitions/default.csv +++ b/tools/partitions/default.csv @@ -3,5 +3,4 @@ nvs, data, nvs, 0x9000, 0x5000, otadata, data, ota, 0xe000, 0x2000, app0, app, ota_0, 0x10000, 0x140000, app1, app, ota_1, 0x150000,0x140000, -eeprom, data, 0x99, 0x290000,0x1000, -spiffs, data, spiffs, 0x291000,0x16F000, +spiffs, data, spiffs, 0x290000,0x170000, diff --git a/tools/partitions/default_16MB.csv b/tools/partitions/default_16MB.csv new file mode 100644 index 00000000000..7b89daee9f0 --- /dev/null +++ b/tools/partitions/default_16MB.csv @@ -0,0 +1,6 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x640000, +app1, app, ota_1, 0x650000,0x640000, +spiffs, data, spiffs, 0xc90000,0x370000, diff --git a/tools/partitions/default_8MB.csv b/tools/partitions/default_8MB.csv new file mode 100644 index 00000000000..d21c7f6b177 --- /dev/null +++ b/tools/partitions/default_8MB.csv @@ -0,0 +1,6 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x330000, +app1, app, ota_1, 0x340000,0x330000, +spiffs, data, spiffs, 0x670000,0x190000, diff --git a/tools/partitions/default_ffat.csv b/tools/partitions/default_ffat.csv new file mode 100644 index 00000000000..d921c9fe3d9 --- /dev/null +++ b/tools/partitions/default_ffat.csv @@ -0,0 +1,6 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x140000, +app1, app, ota_1, 0x150000,0x140000, +ffat, data, fat, 0x290000,0x170000, diff --git a/tools/partitions/ffat.csv b/tools/partitions/ffat.csv new file mode 100644 index 00000000000..b98bf0c3034 --- /dev/null +++ b/tools/partitions/ffat.csv @@ -0,0 +1,7 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x200000, +app1, app, ota_1, 0x210000,0x200000, +ffat, data, fat, 0x410000,0xBF0000, +# to create/use ffat, see https://github.com/marcmerlin/esp32_fatfsimage diff --git a/tools/partitions/huge_app.csv b/tools/partitions/huge_app.csv new file mode 100644 index 00000000000..290a7cc738b --- /dev/null +++ b/tools/partitions/huge_app.csv @@ -0,0 +1,5 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x300000, +spiffs, data, spiffs, 0x310000,0xF0000, diff --git a/tools/partitions/large_spiffs_16MB.csv b/tools/partitions/large_spiffs_16MB.csv new file mode 100644 index 00000000000..7974c9eb140 --- /dev/null +++ b/tools/partitions/large_spiffs_16MB.csv @@ -0,0 +1,6 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x480000, +app1, app, ota_1, 0x490000,0x480000, +spiffs, data, spiffs, 0x910000,0x6F0000, diff --git a/tools/partitions/min_spiffs.csv b/tools/partitions/min_spiffs.csv index ae4aa752671..0b6a9ffd01e 100644 --- a/tools/partitions/min_spiffs.csv +++ b/tools/partitions/min_spiffs.csv @@ -3,5 +3,4 @@ nvs, data, nvs, 0x9000, 0x5000, otadata, data, ota, 0xe000, 0x2000, app0, app, ota_0, 0x10000, 0x1E0000, app1, app, ota_1, 0x1F0000,0x1E0000, -eeprom, data, 0x99, 0x3F0000,0x1000, -spiffs, data, spiffs, 0x3F1000,0xF000, +spiffs, data, spiffs, 0x3D0000,0x30000, diff --git a/tools/partitions/minimal.csv b/tools/partitions/minimal.csv index 703fbee3d4b..6ebeeb32dc2 100644 --- a/tools/partitions/minimal.csv +++ b/tools/partitions/minimal.csv @@ -2,5 +2,4 @@ nvs, data, nvs, 0x9000, 0x5000, otadata, data, ota, 0xe000, 0x2000, app0, app, ota_0, 0x10000, 0x140000, -eeprom, data, 0x99, 0x150000, 0x1000, -spiffs, data, spiffs, 0x151000, 0xAF000, +spiffs, data, spiffs, 0x150000, 0xB0000, diff --git a/tools/partitions/no_ota.csv b/tools/partitions/no_ota.csv index 8b86c231979..3314273b884 100644 --- a/tools/partitions/no_ota.csv +++ b/tools/partitions/no_ota.csv @@ -2,5 +2,4 @@ nvs, data, nvs, 0x9000, 0x5000, otadata, data, ota, 0xe000, 0x2000, app0, app, ota_0, 0x10000, 0x200000, -eeprom, data, 0x99, 0x210000,0x1000, -spiffs, data, spiffs, 0x211000,0x1EF000, +spiffs, data, spiffs, 0x210000,0x1F0000, diff --git a/tools/partitions/noota_3g.csv b/tools/partitions/noota_3g.csv new file mode 100644 index 00000000000..a684385bdc8 --- /dev/null +++ b/tools/partitions/noota_3g.csv @@ -0,0 +1,5 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x100000, +spiffs, data, spiffs, 0x110000,0x2F0000, diff --git a/tools/partitions/noota_3gffat.csv b/tools/partitions/noota_3gffat.csv new file mode 100644 index 00000000000..f008c277897 --- /dev/null +++ b/tools/partitions/noota_3gffat.csv @@ -0,0 +1,6 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x100000, +ffat, data, fat, 0x110000,0x2F0000, +# to create/use ffat, see https://github.com/marcmerlin/esp32_fatfsimage diff --git a/tools/partitions/noota_ffat.csv b/tools/partitions/noota_ffat.csv new file mode 100644 index 00000000000..69d702f80b2 --- /dev/null +++ b/tools/partitions/noota_ffat.csv @@ -0,0 +1,6 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x200000, +ffat, data, fat, 0x210000,0x1F0000, +# to create/use ffat, see https://github.com/marcmerlin/esp32_fatfsimage diff --git a/tools/platformio-build.py b/tools/platformio-build.py index 3bc9ebb58bb..93c021a2bfb 100644 --- a/tools/platformio-build.py +++ b/tools/platformio-build.py @@ -24,7 +24,7 @@ # Extends: https://github.com/platformio/platform-espressif32/blob/develop/builder/main.py -from os.path import isdir, join +from os.path import abspath, isdir, isfile, join from SCons.Script import DefaultEnvironment @@ -34,123 +34,151 @@ FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoespressif32") assert isdir(FRAMEWORK_DIR) -env.Prepend( - CPPDEFINES=[ - ("ARDUINO", 10805), - "ARDUINO_ARCH_ESP32", - ("ARDUINO_VARIANT", '\\"%s\\"' % env.BoardConfig().get("build.variant").replace('"', "")), - ("ARDUINO_BOARD", '\\"%s\\"' % env.BoardConfig().get("name").replace('"', "")) - ], +env.Append( + ASFLAGS=["-x", "assembler-with-cpp"], - CFLAGS=["-Wno-old-style-declaration"], + CFLAGS=[ + "-std=gnu99", + "-Wno-old-style-declaration" + ], CCFLAGS=[ + "-Os", + "-g3", + "-Wall", + "-nostdlib", + "-Wpointer-arith", + "-Wno-error=unused-but-set-variable", + "-Wno-error=unused-variable", + "-mlongcalls", + "-ffunction-sections", + "-fdata-sections", + "-fstrict-volatile-bitfields", "-Wno-error=deprecated-declarations", "-Wno-error=unused-function", "-Wno-unused-parameter", "-Wno-sign-compare", "-fstack-protector", - "-fexceptions" + "-fexceptions", + "-Werror=reorder" + ], + + CXXFLAGS=[ + "-fno-rtti", + "-fno-exceptions", + "-std=gnu++11" + ], + + LINKFLAGS=[ + "-nostdlib", + "-Wl,-static", + "-u", "call_user_start_cpu0", + "-Wl,--undefined=uxTopUsedPriority", + "-Wl,--gc-sections", + "-Wl,-EL", + "-T", "esp32.common.ld", + "-T", "esp32.rom.ld", + "-T", "esp32.peripherals.ld", + "-T", "esp32.rom.libgcc.ld", + "-T", "esp32.rom.spiram_incompatible_fns.ld", + "-u", "ld_include_panic_highint_hdl", + "-u", "__cxa_guard_dummy", + "-u", "__cxx_fatal_exception" + ], + + CPPDEFINES=[ + "ESP32", + "ESP_PLATFORM", + ("F_CPU", "$BOARD_F_CPU"), + "HAVE_CONFIG_H", + ("MBEDTLS_CONFIG_FILE", '\\"mbedtls/esp_config.h\\"'), + ("ARDUINO", 10805), + "ARDUINO_ARCH_ESP32", + ("ARDUINO_VARIANT", '\\"%s\\"' % env.BoardConfig().get("build.variant").replace('"', "")), + ("ARDUINO_BOARD", '\\"%s\\"' % env.BoardConfig().get("name").replace('"', "")) ], CPPPATH=[ - join(FRAMEWORK_DIR, "tools", "sdk", "include", "config"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "bluedroid"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "config"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "app_trace"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "app_update"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "asio"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "bootloader_support"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "bt"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "coap"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "console"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "driver"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp-tls"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp32"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_adc_cal"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_event"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_http_client"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_http_server"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_https_ota"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_ringbuf"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "ethernet"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "expat"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "fatfs"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "freemodbus"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "freertos"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "heap"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "idf_test"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "jsmn"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "json"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "libsodium"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "log"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "mdns"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "lwip"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "mbedtls"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "mbedtls_port"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "mdns"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "micro-ecc"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "mqtt"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "newlib"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "nghttp"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "nvs_flash"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "openssl"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "spi_flash"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "protobuf-c"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "protocomm"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "pthread"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "sdmmc"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "smartconfig_ack"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "soc"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "spi_flash"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "spiffs"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "tcp_transport"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "tcpip_adapter"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "ulp"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "vfs"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "wear_levelling"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "xtensa-debug-module"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "coap"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "console"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "expat"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "json"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "lwip"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "newlib"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "nghttp"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "soc"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "wifi_provisioning"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "wpa_supplicant"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "xtensa-debug-module"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp-face"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp32-camera"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp-face"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "fb_gfx"), join(FRAMEWORK_DIR, "cores", env.BoardConfig().get("build.core")) ], + LIBPATH=[ join(FRAMEWORK_DIR, "tools", "sdk", "lib"), join(FRAMEWORK_DIR, "tools", "sdk", "ld") ], + LIBS=[ - "gcc", "openssl", "btdm_app", "fatfs", "wps", "coexist", "wear_levelling", "hal", "newlib", "driver", "bootloader_support", "pp", "mesh", "smartconfig", "jsmn", "wpa", "ethernet", "phy", "app_trace", "console", "ulp", "wpa_supplicant", "freertos", "bt", "micro-ecc", "cxx", "xtensa-debug-module", "mdns", "vfs", "soc", "core", "sdmmc", "coap", "tcpip_adapter", "c_nano", "rtc", "spi_flash", "wpa2", "esp32", "app_update", "nghttp", "spiffs", "espnow", "nvs_flash", "esp_adc_cal", "log", "expat", "m", "c", "heap", "mbedtls", "lwip", "net80211", "pthread", "json", "stdc++" + "-lgcc", "-lesp32", "-lphy", "-lesp_http_client", "-lmbedtls", "-lrtc", "-lesp_http_server", "-lbtdm_app", "-lspiffs", "-lbootloader_support", "-lmdns", "-lnvs_flash", "-lfatfs", "-lpp", "-lnet80211", "-ljsmn", "-lface_detection", "-llibsodium", "-lvfs", "-ldl_lib", "-llog", "-lfreertos", "-lcxx", "-lsmartconfig_ack", "-lxtensa-debug-module", "-lheap", "-ltcpip_adapter", "-lmqtt", "-lulp", "-lfd", "-lfb_gfx", "-lnghttp", "-lprotocomm", "-lsmartconfig", "-lm", "-lethernet", "-limage_util", "-lc_nano", "-lsoc", "-ltcp_transport", "-lc", "-lmicro-ecc", "-lface_recognition", "-ljson", "-lwpa_supplicant", "-lmesh", "-lesp_https_ota", "-lwpa2", "-lexpat", "-llwip", "-lwear_levelling", "-lapp_update", "-ldriver", "-lbt", "-lespnow", "-lcoap", "-lasio", "-lnewlib", "-lconsole", "-lapp_trace", "-lesp32-camera", "-lhal", "-lprotobuf-c", "-lsdmmc", "-lcore", "-lpthread", "-lcoexist", "-lfreemodbus", "-lspi_flash", "-lesp-tls", "-lwpa", "-lwifi_provisioning", "-lwps", "-lesp_adc_cal", "-lesp_event", "-lopenssl", "-lesp_ringbuf", "-lfr", "-lstdc++" ], - UPLOADERFLAGS=[ - "--before", "default_reset", - "--after", "hard_reset" - ] -) - - -def _get_board_flash_mode(env): - mode = env.subst("$BOARD_FLASH_MODE") - if mode == "qio": - return "dio" - elif mode == "qout": - return "dout" - return mode - - -env.Append( - __get_board_flash_mode=_get_board_flash_mode, - LIBSOURCE_DIRS=[ join(FRAMEWORK_DIR, "libraries") ], - LINKFLAGS=[ - "-Wl,-EL", - "-T", "esp32.common.ld", - "-T", "esp32.rom.ld", - "-T", "esp32.peripherals.ld", - "-T", "esp32.rom.spiram_incompatible_fns.ld", - "-u", "ld_include_panic_highint_hdl", - "-u", "__cxa_guard_dummy", - "-u", "__cxx_fatal_exception" - ], - - UPLOADERFLAGS=[ - "0x1000", join(FRAMEWORK_DIR, "tools", "sdk", "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"), - "0x10000" + FLASH_EXTRA_IMAGES=[ + ("0x1000", join(FRAMEWORK_DIR, "tools", "sdk", "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")) ] ) -if "$BOARD_FLASH_MODE" in env['UPLOADERFLAGS']: - env['UPLOADERFLAGS'][env['UPLOADERFLAGS'].index("$BOARD_FLASH_MODE")] = "${__get_board_flash_mode(__env__)}" - -env.Replace( - UPLOADER=join(FRAMEWORK_DIR, "tools", "esptool.py") -) - # # Target: Build Core Library # @@ -181,10 +209,17 @@ def _get_board_flash_mode(env): # # 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"), - join(FRAMEWORK_DIR, "tools", "partitions", - "%s.csv" % env.BoardConfig().get("build.partitions", "default")), + "$PARTITIONS_TABLE_CSV", env.VerboseAction('"$PYTHONEXE" "%s" -q $SOURCE $TARGET' % join( FRAMEWORK_DIR, "tools", "gen_esp32part.py"), "Generating partitions $TARGET")) diff --git a/tools/sdk/bin/bootloader_dio_40m.bin b/tools/sdk/bin/bootloader_dio_40m.bin index e01d6293d5b..ac057886d98 100644 Binary files a/tools/sdk/bin/bootloader_dio_40m.bin and b/tools/sdk/bin/bootloader_dio_40m.bin differ diff --git a/tools/sdk/bin/bootloader_dio_80m.bin b/tools/sdk/bin/bootloader_dio_80m.bin index 839f1cbf62b..726e1ca9145 100644 Binary files a/tools/sdk/bin/bootloader_dio_80m.bin and b/tools/sdk/bin/bootloader_dio_80m.bin differ diff --git a/tools/sdk/bin/bootloader_dout_40m.bin b/tools/sdk/bin/bootloader_dout_40m.bin index 36e77645903..eab1e96d1f5 100644 Binary files a/tools/sdk/bin/bootloader_dout_40m.bin and b/tools/sdk/bin/bootloader_dout_40m.bin differ diff --git a/tools/sdk/bin/bootloader_dout_80m.bin b/tools/sdk/bin/bootloader_dout_80m.bin index bb3935c0e70..4d1f69f44c1 100644 Binary files a/tools/sdk/bin/bootloader_dout_80m.bin and b/tools/sdk/bin/bootloader_dout_80m.bin differ diff --git a/tools/sdk/bin/bootloader_qio_40m.bin b/tools/sdk/bin/bootloader_qio_40m.bin index d9a082e1e5c..0c2e9fe279a 100644 Binary files a/tools/sdk/bin/bootloader_qio_40m.bin and b/tools/sdk/bin/bootloader_qio_40m.bin differ diff --git a/tools/sdk/bin/bootloader_qio_80m.bin b/tools/sdk/bin/bootloader_qio_80m.bin index 2fa85e2b49d..944f4947edf 100644 Binary files a/tools/sdk/bin/bootloader_qio_80m.bin and b/tools/sdk/bin/bootloader_qio_80m.bin differ diff --git a/tools/sdk/bin/bootloader_qout_40m.bin b/tools/sdk/bin/bootloader_qout_40m.bin index eb86753a055..07a6be715c0 100644 Binary files a/tools/sdk/bin/bootloader_qout_40m.bin and b/tools/sdk/bin/bootloader_qout_40m.bin differ diff --git a/tools/sdk/bin/bootloader_qout_80m.bin b/tools/sdk/bin/bootloader_qout_80m.bin index 2fa85e2b49d..8cfb0c2529e 100644 Binary files a/tools/sdk/bin/bootloader_qout_80m.bin and b/tools/sdk/bin/bootloader_qout_80m.bin differ diff --git a/tools/sdk/include/app_trace/esp_app_trace.h b/tools/sdk/include/app_trace/esp_app_trace.h new file mode 100644 index 00000000000..dbac4f475e3 --- /dev/null +++ b/tools/sdk/include/app_trace/esp_app_trace.h @@ -0,0 +1,265 @@ +// 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 + +/** + * 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(); + +/** + * @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 indefinetly. + * + * @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 indefinetly. + * + * @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 indefinetly. + * + * @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 indefinetly. + * @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 indefinetly. + * + * @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 indefinetly. + * + * @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 indefinetly. + * + * @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 Rertrieves 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 initializaed with requested value. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. + * + * @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 processesd. + * 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 indefinetly. + * + * @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); + +#endif diff --git a/tools/sdk/include/app_trace/esp_app_trace_util.h b/tools/sdk/include/app_trace/esp_app_trace_util.h new file mode 100644 index 00000000000..6376008c2f6 --- /dev/null +++ b/tools/sdk/include/app_trace/esp_app_trace_util.h @@ -0,0 +1,167 @@ +// 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_ + +#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); + +#endif //ESP_APP_TRACE_UTIL_H_ diff --git a/tools/sdk/include/app_trace/esp_ota_ops.h b/tools/sdk/include/app_trace/esp_ota_ops.h deleted file mode 100755 index a089a92be05..00000000000 --- a/tools/sdk/include/app_trace/esp_ota_ops.h +++ /dev/null @@ -1,178 +0,0 @@ -// 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_spi_flash.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -#define OTA_SIZE_UNKNOWN 0xffffffff /*!< Used for esp_ota_begin() if new image size is unknown */ - -#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 */ - -/** - * @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 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. - * - * @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_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 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 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_load(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); - -#ifdef __cplusplus -} -#endif - -#endif /* OTA_OPS_H */ diff --git a/tools/sdk/include/app_update/esp_ota_ops.h b/tools/sdk/include/app_update/esp_ota_ops.h old mode 100755 new mode 100644 index a089a92be05..ca77b54226e --- a/tools/sdk/include/app_update/esp_ota_ops.h +++ b/tools/sdk/include/app_update/esp_ota_ops.h @@ -20,7 +20,6 @@ #include #include "esp_err.h" #include "esp_partition.h" -#include "esp_spi_flash.h" #ifdef __cplusplus extern "C" @@ -133,7 +132,7 @@ esp_err_t esp_ota_set_boot_partition(const esp_partition_t* partition); * 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_load(ESP_IMAGE_VERIFY, ...) to verify if the + * 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. diff --git a/tools/sdk/include/asio/asio.hpp b/tools/sdk/include/asio/asio.hpp new file mode 100644 index 00000000000..6a58006b6ed --- /dev/null +++ b/tools/sdk/include/asio/asio.hpp @@ -0,0 +1,156 @@ +// +// asio.hpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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_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/completion_condition.hpp" +#include "asio/connect.hpp" +#include "asio/coroutine.hpp" +#include "asio/datagram_socket_service.hpp" +#include "asio/deadline_timer_service.hpp" +#include "asio/deadline_timer.hpp" +#include "asio/defer.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/handler_type.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/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/resolver_service.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/posix/stream_descriptor_service.hpp" +#include "asio/post.hpp" +#include "asio/raw_socket_service.hpp" +#include "asio/read.hpp" +#include "asio/read_at.hpp" +#include "asio/read_until.hpp" +#include "asio/seq_packet_socket_service.hpp" +#include "asio/serial_port.hpp" +#include "asio/serial_port_base.hpp" +#include "asio/serial_port_service.hpp" +#include "asio/signal_set.hpp" +#include "asio/signal_set_service.hpp" +#include "asio/socket_acceptor_service.hpp" +#include "asio/socket_base.hpp" +#include "asio/steady_timer.hpp" +#include "asio/strand.hpp" +#include "asio/stream_socket_service.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/thread.hpp" +#include "asio/thread_pool.hpp" +#include "asio/time_traits.hpp" +#include "asio/use_future.hpp" +#include "asio/uses_executor.hpp" +#include "asio/version.hpp" +#include "asio/wait_traits.hpp" +#include "asio/waitable_timer_service.hpp" +#include "asio/windows/basic_handle.hpp" +#include "asio/windows/basic_object_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/object_handle_service.hpp" +#include "asio/windows/overlapped_handle.hpp" +#include "asio/windows/overlapped_ptr.hpp" +#include "asio/windows/random_access_handle.hpp" +#include "asio/windows/random_access_handle_service.hpp" +#include "asio/windows/stream_handle.hpp" +#include "asio/windows/stream_handle_service.hpp" +#include "asio/write.hpp" +#include "asio/write_at.hpp" + +#endif // ASIO_HPP diff --git a/tools/sdk/include/asio/asio/associated_allocator.hpp b/tools/sdk/include/asio/asio/associated_allocator.hpp new file mode 100644 index 00000000000..8b488bb344e --- /dev/null +++ b/tools/sdk/include/asio/asio/associated_allocator.hpp @@ -0,0 +1,131 @@ +// +// associated_allocator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/associated_executor.hpp b/tools/sdk/include/asio/asio/associated_executor.hpp new file mode 100644 index 00000000000..4c5c2078848 --- /dev/null +++ b/tools/sdk/include/asio/asio/associated_executor.hpp @@ -0,0 +1,149 @@ +// +// associated_executor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/async_result.hpp b/tools/sdk/include/asio/asio/async_result.hpp new file mode 100644 index 00000000000..18acdf20a20 --- /dev/null +++ b/tools/sdk/include/asio/asio/async_result.hpp @@ -0,0 +1,221 @@ +// +// async_result.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/handler_type.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// 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. + */ +#if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) +template +#else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) +template +#endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) +class async_result +{ +public: +#if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + /// 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; +#else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + // For backward compatibility, determine the concrete completion handler type + // by using the legacy handler_type trait. + typedef typename handler_type::type + completion_handler_type; + + // For backward compatibility, determine the initiating function return type + // using the legacy single-parameter version of async_result. + typedef typename async_result::type return_type; +#endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + + /// 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) +#if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + // No data members to initialise. +#else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + : legacy_result_(h) +#endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + { + (void)h; + } + + /// Obtain the value to be returned from the initiating function. + return_type get() + { +#if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + // Nothing to do. +#else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + return legacy_result_.get(); +#endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + } + +private: + async_result(const async_result&) ASIO_DELETED; + async_result& operator=(const async_result&) ASIO_DELETED; + +#if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + // No data members. +#else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + async_result legacy_result_; +#endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) +}; + +#if !defined(ASIO_NO_DEPRECATED) + +/// (Deprecated: Use two-parameter version of async_result.) An interface for +/// customising the behaviour of an initiating function. +/** + * This template may be specialised for user-defined handler types. + */ +template +class async_result +{ +public: + /// The return type of the initiating function. + typedef void 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 handler, which is then + * returned from the initiating function. + */ + explicit async_result(Handler&) + { + } + + /// Obtain the value to be returned from the initiating function. + type get() + { + } +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +/// 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> +{ +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#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 + +#endif // ASIO_ASYNC_RESULT_HPP diff --git a/tools/sdk/include/asio/asio/basic_datagram_socket.hpp b/tools/sdk/include/asio/asio/basic_datagram_socket.hpp new file mode 100644 index 00000000000..346cc353f5f --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_datagram_socket.hpp @@ -0,0 +1,1040 @@ +// +// basic_datagram_socket.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/datagram_socket_service.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// 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 native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename basic_socket< + Protocol ASIO_SVC_TARG>::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 io_context The io_context object that the datagram socket will use + * to dispatch handlers for any asynchronous operations performed on the + * socket. + */ + explicit basic_datagram_socket(asio::io_context& io_context) + : basic_socket(io_context) + { + } + + /// Construct and open a basic_datagram_socket. + /** + * This constructor creates and opens a datagram socket. + * + * @param io_context The io_context object that the datagram socket will use + * 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(asio::io_context& io_context, + const protocol_type& protocol) + : basic_socket(io_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 io_context The io_context object that the datagram socket will use + * 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(asio::io_context& io_context, + const endpoint_type& endpoint) + : basic_socket(io_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 io_context The io_context object that the datagram socket will use + * 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(asio::io_context& io_context, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_socket( + io_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(io_context&) constructor. + */ + basic_datagram_socket(basic_datagram_socket&& other) + : 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(io_context&) 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(io_context&) constructor. + */ + template + basic_datagram_socket( + basic_datagram_socket&& other, + typename enable_if::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(io_context&) constructor. + */ + template + typename enable_if::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->get_service().send( + this->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->get_service().send( + this->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->get_service().send( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send(this->get_implementation(), + buffers, 0, ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send(this->get_implementation(), + buffers, 0, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send(this->get_implementation(), + buffers, flags, ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send(this->get_implementation(), + buffers, flags, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().send_to( + this->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->get_service().send_to( + this->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->get_service().send_to(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send_to( + this->get_implementation(), buffers, destination, 0, + ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send_to( + this->get_implementation(), buffers, destination, 0, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send_to( + this->get_implementation(), buffers, destination, flags, + ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send_to( + this->get_implementation(), buffers, destination, flags, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().receive( + this->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->get_service().receive( + this->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->get_service().receive( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive(this->get_implementation(), + buffers, 0, ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive(this->get_implementation(), + buffers, 0, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive(this->get_implementation(), + buffers, flags, ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive(this->get_implementation(), + buffers, flags, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().receive_from( + this->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->get_service().receive_from( + this->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->get_service().receive_from(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive_from( + this->get_implementation(), buffers, sender_endpoint, 0, + ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive_from( + this->get_implementation(), buffers, sender_endpoint, 0, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive_from( + this->get_implementation(), buffers, sender_endpoint, flags, + ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive_from( + this->get_implementation(), buffers, sender_endpoint, flags, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_DATAGRAM_SOCKET_HPP diff --git a/tools/sdk/include/asio/asio/basic_deadline_timer.hpp b/tools/sdk/include/asio/asio/basic_deadline_timer.hpp new file mode 100644 index 00000000000..5b20066dff7 --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_deadline_timer.hpp @@ -0,0 +1,628 @@ +// +// basic_deadline_timer.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/time_traits.hpp" + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/deadline_timer_service.hpp" +#else // defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/detail/deadline_timer_service.hpp" +# define ASIO_SVC_T detail::deadline_timer_service +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#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(io_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(io_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 + ASIO_SVC_TPARAM_DEF2(= deadline_timer_service)> +class basic_deadline_timer + : ASIO_SVC_ACCESS basic_io_object +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// 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 io_context The io_context object that the timer will use to dispatch + * handlers for any asynchronous operations performed on the timer. + */ + explicit basic_deadline_timer(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Constructor to set a particular expiry time as an absolute time. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param io_context The io_context object that the timer will use 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(asio::io_context& io_context, + const time_type& expiry_time) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().expires_at(this->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 io_context The io_context object that the timer will use 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(asio::io_context& io_context, + const duration_type& expiry_time) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().expires_from_now( + this->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(io_context&) constructor. + */ + basic_deadline_timer(basic_deadline_timer&& other) + : basic_io_object(std::move(other)) + { + } + + /// 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(io_context&) constructor. + */ + basic_deadline_timer& operator=(basic_deadline_timer&& other) + { + basic_io_object::operator=(std::move(other)); + 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() + { + } + +#if defined(ASIO_ENABLE_OLD_SERVICES) + // These functions are provided by basic_io_object<>. +#else // defined(ASIO_ENABLE_OLD_SERVICES) +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::get_executor(); + } +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + + /// 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 = this->get_service().cancel(this->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 this->get_service().cancel(this->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 = this->get_service().cancel_one( + this->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 this->get_service().cancel_one(this->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 this->get_service().expires_at(this->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 = this->get_service().expires_at( + this->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 this->get_service().expires_at( + this->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 this->get_service().expires_from_now(this->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 = this->get_service().expires_from_now( + this->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 this->get_service().expires_from_now( + this->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; + this->get_service().wait(this->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) + { + this->get_service().wait(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(ASIO_MOVE_ARG(WaitHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_wait(this->get_implementation(), + ASIO_MOVE_CAST(WaitHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_wait(this->get_implementation(), + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if !defined(ASIO_ENABLE_OLD_SERVICES) +# undef ASIO_SVC_T +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_BASIC_DEADLINE_TIMER_HPP diff --git a/tools/sdk/include/asio/asio/basic_io_object.hpp b/tools/sdk/include/asio/asio/basic_io_object.hpp new file mode 100644 index 00000000000..442e85429dc --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_io_object.hpp @@ -0,0 +1,290 @@ +// +// basic_io_object.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/basic_raw_socket.hpp b/tools/sdk/include/asio/asio/basic_raw_socket.hpp new file mode 100644 index 00000000000..0de7c776618 --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_raw_socket.hpp @@ -0,0 +1,1030 @@ +// +// basic_raw_socket.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/raw_socket_service.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// 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 native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename basic_socket< + Protocol ASIO_SVC_TARG>::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 io_context The io_context object that the raw socket will use + * to dispatch handlers for any asynchronous operations performed on the + * socket. + */ + explicit basic_raw_socket(asio::io_context& io_context) + : basic_socket(io_context) + { + } + + /// Construct and open a basic_raw_socket. + /** + * This constructor creates and opens a raw socket. + * + * @param io_context The io_context object that the raw socket will use + * 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(asio::io_context& io_context, + const protocol_type& protocol) + : basic_socket(io_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 io_context The io_context object that the raw socket will use + * 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(asio::io_context& io_context, + const endpoint_type& endpoint) + : basic_socket(io_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 io_context The io_context object that the raw socket will use + * 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(asio::io_context& io_context, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_socket( + io_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(io_context&) constructor. + */ + basic_raw_socket(basic_raw_socket&& other) + : 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(io_context&) 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(io_context&) constructor. + */ + template + basic_raw_socket(basic_raw_socket&& other, + typename enable_if::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(io_context&) constructor. + */ + template + typename enable_if::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->get_service().send( + this->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->get_service().send( + this->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->get_service().send( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send(this->get_implementation(), + buffers, 0, ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send(this->get_implementation(), + buffers, 0, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send(this->get_implementation(), + buffers, flags, ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send(this->get_implementation(), + buffers, flags, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().send_to( + this->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->get_service().send_to( + this->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->get_service().send_to(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send_to(this->get_implementation(), + buffers, destination, 0, ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send_to(this->get_implementation(), + buffers, destination, 0, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send_to( + this->get_implementation(), buffers, destination, flags, + ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send_to( + this->get_implementation(), buffers, destination, flags, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().receive( + this->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->get_service().receive( + this->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->get_service().receive( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive(this->get_implementation(), + buffers, 0, ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive(this->get_implementation(), + buffers, 0, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive(this->get_implementation(), + buffers, flags, ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive(this->get_implementation(), + buffers, flags, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().receive_from( + this->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->get_service().receive_from( + this->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->get_service().receive_from(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive_from( + this->get_implementation(), buffers, sender_endpoint, 0, + ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive_from( + this->get_implementation(), buffers, sender_endpoint, 0, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive_from( + this->get_implementation(), buffers, sender_endpoint, flags, + ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive_from( + this->get_implementation(), buffers, sender_endpoint, flags, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_RAW_SOCKET_HPP diff --git a/tools/sdk/include/asio/asio/basic_seq_packet_socket.hpp b/tools/sdk/include/asio/asio/basic_seq_packet_socket.hpp new file mode 100644 index 00000000000..3655d881cc3 --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_seq_packet_socket.hpp @@ -0,0 +1,618 @@ +// +// basic_seq_packet_socket.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/seq_packet_socket_service.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// 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 native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename basic_socket< + Protocol ASIO_SVC_TARG>::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 io_context The io_context object that the sequenced packet socket + * will use to dispatch handlers for any asynchronous operations performed on + * the socket. + */ + explicit basic_seq_packet_socket(asio::io_context& io_context) + : basic_socket(io_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 io_context The io_context object that the sequenced packet socket + * will use 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(asio::io_context& io_context, + const protocol_type& protocol) + : basic_socket(io_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 io_context The io_context object that the sequenced packet socket + * will use 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(asio::io_context& io_context, + const endpoint_type& endpoint) + : basic_socket(io_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 io_context The io_context object that the sequenced packet socket + * will use 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(asio::io_context& io_context, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_socket( + io_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(io_context&) constructor. + */ + basic_seq_packet_socket(basic_seq_packet_socket&& other) + : 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(io_context&) 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(io_context&) constructor. + */ + template + basic_seq_packet_socket( + basic_seq_packet_socket&& other, + typename enable_if::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(io_context&) constructor. + */ + template + typename enable_if::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->get_service().send( + this->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->get_service().send( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send(this->get_implementation(), + buffers, flags, ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send(this->get_implementation(), + buffers, flags, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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; +#if defined(ASIO_ENABLE_OLD_SERVICES) + std::size_t s = this->get_service().receive( + this->get_implementation(), buffers, 0, out_flags, ec); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + std::size_t s = this->get_service().receive_with_flags( + this->get_implementation(), buffers, 0, out_flags, ec); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + 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; +#if defined(ASIO_ENABLE_OLD_SERVICES) + std::size_t s = this->get_service().receive( + this->get_implementation(), buffers, in_flags, out_flags, ec); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + std::size_t s = this->get_service().receive_with_flags( + this->get_implementation(), buffers, in_flags, out_flags, ec); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + 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) + { +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().receive(this->get_implementation(), + buffers, in_flags, out_flags, ec); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().receive_with_flags(this->get_implementation(), + buffers, in_flags, out_flags, ec); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive( + this->get_implementation(), buffers, 0, out_flags, + ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive_with_flags( + this->get_implementation(), buffers, 0, out_flags, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive( + this->get_implementation(), buffers, in_flags, out_flags, + ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive_with_flags( + this->get_implementation(), buffers, in_flags, out_flags, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_SEQ_PACKET_SOCKET_HPP diff --git a/tools/sdk/include/asio/asio/basic_serial_port.hpp b/tools/sdk/include/asio/asio/basic_serial_port.hpp new file mode 100644 index 00000000000..32262f84295 --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_serial_port.hpp @@ -0,0 +1,688 @@ +// +// basic_serial_port.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_SERIAL_PORT) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/serial_port_base.hpp" +#include "asio/serial_port_service.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Provides serial port functionality. +/** + * The basic_serial_port class template provides functionality that is common + * to all serial ports. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_serial_port + : public basic_io_object, + public serial_port_base +{ +public: + /// The native representation of a serial port. + typedef typename SerialPortService::native_handle_type native_handle_type; + + /// A 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 io_context The io_context object that the serial port will use to + * dispatch handlers for any asynchronous operations performed on the port. + */ + explicit basic_serial_port(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct and open a basic_serial_port. + /** + * This constructor creates and opens a serial port for the specified device + * name. + * + * @param io_context The io_context object that the serial port will use to + * dispatch handlers for any asynchronous operations performed on the port. + * + * @param device The platform-specific device name for this serial + * port. + */ + explicit basic_serial_port(asio::io_context& io_context, + const char* device) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().open(this->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 io_context The io_context object that the serial port will use to + * dispatch handlers for any asynchronous operations performed on the port. + * + * @param device The platform-specific device name for this serial + * port. + */ + explicit basic_serial_port(asio::io_context& io_context, + const std::string& device) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().open(this->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 io_context The io_context object that the serial port will use to + * dispatch handlers for any asynchronous operations performed on the port. + * + * @param native_serial_port A native serial port. + * + * @throws asio::system_error Thrown on failure. + */ + basic_serial_port(asio::io_context& io_context, + const native_handle_type& native_serial_port) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->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(io_context&) constructor. + */ + basic_serial_port(basic_serial_port&& other) + : basic_io_object( + ASIO_MOVE_CAST(basic_serial_port)(other)) + { + } + + /// 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(io_context&) constructor. + */ + basic_serial_port& operator=(basic_serial_port&& other) + { + basic_io_object::operator=( + ASIO_MOVE_CAST(basic_serial_port)(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// 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; + this->get_service().open(this->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) + { + this->get_service().open(this->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; + this->get_service().assign(this->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) + { + this->get_service().assign(this->get_implementation(), + native_serial_port, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the serial port is open. + bool is_open() const + { + return this->get_service().is_open(this->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; + this->get_service().close(this->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) + { + this->get_service().close(this->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 this->get_service().native_handle(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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; + this->get_service().send_break(this->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) + { + this->get_service().send_break(this->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; + this->get_service().set_option(this->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) + { + this->get_service().set_option(this->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) + { + asio::error_code ec; + this->get_service().get_option(this->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) + { + this->get_service().get_option(this->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 + * 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 = this->get_service().write_some( + this->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 this->get_service().write_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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 + * 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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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; + + return this->get_service().async_write_some(this->get_implementation(), + buffers, ASIO_MOVE_CAST(WriteHandler)(handler)); + } + + /// 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 + * 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 = this->get_service().read_some( + this->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 this->get_service().read_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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 + * 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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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 this->get_service().async_read_some(this->get_implementation(), + buffers, ASIO_MOVE_CAST(ReadHandler)(handler)); + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_SERIAL_PORT) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_BASIC_SERIAL_PORT_HPP diff --git a/tools/sdk/include/asio/asio/basic_signal_set.hpp b/tools/sdk/include/asio/asio/basic_signal_set.hpp new file mode 100644 index 00000000000..cf34643f8f3 --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_signal_set.hpp @@ -0,0 +1,391 @@ +// +// basic_signal_set.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" + +#if defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/signal_set_service.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Provides signal functionality. +/** + * The basic_signal_set class template provides the ability to perform an + * asynchronous wait for one or more signals to occur. + * + * Most applications will use the asio::signal_set typedef. + * + * @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(io_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 basic_io_object +{ +public: + /// Construct a signal set without adding any signals. + /** + * This constructor creates a signal set without registering for any signals. + * + * @param io_context The io_context object that the signal set will use to + * dispatch handlers for any asynchronous operations performed on the set. + */ + explicit basic_signal_set(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct a signal set and add one signal. + /** + * This constructor creates a signal set and registers for one signal. + * + * @param io_context The io_context object that the signal set will use to + * dispatch handlers for any asynchronous operations performed on the set. + * + * @param signal_number_1 The signal number to be added. + * + * @note This constructor is equivalent to performing: + * @code asio::signal_set signals(io_context); + * signals.add(signal_number_1); @endcode + */ + basic_signal_set(asio::io_context& io_context, int signal_number_1) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().add(this->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 io_context The io_context object that the signal set will use to + * dispatch handlers for any asynchronous operations performed on the 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(io_context); + * signals.add(signal_number_1); + * signals.add(signal_number_2); @endcode + */ + basic_signal_set(asio::io_context& io_context, int signal_number_1, + int signal_number_2) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().add(this->get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + this->get_service().add(this->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 io_context The io_context object that the signal set will use to + * dispatch handlers for any asynchronous operations performed on the 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(io_context); + * signals.add(signal_number_1); + * signals.add(signal_number_2); + * signals.add(signal_number_3); @endcode + */ + basic_signal_set(asio::io_context& io_context, int signal_number_1, + int signal_number_2, int signal_number_3) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().add(this->get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + this->get_service().add(this->get_implementation(), signal_number_2, ec); + asio::detail::throw_error(ec, "add"); + this->get_service().add(this->get_implementation(), signal_number_3, 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. + * + * @throws asio::system_error Thrown on failure. + */ + void add(int signal_number) + { + asio::error_code ec; + this->get_service().add(this->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) + { + this->get_service().add(this->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; + this->get_service().remove(this->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) + { + this->get_service().remove(this->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; + this->get_service().clear(this->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) + { + this->get_service().clear(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_RESULT_TYPE(SignalHandler, + void (asio::error_code, int)) + async_wait(ASIO_MOVE_ARG(SignalHandler) handler) + { + // 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; + + return this->get_service().async_wait(this->get_implementation(), + ASIO_MOVE_CAST(SignalHandler)(handler)); + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_BASIC_SIGNAL_SET_HPP diff --git a/tools/sdk/include/asio/asio/basic_socket.hpp b/tools/sdk/include/asio/asio/basic_socket.hpp new file mode 100644 index 00000000000..3dfacb42496 --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_socket.hpp @@ -0,0 +1,1757 @@ +// +// basic_socket.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/post.hpp" +#include "asio/socket_base.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#if !defined(ASIO_ENABLE_OLD_SERVICES) +# if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/winrt_ssocket_service.hpp" +# define ASIO_SVC_T detail::winrt_ssocket_service +# elif defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_socket_service.hpp" +# define ASIO_SVC_T detail::win_iocp_socket_service +# else +# include "asio/detail/reactive_socket_service.hpp" +# define ASIO_SVC_T detail::reactive_socket_service +# endif +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// 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 + : ASIO_SVC_ACCESS basic_io_object, + public socket_base +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// The native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename ASIO_SVC_T::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 io_context The io_context object that the socket will use to + * dispatch handlers for any asynchronous operations performed on the socket. + */ + explicit basic_socket(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct and open a basic_socket. + /** + * This constructor creates and opens a socket. + * + * @param io_context The io_context object that the socket will use 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(asio::io_context& io_context, + const protocol_type& protocol) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().open(this->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 io_context The io_context object that the socket will use 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(asio::io_context& io_context, + const endpoint_type& endpoint) + : basic_io_object(io_context) + { + asio::error_code ec; + const protocol_type protocol = endpoint.protocol(); + this->get_service().open(this->get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + this->get_service().bind(this->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 io_context The io_context object that the socket will use 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(asio::io_context& io_context, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->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(io_context&) constructor. + */ + basic_socket(basic_socket&& other) + : basic_io_object(std::move(other)) + { + } + + /// 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(io_context&) constructor. + */ + basic_socket& operator=(basic_socket&& other) + { + basic_io_object::operator=(std::move(other)); + 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(io_context&) constructor. + */ + template + basic_socket(basic_socket&& other, + typename enable_if::value>::type* = 0) + : basic_io_object( + other.get_service(), other.get_implementation()) + { + } + + /// 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(io_context&) constructor. + */ + template + typename enable_if::value, + basic_socket>::type& operator=( + basic_socket&& other) + { + basic_socket tmp(std::move(other)); + basic_io_object::operator=(std::move(tmp)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + +#if defined(ASIO_ENABLE_OLD_SERVICES) + // These functions are provided by basic_io_object<>. +#else // defined(ASIO_ENABLE_OLD_SERVICES) +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::get_executor(); + } +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#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(io_context); + * socket.open(asio::ip::tcp::v4()); + * @endcode + */ + void open(const protocol_type& protocol = protocol_type()) + { + asio::error_code ec; + this->get_service().open(this->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(io_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) + { + this->get_service().open(this->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; + this->get_service().assign(this->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) + { + this->get_service().assign(this->get_implementation(), + protocol, native_socket, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is open. + bool is_open() const + { + return this->get_service().is_open(this->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; + this->get_service().close(this->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(io_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) + { + this->get_service().close(this->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 = this->get_service().release( + this->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 this->get_service().release(this->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 this->get_service().native_handle(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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 = this->get_service().at_mark(this->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 this->get_service().at_mark(this->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 = this->get_service().available( + this->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 this->get_service().available(this->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(io_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; + this->get_service().bind(this->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(io_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) + { + this->get_service().bind(this->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(io_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()) + { + this->get_service().open(this->get_implementation(), + peer_endpoint.protocol(), ec); + asio::detail::throw_error(ec, "connect"); + } + this->get_service().connect(this->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(io_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()) + { + this->get_service().open(this->get_implementation(), + peer_endpoint.protocol(), ec); + if (ec) + { + ASIO_SYNC_OP_VOID_RETURN(ec); + } + } + + this->get_service().connect(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @par Example + * @code + * void connect_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Connect succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::socket socket(io_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_INITFN_RESULT_TYPE(ConnectHandler, + void (asio::error_code)) + async_connect(const endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(ConnectHandler) handler) + { + // 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 (!is_open()) + { + asio::error_code ec; + const protocol_type protocol = peer_endpoint.protocol(); + this->get_service().open(this->get_implementation(), protocol, ec); + if (ec) + { + async_completion init(handler); + + asio::post(this->get_executor(), + asio::detail::bind_handler( + ASIO_MOVE_CAST(ASIO_HANDLER_TYPE( + ConnectHandler, void (asio::error_code)))( + init.completion_handler), ec)); + + return init.result.get(); + } + } + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_connect(this->get_implementation(), + peer_endpoint, ASIO_MOVE_CAST(ConnectHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_connect( + this->get_implementation(), peer_endpoint, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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(io_context); + * ... + * asio::ip::tcp::no_delay option(true); + * socket.set_option(option); + * @endcode + */ + template + void set_option(const SettableSocketOption& option) + { + asio::error_code ec; + this->get_service().set_option(this->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(io_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) + { + this->get_service().set_option(this->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(io_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; + this->get_service().get_option(this->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(io_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 + { + this->get_service().get_option(this->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(io_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; + this->get_service().io_control(this->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(io_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) + { + this->get_service().io_control(this->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 this->get_service().non_blocking(this->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; + this->get_service().non_blocking(this->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) + { + this->get_service().non_blocking(this->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 this->get_service().native_non_blocking(this->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; + this->get_service().native_non_blocking( + this->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) + { + this->get_service().native_non_blocking( + this->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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint = socket.local_endpoint(); + * @endcode + */ + endpoint_type local_endpoint() const + { + asio::error_code ec; + endpoint_type ep = this->get_service().local_endpoint( + this->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(io_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 this->get_service().local_endpoint(this->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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(); + * @endcode + */ + endpoint_type remote_endpoint() const + { + asio::error_code ec; + endpoint_type ep = this->get_service().remote_endpoint( + this->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(io_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 this->get_service().remote_endpoint(this->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(io_context); + * ... + * socket.shutdown(asio::ip::tcp::socket::shutdown_send); + * @endcode + */ + void shutdown(shutdown_type what) + { + asio::error_code ec; + this->get_service().shutdown(this->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(io_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) + { + this->get_service().shutdown(this->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(io_context); + * ... + * socket.wait(asio::ip::tcp::socket::wait_read); + * @endcode + */ + void wait(wait_type w) + { + asio::error_code ec; + this->get_service().wait(this->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(io_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) + { + this->get_service().wait(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @par Example + * @code + * void wait_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Wait succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::socket socket(io_context); + * ... + * socket.async_wait(asio::ip::tcp::socket::wait_read, wait_handler); + * @endcode + */ + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(wait_type w, ASIO_MOVE_ARG(WaitHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_wait(this->get_implementation(), + w, ASIO_MOVE_CAST(WaitHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_wait(this->get_implementation(), + w, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + +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() + { + } + +private: + // Disallow copying and assignment. + basic_socket(const basic_socket&) ASIO_DELETED; + basic_socket& operator=(const basic_socket&) ASIO_DELETED; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if !defined(ASIO_ENABLE_OLD_SERVICES) +# undef ASIO_SVC_T +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_BASIC_SOCKET_HPP diff --git a/tools/sdk/include/asio/asio/basic_socket_acceptor.hpp b/tools/sdk/include/asio/asio/basic_socket_acceptor.hpp new file mode 100644 index 00000000000..ed201bbcaec --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_socket_acceptor.hpp @@ -0,0 +1,1986 @@ +// +// basic_socket_acceptor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_io_object.hpp" +#include "asio/basic_socket.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/socket_base.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/socket_acceptor_service.hpp" +#else // defined(ASIO_ENABLE_OLD_SERVICES) +# if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/null_socket_service.hpp" +# define ASIO_SVC_T detail::null_socket_service +# elif defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_socket_service.hpp" +# define ASIO_SVC_T detail::win_iocp_socket_service +# else +# include "asio/detail/reactive_socket_service.hpp" +# define ASIO_SVC_T detail::reactive_socket_service +# endif +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// 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(io_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 + : ASIO_SVC_ACCESS basic_io_object, + public socket_base +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// The native representation of an acceptor. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename ASIO_SVC_T::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 io_context The io_context object that the acceptor will use to + * dispatch handlers for any asynchronous operations performed on the + * acceptor. + */ + explicit basic_socket_acceptor(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct an open acceptor. + /** + * This constructor creates an acceptor and automatically opens it. + * + * @param io_context The io_context object that the acceptor will use 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(asio::io_context& io_context, + const protocol_type& protocol) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().open(this->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 io_context The io_context object that the acceptor will use 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(io_context); + * acceptor.open(endpoint.protocol()); + * if (reuse_addr) + * acceptor.set_option(socket_base::reuse_address(true)); + * acceptor.bind(endpoint); + * acceptor.listen(listen_backlog); + * @endcode + */ + basic_socket_acceptor(asio::io_context& io_context, + const endpoint_type& endpoint, bool reuse_addr = true) + : basic_io_object(io_context) + { + asio::error_code ec; + const protocol_type protocol = endpoint.protocol(); + this->get_service().open(this->get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + if (reuse_addr) + { + this->get_service().set_option(this->get_implementation(), + socket_base::reuse_address(true), ec); + asio::detail::throw_error(ec, "set_option"); + } + this->get_service().bind(this->get_implementation(), endpoint, ec); + asio::detail::throw_error(ec, "bind"); + this->get_service().listen(this->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 io_context The io_context object that the acceptor will use 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(asio::io_context& io_context, + const protocol_type& protocol, const native_handle_type& native_acceptor) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->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(io_context&) constructor. + */ + basic_socket_acceptor(basic_socket_acceptor&& other) + : basic_io_object(std::move(other)) + { + } + + /// 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(io_context&) constructor. + */ + basic_socket_acceptor& operator=(basic_socket_acceptor&& other) + { + basic_io_object::operator=(std::move(other)); + 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(io_context&) constructor. + */ + template + basic_socket_acceptor( + basic_socket_acceptor&& other, + typename enable_if::value>::type* = 0) + : basic_io_object( + other.get_service(), other.get_implementation()) + { + } + + /// 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(io_context&) constructor. + */ + template + typename enable_if::value, + basic_socket_acceptor>::type& operator=( + basic_socket_acceptor&& other) + { + basic_socket_acceptor tmp(std::move(other)); + basic_io_object::operator=(std::move(tmp)); + 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() + { + } + +#if defined(ASIO_ENABLE_OLD_SERVICES) + // These functions are provided by basic_io_object<>. +#else // defined(ASIO_ENABLE_OLD_SERVICES) +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::get_executor(); + } +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + + /// 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(io_context); + * acceptor.open(asio::ip::tcp::v4()); + * @endcode + */ + void open(const protocol_type& protocol = protocol_type()) + { + asio::error_code ec; + this->get_service().open(this->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(io_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) + { + this->get_service().open(this->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; + this->get_service().assign(this->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) + { + this->get_service().assign(this->get_implementation(), + protocol, native_acceptor, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the acceptor is open. + bool is_open() const + { + return this->get_service().is_open(this->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(io_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; + this->get_service().bind(this->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(io_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) + { + this->get_service().bind(this->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; + this->get_service().listen(this->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(io_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) + { + this->get_service().listen(this->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; + this->get_service().close(this->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(io_context); + * ... + * asio::error_code ec; + * acceptor.close(ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + this->get_service().close(this->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 = this->get_service().release( + this->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 this->get_service().release(this->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 this->get_service().native_handle(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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(io_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; + this->get_service().set_option(this->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(io_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) + { + this->get_service().set_option(this->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(io_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; + this->get_service().get_option(this->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(io_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 + { + this->get_service().get_option(this->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(io_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; + this->get_service().io_control(this->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(io_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) + { + this->get_service().io_control(this->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 this->get_service().non_blocking(this->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; + this->get_service().non_blocking(this->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) + { + this->get_service().non_blocking(this->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 this->get_service().native_non_blocking(this->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; + this->get_service().native_non_blocking( + this->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) + { + this->get_service().native_non_blocking( + this->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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint(); + * @endcode + */ + endpoint_type local_endpoint() const + { + asio::error_code ec; + endpoint_type ep = this->get_service().local_endpoint( + this->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(io_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 this->get_service().local_endpoint(this->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(io_context); + * ... + * acceptor.wait(asio::ip::tcp::acceptor::wait_read); + * @endcode + */ + void wait(wait_type w) + { + asio::error_code ec; + this->get_service().wait(this->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(io_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) + { + this->get_service().wait(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @par Example + * @code + * void wait_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Wait succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(io_context); + * ... + * acceptor.async_wait( + * asio::ip::tcp::acceptor::wait_read, + * wait_handler); + * @endcode + */ + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(wait_type w, ASIO_MOVE_ARG(WaitHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_wait(this->get_implementation(), + w, ASIO_MOVE_CAST(WaitHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_wait(this->get_implementation(), + w, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + +#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(io_context); + * ... + * asio::ip::tcp::socket socket(io_context); + * acceptor.accept(socket); + * @endcode + */ +#if defined(ASIO_ENABLE_OLD_SERVICES) + template + void accept(basic_socket& peer, + typename enable_if::value>::type* = 0) +#else // defined(ASIO_ENABLE_OLD_SERVICES) + template + void accept(basic_socket& peer, + typename enable_if::value>::type* = 0) +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + { + asio::error_code ec; + this->get_service().accept(this->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(io_context); + * ... + * asio::ip::tcp::socket socket(io_context); + * asio::error_code ec; + * acceptor.accept(socket, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ +#if defined(ASIO_ENABLE_OLD_SERVICES) + template + ASIO_SYNC_OP_VOID accept( + basic_socket& peer, + asio::error_code& ec, + typename enable_if::value>::type* = 0) +#else // defined(ASIO_ENABLE_OLD_SERVICES) + template + ASIO_SYNC_OP_VOID accept( + basic_socket& peer, asio::error_code& ec, + typename enable_if::value>::type* = 0) +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + { + this->get_service().accept(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @par Example + * @code + * void accept_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Accept succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(io_context); + * ... + * asio::ip::tcp::socket socket(io_context); + * acceptor.async_accept(socket, accept_handler); + * @endcode + */ +#if defined(ASIO_ENABLE_OLD_SERVICES) + template + ASIO_INITFN_RESULT_TYPE(AcceptHandler, + void (asio::error_code)) + async_accept(basic_socket& peer, + ASIO_MOVE_ARG(AcceptHandler) handler, + typename enable_if::value>::type* = 0) +#else // defined(ASIO_ENABLE_OLD_SERVICES) + template + ASIO_INITFN_RESULT_TYPE(AcceptHandler, + void (asio::error_code)) + async_accept(basic_socket& peer, + ASIO_MOVE_ARG(AcceptHandler) handler, + typename enable_if::value>::type* = 0) +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_accept(this->get_implementation(), + peer, static_cast(0), + ASIO_MOVE_CAST(AcceptHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_accept(this->get_implementation(), + peer, static_cast(0), init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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(io_context); + * ... + * asio::ip::tcp::socket socket(io_context); + * asio::ip::tcp::endpoint endpoint; + * acceptor.accept(socket, endpoint); + * @endcode + */ +#if defined(ASIO_ENABLE_OLD_SERVICES) + template + void accept(basic_socket& peer, + endpoint_type& peer_endpoint) +#else // defined(ASIO_ENABLE_OLD_SERVICES) + void accept(basic_socket& peer, endpoint_type& peer_endpoint) +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + { + asio::error_code ec; + this->get_service().accept(this->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(io_context); + * ... + * asio::ip::tcp::socket socket(io_context); + * asio::ip::tcp::endpoint endpoint; + * asio::error_code ec; + * acceptor.accept(socket, endpoint, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ +#if defined(ASIO_ENABLE_OLD_SERVICES) + template + ASIO_SYNC_OP_VOID accept( + basic_socket& peer, + endpoint_type& peer_endpoint, asio::error_code& ec) +#else // defined(ASIO_ENABLE_OLD_SERVICES) + ASIO_SYNC_OP_VOID accept(basic_socket& peer, + endpoint_type& peer_endpoint, asio::error_code& ec) +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + { + this->get_service().accept( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +#if defined(ASIO_ENABLE_OLD_SERVICES) + template + ASIO_INITFN_RESULT_TYPE(AcceptHandler, + void (asio::error_code)) + async_accept(basic_socket& peer, + endpoint_type& peer_endpoint, ASIO_MOVE_ARG(AcceptHandler) handler) +#else // defined(ASIO_ENABLE_OLD_SERVICES) + template + ASIO_INITFN_RESULT_TYPE(AcceptHandler, + void (asio::error_code)) + async_accept(basic_socket& peer, + endpoint_type& peer_endpoint, ASIO_MOVE_ARG(AcceptHandler) handler) +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_accept(this->get_implementation(), peer, + &peer_endpoint, ASIO_MOVE_CAST(AcceptHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_accept(this->get_implementation(), + peer, &peer_endpoint, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +#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(io_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept()); + * @endcode + */ + typename Protocol::socket accept() + { + asio::error_code ec; + typename Protocol::socket peer( + this->get_service().accept( + this->get_implementation(), 0, 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(io_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept(ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + typename Protocol::socket accept(asio::error_code& ec) + { + return this->get_service().accept(this->get_implementation(), 0, 0, ec); + } + + /// 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( + * const asio::error_code& error, // Result of operation. + * typename Protocol::socket 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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(io_context); + * ... + * acceptor.async_accept(accept_handler); + * @endcode + */ + template + ASIO_INITFN_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, typename Protocol::socket)) + async_accept(ASIO_MOVE_ARG(MoveAcceptHandler) handler) + { + // 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, typename Protocol::socket) type_check; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_accept( + this->get_implementation(), static_cast(0), + static_cast(0), + ASIO_MOVE_CAST(MoveAcceptHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_accept( + this->get_implementation(), static_cast(0), + static_cast(0), init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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 io_context The io_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(io_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept()); + * @endcode + */ + typename Protocol::socket accept(asio::io_context& io_context) + { + asio::error_code ec; + typename Protocol::socket peer( + this->get_service().accept(this->get_implementation(), + &io_context, static_cast(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 io_context The io_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(io_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept(io_context2, ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + typename Protocol::socket accept( + asio::io_context& io_context, asio::error_code& ec) + { + return this->get_service().accept(this->get_implementation(), + &io_context, static_cast(0), ec); + } + + /// 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 io_context The io_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 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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(io_context); + * ... + * acceptor.async_accept(io_context2, accept_handler); + * @endcode + */ + template + ASIO_INITFN_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, typename Protocol::socket)) + async_accept(asio::io_context& io_context, + ASIO_MOVE_ARG(MoveAcceptHandler) handler) + { + // 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, typename Protocol::socket) type_check; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_accept(this->get_implementation(), + &io_context, static_cast(0), + ASIO_MOVE_CAST(MoveAcceptHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_accept(this->get_implementation(), + &io_context, static_cast(0), init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket(acceptor.accept(endpoint)); + * @endcode + */ + typename Protocol::socket accept(endpoint_type& peer_endpoint) + { + asio::error_code ec; + typename Protocol::socket peer( + this->get_service().accept(this->get_implementation(), + static_cast(0), &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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket(acceptor.accept(endpoint, ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + typename Protocol::socket accept( + endpoint_type& peer_endpoint, asio::error_code& ec) + { + return this->get_service().accept(this->get_implementation(), + static_cast(0), &peer_endpoint, ec); + } + + /// 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( + * const asio::error_code& error, // Result of operation. + * typename Protocol::socket 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * acceptor.async_accept(endpoint, accept_handler); + * @endcode + */ + template + ASIO_INITFN_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, typename Protocol::socket)) + async_accept(endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(MoveAcceptHandler) handler) + { + // 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, typename Protocol::socket) type_check; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_accept(this->get_implementation(), + static_cast(0), &peer_endpoint, + ASIO_MOVE_CAST(MoveAcceptHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_accept(this->get_implementation(), + static_cast(0), &peer_endpoint, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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 io_context The io_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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket( + * acceptor.accept(io_context2, endpoint)); + * @endcode + */ + typename Protocol::socket accept( + asio::io_context& io_context, endpoint_type& peer_endpoint) + { + asio::error_code ec; + typename Protocol::socket peer( + this->get_service().accept(this->get_implementation(), + &io_context, &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 io_context The io_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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket( + * acceptor.accept(io_context2, endpoint, ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + typename Protocol::socket accept(asio::io_context& io_context, + endpoint_type& peer_endpoint, asio::error_code& ec) + { + return this->get_service().accept(this->get_implementation(), + &io_context, &peer_endpoint, ec); + } + + /// 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 io_context The io_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 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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(io_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * acceptor.async_accept(io_context2, endpoint, accept_handler); + * @endcode + */ + template + ASIO_INITFN_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, typename Protocol::socket)) + async_accept(asio::io_context& io_context, + endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(MoveAcceptHandler) handler) + { + // 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, typename Protocol::socket) type_check; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_accept( + this->get_implementation(), &io_context, &peer_endpoint, + ASIO_MOVE_CAST(MoveAcceptHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_accept(this->get_implementation(), + &io_context, &peer_endpoint, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if !defined(ASIO_ENABLE_OLD_SERVICES) +# undef ASIO_SVC_T +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_BASIC_SOCKET_ACCEPTOR_HPP diff --git a/tools/sdk/include/asio/asio/basic_socket_iostream.hpp b/tools/sdk/include/asio/asio/basic_socket_iostream.hpp new file mode 100644 index 00000000000..6681367fdfa --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_socket_iostream.hpp @@ -0,0 +1,430 @@ +// +// basic_socket_iostream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_ENABLE_OLD_SERVICES) +# include "asio/stream_socket_service.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#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 ASIO_SVC_TARG, Clock, +// WaitTraits ASIO_SVC_TARG1>::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 ASIO_SVC_TARG, Clock, \ + WaitTraits ASIO_SVC_TARG1>::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 ), +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + typename Clock = boost::posix_time::ptime, + typename WaitTraits = time_traits + ASIO_SVC_TPARAM1_DEF2(= deadline_timer_service)> +#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 + ASIO_SVC_TPARAM1_DEF1(= steady_timer::service_type)> +#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 ASIO_SVC_TARG, Clock, + WaitTraits ASIO_SVC_TARG1>::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 ASIO_SVC_TARG, Clock, + WaitTraits ASIO_SVC_TARG1>(std::move(s)), + std::basic_iostream( + &this->detail::socket_iostream_base< + Protocol ASIO_SVC_TARG, Clock, + WaitTraits ASIO_SVC_TARG1>::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 ASIO_SVC_TARG, Clock, + WaitTraits ASIO_SVC_TARG1>(std::move(other)), + std::basic_iostream(std::move(other)) + { + this->set_rdbuf(&this->detail::socket_iostream_base< + Protocol ASIO_SVC_TARG, Clock, + WaitTraits ASIO_SVC_TARG1>::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 ASIO_SVC_TARG, Clock, + WaitTraits ASIO_SVC_TARG1>::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 ASIO_SVC_TARG, Clock, + WaitTraits ASIO_SVC_TARG1>::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 ASIO_SVC_TARG, Clock, + WaitTraits ASIO_SVC_TARG1>::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/include/asio/asio/basic_socket_streambuf.hpp b/tools/sdk/include/asio/asio/basic_socket_streambuf.hpp new file mode 100644 index 00000000000..56a3637dccc --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_socket_streambuf.hpp @@ -0,0 +1,707 @@ +// +// basic_socket_streambuf.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_ENABLE_OLD_SERVICES) +# include "asio/stream_socket_service.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) +# if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/deadline_timer_service.hpp" +# else // defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/detail/deadline_timer_service.hpp" +# endif // defined(ASIO_ENABLE_OLD_SERVICES) +#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().context()); +// 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().context()); \ + connect_to_endpoints( \ + resolver.resolve(ASIO_VARIADIC_BYVAL_ARGS(n), ec_)); \ + return !ec_ ? this : 0; \ + } \ + /**/ + +#endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#if !defined(ASIO_ENABLE_OLD_SERVICES) +# define ASIO_SVC_T1 detail::deadline_timer_service +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#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 ), +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + typename Clock = boost::posix_time::ptime, + typename WaitTraits = time_traits + ASIO_SVC_TPARAM1_DEF2(= deadline_timer_service)> +#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 + ASIO_SVC_TPARAM1_DEF1(= steady_timer::service_type)> +#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().context()); + 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_ENABLE_OLD_SERVICES) +# undef ASIO_SVC_T1 +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#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/include/asio/asio/basic_stream_socket.hpp b/tools/sdk/include/asio/asio/basic_stream_socket.hpp new file mode 100644 index 00000000000..eea88627462 --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_stream_socket.hpp @@ -0,0 +1,921 @@ +// +// basic_stream_socket.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/throw_error.hpp" +#include "asio/error.hpp" + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/stream_socket_service.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// 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 native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename basic_socket< + Protocol ASIO_SVC_TARG>::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 io_context The io_context object that the stream socket will use to + * dispatch handlers for any asynchronous operations performed on the socket. + */ + explicit basic_stream_socket(asio::io_context& io_context) + : basic_socket(io_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 io_context The io_context object that the stream socket will use 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(asio::io_context& io_context, + const protocol_type& protocol) + : basic_socket(io_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 io_context The io_context object that the stream socket will use 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(asio::io_context& io_context, + const endpoint_type& endpoint) + : basic_socket(io_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 io_context The io_context object that the stream socket will use 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(asio::io_context& io_context, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_socket( + io_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(io_context&) constructor. + */ + basic_stream_socket(basic_stream_socket&& other) + : 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(io_context&) 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(io_context&) constructor. + */ + template + basic_stream_socket( + basic_stream_socket&& other, + typename enable_if::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(io_context&) constructor. + */ + template + typename enable_if::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->get_service().send( + this->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->get_service().send( + this->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->get_service().send( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send( + this->get_implementation(), buffers, 0, + ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send( + this->get_implementation(), buffers, 0, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send( + this->get_implementation(), buffers, flags, + ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send( + this->get_implementation(), buffers, flags, + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().receive( + this->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->get_service().receive( + this->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->get_service().receive( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive(this->get_implementation(), + buffers, 0, ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive(this->get_implementation(), + buffers, 0, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive(this->get_implementation(), + buffers, flags, ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive(this->get_implementation(), + buffers, flags, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().send( + this->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->get_service().send(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_send(this->get_implementation(), + buffers, 0, ASIO_MOVE_CAST(WriteHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_send(this->get_implementation(), + buffers, 0, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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->get_service().receive( + this->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->get_service().receive( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_receive(this->get_implementation(), + buffers, 0, ASIO_MOVE_CAST(ReadHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_receive(this->get_implementation(), + buffers, 0, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_STREAM_SOCKET_HPP diff --git a/tools/sdk/include/asio/asio/basic_streambuf.hpp b/tools/sdk/include/asio/asio/basic_streambuf.hpp new file mode 100644 index 00000000000..14f85d22fcf --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_streambuf.hpp @@ -0,0 +1,452 @@ +// +// basic_streambuf.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/basic_streambuf_fwd.hpp b/tools/sdk/include/asio/asio/basic_streambuf_fwd.hpp new file mode 100644 index 00000000000..ed54fe95645 --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_streambuf_fwd.hpp @@ -0,0 +1,36 @@ +// +// basic_streambuf_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/basic_waitable_timer.hpp b/tools/sdk/include/asio/asio/basic_waitable_timer.hpp new file mode 100644 index 00000000000..22b85a698ed --- /dev/null +++ b/tools/sdk/include/asio/asio/basic_waitable_timer.hpp @@ -0,0 +1,705 @@ +// +// basic_waitable_timer.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/wait_traits.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/waitable_timer_service.hpp" +#else // defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/detail/chrono_time_traits.hpp" +# include "asio/detail/deadline_timer_service.hpp" +# define ASIO_SVC_T \ + detail::deadline_timer_service< \ + detail::chrono_time_traits > +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#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 + ASIO_SVC_TPARAM_DEF2(= waitable_timer_service)> +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(io_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(io_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 + : ASIO_SVC_ACCESS basic_io_object +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// 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 io_context The io_context object that the timer will use to dispatch + * handlers for any asynchronous operations performed on the timer. + */ + explicit basic_waitable_timer(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Constructor to set a particular expiry time as an absolute time. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param io_context The io_context object that the timer will use 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(asio::io_context& io_context, + const time_point& expiry_time) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().expires_at(this->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 io_context The io_context object that the timer will use 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(asio::io_context& io_context, + const duration& expiry_time) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().expires_after( + this->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(io_context&) constructor. + */ + basic_waitable_timer(basic_waitable_timer&& other) + : basic_io_object(std::move(other)) + { + } + + /// 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(io_context&) constructor. + */ + basic_waitable_timer& operator=(basic_waitable_timer&& other) + { + basic_io_object::operator=(std::move(other)); + 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() + { + } + +#if defined(ASIO_ENABLE_OLD_SERVICES) + // These functions are provided by basic_io_object<>. +#else // defined(ASIO_ENABLE_OLD_SERVICES) +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::get_executor(); + } +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + + /// 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 = this->get_service().cancel(this->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 this->get_service().cancel(this->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 = this->get_service().cancel_one( + this->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 this->get_service().cancel_one(this->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 this->get_service().expires_at(this->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 this->get_service().expiry(this->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 = this->get_service().expires_at( + this->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 this->get_service().expires_at( + this->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 = this->get_service().expires_after( + this->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 this->get_service().expires_from_now(this->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 = this->get_service().expires_from_now( + this->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 this->get_service().expires_from_now( + this->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; + this->get_service().wait(this->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) + { + this->get_service().wait(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(ASIO_MOVE_ARG(WaitHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_wait(this->get_implementation(), + ASIO_MOVE_CAST(WaitHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + async_completion init(handler); + + this->get_service().async_wait(this->get_implementation(), + init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + +private: + // Disallow copying and assignment. + basic_waitable_timer(const basic_waitable_timer&) ASIO_DELETED; + basic_waitable_timer& operator=( + const basic_waitable_timer&) ASIO_DELETED; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if !defined(ASIO_ENABLE_OLD_SERVICES) +# undef ASIO_SVC_T +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_BASIC_WAITABLE_TIMER_HPP diff --git a/tools/sdk/include/asio/asio/bind_executor.hpp b/tools/sdk/include/asio/asio/bind_executor.hpp new file mode 100644 index 00000000000..9e2094b5443 --- /dev/null +++ b/tools/sdk/include/asio/asio/bind_executor.hpp @@ -0,0 +1,611 @@ +// +// bind_executor.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_; +}; + +#if !defined(ASIO_NO_DEPRECATED) + +template +struct handler_type, Signature> +{ + typedef executor_binder< + typename handler_type::type, Executor> type; +}; + +template +class async_result > +{ +public: + typedef typename async_result::type type; + + explicit async_result(executor_binder& b) + : target_(b.get()) + { + } + + type get() + { + return target_.get(); + } + +private: + async_result target_; +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +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/include/asio/asio/buffer.hpp b/tools/sdk/include/asio/asio/buffer.hpp new file mode 100644 index 00000000000..a9aa8aad272 --- /dev/null +++ b/tools/sdk/include/asio/asio/buffer.hpp @@ -0,0 +1,2162 @@ +// +// buffer.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/is_buffer_sequence.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) + +/// 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) +{ +}; + +/// Trait to determine whether a type satisfies the DynamicBuffer requirements. +template +struct is_dynamic_buffer +#if defined(GENERATING_DOCUMENTATION) + : integral_constant +#else // defined(GENERATING_DOCUMENTATION) + : asio::detail::is_dynamic_buffer +#endif // defined(GENERATING_DOCUMENTATION) +{ +}; + +/// (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. +inline const mutable_buffer* buffer_sequence_begin(const mutable_buffer& b) +{ + return &b; +} + +/// Get an iterator to the first element in a buffer sequence. +inline const const_buffer* buffer_sequence_begin(const const_buffer& b) +{ + return &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) -> 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) -> decltype(c.begin()) +{ + return c.begin(); +} + +#else // defined(ASIO_HAS_DECLTYPE) || defined(GENERATING_DOCUMENTATION) + +template +inline typename C::iterator buffer_sequence_begin(C& c) +{ + return c.begin(); +} + +template +inline typename C::const_iterator buffer_sequence_begin(const C& c) +{ + 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. +inline const mutable_buffer* buffer_sequence_end(const mutable_buffer& b) +{ + return &b + 1; +} + +/// Get an iterator to one past the end element in a buffer sequence. +inline const const_buffer* buffer_sequence_end(const const_buffer& b) +{ + return &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) -> 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) -> decltype(c.end()) +{ + return c.end(); +} + +#else // defined(ASIO_HAS_DECLTYPE) || defined(GENERATING_DOCUMENTATION) + +template +inline typename C::iterator buffer_sequence_end(C& c) +{ + return c.end(); +} + +template +inline typename C::const_iterator buffer_sequence_end(const C& c) +{ + 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 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 + * + * @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 the input sequence as a list of buffers. + typedef ASIO_CONST_BUFFER const_buffers_type; + + /// The type used to represent the output sequence as a list of buffers. + 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. + * Any existing data in the string is treated as the dynamic buffer's input + * sequence. The object stores a reference to the string and the user is + * responsible for ensuring that the string object remains valid until the + * dynamic_string_buffer object is destroyed. + * + * @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), + size_(string_.size()), + max_size_(maximum_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_), + size_(other.size_), + max_size_(other.max_size_) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get the size of the input sequence. + std::size_t size() const ASIO_NOEXCEPT + { + return size_; + } + + /// Get the maximum size of the dynamic buffer. + /** + * @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 dynamic buffer. + /** + * @returns The current total capacity of the buffer, i.e. for both the input + * sequence and output sequence. + */ + std::size_t capacity() const ASIO_NOEXCEPT + { + return string_.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 the basic_string memory in + * input sequence. + * + * @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. + */ + const_buffers_type data() const ASIO_NOEXCEPT + { + return const_buffers_type(asio::buffer(string_, size_)); + } + + /// 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); + } + + string_.resize(size_ + n); + + return asio::buffer(asio::buffer(string_) + size_, n); + } + + /// 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_); + } + + /// 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) + { + std::size_t consume_length = (std::min)(n, size_); + string_.erase(0, consume_length); + size_ -= consume_length; + } + +private: + std::basic_string& string_; + std::size_t size_; + 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 the input sequence as a list of buffers. + typedef ASIO_CONST_BUFFER const_buffers_type; + + /// The type used to represent the output sequence as a list of buffers. + typedef ASIO_MUTABLE_BUFFER mutable_buffers_type; + + /// Construct a dynamic buffer from a string. + /** + * @param v The vector to be used as backing storage for the dynamic buffer. + * Any existing data in the vector is treated as the dynamic buffer's input + * sequence. The object stores a reference to the vector and the user is + * responsible for ensuring that the vector object remains valid until the + * dynamic_vector_buffer object is destroyed. + * + * @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), + size_(vector_.size()), + max_size_(maximum_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_), + size_(other.size_), + max_size_(other.max_size_) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get the size of the input sequence. + std::size_t size() const ASIO_NOEXCEPT + { + return size_; + } + + /// Get the maximum size of the dynamic buffer. + /** + * @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 dynamic buffer. + /** + * @returns The current total capacity of the buffer, i.e. for both the input + * sequence and output sequence. + */ + std::size_t capacity() const ASIO_NOEXCEPT + { + return vector_.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 the basic_string memory in + * input sequence. + * + * @note The returned object is invalidated by any @c dynamic_vector_buffer + * or @c basic_string 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_)); + } + + /// 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_vector_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_vector_buffer too long"); + asio::detail::throw_exception(ex); + } + + vector_.resize(size_ + n); + + return asio::buffer(asio::buffer(vector_) + size_, n); + } + + /// 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_); + } + + /// 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) + { + std::size_t consume_length = (std::min)(n, size_); + vector_.erase(vector_.begin(), vector_.begin() + consume_length); + size_ -= consume_length; + } + +private: + std::vector& vector_; + std::size_t size_; + 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" + +#endif // ASIO_BUFFER_HPP diff --git a/tools/sdk/include/asio/asio/buffered_read_stream.hpp b/tools/sdk/include/asio/asio/buffered_read_stream.hpp new file mode 100644 index 00000000000..c3e7f0b57e2 --- /dev/null +++ b/tools/sdk/include/asio/asio/buffered_read_stream.hpp @@ -0,0 +1,257 @@ +// +// buffered_read_stream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_context.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(); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + asio::io_context& get_io_context() + { + return next_layer_.get_io_context(); + } + + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + asio::io_context& get_io_service() + { + return next_layer_.get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// 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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + 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_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_fill(ASIO_MOVE_ARG(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); + + /// 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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(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); + + /// 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/include/asio/asio/buffered_read_stream_fwd.hpp b/tools/sdk/include/asio/asio/buffered_read_stream_fwd.hpp new file mode 100644 index 00000000000..334b88a5c0a --- /dev/null +++ b/tools/sdk/include/asio/asio/buffered_read_stream_fwd.hpp @@ -0,0 +1,25 @@ +// +// buffered_read_stream_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/buffered_stream.hpp b/tools/sdk/include/asio/asio/buffered_stream.hpp new file mode 100644 index 00000000000..8014fa4dd94 --- /dev/null +++ b/tools/sdk/include/asio/asio/buffered_stream.hpp @@ -0,0 +1,278 @@ +// +// buffered_stream.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_context.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(); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + asio::io_context& get_io_context() + { + return stream_impl_.get_io_context(); + } + + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + asio::io_context& get_io_service() + { + return stream_impl_.get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// 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_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_flush(ASIO_MOVE_ARG(WriteHandler) handler) + { + 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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + 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_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_fill(ASIO_MOVE_ARG(ReadHandler) handler) + { + 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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + 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/include/asio/asio/buffered_stream_fwd.hpp b/tools/sdk/include/asio/asio/buffered_stream_fwd.hpp new file mode 100644 index 00000000000..3492979d2b1 --- /dev/null +++ b/tools/sdk/include/asio/asio/buffered_stream_fwd.hpp @@ -0,0 +1,25 @@ +// +// buffered_stream_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/buffered_write_stream.hpp b/tools/sdk/include/asio/asio/buffered_write_stream.hpp new file mode 100644 index 00000000000..aac33d38f47 --- /dev/null +++ b/tools/sdk/include/asio/asio/buffered_write_stream.hpp @@ -0,0 +1,249 @@ +// +// buffered_write_stream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_context.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(); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + asio::io_context& get_io_context() + { + return next_layer_.get_io_context(); + } + + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + asio::io_context& get_io_service() + { + return next_layer_.get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// 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_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_flush(ASIO_MOVE_ARG(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); + + /// 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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) 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 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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + 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/include/asio/asio/buffered_write_stream_fwd.hpp b/tools/sdk/include/asio/asio/buffered_write_stream_fwd.hpp new file mode 100644 index 00000000000..6ef54ba0d6c --- /dev/null +++ b/tools/sdk/include/asio/asio/buffered_write_stream_fwd.hpp @@ -0,0 +1,25 @@ +// +// buffered_write_stream_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/buffers_iterator.hpp b/tools/sdk/include/asio/asio/buffers_iterator.hpp new file mode 100644 index 00000000000..f5c9d4c3548 --- /dev/null +++ b/tools/sdk/include/asio/asio/buffers_iterator.hpp @@ -0,0 +1,521 @@ +// +// buffers_iterator.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/completion_condition.hpp b/tools/sdk/include/asio/asio/completion_condition.hpp new file mode 100644 index 00000000000..563f417d1a5 --- /dev/null +++ b/tools/sdk/include/asio/asio/completion_condition.hpp @@ -0,0 +1,218 @@ +// +// completion_condition.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/connect.hpp b/tools/sdk/include/asio/asio/connect.hpp new file mode 100644 index 00000000000..487ce3e0856 --- /dev/null +++ b/tools/sdk/include/asio/asio/connect.hpp @@ -0,0 +1,1059 @@ +// +// connect.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(io_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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(io_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.) 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.) 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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::resolver::results_type e = r.resolve(q); + * tcp::socket s(io_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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::resolver::results_type e = r.resolve(q); + * tcp::socket s(io_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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(io_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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(io_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.) 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.) 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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::resolver::results_type e = r.resolve(q); + * tcp::socket s(io_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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::resolver::results_type e = r.resolve(q); + * tcp::socket s(io_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 Asynchronously 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @par Example + * @code tcp::resolver r(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(io_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_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* = 0); + +#if !defined(ASIO_NO_DEPRECATED) +/// (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 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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* = 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @par Example + * @code std::vector endpoints = ...; + * tcp::socket s(io_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_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, + Iterator begin, Iterator end, + ASIO_MOVE_ARG(IteratorConnectHandler) handler); + +/// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(io_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_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* = 0); + +#if !defined(ASIO_NO_DEPRECATED) +/// (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 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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* = 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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(io_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(io_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_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); + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/connect.hpp" + +#endif diff --git a/tools/sdk/include/asio/asio/coroutine.hpp b/tools/sdk/include/asio/asio/coroutine.hpp new file mode 100644 index 00000000000..cd2d99e536a --- /dev/null +++ b/tools/sdk/include/asio/asio/coroutine.hpp @@ -0,0 +1,328 @@ +// +// coroutine.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(io_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 io_context::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/include/asio/asio/datagram_socket_service.hpp b/tools/sdk/include/asio/asio/datagram_socket_service.hpp new file mode 100644 index 00000000000..7dc1a3b34a7 --- /dev/null +++ b/tools/sdk/include/asio/asio/datagram_socket_service.hpp @@ -0,0 +1,466 @@ +// +// datagram_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DATAGRAM_SOCKET_SERVICE_HPP +#define ASIO_DATAGRAM_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_ENABLE_OLD_SERVICES) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/io_context.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 + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a datagram socket. +template +class datagram_socket_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base > +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + +private: + // The type of the platform-specific implementation. +#if defined(ASIO_WINDOWS_RUNTIME) + typedef detail::null_socket_service service_impl_type; +#elif defined(ASIO_HAS_IOCP) + typedef detail::win_iocp_socket_service service_impl_type; +#else + typedef detail::reactive_socket_service service_impl_type; +#endif + +public: + /// The type of a datagram socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef typename service_impl_type::implementation_type implementation_type; +#endif + + /// The native socket type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new datagram socket service for the specified io_context. + explicit datagram_socket_service(asio::io_context& io_context) + : asio::detail::service_base< + datagram_socket_service >(io_context), + service_impl_(io_context) + { + } + + /// Construct a new datagram socket implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new datagram socket implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another datagram socket implementation. + void move_assign(implementation_type& impl, + datagram_socket_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } + + // All socket services have access to each other's implementations. + template friend class datagram_socket_service; + + /// Move-construct a new datagram socket implementation from another protocol + /// type. + template + void converting_move_construct(implementation_type& impl, + datagram_socket_service& other_service, + typename datagram_socket_service< + Protocol1>::implementation_type& other_impl, + typename enable_if::value>::type* = 0) + { + service_impl_.template converting_move_construct( + impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a datagram socket implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + // Open a new datagram socket implementation. + ASIO_SYNC_OP_VOID open(implementation_type& impl, + const protocol_type& protocol, asio::error_code& ec) + { + if (protocol.type() == ASIO_OS_DEF(SOCK_DGRAM)) + service_impl_.open(impl, protocol, ec); + else + ec = asio::error::invalid_argument; + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assign an existing native socket to a datagram socket. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const protocol_type& protocol, const native_handle_type& native_socket, + asio::error_code& ec) + { + service_impl_.assign(impl, protocol, native_socket, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close a datagram socket implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Release ownership of the underlying socket. + native_handle_type release(implementation_type& impl, + asio::error_code& ec) + { + return service_impl_.release(impl, ec); + } + + /// Get the native socket implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Cancel all asynchronous operations associated with the socket. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is at the out-of-band data mark. + bool at_mark(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.at_mark(impl, ec); + } + + /// Determine the number of bytes available for reading. + std::size_t available(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.available(impl, ec); + } + + // Bind the datagram socket to the specified local endpoint. + ASIO_SYNC_OP_VOID bind(implementation_type& impl, + const endpoint_type& endpoint, asio::error_code& ec) + { + service_impl_.bind(impl, endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Connect the datagram socket to the specified endpoint. + ASIO_SYNC_OP_VOID connect(implementation_type& impl, + const endpoint_type& peer_endpoint, asio::error_code& ec) + { + service_impl_.connect(impl, peer_endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous connect. + template + ASIO_INITFN_RESULT_TYPE(ConnectHandler, + void (asio::error_code)) + async_connect(implementation_type& impl, + const endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(ConnectHandler) handler) + { + async_completion init(handler); + + service_impl_.async_connect(impl, peer_endpoint, init.completion_handler); + + return init.result.get(); + } + + /// Set a socket option. + template + ASIO_SYNC_OP_VOID set_option(implementation_type& impl, + const SettableSocketOption& option, asio::error_code& ec) + { + service_impl_.set_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get a socket option. + template + ASIO_SYNC_OP_VOID get_option(const implementation_type& impl, + GettableSocketOption& option, asio::error_code& ec) const + { + service_impl_.get_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the socket. + template + ASIO_SYNC_OP_VOID io_control(implementation_type& impl, + IoControlCommand& command, asio::error_code& ec) + { + service_impl_.io_control(impl, command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the socket. + bool non_blocking(const implementation_type& impl) const + { + return service_impl_.non_blocking(impl); + } + + /// Sets the non-blocking mode of the socket. + ASIO_SYNC_OP_VOID non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native socket implementation. + bool native_non_blocking(const implementation_type& impl) const + { + return service_impl_.native_non_blocking(impl); + } + + /// Sets the non-blocking mode of the native socket implementation. + ASIO_SYNC_OP_VOID native_non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.native_non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the local endpoint. + endpoint_type local_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.local_endpoint(impl, ec); + } + + /// Get the remote endpoint. + endpoint_type remote_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.remote_endpoint(impl, ec); + } + + /// Disable sends or receives on the socket. + ASIO_SYNC_OP_VOID shutdown(implementation_type& impl, + socket_base::shutdown_type what, asio::error_code& ec) + { + service_impl_.shutdown(impl, 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. + ASIO_SYNC_OP_VOID wait(implementation_type& impl, + socket_base::wait_type w, asio::error_code& ec) + { + service_impl_.wait(impl, 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. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, socket_base::wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, w, init.completion_handler); + + return init.result.get(); + } + + /// Send the given data to the peer. + template + std::size_t send(implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.send(impl, buffers, flags, ec); + } + + /// Start an asynchronous send. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(implementation_type& impl, const ConstBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler) + { + async_completion init(handler); + + service_impl_.async_send(impl, buffers, flags, init.completion_handler); + + return init.result.get(); + } + + /// Send a datagram to the specified endpoint. + template + std::size_t send_to(implementation_type& impl, + const ConstBufferSequence& buffers, const endpoint_type& destination, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.send_to(impl, buffers, destination, flags, ec); + } + + /// Start an asynchronous send. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send_to(implementation_type& impl, + const ConstBufferSequence& buffers, const endpoint_type& destination, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler) + { + async_completion init(handler); + + service_impl_.async_send_to(impl, buffers, + destination, flags, init.completion_handler); + + return init.result.get(); + } + + /// Receive some data from the peer. + template + std::size_t receive(implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.receive(impl, buffers, flags, ec); + } + + /// Start an asynchronous receive. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler) + { + async_completion init(handler); + + service_impl_.async_receive(impl, buffers, flags, init.completion_handler); + + return init.result.get(); + } + + /// Receive a datagram with the endpoint of the sender. + template + std::size_t receive_from(implementation_type& impl, + const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.receive_from(impl, buffers, sender_endpoint, flags, + ec); + } + + /// Start an asynchronous receive that will get the endpoint of the sender. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive_from(implementation_type& impl, + const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, + socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler) + { + async_completion init(handler); + + service_impl_.async_receive_from(impl, buffers, + sender_endpoint, flags, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_DATAGRAM_SOCKET_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/deadline_timer.hpp b/tools/sdk/include/asio/asio/deadline_timer.hpp new file mode 100644 index 00000000000..5a2155474a5 --- /dev/null +++ b/tools/sdk/include/asio/asio/deadline_timer.hpp @@ -0,0 +1,38 @@ +// +// deadline_timer.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/deadline_timer_service.hpp b/tools/sdk/include/asio/asio/deadline_timer_service.hpp new file mode 100644 index 00000000000..2dcc83e2f92 --- /dev/null +++ b/tools/sdk/include/asio/asio/deadline_timer_service.hpp @@ -0,0 +1,173 @@ +// +// deadline_timer_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_SERVICE_HPP +#define ASIO_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" + +#if defined(ASIO_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/deadline_timer_service.hpp" +#include "asio/io_context.hpp" +#include "asio/time_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a timer. +template > +class deadline_timer_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base< + deadline_timer_service > +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + + /// 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; + +private: + // The type of the platform-specific implementation. + typedef detail::deadline_timer_service service_impl_type; + +public: + /// The implementation type of the deadline timer. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef typename service_impl_type::implementation_type implementation_type; +#endif + + /// Construct a new timer service for the specified io_context. + explicit deadline_timer_service(asio::io_context& io_context) + : asio::detail::service_base< + deadline_timer_service >(io_context), + service_impl_(io_context) + { + } + + /// Construct a new timer implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + + /// Destroy a timer implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Cancel any asynchronous wait operations associated with the timer. + std::size_t cancel(implementation_type& impl, asio::error_code& ec) + { + return service_impl_.cancel(impl, ec); + } + + /// Cancels one asynchronous wait operation associated with the timer. + std::size_t cancel_one(implementation_type& impl, + asio::error_code& ec) + { + return service_impl_.cancel_one(impl, ec); + } + + /// Get the expiry time for the timer as an absolute time. + time_type expires_at(const implementation_type& impl) const + { + return service_impl_.expiry(impl); + } + + /// 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) + { + return service_impl_.expires_at(impl, expiry_time, ec); + } + + /// Get the expiry time for the timer relative to now. + duration_type expires_from_now(const implementation_type& impl) const + { + return TimeTraits::subtract(service_impl_.expiry(impl), TimeTraits::now()); + } + + /// 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 service_impl_.expires_after(impl, expiry_time, ec); + } + + // Perform a blocking wait on the timer. + void wait(implementation_type& impl, asio::error_code& ec) + { + service_impl_.wait(impl, ec); + } + + // Start an asynchronous wait on the timer. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, + ASIO_MOVE_ARG(WaitHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_DEADLINE_TIMER_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/defer.hpp b/tools/sdk/include/asio/asio/defer.hpp new file mode 100644 index 00000000000..a0897f2f83f --- /dev/null +++ b/tools/sdk/include/asio/asio/defer.hpp @@ -0,0 +1,107 @@ +// +// defer.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(). + * + * 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_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(). + * + * 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_RESULT_TYPE(CompletionToken, void()) defer( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + 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_RESULT_TYPE(CompletionToken, void()) defer( + ExecutionContext& ctx, ASIO_MOVE_ARG(CompletionToken) token, + 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/include/asio/asio/detail/array.hpp b/tools/sdk/include/asio/asio/detail/array.hpp new file mode 100644 index 00000000000..ba4297462ca --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/array.hpp @@ -0,0 +1,38 @@ +// +// detail/array.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/array_fwd.hpp b/tools/sdk/include/asio/asio/detail/array_fwd.hpp new file mode 100644 index 00000000000..4161db0dbde --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/array_fwd.hpp @@ -0,0 +1,34 @@ +// +// detail/array_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/assert.hpp b/tools/sdk/include/asio/asio/detail/assert.hpp new file mode 100644 index 00000000000..a952a441f2c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/assert.hpp @@ -0,0 +1,32 @@ +// +// detail/assert.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/atomic_count.hpp b/tools/sdk/include/asio/asio/detail/atomic_count.hpp new file mode 100644 index 00000000000..2bf75a5355e --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/atomic_count.hpp @@ -0,0 +1,45 @@ +// +// detail/atomic_count.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/base_from_completion_cond.hpp b/tools/sdk/include/asio/asio/detail/base_from_completion_cond.hpp new file mode 100644 index 00000000000..73b4a957f3a --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/base_from_completion_cond.hpp @@ -0,0 +1,68 @@ +// +// detail/base_from_completion_cond.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_(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/include/asio/asio/detail/bind_handler.hpp b/tools/sdk/include/asio/asio/detail/bind_handler.hpp new file mode 100644 index 00000000000..0f4f066d837 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/bind_handler.hpp @@ -0,0 +1,816 @@ +// +// detail/bind_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/buffer_resize_guard.hpp b/tools/sdk/include/asio/asio/detail/buffer_resize_guard.hpp new file mode 100644 index 00000000000..58ebc4cc79c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/buffer_resize_guard.hpp @@ -0,0 +1,66 @@ +// +// detail/buffer_resize_guard.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/buffer_sequence_adapter.hpp b/tools/sdk/include/asio/asio/detail/buffer_sequence_adapter.hpp new file mode 100644 index 00000000000..92a8e3d2faf --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/buffer_sequence_adapter.hpp @@ -0,0 +1,544 @@ +// +// detail/buffer_sequence_adapter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/buffered_stream_storage.hpp b/tools/sdk/include/asio/asio/detail/buffered_stream_storage.hpp new file mode 100644 index 00000000000..c5eb081d9a3 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/buffered_stream_storage.hpp @@ -0,0 +1,126 @@ +// +// detail/buffered_stream_storage.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/call_stack.hpp b/tools/sdk/include/asio/asio/detail/call_stack.hpp new file mode 100644 index 00000000000..5725a10a22f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/call_stack.hpp @@ -0,0 +1,125 @@ +// +// detail/call_stack.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/chrono.hpp b/tools/sdk/include/asio/asio/detail/chrono.hpp new file mode 100644 index 00000000000..8f56beed5fa --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/chrono.hpp @@ -0,0 +1,66 @@ +// +// detail/chrono.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/chrono_time_traits.hpp b/tools/sdk/include/asio/asio/detail/chrono_time_traits.hpp new file mode 100644 index 00000000000..d1528f70db3 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/chrono_time_traits.hpp @@ -0,0 +1,190 @@ +// +// detail/chrono_time_traits.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/completion_handler.hpp b/tools/sdk/include/asio/asio/detail/completion_handler.hpp new file mode 100644 index 00000000000..58a2e6db984 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/completion_handler.hpp @@ -0,0 +1,83 @@ +// +// detail/completion_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/concurrency_hint.hpp b/tools/sdk/include/asio/asio/detail/concurrency_hint.hpp new file mode 100644 index 00000000000..229124d3765 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/concurrency_hint.hpp @@ -0,0 +1,94 @@ +// +// detail/concurrency_hint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/conditionally_enabled_event.hpp b/tools/sdk/include/asio/asio/detail/conditionally_enabled_event.hpp new file mode 100644 index 00000000000..0fda401e3bb --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/conditionally_enabled_event.hpp @@ -0,0 +1,112 @@ +// +// detail/conditionally_enabled_event.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/conditionally_enabled_mutex.hpp b/tools/sdk/include/asio/asio/detail/conditionally_enabled_mutex.hpp new file mode 100644 index 00000000000..2872db98be9 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/conditionally_enabled_mutex.hpp @@ -0,0 +1,149 @@ +// +// detail/conditionally_enabled_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/config.hpp b/tools/sdk/include/asio/asio/detail/config.hpp new file mode 100644 index 00000000000..949d67f2a87 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/config.hpp @@ -0,0 +1,1441 @@ +// +// detail/config.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + +#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) +#if defined(ASIO_MSVC) +# include // Needed for _HAS_CXX17. +#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) +# 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 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_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_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 (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 >= 1700) +# define ASIO_HAS_DECLTYPE 1 +# endif // (_MSC_VER >= 1700) +# 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) + +// 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 (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() +# 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_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 (BOOST_VERSION >= 104700) +# define ASIO_HAS_BOOST_CHRONO 1 +# endif // (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__) +# if defined(_GLIBCXX_HAS_GTHREADS) +# define ASIO_HAS_STD_FUTURE 1 +# endif // defined(_GLIBCXX_HAS_GTHREADS) +# 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 (__cplusplus >= 201703) +# if __has_include() +# define ASIO_HAS_STD_STRING_VIEW 1 +# endif // __has_include() +# endif // (__cplusplus >= 201703) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if (__GNUC__ >= 7) +# if (__cplusplus >= 201703) +# define ASIO_HAS_STD_STRING_VIEW 1 +# endif // (__cplusplus >= 201703) +# endif // (__GNUC__ >= 7) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1910 && _HAS_CXX17) +# define ASIO_HAS_STD_STRING_VIEW +# endif // (_MSC_VER >= 1910 && _HAS_CXX17) +# 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 (__cplusplus >= 201402) +# if __has_include() +# define ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW 1 +# endif // __has_include() +# endif // (__cplusplus >= 201402) +# 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 >= 1910 && _HAS_CXX17) +# define ASIO_HAS_STD_INVOKE_RESULT 1 +# endif // (_MSC_VER >= 1910 && _HAS_CXX17) +# 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=0x0501 to the compiler command line; or\n"\ + "- add _WIN32_WINNT=0x0501 to your project's Preprocessor Definitions.\n"\ + "Assuming _WIN32_WINNT=0x0501 (i.e. Windows XP target).") +# else // defined(_MSC_VER) || defined(__BORLANDC__) +# warning Please define _WIN32_WINNT or _WIN32_WINDOWS appropriately. +# warning For example, add -D_WIN32_WINNT=0x0501 to the compiler command line. +# warning Assuming _WIN32_WINNT=0x0501 (i.e. Windows XP target). +# endif // defined(_MSC_VER) || defined(__BORLANDC__) +# define _WIN32_WINNT 0x0501 +# 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__) +# 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(_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 +# 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 the transition away from the old services-based API. +#if defined(ASIO_ENABLE_OLD_SERVICES) +# define ASIO_SVC_TPARAM , typename Service +# define ASIO_SVC_TPARAM_DEF1(d1) , typename Service d1 +# define ASIO_SVC_TPARAM_DEF2(d1, d2) , typename Service d1, d2 +# define ASIO_SVC_TARG , Service +# define ASIO_SVC_T Service +# define ASIO_SVC_TPARAM1 , typename Service1 +# define ASIO_SVC_TPARAM1_DEF1(d1) , typename Service1 d1 +# define ASIO_SVC_TPARAM1_DEF2(d1, d2) , typename Service1 d1, d2 +# define ASIO_SVC_TARG1 , Service1 +# define ASIO_SVC_T1 Service1 +# define ASIO_SVC_ACCESS public +#else // defined(ASIO_ENABLE_OLD_SERVICES) +# define ASIO_SVC_TPARAM +# define ASIO_SVC_TPARAM_DEF1(d1) +# define ASIO_SVC_TPARAM_DEF2(d1, d2) +# define ASIO_SVC_TARG +// ASIO_SVC_T is defined at each point of use. +# define ASIO_SVC_TPARAM1 +# define ASIO_SVC_TPARAM1_DEF1(d1) +# define ASIO_SVC_TPARAM1_DEF2(d1, d2) +# define ASIO_SVC_TARG1 +// ASIO_SVC_T1 is defined at each point of use. +# define ASIO_SVC_ACCESS protected +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +// 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 (__cpp_coroutines >= 201703) +# if __has_include() +# define ASIO_HAS_CO_AWAIT 1 +# endif // __has_include() +# endif // (__cpp_coroutines >= 201703) +# endif // defined(__clang__) +#endif // !defined(ASIO_HAS_CO_AWAIT) + +#endif // ASIO_DETAIL_CONFIG_HPP diff --git a/tools/sdk/include/asio/asio/detail/consuming_buffers.hpp b/tools/sdk/include/asio/asio/detail/consuming_buffers.hpp new file mode 100644 index 00000000000..8127ae75ca2 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/consuming_buffers.hpp @@ -0,0 +1,414 @@ +// +// detail/consuming_buffers.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/cstddef.hpp b/tools/sdk/include/asio/asio/detail/cstddef.hpp new file mode 100644 index 00000000000..3912da40df2 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/cstddef.hpp @@ -0,0 +1,31 @@ +// +// detail/cstddef.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/cstdint.hpp b/tools/sdk/include/asio/asio/detail/cstdint.hpp new file mode 100644 index 00000000000..62342b2d2c1 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/cstdint.hpp @@ -0,0 +1,60 @@ +// +// detail/cstdint.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/date_time_fwd.hpp b/tools/sdk/include/asio/asio/detail/date_time_fwd.hpp new file mode 100644 index 00000000000..a159562eb5c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/date_time_fwd.hpp @@ -0,0 +1,34 @@ +// +// detail/date_time_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/deadline_timer_service.hpp b/tools/sdk/include/asio/asio/detail/deadline_timer_service.hpp new file mode 100644 index 00000000000..f58a6e0e764 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/deadline_timer_service.hpp @@ -0,0 +1,278 @@ +// +// detail/deadline_timer_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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 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(asio::io_context& io_context) + : service_base >(io_context), + scheduler_(asio::use_service(io_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) + { + // 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); + + 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/include/asio/asio/detail/dependent_type.hpp b/tools/sdk/include/asio/asio/detail/dependent_type.hpp new file mode 100644 index 00000000000..85b41c8935f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/dependent_type.hpp @@ -0,0 +1,36 @@ +// +// detail/dependent_type.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/descriptor_ops.hpp b/tools/sdk/include/asio/asio/detail/descriptor_ops.hpp new file mode 100644 index 00000000000..9c0560aa2c9 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/descriptor_ops.hpp @@ -0,0 +1,121 @@ +// +// detail/descriptor_ops.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/descriptor_read_op.hpp b/tools/sdk/include/asio/asio/detail/descriptor_read_op.hpp new file mode 100644 index 00000000000..6db4bfb958e --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/descriptor_read_op.hpp @@ -0,0 +1,128 @@ +// +// detail/descriptor_read_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : descriptor_read_op_base( + descriptor, buffers, &descriptor_read_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + descriptor_read_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // 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/include/asio/asio/detail/descriptor_write_op.hpp b/tools/sdk/include/asio/asio/detail/descriptor_write_op.hpp new file mode 100644 index 00000000000..a9ec2a97624 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/descriptor_write_op.hpp @@ -0,0 +1,128 @@ +// +// detail/descriptor_write_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : descriptor_write_op_base( + descriptor, buffers, &descriptor_write_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + descriptor_write_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // 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/include/asio/asio/detail/dev_poll_reactor.hpp b/tools/sdk/include/asio/asio/detail/dev_poll_reactor.hpp new file mode 100644 index 00000000000..e9e4e29e04b --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/dev_poll_reactor.hpp @@ -0,0 +1,218 @@ +// +// detail/dev_poll_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/epoll_reactor.hpp b/tools/sdk/include/asio/asio/detail/epoll_reactor.hpp new file mode 100644 index 00000000000..5f58109930b --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/epoll_reactor.hpp @@ -0,0 +1,266 @@ +// +// detail/epoll_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/event.hpp b/tools/sdk/include/asio/asio/detail/event.hpp new file mode 100644 index 00000000000..da8fa770b35 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/event.hpp @@ -0,0 +1,48 @@ +// +// detail/event.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/eventfd_select_interrupter.hpp b/tools/sdk/include/asio/asio/detail/eventfd_select_interrupter.hpp new file mode 100644 index 00000000000..f6e594b6112 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/eventfd_select_interrupter.hpp @@ -0,0 +1,83 @@ +// +// detail/eventfd_select_interrupter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/detail/executor_op.hpp b/tools/sdk/include/asio/asio/detail/executor_op.hpp new file mode 100644 index 00000000000..2d5c7e8b89d --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/executor_op.hpp @@ -0,0 +1,84 @@ +// +// detail/executor_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/fd_set_adapter.hpp b/tools/sdk/include/asio/asio/detail/fd_set_adapter.hpp new file mode 100644 index 00000000000..fd373dae1f3 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/fd_set_adapter.hpp @@ -0,0 +1,39 @@ +// +// detail/fd_set_adapter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/fenced_block.hpp b/tools/sdk/include/asio/asio/detail/fenced_block.hpp new file mode 100644 index 00000000000..dc34bd9fb47 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/fenced_block.hpp @@ -0,0 +1,80 @@ +// +// detail/fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/functional.hpp b/tools/sdk/include/asio/asio/detail/functional.hpp new file mode 100644 index 00000000000..a37e9e63186 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/functional.hpp @@ -0,0 +1,38 @@ +// +// detail/functional.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/gcc_arm_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/gcc_arm_fenced_block.hpp new file mode 100644 index 00000000000..7919a551c70 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/gcc_arm_fenced_block.hpp @@ -0,0 +1,91 @@ +// +// detail/gcc_arm_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/gcc_hppa_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/gcc_hppa_fenced_block.hpp new file mode 100644 index 00000000000..d3957ce33e6 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/gcc_hppa_fenced_block.hpp @@ -0,0 +1,68 @@ +// +// detail/gcc_hppa_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/gcc_sync_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/gcc_sync_fenced_block.hpp new file mode 100644 index 00000000000..90d176f12ae --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/gcc_sync_fenced_block.hpp @@ -0,0 +1,65 @@ +// +// detail/gcc_sync_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/gcc_x86_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/gcc_x86_fenced_block.hpp new file mode 100644 index 00000000000..1366def74e6 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/gcc_x86_fenced_block.hpp @@ -0,0 +1,99 @@ +// +// detail/gcc_x86_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/global.hpp b/tools/sdk/include/asio/asio/detail/global.hpp new file mode 100644 index 00000000000..085ac643d6c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/global.hpp @@ -0,0 +1,52 @@ +// +// detail/global.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/handler_alloc_helpers.hpp b/tools/sdk/include/asio/asio/detail/handler_alloc_helpers.hpp new file mode 100644 index 00000000000..afefb4d12d6 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/handler_alloc_helpers.hpp @@ -0,0 +1,235 @@ +// +// detail/handler_alloc_helpers.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_HANDLER_ALLOCATOR_PTR(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>::type recycling_allocator_type; \ + ASIO_REBIND_ALLOC(recycling_allocator_type, op) a1( \ + ::asio::detail::get_recycling_allocator::get(a)); \ + return a1.allocate(1); \ + } \ + void reset() \ + { \ + if (p) \ + { \ + p->~op(); \ + p = 0; \ + } \ + if (v) \ + { \ + typedef typename ::asio::detail::get_recycling_allocator< \ + Alloc>::type recycling_allocator_type; \ + ASIO_REBIND_ALLOC(recycling_allocator_type, op) a1( \ + ::asio::detail::get_recycling_allocator::get(*a)); \ + a1.deallocate(static_cast(v), 1); \ + v = 0; \ + } \ + } \ + } \ + /**/ + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_HANDLER_ALLOC_HELPERS_HPP diff --git a/tools/sdk/include/asio/asio/detail/handler_cont_helpers.hpp b/tools/sdk/include/asio/asio/detail/handler_cont_helpers.hpp new file mode 100644 index 00000000000..110ba944f9f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/handler_cont_helpers.hpp @@ -0,0 +1,45 @@ +// +// detail/handler_cont_helpers.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/handler_invoke_helpers.hpp b/tools/sdk/include/asio/asio/detail/handler_invoke_helpers.hpp new file mode 100644 index 00000000000..4c65c4c530c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/handler_invoke_helpers.hpp @@ -0,0 +1,57 @@ +// +// detail/handler_invoke_helpers.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/handler_tracking.hpp b/tools/sdk/include/asio/asio/detail/handler_tracking.hpp new file mode 100644 index 00000000000..83f820eca95 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/handler_tracking.hpp @@ -0,0 +1,238 @@ +// +// detail/handler_tracking.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/handler_type_requirements.hpp b/tools/sdk/include/asio/asio/detail/handler_type_requirements.hpp new file mode 100644 index 00000000000..9181bc515e2 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/handler_type_requirements.hpp @@ -0,0 +1,556 @@ +// +// detail/handler_type_requirements.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/handler_work.hpp b/tools/sdk/include/asio/asio/detail/handler_work.hpp new file mode 100644 index 00000000000..cce5c4b6de2 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/handler_work.hpp @@ -0,0 +1,95 @@ +// +// detail/handler_work.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 + : executor_(associated_executor::get(handler)) + { + } + + static void start(Handler& handler) ASIO_NOEXCEPT + { + Executor ex(associated_executor::get(handler)); + ex.on_work_started(); + } + + ~handler_work() + { + executor_.on_work_finished(); + } + + template + void complete(Function& function, Handler& handler) + { + executor_.dispatch(ASIO_MOVE_CAST(Function)(function), + associated_allocator::get(handler)); + } + +private: + // Disallow copying and assignment. + handler_work(const handler_work&); + handler_work& operator=(const handler_work&); + + typename associated_executor::type 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/include/asio/asio/detail/hash_map.hpp b/tools/sdk/include/asio/asio/detail/hash_map.hpp new file mode 100644 index 00000000000..e70970d6b14 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/hash_map.hpp @@ -0,0 +1,331 @@ +// +// detail/hash_map.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/impl/dev_poll_reactor.hpp b/tools/sdk/include/asio/asio/detail/impl/dev_poll_reactor.hpp new file mode 100644 index 00000000000..4cd8aafec21 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/dev_poll_reactor.hpp @@ -0,0 +1,91 @@ +// +// detail/impl/dev_poll_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/impl/epoll_reactor.hpp b/tools/sdk/include/asio/asio/detail/impl/epoll_reactor.hpp new file mode 100644 index 00000000000..f990059d828 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/epoll_reactor.hpp @@ -0,0 +1,89 @@ +// +// detail/impl/epoll_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/impl/kqueue_reactor.hpp b/tools/sdk/include/asio/asio/detail/impl/kqueue_reactor.hpp new file mode 100644 index 00000000000..136d1678d34 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/kqueue_reactor.hpp @@ -0,0 +1,93 @@ +// +// detail/impl/kqueue_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/detail/impl/select_reactor.hpp b/tools/sdk/include/asio/asio/detail/impl/select_reactor.hpp new file mode 100644 index 00000000000..04a04d49f8c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/select_reactor.hpp @@ -0,0 +1,100 @@ +// +// detail/impl/select_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/impl/service_registry.hpp b/tools/sdk/include/asio/asio/detail/impl/service_registry.hpp new file mode 100644 index 00000000000..d4db589947b --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/service_registry.hpp @@ -0,0 +1,94 @@ +// +// detail/impl/service_registry.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/impl/strand_executor_service.hpp b/tools/sdk/include/asio/asio/detail/impl/strand_executor_service.hpp new file mode 100644 index 00000000000..0e18ca05ec9 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/strand_executor_service.hpp @@ -0,0 +1,179 @@ +// +// detail/impl/strand_executor_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/impl/strand_service.hpp b/tools/sdk/include/asio/asio/detail/impl/strand_service.hpp new file mode 100644 index 00000000000..da5b716946f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/strand_service.hpp @@ -0,0 +1,118 @@ +// +// detail/impl/strand_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/impl/win_iocp_io_context.hpp b/tools/sdk/include/asio/asio/detail/impl/win_iocp_io_context.hpp new file mode 100644 index 00000000000..44887d7c219 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/win_iocp_io_context.hpp @@ -0,0 +1,103 @@ +// +// detail/impl/win_iocp_io_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/impl/winrt_timer_scheduler.hpp b/tools/sdk/include/asio/asio/detail/impl/winrt_timer_scheduler.hpp new file mode 100644 index 00000000000..856378feb09 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/impl/winrt_timer_scheduler.hpp @@ -0,0 +1,92 @@ +// +// detail/impl/winrt_timer_scheduler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_) + { + io_context_.post_immediate_completion(op, false); + return; + } + + bool earliest = queue.enqueue_timer(time, timer, op); + io_context_.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(); + io_context_.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/include/asio/asio/detail/io_control.hpp b/tools/sdk/include/asio/asio/detail/io_control.hpp new file mode 100644 index 00000000000..12f35e096fb --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/io_control.hpp @@ -0,0 +1,84 @@ +// +// detail/io_control.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/is_buffer_sequence.hpp b/tools/sdk/include/asio/asio/detail/is_buffer_sequence.hpp new file mode 100644 index 00000000000..42ad0ebe1a2 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/is_buffer_sequence.hpp @@ -0,0 +1,239 @@ +// +// detail/is_buffer_sequence.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(); +}; + +template +struct buffer_sequence_memfns_derived + : T, buffer_sequence_memfns_base +{ +}; + +template +struct buffer_sequence_memfns_check +{ +}; + +template +char (&begin_memfn_helper(...))[2]; + +template +char begin_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::begin>*); + +template +char (&end_memfn_helper(...))[2]; + +template +char end_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::end>*); + +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 (&buffer_element_type_helper(...))[2]; + +#if defined(ASIO_HAS_DECL_TYPE) + +template +char buffer_element_type_helper(T* t, + typename enable_if::value>::type*); + +#else // defined(ASIO_HAS_DECL_TYPE) + +template +char buffer_element_type_helper( + typename T::const_iterator*, + typename enable_if::value>::type*); + +#endif // defined(ASIO_HAS_DECL_TYPE) + +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)) != 1 && + sizeof(end_memfn_helper(0)) != 1 && + sizeof(buffer_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 + : 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 + : conditional::value, + is_dynamic_buffer_class, + 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/include/asio/asio/detail/is_executor.hpp b/tools/sdk/include/asio/asio/detail/is_executor.hpp new file mode 100644 index 00000000000..4584dd04bf6 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/is_executor.hpp @@ -0,0 +1,126 @@ +// +// detail/is_executor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/keyword_tss_ptr.hpp b/tools/sdk/include/asio/asio/detail/keyword_tss_ptr.hpp new file mode 100644 index 00000000000..2ae651ab282 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/keyword_tss_ptr.hpp @@ -0,0 +1,70 @@ +// +// detail/keyword_tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/kqueue_reactor.hpp b/tools/sdk/include/asio/asio/detail/kqueue_reactor.hpp new file mode 100644 index 00000000000..43cb9f9351c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/kqueue_reactor.hpp @@ -0,0 +1,242 @@ +// +// detail/kqueue_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/detail/limits.hpp b/tools/sdk/include/asio/asio/detail/limits.hpp new file mode 100644 index 00000000000..d32470d2d35 --- /dev/null +++ b/tools/sdk/include/asio/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/include/asio/asio/detail/local_free_on_block_exit.hpp b/tools/sdk/include/asio/asio/detail/local_free_on_block_exit.hpp new file mode 100644 index 00000000000..eba6b7771d0 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/local_free_on_block_exit.hpp @@ -0,0 +1,59 @@ +// +// detail/local_free_on_block_exit.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/macos_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/macos_fenced_block.hpp new file mode 100644 index 00000000000..bbac270a46c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/macos_fenced_block.hpp @@ -0,0 +1,62 @@ +// +// detail/macos_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/memory.hpp b/tools/sdk/include/asio/asio/detail/memory.hpp new file mode 100644 index 00000000000..b1ec4975faf --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/memory.hpp @@ -0,0 +1,70 @@ +// +// detail/memory.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/mutex.hpp b/tools/sdk/include/asio/asio/detail/mutex.hpp new file mode 100644 index 00000000000..2f8f0b1329b --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/mutex.hpp @@ -0,0 +1,48 @@ +// +// detail/mutex.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/noncopyable.hpp b/tools/sdk/include/asio/asio/detail/noncopyable.hpp new file mode 100644 index 00000000000..0c038e11ed0 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/noncopyable.hpp @@ -0,0 +1,43 @@ +// +// detail/noncopyable.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_event.hpp b/tools/sdk/include/asio/asio/detail/null_event.hpp new file mode 100644 index 00000000000..5686a41e74a --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_event.hpp @@ -0,0 +1,100 @@ +// +// detail/null_event.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/null_fenced_block.hpp new file mode 100644 index 00000000000..0275326b177 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_fenced_block.hpp @@ -0,0 +1,47 @@ +// +// detail/null_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_global.hpp b/tools/sdk/include/asio/asio/detail/null_global.hpp new file mode 100644 index 00000000000..727dd3f4989 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_global.hpp @@ -0,0 +1,59 @@ +// +// detail/null_global.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_mutex.hpp b/tools/sdk/include/asio/asio/detail/null_mutex.hpp new file mode 100644 index 00000000000..afe3fc03251 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_mutex.hpp @@ -0,0 +1,64 @@ +// +// detail/null_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_reactor.hpp b/tools/sdk/include/asio/asio/detail/null_reactor.hpp new file mode 100644 index 00000000000..ca3c5fde662 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_reactor.hpp @@ -0,0 +1,68 @@ +// +// detail/null_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_signal_blocker.hpp b/tools/sdk/include/asio/asio/detail/null_signal_blocker.hpp new file mode 100644 index 00000000000..edfe820519e --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_signal_blocker.hpp @@ -0,0 +1,69 @@ +// +// detail/null_signal_blocker.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_socket_service.hpp b/tools/sdk/include/asio/asio/detail/null_socket_service.hpp new file mode 100644 index 00000000000..109c6c7bd36 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_socket_service.hpp @@ -0,0 +1,508 @@ +// +// detail/null_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_context.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 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(asio::io_context& io_context) + : service_base >(io_context), + io_context_(io_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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + io_context_.post(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) + { + asio::error_code ec = asio::error::operation_not_supported; + io_context_.post(detail::bind_handler(handler, ec)); + } + +private: + asio::io_context& io_context_; +}; + +} // 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/include/asio/asio/detail/null_static_mutex.hpp b/tools/sdk/include/asio/asio/detail/null_static_mutex.hpp new file mode 100644 index 00000000000..36ec04f7e3d --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_static_mutex.hpp @@ -0,0 +1,60 @@ +// +// detail/null_static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_thread.hpp b/tools/sdk/include/asio/asio/detail/null_thread.hpp new file mode 100644 index 00000000000..7291ba3841d --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_thread.hpp @@ -0,0 +1,67 @@ +// +// detail/null_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/null_tss_ptr.hpp b/tools/sdk/include/asio/asio/detail/null_tss_ptr.hpp new file mode 100644 index 00000000000..323967d6cf4 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/null_tss_ptr.hpp @@ -0,0 +1,68 @@ +// +// detail/null_tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/object_pool.hpp b/tools/sdk/include/asio/asio/detail/object_pool.hpp new file mode 100644 index 00000000000..e1a3c5482a9 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/object_pool.hpp @@ -0,0 +1,171 @@ +// +// detail/object_pool.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/old_win_sdk_compat.hpp b/tools/sdk/include/asio/asio/detail/old_win_sdk_compat.hpp new file mode 100644 index 00000000000..bfb109e7f7b --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/old_win_sdk_compat.hpp @@ -0,0 +1,214 @@ +// +// detail/old_win_sdk_compat.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/op_queue.hpp b/tools/sdk/include/asio/asio/detail/op_queue.hpp new file mode 100644 index 00000000000..6219f797d7f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/op_queue.hpp @@ -0,0 +1,162 @@ +// +// detail/op_queue.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/operation.hpp b/tools/sdk/include/asio/asio/detail/operation.hpp new file mode 100644 index 00000000000..811e54d4aa7 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/operation.hpp @@ -0,0 +1,38 @@ +// +// detail/operation.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/pipe_select_interrupter.hpp b/tools/sdk/include/asio/asio/detail/pipe_select_interrupter.hpp new file mode 100644 index 00000000000..55d7db4916e --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/pipe_select_interrupter.hpp @@ -0,0 +1,89 @@ +// +// detail/pipe_select_interrupter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/pop_options.hpp b/tools/sdk/include/asio/asio/detail/pop_options.hpp new file mode 100644 index 00000000000..1045612bf40 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/pop_options.hpp @@ -0,0 +1,135 @@ +// +// detail/pop_options.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the 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) +# pragma GCC visibility pop +# 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) +# pragma GCC visibility pop +# 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) +# pragma GCC visibility pop +# 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/include/asio/asio/detail/posix_event.hpp b/tools/sdk/include/asio/asio/detail/posix_event.hpp new file mode 100644 index 00000000000..121065efbbc --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/posix_event.hpp @@ -0,0 +1,162 @@ +// +// detail/posix_event.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/posix_fd_set_adapter.hpp b/tools/sdk/include/asio/asio/detail/posix_fd_set_adapter.hpp new file mode 100644 index 00000000000..95042d66314 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/posix_fd_set_adapter.hpp @@ -0,0 +1,118 @@ +// +// detail/posix_fd_set_adapter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/posix_global.hpp b/tools/sdk/include/asio/asio/detail/posix_global.hpp new file mode 100644 index 00000000000..7ee0a715450 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/posix_global.hpp @@ -0,0 +1,80 @@ +// +// detail/posix_global.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/posix_mutex.hpp b/tools/sdk/include/asio/asio/detail/posix_mutex.hpp new file mode 100644 index 00000000000..c0d9fc9b777 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/posix_mutex.hpp @@ -0,0 +1,76 @@ +// +// detail/posix_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/posix_signal_blocker.hpp b/tools/sdk/include/asio/asio/detail/posix_signal_blocker.hpp new file mode 100644 index 00000000000..fab5eb1296c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/posix_signal_blocker.hpp @@ -0,0 +1,85 @@ +// +// detail/posix_signal_blocker.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/posix_static_mutex.hpp b/tools/sdk/include/asio/asio/detail/posix_static_mutex.hpp new file mode 100644 index 00000000000..59b86c1885c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/posix_static_mutex.hpp @@ -0,0 +1,64 @@ +// +// detail/posix_static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/posix_thread.hpp b/tools/sdk/include/asio/asio/detail/posix_thread.hpp new file mode 100644 index 00000000000..1817af28d40 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/posix_thread.hpp @@ -0,0 +1,109 @@ +// +// detail/posix_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/posix_tss_ptr.hpp b/tools/sdk/include/asio/asio/detail/posix_tss_ptr.hpp new file mode 100644 index 00000000000..a3096b43e6c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/posix_tss_ptr.hpp @@ -0,0 +1,79 @@ +// +// detail/posix_tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/push_options.hpp b/tools/sdk/include/asio/asio/detail/push_options.hpp new file mode 100644 index 00000000000..0a3e9798049 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/push_options.hpp @@ -0,0 +1,175 @@ +// +// detail/push_options.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the 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) +# pragma GCC visibility push (default) +# 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) +# pragma GCC visibility push (default) +# 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) +# pragma GCC visibility push (default) +# 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/include/asio/asio/detail/reactive_descriptor_service.hpp b/tools/sdk/include/asio/asio/detail/reactive_descriptor_service.hpp new file mode 100644 index 00000000000..e8668639968 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_descriptor_service.hpp @@ -0,0 +1,388 @@ +// +// detail/reactive_descriptor_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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 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( + asio::io_context& io_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) + { + 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); + + 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) + { + 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); + + 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) + { + 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); + + 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) + { + 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); + + 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) + { + 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); + + 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/include/asio/asio/detail/reactive_null_buffers_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_null_buffers_op.hpp new file mode 100644 index 00000000000..740826928dd --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_null_buffers_op.hpp @@ -0,0 +1,90 @@ +// +// detail/reactive_null_buffers_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactor_op(&reactive_null_buffers_op::do_perform, + &reactive_null_buffers_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_NULL_BUFFERS_OP_HPP diff --git a/tools/sdk/include/asio/asio/detail/reactive_serial_port_service.hpp b/tools/sdk/include/asio/asio/detail/reactive_serial_port_service.hpp new file mode 100644 index 00000000000..6fddd9f1aac --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_serial_port_service.hpp @@ -0,0 +1,236 @@ +// +// detail/reactive_serial_port_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/io_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 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( + asio::io_context& io_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) + { + descriptor_service_.async_write_some(impl, buffers, handler); + } + + // 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) + { + descriptor_service_.async_read_some(impl, buffers, handler); + } + +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/include/asio/asio/detail/reactive_socket_accept_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_accept_op.hpp new file mode 100644 index 00000000000..4a98f047f78 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_accept_op.hpp @@ -0,0 +1,217 @@ +// +// detail/reactive_socket_accept_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactive_socket_accept_op_base(socket, state, peer, + protocol, peer_endpoint, &reactive_socket_accept_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + reactive_socket_accept_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + // 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_; +}; + +#if defined(ASIO_HAS_MOVE) + +template +class reactive_socket_move_accept_op : + private Protocol::socket, + public reactive_socket_accept_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_move_accept_op); + + reactive_socket_move_accept_op(io_context& ioc, socket_type socket, + socket_ops::state_type state, const Protocol& protocol, + typename Protocol::endpoint* peer_endpoint, Handler& handler) + : Protocol::socket(ioc), + reactive_socket_accept_op_base( + socket, state, *this, protocol, peer_endpoint, + &reactive_socket_move_accept_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + reactive_socket_move_accept_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + // 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(typename Protocol::socket)(*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: + Handler handler_; +}; + +#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/include/asio/asio/detail/reactive_socket_connect_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_connect_op.hpp new file mode 100644 index 00000000000..76164b2a8ed --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_connect_op.hpp @@ -0,0 +1,113 @@ +// +// detail/reactive_socket_connect_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactive_socket_connect_op_base(socket, + &reactive_socket_connect_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + reactive_socket_connect_op* o + (static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_CONNECT_OP_HPP diff --git a/tools/sdk/include/asio/asio/detail/reactive_socket_recv_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_recv_op.hpp new file mode 100644 index 00000000000..04bd266f9cf --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_recv_op.hpp @@ -0,0 +1,135 @@ +// +// detail/reactive_socket_recv_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactive_socket_recv_op_base(socket, state, + buffers, flags, &reactive_socket_recv_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + reactive_socket_recv_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_RECV_OP_HPP diff --git a/tools/sdk/include/asio/asio/detail/reactive_socket_recvfrom_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_recvfrom_op.hpp new file mode 100644 index 00000000000..3d4fa4cadf7 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_recvfrom_op.hpp @@ -0,0 +1,138 @@ +// +// detail/reactive_socket_recvfrom_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactive_socket_recvfrom_op_base( + socket, protocol_type, buffers, endpoint, flags, + &reactive_socket_recvfrom_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + reactive_socket_recvfrom_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_RECVFROM_OP_HPP diff --git a/tools/sdk/include/asio/asio/detail/reactive_socket_recvmsg_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_recvmsg_op.hpp new file mode 100644 index 00000000000..f473274724a --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_recvmsg_op.hpp @@ -0,0 +1,132 @@ +// +// detail/reactive_socket_recvmsg_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactive_socket_recvmsg_op_base(socket, buffers, + in_flags, out_flags, &reactive_socket_recvmsg_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + reactive_socket_recvmsg_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_RECVMSG_OP_HPP diff --git a/tools/sdk/include/asio/asio/detail/reactive_socket_send_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_send_op.hpp new file mode 100644 index 00000000000..bd550d9c5ea --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_send_op.hpp @@ -0,0 +1,134 @@ +// +// detail/reactive_socket_send_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactive_socket_send_op_base(socket, + state, buffers, flags, &reactive_socket_send_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + reactive_socket_send_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_SEND_OP_HPP diff --git a/tools/sdk/include/asio/asio/detail/reactive_socket_sendto_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_sendto_op.hpp new file mode 100644 index 00000000000..c97554d7b68 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_sendto_op.hpp @@ -0,0 +1,130 @@ +// +// detail/reactive_socket_sendto_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactive_socket_sendto_op_base(socket, + buffers, endpoint, flags, &reactive_socket_sendto_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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. + reactive_socket_sendto_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_SENDTO_OP_HPP diff --git a/tools/sdk/include/asio/asio/detail/reactive_socket_service.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_service.hpp new file mode 100644 index 00000000000..15a4fdb588e --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_service.hpp @@ -0,0 +1,526 @@ +// +// detail/reactive_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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 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(asio::io_context& io_context) + : service_base >(io_context), + reactive_socket_service_base(io_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) + { + 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) + { + 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); + + 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) + { + 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); + + 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) + { + 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); + + 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) + { + 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); + + 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; + } + +#if defined(ASIO_HAS_MOVE) + // Accept a new connection. + typename Protocol::socket accept(implementation_type& impl, + io_context* peer_io_context, endpoint_type* peer_endpoint, + asio::error_code& ec) + { + typename Protocol::socket peer( + peer_io_context ? *peer_io_context : io_context_); + + 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 peer; + } +#endif // 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_accept(implementation_type& impl, Socket& peer, + endpoint_type* peer_endpoint, Handler& handler) + { + 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); + + 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_accept(implementation_type& impl, + asio::io_context* peer_io_context, + endpoint_type* peer_endpoint, Handler& handler) + { + 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_context ? *peer_io_context : io_context_, + impl.socket_, impl.state_, impl.protocol_, peer_endpoint, handler); + + 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) + { + 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); + + 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/include/asio/asio/detail/reactive_socket_service_base.hpp b/tools/sdk/include/asio/asio/detail/reactive_socket_service_base.hpp new file mode 100644 index 00000000000..ccd497e8013 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_socket_service_base.hpp @@ -0,0 +1,511 @@ +// +// detail/reactive_socket_service_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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( + asio::io_context& io_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); + + // 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) + { + 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); + + 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) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_send_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_, buffers, flags, handler); + + 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) + { + 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); + + 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) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_recv_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_, buffers, flags, handler); + + 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) + { + 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); + + 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) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_recvmsg_op 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); + + 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) + { + 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); + + 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 io_context that owns this socket service. + io_context& io_context_; + + // 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/include/asio/asio/detail/reactive_wait_op.hpp b/tools/sdk/include/asio/asio/detail/reactive_wait_op.hpp new file mode 100644 index 00000000000..616d8b11504 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactive_wait_op.hpp @@ -0,0 +1,90 @@ +// +// detail/reactive_wait_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactor_op(&reactive_wait_op::do_perform, + &reactive_wait_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_WAIT_OP_HPP diff --git a/tools/sdk/include/asio/asio/detail/reactor.hpp b/tools/sdk/include/asio/asio/detail/reactor.hpp new file mode 100644 index 00000000000..47502764f05 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactor.hpp @@ -0,0 +1,32 @@ +// +// detail/reactor.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/reactor_fwd.hpp b/tools/sdk/include/asio/asio/detail/reactor_fwd.hpp new file mode 100644 index 00000000000..a4555c3db00 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactor_fwd.hpp @@ -0,0 +1,40 @@ +// +// detail/reactor_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/reactor_op.hpp b/tools/sdk/include/asio/asio/detail/reactor_op.hpp new file mode 100644 index 00000000000..faad1a775cc --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactor_op.hpp @@ -0,0 +1,65 @@ +// +// detail/reactor_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/reactor_op_queue.hpp b/tools/sdk/include/asio/asio/detail/reactor_op_queue.hpp new file mode 100644 index 00000000000..898f31d1c6c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/reactor_op_queue.hpp @@ -0,0 +1,168 @@ +// +// detail/reactor_op_queue.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/recycling_allocator.hpp b/tools/sdk/include/asio/asio/detail/recycling_allocator.hpp new file mode 100644 index 00000000000..964af1da6f1 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/recycling_allocator.hpp @@ -0,0 +1,104 @@ +// +// detail/recycling_allocator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(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(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 > +{ + 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/include/asio/asio/detail/regex_fwd.hpp b/tools/sdk/include/asio/asio/detail/regex_fwd.hpp new file mode 100644 index 00000000000..dcf7d06e3c7 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/regex_fwd.hpp @@ -0,0 +1,35 @@ +// +// detail/regex_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/resolve_endpoint_op.hpp b/tools/sdk/include/asio/asio/detail/resolve_endpoint_op.hpp new file mode 100644 index 00000000000..8eee2f98bf4 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/resolve_endpoint_op.hpp @@ -0,0 +1,122 @@ +// +// detail/resolve_endpoint_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_context.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" + +#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; + + resolve_endpoint_op(socket_ops::weak_cancel_token_type cancel_token, + const endpoint_type& endpoint, io_context_impl& ioc, Handler& handler) + : resolve_op(&resolve_endpoint_op::do_complete), + cancel_token_(cancel_token), + endpoint_(endpoint), + io_context_impl_(ioc), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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 operation object. + resolve_endpoint_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + if (owner && owner != &o->io_context_impl_) + { + // 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->io_context_impl_.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_; + io_context_impl& io_context_impl_; + Handler handler_; + 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/include/asio/asio/detail/resolve_op.hpp b/tools/sdk/include/asio/asio/detail/resolve_op.hpp new file mode 100644 index 00000000000..a528aa825f3 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/resolve_op.hpp @@ -0,0 +1,45 @@ +// +// detail/resolve_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/resolve_query_op.hpp b/tools/sdk/include/asio/asio/detail/resolve_query_op.hpp new file mode 100644 index 00000000000..0ec5a32101c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/resolve_query_op.hpp @@ -0,0 +1,134 @@ +// +// detail/resolve_query_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_context.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" + +#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; + + resolve_query_op(socket_ops::weak_cancel_token_type cancel_token, + const query_type& query, io_context_impl& ioc, Handler& handler) + : resolve_op(&resolve_query_op::do_complete), + cancel_token_(cancel_token), + query_(query), + io_context_impl_(ioc), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + addrinfo_(0) + { + handler_work::start(handler_); + } + + ~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->io_context_impl_) + { + // 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->io_context_impl_.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_); + + 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_; + io_context_impl& io_context_impl_; + Handler handler_; + 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/include/asio/asio/detail/resolver_service.hpp b/tools/sdk/include/asio/asio/detail/resolver_service.hpp new file mode 100644 index 00000000000..11a94d1353d --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/resolver_service.hpp @@ -0,0 +1,145 @@ +// +// detail/resolver_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 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(asio::io_context& io_context) + : service_base >(io_context), + resolver_service_base(io_context) + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + this->base_shutdown(); + } + + // Perform any fork-related housekeeping. + void notify_fork(asio::io_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) + { + // 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, io_context_impl_, handler); + + ASIO_HANDLER_CREATION((io_context_impl_.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) + { + // 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, io_context_impl_, handler); + + ASIO_HANDLER_CREATION((io_context_impl_.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/include/asio/asio/detail/resolver_service_base.hpp b/tools/sdk/include/asio/asio/detail/resolver_service_base.hpp new file mode 100644 index 00000000000..10a792241c5 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/resolver_service_base.hpp @@ -0,0 +1,140 @@ +// +// detail/resolver_service_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/executor_work_guard.hpp" +#include "asio/io_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" + +#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(asio::io_context& io_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( + asio::io_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 io_context in a thread. + class work_io_context_runner; + + // Start the work thread if it's not already running. + ASIO_DECL void start_work_thread(); + + // The io_context implementation used to post completions. + io_context_impl& io_context_impl_; + +private: + // Mutex to protect access to internal data. + asio::detail::mutex mutex_; + + // Private io_context used for performing asynchronous host resolution. + asio::detail::scoped_ptr work_io_context_; + + // The work io_context implementation used to post completions. + io_context_impl& work_io_context_impl_; + + // Work for the private io_context to perform. + asio::executor_work_guard< + asio::io_context::executor_type> work_; + + // 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/include/asio/asio/detail/scheduler.hpp b/tools/sdk/include/asio/asio/detail/scheduler.hpp new file mode 100644 index 00000000000..10c29b7edf2 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/scheduler.hpp @@ -0,0 +1,213 @@ +// +// detail/scheduler.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_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); + + // 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 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_; +}; + +} // 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/include/asio/asio/detail/scheduler_operation.hpp b/tools/sdk/include/asio/asio/detail/scheduler_operation.hpp new file mode 100644 index 00000000000..1c2ce02ecc7 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/scheduler_operation.hpp @@ -0,0 +1,78 @@ +// +// detail/scheduler_operation.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/scheduler_thread_info.hpp b/tools/sdk/include/asio/asio/detail/scheduler_thread_info.hpp new file mode 100644 index 00000000000..2ffe013bcb1 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/scheduler_thread_info.hpp @@ -0,0 +1,40 @@ +// +// detail/scheduler_thread_info.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/scoped_lock.hpp b/tools/sdk/include/asio/asio/detail/scoped_lock.hpp new file mode 100644 index 00000000000..6cbce381402 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/scoped_lock.hpp @@ -0,0 +1,101 @@ +// +// detail/scoped_lock.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/scoped_ptr.hpp b/tools/sdk/include/asio/asio/detail/scoped_ptr.hpp new file mode 100644 index 00000000000..3449c53b72b --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/scoped_ptr.hpp @@ -0,0 +1,87 @@ +// +// detail/scoped_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/select_interrupter.hpp b/tools/sdk/include/asio/asio/detail/select_interrupter.hpp new file mode 100644 index 00000000000..c58327387b6 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/select_interrupter.hpp @@ -0,0 +1,46 @@ +// +// detail/select_interrupter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/select_reactor.hpp b/tools/sdk/include/asio/asio/detail/select_reactor.hpp new file mode 100644 index 00000000000..09965492785 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/select_reactor.hpp @@ -0,0 +1,238 @@ +// +// detail/select_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/service_registry.hpp b/tools/sdk/include/asio/asio/detail/service_registry.hpp new file mode 100644 index 00000000000..cda63072f08 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/service_registry.hpp @@ -0,0 +1,164 @@ +// +// detail/service_registry.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/signal_blocker.hpp b/tools/sdk/include/asio/asio/detail/signal_blocker.hpp new file mode 100644 index 00000000000..b684295775f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/signal_blocker.hpp @@ -0,0 +1,44 @@ +// +// detail/signal_blocker.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/signal_handler.hpp b/tools/sdk/include/asio/asio/detail/signal_handler.hpp new file mode 100644 index 00000000000..d1c99105a7e --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/signal_handler.hpp @@ -0,0 +1,86 @@ +// +// detail/signal_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : signal_op(&signal_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. + signal_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. + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SIGNAL_HANDLER_HPP diff --git a/tools/sdk/include/asio/asio/detail/signal_init.hpp b/tools/sdk/include/asio/asio/detail/signal_init.hpp new file mode 100644 index 00000000000..814ff519624 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/signal_init.hpp @@ -0,0 +1,47 @@ +// +// detail/signal_init.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/signal_op.hpp b/tools/sdk/include/asio/asio/detail/signal_op.hpp new file mode 100644 index 00000000000..c4e364c14e5 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/signal_op.hpp @@ -0,0 +1,49 @@ +// +// detail/signal_op.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/signal_set_service.hpp b/tools/sdk/include/asio/asio/detail/signal_set_service.hpp new file mode 100644 index 00000000000..a18ab709356 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/signal_set_service.hpp @@ -0,0 +1,217 @@ +// +// detail/signal_set_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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_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 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(asio::io_context& io_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::io_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) + { + // 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); + + ASIO_HANDLER_CREATION((io_context_.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 io_context instance used for dispatching handlers. + io_context_impl& io_context_; + +#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/include/asio/asio/detail/socket_holder.hpp b/tools/sdk/include/asio/asio/detail/socket_holder.hpp new file mode 100644 index 00000000000..99b081f7129 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/socket_holder.hpp @@ -0,0 +1,98 @@ +// +// detail/socket_holder.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/socket_ops.hpp b/tools/sdk/include/asio/asio/detail/socket_ops.hpp new file mode 100644 index 00000000000..815b0d1c8e0 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/socket_ops.hpp @@ -0,0 +1,337 @@ +// +// detail/socket_ops.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/socket_option.hpp b/tools/sdk/include/asio/asio/detail/socket_option.hpp new file mode 100644 index 00000000000..6852d56993e --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/socket_option.hpp @@ -0,0 +1,316 @@ +// +// detail/socket_option.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/socket_select_interrupter.hpp b/tools/sdk/include/asio/asio/detail/socket_select_interrupter.hpp new file mode 100644 index 00000000000..540b2aebd40 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/socket_select_interrupter.hpp @@ -0,0 +1,92 @@ +// +// detail/socket_select_interrupter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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__) + +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_SOCKET_SELECT_INTERRUPTER_HPP diff --git a/tools/sdk/include/asio/asio/detail/socket_types.hpp b/tools/sdk/include/asio/asio/detail/socket_types.hpp new file mode 100644 index 00000000000..6f1abb20536 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/socket_types.hpp @@ -0,0 +1,419 @@ +// +// detail/socket_types.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/solaris_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/solaris_fenced_block.hpp new file mode 100644 index 00000000000..d48f6a374cd --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/solaris_fenced_block.hpp @@ -0,0 +1,62 @@ +// +// detail/solaris_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/static_mutex.hpp b/tools/sdk/include/asio/asio/detail/static_mutex.hpp new file mode 100644 index 00000000000..8f2bc02a084 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/static_mutex.hpp @@ -0,0 +1,52 @@ +// +// detail/static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/std_event.hpp b/tools/sdk/include/asio/asio/detail/std_event.hpp new file mode 100644 index 00000000000..5639ecdd432 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/std_event.hpp @@ -0,0 +1,176 @@ +// +// detail/std_event.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/std_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/std_fenced_block.hpp new file mode 100644 index 00000000000..0d8ade028e6 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/std_fenced_block.hpp @@ -0,0 +1,62 @@ +// +// detail/std_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/std_global.hpp b/tools/sdk/include/asio/asio/detail/std_global.hpp new file mode 100644 index 00000000000..0c5173e6bd7 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/std_global.hpp @@ -0,0 +1,70 @@ +// +// detail/std_global.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/std_mutex.hpp b/tools/sdk/include/asio/asio/detail/std_mutex.hpp new file mode 100644 index 00000000000..159049e8c29 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/std_mutex.hpp @@ -0,0 +1,73 @@ +// +// detail/std_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/std_static_mutex.hpp b/tools/sdk/include/asio/asio/detail/std_static_mutex.hpp new file mode 100644 index 00000000000..e9c9dc5ee3a --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/std_static_mutex.hpp @@ -0,0 +1,81 @@ +// +// detail/std_static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/std_thread.hpp b/tools/sdk/include/asio/asio/detail/std_thread.hpp new file mode 100644 index 00000000000..a240308d8a0 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/std_thread.hpp @@ -0,0 +1,71 @@ +// +// detail/std_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/strand_executor_service.hpp b/tools/sdk/include/asio/asio/detail/strand_executor_service.hpp new file mode 100644 index 00000000000..67e84274ba2 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/strand_executor_service.hpp @@ -0,0 +1,142 @@ +// +// detail/strand_executor_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/strand_service.hpp b/tools/sdk/include/asio/asio/detail/strand_service.hpp new file mode 100644 index 00000000000..edc14a0f7d5 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/strand_service.hpp @@ -0,0 +1,142 @@ +// +// detail/strand_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/string_view.hpp b/tools/sdk/include/asio/asio/detail/string_view.hpp new file mode 100644 index 00000000000..f09cebc2b64 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/string_view.hpp @@ -0,0 +1,47 @@ +// +// detail/string_view.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/thread.hpp b/tools/sdk/include/asio/asio/detail/thread.hpp new file mode 100644 index 00000000000..ea556dba65f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/thread.hpp @@ -0,0 +1,60 @@ +// +// detail/thread.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/thread_context.hpp b/tools/sdk/include/asio/asio/detail/thread_context.hpp new file mode 100644 index 00000000000..88b4f311571 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/thread_context.hpp @@ -0,0 +1,42 @@ +// +// detail/thread_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/thread_group.hpp b/tools/sdk/include/asio/asio/detail/thread_group.hpp new file mode 100644 index 00000000000..1e400b03737 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/thread_group.hpp @@ -0,0 +1,89 @@ +// +// detail/thread_group.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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; + } + } + +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/include/asio/asio/detail/thread_info_base.hpp b/tools/sdk/include/asio/asio/detail/thread_info_base.hpp new file mode 100644 index 00000000000..1b2220745b2 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/thread_info_base.hpp @@ -0,0 +1,121 @@ +// +// detail/thread_info_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 awaitee_tag + { + enum { mem_index = 1 }; + }; + + 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 = 2 }; + 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/include/asio/asio/detail/throw_error.hpp b/tools/sdk/include/asio/asio/detail/throw_error.hpp new file mode 100644 index 00000000000..5dd87855aad --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/throw_error.hpp @@ -0,0 +1,53 @@ +// +// detail/throw_error.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/throw_exception.hpp b/tools/sdk/include/asio/asio/detail/throw_exception.hpp new file mode 100644 index 00000000000..f9f7bfb9f17 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/throw_exception.hpp @@ -0,0 +1,51 @@ +// +// detail/throw_exception.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/timer_queue.hpp b/tools/sdk/include/asio/asio/detail/timer_queue.hpp new file mode 100644 index 00000000000..380e7791eb9 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/timer_queue.hpp @@ -0,0 +1,358 @@ +// +// detail/timer_queue.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + { + heap_.pop_back(); + } + else + { + swap_heap(index, heap_.size() - 1); + 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/include/asio/asio/detail/timer_queue_base.hpp b/tools/sdk/include/asio/asio/detail/timer_queue_base.hpp new file mode 100644 index 00000000000..4af995f237c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/timer_queue_base.hpp @@ -0,0 +1,68 @@ +// +// detail/timer_queue_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/timer_queue_ptime.hpp b/tools/sdk/include/asio/asio/detail/timer_queue_ptime.hpp new file mode 100644 index 00000000000..84e83385e69 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/timer_queue_ptime.hpp @@ -0,0 +1,99 @@ +// +// detail/timer_queue_ptime.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/timer_queue_set.hpp b/tools/sdk/include/asio/asio/detail/timer_queue_set.hpp new file mode 100644 index 00000000000..0ea372ae5ad --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/timer_queue_set.hpp @@ -0,0 +1,66 @@ +// +// detail/timer_queue_set.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/timer_scheduler.hpp b/tools/sdk/include/asio/asio/detail/timer_scheduler.hpp new file mode 100644 index 00000000000..b1f8df45d4f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/timer_scheduler.hpp @@ -0,0 +1,35 @@ +// +// detail/timer_scheduler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/timer_scheduler_fwd.hpp b/tools/sdk/include/asio/asio/detail/timer_scheduler_fwd.hpp new file mode 100644 index 00000000000..80bae5034f8 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/timer_scheduler_fwd.hpp @@ -0,0 +1,40 @@ +// +// detail/timer_scheduler_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/tss_ptr.hpp b/tools/sdk/include/asio/asio/detail/tss_ptr.hpp new file mode 100644 index 00000000000..e628abe9dfa --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/tss_ptr.hpp @@ -0,0 +1,69 @@ +// +// detail/tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/type_traits.hpp b/tools/sdk/include/asio/asio/detail/type_traits.hpp new file mode 100644 index 00000000000..edf09281a48 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/type_traits.hpp @@ -0,0 +1,86 @@ +// +// detail/type_traits.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 +#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::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::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/include/asio/asio/detail/variadic_templates.hpp b/tools/sdk/include/asio/asio/detail/variadic_templates.hpp new file mode 100644 index 00000000000..d54eb4e4b10 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/variadic_templates.hpp @@ -0,0 +1,119 @@ +// +// detail/variadic_templates.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_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_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/include/asio/asio/detail/wait_handler.hpp b/tools/sdk/include/asio/asio/detail/wait_handler.hpp new file mode 100644 index 00000000000..bd3dc24419f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/wait_handler.hpp @@ -0,0 +1,85 @@ +// +// detail/wait_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/memory.hpp" +#include "asio/detail/wait_op.hpp" +#include "asio/io_context.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) + : wait_op(&wait_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. + wait_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. + 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_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_WAIT_HANDLER_HPP diff --git a/tools/sdk/include/asio/asio/detail/wait_op.hpp b/tools/sdk/include/asio/asio/detail/wait_op.hpp new file mode 100644 index 00000000000..1a3017baeef --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/wait_op.hpp @@ -0,0 +1,45 @@ +// +// detail/wait_op.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_event.hpp b/tools/sdk/include/asio/asio/detail/win_event.hpp new file mode 100644 index 00000000000..859cdee7b92 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_event.hpp @@ -0,0 +1,151 @@ +// +// detail/win_event.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_fd_set_adapter.hpp b/tools/sdk/include/asio/asio/detail/win_fd_set_adapter.hpp new file mode 100644 index 00000000000..8d5e700e226 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_fd_set_adapter.hpp @@ -0,0 +1,149 @@ +// +// detail/win_fd_set_adapter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_fenced_block.hpp b/tools/sdk/include/asio/asio/detail/win_fenced_block.hpp new file mode 100644 index 00000000000..1ce6e13b9c1 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_fenced_block.hpp @@ -0,0 +1,90 @@ +// +// detail/win_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_global.hpp b/tools/sdk/include/asio/asio/detail/win_global.hpp new file mode 100644 index 00000000000..3b15a32d301 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_global.hpp @@ -0,0 +1,73 @@ +// +// detail/win_global.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_; + static 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 +T* win_global_impl::ptr_ = 0; + +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_); + win_global_impl::ptr_ = new T; + win_global_impl::tss_ptr_ = win_global_impl::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/include/asio/asio/detail/win_iocp_handle_read_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_handle_read_op.hpp new file mode 100644 index 00000000000..88e3f6c7b50 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_handle_read_op.hpp @@ -0,0 +1,111 @@ +// +// detail/win_iocp_handle_read_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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) + : operation(&win_iocp_handle_read_op::do_complete), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_handle_service.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_handle_service.hpp new file mode 100644 index 00000000000..849fe8f1883 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_handle_service.hpp @@ -0,0 +1,323 @@ +// +// detail/win_iocp_handle_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/io_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 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(asio::io_context& io_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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_handle_write_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler); + + 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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_handle_write_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler); + + 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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_handle_read_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler); + + 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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_handle_read_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler); + + 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); + template + void async_write_some_at(implementation_type& impl, uint64_t offset, + const null_buffers& buffers, Handler& handler); + 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); + template + void async_read_some_at(implementation_type& impl, uint64_t offset, + const null_buffers& buffers, Handler& handler); + + // 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/include/asio/asio/detail/win_iocp_handle_write_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_handle_write_op.hpp new file mode 100644 index 00000000000..d7bb9443a7c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_handle_write_op.hpp @@ -0,0 +1,103 @@ +// +// detail/win_iocp_handle_write_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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) + : operation(&win_iocp_handle_write_op::do_complete), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_io_context.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_io_context.hpp new file mode 100644 index 00000000000..11bf58b7d1a --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_io_context.hpp @@ -0,0 +1,328 @@ +// +// detail/win_iocp_io_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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); + + // 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_; + + // 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_null_buffers_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_null_buffers_op.hpp new file mode 100644 index 00000000000..db70cb28a14 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_null_buffers_op.hpp @@ -0,0 +1,121 @@ +// +// detail/win_iocp_null_buffers_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : 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)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_operation.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_operation.hpp new file mode 100644 index 00000000000..81d43f07f64 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_operation.hpp @@ -0,0 +1,96 @@ +// +// detail/win_iocp_operation.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_iocp_overlapped_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_overlapped_op.hpp new file mode 100644 index 00000000000..2b2cc319b22 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_overlapped_op.hpp @@ -0,0 +1,90 @@ +// +// detail/win_iocp_overlapped_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : operation(&win_iocp_overlapped_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + 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 operation object. + win_iocp_overlapped_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_overlapped_ptr.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_overlapped_ptr.hpp new file mode 100644 index 00000000000..7a191143484 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_overlapped_ptr.hpp @@ -0,0 +1,143 @@ +// +// detail/win_iocp_overlapped_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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( + asio::io_context& io_context, ASIO_MOVE_ARG(Handler) handler) + : ptr_(0), + iocp_service_(0) + { + this->reset(io_context, 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(asio::io_context& io_context, Handler handler) + { + 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); + + ASIO_HANDLER_CREATION((io_context, *p.p, + "io_context", &io_context.impl_, 0, "overlapped")); + + io_context.impl_.work_started(); + reset(); + ptr_ = p.p; + p.v = p.p = 0; + iocp_service_ = &io_context.impl_; + } + + // 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: + 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/include/asio/asio/detail/win_iocp_serial_port_service.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_serial_port_service.hpp new file mode 100644 index 00000000000..ac06348ecfd --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_serial_port_service.hpp @@ -0,0 +1,230 @@ +// +// detail/win_iocp_serial_port_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/io_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 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( + asio::io_context& io_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) + { + handle_service_.async_write_some(impl, buffers, handler); + } + + // 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) + { + handle_service_.async_read_some(impl, buffers, handler); + } + +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/include/asio/asio/detail/win_iocp_socket_accept_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_socket_accept_op.hpp new file mode 100644 index 00000000000..18e73356ca5 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_socket_accept_op.hpp @@ -0,0 +1,297 @@ +// +// detail/win_iocp_socket_accept_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : 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)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +#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, asio::io_context& peer_io_context, + typename Protocol::endpoint* peer_endpoint, + bool enable_connection_aborted, Handler& handler) + : operation(&win_iocp_socket_move_accept_op::do_complete), + socket_service_(socket_service), + socket_(socket), + peer_(peer_io_context), + protocol_(protocol), + peer_endpoint_(peer_endpoint), + enable_connection_aborted_(enable_connection_aborted), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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(typename Protocol::socket)(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: + win_iocp_socket_service_base& socket_service_; + socket_type socket_; + socket_holder new_socket_; + typename Protocol::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_; +}; + +#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/include/asio/asio/detail/win_iocp_socket_connect_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_socket_connect_op.hpp new file mode 100644 index 00000000000..e0c52dc9758 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_socket_connect_op.hpp @@ -0,0 +1,127 @@ +// +// detail/win_iocp_socket_connect_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : win_iocp_socket_connect_op_base(socket, + &win_iocp_socket_connect_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_socket_recv_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_socket_recv_op.hpp new file mode 100644 index 00000000000..41595405db3 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_socket_recv_op.hpp @@ -0,0 +1,117 @@ +// +// detail/win_iocp_socket_recv_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : operation(&win_iocp_socket_recv_op::do_complete), + state_(state), + cancel_token_(cancel_token), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_socket_recvfrom_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_socket_recvfrom_op.hpp new file mode 100644 index 00000000000..843ce5bba5f --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_socket_recvfrom_op.hpp @@ -0,0 +1,125 @@ +// +// detail/win_iocp_socket_recvfrom_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : 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)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_socket_recvmsg_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_socket_recvmsg_op.hpp new file mode 100644 index 00000000000..78f36b7f343 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_socket_recvmsg_op.hpp @@ -0,0 +1,118 @@ +// +// detail/win_iocp_socket_recvmsg_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : operation(&win_iocp_socket_recvmsg_op::do_complete), + cancel_token_(cancel_token), + buffers_(buffers), + out_flags_(out_flags), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_socket_send_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_socket_send_op.hpp new file mode 100644 index 00000000000..e1c7ab93c5c --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_socket_send_op.hpp @@ -0,0 +1,111 @@ +// +// detail/win_iocp_socket_send_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : operation(&win_iocp_socket_send_op::do_complete), + cancel_token_(cancel_token), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_iocp_socket_service.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_socket_service.hpp new file mode 100644 index 00000000000..3f01b4d3e77 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_socket_service.hpp @@ -0,0 +1,599 @@ +// +// detail/win_iocp_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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 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(asio::io_context& io_context) + : service_base >(io_context), + win_iocp_socket_service_base(io_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) + { + 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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_send_op 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); + + ASIO_HANDLER_CREATION((io_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) + { + // 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); + + ASIO_HANDLER_CREATION((io_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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_recvfrom_op< + MutableBufferSequence, endpoint_type, Handler> 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); + + ASIO_HANDLER_CREATION((io_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) + { + // 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); + + ASIO_HANDLER_CREATION((io_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; + } + +#if defined(ASIO_HAS_MOVE) + // Accept a new connection. + typename Protocol::socket accept(implementation_type& impl, + io_context* peer_io_context, endpoint_type* peer_endpoint, + asio::error_code& ec) + { + typename Protocol::socket peer( + peer_io_context ? *peer_io_context : io_context_); + + 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 peer; + } +#endif // 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_accept(implementation_type& impl, Socket& peer, + endpoint_type* peer_endpoint, Handler& handler) + { + // 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); + + ASIO_HANDLER_CREATION((io_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_accept(implementation_type& impl, + asio::io_context* peer_io_context, + endpoint_type* peer_endpoint, Handler& handler) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_move_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_, impl.protocol_, + peer_io_context ? *peer_io_context : io_context_, + peer_endpoint, enable_connection_aborted, handler); + + ASIO_HANDLER_CREATION((io_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) + { + // 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); + + ASIO_HANDLER_CREATION((io_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/include/asio/asio/detail/win_iocp_socket_service_base.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_socket_service_base.hpp new file mode 100644 index 00000000000..ef1d7180e36 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_socket_service_base.hpp @@ -0,0 +1,591 @@ +// +// detail/win_iocp_socket_service_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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( + asio::io_context& io_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); + + // 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) + { + 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); + + ASIO_HANDLER_CREATION((io_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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_send_op 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); + + ASIO_HANDLER_CREATION((io_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) + { + // 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); + + ASIO_HANDLER_CREATION((io_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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_recv_op 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); + + ASIO_HANDLER_CREATION((io_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) + { + // 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); + + ASIO_HANDLER_CREATION((io_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) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_recvmsg_op 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); + + ASIO_HANDLER_CREATION((io_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) + { + // 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); + + ASIO_HANDLER_CREATION((io_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 io_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 io_context used to obtain the reactor, if required. + asio::io_context& io_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/include/asio/asio/detail/win_iocp_thread_info.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_thread_info.hpp new file mode 100644 index 00000000000..13181e2ec6d --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_thread_info.hpp @@ -0,0 +1,34 @@ +// +// detail/win_iocp_thread_info.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_iocp_wait_op.hpp b/tools/sdk/include/asio/asio/detail/win_iocp_wait_op.hpp new file mode 100644 index 00000000000..472eea38a32 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_iocp_wait_op.hpp @@ -0,0 +1,121 @@ +// +// detail/win_iocp_wait_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : reactor_op(&win_iocp_wait_op::do_perform, + &win_iocp_wait_op::do_complete), + cancel_token_(cancel_token), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/win_mutex.hpp b/tools/sdk/include/asio/asio/detail/win_mutex.hpp new file mode 100644 index 00000000000..ce52a2f7968 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_mutex.hpp @@ -0,0 +1,78 @@ +// +// detail/win_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_object_handle_service.hpp b/tools/sdk/include/asio/asio/detail/win_object_handle_service.hpp new file mode 100644 index 00000000000..1d8abc9c74a --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_object_handle_service.hpp @@ -0,0 +1,184 @@ +// +// detail/win_object_handle_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_object_handle_service : + public 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( + asio::io_context& io_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) + { + // 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); + + ASIO_HANDLER_CREATION((io_context_.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 io_context implementation used to post completions. + io_context_impl& io_context_; + + // 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/include/asio/asio/detail/win_static_mutex.hpp b/tools/sdk/include/asio/asio/detail/win_static_mutex.hpp new file mode 100644 index 00000000000..b16968862cc --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_static_mutex.hpp @@ -0,0 +1,74 @@ +// +// detail/win_static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_thread.hpp b/tools/sdk/include/asio/asio/detail/win_thread.hpp new file mode 100644 index 00000000000..8b28a90b679 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_thread.hpp @@ -0,0 +1,147 @@ +// +// detail/win_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/win_tss_ptr.hpp b/tools/sdk/include/asio/asio/detail/win_tss_ptr.hpp new file mode 100644 index 00000000000..4207108a30e --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/win_tss_ptr.hpp @@ -0,0 +1,79 @@ +// +// detail/win_tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/winapp_thread.hpp b/tools/sdk/include/asio/asio/detail/winapp_thread.hpp new file mode 100644 index 00000000000..69dcf08d4e1 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winapp_thread.hpp @@ -0,0 +1,124 @@ +// +// detail/winapp_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/wince_thread.hpp b/tools/sdk/include/asio/asio/detail/wince_thread.hpp new file mode 100644 index 00000000000..a2863f625da --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/wince_thread.hpp @@ -0,0 +1,124 @@ +// +// detail/wince_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/winrt_async_manager.hpp b/tools/sdk/include/asio/asio/detail/winrt_async_manager.hpp new file mode 100644 index 00000000000..e22ad52e2e7 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_async_manager.hpp @@ -0,0 +1,294 @@ +// +// detail/winrt_async_manager.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class winrt_async_manager + : public asio::detail::service_base +{ +public: + // Constructor. + winrt_async_manager(asio::io_context& io_context) + : asio::detail::service_base(io_context), + io_context_(use_service(io_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; + } + io_context_.post_deferred_completion(handler); + if (--outstanding_ops_ == 0) + promise_.set_value(); + }); + + io_context_.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; + } + io_context_.post_deferred_completion(handler); + if (--outstanding_ops_ == 0) + promise_.set_value(); + }); + + io_context_.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; + } + io_context_.post_deferred_completion(handler); + if (--outstanding_ops_ == 0) + promise_.set_value(); + }); + + io_context_.work_started(); + ++outstanding_ops_; + operation->Completed = on_completed; + } + +private: + // The io_context implementation used to post completed handlers. + io_context_impl& io_context_; + + // 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/include/asio/asio/detail/winrt_async_op.hpp b/tools/sdk/include/asio/asio/detail/winrt_async_op.hpp new file mode 100644 index 00000000000..75891a4ad1a --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_async_op.hpp @@ -0,0 +1,65 @@ +// +// detail/winrt_async_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/winrt_resolve_op.hpp b/tools/sdk/include/asio/asio/detail/winrt_resolve_op.hpp new file mode 100644 index 00000000000..07efd29d20d --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_resolve_op.hpp @@ -0,0 +1,118 @@ +// +// detail/winrt_resolve_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : winrt_async_op< + Windows::Foundation::Collections::IVectorView< + Windows::Networking::EndpointPair^>^>( + &winrt_resolve_op::do_complete), + query_(query), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/winrt_resolver_service.hpp b/tools/sdk/include/asio/asio/detail/winrt_resolver_service.hpp new file mode 100644 index 00000000000..aeb44485e57 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_resolver_service.hpp @@ -0,0 +1,198 @@ +// +// detail/winrt_resolver_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class winrt_resolver_service : + public 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(asio::io_context& io_context) + : service_base >(io_context), + io_context_(use_service(io_context)), + async_manager_(use_service(io_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(asio::io_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) + { + 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); + + ASIO_HANDLER_CREATION((io_context_.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()); + io_context_.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) + { + asio::error_code ec = asio::error::operation_not_supported; + const results_type results; + io_context_.get_io_context().post( + detail::bind_handler(handler, ec, results)); + } + +private: + io_context_impl& io_context_; + 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/include/asio/asio/detail/winrt_socket_connect_op.hpp b/tools/sdk/include/asio/asio/detail/winrt_socket_connect_op.hpp new file mode 100644 index 00000000000..f18b445f880 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_socket_connect_op.hpp @@ -0,0 +1,92 @@ +// +// detail/winrt_socket_connect_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : winrt_async_op(&winrt_socket_connect_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/winrt_socket_recv_op.hpp b/tools/sdk/include/asio/asio/detail/winrt_socket_recv_op.hpp new file mode 100644 index 00000000000..8f1fcf576f8 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_socket_recv_op.hpp @@ -0,0 +1,112 @@ +// +// detail/winrt_socket_recv_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : winrt_async_op( + &winrt_socket_recv_op::do_complete), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/winrt_socket_send_op.hpp b/tools/sdk/include/asio/asio/detail/winrt_socket_send_op.hpp new file mode 100644 index 00000000000..1148c24e4cf --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_socket_send_op.hpp @@ -0,0 +1,103 @@ +// +// detail/winrt_socket_send_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : winrt_async_op(&winrt_socket_send_op::do_complete), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + handler_work::start(handler_); + } + + 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_); + + 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_; +}; + +} // 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/include/asio/asio/detail/winrt_ssocket_service.hpp b/tools/sdk/include/asio/asio/detail/winrt_ssocket_service.hpp new file mode 100644 index 00000000000..603724a30e6 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_ssocket_service.hpp @@ -0,0 +1,241 @@ +// +// detail/winrt_ssocket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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 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(asio::io_context& io_context) + : service_base >(io_context), + winrt_ssocket_service_base(io_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) + { + 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; + } + + // 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) + { + 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); + + ASIO_HANDLER_CREATION((io_context_.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/include/asio/asio/detail/winrt_ssocket_service_base.hpp b/tools/sdk/include/asio/asio/detail/winrt_ssocket_service_base.hpp new file mode 100644 index 00000000000..61328d0a034 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_ssocket_service_base.hpp @@ -0,0 +1,359 @@ +// +// detail/winrt_ssocket_service_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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" + +#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( + asio::io_context& io_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); + + // 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; + } + + // Disable sends or receives on the socket. + asio::error_code shutdown(base_implementation_type&, + socket_base::shutdown_type, 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) + { + 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); + + ASIO_HANDLER_CREATION((io_context_.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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.get_io_context().post( + 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) + { + 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); + + ASIO_HANDLER_CREATION((io_context_.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) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + io_context_.get_io_context().post( + 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 io_context implementation used for delivering completions. + io_context_impl& io_context_; + + // 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/include/asio/asio/detail/winrt_timer_scheduler.hpp b/tools/sdk/include/asio/asio/detail/winrt_timer_scheduler.hpp new file mode 100644 index 00000000000..5dec7c0b696 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_timer_scheduler.hpp @@ -0,0 +1,137 @@ +// +// detail/winrt_timer_scheduler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/io_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 winrt_timer_scheduler + : public asio::detail::service_base +{ +public: + // Constructor. + ASIO_DECL winrt_timer_scheduler(asio::io_context& io_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( + asio::io_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 io_context implementation used to post completions. + io_context_impl& io_context_; + + // 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/include/asio/asio/detail/winrt_utils.hpp b/tools/sdk/include/asio/asio/detail/winrt_utils.hpp new file mode 100644 index 00000000000..22a24895834 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winrt_utils.hpp @@ -0,0 +1,106 @@ +// +// detail/winrt_utils.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/winsock_init.hpp b/tools/sdk/include/asio/asio/detail/winsock_init.hpp new file mode 100644 index 00000000000..9094363abd7 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/winsock_init.hpp @@ -0,0 +1,128 @@ +// +// detail/winsock_init.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/detail/work_dispatcher.hpp b/tools/sdk/include/asio/asio/detail/work_dispatcher.hpp new file mode 100644 index 00000000000..7abce497ba0 --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/work_dispatcher.hpp @@ -0,0 +1,72 @@ +// +// detail/work_dispatcher.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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: + work_dispatcher(Handler& handler) + : work_((get_associated_executor)(handler)), + handler_(ASIO_MOVE_CAST(Handler)(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/include/asio/asio/detail/wrapped_handler.hpp b/tools/sdk/include/asio/asio/detail/wrapped_handler.hpp new file mode 100644 index 00000000000..751f0ea830a --- /dev/null +++ b/tools/sdk/include/asio/asio/detail/wrapped_handler.hpp @@ -0,0 +1,291 @@ +// +// detail/wrapped_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/dispatch.hpp b/tools/sdk/include/asio/asio/dispatch.hpp new file mode 100644 index 00000000000..b8dfd69102b --- /dev/null +++ b/tools/sdk/include/asio/asio/dispatch.hpp @@ -0,0 +1,108 @@ +// +// dispatch.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 is queued for execution, and is never called + * from the current thread prior to returning from dispatch(). + * + * 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_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 is queued for execution, and is never called from the + * current thread prior to returning from dispatch(). + * + * 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_RESULT_TYPE(CompletionToken, void()) dispatch( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + 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_RESULT_TYPE(CompletionToken, void()) dispatch( + ExecutionContext& ctx, ASIO_MOVE_ARG(CompletionToken) token, + 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/include/asio/asio/error.hpp b/tools/sdk/include/asio/asio/error.hpp new file mode 100644 index 00000000000..2be9bdeed82 --- /dev/null +++ b/tools/sdk/include/asio/asio/error.hpp @@ -0,0 +1,356 @@ +// +// error.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/error_code.hpp b/tools/sdk/include/asio/asio/error_code.hpp new file mode 100644 index 00000000000..042ab85388b --- /dev/null +++ b/tools/sdk/include/asio/asio/error_code.hpp @@ -0,0 +1,206 @@ +// +// error_code.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/execution_context.hpp b/tools/sdk/include/asio/asio/execution_context.hpp new file mode 100644 index 00000000000..1476d19b5b4 --- /dev/null +++ b/tools/sdk/include/asio/asio/execution_context.hpp @@ -0,0 +1,411 @@ +// +// execution_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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; + +protected: + /// Constructor. + ASIO_DECL execution_context(); + + /// Destructor. + ASIO_DECL ~execution_context(); + + /// 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/include/asio/asio/executor.hpp b/tools/sdk/include/asio/asio/executor.hpp new file mode 100644 index 00000000000..e552cfbf2e3 --- /dev/null +++ b/tools/sdk/include/asio/asio/executor.hpp @@ -0,0 +1,341 @@ +// +// executor.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/executor_work_guard.hpp b/tools/sdk/include/asio/asio/executor_work_guard.hpp new file mode 100644 index 00000000000..1875f542b21 --- /dev/null +++ b/tools/sdk/include/asio/asio/executor_work_guard.hpp @@ -0,0 +1,170 @@ +// +// executor_work_guard.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + : 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/include/asio/asio/experimental.hpp b/tools/sdk/include/asio/asio/experimental.hpp new file mode 100644 index 00000000000..5765c37d0ee --- /dev/null +++ b/tools/sdk/include/asio/asio/experimental.hpp @@ -0,0 +1,22 @@ +// +// experimental.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXPERIMENTAL_HPP +#define ASIO_EXPERIMENTAL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/experimental/co_spawn.hpp" +#include "asio/experimental/detached.hpp" +#include "asio/experimental/redirect_error.hpp" + +#endif // ASIO_EXPERIMENTAL_HPP diff --git a/tools/sdk/include/asio/asio/experimental/co_spawn.hpp b/tools/sdk/include/asio/asio/experimental/co_spawn.hpp new file mode 100644 index 00000000000..cbf5bc525e1 --- /dev/null +++ b/tools/sdk/include/asio/asio/experimental/co_spawn.hpp @@ -0,0 +1,226 @@ +// +// experimental/co_spawn.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXPERIMENTAL_CO_SPAWN_HPP +#define ASIO_EXPERIMENTAL_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 +#include "asio/executor.hpp" +#include "asio/strand.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace experimental { +namespace detail { + +using std::experimental::coroutine_handle; + +template class awaiter; +template class awaitee_base; +template class awaitee; +template class await_handler_base; +template +auto co_spawn(const Executor& ex, F&& f, CompletionToken&& token); + +} // namespace detail + +namespace this_coro { + +/// Awaitable type that returns a completion token for the current coroutine. +struct token_t {}; + +/// Awaitable object that returns a completion token for the current coroutine. +constexpr inline token_t token() { return {}; } + +/// Awaitable type that returns the executor of the current coroutine. +struct executor_t {}; + +/// Awaitable object that returns the executor of the current coroutine. +constexpr inline executor_t executor() { return {}; } + +} // namespace this_coro + +/// A completion token that represents the currently executing coroutine. +/** + * The await_token class is used to represent the currently executing + * coroutine. An await_token may be passed as a handler to an asynchronous + * operation. For example: + * + * @code awaitable my_coroutine() + * { + * await_token token = co_await this_coro::token(); + * ... + * std::size_t n = co_await my_socket.async_read_some(buffer, token); + * ... + * } @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 await_token +{ +public: + /// The associated executor type. + typedef Executor executor_type; + + /// Copy constructor. + await_token(const await_token& other) noexcept + : awaiter_(other.awaiter_) + { + } + + /// Move constructor. + await_token(await_token&& other) noexcept + : awaiter_(std::exchange(other.awaiter_, nullptr)) + { + } + + /// Get the associated executor. + executor_type get_executor() const noexcept + { + return awaiter_->get_executor(); + } + +private: + // No assignment allowed. + await_token& operator=(const await_token&) = delete; + + template friend class detail::awaitee_base; + template friend class detail::await_handler_base; + + // Private constructor used by awaitee_base. + explicit await_token(detail::awaiter* a) + : awaiter_(a) + { + } + + detail::awaiter* awaiter_; +}; + +/// 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; + + /// Move constructor. + awaitable(awaitable&& other) noexcept + : awaitee_(std::exchange(other.awaitee_, nullptr)) + { + } + + /// Destructor + ~awaitable() + { + if (awaitee_) + { + detail::coroutine_handle< + detail::awaitee>::from_promise( + *awaitee_).destroy(); + } + } + +#if !defined(GENERATING_DOCUMENTATION) + + // Support for co_await keyword. + bool await_ready() const noexcept + { + return awaitee_->ready(); + } + + // Support for co_await keyword. + void await_suspend(detail::coroutine_handle> h) + { + awaitee_->attach_caller(h); + } + + // Support for co_await keyword. + template + void await_suspend(detail::coroutine_handle> h) + { + awaitee_->attach_caller(h); + } + + // Support for co_await keyword. + T await_resume() + { + return awaitee_->get(); + } + +#endif // !defined(GENERATING_DOCUMENTATION) + +private: + template friend class detail::awaitee; + template friend class detail::await_handler_base; + + // Not copy constructible or copy assignable. + awaitable(const awaitable&) = delete; + awaitable& operator=(const awaitable&) = delete; + + // Construct the awaitable from a coroutine's promise object. + explicit awaitable(detail::awaitee* a) : awaitee_(a) {} + + detail::awaitee* awaitee_; +}; + +/// Spawn a new thread of execution. +template ::value>::type> +inline auto co_spawn(const Executor& ex, F&& f, CompletionToken&& token) +{ + return detail::co_spawn(ex, std::forward(f), + std::forward(token)); +} + +/// Spawn a new thread of execution. +template ::value>::type> +inline auto co_spawn(ExecutionContext& ctx, F&& f, CompletionToken&& token) +{ + return detail::co_spawn(ctx.get_executor(), std::forward(f), + std::forward(token)); +} + +/// Spawn a new thread of execution. +template +inline auto co_spawn(const await_token& parent, + F&& f, CompletionToken&& token) +{ + return detail::co_spawn(parent.get_executor(), std::forward(f), + std::forward(token)); +} + +} // namespace experimental +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/experimental/impl/co_spawn.hpp" + +#endif // defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_EXPERIMENTAL_CO_SPAWN_HPP diff --git a/tools/sdk/include/asio/asio/experimental/detached.hpp b/tools/sdk/include/asio/asio/experimental/detached.hpp new file mode 100644 index 00000000000..d484f18fbaf --- /dev/null +++ b/tools/sdk/include/asio/asio/experimental/detached.hpp @@ -0,0 +1,65 @@ +// +// experimental/detached.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXPERIMENTAL_DETACHED_HPP +#define ASIO_EXPERIMENTAL_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 { +namespace experimental { + +/// 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::experimental::detached. For example: + + * @code my_socket.async_send(my_buffer, asio::experimental::detached); + * @endcode + */ +class detached_t +{ +public: + /// Constructor. + ASIO_CONSTEXPR detached_t() + { + } +}; + +/// A special value, similar to std::nothrow. +/** + * See the documentation for asio::experimental::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 experimental +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/experimental/impl/detached.hpp" + +#endif // ASIO_EXPERIMENTAL_DETACHED_HPP diff --git a/tools/sdk/include/asio/asio/experimental/impl/co_spawn.hpp b/tools/sdk/include/asio/asio/experimental/impl/co_spawn.hpp new file mode 100644 index 00000000000..8263eff96a5 --- /dev/null +++ b/tools/sdk/include/asio/asio/experimental/impl/co_spawn.hpp @@ -0,0 +1,876 @@ +// +// experimental/impl/co_spawn.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXPERIMENTAL_IMPL_CO_SPAWN_HPP +#define ASIO_EXPERIMENTAL_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 +#include +#include +#include +#include +#include +#include "asio/async_result.hpp" +#include "asio/detail/thread_context.hpp" +#include "asio/detail/thread_info_base.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/dispatch.hpp" +#include "asio/post.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace experimental { +namespace detail { + +// Promise object for coroutine at top of thread-of-execution "stack". +template +class awaiter +{ +public: + struct deleter + { + void operator()(awaiter* a) + { + if (a) + a->release(); + } + }; + + typedef std::unique_ptr ptr; + + typedef Executor executor_type; + + ~awaiter() + { + if (has_executor_) + static_cast(static_cast(executor_))->~Executor(); + } + + void set_executor(const Executor& ex) + { + new (&executor_) Executor(ex); + has_executor_ = true; + } + + executor_type get_executor() const noexcept + { + return *static_cast(static_cast(executor_)); + } + + awaiter* get_return_object() + { + return this; + } + + auto initial_suspend() + { + return std::experimental::suspend_always(); + } + + auto final_suspend() + { + return std::experimental::suspend_always(); + } + + void return_void() + { + } + + awaiter* add_ref() + { + ++ref_count_; + return this; + } + + void release() + { + if (--ref_count_ == 0) + coroutine_handle::from_promise(*this).destroy(); + } + + void unhandled_exception() + { + pending_exception_ = std::current_exception(); + } + + void rethrow_unhandled_exception() + { + if (pending_exception_) + { + std::exception_ptr ex = std::exchange(pending_exception_, nullptr); + std::rethrow_exception(ex); + } + } + +private: + std::size_t ref_count_ = 0; + std::exception_ptr pending_exception_ = nullptr; + alignas(Executor) unsigned char executor_[sizeof(Executor)]; + bool has_executor_ = false; +}; + +// Base promise for coroutines further down the thread-of-execution "stack". +template +class awaitee_base +{ +public: +#if !defined(ASIO_DISABLE_AWAITEE_RECYCLING) + void* operator new(std::size_t size) + { + return asio::detail::thread_info_base::allocate( + asio::detail::thread_info_base::awaitee_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::awaitee_tag(), + asio::detail::thread_context::thread_call_stack::top(), + pointer, size); + } +#endif // !defined(ASIO_DISABLE_AWAITEE_RECYCLING) + + auto initial_suspend() + { + return std::experimental::suspend_never(); + } + + struct final_suspender + { + awaitee_base* this_; + + bool await_ready() const noexcept + { + return false; + } + + void await_suspend(coroutine_handle) + { + this_->wake_caller(); + } + + void await_resume() const noexcept + { + } + }; + + auto final_suspend() + { + return final_suspender{this}; + } + + void set_except(std::exception_ptr e) + { + pending_exception_ = e; + } + + 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); + } + } + + awaiter* top() + { + return awaiter_; + } + + coroutine_handle caller() + { + return caller_; + } + + bool ready() const + { + return ready_; + } + + void wake_caller() + { + if (caller_) + caller_.resume(); + else + ready_ = true; + } + + class awaitable_executor + { + public: + explicit awaitable_executor(awaitee_base* a) + : this_(a) + { + } + + bool await_ready() const noexcept + { + return this_->awaiter_ != nullptr; + } + + template + void await_suspend(coroutine_handle> h) noexcept + { + this_->resume_on_attach_ = h; + } + + Executor await_resume() + { + return this_->awaiter_->get_executor(); + } + + private: + awaitee_base* this_; + }; + + awaitable_executor await_transform(this_coro::executor_t) noexcept + { + return awaitable_executor(this); + } + + class awaitable_token + { + public: + explicit awaitable_token(awaitee_base* a) + : this_(a) + { + } + + bool await_ready() const noexcept + { + return this_->awaiter_ != nullptr; + } + + template + void await_suspend(coroutine_handle> h) noexcept + { + this_->resume_on_attach_ = h; + } + + await_token await_resume() + { + return await_token(this_->awaiter_); + } + + private: + awaitee_base* this_; + }; + + awaitable_token await_transform(this_coro::token_t) noexcept + { + return awaitable_token(this); + } + + template + awaitable await_transform(awaitable& t) const + { + return std::move(t); + } + + template + awaitable await_transform(awaitable&& t) const + { + return std::move(t); + } + + std::experimental::suspend_always await_transform( + std::experimental::suspend_always) const + { + return std::experimental::suspend_always(); + } + + void attach_caller(coroutine_handle> h) + { + this->caller_ = h; + this->attach_callees(&h.promise()); + } + + template + void attach_caller(coroutine_handle> h) + { + this->caller_ = h; + if (h.promise().awaiter_) + this->attach_callees(h.promise().awaiter_); + else + h.promise().unattached_callee_ = this; + } + + void attach_callees(awaiter* a) + { + for (awaitee_base* curr = this; curr != nullptr; + curr = std::exchange(curr->unattached_callee_, nullptr)) + { + curr->awaiter_ = a; + if (curr->resume_on_attach_) + return std::exchange(curr->resume_on_attach_, nullptr).resume(); + } + } + +protected: + awaiter* awaiter_ = nullptr; + coroutine_handle caller_ = nullptr; + awaitee_base* unattached_callee_ = nullptr; + std::exception_ptr pending_exception_ = nullptr; + coroutine_handle resume_on_attach_ = nullptr; + bool ready_ = false; +}; + +// Promise object for coroutines further down the thread-of-execution "stack". +template +class awaitee + : public awaitee_base +{ +public: + awaitee() + { + } + + awaitee(awaitee&& other) noexcept + : awaitee_base(std::move(other)) + { + } + + ~awaitee() + { + if (has_result_) + static_cast(static_cast(result_))->~T(); + } + + awaitable get_return_object() + { + return awaitable(this); + }; + + template + void return_value(U&& u) + { + new (&result_) T(std::forward(u)); + has_result_ = true; + } + + 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; +}; + +// Promise object for coroutines further down the thread-of-execution "stack". +template +class awaitee + : public awaitee_base +{ +public: + awaitable get_return_object() + { + return awaitable(this); + }; + + void return_void() + { + } + + void get() + { + this->caller_ = nullptr; + this->rethrow_exception(); + } +}; + +template +class awaiter_task +{ +public: + typedef Executor executor_type; + + awaiter_task(awaiter* a) + : awaiter_(a->add_ref()) + { + } + + awaiter_task(awaiter_task&& other) noexcept + : awaiter_(std::exchange(other.awaiter_, nullptr)) + { + } + + ~awaiter_task() + { + if (awaiter_) + { + // Coroutine "stack unwinding" must be performed through the executor. + executor_type ex(awaiter_->get_executor()); + (post)(ex, + [a = std::move(awaiter_)]() mutable + { + typename awaiter::ptr(std::move(a)); + }); + } + } + + executor_type get_executor() const noexcept + { + return awaiter_->get_executor(); + } + +protected: + typename awaiter::ptr awaiter_; +}; + +template +class co_spawn_handler : public awaiter_task +{ +public: + using awaiter_task::awaiter_task; + + void operator()() + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + coroutine_handle>::from_promise(*ptr.get()).resume(); + } +}; + +template +class await_handler_base : public awaiter_task +{ +public: + typedef awaitable awaitable_type; + + await_handler_base(await_token token) + : awaiter_task(token.awaiter_), + awaitee_(nullptr) + { + } + + await_handler_base(await_handler_base&& other) noexcept + : awaiter_task(std::move(other)), + awaitee_(std::exchange(other.awaitee_, nullptr)) + { + } + + void attach_awaitee(const awaitable& a) + { + awaitee_ = a.awaitee_; + } + +protected: + awaitee* awaitee_; +}; + +template class await_handler; + +template +class await_handler + : public await_handler_base +{ +public: + using await_handler_base::await_handler_base; + + void operator()() + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + this->awaitee_->return_void(); + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +template +class await_handler + : public await_handler_base +{ +public: + typedef void return_type; + + using await_handler_base::await_handler_base; + + void operator()(const asio::error_code& ec) + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + if (ec) + { + this->awaitee_->set_except( + std::make_exception_ptr(asio::system_error(ec))); + } + else + this->awaitee_->return_void(); + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +template +class await_handler + : public await_handler_base +{ +public: + using await_handler_base::await_handler_base; + + void operator()(std::exception_ptr ex) + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + if (ex) + this->awaitee_->set_except(ex); + else + this->awaitee_->return_void(); + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +template +class await_handler + : public await_handler_base +{ +public: + using await_handler_base::await_handler_base; + + template + void operator()(Arg&& arg) + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + this->awaitee_->return_value(std::forward(arg)); + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +template +class await_handler + : public await_handler_base +{ +public: + using await_handler_base::await_handler_base; + + template + void operator()(const asio::error_code& ec, Arg&& arg) + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + if (ec) + { + this->awaitee_->set_except( + std::make_exception_ptr(asio::system_error(ec))); + } + else + this->awaitee_->return_value(std::forward(arg)); + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +template +class await_handler + : public await_handler_base +{ +public: + using await_handler_base::await_handler_base; + + template + void operator()(std::exception_ptr ex, Arg&& arg) + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + if (ex) + this->awaitee_->set_except(ex); + else + this->awaitee_->return_value(std::forward(arg)); + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +template +class await_handler + : public await_handler_base> +{ +public: + using await_handler_base>::await_handler_base; + + template + void operator()(Args&&... args) + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + this->awaitee_->return_value( + std::forward_as_tuple(std::forward(args)...)); + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +template +class await_handler + : public await_handler_base> +{ +public: + using await_handler_base>::await_handler_base; + + template + void operator()(const asio::error_code& ec, Args&&... args) + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + if (ec) + { + this->awaitee_->set_except( + std::make_exception_ptr(asio::system_error(ec))); + } + else + { + this->awaitee_->return_value( + std::forward_as_tuple(std::forward(args)...)); + } + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +template +class await_handler + : public await_handler_base> +{ +public: + using await_handler_base>::await_handler_base; + + template + void operator()(std::exception_ptr ex, Args&&... args) + { + typename awaiter::ptr ptr(std::move(this->awaiter_)); + if (ex) + this->awaitee_->set_except(ex); + else + { + this->awaitee_->return_value( + std::forward_as_tuple(std::forward(args)...)); + } + this->awaitee_->wake_caller(); + ptr->rethrow_unhandled_exception(); + } +}; + +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); +}; + +template +awaiter* co_spawn_entry_point(awaitable*, + executor_work_guard work_guard, F f, Handler handler) +{ + bool done = false; + + try + { + T t = co_await f(); + + done = true; + + (dispatch)(work_guard.get_executor(), + [handler = std::move(handler), t = std::move(t)]() mutable + { + handler(std::exception_ptr(), std::move(t)); + }); + } + catch (...) + { + if (done) + throw; + + (dispatch)(work_guard.get_executor(), + [handler = std::move(handler), e = std::current_exception()]() mutable + { + handler(e, T()); + }); + } +} + +template +awaiter* co_spawn_entry_point(awaitable*, + executor_work_guard work_guard, F f, Handler handler) +{ + std::exception_ptr e = nullptr; + + try + { + co_await f(); + } + catch (...) + { + e = std::current_exception(); + } + + (dispatch)(work_guard.get_executor(), + [handler = std::move(handler), e]() mutable + { + handler(e); + }); +} + +template +auto co_spawn(const Executor& ex, F&& f, CompletionToken&& token) +{ + typedef typename result_of::type awaitable_type; + typedef typename awaitable_type::executor_type executor_type; + typedef typename awaitable_signature::type signature_type; + + async_completion completion(token); + + executor_type ex2(ex); + auto work_guard = make_work_guard(completion.completion_handler, ex2); + + auto* a = (co_spawn_entry_point)( + static_cast(nullptr), std::move(work_guard), + std::forward(f), std::move(completion.completion_handler)); + + a->set_executor(ex2); + (post)(co_spawn_handler(a)); + + return completion.result.get(); +} + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable:4033) +#endif // defined(_MSC_VER) + +#if defined(_MSC_VER) +template T dummy_return() +{ + return std::move(*static_cast(nullptr)); +} + +template <> +inline void dummy_return() +{ +} +#endif // defined(_MSC_VER) + +template +inline Awaitable make_dummy_awaitable() +{ + for (;;) co_await std::experimental::suspend_always(); +#if defined(_MSC_VER) + co_return dummy_return(); +#endif // defined(_MSC_VER) +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif // defined(_MSC_VER) + +} // namespace detail +} // namespace experimental + +template +class async_result, R(Args...)> +{ +public: + typedef experimental::detail::await_handler< + Executor, typename decay::type...> completion_handler_type; + + typedef typename experimental::detail::await_handler< + Executor, Args...>::awaitable_type return_type; + + async_result(completion_handler_type& h) + : awaitable_(experimental::detail::make_dummy_awaitable()) + { + h.attach_awaitee(awaitable_); + } + + return_type get() + { + return std::move(awaitable_); + } + +private: + return_type awaitable_; +}; + +#if !defined(ASIO_NO_DEPRECATED) + +template +struct handler_type, R(Args...)> +{ + typedef experimental::detail::await_handler< + Executor, typename decay::type...> type; +}; + +template +class async_result> +{ +public: + typedef typename experimental::detail::await_handler< + Executor, Args...>::awaitable_type type; + + async_result(experimental::detail::await_handler& h) + : awaitable_(experimental::detail::make_dummy_awaitable()) + { + h.attach_awaitee(awaitable_); + } + + type get() + { + return std::move(awaitable_); + } + +private: + type awaitable_; +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +} // namespace asio + +namespace std { namespace experimental { + +template +struct coroutine_traits< + asio::experimental::detail::awaiter*, Args...> +{ + typedef asio::experimental::detail::awaiter promise_type; +}; + +template +struct coroutine_traits< + asio::experimental::awaitable, Args...> +{ + typedef asio::experimental::detail::awaitee promise_type; +}; + +}} // namespace std::experimental + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_EXPERIMENTAL_IMPL_CO_SPAWN_HPP diff --git a/tools/sdk/include/asio/asio/experimental/impl/detached.hpp b/tools/sdk/include/asio/asio/experimental/impl/detached.hpp new file mode 100644 index 00000000000..6ce88872e22 --- /dev/null +++ b/tools/sdk/include/asio/asio/experimental/impl/detached.hpp @@ -0,0 +1,91 @@ +// +// experimental/impl/detached.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXPERIMENTAL_IMPL_DETACHED_HPP +#define ASIO_EXPERIMENTAL_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/handler_type.hpp" +#include "asio/system_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace experimental { +namespace detail { + + // Class to adapt a detached_t as a completion handler. + class detached_handler + { + public: + 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_BYVAL_PARAMS(n)) \ + { \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_DETACHED_DEF) +#undef ASIO_PRIVATE_DETACHED_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + }; + +} // namespace detail +} // namespace experimental + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct async_result +{ + typedef asio::experimental::detail::detached_handler + completion_handler_type; + + typedef void return_type; + + explicit async_result(completion_handler_type&) + { + } + + void get() + { + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_EXPERIMENTAL_IMPL_DETACHED_HPP diff --git a/tools/sdk/include/asio/asio/experimental/impl/redirect_error.hpp b/tools/sdk/include/asio/asio/experimental/impl/redirect_error.hpp new file mode 100644 index 00000000000..d3b97facc91 --- /dev/null +++ b/tools/sdk/include/asio/asio/experimental/impl/redirect_error.hpp @@ -0,0 +1,294 @@ +// +// experimental/impl/redirect_error.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXPERIMENTAL_IMPL_REDIRECT_ERROR_HPP +#define ASIO_EXPERIMENTAL_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/handler_type.hpp" +#include "asio/system_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace experimental { +namespace detail { + +// Class to adapt a redirect_error_t as a completion handler. +template +class redirect_error_handler +{ +public: + template + redirect_error_handler(redirect_error_t e) + : ec_(e.ec_), + handler_(ASIO_MOVE_CAST(CompletionToken)(e.token_)) + { + } + + 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 +} // namespace experimental + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct async_result, Signature> + : async_result::type> +{ + typedef experimental::detail::redirect_error_handler< + typename async_result::type> + ::completion_handler_type> completion_handler_type; + + explicit async_result(completion_handler_type& h) + : async_result::type>(h.handler_) + { + } +}; + +#if !defined(ASIO_NO_DEPRECATED) + +template +struct handler_type, Signature> +{ + typedef experimental::detail::redirect_error_handler< + typename async_result::type> + ::completion_handler_type> type; +}; + +template +struct async_result > + : async_result +{ + explicit async_result( + experimental::detail::redirect_error_handler& h) + : async_result(h.handler_) + { + } +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +template +struct associated_executor< + experimental::detail::redirect_error_handler, Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const experimental::detail::redirect_error_handler& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +template +struct associated_allocator< + experimental::detail::redirect_error_handler, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const experimental::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_EXPERIMENTAL_IMPL_REDIRECT_ERROR_HPP diff --git a/tools/sdk/include/asio/asio/experimental/redirect_error.hpp b/tools/sdk/include/asio/asio/experimental/redirect_error.hpp new file mode 100644 index 00000000000..30e81cf5a28 --- /dev/null +++ b/tools/sdk/include/asio/asio/experimental/redirect_error.hpp @@ -0,0 +1,67 @@ +// +// experimental/redirect_error.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXPERIMENTAL_REDIRECT_ERROR_HPP +#define ASIO_EXPERIMENTAL_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 { +namespace experimental { + +/// 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( + CompletionToken&& completion_token, asio::error_code& ec) +{ + return redirect_error_t::type>( + ASIO_MOVE_CAST(CompletionToken)(completion_token), ec); +} + +} // namespace experimental +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/experimental/impl/redirect_error.hpp" + +#endif // ASIO_EXPERIMENTAL_REDIRECT_ERROR_HPP diff --git a/tools/sdk/include/asio/asio/generic/basic_endpoint.hpp b/tools/sdk/include/asio/asio/generic/basic_endpoint.hpp new file mode 100644 index 00000000000..73aa151d627 --- /dev/null +++ b/tools/sdk/include/asio/asio/generic/basic_endpoint.hpp @@ -0,0 +1,193 @@ +// +// generic/basic_endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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() + { + } + + /// 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/include/asio/asio/generic/datagram_protocol.hpp b/tools/sdk/include/asio/asio/generic/datagram_protocol.hpp new file mode 100644 index 00000000000..8678ad85bcc --- /dev/null +++ b/tools/sdk/include/asio/asio/generic/datagram_protocol.hpp @@ -0,0 +1,123 @@ +// +// generic/datagram_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 + { + return ASIO_OS_DEF(SOCK_DGRAM); + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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/include/asio/asio/generic/detail/endpoint.hpp b/tools/sdk/include/asio/asio/generic/detail/endpoint.hpp new file mode 100644 index 00000000000..190beb14c64 --- /dev/null +++ b/tools/sdk/include/asio/asio/generic/detail/endpoint.hpp @@ -0,0 +1,133 @@ +// +// generic/detail/endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/generic/raw_protocol.hpp b/tools/sdk/include/asio/asio/generic/raw_protocol.hpp new file mode 100644 index 00000000000..b83dca6e32c --- /dev/null +++ b/tools/sdk/include/asio/asio/generic/raw_protocol.hpp @@ -0,0 +1,121 @@ +// +// generic/raw_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 + { + return ASIO_OS_DEF(SOCK_RAW); + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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/include/asio/asio/generic/seq_packet_protocol.hpp b/tools/sdk/include/asio/asio/generic/seq_packet_protocol.hpp new file mode 100644 index 00000000000..f92a4c8f89f --- /dev/null +++ b/tools/sdk/include/asio/asio/generic/seq_packet_protocol.hpp @@ -0,0 +1,122 @@ +// +// generic/seq_packet_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 + { + return ASIO_OS_DEF(SOCK_SEQPACKET); + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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/include/asio/asio/generic/stream_protocol.hpp b/tools/sdk/include/asio/asio/generic/stream_protocol.hpp new file mode 100644 index 00000000000..8349f25bc71 --- /dev/null +++ b/tools/sdk/include/asio/asio/generic/stream_protocol.hpp @@ -0,0 +1,127 @@ +// +// generic/stream_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 + { + return ASIO_OS_DEF(SOCK_STREAM); + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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/include/asio/asio/handler_alloc_hook.hpp b/tools/sdk/include/asio/asio/handler_alloc_hook.hpp new file mode 100644 index 00000000000..d7fe2b01fa5 --- /dev/null +++ b/tools/sdk/include/asio/asio/handler_alloc_hook.hpp @@ -0,0 +1,81 @@ +// +// handler_alloc_hook.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/handler_continuation_hook.hpp b/tools/sdk/include/asio/asio/handler_continuation_hook.hpp new file mode 100644 index 00000000000..d41d10595f3 --- /dev/null +++ b/tools/sdk/include/asio/asio/handler_continuation_hook.hpp @@ -0,0 +1,54 @@ +// +// handler_continuation_hook.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/handler_invoke_hook.hpp b/tools/sdk/include/asio/asio/handler_invoke_hook.hpp new file mode 100644 index 00000000000..ee618e5ef63 --- /dev/null +++ b/tools/sdk/include/asio/asio/handler_invoke_hook.hpp @@ -0,0 +1,85 @@ +// +// handler_invoke_hook.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/handler_type.hpp b/tools/sdk/include/asio/asio/handler_type.hpp new file mode 100644 index 00000000000..bc0d3051405 --- /dev/null +++ b/tools/sdk/include/asio/asio/handler_type.hpp @@ -0,0 +1,50 @@ +// +// handler_type.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_TYPE_HPP +#define ASIO_HANDLER_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/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// (Deprecated: Use two-parameter version of async_result.) Default handler +/// type traits provided for all completion token types. +/** + * The handler_type traits class is used for determining the concrete handler + * type to be used for an asynchronous operation. It allows the handler type 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. + */ +template +struct handler_type +{ + /// The handler type for the specific signature. + typedef typename conditional< + is_same::type>::value, + decay, + handler_type::type, Signature> + >::type::type type; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_HANDLER_TYPE_HPP diff --git a/tools/sdk/include/asio/asio/high_resolution_timer.hpp b/tools/sdk/include/asio/asio/high_resolution_timer.hpp new file mode 100644 index 00000000000..0549cc2569c --- /dev/null +++ b/tools/sdk/include/asio/asio/high_resolution_timer.hpp @@ -0,0 +1,44 @@ +// +// high_resolution_timer.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/impl/buffered_read_stream.hpp b/tools/sdk/include/asio/asio/impl/buffered_read_stream.hpp new file mode 100644 index 00000000000..e0ed20e4c20 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/buffered_read_stream.hpp @@ -0,0 +1,429 @@ +// +// impl/buffered_read_stream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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_); + } +} // 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_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +buffered_read_stream::async_fill( + ASIO_MOVE_ARG(ReadHandler) handler) +{ + // 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; + + async_completion init(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), + detail::buffered_fill_handler( + storage_, previous_size, init.completion_handler)); + + return init.result.get(); +} + +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_); + } +} // 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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +buffered_read_stream::async_read_some( + const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + // 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; + + async_completion init(handler); + + using asio::buffer_size; + if (buffer_size(buffers) == 0 || !storage_.empty()) + { + next_layer_.async_read_some(ASIO_MUTABLE_BUFFER(0, 0), + detail::buffered_read_some_handler< + MutableBufferSequence, ASIO_HANDLER_TYPE( + ReadHandler, void (asio::error_code, std::size_t))>( + storage_, buffers, init.completion_handler)); + } + else + { + this->async_fill(detail::buffered_read_some_handler< + MutableBufferSequence, ASIO_HANDLER_TYPE( + ReadHandler, void (asio::error_code, std::size_t))>( + storage_, buffers, init.completion_handler)); + } + + return init.result.get(); +} + +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/include/asio/asio/impl/buffered_write_stream.hpp b/tools/sdk/include/asio/asio/impl/buffered_write_stream.hpp new file mode 100644 index 00000000000..bc2d823ab7b --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/buffered_write_stream.hpp @@ -0,0 +1,411 @@ +// +// impl/buffered_write_stream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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_); + } +} // 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_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +buffered_write_stream::async_flush( + ASIO_MOVE_ARG(WriteHandler) handler) +{ + // 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; + + async_completion init(handler); + + async_write(next_layer_, buffer(storage_.data(), storage_.size()), + detail::buffered_flush_handler( + storage_, init.completion_handler)); + + return init.result.get(); +} + +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_); + } +} // 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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +buffered_write_stream::async_write_some( + const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) +{ + // 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; + + async_completion init(handler); + + using asio::buffer_size; + if (buffer_size(buffers) == 0 + || storage_.size() < storage_.capacity()) + { + next_layer_.async_write_some(ASIO_CONST_BUFFER(0, 0), + detail::buffered_write_some_handler< + ConstBufferSequence, ASIO_HANDLER_TYPE( + WriteHandler, void (asio::error_code, std::size_t))>( + storage_, buffers, init.completion_handler)); + } + else + { + this->async_flush(detail::buffered_write_some_handler< + ConstBufferSequence, ASIO_HANDLER_TYPE( + WriteHandler, void (asio::error_code, std::size_t))>( + storage_, buffers, init.completion_handler)); + } + + return init.result.get(); +} + +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/include/asio/asio/impl/connect.hpp b/tools/sdk/include/asio/asio/impl/connect.hpp new file mode 100644 index 00000000000..bff1913b1fb --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/connect.hpp @@ -0,0 +1,860 @@ +// +// impl/connect.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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) + { + typename EndpointSequence::const_iterator begin = endpoints_.begin(); + typename EndpointSequence::const_iterator iter = begin; + std::advance(iter, index_); + typename EndpointSequence::const_iterator end = endpoints_.end(); + + 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; + } + + 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)); + } + } + + //private: + 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 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; + } + + 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_); + } +} // 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, + Executor> +{ + typedef typename associated_executor< + RangeConnectHandler, Executor>::type type; + + static type get( + const detail::range_connect_op& h, + const Executor& ex = Executor()) 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, + Executor> +{ + typedef typename associated_executor< + IteratorConnectHandler, Executor>::type type; + + static type get( + const detail::iterator_connect_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_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*) +{ + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a RangeConnectHandler. + ASIO_RANGE_CONNECT_HANDLER_CHECK( + RangeConnectHandler, handler, typename Protocol::endpoint) type_check; + + async_completion + init(handler); + + detail::range_connect_op(s, + endpoints, detail::default_connect_condition(), + init.completion_handler)(asio::error_code(), 1); + + return init.result.get(); +} + +#if !defined(ASIO_NO_DEPRECATED) +template +inline ASIO_INITFN_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*) +{ + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a IteratorConnectHandler. + ASIO_ITERATOR_CONNECT_HANDLER_CHECK( + IteratorConnectHandler, handler, Iterator) type_check; + + async_completion init(handler); + + detail::iterator_connect_op(s, + begin, Iterator(), detail::default_connect_condition(), + init.completion_handler)(asio::error_code(), 1); + + return init.result.get(); +} +#endif // !defined(ASIO_NO_DEPRECATED) + +template +inline ASIO_INITFN_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, + Iterator begin, Iterator end, + ASIO_MOVE_ARG(IteratorConnectHandler) handler) +{ + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a IteratorConnectHandler. + ASIO_ITERATOR_CONNECT_HANDLER_CHECK( + IteratorConnectHandler, handler, Iterator) type_check; + + async_completion init(handler); + + detail::iterator_connect_op(s, + begin, end, detail::default_connect_condition(), + init.completion_handler)(asio::error_code(), 1); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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*) +{ + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a RangeConnectHandler. + ASIO_RANGE_CONNECT_HANDLER_CHECK( + RangeConnectHandler, handler, typename Protocol::endpoint) type_check; + + async_completion + init(handler); + + detail::range_connect_op(s, + endpoints, connect_condition, init.completion_handler)( + asio::error_code(), 1); + + return init.result.get(); +} + +#if !defined(ASIO_NO_DEPRECATED) +template +inline ASIO_INITFN_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*) +{ + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a IteratorConnectHandler. + ASIO_ITERATOR_CONNECT_HANDLER_CHECK( + IteratorConnectHandler, handler, Iterator) type_check; + + async_completion init(handler); + + detail::iterator_connect_op(s, + begin, Iterator(), connect_condition, init.completion_handler)( + asio::error_code(), 1); + + return init.result.get(); +} +#endif // !defined(ASIO_NO_DEPRECATED) + +template +inline ASIO_INITFN_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) +{ + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a IteratorConnectHandler. + ASIO_ITERATOR_CONNECT_HANDLER_CHECK( + IteratorConnectHandler, handler, Iterator) type_check; + + async_completion init(handler); + + detail::iterator_connect_op(s, + begin, end, connect_condition, init.completion_handler)( + asio::error_code(), 1); + + return init.result.get(); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_CONNECT_HPP diff --git a/tools/sdk/include/asio/asio/impl/defer.hpp b/tools/sdk/include/asio/asio/impl/defer.hpp new file mode 100644 index 00000000000..a27df0f134b --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/defer.hpp @@ -0,0 +1,77 @@ +// +// impl/defer.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 { + +template +ASIO_INITFN_RESULT_TYPE(CompletionToken, void()) defer( + ASIO_MOVE_ARG(CompletionToken) token) +{ + typedef ASIO_HANDLER_TYPE(CompletionToken, void()) handler; + + async_completion init(token); + + typename associated_executor::type ex( + (get_associated_executor)(init.completion_handler)); + + typename associated_allocator::type alloc( + (get_associated_allocator)(init.completion_handler)); + + ex.defer(ASIO_MOVE_CAST(handler)(init.completion_handler), alloc); + + return init.result.get(); +} + +template +ASIO_INITFN_RESULT_TYPE(CompletionToken, void()) defer( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + typedef ASIO_HANDLER_TYPE(CompletionToken, void()) handler; + + async_completion init(token); + + typename associated_allocator::type alloc( + (get_associated_allocator)(init.completion_handler)); + + ex.defer(detail::work_dispatcher(init.completion_handler), alloc); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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/include/asio/asio/impl/dispatch.hpp b/tools/sdk/include/asio/asio/impl/dispatch.hpp new file mode 100644 index 00000000000..4e11c6b2eba --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/dispatch.hpp @@ -0,0 +1,78 @@ +// +// impl/dispatch.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 { + +template +ASIO_INITFN_RESULT_TYPE(CompletionToken, void()) dispatch( + ASIO_MOVE_ARG(CompletionToken) token) +{ + typedef ASIO_HANDLER_TYPE(CompletionToken, void()) handler; + + async_completion init(token); + + typename associated_executor::type ex( + (get_associated_executor)(init.completion_handler)); + + typename associated_allocator::type alloc( + (get_associated_allocator)(init.completion_handler)); + + ex.dispatch(ASIO_MOVE_CAST(handler)(init.completion_handler), alloc); + + return init.result.get(); +} + +template +ASIO_INITFN_RESULT_TYPE(CompletionToken, void()) dispatch( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + typedef ASIO_HANDLER_TYPE(CompletionToken, void()) handler; + + async_completion init(token); + + typename associated_allocator::type alloc( + (get_associated_allocator)(init.completion_handler)); + + ex.dispatch(detail::work_dispatcher( + init.completion_handler), alloc); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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/include/asio/asio/impl/execution_context.hpp b/tools/sdk/include/asio/asio/impl/execution_context.hpp new file mode 100644 index 00000000000..3d1e457e74e --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/execution_context.hpp @@ -0,0 +1,107 @@ +// +// impl/execution_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 { + +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(GENERATING_DOCUMENTATION) +# 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) +#endif // !defined(GENERATING_DOCUMENTATION) + +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(); +} + +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/include/asio/asio/impl/executor.hpp b/tools/sdk/include/asio/asio/impl/executor.hpp new file mode 100644 index 00000000000..0fcf5f54a0e --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/executor.hpp @@ -0,0 +1,386 @@ +// +// impl/executor.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_op.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_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + op_ = new (p.v) op(ASIO_MOVE_CAST(F)(f), a); + p.v = 0; + } + + function(function&& other) + : op_(other.op_) + { + other.op_ = 0; + } + + ~function() + { + if (op_) + op_->destroy(); + } + + void operator()() + { + if (op_) + { + detail::scheduler_operation* op = op_; + op_ = 0; + op->complete(this, asio::error_code(), 0); + } + } + +private: + detail::scheduler_operation* op_; +}; + +#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/include/asio/asio/impl/io_context.hpp b/tools/sdk/include/asio/asio/impl/io_context.hpp new file mode 100644 index 00000000000..eaf580da7fd --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/io_context.hpp @@ -0,0 +1,343 @@ +// +// impl/io_context.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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" + +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 + +#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(); +} + +template +ASIO_INITFN_RESULT_TYPE(LegacyCompletionHandler, void ()) +io_context::dispatch(ASIO_MOVE_ARG(LegacyCompletionHandler) handler) +{ + // 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; + + async_completion init(handler); + + if (impl_.can_dispatch()) + { + detail::fenced_block b(detail::fenced_block::full); + asio_handler_invoke_helpers::invoke( + init.completion_handler, init.completion_handler); + } + else + { + // Allocate and construct an operation to wrap the handler. + typedef detail::completion_handler< + typename handler_type::type> op; + typename op::ptr p = { detail::addressof(init.completion_handler), + op::ptr::allocate(init.completion_handler), 0 }; + p.p = new (p.v) op(init.completion_handler); + + ASIO_HANDLER_CREATION((*this, *p.p, + "io_context", this, 0, "dispatch")); + + impl_.do_dispatch(p.p); + p.v = p.p = 0; + } + + return init.result.get(); +} + +template +ASIO_INITFN_RESULT_TYPE(LegacyCompletionHandler, void ()) +io_context::post(ASIO_MOVE_ARG(LegacyCompletionHandler) handler) +{ + // 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; + + async_completion init(handler); + + bool is_continuation = + asio_handler_cont_helpers::is_continuation(init.completion_handler); + + // Allocate and construct an operation to wrap the handler. + typedef detail::completion_handler< + typename handler_type::type> op; + typename op::ptr p = { detail::addressof(init.completion_handler), + op::ptr::allocate(init.completion_handler), 0 }; + p.p = new (p.v) op(init.completion_handler); + + ASIO_HANDLER_CREATION((*this, *p.p, + "io_context", this, 0, "post")); + + impl_.post_immediate_completion(p.p, is_continuation); + p.v = p.p = 0; + + return init.result.get(); +} + +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, "post")); + + 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()); +} + +inline asio::io_context& io_context::work::get_io_service() +{ + 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()); +} + +#if !defined(ASIO_NO_DEPRECATED) +inline asio::io_context& io_context::service::get_io_service() +{ + return static_cast(context()); +} +#endif // !defined(ASIO_NO_DEPRECATED) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_IO_CONTEXT_HPP diff --git a/tools/sdk/include/asio/asio/impl/post.hpp b/tools/sdk/include/asio/asio/impl/post.hpp new file mode 100644 index 00000000000..55389532b48 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/post.hpp @@ -0,0 +1,77 @@ +// +// impl/post.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 { + +template +ASIO_INITFN_RESULT_TYPE(CompletionToken, void()) post( + ASIO_MOVE_ARG(CompletionToken) token) +{ + typedef ASIO_HANDLER_TYPE(CompletionToken, void()) handler; + + async_completion init(token); + + typename associated_executor::type ex( + (get_associated_executor)(init.completion_handler)); + + typename associated_allocator::type alloc( + (get_associated_allocator)(init.completion_handler)); + + ex.post(ASIO_MOVE_CAST(handler)(init.completion_handler), alloc); + + return init.result.get(); +} + +template +ASIO_INITFN_RESULT_TYPE(CompletionToken, void()) post( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + typedef ASIO_HANDLER_TYPE(CompletionToken, void()) handler; + + async_completion init(token); + + typename associated_allocator::type alloc( + (get_associated_allocator)(init.completion_handler)); + + ex.post(detail::work_dispatcher(init.completion_handler), alloc); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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/include/asio/asio/impl/read.hpp b/tools/sdk/include/asio/asio/impl/read.hpp new file mode 100644 index 00000000000..603a7a9b19a --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/read.hpp @@ -0,0 +1,715 @@ +// +// impl/read.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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), 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, completion_condition, ec); + asio::detail::throw_error(ec, "read"); + return bytes_transferred; +} + +template +std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer)(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) buffers, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read(s, + ASIO_MOVE_CAST(DynamicBuffer)(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) buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + return read(s, ASIO_MOVE_CAST(DynamicBuffer)(buffers), + transfer_all(), ec); +} + +template +inline std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read(s, + ASIO_MOVE_CAST(DynamicBuffer)(buffers), + 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), 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), completion_condition); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +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(other), + stream_(other.stream_), + buffers_(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: + AsyncReadStream& stream_; + asio::detail::consuming_buffers 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); + } +} // 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_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*) +{ + // 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; + + async_completion init(handler); + + detail::start_read_buffer_sequence_op(s, buffers, + asio::buffer_sequence_begin(buffers), completion_condition, + init.completion_handler); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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*) +{ + // 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; + + async_completion init(handler); + + detail::start_read_buffer_sequence_op(s, buffers, + asio::buffer_sequence_begin(buffers), transfer_all(), + init.completion_handler); + + return init.result.get(); +} + +namespace detail +{ + template + class read_dynbuf_op + : detail::base_from_completion_cond + { + public: + template + read_dynbuf_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_op(const read_dynbuf_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_op(read_dynbuf_op&& other) + : detail::base_from_completion_cond(other), + stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer)(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_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 buffers_; + int start_; + std::size_t total_transferred_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_dynbuf_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_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_dynbuf_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_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_dynbuf_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_dynbuf_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_dynbuf_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_dynbuf_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_dynbuf_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + return async_read(s, + ASIO_MOVE_CAST(DynamicBuffer)(buffers), + transfer_all(), ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +template +inline ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer::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; + + async_completion init(handler); + + detail::read_dynbuf_op::type, + CompletionCondition, ASIO_HANDLER_TYPE( + ReadHandler, void (asio::error_code, std::size_t))>( + s, ASIO_MOVE_CAST(DynamicBuffer)(buffers), + completion_condition, init.completion_handler)( + asio::error_code(), 0, 1); + + return init.result.get(); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +template +inline ASIO_INITFN_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_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), + completion_condition, ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_READ_HPP diff --git a/tools/sdk/include/asio/asio/impl/read_at.hpp b/tools/sdk/include/asio/asio/impl/read_at.hpp new file mode 100644 index 00000000000..d736d4d3156 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/read_at.hpp @@ -0,0 +1,640 @@ +// +// impl/read_at.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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), 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, 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, 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(other), + device_(other.device_), + offset_(other.offset_), + buffers_(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: + AsyncRandomAccessReadDevice& device_; + uint64_t offset_; + asio::detail::consuming_buffers 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); + } +} // 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_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) +{ + // 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; + + async_completion init(handler); + + detail::start_read_at_buffer_sequence_op(d, offset, buffers, + asio::buffer_sequence_begin(buffers), completion_condition, + init.completion_handler); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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) +{ + // 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; + + async_completion init(handler); + + detail::start_read_at_buffer_sequence_op(d, offset, buffers, + asio::buffer_sequence_begin(buffers), transfer_all(), + init.completion_handler); + + return init.result.get(); +} + +#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(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_); + } +} // 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_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) +{ + // 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; + + async_completion init(handler); + + detail::read_at_streambuf_op( + d, offset, b, completion_condition, init.completion_handler)( + asio::error_code(), 0, 1); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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) +{ + // 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; + + async_completion init(handler); + + detail::read_at_streambuf_op( + d, offset, b, transfer_all(), init.completion_handler)( + asio::error_code(), 0, 1); + + return init.result.get(); +} + +#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/include/asio/asio/impl/read_until.hpp b/tools/sdk/include/asio/asio/impl/read_until.hpp new file mode 100644 index 00000000000..1f39e1933b5 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/read_until.hpp @@ -0,0 +1,1500 @@ +// +// impl/read_until.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +template +inline std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, char delim) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer)(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) buffers, + char delim, asio::error_code& ec) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer)(buffers)); + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer::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) buffers, + ASIO_STRING_VIEW_PARAM delim) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer)(buffers), delim, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +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 + +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer)(buffers)); + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer::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) buffers, + const boost::regex& expr) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer)(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) buffers, + const boost::regex& expr, asio::error_code& ec) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer)(buffers)); + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer::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 = read_size_helper(b, 65536); + 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) buffers, + MatchCondition match_condition, + typename enable_if::value>::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer)(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) buffers, + MatchCondition match_condition, asio::error_code& ec, + typename enable_if::value>::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer)(buffers)); + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer::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) + +namespace detail +{ + template + class read_until_delim_op + { + public: + template + read_until_delim_op(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(const read_until_delim_op& 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(read_until_delim_op&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer)(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::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 operation to obtain more data. + stream_.async_read_some(buffers_.prepare(bytes_to_read), + ASIO_MOVE_CAST(read_until_delim_op)(*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 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* 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* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_delim_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_until_delim_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_delim_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_delim_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_delim_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_delim_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_delim_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + char delim, ASIO_MOVE_ARG(ReadHandler) handler) +{ + // 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; + + async_completion init(handler); + + detail::read_until_delim_op::type, + ASIO_HANDLER_TYPE(ReadHandler, + void (asio::error_code, std::size_t))>( + s, ASIO_MOVE_CAST(DynamicBuffer)(buffers), + delim, init.completion_handler)(asio::error_code(), 0, 1); + + return init.result.get(); +} + +namespace detail +{ + template + class read_until_delim_string_op + { + public: + template + read_until_delim_string_op(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(const read_until_delim_string_op& 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(read_until_delim_string_op&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer)(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::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 operation to obtain more data. + stream_.async_read_some(buffers_.prepare(bytes_to_read), + ASIO_MOVE_CAST(read_until_delim_string_op)(*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 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* 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* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_delim_string_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_until_delim_string_op* 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* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_delim_string_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_delim_string_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_delim_string_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_delim_string_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + ASIO_STRING_VIEW_PARAM delim, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + // 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; + + async_completion init(handler); + + detail::read_until_delim_string_op::type, + ASIO_HANDLER_TYPE(ReadHandler, + void (asio::error_code, std::size_t))>( + s, ASIO_MOVE_CAST(DynamicBuffer)(buffers), + static_cast(delim), + init.completion_handler)(asio::error_code(), 0, 1); + + return init.result.get(); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) + +namespace detail +{ + template + class read_until_expr_op + { + public: + template + read_until_expr_op(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(const read_until_expr_op& 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(read_until_expr_op&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer)(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::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 operation to obtain more data. + stream_.async_read_some(buffers_.prepare(bytes_to_read), + ASIO_MOVE_CAST(read_until_expr_op)(*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 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* 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* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_expr_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_until_expr_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_expr_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_expr_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_expr_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_expr_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_expr_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + const boost::regex& expr, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + // 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; + + async_completion init(handler); + + detail::read_until_expr_op::type, + boost::regex, ASIO_HANDLER_TYPE(ReadHandler, + void (asio::error_code, std::size_t))>( + s, ASIO_MOVE_CAST(DynamicBuffer)(buffers), + expr, init.completion_handler)(asio::error_code(), 0, 1); + + return init.result.get(); +} + +#endif // defined(ASIO_HAS_BOOST_REGEX) + +namespace detail +{ + template + class read_until_match_op + { + public: + template + read_until_match_op(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(const read_until_match_op& 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(read_until_match_op&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer)(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::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 operation to obtain more data. + stream_.async_read_some(buffers_.prepare(bytes_to_read), + ASIO_MOVE_CAST(read_until_match_op)(*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 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* 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* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_match_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_until_match_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_match_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_match_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_match_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_match_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_match_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + MatchCondition match_condition, ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if::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; + + async_completion init(handler); + + detail::read_until_match_op::type, + MatchCondition, ASIO_HANDLER_TYPE(ReadHandler, + void (asio::error_code, std::size_t))>( + s, ASIO_MOVE_CAST(DynamicBuffer)(buffers), + match_condition, init.completion_handler)( + asio::error_code(), 0, 1); + + return init.result.get(); +} + +#if !defined(ASIO_NO_IOSTREAM) + +template +inline ASIO_INITFN_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_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_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_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) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_READ_UNTIL_HPP diff --git a/tools/sdk/include/asio/asio/impl/serial_port_base.hpp b/tools/sdk/include/asio/asio/impl/serial_port_base.hpp new file mode 100644 index 00000000000..cdc201d8ab6 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/serial_port_base.hpp @@ -0,0 +1,59 @@ +// +// impl/serial_port_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/impl/spawn.hpp b/tools/sdk/include/asio/asio/impl/spawn.hpp new file mode 100644 index 00000000000..5594ad93d43 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/spawn.hpp @@ -0,0 +1,535 @@ +// +// impl/spawn.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) + { + } +}; + +#if !defined(ASIO_NO_DEPRECATED) + +template +struct handler_type, ReturnType()> +{ + typedef detail::coro_handler type; +}; + +template +struct handler_type, ReturnType(Arg1)> +{ + typedef detail::coro_handler::type> type; +}; + +template +struct handler_type, + ReturnType(asio::error_code)> +{ + typedef detail::coro_handler type; +}; + +template +struct handler_type, + ReturnType(asio::error_code, Arg2)> +{ + typedef detail::coro_handler::type> type; +}; + +template +class async_result > + : public detail::coro_async_result +{ +public: + typedef typename detail::coro_async_result::return_type type; + + explicit async_result( + typename detail::coro_async_result::completion_handler_type& h) + : detail::coro_async_result(h) + { + } +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +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/include/asio/asio/impl/src.hpp b/tools/sdk/include/asio/asio/impl/src.hpp new file mode 100644 index 00000000000..a72637b94ed --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/src.hpp @@ -0,0 +1,82 @@ +// +// impl/src.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/impl/system_context.hpp b/tools/sdk/include/asio/asio/impl/system_context.hpp new file mode 100644 index 00000000000..87ffe76a258 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/system_context.hpp @@ -0,0 +1,34 @@ +// +// impl/system_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/impl/system_executor.hpp b/tools/sdk/include/asio/asio/impl/system_executor.hpp new file mode 100644 index 00000000000..ac4861f56b8 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/system_executor.hpp @@ -0,0 +1,85 @@ +// +// impl/system_executor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/impl/thread_pool.hpp b/tools/sdk/include/asio/asio/impl/thread_pool.hpp new file mode 100644 index 00000000000..058e3771bba --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/thread_pool.hpp @@ -0,0 +1,127 @@ +// +// impl/thread_pool.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/impl/use_future.hpp b/tools/sdk/include/asio/asio/impl/use_future.hpp new file mode 100644 index 00000000000..51eb7e2ca41 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/use_future.hpp @@ -0,0 +1,938 @@ +// +// impl/use_future.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 +#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) + +#if !defined(ASIO_NO_DEPRECATED) + +template +struct handler_type, Signature> +{ + typedef typename async_result, + Signature>::completion_handler_type type; +}; + +template +class async_result > + : public detail::promise_async_result +{ +public: + typedef typename detail::promise_async_result< + Signature, Allocator>::return_type type; + + explicit async_result( + typename detail::promise_async_result< + Signature, Allocator>::completion_handler_type& h) + : detail::promise_async_result(h) + { + } +}; + +template +struct handler_type, Signature> +{ + typedef typename async_result, + Signature>::completion_handler_type type; +}; + +template +class async_result > + : public detail::packaged_async_result +{ +public: + typedef typename detail::packaged_async_result< + Function, Allocator, Result>::return_type type; + + explicit async_result( + typename detail::packaged_async_result< + Function, Allocator, Result>::completion_handler_type& h) + : detail::packaged_async_result(h) + { + } +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_USE_FUTURE_HPP diff --git a/tools/sdk/include/asio/asio/impl/write.hpp b/tools/sdk/include/asio/asio/impl/write.hpp new file mode 100644 index 00000000000..d07e8d3e077 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/write.hpp @@ -0,0 +1,674 @@ +// +// impl/write.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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), 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, completion_condition, ec); + asio::detail::throw_error(ec, "write"); + return bytes_transferred; +} + +template +std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer)(buffers)); + + std::size_t bytes_transferred = write(s, b.data(), completion_condition, ec); + b.consume(bytes_transferred); + return bytes_transferred; +} + +template +inline std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = write(s, + ASIO_MOVE_CAST(DynamicBuffer)(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) buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + return write(s, ASIO_MOVE_CAST(DynamicBuffer)(buffers), + transfer_all(), ec); +} + +template +inline std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = write(s, + ASIO_MOVE_CAST(DynamicBuffer)(buffers), + 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), 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), completion_condition); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +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(other), + stream_(other.stream_), + buffers_(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: + AsyncWriteStream& stream_; + asio::detail::consuming_buffers 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); + } + +} // 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_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*) +{ + // 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; + + async_completion init(handler); + + detail::start_write_buffer_sequence_op(s, buffers, + asio::buffer_sequence_begin(buffers), completion_condition, + init.completion_handler); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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*) +{ + // 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; + + async_completion init(handler); + + detail::start_write_buffer_sequence_op(s, buffers, + asio::buffer_sequence_begin(buffers), transfer_all(), + init.completion_handler); + + return init.result.get(); +} + +namespace detail +{ + template + class write_dynbuf_op + { + public: + template + write_dynbuf_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_op(const write_dynbuf_op& other) + : stream_(other.stream_), + buffers_(other.buffers_), + completion_condition_(other.completion_condition_), + handler_(other.handler_) + { + } + + write_dynbuf_op(write_dynbuf_op&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer)(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(), completion_condition_, + ASIO_MOVE_CAST(write_dynbuf_op)(*this)); + return; default: + buffers_.consume(bytes_transferred); + handler_(ec, static_cast(bytes_transferred)); + } + } + + //private: + AsyncWriteStream& stream_; + DynamicBuffer buffers_; + CompletionCondition completion_condition_; + WriteHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + write_dynbuf_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_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + write_dynbuf_op* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + write_dynbuf_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + write_dynbuf_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::write_dynbuf_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::write_dynbuf_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::write_dynbuf_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::write_dynbuf_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_dynamic_buffer::type>::value + >::type*) +{ + return async_write(s, + ASIO_MOVE_CAST(DynamicBuffer)(buffers), + transfer_all(), ASIO_MOVE_CAST(WriteHandler)(handler)); +} + +template +inline ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_dynamic_buffer::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 WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + async_completion init(handler); + + detail::write_dynbuf_op::type, + CompletionCondition, ASIO_HANDLER_TYPE( + WriteHandler, void (asio::error_code, std::size_t))>( + s, ASIO_MOVE_CAST(DynamicBuffer)(buffers), + completion_condition, init.completion_handler)( + asio::error_code(), 0, 1); + + return init.result.get(); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +template +inline ASIO_INITFN_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_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), + completion_condition, ASIO_MOVE_CAST(WriteHandler)(handler)); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_WRITE_HPP diff --git a/tools/sdk/include/asio/asio/impl/write_at.hpp b/tools/sdk/include/asio/asio/impl/write_at.hpp new file mode 100644 index 00000000000..cc6f336f1d1 --- /dev/null +++ b/tools/sdk/include/asio/asio/impl/write_at.hpp @@ -0,0 +1,572 @@ +// +// impl/write_at.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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), 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, 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(), 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, 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(other), + device_(other.device_), + offset_(other.offset_), + buffers_(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: + AsyncRandomAccessWriteDevice& device_; + uint64_t offset_; + asio::detail::consuming_buffers 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); + } +} // 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_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) +{ + // 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; + + async_completion init(handler); + + detail::start_write_at_buffer_sequence_op(d, offset, buffers, + asio::buffer_sequence_begin(buffers), completion_condition, + init.completion_handler); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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) +{ + // 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; + + async_completion init(handler); + + detail::start_write_at_buffer_sequence_op(d, offset, buffers, + asio::buffer_sequence_begin(buffers), transfer_all(), + init.completion_handler); + + return init.result.get(); +} + +#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 + inline write_at_streambuf_op + make_write_at_streambuf_op( + asio::basic_streambuf& b, WriteHandler handler) + { + return write_at_streambuf_op(b, handler); + } +} // 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_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) +{ + // 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; + + async_completion init(handler); + + async_write_at(d, offset, b.data(), completion_condition, + detail::write_at_streambuf_op( + b, init.completion_handler)); + + return init.result.get(); +} + +template +inline ASIO_INITFN_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) +{ + // 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; + + async_completion init(handler); + + async_write_at(d, offset, b.data(), transfer_all(), + detail::write_at_streambuf_op( + b, init.completion_handler)); + + return init.result.get(); +} + +#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/include/asio/asio/io_context.hpp b/tools/sdk/include/asio/asio/io_context.hpp new file mode 100644 index 00000000000..4d93be44b2c --- /dev/null +++ b/tools/sdk/include/asio/asio/io_context.hpp @@ -0,0 +1,876 @@ +// +// io_context.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_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_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: + // 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(); + + /// (Deprecated: Use get_io_context().) Get the io_context associated with the + /// work. + asio::io_context& get_io_service(); + +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(); + +#if !defined(ASIO_NO_DEPRECATED) + /// Get the io_context object that owns the service. + asio::io_context& get_io_service(); +#endif // !defined(ASIO_NO_DEPRECATED) + +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/include/asio/asio/io_context_strand.hpp b/tools/sdk/include/asio/asio/io_context_strand.hpp new file mode 100644 index 00000000000..3c596f125ea --- /dev/null +++ b/tools/sdk/include/asio/asio/io_context_strand.hpp @@ -0,0 +1,384 @@ +// +// io_context_strand.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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() + { + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use context().) Get the io_context associated with the + /// strand. + /** + * This function may be used to obtain the io_context object that the strand + * uses to dispatch handlers for asynchronous operations. + * + * @return A reference to the io_context object that the strand 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 context().) Get the io_context associated with the + /// strand. + /** + * This function may be used to obtain the io_context object that the strand + * uses to dispatch handlers for asynchronous operations. + * + * @return A reference to the io_context object that the strand 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) + + /// 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_RESULT_TYPE(LegacyCompletionHandler, void ()) + dispatch(ASIO_MOVE_ARG(LegacyCompletionHandler) handler) + { + // 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; + + async_completion init(handler); + + service_.dispatch(impl_, init.completion_handler); + + return init.result.get(); + } +#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_RESULT_TYPE(LegacyCompletionHandler, void ()) + post(ASIO_MOVE_ARG(LegacyCompletionHandler) handler) + { + // 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; + + async_completion init(handler); + + service_.post(impl_, init.completion_handler); + + return init.result.get(); + } +#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: + 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/include/asio/asio/io_service.hpp b/tools/sdk/include/asio/asio/io_service.hpp new file mode 100644 index 00000000000..ed05c834101 --- /dev/null +++ b/tools/sdk/include/asio/asio/io_service.hpp @@ -0,0 +1,33 @@ +// +// io_service.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/io_service_strand.hpp b/tools/sdk/include/asio/asio/io_service_strand.hpp new file mode 100644 index 00000000000..7093f0e9074 --- /dev/null +++ b/tools/sdk/include/asio/asio/io_service_strand.hpp @@ -0,0 +1,20 @@ +// +// io_service_strand.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/address.hpp b/tools/sdk/include/asio/asio/ip/address.hpp new file mode 100644 index 00000000000..cf852a6d619 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/address.hpp @@ -0,0 +1,260 @@ +// +// ip/address.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(); + + /// Construct an address from an IPv4 address. + ASIO_DECL address(const asio::ip::address_v4& ipv4_address); + + /// Construct an address from an IPv6 address. + ASIO_DECL address(const asio::ip::address_v6& ipv6_address); + + /// Copy constructor. + ASIO_DECL address(const address& other); + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + ASIO_DECL address(address&& other); +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another address. + ASIO_DECL address& operator=(const address& other); + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another address. + ASIO_DECL address& operator=(address&& other); +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from an IPv4 address. + ASIO_DECL address& operator=( + const asio::ip::address_v4& ipv4_address); + + /// Assign from an IPv6 address. + ASIO_DECL address& operator=( + const asio::ip::address_v6& ipv6_address); + + /// Get whether the address is an IP version 4 address. + bool is_v4() const + { + return type_ == ipv4; + } + + /// Get whether the address is an IP version 6 address. + bool is_v6() const + { + 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; + + /// Determine whether the address is unspecified. + ASIO_DECL bool is_unspecified() const; + + /// Determine whether the address is a multicast address. + ASIO_DECL bool is_multicast() const; + + /// Compare two addresses for equality. + ASIO_DECL friend bool operator==(const address& a1, const address& a2); + + /// Compare two addresses for inequality. + friend bool operator!=(const address& a1, const address& a2) + { + return !(a1 == a2); + } + + /// Compare addresses for ordering. + ASIO_DECL friend bool operator<(const address& a1, const address& a2); + + /// Compare addresses for ordering. + friend bool operator>(const address& a1, const address& a2) + { + return a2 < a1; + } + + /// Compare addresses for ordering. + friend bool operator<=(const address& a1, const address& a2) + { + return !(a2 < a1); + } + + /// Compare addresses for ordering. + friend bool operator>=(const address& a1, const address& a2) + { + 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); + +/// 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); + +#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); + +#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/include/asio/asio/ip/address_v4.hpp b/tools/sdk/include/asio/asio/ip/address_v4.hpp new file mode 100644 index 00000000000..4e1cc9a3348 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/address_v4.hpp @@ -0,0 +1,329 @@ +// +// ip/address_v4.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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() + { + 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) + : addr_(other.addr_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + address_v4(address_v4&& other) + : addr_(other.addr_) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another address. + address_v4& operator=(const address_v4& other) + { + addr_ = other.addr_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another address. + address_v4& operator=(address_v4&& other) + { + 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; + + /// Get the address as an unsigned integer in host byte order + ASIO_DECL uint_type to_uint() const; + +#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; + + /// Determine whether the address is unspecified. + ASIO_DECL bool is_unspecified() const; + +#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; + + /// Compare two addresses for equality. + friend bool operator==(const address_v4& a1, const address_v4& a2) + { + 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) + { + return a1.addr_.s_addr != a2.addr_.s_addr; + } + + /// Compare addresses for ordering. + friend bool operator<(const address_v4& a1, const address_v4& a2) + { + return a1.to_uint() < a2.to_uint(); + } + + /// Compare addresses for ordering. + friend bool operator>(const address_v4& a1, const address_v4& a2) + { + return a1.to_uint() > a2.to_uint(); + } + + /// Compare addresses for ordering. + friend bool operator<=(const address_v4& a1, const address_v4& a2) + { + return a1.to_uint() <= a2.to_uint(); + } + + /// Compare addresses for ordering. + friend bool operator>=(const address_v4& a1, const address_v4& a2) + { + return a1.to_uint() >= a2.to_uint(); + } + + /// Obtain an address object that represents any address. + static address_v4 any() + { + return address_v4(); + } + + /// Obtain an address object that represents the loopback address. + static address_v4 loopback() + { + return address_v4(0x7F000001); + } + + /// Obtain an address object that represents the broadcast address. + static address_v4 broadcast() + { + 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); + +/// 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); + +#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); + +#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/include/asio/asio/ip/address_v4_iterator.hpp b/tools/sdk/include/asio/asio/ip/address_v4_iterator.hpp new file mode 100644 index 00000000000..e2ef3937e82 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/address_v4_iterator.hpp @@ -0,0 +1,162 @@ +// +// ip/address_v4_iterator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/address_v4_range.hpp b/tools/sdk/include/asio/asio/ip/address_v4_range.hpp new file mode 100644 index 00000000000..a402842080b --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/address_v4_range.hpp @@ -0,0 +1,134 @@ +// +// ip/address_v4_range.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/address_v6.hpp b/tools/sdk/include/asio/asio/ip/address_v6.hpp new file mode 100644 index 00000000000..fece3329756 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/address_v6.hpp @@ -0,0 +1,336 @@ +// +// ip/address_v6.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(); + + /// 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); + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + ASIO_DECL address_v6(address_v6&& other); +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another address. + ASIO_DECL address_v6& operator=(const address_v6& other); + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another address. + ASIO_DECL address_v6& operator=(address_v6&& other); +#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 + { + return scope_id_; + } + + /// The scope ID of the address. + /** + * Modifies the scope ID associated with the IPv6 address. + */ + void scope_id(unsigned long id) + { + scope_id_ = id; + } + + /// Get the address in bytes, in network byte order. + ASIO_DECL bytes_type to_bytes() 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_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; + + /// Determine whether the address is unspecified. + ASIO_DECL bool is_unspecified() const; + + /// Determine whether the address is link local. + ASIO_DECL bool is_link_local() const; + + /// Determine whether the address is site local. + ASIO_DECL bool is_site_local() const; + + /// Determine whether the address is a mapped IPv4 address. + ASIO_DECL bool is_v4_mapped() const; + +#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; + + /// Determine whether the address is a global multicast address. + ASIO_DECL bool is_multicast_global() const; + + /// Determine whether the address is a link-local multicast address. + ASIO_DECL bool is_multicast_link_local() const; + + /// Determine whether the address is a node-local multicast address. + ASIO_DECL bool is_multicast_node_local() const; + + /// Determine whether the address is a org-local multicast address. + ASIO_DECL bool is_multicast_org_local() const; + + /// Determine whether the address is a site-local multicast address. + ASIO_DECL bool is_multicast_site_local() const; + + /// Compare two addresses for equality. + ASIO_DECL friend bool operator==( + const address_v6& a1, const address_v6& a2); + + /// Compare two addresses for inequality. + friend bool operator!=(const address_v6& a1, const address_v6& a2) + { + return !(a1 == a2); + } + + /// Compare addresses for ordering. + ASIO_DECL friend bool operator<( + const address_v6& a1, const address_v6& a2); + + /// Compare addresses for ordering. + friend bool operator>(const address_v6& a1, const address_v6& a2) + { + return a2 < a1; + } + + /// Compare addresses for ordering. + friend bool operator<=(const address_v6& a1, const address_v6& a2) + { + return !(a2 < a1); + } + + /// Compare addresses for ordering. + friend bool operator>=(const address_v6& a1, const address_v6& a2) + { + return !(a1 < a2); + } + + /// Obtain an address object that represents any address. + static address_v6 any() + { + return address_v6(); + } + + /// Obtain an address object that represents the loopback address. + ASIO_DECL static address_v6 loopback(); + +#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); + +/// 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); + +#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); + +#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/include/asio/asio/ip/address_v6_iterator.hpp b/tools/sdk/include/asio/asio/ip/address_v6_iterator.hpp new file mode 100644 index 00000000000..0a1fb3feabd --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/address_v6_iterator.hpp @@ -0,0 +1,183 @@ +// +// ip/address_v6_iterator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/ip/address_v6_range.hpp b/tools/sdk/include/asio/asio/ip/address_v6_range.hpp new file mode 100644 index 00000000000..9d7062ef8eb --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/address_v6_range.hpp @@ -0,0 +1,129 @@ +// +// ip/address_v6_range.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/ip/bad_address_cast.hpp b/tools/sdk/include/asio/asio/ip/bad_address_cast.hpp new file mode 100644 index 00000000000..8c71f704f83 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/bad_address_cast.hpp @@ -0,0 +1,48 @@ +// +// ip/bad_address_cast.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 : public std::bad_cast +{ +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/include/asio/asio/ip/basic_endpoint.hpp b/tools/sdk/include/asio/asio/ip/basic_endpoint.hpp new file mode 100644 index 00000000000..4418ee77636 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/basic_endpoint.hpp @@ -0,0 +1,263 @@ +// +// ip/basic_endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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() + : 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) + : 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) + : impl_(addr, port_num) + { + } + + /// Copy constructor. + basic_endpoint(const basic_endpoint& other) + : impl_(other.impl_) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move constructor. + basic_endpoint(basic_endpoint&& other) + : impl_(other.impl_) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Assign from another endpoint. + basic_endpoint& operator=(const basic_endpoint& other) + { + impl_ = other.impl_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-assign from another endpoint. + basic_endpoint& operator=(basic_endpoint&& other) + { + impl_ = other.impl_; + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// The protocol associated with the endpoint. + protocol_type protocol() const + { + if (impl_.is_v4()) + return InternetProtocol::v4(); + return InternetProtocol::v6(); + } + + /// 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 port associated with the endpoint. The port number is always in + /// the host's byte order. + unsigned short port() const + { + 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) + { + impl_.port(port_num); + } + + /// Get the IP address associated with the endpoint. + asio::ip::address address() const + { + return impl_.address(); + } + + /// Set the IP address associated with the endpoint. + void address(const asio::ip::address& addr) + { + impl_.address(addr); + } + + /// 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 == e2); + } + + /// 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 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/include/asio/asio/ip/basic_resolver.hpp b/tools/sdk/include/asio/asio/ip/basic_resolver.hpp new file mode 100644 index 00000000000..812dbec541c --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/basic_resolver.hpp @@ -0,0 +1,1018 @@ +// +// ip/basic_resolver.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/string_view.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/io_context.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_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/ip/resolver_service.hpp" +#else // defined(ASIO_ENABLE_OLD_SERVICES) +# if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/winrt_resolver_service.hpp" +# define ASIO_SVC_T \ + asio::detail::winrt_resolver_service +# else +# include "asio/detail/resolver_service.hpp" +# define ASIO_SVC_T \ + asio::detail::resolver_service +# endif +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// 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 + : ASIO_SVC_ACCESS basic_io_object, + public resolver_base +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// 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; + + /// Constructor. + /** + * This constructor creates a basic_resolver. + * + * @param io_context The io_context object that the resolver will use to + * dispatch handlers for any asynchronous operations performed on the + * resolver. + */ + explicit basic_resolver(asio::io_context& io_context) + : basic_io_object(io_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(io_context&) constructor. + */ + basic_resolver(basic_resolver&& other) + : basic_io_object(std::move(other)) + { + } + + /// 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(io_context&) constructor. + */ + basic_resolver& operator=(basic_resolver&& other) + { + basic_io_object::operator=(std::move(other)); + 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() + { + } + +#if defined(ASIO_ENABLE_OLD_SERVICES) + // These functions are provided by basic_io_object<>. +#else // defined(ASIO_ENABLE_OLD_SERVICES) +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::get_executor(); + } +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + + /// 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 this->get_service().cancel(this->get_implementation()); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated.) 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 = this->get_service().resolve( + this->get_implementation(), q, ec); + asio::detail::throw_error(ec, "resolve"); + return r; + } + + /// (Deprecated.) 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 this->get_service().resolve(this->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. + * + * @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 = this->get_service().resolve( + this->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. + * + * @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 this->get_service().resolve(this->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. + * + * @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 = this->get_service().resolve( + this->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. + * + * @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 this->get_service().resolve(this->get_implementation(), q, ec); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated.) 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * A successful resolve operation is guaranteed to pass a non-empty range to + * the handler. + */ + template + ASIO_INITFN_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(const query& q, + ASIO_MOVE_ARG(ResolveHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_resolve(this->get_implementation(), q, + ASIO_MOVE_CAST(ResolveHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + asio::async_completion init(handler); + + this->get_service().async_resolve( + this->get_implementation(), q, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +#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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_INITFN_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) + { + 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. + * + * @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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_INITFN_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) + { + // 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; + + basic_resolver_query q(static_cast(host), + static_cast(service), resolve_flags); + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_resolve(this->get_implementation(), q, + ASIO_MOVE_CAST(ResolveHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + asio::async_completion init(handler); + + this->get_service().async_resolve( + this->get_implementation(), q, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_INITFN_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) + { + 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. + * + * @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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_INITFN_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) + { + // 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; + + basic_resolver_query q( + protocol, static_cast(host), + static_cast(service), resolve_flags); + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_resolve(this->get_implementation(), q, + ASIO_MOVE_CAST(ResolveHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + asio::async_completion init(handler); + + this->get_service().async_resolve( + this->get_implementation(), q, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } + + /// 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 = this->get_service().resolve( + this->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 this->get_service().resolve(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * A successful resolve operation is guaranteed to pass a non-empty range to + * the handler. + */ + template + ASIO_INITFN_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(const endpoint_type& e, + ASIO_MOVE_ARG(ResolveHandler) handler) + { + // 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; + +#if defined(ASIO_ENABLE_OLD_SERVICES) + return this->get_service().async_resolve(this->get_implementation(), e, + ASIO_MOVE_CAST(ResolveHandler)(handler)); +#else // defined(ASIO_ENABLE_OLD_SERVICES) + asio::async_completion init(handler); + + this->get_service().async_resolve( + this->get_implementation(), e, init.completion_handler); + + return init.result.get(); +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + } +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if !defined(ASIO_ENABLE_OLD_SERVICES) +# undef ASIO_SVC_T +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_IP_BASIC_RESOLVER_HPP diff --git a/tools/sdk/include/asio/asio/ip/basic_resolver_entry.hpp b/tools/sdk/include/asio/asio/ip/basic_resolver_entry.hpp new file mode 100644 index 00000000000..99bcbd29e6f --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/basic_resolver_entry.hpp @@ -0,0 +1,113 @@ +// +// ip/basic_resolver_entry.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/basic_resolver_iterator.hpp b/tools/sdk/include/asio/asio/ip/basic_resolver_iterator.hpp new file mode 100644 index 00000000000..ec5412cf6f7 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/basic_resolver_iterator.hpp @@ -0,0 +1,192 @@ +// +// ip/basic_resolver_iterator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/basic_resolver_query.hpp b/tools/sdk/include/asio/asio/ip/basic_resolver_query.hpp new file mode 100644 index 00000000000..84cd98d5582 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/basic_resolver_query.hpp @@ -0,0 +1,244 @@ +// +// ip/basic_resolver_query.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/basic_resolver_results.hpp b/tools/sdk/include/asio/asio/ip/basic_resolver_results.hpp new file mode 100644 index 00000000000..185075f0bf9 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/basic_resolver_results.hpp @@ -0,0 +1,311 @@ +// +// ip/basic_resolver_results.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_->size(); + } + + /// Get the maximum number of entries permitted in a results range. + size_type max_size() const ASIO_NOEXCEPT + { + return this->values_->max_size(); + } + + /// Determine whether the results range is empty. + bool empty() const ASIO_NOEXCEPT + { + return this->values_->empty(); + } + + /// Obtain a begin iterator for the results range. + const_iterator begin() const + { + basic_resolver_results tmp(*this); + tmp.index_ = 0; + return 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/include/asio/asio/ip/detail/endpoint.hpp b/tools/sdk/include/asio/asio/ip/detail/endpoint.hpp new file mode 100644 index 00000000000..9acefe5fe29 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/detail/endpoint.hpp @@ -0,0 +1,139 @@ +// +// ip/detail/endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(); + + // Construct an endpoint using a family and port number. + ASIO_DECL endpoint(int family, unsigned short port_num); + + // Construct an endpoint using an address and port number. + ASIO_DECL endpoint(const asio::ip::address& addr, + unsigned short port_num); + + // Copy constructor. + endpoint(const endpoint& other) + : data_(other.data_) + { + } + + // Assign from another endpoint. + endpoint& operator=(const endpoint& other) + { + data_ = other.data_; + 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 + { + 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 + { + return sizeof(data_); + } + + // Get the port associated with the endpoint. + ASIO_DECL unsigned short port() const; + + // Set the port associated with the endpoint. + ASIO_DECL void port(unsigned short port_num); + + // Get the IP address associated with the endpoint. + ASIO_DECL asio::ip::address address() const; + + // Set the IP address associated with the endpoint. + ASIO_DECL void address(const asio::ip::address& addr); + + // 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); + + // Determine whether the endpoint is IPv4. + bool is_v4() const + { + 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/include/asio/asio/ip/detail/socket_option.hpp b/tools/sdk/include/asio/asio/ip/detail/socket_option.hpp new file mode 100644 index 00000000000..051ef30db95 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/detail/socket_option.hpp @@ -0,0 +1,566 @@ +// +// detail/socket_option.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/host_name.hpp b/tools/sdk/include/asio/asio/ip/host_name.hpp new file mode 100644 index 00000000000..d06de5089ab --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/host_name.hpp @@ -0,0 +1,42 @@ +// +// ip/host_name.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/icmp.hpp b/tools/sdk/include/asio/asio/ip/icmp.hpp new file mode 100644 index 00000000000..92e1953f301 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/icmp.hpp @@ -0,0 +1,115 @@ +// +// ip/icmp.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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() + { + return icmp(ASIO_OS_DEF(IPPROTO_ICMP), + ASIO_OS_DEF(AF_INET)); + } + + /// Construct to represent the IPv6 ICMP protocol. + static icmp v6() + { + return icmp(ASIO_OS_DEF(IPPROTO_ICMPV6), + ASIO_OS_DEF(AF_INET6)); + } + + /// Obtain an identifier for the type of the protocol. + int type() const + { + return ASIO_OS_DEF(SOCK_RAW); + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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) + : 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/include/asio/asio/ip/impl/address.hpp b/tools/sdk/include/asio/asio/ip/impl/address.hpp new file mode 100644 index 00000000000..085b93f7b51 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/impl/address.hpp @@ -0,0 +1,67 @@ +// +// ip/impl/address.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/impl/address_v4.hpp b/tools/sdk/include/asio/asio/ip/impl/address_v4.hpp new file mode 100644 index 00000000000..d1cf407c30c --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/impl/address_v4.hpp @@ -0,0 +1,67 @@ +// +// ip/impl/address_v4.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/impl/address_v6.hpp b/tools/sdk/include/asio/asio/ip/impl/address_v6.hpp new file mode 100644 index 00000000000..330eafd1fed --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/impl/address_v6.hpp @@ -0,0 +1,67 @@ +// +// ip/impl/address_v6.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/impl/basic_endpoint.hpp b/tools/sdk/include/asio/asio/ip/impl/basic_endpoint.hpp new file mode 100644 index 00000000000..5680a438176 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/impl/basic_endpoint.hpp @@ -0,0 +1,43 @@ +// +// ip/impl/basic_endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/impl/network_v4.hpp b/tools/sdk/include/asio/asio/ip/impl/network_v4.hpp new file mode 100644 index 00000000000..911a45c3fbe --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/impl/network_v4.hpp @@ -0,0 +1,54 @@ +// +// ip/impl/network_v4.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/ip/impl/network_v6.hpp b/tools/sdk/include/asio/asio/ip/impl/network_v6.hpp new file mode 100644 index 00000000000..b0eedaded2e --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/impl/network_v6.hpp @@ -0,0 +1,53 @@ +// +// ip/impl/network_v6.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/multicast.hpp b/tools/sdk/include/asio/asio/ip/multicast.hpp new file mode 100644 index 00000000000..ea624e147b7 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/multicast.hpp @@ -0,0 +1,191 @@ +// +// ip/multicast.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(io_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(io_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(io_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(io_context); + * ... + * asio::ip::multicast::hops option(4); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::udp::socket socket(io_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(io_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(io_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/include/asio/asio/ip/network_v4.hpp b/tools/sdk/include/asio/asio/ip/network_v4.hpp new file mode 100644 index 00000000000..e38f60fe9ae --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/network_v4.hpp @@ -0,0 +1,261 @@ +// +// ip/network_v4.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/ip/network_v6.hpp b/tools/sdk/include/asio/asio/ip/network_v6.hpp new file mode 100644 index 00000000000..7b6b7e61389 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/network_v6.hpp @@ -0,0 +1,235 @@ +// +// ip/network_v6.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/ip/resolver_base.hpp b/tools/sdk/include/asio/asio/ip/resolver_base.hpp new file mode 100644 index 00000000000..d32c9110d2b --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/resolver_base.hpp @@ -0,0 +1,129 @@ +// +// ip/resolver_base.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/resolver_query_base.hpp b/tools/sdk/include/asio/asio/ip/resolver_query_base.hpp new file mode 100644 index 00000000000..be368589ed7 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/resolver_query_base.hpp @@ -0,0 +1,43 @@ +// +// ip/resolver_query_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ip/resolver_service.hpp b/tools/sdk/include/asio/asio/ip/resolver_service.hpp new file mode 100644 index 00000000000..519d72dbb11 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/resolver_service.hpp @@ -0,0 +1,200 @@ +// +// ip/resolver_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_SERVICE_HPP +#define ASIO_IP_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_ENABLE_OLD_SERVICES) + +#include "asio/async_result.hpp" +#include "asio/error_code.hpp" +#include "asio/io_context.hpp" +#include "asio/ip/basic_resolver_iterator.hpp" +#include "asio/ip/basic_resolver_query.hpp" +#include "asio/ip/basic_resolver_results.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/winrt_resolver_service.hpp" +#else +# include "asio/detail/resolver_service.hpp" +#endif + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Default service implementation for a resolver. +template +class resolver_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base< + resolver_service > +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + + /// The protocol type. + typedef InternetProtocol protocol_type; + + /// The endpoint type. + typedef typename InternetProtocol::endpoint endpoint_type; + + /// The query type. + typedef basic_resolver_query query_type; + + /// The iterator type. + typedef basic_resolver_iterator iterator_type; + + /// The results type. + typedef basic_resolver_results results_type; + +private: + // The type of the platform-specific implementation. +#if defined(ASIO_WINDOWS_RUNTIME) + typedef asio::detail::winrt_resolver_service + service_impl_type; +#else + typedef asio::detail::resolver_service + service_impl_type; +#endif + +public: + /// The type of a resolver implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef typename service_impl_type::implementation_type implementation_type; +#endif + + /// Construct a new resolver service for the specified io_context. + explicit resolver_service(asio::io_context& io_context) + : asio::detail::service_base< + resolver_service >(io_context), + service_impl_(io_context) + { + } + + /// Construct a new resolver implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new resolver implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another resolver implementation. + void move_assign(implementation_type& impl, + resolver_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a resolver implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Cancel pending asynchronous operations. + void cancel(implementation_type& impl) + { + service_impl_.cancel(impl); + } + + /// Resolve a query to a list of entries. + results_type resolve(implementation_type& impl, const query_type& query, + asio::error_code& ec) + { + return service_impl_.resolve(impl, query, ec); + } + + /// Asynchronously resolve a query to a list of entries. + template + ASIO_INITFN_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(implementation_type& impl, const query_type& query, + ASIO_MOVE_ARG(ResolveHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_resolve(impl, query, init.completion_handler); + + return init.result.get(); + } + + /// Resolve an endpoint to a list of entries. + results_type resolve(implementation_type& impl, + const endpoint_type& endpoint, asio::error_code& ec) + { + return service_impl_.resolve(impl, endpoint, ec); + } + + /// Asynchronously resolve an endpoint to a list of entries. + template + ASIO_INITFN_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(implementation_type& impl, const endpoint_type& endpoint, + ASIO_MOVE_ARG(ResolveHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_resolve(impl, endpoint, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // Perform any fork-related housekeeping. + void notify_fork(asio::io_context::fork_event event) + { + service_impl_.notify_fork(event); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_IP_RESOLVER_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/ip/tcp.hpp b/tools/sdk/include/asio/asio/ip/tcp.hpp new file mode 100644 index 00000000000..f1adeb02c80 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/tcp.hpp @@ -0,0 +1,155 @@ +// +// ip/tcp.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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() + { + return tcp(ASIO_OS_DEF(AF_INET)); + } + + /// Construct to represent the IPv6 TCP protocol. + static tcp v6() + { + return tcp(ASIO_OS_DEF(AF_INET6)); + } + + /// Obtain an identifier for the type of the protocol. + int type() const + { + return ASIO_OS_DEF(SOCK_STREAM); + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return ASIO_OS_DEF(IPPROTO_TCP); + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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(io_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(io_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) + : 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/include/asio/asio/ip/udp.hpp b/tools/sdk/include/asio/asio/ip/udp.hpp new file mode 100644 index 00000000000..1c93f9b0a5a --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/udp.hpp @@ -0,0 +1,111 @@ +// +// ip/udp.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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() + { + return udp(ASIO_OS_DEF(AF_INET)); + } + + /// Construct to represent the IPv6 UDP protocol. + static udp v6() + { + return udp(ASIO_OS_DEF(AF_INET6)); + } + + /// Obtain an identifier for the type of the protocol. + int type() const + { + return ASIO_OS_DEF(SOCK_DGRAM); + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return ASIO_OS_DEF(IPPROTO_UDP); + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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) + : 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/include/asio/asio/ip/unicast.hpp b/tools/sdk/include/asio/asio/ip/unicast.hpp new file mode 100644 index 00000000000..14e3e489fd4 --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/unicast.hpp @@ -0,0 +1,70 @@ +// +// ip/unicast.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(io_context); + * ... + * asio::ip::unicast::hops option(4); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::udp::socket socket(io_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/include/asio/asio/ip/v6_only.hpp b/tools/sdk/include/asio/asio/ip/v6_only.hpp new file mode 100644 index 00000000000..ac7234edcba --- /dev/null +++ b/tools/sdk/include/asio/asio/ip/v6_only.hpp @@ -0,0 +1,69 @@ +// +// ip/v6_only.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(io_context); + * ... + * asio::ip::v6_only option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(io_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/include/asio/asio/is_executor.hpp b/tools/sdk/include/asio/asio/is_executor.hpp new file mode 100644 index 00000000000..a1661ec46b6 --- /dev/null +++ b/tools/sdk/include/asio/asio/is_executor.hpp @@ -0,0 +1,46 @@ +// +// is_executor.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/is_read_buffered.hpp b/tools/sdk/include/asio/asio/is_read_buffered.hpp new file mode 100644 index 00000000000..c5a67b2da77 --- /dev/null +++ b/tools/sdk/include/asio/asio/is_read_buffered.hpp @@ -0,0 +1,59 @@ +// +// is_read_buffered.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/is_write_buffered.hpp b/tools/sdk/include/asio/asio/is_write_buffered.hpp new file mode 100644 index 00000000000..e237dd6f461 --- /dev/null +++ b/tools/sdk/include/asio/asio/is_write_buffered.hpp @@ -0,0 +1,59 @@ +// +// is_write_buffered.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/local/basic_endpoint.hpp b/tools/sdk/include/asio/asio/local/basic_endpoint.hpp new file mode 100644 index 00000000000..94e470a4b72 --- /dev/null +++ b/tools/sdk/include/asio/asio/local/basic_endpoint.hpp @@ -0,0 +1,239 @@ +// +// local/basic_endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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() + { + } + + /// 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) + { + } + + /// 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/include/asio/asio/local/connect_pair.hpp b/tools/sdk/include/asio/asio/local/connect_pair.hpp new file mode 100644 index 00000000000..2f7c090edb1 --- /dev/null +++ b/tools/sdk/include/asio/asio/local/connect_pair.hpp @@ -0,0 +1,106 @@ +// +// local/connect_pair.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/local/datagram_protocol.hpp b/tools/sdk/include/asio/asio/local/datagram_protocol.hpp new file mode 100644 index 00000000000..b87df2e5643 --- /dev/null +++ b/tools/sdk/include/asio/asio/local/datagram_protocol.hpp @@ -0,0 +1,80 @@ +// +// local/datagram_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 + { + return SOCK_DGRAM; + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return 0; + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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/include/asio/asio/local/detail/endpoint.hpp b/tools/sdk/include/asio/asio/local/detail/endpoint.hpp new file mode 100644 index 00000000000..4870f3b9aa7 --- /dev/null +++ b/tools/sdk/include/asio/asio/local/detail/endpoint.hpp @@ -0,0 +1,133 @@ +// +// local/detail/endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/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); + + // 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/include/asio/asio/local/stream_protocol.hpp b/tools/sdk/include/asio/asio/local/stream_protocol.hpp new file mode 100644 index 00000000000..e2ef5f3b95f --- /dev/null +++ b/tools/sdk/include/asio/asio/local/stream_protocol.hpp @@ -0,0 +1,90 @@ +// +// local/stream_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 + { + return SOCK_STREAM; + } + + /// Obtain an identifier for the protocol. + int protocol() const + { + return 0; + } + + /// Obtain an identifier for the protocol family. + int family() const + { + 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/include/asio/asio/packaged_task.hpp b/tools/sdk/include/asio/asio/packaged_task.hpp new file mode 100644 index 00000000000..1e20b42e4d2 --- /dev/null +++ b/tools/sdk/include/asio/asio/packaged_task.hpp @@ -0,0 +1,126 @@ +// +// packaged_task.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" + +#if defined(ASIO_HAS_STD_FUTURE) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#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) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_PACKAGED_TASK_HPP diff --git a/tools/sdk/include/asio/asio/placeholders.hpp b/tools/sdk/include/asio/asio/placeholders.hpp new file mode 100644 index 00000000000..e71a21e7f10 --- /dev/null +++ b/tools/sdk/include/asio/asio/placeholders.hpp @@ -0,0 +1,151 @@ +// +// placeholders.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/posix/basic_descriptor.hpp b/tools/sdk/include/asio/asio/posix/basic_descriptor.hpp new file mode 100644 index 00000000000..c15da632c95 --- /dev/null +++ b/tools/sdk/include/asio/asio/posix/basic_descriptor.hpp @@ -0,0 +1,582 @@ +// +// posix/basic_descriptor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_io_object.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/posix/descriptor_base.hpp" + +#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 basic_io_object, + public descriptor_base +{ +public: + /// The native representation of a descriptor. + typedef typename DescriptorService::native_handle_type native_handle_type; + + /// A basic_descriptor is always the lowest layer. + typedef basic_descriptor lowest_layer_type; + + /// Construct a basic_descriptor without opening it. + /** + * This constructor creates a descriptor without opening it. + * + * @param io_context The io_context object that the descriptor will use to + * dispatch handlers for any asynchronous operations performed on the + * descriptor. + */ + explicit basic_descriptor(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct a basic_descriptor on an existing native descriptor. + /** + * This constructor creates a descriptor object to hold an existing native + * descriptor. + * + * @param io_context The io_context object that the descriptor will use 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(asio::io_context& io_context, + const native_handle_type& native_descriptor) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->get_implementation(), + native_descriptor, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_descriptor from another. + /** + * This constructor moves a descriptor from one object to another. + * + * @param other The other basic_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(io_context&) constructor. + */ + basic_descriptor(basic_descriptor&& other) + : basic_io_object( + ASIO_MOVE_CAST(basic_descriptor)(other)) + { + } + + /// Move-assign a basic_descriptor from another. + /** + * This assignment operator moves a descriptor from one object to another. + * + * @param other The other basic_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(io_context&) constructor. + */ + basic_descriptor& operator=(basic_descriptor&& other) + { + basic_io_object::operator=( + ASIO_MOVE_CAST(basic_descriptor)(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * layers. Since a basic_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 basic_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; + this->get_service().assign(this->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) + { + this->get_service().assign( + this->get_implementation(), native_descriptor, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the descriptor is open. + bool is_open() const + { + return this->get_service().is_open(this->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; + this->get_service().close(this->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) + { + this->get_service().close(this->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 this->get_service().native_handle(this->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 this->get_service().release(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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(io_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; + this->get_service().io_control(this->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(io_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) + { + this->get_service().io_control(this->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 this->get_service().non_blocking(this->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; + this->get_service().non_blocking(this->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) + { + this->get_service().non_blocking(this->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 this->get_service().native_non_blocking( + this->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; + this->get_service().native_non_blocking( + this->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) + { + this->get_service().native_non_blocking( + this->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(io_context); + * ... + * descriptor.wait(asio::posix::stream_descriptor::wait_read); + * @endcode + */ + void wait(wait_type w) + { + asio::error_code ec; + this->get_service().wait(this->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(io_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) + { + this->get_service().wait(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @par Example + * @code + * void wait_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Wait succeeded. + * } + * } + * + * ... + * + * asio::posix::stream_descriptor descriptor(io_context); + * ... + * descriptor.async_wait( + * asio::posix::stream_descriptor::wait_read, + * wait_handler); + * @endcode + */ + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(wait_type w, ASIO_MOVE_ARG(WaitHandler) handler) + { + // 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; + + return this->get_service().async_wait(this->get_implementation(), + w, ASIO_MOVE_CAST(WaitHandler)(handler)); + } + +protected: + /// Protected destructor to prevent deletion through this type. + ~basic_descriptor() + { + } +}; + +} // namespace posix +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_POSIX_BASIC_DESCRIPTOR_HPP diff --git a/tools/sdk/include/asio/asio/posix/basic_stream_descriptor.hpp b/tools/sdk/include/asio/asio/posix/basic_stream_descriptor.hpp new file mode 100644 index 00000000000..acd5cb6ae18 --- /dev/null +++ b/tools/sdk/include/asio/asio/posix/basic_stream_descriptor.hpp @@ -0,0 +1,362 @@ +// +// posix/basic_stream_descriptor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" + +#if defined(ASIO_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/posix/basic_descriptor.hpp" +#include "asio/posix/stream_descriptor_service.hpp" + +#include "asio/detail/push_options.hpp" + +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 native representation of a descriptor. + typedef typename StreamDescriptorService::native_handle_type + native_handle_type; + + /// Construct a basic_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 io_context The io_context object that the stream descriptor will + * use to dispatch handlers for any asynchronous operations performed on the + * descriptor. + */ + explicit basic_stream_descriptor(asio::io_context& io_context) + : basic_descriptor(io_context) + { + } + + /// Construct a basic_stream_descriptor on an existing native descriptor. + /** + * This constructor creates a stream descriptor object to hold an existing + * native descriptor. + * + * @param io_context The io_context object that the stream descriptor will + * use 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(asio::io_context& io_context, + const native_handle_type& native_descriptor) + : basic_descriptor(io_context, native_descriptor) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_stream_descriptor from another. + /** + * This constructor moves a stream descriptor from one object to another. + * + * @param other The other basic_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(io_context&) constructor. + */ + basic_stream_descriptor(basic_stream_descriptor&& other) + : basic_descriptor( + ASIO_MOVE_CAST(basic_stream_descriptor)(other)) + { + } + + /// Move-assign a basic_stream_descriptor from another. + /** + * This assignment operator moves a stream descriptor from one object to + * another. + * + * @param other The other basic_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(io_context&) constructor. + */ + basic_stream_descriptor& operator=(basic_stream_descriptor&& other) + { + basic_descriptor::operator=( + ASIO_MOVE_CAST(basic_stream_descriptor)(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->get_service().write_some( + this->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->get_service().write_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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; + + return this->get_service().async_write_some(this->get_implementation(), + buffers, ASIO_MOVE_CAST(WriteHandler)(handler)); + } + + /// 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->get_service().read_some( + this->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->get_service().read_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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 this->get_service().async_read_some(this->get_implementation(), + buffers, ASIO_MOVE_CAST(ReadHandler)(handler)); + } +}; + +} // namespace posix +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP diff --git a/tools/sdk/include/asio/asio/posix/descriptor.hpp b/tools/sdk/include/asio/asio/posix/descriptor.hpp new file mode 100644 index 00000000000..d0cee1a2647 --- /dev/null +++ b/tools/sdk/include/asio/asio/posix/descriptor.hpp @@ -0,0 +1,644 @@ +// +// posix/descriptor.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/async_result.hpp" +#include "asio/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/reactive_descriptor_service.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" +#include "asio/posix/descriptor_base.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#define ASIO_SVC_T asio::detail::reactive_descriptor_service + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace posix { + +/// Provides POSIX descriptor functionality. +/** + * The posix::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. + */ +class descriptor + : ASIO_SVC_ACCESS basic_io_object, + public descriptor_base +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// The native representation of a descriptor. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef ASIO_SVC_T::native_handle_type native_handle_type; +#endif + + /// A descriptor is always the lowest layer. + typedef descriptor lowest_layer_type; + + /// Construct a descriptor without opening it. + /** + * This constructor creates a descriptor without opening it. + * + * @param io_context The io_context object that the descriptor will use to + * dispatch handlers for any asynchronous operations performed on the + * descriptor. + */ + explicit descriptor(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct a descriptor on an existing native descriptor. + /** + * This constructor creates a descriptor object to hold an existing native + * descriptor. + * + * @param io_context The io_context object that the descriptor will use to + * dispatch handlers for any asynchronous operations performed on the + * descriptor. + * + * @param native_descriptor A native descriptor. + * + * @throws asio::system_error Thrown on failure. + */ + descriptor(asio::io_context& io_context, + const native_handle_type& native_descriptor) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->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 descriptor(io_context&) constructor. + */ + descriptor(descriptor&& other) + : basic_io_object(std::move(other)) + { + } + + /// 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 descriptor(io_context&) constructor. + */ + descriptor& operator=(descriptor&& other) + { + basic_io_object::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::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; + this->get_service().assign(this->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) + { + this->get_service().assign( + this->get_implementation(), native_descriptor, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the descriptor is open. + bool is_open() const + { + return this->get_service().is_open(this->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; + this->get_service().close(this->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) + { + this->get_service().close(this->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 this->get_service().native_handle(this->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 this->get_service().release(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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(io_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; + this->get_service().io_control(this->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(io_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) + { + this->get_service().io_control(this->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 this->get_service().non_blocking(this->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; + this->get_service().non_blocking(this->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) + { + this->get_service().non_blocking(this->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 this->get_service().native_non_blocking( + this->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; + this->get_service().native_non_blocking( + this->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) + { + this->get_service().native_non_blocking( + this->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(io_context); + * ... + * descriptor.wait(asio::posix::stream_descriptor::wait_read); + * @endcode + */ + void wait(wait_type w) + { + asio::error_code ec; + this->get_service().wait(this->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(io_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) + { + this->get_service().wait(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @par Example + * @code + * void wait_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Wait succeeded. + * } + * } + * + * ... + * + * asio::posix::stream_descriptor descriptor(io_context); + * ... + * descriptor.async_wait( + * asio::posix::stream_descriptor::wait_read, + * wait_handler); + * @endcode + */ + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(wait_type w, ASIO_MOVE_ARG(WaitHandler) handler) + { + // 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; + + async_completion init(handler); + + this->get_service().async_wait( + this->get_implementation(), w, init.completion_handler); + + return init.result.get(); + } + +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. + */ + ~descriptor() + { + } +}; + +} // namespace posix +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#undef ASIO_SVC_T + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_POSIX_DESCRIPTOR_HPP diff --git a/tools/sdk/include/asio/asio/posix/descriptor_base.hpp b/tools/sdk/include/asio/asio/posix/descriptor_base.hpp new file mode 100644 index 00000000000..4aac04f1088 --- /dev/null +++ b/tools/sdk/include/asio/asio/posix/descriptor_base.hpp @@ -0,0 +1,90 @@ +// +// posix/descriptor_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(io_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/include/asio/asio/posix/stream_descriptor.hpp b/tools/sdk/include/asio/asio/posix/stream_descriptor.hpp new file mode 100644 index 00000000000..abb426a3904 --- /dev/null +++ b/tools/sdk/include/asio/asio/posix/stream_descriptor.hpp @@ -0,0 +1,360 @@ +// +// posix/stream_descriptor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" +#include "asio/posix/descriptor.hpp" + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/posix/basic_stream_descriptor.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +namespace asio { +namespace posix { + +#if defined(ASIO_ENABLE_OLD_SERVICES) +// Typedef for the typical usage of a stream-oriented descriptor. +typedef basic_stream_descriptor<> stream_descriptor; +#else // defined(ASIO_ENABLE_OLD_SERVICES) +/// Provides stream-oriented descriptor functionality. +/** + * The posix::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. + */ +class stream_descriptor + : public descriptor +{ +public: + /// 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 io_context The io_context object that the stream descriptor will + * use to dispatch handlers for any asynchronous operations performed on the + * descriptor. + */ + explicit stream_descriptor(asio::io_context& io_context) + : descriptor(io_context) + { + } + + /// Construct a stream_descriptor on an existing native descriptor. + /** + * This constructor creates a stream descriptor object to hold an existing + * native descriptor. + * + * @param io_context The io_context object that the stream descriptor will + * use 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. + */ + stream_descriptor(asio::io_context& io_context, + const native_handle_type& native_descriptor) + : descriptor(io_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 stream_descriptor(io_context&) constructor. + */ + stream_descriptor(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 stream_descriptor(io_context&) constructor. + */ + stream_descriptor& operator=(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->get_service().write_some( + this->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->get_service().write_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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::async_completion init(handler); + + this->get_service().async_write_some( + this->get_implementation(), buffers, init.completion_handler); + + return init.result.get(); + } + + /// 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->get_service().read_some( + this->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->get_service().read_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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::async_completion init(handler); + + this->get_service().async_read_some( + this->get_implementation(), buffers, init.completion_handler); + + return init.result.get(); + } +}; +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +} // 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/include/asio/asio/posix/stream_descriptor_service.hpp b/tools/sdk/include/asio/asio/posix/stream_descriptor_service.hpp new file mode 100644 index 00000000000..4ffbb9602d5 --- /dev/null +++ b/tools/sdk/include/asio/asio/posix/stream_descriptor_service.hpp @@ -0,0 +1,279 @@ +// +// posix/stream_descriptor_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_SERVICE_HPP +#define ASIO_POSIX_STREAM_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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/async_result.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" +#include "asio/detail/reactive_descriptor_service.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace posix { + +/// Default service implementation for a stream descriptor. +class stream_descriptor_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + +private: + // The type of the platform-specific implementation. + typedef detail::reactive_descriptor_service service_impl_type; + +public: + /// The type of a stream descriptor implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef service_impl_type::implementation_type implementation_type; +#endif + + /// The native descriptor type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new stream descriptor service for the specified io_context. + explicit stream_descriptor_service(asio::io_context& io_context) + : asio::detail::service_base(io_context), + service_impl_(io_context) + { + } + + /// Construct a new stream descriptor implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new stream descriptor implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another stream descriptor implementation. + void move_assign(implementation_type& impl, + stream_descriptor_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a stream descriptor implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Assign an existing native descriptor to a stream descriptor. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const native_handle_type& native_descriptor, + asio::error_code& ec) + { + service_impl_.assign(impl, native_descriptor, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the descriptor is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close a stream descriptor implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native descriptor implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Release ownership of the native descriptor implementation. + native_handle_type release(implementation_type& impl) + { + return service_impl_.release(impl); + } + + /// Cancel all asynchronous operations associated with the descriptor. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the descriptor. + template + ASIO_SYNC_OP_VOID io_control(implementation_type& impl, + IoControlCommand& command, asio::error_code& ec) + { + service_impl_.io_control(impl, command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the descriptor. + bool non_blocking(const implementation_type& impl) const + { + return service_impl_.non_blocking(impl); + } + + /// Sets the non-blocking mode of the descriptor. + ASIO_SYNC_OP_VOID non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native descriptor implementation. + bool native_non_blocking(const implementation_type& impl) const + { + return service_impl_.native_non_blocking(impl); + } + + /// Sets the non-blocking mode of the native descriptor implementation. + ASIO_SYNC_OP_VOID native_non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.native_non_blocking(impl, 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. + ASIO_SYNC_OP_VOID wait(implementation_type& impl, + descriptor_base::wait_type w, asio::error_code& ec) + { + service_impl_.wait(impl, 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. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, descriptor_base::wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, w, init.completion_handler); + + return init.result.get(); + } + + /// Write the given data to the stream. + template + std::size_t write_some(implementation_type& impl, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + return service_impl_.write_some(impl, buffers, ec); + } + + /// Start an asynchronous write. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(implementation_type& impl, + const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_write_some(impl, buffers, init.completion_handler); + + return init.result.get(); + } + + /// Read some data from the stream. + template + std::size_t read_some(implementation_type& impl, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + return service_impl_.read_some(impl, buffers, ec); + } + + /// Start an asynchronous read. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(implementation_type& impl, + const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_read_some(impl, buffers, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace posix +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_POSIX_STREAM_DESCRIPTOR_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/post.hpp b/tools/sdk/include/asio/asio/post.hpp new file mode 100644 index 00000000000..87d7b96d6be --- /dev/null +++ b/tools/sdk/include/asio/asio/post.hpp @@ -0,0 +1,107 @@ +// +// post.hpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(). + * + * 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_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(). + * + * 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_RESULT_TYPE(CompletionToken, void()) post( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + 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_RESULT_TYPE(CompletionToken, void()) post( + ExecutionContext& ctx, ASIO_MOVE_ARG(CompletionToken) token, + 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/include/asio/asio/raw_socket_service.hpp b/tools/sdk/include/asio/asio/raw_socket_service.hpp new file mode 100644 index 00000000000..2bccf032e3d --- /dev/null +++ b/tools/sdk/include/asio/asio/raw_socket_service.hpp @@ -0,0 +1,466 @@ +// +// raw_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_RAW_SOCKET_SERVICE_HPP +#define ASIO_RAW_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_ENABLE_OLD_SERVICES) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/io_context.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 + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a raw socket. +template +class raw_socket_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base > +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + +private: + // The type of the platform-specific implementation. +#if defined(ASIO_WINDOWS_RUNTIME) + typedef detail::null_socket_service service_impl_type; +#elif defined(ASIO_HAS_IOCP) + typedef detail::win_iocp_socket_service service_impl_type; +#else + typedef detail::reactive_socket_service service_impl_type; +#endif + +public: + /// The type of a raw socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef typename service_impl_type::implementation_type implementation_type; +#endif + + /// The native socket type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new raw socket service for the specified io_context. + explicit raw_socket_service(asio::io_context& io_context) + : asio::detail::service_base< + raw_socket_service >(io_context), + service_impl_(io_context) + { + } + + /// Construct a new raw socket implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new raw socket implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another raw socket implementation. + void move_assign(implementation_type& impl, + raw_socket_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } + + // All socket services have access to each other's implementations. + template friend class raw_socket_service; + + /// Move-construct a new raw socket implementation from another protocol + /// type. + template + void converting_move_construct(implementation_type& impl, + raw_socket_service& other_service, + typename raw_socket_service< + Protocol1>::implementation_type& other_impl, + typename enable_if::value>::type* = 0) + { + service_impl_.template converting_move_construct( + impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a raw socket implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + // Open a new raw socket implementation. + ASIO_SYNC_OP_VOID open(implementation_type& impl, + const protocol_type& protocol, asio::error_code& ec) + { + if (protocol.type() == ASIO_OS_DEF(SOCK_RAW)) + service_impl_.open(impl, protocol, ec); + else + ec = asio::error::invalid_argument; + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assign an existing native socket to a raw socket. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const protocol_type& protocol, const native_handle_type& native_socket, + asio::error_code& ec) + { + service_impl_.assign(impl, protocol, native_socket, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close a raw socket implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Release ownership of the underlying socket. + native_handle_type release(implementation_type& impl, + asio::error_code& ec) + { + return service_impl_.release(impl, ec); + } + + /// Get the native socket implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Cancel all asynchronous operations associated with the socket. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is at the out-of-band data mark. + bool at_mark(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.at_mark(impl, ec); + } + + /// Determine the number of bytes available for reading. + std::size_t available(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.available(impl, ec); + } + + // Bind the raw socket to the specified local endpoint. + ASIO_SYNC_OP_VOID bind(implementation_type& impl, + const endpoint_type& endpoint, asio::error_code& ec) + { + service_impl_.bind(impl, endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Connect the raw socket to the specified endpoint. + ASIO_SYNC_OP_VOID connect(implementation_type& impl, + const endpoint_type& peer_endpoint, asio::error_code& ec) + { + service_impl_.connect(impl, peer_endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous connect. + template + ASIO_INITFN_RESULT_TYPE(ConnectHandler, + void (asio::error_code)) + async_connect(implementation_type& impl, + const endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(ConnectHandler) handler) + { + async_completion init(handler); + + service_impl_.async_connect(impl, peer_endpoint, init.completion_handler); + + return init.result.get(); + } + + /// Set a socket option. + template + ASIO_SYNC_OP_VOID set_option(implementation_type& impl, + const SettableSocketOption& option, asio::error_code& ec) + { + service_impl_.set_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get a socket option. + template + ASIO_SYNC_OP_VOID get_option(const implementation_type& impl, + GettableSocketOption& option, asio::error_code& ec) const + { + service_impl_.get_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the socket. + template + ASIO_SYNC_OP_VOID io_control(implementation_type& impl, + IoControlCommand& command, asio::error_code& ec) + { + service_impl_.io_control(impl, command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the socket. + bool non_blocking(const implementation_type& impl) const + { + return service_impl_.non_blocking(impl); + } + + /// Sets the non-blocking mode of the socket. + ASIO_SYNC_OP_VOID non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native socket implementation. + bool native_non_blocking(const implementation_type& impl) const + { + return service_impl_.native_non_blocking(impl); + } + + /// Sets the non-blocking mode of the native socket implementation. + ASIO_SYNC_OP_VOID native_non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.native_non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the local endpoint. + endpoint_type local_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.local_endpoint(impl, ec); + } + + /// Get the remote endpoint. + endpoint_type remote_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.remote_endpoint(impl, ec); + } + + /// Disable sends or receives on the socket. + ASIO_SYNC_OP_VOID shutdown(implementation_type& impl, + socket_base::shutdown_type what, asio::error_code& ec) + { + service_impl_.shutdown(impl, 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. + ASIO_SYNC_OP_VOID wait(implementation_type& impl, + socket_base::wait_type w, asio::error_code& ec) + { + service_impl_.wait(impl, 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. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, socket_base::wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, w, init.completion_handler); + + return init.result.get(); + } + + /// Send the given data to the peer. + template + std::size_t send(implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.send(impl, buffers, flags, ec); + } + + /// Start an asynchronous send. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(implementation_type& impl, const ConstBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler) + { + async_completion init(handler); + + service_impl_.async_send(impl, buffers, flags, init.completion_handler); + + return init.result.get(); + } + + /// Send raw data to the specified endpoint. + template + std::size_t send_to(implementation_type& impl, + const ConstBufferSequence& buffers, const endpoint_type& destination, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.send_to(impl, buffers, destination, flags, ec); + } + + /// Start an asynchronous send. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send_to(implementation_type& impl, + const ConstBufferSequence& buffers, const endpoint_type& destination, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler) + { + async_completion init(handler); + + service_impl_.async_send_to(impl, buffers, + destination, flags, init.completion_handler); + + return init.result.get(); + } + + /// Receive some data from the peer. + template + std::size_t receive(implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.receive(impl, buffers, flags, ec); + } + + /// Start an asynchronous receive. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler) + { + async_completion init(handler); + + service_impl_.async_receive(impl, buffers, flags, init.completion_handler); + + return init.result.get(); + } + + /// Receive raw data with the endpoint of the sender. + template + std::size_t receive_from(implementation_type& impl, + const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.receive_from(impl, buffers, sender_endpoint, flags, + ec); + } + + /// Start an asynchronous receive that will get the endpoint of the sender. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive_from(implementation_type& impl, + const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, + socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler) + { + async_completion init(handler); + + service_impl_.async_receive_from(impl, buffers, + sender_endpoint, flags, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_RAW_SOCKET_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/read.hpp b/tools/sdk/include/asio/asio/read.hpp new file mode 100644 index 00000000000..e77206a88cf --- /dev/null +++ b/tools/sdk/include/asio/asio/read.hpp @@ -0,0 +1,947 @@ +// +// read.hpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 Attempt to read 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); + +/// 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) buffers, + typename enable_if< + is_dynamic_buffer::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) buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer::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) buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer::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) buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer::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) + +/*@}*/ +/** + * @defgroup async_read asio::async_read + * + * @brief Start an asynchronous operation to read a certain amount of data from + * a stream. + */ +/*@{*/ + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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* = 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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* = 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 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @note This overload is equivalent to calling: + * @code asio::async_read( + * s, buffers, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer::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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer::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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @note This overload is equivalent to calling: + * @code asio::async_read( + * s, b, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, basic_streambuf& b, + ASIO_MOVE_ARG(ReadHandler) handler); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_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); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/read.hpp" + +#endif // ASIO_READ_HPP diff --git a/tools/sdk/include/asio/asio/read_at.hpp b/tools/sdk/include/asio/asio/read_at.hpp new file mode 100644 index 00000000000..df2c628782c --- /dev/null +++ b/tools/sdk/include/asio/asio/read_at.hpp @@ -0,0 +1,671 @@ +// +// read_at.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 Attempt to read 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 Start an asynchronous operation to read 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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); + +#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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + * + * @note This overload is equivalent to calling: + * @code asio::async_read_at( + * d, 42, b, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_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); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_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); + +#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/include/asio/asio/read_until.hpp b/tools/sdk/include/asio/asio/read_until.hpp new file mode 100644 index 00000000000..f413d987d0f --- /dev/null +++ b/tools/sdk/include/asio/asio/read_until.hpp @@ -0,0 +1,1824 @@ +// +// read_until.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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 Read 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. + */ +/*@{*/ + +/// 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) buffers, char delim); + +/// 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) buffers, + char delim, asio::error_code& ec); + +/// 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) buffers, + ASIO_STRING_VIEW_PARAM delim); + +/// 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) buffers, + ASIO_STRING_VIEW_PARAM delim, + asio::error_code& ec); + +#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) buffers, + const boost::regex& expr); + +/// 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) buffers, + const boost::regex& expr, asio::error_code& ec); + +#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) buffers, + MatchCondition match_condition, + typename enable_if::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) buffers, + MatchCondition match_condition, asio::error_code& ec, + typename enable_if::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) + +/*@}*/ +/** + * @defgroup async_read_until asio::async_read_until + * + * @brief Start an asynchronous operation to read 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. + */ +/*@{*/ + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + char delim, ASIO_MOVE_ARG(ReadHandler) handler); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + ASIO_STRING_VIEW_PARAM delim, + ASIO_MOVE_ARG(ReadHandler) handler); + +#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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + const boost::regex& expr, + ASIO_MOVE_ARG(ReadHandler) handler); + +#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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + MatchCondition match_condition, ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if::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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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); + +#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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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); + +#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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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* = 0); + +#endif // !defined(ASIO_NO_IOSTREAM) +#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/include/asio/asio/seq_packet_socket_service.hpp b/tools/sdk/include/asio/asio/seq_packet_socket_service.hpp new file mode 100644 index 00000000000..7e6824d41e0 --- /dev/null +++ b/tools/sdk/include/asio/asio/seq_packet_socket_service.hpp @@ -0,0 +1,416 @@ +// +// seq_packet_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SEQ_PACKET_SOCKET_SERVICE_HPP +#define ASIO_SEQ_PACKET_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_ENABLE_OLD_SERVICES) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/io_context.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 + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a sequenced packet socket. +template +class seq_packet_socket_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base< + seq_packet_socket_service > +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + +private: + // The type of the platform-specific implementation. +#if defined(ASIO_WINDOWS_RUNTIME) + typedef detail::null_socket_service service_impl_type; +#elif defined(ASIO_HAS_IOCP) + typedef detail::win_iocp_socket_service service_impl_type; +#else + typedef detail::reactive_socket_service service_impl_type; +#endif + +public: + /// The type of a sequenced packet socket implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef typename service_impl_type::implementation_type implementation_type; +#endif + + /// The native socket type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new sequenced packet socket service for the specified + /// io_context. + explicit seq_packet_socket_service(asio::io_context& io_context) + : asio::detail::service_base< + seq_packet_socket_service >(io_context), + service_impl_(io_context) + { + } + + /// Construct a new sequenced packet socket implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new sequenced packet socket implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another sequenced packet socket implementation. + void move_assign(implementation_type& impl, + seq_packet_socket_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } + + // All socket services have access to each other's implementations. + template friend class seq_packet_socket_service; + + /// Move-construct a new sequenced packet socket implementation from another + /// protocol type. + template + void converting_move_construct(implementation_type& impl, + seq_packet_socket_service& other_service, + typename seq_packet_socket_service< + Protocol1>::implementation_type& other_impl, + typename enable_if::value>::type* = 0) + { + service_impl_.template converting_move_construct( + impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a sequenced packet socket implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Open a sequenced packet socket. + ASIO_SYNC_OP_VOID open(implementation_type& impl, + const protocol_type& protocol, asio::error_code& ec) + { + if (protocol.type() == ASIO_OS_DEF(SOCK_SEQPACKET)) + service_impl_.open(impl, protocol, ec); + else + ec = asio::error::invalid_argument; + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assign an existing native socket to a sequenced packet socket. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const protocol_type& protocol, const native_handle_type& native_socket, + asio::error_code& ec) + { + service_impl_.assign(impl, protocol, native_socket, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close a sequenced packet socket implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Release ownership of the underlying socket. + native_handle_type release(implementation_type& impl, + asio::error_code& ec) + { + return service_impl_.release(impl, ec); + } + + /// Get the native socket implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Cancel all asynchronous operations associated with the socket. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is at the out-of-band data mark. + bool at_mark(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.at_mark(impl, ec); + } + + /// Determine the number of bytes available for reading. + std::size_t available(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.available(impl, ec); + } + + /// Bind the sequenced packet socket to the specified local endpoint. + ASIO_SYNC_OP_VOID bind(implementation_type& impl, + const endpoint_type& endpoint, asio::error_code& ec) + { + service_impl_.bind(impl, endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Connect the sequenced packet socket to the specified endpoint. + ASIO_SYNC_OP_VOID connect(implementation_type& impl, + const endpoint_type& peer_endpoint, asio::error_code& ec) + { + service_impl_.connect(impl, peer_endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous connect. + template + ASIO_INITFN_RESULT_TYPE(ConnectHandler, + void (asio::error_code)) + async_connect(implementation_type& impl, + const endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(ConnectHandler) handler) + { + async_completion init(handler); + + service_impl_.async_connect(impl, peer_endpoint, init.completion_handler); + + return init.result.get(); + } + + /// Set a socket option. + template + ASIO_SYNC_OP_VOID set_option(implementation_type& impl, + const SettableSocketOption& option, asio::error_code& ec) + { + service_impl_.set_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get a socket option. + template + ASIO_SYNC_OP_VOID get_option(const implementation_type& impl, + GettableSocketOption& option, asio::error_code& ec) const + { + service_impl_.get_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the socket. + template + ASIO_SYNC_OP_VOID io_control(implementation_type& impl, + IoControlCommand& command, asio::error_code& ec) + { + service_impl_.io_control(impl, command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the socket. + bool non_blocking(const implementation_type& impl) const + { + return service_impl_.non_blocking(impl); + } + + /// Sets the non-blocking mode of the socket. + ASIO_SYNC_OP_VOID non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native socket implementation. + bool native_non_blocking(const implementation_type& impl) const + { + return service_impl_.native_non_blocking(impl); + } + + /// Sets the non-blocking mode of the native socket implementation. + ASIO_SYNC_OP_VOID native_non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.native_non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the local endpoint. + endpoint_type local_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.local_endpoint(impl, ec); + } + + /// Get the remote endpoint. + endpoint_type remote_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.remote_endpoint(impl, ec); + } + + /// Disable sends or receives on the socket. + ASIO_SYNC_OP_VOID shutdown(implementation_type& impl, + socket_base::shutdown_type what, asio::error_code& ec) + { + service_impl_.shutdown(impl, 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. + ASIO_SYNC_OP_VOID wait(implementation_type& impl, + socket_base::wait_type w, asio::error_code& ec) + { + service_impl_.wait(impl, 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. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, socket_base::wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, w, init.completion_handler); + + return init.result.get(); + } + + /// Send the given data to the peer. + template + std::size_t send(implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.send(impl, buffers, flags, ec); + } + + /// Start an asynchronous send. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler) + { + async_completion init(handler); + + service_impl_.async_send(impl, buffers, flags, init.completion_handler); + + return init.result.get(); + } + + /// Receive some data from the peer. + template + std::size_t receive(implementation_type& impl, + const MutableBufferSequence& buffers, socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, asio::error_code& ec) + { + return service_impl_.receive_with_flags(impl, + buffers, in_flags, out_flags, ec); + } + + /// Start an asynchronous receive. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(implementation_type& impl, + const MutableBufferSequence& buffers, socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, + ASIO_MOVE_ARG(ReadHandler) handler) + { + async_completion init(handler); + + service_impl_.async_receive_with_flags(impl, + buffers, in_flags, out_flags, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_SEQ_PACKET_SOCKET_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/serial_port.hpp b/tools/sdk/include/asio/asio/serial_port.hpp new file mode 100644 index 00000000000..27bb63ef739 --- /dev/null +++ b/tools/sdk/include/asio/asio/serial_port.hpp @@ -0,0 +1,769 @@ +// +// serial_port.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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 +#include "asio/async_result.hpp" +#include "asio/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" +#include "asio/serial_port_base.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/basic_serial_port.hpp" +#else // defined(ASIO_ENABLE_OLD_SERVICES) +# if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_serial_port_service.hpp" +# define ASIO_SVC_T detail::win_iocp_serial_port_service +# else +# include "asio/detail/reactive_serial_port_service.hpp" +# define ASIO_SVC_T detail::reactive_serial_port_service +# endif +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if defined(ASIO_ENABLE_OLD_SERVICES) +// Typedef for the typical usage of a serial port. +typedef basic_serial_port<> serial_port; +#else // defined(ASIO_ENABLE_OLD_SERVICES) +/// Provides serial port functionality. +/** + * The serial_port class provides a wrapper over serial port functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +class serial_port + : ASIO_SVC_ACCESS basic_io_object, + public serial_port_base +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// The native representation of a serial port. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef ASIO_SVC_T::native_handle_type native_handle_type; +#endif + + /// A basic_serial_port is always the lowest layer. + typedef serial_port lowest_layer_type; + + /// Construct a serial_port without opening it. + /** + * This constructor creates a serial port without opening it. + * + * @param io_context The io_context object that the serial port will use to + * dispatch handlers for any asynchronous operations performed on the port. + */ + explicit serial_port(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct and open a serial_port. + /** + * This constructor creates and opens a serial port for the specified device + * name. + * + * @param io_context The io_context object that the serial port will use to + * dispatch handlers for any asynchronous operations performed on the port. + * + * @param device The platform-specific device name for this serial + * port. + */ + explicit serial_port(asio::io_context& io_context, + const char* device) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().open(this->get_implementation(), device, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct and open a serial_port. + /** + * This constructor creates and opens a serial port for the specified device + * name. + * + * @param io_context The io_context object that the serial port will use to + * dispatch handlers for any asynchronous operations performed on the port. + * + * @param device The platform-specific device name for this serial + * port. + */ + explicit serial_port(asio::io_context& io_context, + const std::string& device) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().open(this->get_implementation(), device, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct a serial_port on an existing native serial port. + /** + * This constructor creates a serial port object to hold an existing native + * serial port. + * + * @param io_context The io_context object that the serial port will use to + * dispatch handlers for any asynchronous operations performed on the port. + * + * @param native_serial_port A native serial port. + * + * @throws asio::system_error Thrown on failure. + */ + serial_port(asio::io_context& io_context, + const native_handle_type& native_serial_port) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->get_implementation(), + native_serial_port, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a serial_port from another. + /** + * This constructor moves a serial port from one object to another. + * + * @param other The other 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 serial_port(io_context&) constructor. + */ + serial_port(serial_port&& other) + : basic_io_object(std::move(other)) + { + } + + /// Move-assign a serial_port from another. + /** + * This assignment operator moves a serial port from one object to another. + * + * @param other The other 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 serial_port(io_context&) constructor. + */ + serial_port& operator=(serial_port&& other) + { + basic_io_object::operator=(std::move(other)); + 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. + */ + ~serial_port() + { + } + +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::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 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 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; + this->get_service().open(this->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) + { + this->get_service().open(this->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; + this->get_service().assign(this->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) + { + this->get_service().assign(this->get_implementation(), + native_serial_port, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the serial port is open. + bool is_open() const + { + return this->get_service().is_open(this->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; + this->get_service().close(this->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) + { + this->get_service().close(this->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 this->get_service().native_handle(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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; + this->get_service().send_break(this->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) + { + this->get_service().send_break(this->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; + this->get_service().set_option(this->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) + { + this->get_service().set_option(this->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) + { + asio::error_code ec; + this->get_service().get_option(this->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) + { + this->get_service().get_option(this->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 + * 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 = this->get_service().write_some( + this->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 this->get_service().write_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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 + * 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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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; + + async_completion init(handler); + + this->get_service().async_write_some( + this->get_implementation(), buffers, init.completion_handler); + + return init.result.get(); + } + + /// 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 + * 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 = this->get_service().read_some( + this->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 this->get_service().read_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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 + * 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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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; + + async_completion init(handler); + + this->get_service().async_read_some( + this->get_implementation(), buffers, init.completion_handler); + + return init.result.get(); + } +}; +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if !defined(ASIO_ENABLE_OLD_SERVICES) +# undef ASIO_SVC_T +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // defined(ASIO_HAS_SERIAL_PORT) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_SERIAL_PORT_HPP diff --git a/tools/sdk/include/asio/asio/serial_port_base.hpp b/tools/sdk/include/asio/asio/serial_port_base.hpp new file mode 100644 index 00000000000..feb5b9df871 --- /dev/null +++ b/tools/sdk/include/asio/asio/serial_port_base.hpp @@ -0,0 +1,167 @@ +// +// serial_port_base.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/include/asio/asio/serial_port_service.hpp b/tools/sdk/include/asio/asio/serial_port_service.hpp new file mode 100644 index 00000000000..0e20d96e3f2 --- /dev/null +++ b/tools/sdk/include/asio/asio/serial_port_service.hpp @@ -0,0 +1,249 @@ +// +// serial_port_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_SERVICE_HPP +#define ASIO_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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_SERIAL_PORT) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include +#include "asio/async_result.hpp" +#include "asio/detail/reactive_serial_port_service.hpp" +#include "asio/detail/win_iocp_serial_port_service.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" +#include "asio/serial_port_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a serial port. +class serial_port_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + +private: + // The type of the platform-specific implementation. +#if defined(ASIO_HAS_IOCP) + typedef detail::win_iocp_serial_port_service service_impl_type; +#else + typedef detail::reactive_serial_port_service service_impl_type; +#endif + +public: + /// The type of a serial port implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef service_impl_type::implementation_type implementation_type; +#endif + + /// The native handle type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new serial port service for the specified io_context. + explicit serial_port_service(asio::io_context& io_context) + : asio::detail::service_base(io_context), + service_impl_(io_context) + { + } + + /// Construct a new serial port implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new serial port implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another serial port implementation. + void move_assign(implementation_type& impl, + serial_port_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a serial port implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Open a serial port. + ASIO_SYNC_OP_VOID open(implementation_type& impl, + const std::string& device, asio::error_code& ec) + { + service_impl_.open(impl, device, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assign an existing native handle to a serial port. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const native_handle_type& handle, asio::error_code& ec) + { + service_impl_.assign(impl, handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close a serial port implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native handle implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Cancel all asynchronous operations associated with the handle. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Set a serial port option. + template + ASIO_SYNC_OP_VOID set_option(implementation_type& impl, + const SettableSerialPortOption& option, asio::error_code& ec) + { + service_impl_.set_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get a serial port option. + template + ASIO_SYNC_OP_VOID get_option(const implementation_type& impl, + GettableSerialPortOption& option, asio::error_code& ec) const + { + service_impl_.get_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Send a break sequence to the serial port. + ASIO_SYNC_OP_VOID send_break(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.send_break(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Write the given data to the stream. + template + std::size_t write_some(implementation_type& impl, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + return service_impl_.write_some(impl, buffers, ec); + } + + /// Start an asynchronous write. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(implementation_type& impl, + const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + async_completion init(handler); + + service_impl_.async_write_some(impl, buffers, init.completion_handler); + + return init.result.get(); + } + + /// Read some data from the stream. + template + std::size_t read_some(implementation_type& impl, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + return service_impl_.read_some(impl, buffers, ec); + } + + /// Start an asynchronous read. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(implementation_type& impl, + const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + async_completion init(handler); + + service_impl_.async_read_some(impl, buffers, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_SERIAL_PORT) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_SERIAL_PORT_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/signal_set.hpp b/tools/sdk/include/asio/asio/signal_set.hpp new file mode 100644 index 00000000000..30e5c4e39b7 --- /dev/null +++ b/tools/sdk/include/asio/asio/signal_set.hpp @@ -0,0 +1,447 @@ +// +// signal_set.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/async_result.hpp" +#include "asio/basic_io_object.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/basic_signal_set.hpp" +#else // defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/detail/signal_set_service.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +namespace asio { + +#if defined(ASIO_ENABLE_OLD_SERVICES) +// Typedef for the typical usage of a signal set. +typedef basic_signal_set<> signal_set; +#else // defined(ASIO_ENABLE_OLD_SERVICES) +/// Provides signal functionality. +/** + * The 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(io_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. + */ +class signal_set + : ASIO_SVC_ACCESS basic_io_object +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// Construct a signal set without adding any signals. + /** + * This constructor creates a signal set without registering for any signals. + * + * @param io_context The io_context object that the signal set will use to + * dispatch handlers for any asynchronous operations performed on the set. + */ + explicit signal_set(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct a signal set and add one signal. + /** + * This constructor creates a signal set and registers for one signal. + * + * @param io_context The io_context object that the signal set will use to + * dispatch handlers for any asynchronous operations performed on the set. + * + * @param signal_number_1 The signal number to be added. + * + * @note This constructor is equivalent to performing: + * @code asio::signal_set signals(io_context); + * signals.add(signal_number_1); @endcode + */ + signal_set(asio::io_context& io_context, int signal_number_1) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().add(this->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 io_context The io_context object that the signal set will use to + * dispatch handlers for any asynchronous operations performed on the 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(io_context); + * signals.add(signal_number_1); + * signals.add(signal_number_2); @endcode + */ + signal_set(asio::io_context& io_context, int signal_number_1, + int signal_number_2) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().add(this->get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + this->get_service().add(this->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 io_context The io_context object that the signal set will use to + * dispatch handlers for any asynchronous operations performed on the 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(io_context); + * signals.add(signal_number_1); + * signals.add(signal_number_2); + * signals.add(signal_number_3); @endcode + */ + signal_set(asio::io_context& io_context, int signal_number_1, + int signal_number_2, int signal_number_3) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().add(this->get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + this->get_service().add(this->get_implementation(), signal_number_2, ec); + asio::detail::throw_error(ec, "add"); + this->get_service().add(this->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. + */ + ~signal_set() + { + } + +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::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; + this->get_service().add(this->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) + { + this->get_service().add(this->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; + this->get_service().remove(this->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) + { + this->get_service().remove(this->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; + this->get_service().clear(this->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) + { + this->get_service().clear(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_RESULT_TYPE(SignalHandler, + void (asio::error_code, int)) + async_wait(ASIO_MOVE_ARG(SignalHandler) handler) + { + // 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; + + async_completion init(handler); + + this->get_service().async_wait(this->get_implementation(), + init.completion_handler); + + return init.result.get(); + } +}; +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +} // namespace asio + +#endif // ASIO_SIGNAL_SET_HPP diff --git a/tools/sdk/include/asio/asio/signal_set_service.hpp b/tools/sdk/include/asio/asio/signal_set_service.hpp new file mode 100644 index 00000000000..3285beb0035 --- /dev/null +++ b/tools/sdk/include/asio/asio/signal_set_service.hpp @@ -0,0 +1,142 @@ +// +// signal_set_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_SERVICE_HPP +#define ASIO_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" + +#if defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/async_result.hpp" +#include "asio/detail/signal_set_service.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a signal set. +class signal_set_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + +public: + /// The type of a signal set implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef detail::signal_set_service::implementation_type implementation_type; +#endif + + /// Construct a new signal set service for the specified io_context. + explicit signal_set_service(asio::io_context& io_context) + : asio::detail::service_base(io_context), + service_impl_(io_context) + { + } + + /// Construct a new signal set implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + + /// Destroy a signal set implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Add a signal to a signal_set. + ASIO_SYNC_OP_VOID add(implementation_type& impl, + int signal_number, asio::error_code& ec) + { + service_impl_.add(impl, signal_number, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Remove a signal to a signal_set. + ASIO_SYNC_OP_VOID remove(implementation_type& impl, + int signal_number, asio::error_code& ec) + { + service_impl_.remove(impl, signal_number, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Remove all signals from a signal_set. + ASIO_SYNC_OP_VOID clear(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.clear(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Cancel all operations associated with the signal set. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + // Start an asynchronous operation to wait for a signal to be delivered. + template + ASIO_INITFN_RESULT_TYPE(SignalHandler, + void (asio::error_code, int)) + async_wait(implementation_type& impl, + ASIO_MOVE_ARG(SignalHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // Perform any fork-related housekeeping. + void notify_fork(asio::io_context::fork_event event) + { + service_impl_.notify_fork(event); + } + + // The platform-specific implementation. + detail::signal_set_service service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_SIGNAL_SET_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/socket_acceptor_service.hpp b/tools/sdk/include/asio/asio/socket_acceptor_service.hpp new file mode 100644 index 00000000000..cd40fe14201 --- /dev/null +++ b/tools/sdk/include/asio/asio/socket_acceptor_service.hpp @@ -0,0 +1,372 @@ +// +// socket_acceptor_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_ACCEPTOR_SERVICE_HPP +#define ASIO_SOCKET_ACCEPTOR_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_ENABLE_OLD_SERVICES) + +#include "asio/basic_socket.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/io_context.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 + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a socket acceptor. +template +class socket_acceptor_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base > +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename protocol_type::endpoint endpoint_type; + +private: + // The type of the platform-specific implementation. +#if defined(ASIO_WINDOWS_RUNTIME) + typedef detail::null_socket_service service_impl_type; +#elif defined(ASIO_HAS_IOCP) + typedef detail::win_iocp_socket_service service_impl_type; +#else + typedef detail::reactive_socket_service service_impl_type; +#endif + +public: + /// The native type of the socket acceptor. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef typename service_impl_type::implementation_type implementation_type; +#endif + + /// The native acceptor type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new socket acceptor service for the specified io_context. + explicit socket_acceptor_service(asio::io_context& io_context) + : asio::detail::service_base< + socket_acceptor_service >(io_context), + service_impl_(io_context) + { + } + + /// Construct a new socket acceptor implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new socket acceptor implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another socket acceptor implementation. + void move_assign(implementation_type& impl, + socket_acceptor_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } + + // All acceptor services have access to each other's implementations. + template friend class socket_acceptor_service; + + /// Move-construct a new socket acceptor implementation from another protocol + /// type. + template + void converting_move_construct(implementation_type& impl, + socket_acceptor_service& other_service, + typename socket_acceptor_service< + Protocol1>::implementation_type& other_impl, + typename enable_if::value>::type* = 0) + { + service_impl_.template converting_move_construct( + impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a socket acceptor implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Open a new socket acceptor implementation. + ASIO_SYNC_OP_VOID open(implementation_type& impl, + const protocol_type& protocol, asio::error_code& ec) + { + service_impl_.open(impl, protocol, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assign an existing native acceptor to a socket acceptor. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const protocol_type& protocol, const native_handle_type& native_acceptor, + asio::error_code& ec) + { + service_impl_.assign(impl, protocol, native_acceptor, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the acceptor is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Cancel all asynchronous operations associated with the acceptor. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Bind the socket acceptor to the specified local endpoint. + ASIO_SYNC_OP_VOID bind(implementation_type& impl, + const endpoint_type& endpoint, asio::error_code& ec) + { + service_impl_.bind(impl, endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Place the socket acceptor into the state where it will listen for new + /// connections. + ASIO_SYNC_OP_VOID listen(implementation_type& impl, int backlog, + asio::error_code& ec) + { + service_impl_.listen(impl, backlog, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Close a socket acceptor implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Release ownership of the underlying acceptor. + native_handle_type release(implementation_type& impl, + asio::error_code& ec) + { + return service_impl_.release(impl, ec); + } + + /// Get the native acceptor implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Set a socket option. + template + ASIO_SYNC_OP_VOID set_option(implementation_type& impl, + const SettableSocketOption& option, asio::error_code& ec) + { + service_impl_.set_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get a socket option. + template + ASIO_SYNC_OP_VOID get_option(const implementation_type& impl, + GettableSocketOption& option, asio::error_code& ec) const + { + service_impl_.get_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the socket. + template + ASIO_SYNC_OP_VOID io_control(implementation_type& impl, + IoControlCommand& command, asio::error_code& ec) + { + service_impl_.io_control(impl, command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the acceptor. + bool non_blocking(const implementation_type& impl) const + { + return service_impl_.non_blocking(impl); + } + + /// Sets the non-blocking mode of the acceptor. + ASIO_SYNC_OP_VOID non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native acceptor implementation. + bool native_non_blocking(const implementation_type& impl) const + { + return service_impl_.native_non_blocking(impl); + } + + /// Sets the non-blocking mode of the native acceptor implementation. + ASIO_SYNC_OP_VOID native_non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.native_non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the local endpoint. + endpoint_type local_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.local_endpoint(impl, ec); + } + + /// Wait for the acceptor to become ready to read, ready to write, or to have + /// pending error conditions. + ASIO_SYNC_OP_VOID wait(implementation_type& impl, + socket_base::wait_type w, asio::error_code& ec) + { + service_impl_.wait(impl, 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. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, socket_base::wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, w, init.completion_handler); + + return init.result.get(); + } + + /// Accept a new connection. + template + ASIO_SYNC_OP_VOID accept(implementation_type& impl, + basic_socket& peer, + endpoint_type* peer_endpoint, asio::error_code& ec, + typename enable_if::value>::type* = 0) + { + service_impl_.accept(impl, peer, peer_endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + +#if defined(ASIO_HAS_MOVE) + /// Accept a new connection. + typename Protocol::socket accept(implementation_type& impl, + io_context* peer_io_context, endpoint_type* peer_endpoint, + asio::error_code& ec) + { + return service_impl_.accept(impl, peer_io_context, peer_endpoint, ec); + } +#endif // defined(ASIO_HAS_MOVE) + + /// Start an asynchronous accept. + template + ASIO_INITFN_RESULT_TYPE(AcceptHandler, + void (asio::error_code)) + async_accept(implementation_type& impl, + basic_socket& peer, + endpoint_type* peer_endpoint, + ASIO_MOVE_ARG(AcceptHandler) handler, + typename enable_if::value>::type* = 0) + { + async_completion init(handler); + + service_impl_.async_accept(impl, + peer, peer_endpoint, init.completion_handler); + + return init.result.get(); + } + +#if defined(ASIO_HAS_MOVE) + /// Start an asynchronous accept. + template + ASIO_INITFN_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, typename Protocol::socket)) + async_accept(implementation_type& impl, + asio::io_context* peer_io_context, endpoint_type* peer_endpoint, + ASIO_MOVE_ARG(MoveAcceptHandler) handler) + { + async_completion init(handler); + + service_impl_.async_accept(impl, + peer_io_context, peer_endpoint, init.completion_handler); + + return init.result.get(); + } +#endif // defined(ASIO_HAS_MOVE) + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_SOCKET_ACCEPTOR_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/socket_base.hpp b/tools/sdk/include/asio/asio/socket_base.hpp new file mode 100644 index 00000000000..87ed8408bd0 --- /dev/null +++ b/tools/sdk/include/asio/asio/socket_base.hpp @@ -0,0 +1,559 @@ +// +// socket_base.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(io_context); + * ... + * asio::socket_base::broadcast option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::udp::socket socket(io_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(io_context); + * ... + * asio::socket_base::debug option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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(io_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/include/asio/asio/spawn.hpp b/tools/sdk/include/asio/asio/spawn.hpp new file mode 100644 index 00000000000..a91c5815fbd --- /dev/null +++ b/tools/sdk/include/asio/asio/spawn.hpp @@ -0,0 +1,336 @@ +// +// spawn.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl.hpp b/tools/sdk/include/asio/asio/ssl.hpp new file mode 100644 index 00000000000..cbad19d81cc --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl.hpp @@ -0,0 +1,27 @@ +// +// ssl.hpp +// ~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/context.hpp b/tools/sdk/include/asio/asio/ssl/context.hpp new file mode 100644 index 00000000000..9543aab68e5 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/context.hpp @@ -0,0 +1,758 @@ +// +// ssl/context.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/context_base.hpp b/tools/sdk/include/asio/asio/ssl/context_base.hpp new file mode 100644 index 00000000000..56c76936e0c --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/context_base.hpp @@ -0,0 +1,192 @@ +// +// ssl/context_base.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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. + 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 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_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/include/asio/asio/ssl/detail/buffered_handshake_op.hpp b/tools/sdk/include/asio/asio/ssl/detail/buffered_handshake_op.hpp new file mode 100644 index 00000000000..38a03fcce97 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/buffered_handshake_op.hpp @@ -0,0 +1,114 @@ +// +// ssl/detail/buffered_handshake_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/detail/engine.hpp b/tools/sdk/include/asio/asio/ssl/detail/engine.hpp new file mode 100644 index 00000000000..2f033d66cf1 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/engine.hpp @@ -0,0 +1,160 @@ +// +// ssl/detail/engine.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/detail/handshake_op.hpp b/tools/sdk/include/asio/asio/ssl/detail/handshake_op.hpp new file mode 100644 index 00000000000..f782023a1b0 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/handshake_op.hpp @@ -0,0 +1,62 @@ +// +// ssl/detail/handshake_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/detail/io.hpp b/tools/sdk/include/asio/asio/ssl/detail/io.hpp new file mode 100644 index 00000000000..0b0e51a2044 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/io.hpp @@ -0,0 +1,372 @@ +// +// ssl/detail/io.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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) +{ + 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_, 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_), 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_), 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/include/asio/asio/ssl/detail/openssl_init.hpp b/tools/sdk/include/asio/asio/ssl/detail/openssl_init.hpp new file mode 100644 index 00000000000..c3e47278fe7 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/openssl_init.hpp @@ -0,0 +1,101 @@ +// +// ssl/detail/openssl_init.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/detail/openssl_types.hpp b/tools/sdk/include/asio/asio/ssl/detail/openssl_types.hpp new file mode 100644 index 00000000000..a044af30d40 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/openssl_types.hpp @@ -0,0 +1,30 @@ +// +// ssl/detail/openssl_types.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" +#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/include/asio/asio/ssl/detail/password_callback.hpp b/tools/sdk/include/asio/asio/ssl/detail/password_callback.hpp new file mode 100644 index 00000000000..9b1dbeeb884 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/password_callback.hpp @@ -0,0 +1,66 @@ +// +// ssl/detail/password_callback.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/detail/read_op.hpp b/tools/sdk/include/asio/asio/ssl/detail/read_op.hpp new file mode 100644 index 00000000000..b0d6de26657 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/read_op.hpp @@ -0,0 +1,67 @@ +// +// ssl/detail/read_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/detail/shutdown_op.hpp b/tools/sdk/include/asio/asio/ssl/detail/shutdown_op.hpp new file mode 100644 index 00000000000..d20b4309ea0 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/shutdown_op.hpp @@ -0,0 +1,54 @@ +// +// ssl/detail/shutdown_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 + { + 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/include/asio/asio/ssl/detail/stream_core.hpp b/tools/sdk/include/asio/asio/ssl/detail/stream_core.hpp new file mode 100644 index 00000000000..13fde74bf98 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/stream_core.hpp @@ -0,0 +1,134 @@ +// +// ssl/detail/stream_core.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 }; + + stream_core(SSL_CTX* context, asio::io_context& io_context) + : engine_(context), + pending_read_(io_context), + pending_write_(io_context), + 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/include/asio/asio/ssl/detail/verify_callback.hpp b/tools/sdk/include/asio/asio/ssl/detail/verify_callback.hpp new file mode 100644 index 00000000000..1c56a27d824 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/verify_callback.hpp @@ -0,0 +1,62 @@ +// +// ssl/detail/verify_callback.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/detail/write_op.hpp b/tools/sdk/include/asio/asio/ssl/detail/write_op.hpp new file mode 100644 index 00000000000..1d341c09d21 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/detail/write_op.hpp @@ -0,0 +1,67 @@ +// +// ssl/detail/write_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/error.hpp b/tools/sdk/include/asio/asio/ssl/error.hpp new file mode 100644 index 00000000000..6165c5cf764 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/error.hpp @@ -0,0 +1,111 @@ +// +// ssl/error.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 +#elif (OPENSSL_VERSION_NUMBER < 0x10100000L) && !defined(OPENSSL_IS_BORINGSSL) + stream_truncated = ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SHORT_READ) +#else + stream_truncated = 1 +#endif +}; + +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/include/asio/asio/ssl/impl/context.hpp b/tools/sdk/include/asio/asio/ssl/impl/context.hpp new file mode 100644 index 00000000000..40199c143cf --- /dev/null +++ b/tools/sdk/include/asio/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-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/impl/src.hpp b/tools/sdk/include/asio/asio/ssl/impl/src.hpp new file mode 100644 index 00000000000..9a1b038a4c3 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/impl/src.hpp @@ -0,0 +1,28 @@ +// +// impl/ssl/src.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/rfc2818_verification.hpp b/tools/sdk/include/asio/asio/ssl/rfc2818_verification.hpp new file mode 100644 index 00000000000..3589f5383eb --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/rfc2818_verification.hpp @@ -0,0 +1,94 @@ +// +// ssl/rfc2818_verification.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/stream.hpp b/tools/sdk/include/asio/asio/ssl/stream.hpp new file mode 100644 index 00000000000..2b221ed514f --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/stream.hpp @@ -0,0 +1,761 @@ +// +// ssl/stream.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/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 io_context; + * asio::ssl::context ctx(asio::ssl::context::sslv23); + * asio::ssl::stream sock(io_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().context()) + { + } +#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().context()) + { + } +#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(); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + asio::io_context& get_io_context() + { + return next_layer_.lowest_layer().get_io_context(); + } + + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + asio::io_context& get_io_service() + { + return next_layer_.lowest_layer().get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// 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(io_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_INITFN_RESULT_TYPE(HandshakeHandler, + void (asio::error_code)) + async_handshake(handshake_type type, + ASIO_MOVE_ARG(HandshakeHandler) handler) + { + // 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::async_completion init(handler); + + detail::async_io(next_layer_, core_, + detail::handshake_op(type), init.completion_handler); + + return init.result.get(); + } + + /// 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_RESULT_TYPE(BufferedHandshakeHandler, + void (asio::error_code, std::size_t)) + async_handshake(handshake_type type, const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(BufferedHandshakeHandler) handler) + { + // 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::async_completion init(handler); + + detail::async_io(next_layer_, core_, + detail::buffered_handshake_op(type, buffers), + init.completion_handler); + + return init.result.get(); + } + + /// 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_INITFN_RESULT_TYPE(ShutdownHandler, + void (asio::error_code)) + async_shutdown(ASIO_MOVE_ARG(ShutdownHandler) handler) + { + // 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_SHUTDOWN_HANDLER_CHECK(ShutdownHandler, handler) type_check; + + asio::async_completion init(handler); + + detail::async_io(next_layer_, core_, detail::shutdown_op(), + init.completion_handler); + + return init.result.get(); + } + + /// 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 blocking operation completes. + */ + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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::async_completion init(handler); + + detail::async_io(next_layer_, core_, + detail::write_op(buffers), + init.completion_handler); + + return init.result.get(); + } + + /// 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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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::async_completion init(handler); + + detail::async_io(next_layer_, core_, + detail::read_op(buffers), + init.completion_handler); + + return init.result.get(); + } + +private: + 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/include/asio/asio/ssl/stream_base.hpp b/tools/sdk/include/asio/asio/ssl/stream_base.hpp new file mode 100644 index 00000000000..56873e4a5c2 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/stream_base.hpp @@ -0,0 +1,52 @@ +// +// ssl/stream_base.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/verify_context.hpp b/tools/sdk/include/asio/asio/ssl/verify_context.hpp new file mode 100644 index 00000000000..e17269715af --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/verify_context.hpp @@ -0,0 +1,67 @@ +// +// ssl/verify_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ssl/verify_mode.hpp b/tools/sdk/include/asio/asio/ssl/verify_mode.hpp new file mode 100644 index 00000000000..8c4b3942628 --- /dev/null +++ b/tools/sdk/include/asio/asio/ssl/verify_mode.hpp @@ -0,0 +1,63 @@ +// +// ssl/verify_mode.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/steady_timer.hpp b/tools/sdk/include/asio/asio/steady_timer.hpp new file mode 100644 index 00000000000..3ede2084706 --- /dev/null +++ b/tools/sdk/include/asio/asio/steady_timer.hpp @@ -0,0 +1,42 @@ +// +// steady_timer.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/strand.hpp b/tools/sdk/include/asio/asio/strand.hpp new file mode 100644 index 00000000000..ea78ef02feb --- /dev/null +++ b/tools/sdk/include/asio/asio/strand.hpp @@ -0,0 +1,286 @@ +// +// strand.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_; +}; + +} // 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/include/asio/asio/stream_socket_service.hpp b/tools/sdk/include/asio/asio/stream_socket_service.hpp new file mode 100644 index 00000000000..91b0a711f2a --- /dev/null +++ b/tools/sdk/include/asio/asio/stream_socket_service.hpp @@ -0,0 +1,412 @@ +// +// stream_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_STREAM_SOCKET_SERVICE_HPP +#define ASIO_STREAM_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_ENABLE_OLD_SERVICES) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/winrt_ssocket_service.hpp" +#elif defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_socket_service.hpp" +#else +# include "asio/detail/reactive_socket_service.hpp" +#endif + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a stream socket. +template +class stream_socket_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base > +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + +private: + // The type of the platform-specific implementation. +#if defined(ASIO_WINDOWS_RUNTIME) + typedef detail::winrt_ssocket_service service_impl_type; +#elif defined(ASIO_HAS_IOCP) + typedef detail::win_iocp_socket_service service_impl_type; +#else + typedef detail::reactive_socket_service service_impl_type; +#endif + +public: + /// The type of a stream socket implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef typename service_impl_type::implementation_type implementation_type; +#endif + + /// The native socket type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new stream socket service for the specified io_context. + explicit stream_socket_service(asio::io_context& io_context) + : asio::detail::service_base< + stream_socket_service >(io_context), + service_impl_(io_context) + { + } + + /// Construct a new stream socket implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new stream socket implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another stream socket implementation. + void move_assign(implementation_type& impl, + stream_socket_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } + + // All socket services have access to each other's implementations. + template friend class stream_socket_service; + + /// Move-construct a new stream socket implementation from another protocol + /// type. + template + void converting_move_construct(implementation_type& impl, + stream_socket_service& other_service, + typename stream_socket_service< + Protocol1>::implementation_type& other_impl, + typename enable_if::value>::type* = 0) + { + service_impl_.template converting_move_construct( + impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a stream socket implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Open a stream socket. + ASIO_SYNC_OP_VOID open(implementation_type& impl, + const protocol_type& protocol, asio::error_code& ec) + { + if (protocol.type() == ASIO_OS_DEF(SOCK_STREAM)) + service_impl_.open(impl, protocol, ec); + else + ec = asio::error::invalid_argument; + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assign an existing native socket to a stream socket. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const protocol_type& protocol, const native_handle_type& native_socket, + asio::error_code& ec) + { + service_impl_.assign(impl, protocol, native_socket, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close a stream socket implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Release ownership of the underlying socket. + native_handle_type release(implementation_type& impl, + asio::error_code& ec) + { + return service_impl_.release(impl, ec); + } + + /// Get the native socket implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Cancel all asynchronous operations associated with the socket. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is at the out-of-band data mark. + bool at_mark(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.at_mark(impl, ec); + } + + /// Determine the number of bytes available for reading. + std::size_t available(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.available(impl, ec); + } + + /// Bind the stream socket to the specified local endpoint. + ASIO_SYNC_OP_VOID bind(implementation_type& impl, + const endpoint_type& endpoint, asio::error_code& ec) + { + service_impl_.bind(impl, endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Connect the stream socket to the specified endpoint. + ASIO_SYNC_OP_VOID connect(implementation_type& impl, + const endpoint_type& peer_endpoint, asio::error_code& ec) + { + service_impl_.connect(impl, peer_endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous connect. + template + ASIO_INITFN_RESULT_TYPE(ConnectHandler, + void (asio::error_code)) + async_connect(implementation_type& impl, + const endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(ConnectHandler) handler) + { + async_completion init(handler); + + service_impl_.async_connect(impl, peer_endpoint, init.completion_handler); + + return init.result.get(); + } + + /// Set a socket option. + template + ASIO_SYNC_OP_VOID set_option(implementation_type& impl, + const SettableSocketOption& option, asio::error_code& ec) + { + service_impl_.set_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get a socket option. + template + ASIO_SYNC_OP_VOID get_option(const implementation_type& impl, + GettableSocketOption& option, asio::error_code& ec) const + { + service_impl_.get_option(impl, option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the socket. + template + ASIO_SYNC_OP_VOID io_control(implementation_type& impl, + IoControlCommand& command, asio::error_code& ec) + { + service_impl_.io_control(impl, command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the socket. + bool non_blocking(const implementation_type& impl) const + { + return service_impl_.non_blocking(impl); + } + + /// Sets the non-blocking mode of the socket. + ASIO_SYNC_OP_VOID non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native socket implementation. + bool native_non_blocking(const implementation_type& impl) const + { + return service_impl_.native_non_blocking(impl); + } + + /// Sets the non-blocking mode of the native socket implementation. + ASIO_SYNC_OP_VOID native_non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + service_impl_.native_non_blocking(impl, mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the local endpoint. + endpoint_type local_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.local_endpoint(impl, ec); + } + + /// Get the remote endpoint. + endpoint_type remote_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + return service_impl_.remote_endpoint(impl, ec); + } + + /// Disable sends or receives on the socket. + ASIO_SYNC_OP_VOID shutdown(implementation_type& impl, + socket_base::shutdown_type what, asio::error_code& ec) + { + service_impl_.shutdown(impl, 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. + ASIO_SYNC_OP_VOID wait(implementation_type& impl, + socket_base::wait_type w, asio::error_code& ec) + { + service_impl_.wait(impl, 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. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, socket_base::wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, w, init.completion_handler); + + return init.result.get(); + } + + /// Send the given data to the peer. + template + std::size_t send(implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.send(impl, buffers, flags, ec); + } + + /// Start an asynchronous send. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler) + { + async_completion init(handler); + + service_impl_.async_send(impl, buffers, flags, init.completion_handler); + + return init.result.get(); + } + + /// Receive some data from the peer. + template + std::size_t receive(implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return service_impl_.receive(impl, buffers, flags, ec); + } + + /// Start an asynchronous receive. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler) + { + async_completion init(handler); + + service_impl_.async_receive(impl, buffers, flags, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_STREAM_SOCKET_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/streambuf.hpp b/tools/sdk/include/asio/asio/streambuf.hpp new file mode 100644 index 00000000000..cb3f35f7d67 --- /dev/null +++ b/tools/sdk/include/asio/asio/streambuf.hpp @@ -0,0 +1,33 @@ +// +// streambuf.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/system_context.hpp b/tools/sdk/include/asio/asio/system_context.hpp new file mode 100644 index 00000000000..ccd11134305 --- /dev/null +++ b/tools/sdk/include/asio/asio/system_context.hpp @@ -0,0 +1,78 @@ +// +// system_context.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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; + + // 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/include/asio/asio/system_error.hpp b/tools/sdk/include/asio/asio/system_error.hpp new file mode 100644 index 00000000000..63908941627 --- /dev/null +++ b/tools/sdk/include/asio/asio/system_error.hpp @@ -0,0 +1,131 @@ +// +// system_error.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/system_executor.hpp b/tools/sdk/include/asio/asio/system_executor.hpp new file mode 100644 index 00000000000..b588a21b410 --- /dev/null +++ b/tools/sdk/include/asio/asio/system_executor.hpp @@ -0,0 +1,129 @@ +// +// system_executor.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/system_timer.hpp b/tools/sdk/include/asio/asio/system_timer.hpp new file mode 100644 index 00000000000..e75e7d4c12b --- /dev/null +++ b/tools/sdk/include/asio/asio/system_timer.hpp @@ -0,0 +1,42 @@ +// +// system_timer.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/thread.hpp b/tools/sdk/include/asio/asio/thread.hpp new file mode 100644 index 00000000000..eeeef7bb5cf --- /dev/null +++ b/tools/sdk/include/asio/asio/thread.hpp @@ -0,0 +1,92 @@ +// +// thread.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/thread_pool.hpp b/tools/sdk/include/asio/asio/thread_pool.hpp new file mode 100644 index 00000000000..f22f18d1177 --- /dev/null +++ b/tools/sdk/include/asio/asio/thread_pool.hpp @@ -0,0 +1,232 @@ +// +// thread_pool.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 io_context, 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; + + // 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/include/asio/asio/time_traits.hpp b/tools/sdk/include/asio/asio/time_traits.hpp new file mode 100644 index 00000000000..72f4aabe782 --- /dev/null +++ b/tools/sdk/include/asio/asio/time_traits.hpp @@ -0,0 +1,86 @@ +// +// time_traits.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ts/buffer.hpp b/tools/sdk/include/asio/asio/ts/buffer.hpp new file mode 100644 index 00000000000..faf08a474b0 --- /dev/null +++ b/tools/sdk/include/asio/asio/ts/buffer.hpp @@ -0,0 +1,24 @@ +// +// ts/buffer.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ts/executor.hpp b/tools/sdk/include/asio/asio/ts/executor.hpp new file mode 100644 index 00000000000..8669cb6c577 --- /dev/null +++ b/tools/sdk/include/asio/asio/ts/executor.hpp @@ -0,0 +1,35 @@ +// +// ts/executor.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/handler_type.hpp" +#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/include/asio/asio/ts/internet.hpp b/tools/sdk/include/asio/asio/ts/internet.hpp new file mode 100644 index 00000000000..6282e905a02 --- /dev/null +++ b/tools/sdk/include/asio/asio/ts/internet.hpp @@ -0,0 +1,40 @@ +// +// ts/internet.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ts/io_context.hpp b/tools/sdk/include/asio/asio/ts/io_context.hpp new file mode 100644 index 00000000000..b967cd63edf --- /dev/null +++ b/tools/sdk/include/asio/asio/ts/io_context.hpp @@ -0,0 +1,20 @@ +// +// ts/io_context.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ts/net.hpp b/tools/sdk/include/asio/asio/ts/net.hpp new file mode 100644 index 00000000000..f96075d9fe6 --- /dev/null +++ b/tools/sdk/include/asio/asio/ts/net.hpp @@ -0,0 +1,26 @@ +// +// ts/net.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ts/netfwd.hpp b/tools/sdk/include/asio/asio/ts/netfwd.hpp new file mode 100644 index 00000000000..657a21d3727 --- /dev/null +++ b/tools/sdk/include/asio/asio/ts/netfwd.hpp @@ -0,0 +1,197 @@ +// +// ts/netfwd.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_ENABLE_OLD_SERVICES) + +template +class waitable_timer_service; + +#if defined(ASIO_HAS_BOOST_DATE_TIME) + +template +class deadline_timer_service; + +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#if !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) +#define ASIO_BASIC_WAITABLE_TIMER_FWD_DECL + +template + ASIO_SVC_TPARAM_DEF2(= waitable_timer_service)> +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) + +template +class basic_socket; + +template +class basic_datagram_socket; + +template +class basic_stream_socket; + +template +class basic_socket_acceptor; + +#if !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) +#define ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL + +// Forward declaration with defaulted arguments. +template ), +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + || defined(GENERATING_DOCUMENTATION) + typename Clock = boost::posix_time::ptime, + typename WaitTraits = time_traits + ASIO_SVC_TPARAM1_DEF2(= deadline_timer_service)> +#else + typename Clock = chrono::steady_clock, + typename WaitTraits = wait_traits + ASIO_SVC_TPARAM1_DEF1(= steady_timer::service_type)> +#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 ), +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + || defined(GENERATING_DOCUMENTATION) + typename Clock = boost::posix_time::ptime, + typename WaitTraits = time_traits + ASIO_SVC_TPARAM1_DEF2(= deadline_timer_service)> +#else + typename Clock = chrono::steady_clock, + typename WaitTraits = wait_traits + ASIO_SVC_TPARAM1_DEF1(= steady_timer::service_type)> +#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; + +template +class basic_resolver; + +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/include/asio/asio/ts/socket.hpp b/tools/sdk/include/asio/asio/ts/socket.hpp new file mode 100644 index 00000000000..a542734856e --- /dev/null +++ b/tools/sdk/include/asio/asio/ts/socket.hpp @@ -0,0 +1,27 @@ +// +// ts/socket.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/ts/timer.hpp b/tools/sdk/include/asio/asio/ts/timer.hpp new file mode 100644 index 00000000000..872be8bfd70 --- /dev/null +++ b/tools/sdk/include/asio/asio/ts/timer.hpp @@ -0,0 +1,26 @@ +// +// ts/timer.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/unyield.hpp b/tools/sdk/include/asio/asio/unyield.hpp new file mode 100644 index 00000000000..de3ed0275e4 --- /dev/null +++ b/tools/sdk/include/asio/asio/unyield.hpp @@ -0,0 +1,21 @@ +// +// unyield.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the 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/include/asio/asio/use_future.hpp b/tools/sdk/include/asio/asio/use_future.hpp new file mode 100644 index 00000000000..3f9c6968790 --- /dev/null +++ b/tools/sdk/include/asio/asio/use_future.hpp @@ -0,0 +1,159 @@ +// +// use_future.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" + +#if defined(ASIO_HAS_STD_FUTURE) \ + || 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) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_USE_FUTURE_HPP diff --git a/tools/sdk/include/asio/asio/uses_executor.hpp b/tools/sdk/include/asio/asio/uses_executor.hpp new file mode 100644 index 00000000000..e985c28245f --- /dev/null +++ b/tools/sdk/include/asio/asio/uses_executor.hpp @@ -0,0 +1,71 @@ +// +// uses_executor.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/version.hpp b/tools/sdk/include/asio/asio/version.hpp new file mode 100644 index 00000000000..ee0313f7366 --- /dev/null +++ b/tools/sdk/include/asio/asio/version.hpp @@ -0,0 +1,23 @@ +// +// version.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 101200 // 1.12.0 + +#endif // ASIO_VERSION_HPP diff --git a/tools/sdk/include/asio/asio/wait_traits.hpp b/tools/sdk/include/asio/asio/wait_traits.hpp new file mode 100644 index 00000000000..a6016f7c037 --- /dev/null +++ b/tools/sdk/include/asio/asio/wait_traits.hpp @@ -0,0 +1,56 @@ +// +// wait_traits.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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/include/asio/asio/waitable_timer_service.hpp b/tools/sdk/include/asio/asio/waitable_timer_service.hpp new file mode 100644 index 00000000000..75e496f8d28 --- /dev/null +++ b/tools/sdk/include/asio/asio/waitable_timer_service.hpp @@ -0,0 +1,210 @@ +// +// waitable_timer_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WAITABLE_TIMER_SERVICE_HPP +#define ASIO_WAITABLE_TIMER_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_ENABLE_OLD_SERVICES) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/chrono_time_traits.hpp" +#include "asio/detail/deadline_timer_service.hpp" +#include "asio/io_context.hpp" +#include "asio/wait_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default service implementation for a timer. +template > +class waitable_timer_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base< + waitable_timer_service > +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + + /// 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; + +private: + // The type of the platform-specific implementation. + typedef detail::deadline_timer_service< + detail::chrono_time_traits > service_impl_type; + +public: + /// The implementation type of the waitable timer. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef typename service_impl_type::implementation_type implementation_type; +#endif + + /// Construct a new timer service for the specified io_context. + explicit waitable_timer_service(asio::io_context& io_context) + : asio::detail::service_base< + waitable_timer_service >(io_context), + service_impl_(io_context) + { + } + + /// Construct a new timer implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + + /// Destroy a timer implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new timer implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another timer implementation. + void move_assign(implementation_type& impl, + waitable_timer_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Cancel any asynchronous wait operations associated with the timer. + std::size_t cancel(implementation_type& impl, asio::error_code& ec) + { + return service_impl_.cancel(impl, ec); + } + + /// Cancels one asynchronous wait operation associated with the timer. + std::size_t cancel_one(implementation_type& impl, + asio::error_code& ec) + { + return service_impl_.cancel_one(impl, ec); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use expiry().) Get the expiry time for the timer as an + /// absolute time. + time_point expires_at(const implementation_type& impl) const + { + return service_impl_.expiry(impl); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the expiry time for the timer as an absolute time. + time_point expiry(const implementation_type& impl) const + { + return service_impl_.expiry(impl); + } + + /// Set the expiry time for the timer as an absolute time. + std::size_t expires_at(implementation_type& impl, + const time_point& expiry_time, asio::error_code& ec) + { + return service_impl_.expires_at(impl, expiry_time, ec); + } + + /// Set the expiry time for the timer relative to now. + std::size_t expires_after(implementation_type& impl, + const duration& expiry_time, asio::error_code& ec) + { + return service_impl_.expires_after(impl, expiry_time, ec); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use expiry().) Get the expiry time for the timer relative to + /// now. + duration expires_from_now(const implementation_type& impl) const + { + typedef detail::chrono_time_traits traits; + return traits::subtract(service_impl_.expiry(impl), traits::now()); + } + + /// (Deprecated: Use expires_after().) Set the expiry time for the timer + /// relative to now. + std::size_t expires_from_now(implementation_type& impl, + const duration& expiry_time, asio::error_code& ec) + { + return service_impl_.expires_after(impl, expiry_time, ec); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + // Perform a blocking wait on the timer. + void wait(implementation_type& impl, asio::error_code& ec) + { + service_impl_.wait(impl, ec); + } + + // Start an asynchronous wait on the timer. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, + ASIO_MOVE_ARG(WaitHandler) handler) + { + async_completion init(handler); + + service_impl_.async_wait(impl, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WAITABLE_TIMER_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/windows/basic_handle.hpp b/tools/sdk/include/asio/asio/windows/basic_handle.hpp new file mode 100644 index 00000000000..f7c9d0d0368 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/basic_handle.hpp @@ -0,0 +1,273 @@ +// +// windows/basic_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_HANDLE_HPP +#define ASIO_WINDOWS_BASIC_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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ + || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ + || defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_io_object.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Provides Windows handle functionality. +/** + * The windows::basic_handle class template provides the ability to wrap a + * Windows handle. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_handle + : public basic_io_object +{ +public: + /// The native representation of a handle. + typedef typename HandleService::native_handle_type native_handle_type; + + /// A basic_handle is always the lowest layer. + typedef basic_handle lowest_layer_type; + + /// Construct a basic_handle without opening it. + /** + * This constructor creates a handle without opening it. + * + * @param io_context The io_context object that the handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + */ + explicit basic_handle(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct a basic_handle on an existing native handle. + /** + * This constructor creates a handle object to hold an existing native handle. + * + * @param io_context The io_context object that the handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + * + * @param handle A native handle. + * + * @throws asio::system_error Thrown on failure. + */ + basic_handle(asio::io_context& io_context, + const native_handle_type& handle) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->get_implementation(), handle, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_handle from another. + /** + * This constructor moves a handle from one object to another. + * + * @param other The other basic_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_handle(io_context&) constructor. + */ + basic_handle(basic_handle&& other) + : basic_io_object( + ASIO_MOVE_CAST(basic_handle)(other)) + { + } + + /// Move-assign a basic_handle from another. + /** + * This assignment operator moves a handle from one object to another. + * + * @param other The other basic_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_handle(io_context&) constructor. + */ + basic_handle& operator=(basic_handle&& other) + { + basic_io_object::operator=( + ASIO_MOVE_CAST(basic_handle)(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * layers. Since a basic_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 a basic_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; + this->get_service().assign(this->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) + { + this->get_service().assign(this->get_implementation(), handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open() const + { + return this->get_service().is_open(this->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; + this->get_service().close(this->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) + { + this->get_service().close(this->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 this->get_service().native_handle(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + +protected: + /// Protected destructor to prevent deletion through this type. + ~basic_handle() + { + } +}; + +} // 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(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WINDOWS_BASIC_HANDLE_HPP diff --git a/tools/sdk/include/asio/asio/windows/basic_object_handle.hpp b/tools/sdk/include/asio/asio/windows/basic_object_handle.hpp new file mode 100644 index 00000000000..4b2968460b7 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/basic_object_handle.hpp @@ -0,0 +1,182 @@ +// +// windows/basic_object_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/windows/basic_handle.hpp" +#include "asio/windows/object_handle_service.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Provides object-oriented handle functionality. +/** + * The windows::basic_object_handle class template 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 basic_handle +{ +public: + /// The native representation of a handle. + typedef typename ObjectHandleService::native_handle_type native_handle_type; + + /// Construct a basic_object_handle without opening it. + /** + * This constructor creates an object handle without opening it. + * + * @param io_context The io_context object that the object handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + */ + explicit basic_object_handle(asio::io_context& io_context) + : basic_handle(io_context) + { + } + + /// Construct a basic_object_handle on an existing native handle. + /** + * This constructor creates an object handle object to hold an existing native + * handle. + * + * @param io_context The io_context object that the object handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + * + * @param native_handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_object_handle(asio::io_context& io_context, + const native_handle_type& native_handle) + : basic_handle(io_context, native_handle) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_object_handle from another. + /** + * This constructor moves an object handle from one object to another. + * + * @param other The other basic_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(io_context&) constructor. + */ + basic_object_handle(basic_object_handle&& other) + : basic_handle( + ASIO_MOVE_CAST(basic_object_handle)(other)) + { + } + + /// Move-assign a basic_object_handle from another. + /** + * This assignment operator moves an object handle from one object to another. + * + * @param other The other basic_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(io_context&) constructor. + */ + basic_object_handle& operator=(basic_object_handle&& other) + { + basic_handle::operator=( + ASIO_MOVE_CAST(basic_object_handle)(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// 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; + this->get_service().wait(this->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) + { + this->get_service().wait(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(ASIO_MOVE_ARG(WaitHandler) handler) + { + return this->get_service().async_wait(this->get_implementation(), + ASIO_MOVE_CAST(WaitHandler)(handler)); + } +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WINDOWS_BASIC_OBJECT_HANDLE_HPP diff --git a/tools/sdk/include/asio/asio/windows/basic_random_access_handle.hpp b/tools/sdk/include/asio/asio/windows/basic_random_access_handle.hpp new file mode 100644 index 00000000000..4226977315e --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/basic_random_access_handle.hpp @@ -0,0 +1,376 @@ +// +// windows/basic_random_access_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" + +#if defined(ASIO_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/windows/basic_handle.hpp" +#include "asio/windows/random_access_handle_service.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Provides random-access handle functionality. +/** + * The windows::basic_random_access_handle class template 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_handle +{ +public: + /// The native representation of a handle. + typedef typename RandomAccessHandleService::native_handle_type + native_handle_type; + + /// Construct a basic_random_access_handle without opening it. + /** + * This constructor creates a random-access handle without opening it. The + * handle needs to be opened before data can be written to or read from it. + * + * @param io_context The io_context object that the random-access handle will + * use to dispatch handlers for any asynchronous operations performed on the + * handle. + */ + explicit basic_random_access_handle(asio::io_context& io_context) + : basic_handle(io_context) + { + } + + /// Construct a basic_random_access_handle on an existing native handle. + /** + * This constructor creates a random-access handle object to hold an existing + * native handle. + * + * @param io_context The io_context object that the random-access handle will + * use to dispatch handlers for any asynchronous operations performed on the + * handle. + * + * @param handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_random_access_handle(asio::io_context& io_context, + const native_handle_type& handle) + : basic_handle(io_context, handle) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_random_access_handle from another. + /** + * This constructor moves a random-access handle from one object to another. + * + * @param other The other basic_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(io_context&) + * constructor. + */ + basic_random_access_handle(basic_random_access_handle&& other) + : basic_handle( + ASIO_MOVE_CAST(basic_random_access_handle)(other)) + { + } + + /// Move-assign a basic_random_access_handle from another. + /** + * This assignment operator moves a random-access handle from one object to + * another. + * + * @param other The other basic_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(io_context&) + * constructor. + */ + basic_random_access_handle& operator=(basic_random_access_handle&& other) + { + basic_handle::operator=( + ASIO_MOVE_CAST(basic_random_access_handle)(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->get_service().write_some_at( + this->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->get_service().write_some_at( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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; + + return this->get_service().async_write_some_at(this->get_implementation(), + offset, buffers, ASIO_MOVE_CAST(WriteHandler)(handler)); + } + + /// 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->get_service().read_some_at( + this->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->get_service().read_some_at( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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 this->get_service().async_read_some_at(this->get_implementation(), + offset, buffers, ASIO_MOVE_CAST(ReadHandler)(handler)); + } +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WINDOWS_BASIC_RANDOM_ACCESS_HANDLE_HPP diff --git a/tools/sdk/include/asio/asio/windows/basic_stream_handle.hpp b/tools/sdk/include/asio/asio/windows/basic_stream_handle.hpp new file mode 100644 index 00000000000..3bfce6884f0 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/basic_stream_handle.hpp @@ -0,0 +1,359 @@ +// +// windows/basic_stream_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" + +#if defined(ASIO_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/windows/basic_handle.hpp" +#include "asio/windows/stream_handle_service.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Provides stream-oriented handle functionality. +/** + * The windows::basic_stream_handle class template 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_handle +{ +public: + /// The native representation of a handle. + typedef typename StreamHandleService::native_handle_type native_handle_type; + + /// Construct a basic_stream_handle without opening it. + /** + * This constructor creates a stream handle without opening it. The handle + * needs to be opened and then connected or accepted before data can be sent + * or received on it. + * + * @param io_context The io_context object that the stream handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + */ + explicit basic_stream_handle(asio::io_context& io_context) + : basic_handle(io_context) + { + } + + /// Construct a basic_stream_handle on an existing native handle. + /** + * This constructor creates a stream handle object to hold an existing native + * handle. + * + * @param io_context The io_context object that the stream handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + * + * @param handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_stream_handle(asio::io_context& io_context, + const native_handle_type& handle) + : basic_handle(io_context, handle) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_stream_handle from another. + /** + * This constructor moves a stream handle from one object to another. + * + * @param other The other basic_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(io_context&) constructor. + */ + basic_stream_handle(basic_stream_handle&& other) + : basic_handle( + ASIO_MOVE_CAST(basic_stream_handle)(other)) + { + } + + /// Move-assign a basic_stream_handle from another. + /** + * This assignment operator moves a stream handle from one object to + * another. + * + * @param other The other basic_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(io_context&) constructor. + */ + basic_stream_handle& operator=(basic_stream_handle&& other) + { + basic_handle::operator=( + ASIO_MOVE_CAST(basic_stream_handle)(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->get_service().write_some( + this->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->get_service().write_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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; + + return this->get_service().async_write_some(this->get_implementation(), + buffers, ASIO_MOVE_CAST(WriteHandler)(handler)); + } + + /// 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->get_service().read_some( + this->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->get_service().read_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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 this->get_service().async_read_some(this->get_implementation(), + buffers, ASIO_MOVE_CAST(ReadHandler)(handler)); + } +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WINDOWS_BASIC_STREAM_HANDLE_HPP diff --git a/tools/sdk/include/asio/asio/windows/object_handle.hpp b/tools/sdk/include/asio/asio/windows/object_handle.hpp new file mode 100644 index 00000000000..581b5680011 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/object_handle.hpp @@ -0,0 +1,381 @@ +// +// windows/object_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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/async_result.hpp" +#include "asio/basic_io_object.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/win_object_handle_service.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/windows/basic_object_handle.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#define ASIO_SVC_T asio::detail::win_object_handle_service + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +#if defined(ASIO_ENABLE_OLD_SERVICES) +// Typedef for the typical usage of an object handle. +typedef basic_object_handle<> object_handle; +#else // defined(ASIO_ENABLE_OLD_SERVICES) +/// Provides object-oriented handle functionality. +/** + * The windows::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. + */ +class object_handle + : ASIO_SVC_ACCESS basic_io_object +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// The native representation of a handle. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef ASIO_SVC_T::native_handle_type native_handle_type; +#endif + + /// An object_handle is always the lowest layer. + typedef object_handle lowest_layer_type; + + /// Construct an object_handle without opening it. + /** + * This constructor creates an object handle without opening it. + * + * @param io_context The io_context object that the object handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + */ + explicit object_handle(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct an object_handle on an existing native handle. + /** + * This constructor creates an object handle object to hold an existing native + * handle. + * + * @param io_context The io_context object that the object handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + * + * @param native_handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + object_handle(asio::io_context& io_context, + const native_handle_type& native_handle) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->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 object_handle(io_context&) constructor. + */ + object_handle(object_handle&& other) + : basic_io_object(std::move(other)) + { + } + + /// 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 object_handle(io_context&) constructor. + */ + object_handle& operator=(object_handle&& other) + { + basic_io_object::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::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; + this->get_service().assign(this->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) + { + this->get_service().assign(this->get_implementation(), handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open() const + { + return this->get_service().is_open(this->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; + this->get_service().close(this->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) + { + this->get_service().close(this->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 this->get_service().native_handle(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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; + this->get_service().wait(this->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) + { + this->get_service().wait(this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(ASIO_MOVE_ARG(WaitHandler) handler) + { + asio::async_completion init(handler); + + this->get_service().async_wait(this->get_implementation(), + init.completion_handler); + + return init.result.get(); + } +}; +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#undef ASIO_SVC_T + +#endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_OBJECT_HANDLE_HPP diff --git a/tools/sdk/include/asio/asio/windows/object_handle_service.hpp b/tools/sdk/include/asio/asio/windows/object_handle_service.hpp new file mode 100644 index 00000000000..95436d790e0 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/object_handle_service.hpp @@ -0,0 +1,183 @@ +// +// windows/object_handle_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 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_SERVICE_HPP +#define ASIO_WINDOWS_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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/async_result.hpp" +#include "asio/detail/win_object_handle_service.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Default service implementation for an object handle. +class object_handle_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + +private: + // The type of the platform-specific implementation. + typedef detail::win_object_handle_service service_impl_type; + +public: + /// The type of an object handle implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef service_impl_type::implementation_type implementation_type; +#endif + + /// The native handle type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new object handle service for the specified io_context. + explicit object_handle_service(asio::io_context& io_context) + : asio::detail::service_base(io_context), + service_impl_(io_context) + { + } + + /// Construct a new object handle implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new object handle implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another object handle implementation. + void move_assign(implementation_type& impl, + object_handle_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy an object handle implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Assign an existing native handle to an object handle. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const native_handle_type& handle, asio::error_code& ec) + { + service_impl_.assign(impl, handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close an object handle implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native handle implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Cancel all asynchronous operations associated with the handle. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + // Wait for a signaled state. + void wait(implementation_type& impl, asio::error_code& ec) + { + service_impl_.wait(impl, ec); + } + + /// Start an asynchronous wait. + template + ASIO_INITFN_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(implementation_type& impl, + ASIO_MOVE_ARG(WaitHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_wait(impl, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WINDOWS_OBJECT_HANDLE_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/windows/overlapped_handle.hpp b/tools/sdk/include/asio/asio/windows/overlapped_handle.hpp new file mode 100644 index 00000000000..3d479ba6c82 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/overlapped_handle.hpp @@ -0,0 +1,331 @@ +// +// windows/overlapped_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_ENABLE_OLD_SERVICES) + +#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/basic_io_object.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/win_iocp_handle_service.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#define ASIO_SVC_T asio::detail::win_iocp_handle_service + +#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. + */ +class overlapped_handle + : ASIO_SVC_ACCESS basic_io_object +{ +public: + /// The type of the executor associated with the object. + typedef io_context::executor_type executor_type; + + /// The native representation of a handle. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef ASIO_SVC_T::native_handle_type native_handle_type; +#endif + + /// An overlapped_handle is always the lowest layer. + typedef overlapped_handle lowest_layer_type; + + /// Construct an overlapped_handle without opening it. + /** + * This constructor creates a handle without opening it. + * + * @param io_context The io_context object that the handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + */ + explicit overlapped_handle(asio::io_context& io_context) + : basic_io_object(io_context) + { + } + + /// Construct an overlapped_handle on an existing native handle. + /** + * This constructor creates a handle object to hold an existing native handle. + * + * @param io_context The io_context object that the handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + * + * @param handle A native handle. + * + * @throws asio::system_error Thrown on failure. + */ + overlapped_handle(asio::io_context& io_context, + const native_handle_type& handle) + : basic_io_object(io_context) + { + asio::error_code ec; + this->get_service().assign(this->get_implementation(), 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(io_context&) constructor. + */ + overlapped_handle(overlapped_handle&& other) + : basic_io_object(std::move(other)) + { + } + + /// 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(io_context&) constructor. + */ + overlapped_handle& operator=(overlapped_handle&& other) + { + basic_io_object::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + +#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 basic_io_object::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 basic_io_object::get_io_service(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return basic_io_object::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; + this->get_service().assign(this->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) + { + this->get_service().assign(this->get_implementation(), handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open() const + { + return this->get_service().is_open(this->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; + this->get_service().close(this->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) + { + this->get_service().close(this->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 this->get_service().native_handle(this->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; + this->get_service().cancel(this->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) + { + this->get_service().cancel(this->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. + */ + ~overlapped_handle() + { + } +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#undef ASIO_SVC_T + +#endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + // || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // !defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WINDOWS_OVERLAPPED_HANDLE_HPP diff --git a/tools/sdk/include/asio/asio/windows/overlapped_ptr.hpp b/tools/sdk/include/asio/asio/windows/overlapped_ptr.hpp new file mode 100644 index 00000000000..ce0b2a42d22 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/overlapped_ptr.hpp @@ -0,0 +1,116 @@ +// +// windows/overlapped_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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(asio::io_context& io_context, + ASIO_MOVE_ARG(Handler) handler) + : impl_(io_context, 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(asio::io_context& io_context, + ASIO_MOVE_ARG(Handler) handler) + { + impl_.reset(io_context, 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/include/asio/asio/windows/random_access_handle.hpp b/tools/sdk/include/asio/asio/windows/random_access_handle.hpp new file mode 100644 index 00000000000..301d5f8dd35 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/random_access_handle.hpp @@ -0,0 +1,378 @@ +// +// windows/random_access_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" +#include "asio/windows/overlapped_handle.hpp" + +#if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/windows/basic_random_access_handle.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +#if defined(ASIO_ENABLE_OLD_SERVICES) +// Typedef for the typical usage of a random-access handle. +typedef basic_random_access_handle<> random_access_handle; +#else // defined(ASIO_ENABLE_OLD_SERVICES) +/// Provides random-access handle functionality. +/** + * The windows::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. + */ +class random_access_handle + : public overlapped_handle +{ +public: + /// Construct a random_access_handle without opening it. + /** + * This constructor creates a random-access handle without opening it. The + * handle needs to be opened before data can be written to or read from it. + * + * @param io_context The io_context object that the random-access handle will + * use to dispatch handlers for any asynchronous operations performed on the + * handle. + */ + explicit random_access_handle(asio::io_context& io_context) + : overlapped_handle(io_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 io_context The io_context object that the random-access handle will + * use to dispatch handlers for any asynchronous operations performed on the + * handle. + * + * @param handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + random_access_handle(asio::io_context& io_context, + const native_handle_type& handle) + : overlapped_handle(io_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 random_access_handle(io_context&) + * constructor. + */ + random_access_handle(random_access_handle&& other) + : 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 random_access_handle(io_context&) + * constructor. + */ + random_access_handle& operator=(random_access_handle&& other) + { + 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->get_service().write_some_at( + this->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->get_service().write_some_at( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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::async_completion init(handler); + + this->get_service().async_write_some_at(this->get_implementation(), + offset, buffers, init.completion_handler); + + return init.result.get(); + } + + /// 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->get_service().read_some_at( + this->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->get_service().read_some_at( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_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) + { + // 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::async_completion init(handler); + + this->get_service().async_read_some_at(this->get_implementation(), + offset, buffers, init.completion_handler); + + return init.result.get(); + } +}; +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP diff --git a/tools/sdk/include/asio/asio/windows/random_access_handle_service.hpp b/tools/sdk/include/asio/asio/windows/random_access_handle_service.hpp new file mode 100644 index 00000000000..ebccf3e3944 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/random_access_handle_service.hpp @@ -0,0 +1,214 @@ +// +// windows/random_access_handle_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_SERVICE_HPP +#define ASIO_WINDOWS_RANDOM_ACCESS_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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/cstdint.hpp" +#include "asio/detail/win_iocp_handle_service.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Default service implementation for a random-access handle. +class random_access_handle_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + +private: + // The type of the platform-specific implementation. + typedef detail::win_iocp_handle_service service_impl_type; + +public: + /// The type of a random-access handle implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef service_impl_type::implementation_type implementation_type; +#endif + + /// The native handle type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new random-access handle service for the specified io_context. + explicit random_access_handle_service(asio::io_context& io_context) + : asio::detail::service_base< + random_access_handle_service>(io_context), + service_impl_(io_context) + { + } + + /// Construct a new random-access handle implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new random-access handle implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another random-access handle implementation. + void move_assign(implementation_type& impl, + random_access_handle_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a random-access handle implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Assign an existing native handle to a random-access handle. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const native_handle_type& handle, asio::error_code& ec) + { + service_impl_.assign(impl, handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close a random-access handle implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native handle implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Cancel all asynchronous operations associated with the handle. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Write the given data at the specified offset. + template + std::size_t write_some_at(implementation_type& impl, uint64_t offset, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + return service_impl_.write_some_at(impl, offset, buffers, ec); + } + + /// Start an asynchronous write at the specified offset. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some_at(implementation_type& impl, + uint64_t offset, const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_write_some_at(impl, + offset, buffers, init.completion_handler); + + return init.result.get(); + } + + /// Read some data from the specified offset. + template + std::size_t read_some_at(implementation_type& impl, uint64_t offset, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + return service_impl_.read_some_at(impl, offset, buffers, ec); + } + + /// Start an asynchronous read at the specified offset. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some_at(implementation_type& impl, + uint64_t offset, const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_read_some_at(impl, + offset, buffers, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/windows/stream_handle.hpp b/tools/sdk/include/asio/asio/windows/stream_handle.hpp new file mode 100644 index 00000000000..8f0a21b1fe9 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/stream_handle.hpp @@ -0,0 +1,362 @@ +// +// windows/stream_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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" +#include "asio/windows/overlapped_handle.hpp" + +#if defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#if defined(ASIO_ENABLE_OLD_SERVICES) +# include "asio/windows/basic_stream_handle.hpp" +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +#if defined(ASIO_ENABLE_OLD_SERVICES) +// Typedef for the typical usage of a stream-oriented handle. +typedef basic_stream_handle<> stream_handle; +#else // defined(ASIO_ENABLE_OLD_SERVICES) +/// Provides stream-oriented handle functionality. +/** + * The windows::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. + */ +class stream_handle + : public overlapped_handle +{ +public: + /// Construct a stream_handle without opening it. + /** + * This constructor creates a stream handle without opening it. The handle + * needs to be opened and then connected or accepted before data can be sent + * or received on it. + * + * @param io_context The io_context object that the stream handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + */ + explicit stream_handle(asio::io_context& io_context) + : overlapped_handle(io_context) + { + } + + /// Construct a stream_handle on an existing native handle. + /** + * This constructor creates a stream handle object to hold an existing native + * handle. + * + * @param io_context The io_context object that the stream handle will use to + * dispatch handlers for any asynchronous operations performed on the handle. + * + * @param handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + stream_handle(asio::io_context& io_context, + const native_handle_type& handle) + : overlapped_handle(io_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 stream_handle(io_context&) constructor. + */ + stream_handle(stream_handle&& other) + : 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 stream_handle(io_context&) constructor. + */ + stream_handle& operator=(stream_handle&& other) + { + 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->get_service().write_some( + this->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->get_service().write_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + // 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::async_completion init(handler); + + this->get_service().async_write_some( + this->get_implementation(), buffers, init.completion_handler); + + return init.result.get(); + } + + /// 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->get_service().read_some( + this->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->get_service().read_some( + this->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. Invocation + * of the handler will be performed in a manner equivalent to using + * asio::io_context::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_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + // 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::async_completion init(handler); + + this->get_service().async_read_some( + this->get_implementation(), buffers, init.completion_handler); + + return init.result.get(); + } +}; +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_STREAM_HANDLE_HPP diff --git a/tools/sdk/include/asio/asio/windows/stream_handle_service.hpp b/tools/sdk/include/asio/asio/windows/stream_handle_service.hpp new file mode 100644 index 00000000000..1c665d5e1e0 --- /dev/null +++ b/tools/sdk/include/asio/asio/windows/stream_handle_service.hpp @@ -0,0 +1,210 @@ +// +// windows/stream_handle_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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_SERVICE_HPP +#define ASIO_WINDOWS_STREAM_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_ENABLE_OLD_SERVICES) + +#if defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/win_iocp_handle_service.hpp" +#include "asio/error.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Default service implementation for a stream handle. +class stream_handle_service +#if defined(GENERATING_DOCUMENTATION) + : public asio::io_context::service +#else + : public asio::detail::service_base +#endif +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The unique service identifier. + static asio::io_context::id id; +#endif + +private: + // The type of the platform-specific implementation. + typedef detail::win_iocp_handle_service service_impl_type; + +public: + /// The type of a stream handle implementation. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined implementation_type; +#else + typedef service_impl_type::implementation_type implementation_type; +#endif + + /// The native handle type. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef service_impl_type::native_handle_type native_handle_type; +#endif + + /// Construct a new stream handle service for the specified io_context. + explicit stream_handle_service(asio::io_context& io_context) + : asio::detail::service_base(io_context), + service_impl_(io_context) + { + } + + /// Construct a new stream handle implementation. + void construct(implementation_type& impl) + { + service_impl_.construct(impl); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a new stream handle implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + service_impl_.move_construct(impl, other_impl); + } + + /// Move-assign from another stream handle implementation. + void move_assign(implementation_type& impl, + stream_handle_service& other_service, + implementation_type& other_impl) + { + service_impl_.move_assign(impl, other_service.service_impl_, other_impl); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroy a stream handle implementation. + void destroy(implementation_type& impl) + { + service_impl_.destroy(impl); + } + + /// Assign an existing native handle to a stream handle. + ASIO_SYNC_OP_VOID assign(implementation_type& impl, + const native_handle_type& handle, asio::error_code& ec) + { + service_impl_.assign(impl, handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open(const implementation_type& impl) const + { + return service_impl_.is_open(impl); + } + + /// Close a stream handle implementation. + ASIO_SYNC_OP_VOID close(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.close(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native handle implementation. + native_handle_type native_handle(implementation_type& impl) + { + return service_impl_.native_handle(impl); + } + + /// Cancel all asynchronous operations associated with the handle. + ASIO_SYNC_OP_VOID cancel(implementation_type& impl, + asio::error_code& ec) + { + service_impl_.cancel(impl, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Write the given data to the stream. + template + std::size_t write_some(implementation_type& impl, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + return service_impl_.write_some(impl, buffers, ec); + } + + /// Start an asynchronous write. + template + ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(implementation_type& impl, + const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_write_some(impl, buffers, init.completion_handler); + + return init.result.get(); + } + + /// Read some data from the stream. + template + std::size_t read_some(implementation_type& impl, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + return service_impl_.read_some(impl, buffers, ec); + } + + /// Start an asynchronous read. + template + ASIO_INITFN_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(implementation_type& impl, + const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) + { + asio::async_completion init(handler); + + service_impl_.async_read_some(impl, buffers, init.completion_handler); + + return init.result.get(); + } + +private: + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + service_impl_.shutdown(); + } + + // The platform-specific implementation. + service_impl_type service_impl_; +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // defined(ASIO_ENABLE_OLD_SERVICES) + +#endif // ASIO_WINDOWS_STREAM_HANDLE_SERVICE_HPP diff --git a/tools/sdk/include/asio/asio/write.hpp b/tools/sdk/include/asio/asio/write.hpp new file mode 100644 index 00000000000..517a8420537 --- /dev/null +++ b/tools/sdk/include/asio/asio/write.hpp @@ -0,0 +1,927 @@ +// +// write.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 Write 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); + +/// 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) buffers, + typename enable_if< + is_dynamic_buffer::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) buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer::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) buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer::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) buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer::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) + +/*@}*/ +/** + * @defgroup async_write asio::async_write + * + * @brief Start an asynchronous operation to write a certain amount of data to a + * stream. + */ +/*@{*/ + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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* = 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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* = 0); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_dynamic_buffer::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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer) buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_dynamic_buffer::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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, basic_streambuf& b, + ASIO_MOVE_ARG(WriteHandler) handler); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_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); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/write.hpp" + +#endif // ASIO_WRITE_HPP diff --git a/tools/sdk/include/asio/asio/write_at.hpp b/tools/sdk/include/asio/asio/write_at.hpp new file mode 100644 index 00000000000..5018d210605 --- /dev/null +++ b/tools/sdk/include/asio/asio/write_at.hpp @@ -0,0 +1,677 @@ +// +// write_at.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software 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 Write 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 Start an asynchronous operation to write a certain amount of data at + * the specified offset. + */ +/*@{*/ + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::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_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); + +#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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_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); + +/// 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. Invocation of + * the handler will be performed in a manner equivalent to using + * asio::io_context::post(). + */ +template +ASIO_INITFN_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); + +#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/include/asio/asio/yield.hpp b/tools/sdk/include/asio/asio/yield.hpp new file mode 100644 index 00000000000..b527ac9b4b2 --- /dev/null +++ b/tools/sdk/include/asio/asio/yield.hpp @@ -0,0 +1,23 @@ +// +// yield.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the 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/include/asio/esp_asio_config.h b/tools/sdk/include/asio/esp_asio_config.h new file mode 100644 index 00000000000..accccad0da7 --- /dev/null +++ b/tools/sdk/include/asio/esp_asio_config.h @@ -0,0 +1,45 @@ +// 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_CXX_EXCEPTIONS +# define ASIO_NO_EXCEPTIONS +# endif // CONFIG_CXX_EXCEPTIONS + +// +// LWIP compatifility 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_NO_TYPEID +# define ASIO_DISABLE_SIGNAL +# define ASIO_HAS_PTHREADS +# define ASIO_DISABLE_EPOLL +# define ASIO_DISABLE_EVENTFD +# define ASIO_DISABLE_SIGNAL +# define ASIO_DISABLE_SIGACTION + +#endif // _ESP_ASIO_CONFIG_H_ diff --git a/tools/sdk/include/asio/esp_exception.h b/tools/sdk/include/asio/esp_exception.h new file mode 100644 index 00000000000..3c5c043755f --- /dev/null +++ b/tools/sdk/include/asio/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_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_CXX_EXCEPTIONS==1 && defined (ASIO_NO_EXCEPTIONS) + +#endif // _ESP_EXCEPTION_H_ diff --git a/tools/sdk/include/bluedroid/a2d_api.h b/tools/sdk/include/bluedroid/a2d_api.h deleted file mode 100644 index eaf6b37f140..00000000000 --- a/tools/sdk/include/bluedroid/a2d_api.h +++ /dev/null @@ -1,256 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2000-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * nterface to A2DP Application Programming Interface - * - ******************************************************************************/ -#ifndef A2D_API_H -#define A2D_API_H -#include "sdp_api.h" -#if (A2D_INCLUDED == TRUE) -/***************************************************************************** -** constants -*****************************************************************************/ - -/* Profile supported features */ -#define A2D_SUPF_PLAYER 0x0001 -#define A2D_SUPF_MIC 0x0002 -#define A2D_SUPF_TUNER 0x0004 -#define A2D_SUPF_MIXER 0x0008 - -#define A2D_SUPF_HEADPHONE 0x0001 -#define A2D_SUPF_SPEAKER 0x0002 -#define A2D_SUPF_RECORDER 0x0004 -#define A2D_SUPF_AMP 0x0008 - -/* AV Media Types */ -#define A2D_MEDIA_TYPE_AUDIO 0x00 /* audio media type + RFA */ -#define A2D_MEDIA_TYPE_VIDEO 0x10 /* video media type + RFA */ -#define A2D_MEDIA_TYPE_MULTI 0x20 /* multimedia media type + RFA */ - -/* AV Media Codec Type (Audio Codec ID) */ -#define A2D_MEDIA_CT_SBC 0x00 /* SBC media codec type */ -#define A2D_MEDIA_CT_M12 0x01 /* MPEG-1, 2 Audio media codec type */ -#define A2D_MEDIA_CT_M24 0x02 /* MPEG-2, 4 AAC media codec type */ -#define A2D_MEDIA_CT_ATRAC 0x04 /* ATRAC family media codec type */ - -#define A2D_SUCCESS 0 /* Success */ -#define A2D_FAIL 0x0A /* Failed */ -#define A2D_BUSY 0x0B /* A2D_FindService is already in progress */ -#define A2D_INVALID_PARAMS 0x0C /* bad parameters */ -#define A2D_WRONG_CODEC 0x0D /* wrong codec info */ -#define A2D_BAD_CODEC_TYPE 0xC1 /* Media Codec Type is not valid */ -#define A2D_NS_CODEC_TYPE 0xC2 /* Media Codec Type is not supported */ -#define A2D_BAD_SAMP_FREQ 0xC3 /* Sampling Frequency is not valid or multiple values have been selected */ -#define A2D_NS_SAMP_FREQ 0xC4 /* Sampling Frequency is not supported */ -#define A2D_BAD_CH_MODE 0xC5 /* Channel Mode is not valid or multiple values have been selected */ -#define A2D_NS_CH_MODE 0xC6 /* Channel Mode is not supported */ -#define A2D_BAD_SUBBANDS 0xC7 /* None or multiple values have been selected for Number of Subbands */ -#define A2D_NS_SUBBANDS 0xC8 /* Number of Subbands is not supported */ -#define A2D_BAD_ALLOC_MTHD 0xC9 /* None or multiple values have been selected for Allocation Method */ -#define A2D_NS_ALLOC_MTHD 0xCA /* Allocation Method is not supported */ -#define A2D_BAD_MIN_BITPOOL 0xCB /* Minimum Bitpool Value is not valid */ -#define A2D_NS_MIN_BITPOOL 0xCC /* Minimum Bitpool Value is not supported */ -#define A2D_BAD_MAX_BITPOOL 0xCD /* Maximum Bitpool Value is not valid */ -#define A2D_NS_MAX_BITPOOL 0xCE /* Maximum Bitpool Value is not supported */ -#define A2D_BAD_LAYER 0xCF /* None or multiple values have been selected for Layer */ -#define A2D_NS_LAYER 0xD0 /* Layer is not supported */ -#define A2D_NS_CRC 0xD1 /* CRC is not supported */ -#define A2D_NS_MPF 0xD2 /* MPF-2 is not supported */ -#define A2D_NS_VBR 0xD3 /* VBR is not supported */ -#define A2D_BAD_BIT_RATE 0xD4 /* None or multiple values have been selected for Bit Rate */ -#define A2D_NS_BIT_RATE 0xD5 /* Bit Rate is not supported */ -#define A2D_BAD_OBJ_TYPE 0xD6 /* Either 1) Object type is not valid (b3-b0) or 2) None or multiple values have been selected for Object Type */ -#define A2D_NS_OBJ_TYPE 0xD7 /* Object type is not supported */ -#define A2D_BAD_CHANNEL 0xD8 /* None or multiple values have been selected for Channels */ -#define A2D_NS_CHANNEL 0xD9 /* Channels is not supported */ -#define A2D_BAD_BLOCK_LEN 0xDD /* None or multiple values have been selected for Block Length */ -#define A2D_BAD_CP_TYPE 0xE0 /* The requested CP Type is not supported. */ -#define A2D_BAD_CP_FORMAT 0xE1 /* The format of Content Protection Service Capability/Content Protection Scheme Dependent Data is not correct. */ - -typedef UINT8 tA2D_STATUS; - -/* the return values from A2D_BitsSet() */ -#define A2D_SET_ONE_BIT 1 /* one and only one bit is set */ -#define A2D_SET_ZERO_BIT 0 /* all bits clear */ -#define A2D_SET_MULTL_BIT 2 /* multiple bits are set */ - -/***************************************************************************** -** type definitions -*****************************************************************************/ - -/* This data type is used in A2D_FindService() to initialize the SDP database - * to hold the result service search. */ -typedef struct { - UINT32 db_len; /* Length, in bytes, of the discovery database */ - UINT16 num_attr;/* The number of attributes in p_attrs */ - tSDP_DISCOVERY_DB *p_db; /* Pointer to the discovery database */ - UINT16 *p_attrs; /* The attributes filter. If NULL, A2DP API sets the attribute filter - * to be ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_BT_PROFILE_DESC_LIST, - * ATTR_ID_SUPPORTED_FEATURES, ATTR_ID_SERVICE_NAME and ATTR_ID_PROVIDER_NAME. - * If not NULL, the input is taken as the filter. */ -} tA2D_SDP_DB_PARAMS; - -/* This data type is used in tA2D_FIND_CBACK to report the result of the SDP discovery process. */ -typedef struct { - UINT16 service_len; /* Length, in bytes, of the service name */ - UINT16 provider_len; /* Length, in bytes, of the provider name */ - char *p_service_name; /* Pointer the service name. This character string may not be null terminated. - * Use the service_len parameter to safely copy this string */ - char *p_provider_name;/* Pointer the provider name. This character string may not be null terminated. - * Use the provider_len parameter to safely copy this string */ - UINT16 features; /* Profile supported features */ - UINT16 avdt_version; /* AVDTP protocol version */ -} tA2D_Service; - -/* This is the callback to notify the result of the SDP discovery process. */ -typedef void (tA2D_FIND_CBACK)(BOOLEAN found, tA2D_Service *p_service); - - -/***************************************************************************** -** external function declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif -/****************************************************************************** -** -** Function A2D_AddRecord -** -** Description This function is called by a server application to add -** SRC or SNK information to an SDP record. Prior to -** calling this function the application must call -** SDP_CreateRecord() to create an SDP record. -** -** Input Parameters: -** service_uuid: Indicates SRC or SNK. -** -** p_service_name: Pointer to a null-terminated character -** string containing the service name. -** -** p_provider_name: Pointer to a null-terminated character -** string containing the provider name. -** -** features: Profile supported features. -** -** sdp_handle: SDP handle returned by SDP_CreateRecord(). -** -** Output Parameters: -** None. -** -** Returns A2D_SUCCESS if function execution succeeded, -** A2D_INVALID_PARAMS if bad parameters are given. -** A2D_FAIL if function execution failed. -** -******************************************************************************/ -extern tA2D_STATUS A2D_AddRecord(UINT16 service_uuid, char *p_service_name, char *p_provider_name, - UINT16 features, UINT32 sdp_handle); - -/****************************************************************************** -** -** Function A2D_FindService -** -** Description This function is called by a client application to -** perform service discovery and retrieve SRC or SNK SDP -** record information from a server. Information is -** returned for the first service record found on the -** server that matches the service UUID. The callback -** function will be executed when service discovery is -** complete. There can only be one outstanding call to -** A2D_FindService() at a time; the application must wait -** for the callback before it makes another call to -** the function. -** -** Input Parameters: -** service_uuid: Indicates SRC or SNK. -** -** bd_addr: BD address of the peer device. -** -** p_db: Pointer to the information to initialize -** the discovery database. -** -** p_cback: Pointer to the A2D_FindService() -** callback function. -** -** Output Parameters: -** None. -** -** Returns A2D_SUCCESS if function execution succeeded, -** A2D_INVALID_PARAMS if bad parameters are given. -** A2D_BUSY if discovery is already in progress. -** A2D_FAIL if function execution failed. -** -******************************************************************************/ -extern tA2D_STATUS A2D_FindService(UINT16 service_uuid, BD_ADDR bd_addr, - tA2D_SDP_DB_PARAMS *p_db, tA2D_FIND_CBACK *p_cback); - -/****************************************************************************** -** -** Function A2D_SetTraceLevel -** -** Description Sets the trace level for A2D. If 0xff is passed, the -** current trace level is returned. -** -** Input Parameters: -** new_level: The level to set the A2D tracing to: -** 0xff-returns the current setting. -** 0-turns off tracing. -** >= 1-Errors. -** >= 2-Warnings. -** >= 3-APIs. -** >= 4-Events. -** >= 5-Debug. -** -** Returns The new trace level or current trace level if -** the input parameter is 0xff. -** -******************************************************************************/ -extern UINT8 A2D_SetTraceLevel (UINT8 new_level); - -/****************************************************************************** -** Function A2D_BitsSet -** -** Description Check the given num for the number of bits set -** Returns A2D_SET_ONE_BIT, if one and only one bit is set -** A2D_SET_ZERO_BIT, if all bits clear -** A2D_SET_MULTL_BIT, if multiple bits are set -******************************************************************************/ -extern UINT8 A2D_BitsSet(UINT8 num); - -#ifdef __cplusplus -} -#endif - -/******************************************************************************* -** -** Function A2D_Init -** -** Description This function is called at stack startup to allocate the -** control block (if using dynamic memory), and initializes the -** control block and tracing level. -** -** Returns void -** -*******************************************************************************/ -extern void A2D_Init(void); -extern void A2D_Deinit(void); -#endif ///A2D_INCLUDED -#endif /* A2D_API_H */ diff --git a/tools/sdk/include/bluedroid/a2d_int.h b/tools/sdk/include/bluedroid/a2d_int.h deleted file mode 100644 index 89055bce991..00000000000 --- a/tools/sdk/include/bluedroid/a2d_int.h +++ /dev/null @@ -1,81 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * 2DP internal header file - * - ******************************************************************************/ -#ifndef A2D_INT_H -#define A2D_INT_H - -#include "a2d_api.h" -#if (A2D_INCLUDED == TRUE) -/***************************************************************************** -** Constants -*****************************************************************************/ -#define A2D_VERSION 0x0102 - -/* Number of attributes in A2D SDP record. */ -#define A2D_NUM_ATTR 6 - -/* Number of protocol elements in protocol element list. */ -#define A2D_NUM_PROTO_ELEMS 2 - -/***************************************************************************** -** Type definitions -*****************************************************************************/ - -/* Control block used by A2D_FindService(). */ -typedef struct { - tA2D_FIND_CBACK *p_cback; /* pointer to application callback */ - tSDP_DISCOVERY_DB *p_db; /* pointer to discovery database */ - UINT16 service_uuid; /* service UUID of search */ -} tA2D_FIND_CB; - -typedef struct { - tA2D_FIND_CB find; /* find service control block */ - UINT8 trace_level; - BOOLEAN use_desc; - UINT16 avdt_sdp_ver; /* AVDTP version */ -} tA2D_CB; - - -#ifdef __cplusplus -extern "C" -{ -#endif - -/****************************************************************************** -** Main Control Block -*******************************************************************************/ -#if A2D_DYNAMIC_MEMORY == FALSE -extern tA2D_CB a2d_cb; -#else -extern tA2D_CB *a2d_cb_ptr; -#define a2d_cb (*a2d_cb_ptr) -#endif - -/* Used only for conformance testing */ -extern void a2d_set_avdt_sdp_ver (UINT16 avdt_sdp_ver); - -#ifdef __cplusplus -} -#endif -#endif ///A2D_INCLUDED == TRUE -#endif /* A2D_INT_H */ diff --git a/tools/sdk/include/bluedroid/a2d_sbc.h b/tools/sdk/include/bluedroid/a2d_sbc.h deleted file mode 100644 index 98b63e46ca9..00000000000 --- a/tools/sdk/include/bluedroid/a2d_sbc.h +++ /dev/null @@ -1,213 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2000-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * nterface to low complexity subband codec (SBC) - * - ******************************************************************************/ -#ifndef A2D_SBC_H -#define A2D_SBC_H -#if (A2D_INCLUDED == TRUE) -/***************************************************************************** -** Constants -*****************************************************************************/ -/* the length of the SBC Media Payload header. */ -#define A2D_SBC_MPL_HDR_LEN 1 - -/* the LOSC of SBC media codec capabilitiy */ -#define A2D_SBC_INFO_LEN 6 - -/* for Codec Specific Information Element */ -#define A2D_SBC_IE_SAMP_FREQ_MSK 0xF0 /* b7-b4 sampling frequency */ -#define A2D_SBC_IE_SAMP_FREQ_16 0x80 /* b7:16 kHz */ -#define A2D_SBC_IE_SAMP_FREQ_32 0x40 /* b6:32 kHz */ -#define A2D_SBC_IE_SAMP_FREQ_44 0x20 /* b5:44.1kHz */ -#define A2D_SBC_IE_SAMP_FREQ_48 0x10 /* b4:48 kHz */ - -#define A2D_SBC_IE_CH_MD_MSK 0x0F /* b3-b0 channel mode */ -#define A2D_SBC_IE_CH_MD_MONO 0x08 /* b3: mono */ -#define A2D_SBC_IE_CH_MD_DUAL 0x04 /* b2: dual */ -#define A2D_SBC_IE_CH_MD_STEREO 0x02 /* b1: stereo */ -#define A2D_SBC_IE_CH_MD_JOINT 0x01 /* b0: joint stereo */ - -#define A2D_SBC_IE_BLOCKS_MSK 0xF0 /* b7-b4 number of blocks */ -#define A2D_SBC_IE_BLOCKS_4 0x80 /* 4 blocks */ -#define A2D_SBC_IE_BLOCKS_8 0x40 /* 8 blocks */ -#define A2D_SBC_IE_BLOCKS_12 0x20 /* 12blocks */ -#define A2D_SBC_IE_BLOCKS_16 0x10 /* 16blocks */ - -#define A2D_SBC_IE_SUBBAND_MSK 0x0C /* b3-b2 number of subbands */ -#define A2D_SBC_IE_SUBBAND_4 0x08 /* b3: 4 */ -#define A2D_SBC_IE_SUBBAND_8 0x04 /* b2: 8 */ - -#define A2D_SBC_IE_ALLOC_MD_MSK 0x03 /* b1-b0 allocation mode */ -#define A2D_SBC_IE_ALLOC_MD_S 0x02 /* b1: SNR */ -#define A2D_SBC_IE_ALLOC_MD_L 0x01 /* b0: loundess */ - -#define A2D_SBC_IE_MIN_BITPOOL 2 -#define A2D_SBC_IE_MAX_BITPOOL 250 - -/* for media payload header */ -#define A2D_SBC_HDR_F_MSK 0x80 -#define A2D_SBC_HDR_S_MSK 0x40 -#define A2D_SBC_HDR_L_MSK 0x20 -#define A2D_SBC_HDR_NUM_MSK 0x0F - -/***************************************************************************** -** Type Definitions -*****************************************************************************/ - -/* data type for the SBC Codec Information Element*/ -typedef struct { - UINT8 samp_freq; /* Sampling frequency */ - UINT8 ch_mode; /* Channel mode */ - UINT8 block_len; /* Block length */ - UINT8 num_subbands; /* Number of subbands */ - UINT8 alloc_mthd; /* Allocation method */ - UINT8 max_bitpool; /* Maximum bitpool */ - UINT8 min_bitpool; /* Minimum bitpool */ -} tA2D_SBC_CIE; - - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif -/****************************************************************************** -** -** Function A2D_SbcChkFrInit -** -** Description check if need to init the descramble control block. -** -** Returns nothing. -******************************************************************************/ -extern void A2D_SbcChkFrInit(UINT8 *p_pkt); - -/****************************************************************************** -** -** Function A2D_SbcDescramble -** -** Description descramble the packet. -** -** Returns nothing. -******************************************************************************/ -extern void A2D_SbcDescramble(UINT8 *p_pkt, UINT16 len); - -/****************************************************************************** -** -** Function A2D_BldSbcInfo -** -** Description This function is called by an application to build -** the SBC Media Codec Capabilities byte sequence -** beginning from the LOSC octet. -** Input Parameters: -** media_type: Indicates Audio, or Multimedia. -** -** p_ie: The SBC Codec Information Element information. -** -** Output Parameters: -** p_result: the resulting codec info byte sequence. -** -** Returns A2D_SUCCESS if function execution succeeded. -** Error status code, otherwise. -******************************************************************************/ -extern tA2D_STATUS A2D_BldSbcInfo(UINT8 media_type, tA2D_SBC_CIE *p_ie, - UINT8 *p_result); - -/****************************************************************************** -** -** Function A2D_ParsSbcInfo -** -** Description This function is called by an application to parse -** the SBC Media Codec Capabilities byte sequence -** beginning from the LOSC octet. -** Input Parameters: -** p_info: the byte sequence to parse. -** -** for_caps: TRUE, if the byte sequence is for get capabilities response. -** -** Output Parameters: -** p_ie: The SBC Codec Information Element information. -** -** Returns A2D_SUCCESS if function execution succeeded. -** Error status code, otherwise. -******************************************************************************/ -extern tA2D_STATUS A2D_ParsSbcInfo(tA2D_SBC_CIE *p_ie, UINT8 *p_info, - BOOLEAN for_caps); - -/****************************************************************************** -** -** Function A2D_BldSbcMplHdr -** -** Description This function is called by an application to parse -** the SBC Media Payload header. -** Input Parameters: -** frag: 1, if fragmented. 0, otherwise. -** -** start: 1, if the starting packet of a fragmented frame. -** -** last: 1, if the last packet of a fragmented frame. -** -** num: If frag is 1, this is the number of remaining fragments -** (including this fragment) of this frame. -** If frag is 0, this is the number of frames in this packet. -** -** Output Parameters: -** p_dst: the resulting media payload header byte sequence. -** -** Returns void. -******************************************************************************/ -extern void A2D_BldSbcMplHdr(UINT8 *p_dst, BOOLEAN frag, BOOLEAN start, - BOOLEAN last, UINT8 num); - -/****************************************************************************** -** -** Function A2D_ParsSbcMplHdr -** -** Description This function is called by an application to parse -** the SBC Media Payload header. -** Input Parameters: -** p_src: the byte sequence to parse.. -** -** Output Parameters: -** frag: 1, if fragmented. 0, otherwise. -** -** start: 1, if the starting packet of a fragmented frame. -** -** last: 1, if the last packet of a fragmented frame. -** -** num: If frag is 1, this is the number of remaining fragments -** (including this fragment) of this frame. -** If frag is 0, this is the number of frames in this packet. -** -** Returns void. -******************************************************************************/ -extern void A2D_ParsSbcMplHdr(UINT8 *p_src, BOOLEAN *p_frag, - BOOLEAN *p_start, BOOLEAN *p_last, - UINT8 *p_num); -#ifdef __cplusplus -} -#endif - -#endif ///A2D_INCLUDED == TRUE - -#endif /* A2D_SBC_H */ diff --git a/tools/sdk/include/bluedroid/aes.h b/tools/sdk/include/bluedroid/aes.h deleted file mode 100644 index 48495bb174d..00000000000 --- a/tools/sdk/include/bluedroid/aes.h +++ /dev/null @@ -1,162 +0,0 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The redistribution and use of this software (with or without changes) - is allowed without the payment of fees or royalties provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue 09/09/2006 - - This is an AES implementation that uses only 8-bit byte operations on the - cipher state. - */ - -#ifndef AES_H -#define AES_H - -#if 1 -# define AES_ENC_PREKEYED /* AES encryption with a precomputed key schedule */ -#endif -#if 1 -# define AES_DEC_PREKEYED /* AES decryption with a precomputed key schedule */ -#endif -#if 1 -# define AES_ENC_128_OTFK /* AES encryption with 'on the fly' 128 bit keying */ -#endif -#if 1 -# define AES_DEC_128_OTFK /* AES decryption with 'on the fly' 128 bit keying */ -#endif -#if 1 -# define AES_ENC_256_OTFK /* AES encryption with 'on the fly' 256 bit keying */ -#endif -#if 1 -# define AES_DEC_256_OTFK /* AES decryption with 'on the fly' 256 bit keying */ -#endif - -#define N_ROW 4 -#define N_COL 4 -#define N_BLOCK (N_ROW * N_COL) -#define N_MAX_ROUNDS 14 - -typedef unsigned char uint_8t; - -typedef uint_8t return_type; - -/* Warning: The key length for 256 bit keys overflows a byte - (see comment below) -*/ - -typedef uint_8t length_type; - -typedef struct { - uint_8t ksch[(N_MAX_ROUNDS + 1) * N_BLOCK]; - uint_8t rnd; -} aes_context; - -/* The following calls are for a precomputed key schedule - - NOTE: If the length_type used for the key length is an - unsigned 8-bit character, a key length of 256 bits must - be entered as a length in bytes (valid inputs are hence - 128, 192, 16, 24 and 32). -*/ - -#if defined( AES_ENC_PREKEYED ) || defined( AES_DEC_PREKEYED ) - -return_type aes_set_key( const unsigned char key[], - length_type keylen, - aes_context ctx[1] ); -#endif - -#if defined( AES_ENC_PREKEYED ) - -return_type bluedroid_aes_encrypt( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const aes_context ctx[1] ); - -return_type aes_cbc_encrypt( const unsigned char *in, - unsigned char *out, - int n_block, - unsigned char iv[N_BLOCK], - const aes_context ctx[1] ); -#endif - -#if defined( AES_DEC_PREKEYED ) - -return_type bluedroid_aes_decrypt( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const aes_context ctx[1] ); - -return_type aes_cbc_decrypt( const unsigned char *in, - unsigned char *out, - int n_block, - unsigned char iv[N_BLOCK], - const aes_context ctx[1] ); -#endif - -/* The following calls are for 'on the fly' keying. In this case the - encryption and decryption keys are different. - - The encryption subroutines take a key in an array of bytes in - key[L] where L is 16, 24 or 32 bytes for key lengths of 128, - 192, and 256 bits respectively. They then encrypts the input - data, in[] with this key and put the reult in the output array - out[]. In addition, the second key array, o_key[L], is used - to output the key that is needed by the decryption subroutine - to reverse the encryption operation. The two key arrays can - be the same array but in this case the original key will be - overwritten. - - In the same way, the decryption subroutines output keys that - can be used to reverse their effect when used for encryption. - - Only 128 and 256 bit keys are supported in these 'on the fly' - modes. -*/ - -#if defined( AES_ENC_128_OTFK ) -void bluedroid_aes_encrypt_128( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], - uint_8t o_key[N_BLOCK] ); -#endif - -#if defined( AES_DEC_128_OTFK ) -void bluedroid_aes_decrypt_128( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], - unsigned char o_key[N_BLOCK] ); -#endif - -#if defined( AES_ENC_256_OTFK ) -void bluedroid_aes_encrypt_256( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], - unsigned char o_key[2 * N_BLOCK] ); -#endif - -#if defined( AES_DEC_256_OTFK ) -void bluedroid_aes_decrypt_256( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], - unsigned char o_key[2 * N_BLOCK] ); -#endif - -#endif diff --git a/tools/sdk/include/bluedroid/alarm.h b/tools/sdk/include/bluedroid/alarm.h deleted file mode 100644 index 3dc177c7a1d..00000000000 --- a/tools/sdk/include/bluedroid/alarm.h +++ /dev/null @@ -1,80 +0,0 @@ -/****************************************************************************** - * - * 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 30 -#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/include/bluedroid/allocator.h b/tools/sdk/include/bluedroid/allocator.h deleted file mode 100644 index 707901f43fd..00000000000 --- a/tools/sdk/include/bluedroid/allocator.h +++ /dev/null @@ -1,153 +0,0 @@ -/****************************************************************************** - * - * 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" -#include "sdkconfig.h" - -typedef void *(*alloc_fn)(size_t size); -typedef void (*free_fn)(void *ptr); - -typedef struct { - alloc_fn alloc; - free_fn free; -} allocator_t; - -// allocator_t abstractions for the osi_*alloc and osi_free functions -extern const allocator_t allocator_malloc; -extern const allocator_t allocator_calloc; - -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); - -#ifdef CONFIG_BLUEDROID_MEM_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); - -#if CONFIG_BT_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 CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST */ - - -#if 0 -#define osi_malloc(size) \ -do { \ - void *p; \ - \ -#if CONFIG_BT_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 CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST */ \ - osi_mem_dbg_record(p, size, __func__, __LINE__); \ - (void *)p; \ -}while(0) - -#define osi_calloc(size) \ -do { \ - void *p; \ - \ -#if CONFIG_BT_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 CONFIG_BT_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 CONFIG_BT_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 CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST */ -#define osi_free(p) free((p)) - -#endif /* CONFIG_BLUEDROID_MEM_DEBUG */ - -#define FREE_AND_RESET(a) \ -do { \ - if (a) { \ - osi_free(a); \ - a = NULL; \ - } \ -}while (0) - - -#endif /* _ALLOCATOR_H_ */ diff --git a/tools/sdk/include/bluedroid/avct_api.h b/tools/sdk/include/bluedroid/avct_api.h deleted file mode 100644 index c2713fdb47e..00000000000 --- a/tools/sdk/include/bluedroid/avct_api.h +++ /dev/null @@ -1,279 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This interface file contains the interface to the Audio Video Control - * Transport Protocol (AVCTP). - * - ******************************************************************************/ -#ifndef AVCT_API_H -#define AVCT_API_H - -#include "bt_types.h" -#include "bt_target.h" - -/***************************************************************************** -** Constants -*****************************************************************************/ - -/* API function return value result codes. */ -#define AVCT_SUCCESS 0 /* Function successful */ -#define AVCT_NO_RESOURCES 1 /* Not enough resources */ -#define AVCT_BAD_HANDLE 2 /* Bad handle */ -#define AVCT_PID_IN_USE 3 /* PID already in use */ -#define AVCT_NOT_OPEN 4 /* Connection not open */ - -/* PSM for AVCT. */ -#define AVCT_PSM 0x0017 -#define AVCT_BR_PSM 0x001B - -/* Protocol revision numbers */ -#define AVCT_REV_1_0 0x0100 -#define AVCT_REV_1_2 0x0102 -#define AVCT_REV_1_3 0x0103 -#define AVCT_REV_1_4 0x0104 - -/* the layer_specific settings */ -#define AVCT_DATA_CTRL 0x0001 /* for the control channel */ -#define AVCT_DATA_BROWSE 0x0002 /* for the browsing channel */ -#define AVCT_DATA_PARTIAL 0x0100 /* Only have room for a partial message */ - -#define AVCT_MIN_CONTROL_MTU 48 /* Per the AVRC spec, minimum MTU for the control channel */ -#define AVCT_MIN_BROWSE_MTU 335 /* Per the AVRC spec, minimum MTU for the browsing channel */ - -/* Message offset. The number of bytes needed by the protocol stack for the -** protocol headers of an AVCTP message packet. -*/ -#define AVCT_MSG_OFFSET 15 -#define AVCT_BROWSE_OFFSET 17 /* the default offset for browsing channel */ - -/* Connection role. */ -#define AVCT_INT 0 /* Initiator connection */ -#define AVCT_ACP 1 /* Acceptor connection */ - -/* Control role. */ -#define AVCT_TARGET 1 /* target */ -#define AVCT_CONTROL 2 /* controller */ -#define AVCT_PASSIVE 4 /* If conflict, allow the other side to succeed */ - -/* Command/Response indicator. */ -#define AVCT_CMD 0 /* Command message */ -#define AVCT_RSP 2 /* Response message */ -#define AVCT_REJ 3 /* Message rejected */ - -/* Control callback events. */ -#define AVCT_CONNECT_CFM_EVT 0 /* Connection confirm */ -#define AVCT_CONNECT_IND_EVT 1 /* Connection indication */ -#define AVCT_DISCONNECT_CFM_EVT 2 /* Disconnect confirm */ -#define AVCT_DISCONNECT_IND_EVT 3 /* Disconnect indication */ -#define AVCT_CONG_IND_EVT 4 /* Congestion indication */ -#define AVCT_UNCONG_IND_EVT 5 /* Uncongestion indication */ -#define AVCT_BROWSE_CONN_CFM_EVT 6 /* Browse Connection confirm */ -#define AVCT_BROWSE_CONN_IND_EVT 7 /* Browse Connection indication */ -#define AVCT_BROWSE_DISCONN_CFM_EVT 8 /* Browse Disconnect confirm */ -#define AVCT_BROWSE_DISCONN_IND_EVT 9 /* Browse Disconnect indication */ -#define AVCT_BROWSE_CONG_IND_EVT 10 /* Congestion indication */ -#define AVCT_BROWSE_UNCONG_IND_EVT 11 /* Uncongestion indication */ - - -/* General purpose failure result code for callback events. */ -#define AVCT_RESULT_FAIL 5 - -/***************************************************************************** -** Type Definitions -*****************************************************************************/ - -/* Control callback function. */ -typedef void (tAVCT_CTRL_CBACK)(UINT8 handle, UINT8 event, UINT16 result, - BD_ADDR peer_addr); - -/* Message callback function */ -/* p_pkt->layer_specific is AVCT_DATA_CTRL or AVCT_DATA_BROWSE */ -typedef void (tAVCT_MSG_CBACK)(UINT8 handle, UINT8 label, UINT8 cr, - BT_HDR *p_pkt); - -/* Structure used by AVCT_CreateConn. */ -typedef struct { - tAVCT_CTRL_CBACK *p_ctrl_cback; /* Control callback */ - tAVCT_MSG_CBACK *p_msg_cback; /* Message callback */ - UINT16 pid; /* Profile ID */ - UINT8 role; /* Initiator/acceptor role */ - UINT8 control; /* Control role (Control/Target) */ -} tAVCT_CC; - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function AVCT_Register -** -** Description This is the system level registration function for the -** AVCTP protocol. This function initializes AVCTP and -** prepares the protocol stack for its use. This function -** must be called once by the system or platform using AVCTP -** before the other functions of the API an be used. -** -** -** Returns void -** -*******************************************************************************/ -extern void AVCT_Register(UINT16 mtu, UINT16 mtu_br, UINT8 sec_mask); - -/******************************************************************************* -** -** Function AVCT_Deregister -** -** Description This function is called to deregister use AVCTP protocol. -** It is called when AVCTP is no longer being used by any -** application in the system. Before this function can be -** called, all connections must be removed with -** AVCT_RemoveConn(). -** -** -** Returns void -** -*******************************************************************************/ -extern void AVCT_Deregister(void); - -/******************************************************************************* -** -** Function AVCT_CreateConn -** -** Description Create an AVCTP connection. There are two types of -** connections, initiator and acceptor, as determined by -** the p_cc->role parameter. When this function is called to -** create an initiator connection, an AVCTP connection to -** the peer device is initiated if one does not already exist. -** If an acceptor connection is created, the connection waits -** passively for an incoming AVCTP connection from a peer device. -** -** -** Returns AVCT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVCT_CreateConn(UINT8 *p_handle, tAVCT_CC *p_cc, - BD_ADDR peer_addr); - -/******************************************************************************* -** -** Function AVCT_RemoveConn -** -** Description Remove an AVCTP connection. This function is called when -** the application is no longer using a connection. If this -** is the last connection to a peer the L2CAP channel for AVCTP -** will be closed. -** -** -** Returns AVCT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVCT_RemoveConn(UINT8 handle); - -/******************************************************************************* -** -** Function AVCT_CreateBrowse -** -** Description Create an AVCTP connection. There are two types of -** connections, initiator and acceptor, as determined by -** the p_cc->role parameter. When this function is called to -** create an initiator connection, an AVCTP connection to -** the peer device is initiated if one does not already exist. -** If an acceptor connection is created, the connection waits -** passively for an incoming AVCTP connection from a peer device. -** -** -** Returns AVCT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVCT_CreateBrowse(UINT8 handle, UINT8 role); - -/******************************************************************************* -** -** Function AVCT_RemoveBrowse -** -** Description Remove an AVCTP connection. This function is called when -** the application is no longer using a connection. If this -** is the last connection to a peer the L2CAP channel for AVCTP -** will be closed. -** -** -** Returns AVCT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVCT_RemoveBrowse(UINT8 handle); - -/******************************************************************************* -** -** Function AVCT_GetBrowseMtu -** -** Description Get the peer_mtu for the AVCTP Browse channel of the given -** connection. -** -** Returns the peer browsing channel MTU. -** -*******************************************************************************/ -extern UINT16 AVCT_GetBrowseMtu (UINT8 handle); - -/******************************************************************************* -** -** Function AVCT_GetPeerMtu -** -** Description Get the peer_mtu for the AVCTP channel of the given -** connection. -** -** Returns the peer MTU size. -** -*******************************************************************************/ -extern UINT16 AVCT_GetPeerMtu (UINT8 handle); - -/******************************************************************************* -** -** Function AVCT_MsgReq -** -** Description Send an AVCTP message to a peer device. In calling -** AVCT_MsgReq(), the application should keep track of the -** congestion state of AVCTP as communicated with events -** AVCT_CONG_IND_EVT and AVCT_UNCONG_IND_EVT. If the -** application calls AVCT_MsgReq() when AVCTP is congested -** the message may be discarded. The application may make its -** first call to AVCT_MsgReq() after it receives an -** AVCT_CONNECT_CFM_EVT or AVCT_CONNECT_IND_EVT on control channel or -** AVCT_BROWSE_CONN_CFM_EVT or AVCT_BROWSE_CONN_IND_EVT on browsing channel. -** -** p_msg->layer_specific must be set to -** AVCT_DATA_CTRL for control channel traffic; -** AVCT_DATA_BROWSE for for browse channel traffic. -** -** Returns AVCT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVCT_MsgReq(UINT8 handle, UINT8 label, UINT8 cr, BT_HDR *p_msg); - -#ifdef __cplusplus -} -#endif - - -#endif /* AVCT_API_H */ diff --git a/tools/sdk/include/bluedroid/avct_defs.h b/tools/sdk/include/bluedroid/avct_defs.h deleted file mode 100644 index 30b8859fe03..00000000000 --- a/tools/sdk/include/bluedroid/avct_defs.h +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This contains constants definitions and other information from the AVCTP - * specification. This file is intended for use internal to AVCT only. - * - ******************************************************************************/ -#ifndef AVCT_DEFS_H -#define AVCT_DEFS_H - -/***************************************************************************** -** constants -*****************************************************************************/ - -/* packet type */ -#define AVCT_PKT_TYPE_SINGLE 0 /* single packet */ -#define AVCT_PKT_TYPE_START 1 /* start packet */ -#define AVCT_PKT_TYPE_CONT 2 /* continue packet */ -#define AVCT_PKT_TYPE_END 3 /* end packet */ - -/* header lengths for different packet types */ -#define AVCT_HDR_LEN_SINGLE 3 -#define AVCT_HDR_LEN_START 4 -#define AVCT_HDR_LEN_CONT 1 -#define AVCT_HDR_LEN_END 1 - -/* invalid cr+ipid value */ -#define AVCT_CR_IPID_INVALID 1 - -/***************************************************************************** -** message parsing and building macros -*****************************************************************************/ - -#define AVCT_BLD_HDR(p, label, type, cr_ipid) \ - *(p)++ = ((label) << 4) | ((type) << 2) | (cr_ipid); - -#define AVCT_PRS_HDR(p, label, type, cr_ipid) \ - label = *(p) >> 4; \ - type = (*(p) >> 2) & 3; \ - cr_ipid = *(p)++ & 3; - -#define AVCT_PRS_PKT_TYPE(p, type) \ - type = (*(p) >> 2) & 3; - -#endif /* AVCT_DEFS_H */ diff --git a/tools/sdk/include/bluedroid/avct_int.h b/tools/sdk/include/bluedroid/avct_int.h deleted file mode 100644 index f70f516c0df..00000000000 --- a/tools/sdk/include/bluedroid/avct_int.h +++ /dev/null @@ -1,237 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains interfaces which are internal to AVCTP. - * - ******************************************************************************/ -#ifndef AVCT_INT_H -#define AVCT_INT_H - -#include "avct_api.h" -#include "avct_defs.h" -#include "l2c_api.h" -#include "fixed_queue.h" - -/***************************************************************************** -** constants -*****************************************************************************/ - -/* lcb state machine events */ -enum { - AVCT_LCB_UL_BIND_EVT, - AVCT_LCB_UL_UNBIND_EVT, - AVCT_LCB_UL_MSG_EVT, - AVCT_LCB_INT_CLOSE_EVT, - AVCT_LCB_LL_OPEN_EVT, - AVCT_LCB_LL_CLOSE_EVT, - AVCT_LCB_LL_MSG_EVT, - AVCT_LCB_LL_CONG_EVT -}; - - -/* "states" used for L2CAP channel */ -#define AVCT_CH_IDLE 0 /* No connection */ -#define AVCT_CH_CONN 1 /* Waiting for connection confirm */ -#define AVCT_CH_CFG 2 /* Waiting for configuration complete */ -#define AVCT_CH_OPEN 3 /* Channel opened */ - -/* "no event" indicator used by ccb dealloc */ -#define AVCT_NO_EVT 0xFF - -/***************************************************************************** -** data types -*****************************************************************************/ -/* sub control block type - common data members for tAVCT_LCB and tAVCT_BCB */ -typedef struct { - UINT16 peer_mtu; /* peer l2c mtu */ - UINT16 ch_result; /* L2CAP connection result value */ - UINT16 ch_lcid; /* L2CAP channel LCID */ - UINT8 allocated; /* 0, not allocated. index+1, otherwise. */ - UINT8 state; /* The state machine state */ - UINT8 ch_state; /* L2CAP channel state */ - UINT8 ch_flags; /* L2CAP configuration flags */ -} tAVCT_SCB; - -/* link control block type */ -typedef struct { - UINT16 peer_mtu; /* peer l2c mtu */ - UINT16 ch_result; /* L2CAP connection result value */ - UINT16 ch_lcid; /* L2CAP channel LCID */ - UINT8 allocated; /* 0, not allocated. index+1, otherwise. */ - UINT8 state; /* The state machine state */ - UINT8 ch_state; /* L2CAP channel state */ - UINT8 ch_flags; /* L2CAP configuration flags */ - BT_HDR *p_rx_msg; /* Message being reassembled */ - UINT16 conflict_lcid; /* L2CAP channel LCID */ - BD_ADDR peer_addr; /* BD address of peer */ - fixed_queue_t *tx_q; /* Transmit data buffer queue */ - BOOLEAN cong; /* TRUE, if congested */ -} tAVCT_LCB; - -/* browse control block type */ -typedef struct { - UINT16 peer_mtu; /* peer l2c mtu */ - UINT16 ch_result; /* L2CAP connection result value */ - UINT16 ch_lcid; /* L2CAP channel LCID */ - UINT8 allocated; /* 0, not allocated. index+1, otherwise. */ - UINT8 state; /* The state machine state */ - UINT8 ch_state; /* L2CAP channel state */ - UINT8 ch_flags; /* L2CAP configuration flags */ - BT_HDR *p_tx_msg; /* Message to be sent - in case the browsing channel is not open when MsgReg is called */ - UINT8 ch_close; /* CCB index+1, if CCB initiated channel close */ -} tAVCT_BCB; - -#define AVCT_ALOC_LCB 0x01 -#define AVCT_ALOC_BCB 0x02 -/* connection control block */ -typedef struct { - tAVCT_CC cc; /* parameters from connection creation */ - tAVCT_LCB *p_lcb; /* Associated LCB */ - tAVCT_BCB *p_bcb; /* associated BCB */ - BOOLEAN ch_close; /* Whether CCB initiated channel close */ - UINT8 allocated; /* Whether LCB/BCB is allocated */ -} tAVCT_CCB; - -/* data type associated with UL_MSG_EVT */ -typedef struct { - BT_HDR *p_buf; - tAVCT_CCB *p_ccb; - UINT8 label; - UINT8 cr; -} tAVCT_UL_MSG; - -/* union associated with lcb state machine events */ -typedef union { - tAVCT_UL_MSG ul_msg; - BT_HDR *p_buf; - tAVCT_CCB *p_ccb; - UINT16 result; - BOOLEAN cong; - UINT8 err_code; -} tAVCT_LCB_EVT; - -/* Control block for AVCT */ -typedef struct { - tAVCT_LCB lcb[AVCT_NUM_LINKS]; /* link control blocks */ - tAVCT_BCB bcb[AVCT_NUM_LINKS]; /* browse control blocks */ - tAVCT_CCB ccb[AVCT_NUM_CONN]; /* connection control blocks */ - UINT16 mtu; /* our L2CAP MTU */ - UINT16 mtu_br; /* our L2CAP MTU for the Browsing channel */ - UINT8 trace_level; /* trace level */ -} tAVCT_CB; - -/***************************************************************************** -** function declarations -*****************************************************************************/ - -/* LCB function declarations */ -extern void avct_lcb_event(tAVCT_LCB *p_lcb, UINT8 event, tAVCT_LCB_EVT *p_data); -#if (AVCT_BROWSE_INCLUDED == TRUE) -extern void avct_bcb_event(tAVCT_BCB *p_bcb, UINT8 event, tAVCT_LCB_EVT *p_data); -extern void avct_close_bcb(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern tAVCT_LCB *avct_lcb_by_bcb(tAVCT_BCB *p_bcb); -extern tAVCT_BCB *avct_bcb_by_lcb(tAVCT_LCB *p_lcb); -extern BOOLEAN avct_bcb_last_ccb(tAVCT_BCB *p_bcb, tAVCT_CCB *p_ccb_last); -extern tAVCT_BCB *avct_bcb_by_lcid(UINT16 lcid); -#endif -extern tAVCT_LCB *avct_lcb_by_bd(BD_ADDR bd_addr); -extern tAVCT_LCB *avct_lcb_alloc(BD_ADDR bd_addr); -extern void avct_lcb_dealloc(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern tAVCT_LCB *avct_lcb_by_lcid(UINT16 lcid); -extern tAVCT_CCB *avct_lcb_has_pid(tAVCT_LCB *p_lcb, UINT16 pid); -extern BOOLEAN avct_lcb_last_ccb(tAVCT_LCB *p_lcb, tAVCT_CCB *p_ccb_last); - -/* LCB action functions */ -extern void avct_lcb_chnl_open(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_unbind_disc(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_open_ind(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_open_fail(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_close_ind(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_close_cfm(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_bind_conn(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_chk_disc(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_chnl_disc(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_bind_fail(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_cong_ind(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_discard_msg(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_send_msg(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_msg_ind(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); -extern void avct_lcb_free_msg_ind(tAVCT_LCB *p_lcb, tAVCT_LCB_EVT *p_data); - -/* BCB action functions */ -#if (AVCT_BROWSE_INCLUDED == TRUE) -typedef void (*tAVCT_BCB_ACTION)(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_chnl_open(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_unbind_disc(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_open_ind(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_open_fail(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_close_ind(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_close_cfm(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_bind_conn(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_chk_disc(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_chnl_disc(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_bind_fail(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_cong_ind(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_discard_msg(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_send_msg(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_msg_ind(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); -extern void avct_bcb_free_msg_ind(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); - -extern void avct_bcb_dealloc(tAVCT_BCB *p_bcb, tAVCT_LCB_EVT *p_data); - -extern const tAVCT_BCB_ACTION avct_bcb_action[]; -extern const UINT8 avct_lcb_pkt_type_len[]; -extern const tL2CAP_FCR_OPTS avct_l2c_br_fcr_opts_def; -#endif - -/* CCB function declarations */ -extern tAVCT_CCB *avct_ccb_alloc(tAVCT_CC *p_cc); -extern void avct_ccb_dealloc(tAVCT_CCB *p_ccb, UINT8 event, UINT16 result, BD_ADDR bd_addr); -extern UINT8 avct_ccb_to_idx(tAVCT_CCB *p_ccb); -extern tAVCT_CCB *avct_ccb_by_idx(UINT8 idx); - - -/***************************************************************************** -** global data -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/* Main control block */ -#if AVCT_DYNAMIC_MEMORY == FALSE -extern tAVCT_CB avct_cb; -#else -extern tAVCT_CB *avct_cb_ptr; -#define avct_cb (*avct_cb_ptr) -#endif - -/* L2CAP callback registration structure */ -extern const tL2CAP_APPL_INFO avct_l2c_appl; -#if (AVCT_BROWSE_INCLUDED == TRUE) -extern const tL2CAP_APPL_INFO avct_l2c_br_appl; -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* AVCT_INT_H */ diff --git a/tools/sdk/include/bluedroid/avdt_api.h b/tools/sdk/include/bluedroid/avdt_api.h deleted file mode 100644 index a1e856b6fd6..00000000000 --- a/tools/sdk/include/bluedroid/avdt_api.h +++ /dev/null @@ -1,988 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This interface file contains the interface to the Audio Video - * Distribution Transport Protocol (AVDTP). - * - ******************************************************************************/ -#ifndef AVDT_API_H -#define AVDT_API_H - -#include "bt_types.h" -#include "bt_target.h" - -/***************************************************************************** -** Constants -*****************************************************************************/ -#ifndef AVDT_VERSION -#define AVDT_VERSION 0x0102 -#endif -#define AVDT_VERSION_SYNC 0x0103 - -/* API function return value result codes. */ -#define AVDT_SUCCESS 0 /* Function successful */ -#define AVDT_BAD_PARAMS 1 /* Invalid parameters */ -#define AVDT_NO_RESOURCES 2 /* Not enough resources */ -#define AVDT_BAD_HANDLE 3 /* Bad handle */ -#define AVDT_BUSY 4 /* A procedure is already in progress */ -#define AVDT_WRITE_FAIL 5 /* Write failed */ - -/* The index to access the codec type in codec_info[]. */ -#define AVDT_CODEC_TYPE_INDEX 2 - -/* The size in bytes of a Adaptation Layer header. */ -#define AVDT_AL_HDR_SIZE 3 - -/* The size in bytes of a media packet header. */ -#define AVDT_MEDIA_HDR_SIZE 12 - -/* AVDTP 7.5.3 Adaptation Layer Fragmentation - * original length of the un-fragmented transport packet should be specified by - * two bytes length field of Adaptation Layer Header */ -#define AVDT_MAX_MEDIA_SIZE (0xFFFF - AVDT_MEDIA_HDR_SIZE) - -/* The handle is used when reporting MULTI_AV specific events */ -#define AVDT_MULTI_AV_HANDLE 0xFF - -/* The number of bytes needed by the protocol stack for the protocol headers -** of a media packet. This is the size of the media packet header, the -** L2CAP packet header and HCI header. -*/ -#define AVDT_MEDIA_OFFSET 23 - -/* The marker bit is used by the application to mark significant events such -** as frame boundaries in the data stream. This constant is used to check or -** set the marker bit in the m_pt parameter of an AVDT_WriteReq() -** or AVDT_DATA_IND_EVT. -*/ -#define AVDT_MARKER_SET 0x80 - -/* SEP Type. This indicates the stream endpoint type. */ -#define AVDT_TSEP_SRC 0 /* Source SEP */ -#define AVDT_TSEP_SNK 1 /* Sink SEP */ - -/* initiator/acceptor role for adaption */ -#define AVDT_INT 0 /* initiator */ -#define AVDT_ACP 1 /* acceptor */ - -/* Media Type. This indicates the media type of the stream endpoint. */ -#define AVDT_MEDIA_AUDIO 0 /* Audio SEP */ -#define AVDT_MEDIA_VIDEO 1 /* Video SEP */ -#define AVDT_MEDIA_MULTI 2 /* Multimedia SEP */ - -/* for reporting packets */ -#define AVDT_RTCP_PT_SR 200 /* the packet type - SR (Sender Report) */ -#define AVDT_RTCP_PT_RR 201 /* the packet type - RR (Receiver Report) */ -#define AVDT_RTCP_PT_SDES 202 /* the packet type - SDES (Source Description) */ -typedef UINT8 AVDT_REPORT_TYPE; - -#define AVDT_RTCP_SDES_CNAME 1 /* SDES item CNAME */ -#ifndef AVDT_MAX_CNAME_SIZE -#define AVDT_MAX_CNAME_SIZE 28 -#endif - -/* Protocol service capabilities. This indicates the protocol service -** capabilities of a stream endpoint. This value is a mask. -** Multiple values can be combined with a bitwise OR. -*/ -#define AVDT_PSC_TRANS (1<<1) /* Media transport */ -#define AVDT_PSC_REPORT (1<<2) /* Reporting */ -#define AVDT_PSC_RECOV (1<<3) /* Recovery */ -#define AVDT_PSC_HDRCMP (1<<5) /* Header compression */ -#define AVDT_PSC_MUX (1<<6) /* Multiplexing */ -#define AVDT_PSC_DELAY_RPT (1<<8) /* Delay Report */ - -/* Recovery type. This indicates the recovery type. */ -#define AVDT_RECOV_RFC2733 1 /* RFC2733 recovery */ - -/* Header compression capabilities. This indicates the header compression -** capabilities. This value is a mask. Multiple values can be combined -** with a bitwise OR. -*/ -#define AVDT_HDRCMP_MEDIA (1<<5) /* Available for media packets */ -#define AVDT_HDRCMP_RECOV (1<<6) /* Available for recovery packets */ -#define AVDT_HDRCMP_BACKCH (1<<7) /* Back channel supported */ - -/* Multiplexing capabilities mask. */ -#define AVDT_MUX_FRAG (1<<7) /* Allow Adaptation Layer Fragmentation */ - -/* Application service category. This indicates the application -** service category. -*/ -#define AVDT_ASC_PROTECT 4 /* Content protection */ -#define AVDT_ASC_CODEC 7 /* Codec */ - -/* Error codes. The following are error codes defined in the AVDTP and GAVDP -** specifications. These error codes communicate protocol errors between -** AVDTP and the application. More detailed descriptions of the error codes -** and their appropriate use can be found in the AVDTP and GAVDP specifications. -** These error codes are unrelated to the result values returned by the -** AVDTP API functions. -*/ -#define AVDT_ERR_HEADER 0x01 /* Bad packet header format */ -#define AVDT_ERR_LENGTH 0x11 /* Bad packet length */ -#define AVDT_ERR_SEID 0x12 /* Invalid SEID */ -#define AVDT_ERR_IN_USE 0x13 /* The SEP is in use */ -#define AVDT_ERR_NOT_IN_USE 0x14 /* The SEP is not in use */ -#define AVDT_ERR_CATEGORY 0x17 /* Bad service category */ -#define AVDT_ERR_PAYLOAD 0x18 /* Bad payload format */ -#define AVDT_ERR_NSC 0x19 /* Requested command not supported */ -#define AVDT_ERR_INVALID_CAP 0x1A /* Reconfigure attempted invalid capabilities */ -#define AVDT_ERR_RECOV_TYPE 0x22 /* Requested recovery type not defined */ -#define AVDT_ERR_MEDIA_TRANS 0x23 /* Media transport capability not correct */ -#define AVDT_ERR_RECOV_FMT 0x25 /* Recovery service capability not correct */ -#define AVDT_ERR_ROHC_FMT 0x26 /* Header compression service capability not correct */ -#define AVDT_ERR_CP_FMT 0x27 /* Content protection service capability not correct */ -#define AVDT_ERR_MUX_FMT 0x28 /* Multiplexing service capability not correct */ -#define AVDT_ERR_UNSUP_CFG 0x29 /* Configuration not supported */ -#define AVDT_ERR_BAD_STATE 0x31 /* Message cannot be processed in this state */ -#define AVDT_ERR_REPORT_FMT 0x65 /* Report service capability not correct */ -#define AVDT_ERR_SERVICE 0x80 /* Invalid service category */ -#define AVDT_ERR_RESOURCE 0x81 /* Insufficient resources */ -#define AVDT_ERR_INVALID_MCT 0xC1 /* Invalid Media Codec Type */ -#define AVDT_ERR_UNSUP_MCT 0xC2 /* Unsupported Media Codec Type */ -#define AVDT_ERR_INVALID_LEVEL 0xC3 /* Invalid Level */ -#define AVDT_ERR_UNSUP_LEVEL 0xC4 /* Unsupported Level */ -#define AVDT_ERR_INVALID_CP 0xE0 /* Invalid Content Protection Type */ -#define AVDT_ERR_INVALID_FORMAT 0xE1 /* Invalid Content Protection format */ - -/* Additional error codes. This indicates error codes used by AVDTP -** in addition to the ones defined in the specifications. -*/ -#define AVDT_ERR_CONNECT 0x07 /* Connection failed. */ -#define AVDT_ERR_TIMEOUT 0x08 /* Response timeout. */ - -/* Control callback events. */ -#define AVDT_DISCOVER_CFM_EVT 0 /* Discover confirm */ -#define AVDT_GETCAP_CFM_EVT 1 /* Get capabilities confirm */ -#define AVDT_OPEN_CFM_EVT 2 /* Open confirm */ -#define AVDT_OPEN_IND_EVT 3 /* Open indication */ -#define AVDT_CONFIG_IND_EVT 4 /* Configuration indication */ -#define AVDT_START_CFM_EVT 5 /* Start confirm */ -#define AVDT_START_IND_EVT 6 /* Start indication */ -#define AVDT_SUSPEND_CFM_EVT 7 /* Suspend confirm */ -#define AVDT_SUSPEND_IND_EVT 8 /* Suspend indication */ -#define AVDT_CLOSE_CFM_EVT 9 /* Close confirm */ -#define AVDT_CLOSE_IND_EVT 10 /* Close indication */ -#define AVDT_RECONFIG_CFM_EVT 11 /* Reconfiguration confirm */ -#define AVDT_RECONFIG_IND_EVT 12 /* Reconfiguration indication */ -#define AVDT_SECURITY_CFM_EVT 13 /* Security confirm */ -#define AVDT_SECURITY_IND_EVT 14 /* Security indication */ -#define AVDT_WRITE_CFM_EVT 15 /* Write confirm */ -#define AVDT_CONNECT_IND_EVT 16 /* Signaling channel connected */ -#define AVDT_DISCONNECT_IND_EVT 17 /* Signaling channel disconnected */ -#define AVDT_REPORT_CONN_EVT 18 /* Reporting channel connected */ -#define AVDT_REPORT_DISCONN_EVT 19 /* Reporting channel disconnected */ -#define AVDT_DELAY_REPORT_EVT 20 /* Delay report received */ -#define AVDT_DELAY_REPORT_CFM_EVT 21 /* Delay report response received */ - -#define AVDT_MAX_EVT (AVDT_DELAY_REPORT_CFM_EVT) - -/* PSM for AVDT */ -#define AVDT_PSM 0x0019 - -/* Nonsupported protocol command messages. This value is used in tAVDT_CS */ -#define AVDT_NSC_SUSPEND 0x01 /* Suspend command not supported */ -#define AVDT_NSC_RECONFIG 0x02 /* Reconfigure command not supported */ -#define AVDT_NSC_SECURITY 0x04 /* Security command not supported */ - -/* AVDT disconnection reason */ -#define AVDT_DISC_RSN_NORMAL 0 -#define AVDT_DISC_RSN_ABNORMAL (0xce) /* unintentional disconnection */ -/***************************************************************************** -** Type Definitions -*****************************************************************************/ - -typedef struct { - UINT32 ntp_sec; /* NTP time: seconds relative to 0h UTC on 1 January 1900 */ - UINT32 ntp_frac; /* NTP time: the fractional part */ - UINT32 rtp_time; /* timestamp in RTP header */ - UINT32 pkt_count; /* sender's packet count: since starting transmission - * up until the time this SR packet was generated. */ - UINT32 octet_count; /* sender's octet count: same comment */ -} tAVDT_SENDER_INFO; - -typedef struct { - UINT8 frag_lost; /* fraction lost since last RR */ - UINT32 packet_lost; /* cumulative number of packets lost since the beginning */ - UINT32 seq_num_rcvd; /* extended highest sequence number received */ - UINT32 jitter; /* interarrival jitter */ - UINT32 lsr; /* last SR timestamp */ - UINT32 dlsr; /* delay since last SR */ -} tAVDT_REPORT_BLK; - -typedef union { - tAVDT_SENDER_INFO sr; - tAVDT_REPORT_BLK rr; - UINT8 cname[AVDT_MAX_CNAME_SIZE + 1]; -} tAVDT_REPORT_DATA; - -/* This structure contains parameters which are set at registration. */ -typedef struct { - UINT16 ctrl_mtu; /* L2CAP MTU of the AVDTP signaling channel */ - UINT8 ret_tout; /* AVDTP signaling retransmission timeout */ - UINT8 sig_tout; /* AVDTP signaling message timeout */ - UINT8 idle_tout; /* AVDTP idle signaling channel timeout */ - UINT8 sec_mask; /* Security mask for BTM_SetSecurityLevel() */ -} tAVDT_REG; - -/* This structure contains the SEP information. This information is -** transferred during the discovery procedure. -*/ -typedef struct { - BOOLEAN in_use; /* TRUE if stream is currently in use */ - UINT8 seid; /* Stream endpoint identifier */ - UINT8 media_type; /* Media type */ - UINT8 tsep; /* SEP type */ -} tAVDT_SEP_INFO; - -/* This structure contains the SEP configuration. */ -typedef struct { - UINT8 codec_info[AVDT_CODEC_SIZE]; /* Codec capabilities array */ - UINT8 protect_info[AVDT_PROTECT_SIZE]; /* Content protection capabilities */ - UINT8 num_codec; /* Number of media codec information elements */ - UINT8 num_protect; /* Number of content protection information elements */ - UINT16 psc_mask; /* Protocol service capabilities mask */ - UINT8 recov_type; /* Recovery type */ - UINT8 recov_mrws; /* Maximum recovery window size */ - UINT8 recov_mnmp; /* Recovery maximum number of media packets */ - UINT8 hdrcmp_mask; /* Header compression capabilities */ -#if AVDT_MULTIPLEXING == TRUE - UINT8 mux_mask; /* Multiplexing capabilities. AVDT_MUX_XXX bits can be combined with a bitwise OR */ - UINT8 mux_tsid_media; /* TSID for media transport session */ - UINT8 mux_tcid_media; /* TCID for media transport session */ - UINT8 mux_tsid_report; /* TSID for reporting transport session */ - UINT8 mux_tcid_report; /* TCID for reporting transport session */ - UINT8 mux_tsid_recov; /* TSID for recovery transport session */ - UINT8 mux_tcid_recov; /* TCID for recovery transport session */ -#endif -} tAVDT_CFG; - -/* Header structure for callback event parameters. */ -typedef struct { - UINT8 err_code; /* Zero if operation succeeded; nonzero if operation failed */ - UINT8 err_param; /* Error parameter included for some events */ - UINT8 label; /* Transaction label */ - UINT8 seid; /* For internal use only */ - UINT8 sig_id; /* For internal use only */ - UINT8 ccb_idx; /* For internal use only */ -} tAVDT_EVT_HDR; - -/* This data structure is associated with the AVDT_GETCAP_CFM_EVT, -** AVDT_RECONFIG_IND_EVT, and AVDT_RECONFIG_CFM_EVT. -*/ -typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ - tAVDT_CFG *p_cfg; /* Pointer to configuration for this SEP */ -} tAVDT_CONFIG; - -/* This data structure is associated with the AVDT_CONFIG_IND_EVT. */ -typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ - tAVDT_CFG *p_cfg; /* Pointer to configuration for this SEP */ - UINT8 int_seid; /* Stream endpoint ID of stream initiating the operation */ -} tAVDT_SETCONFIG; - -/* This data structure is associated with the AVDT_OPEN_IND_EVT and AVDT_OPEN_CFM_EVT. */ -typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ - UINT16 peer_mtu; /* Transport channel L2CAP MTU of the peer */ - UINT16 lcid; /* L2CAP LCID for media channel */ -} tAVDT_OPEN; - -/* This data structure is associated with the AVDT_SECURITY_IND_EVT -** and AVDT_SECURITY_CFM_EVT. -*/ -typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ - UINT8 *p_data; /* Pointer to security data */ - UINT16 len; /* Length in bytes of the security data */ -} tAVDT_SECURITY; - -/* This data structure is associated with the AVDT_DISCOVER_CFM_EVT. */ -typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ - tAVDT_SEP_INFO *p_sep_info; /* Pointer to SEP information */ - UINT8 num_seps; /* Number of stream endpoints */ -} tAVDT_DISCOVER; - -/* This data structure is associated with the AVDT_DELAY_REPORT_EVT. */ -typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ - UINT16 delay; /* Delay value */ -} tAVDT_DELAY_RPT; - -/* Union of all control callback event data structures */ -typedef union { - tAVDT_EVT_HDR hdr; - tAVDT_DISCOVER discover_cfm; - tAVDT_CONFIG getcap_cfm; - tAVDT_OPEN open_cfm; - tAVDT_OPEN open_ind; - tAVDT_SETCONFIG config_ind; - tAVDT_EVT_HDR start_cfm; - tAVDT_EVT_HDR suspend_cfm; - tAVDT_EVT_HDR close_cfm; - tAVDT_CONFIG reconfig_cfm; - tAVDT_CONFIG reconfig_ind; - tAVDT_SECURITY security_cfm; - tAVDT_SECURITY security_ind; - tAVDT_EVT_HDR connect_ind; - tAVDT_EVT_HDR disconnect_ind; - tAVDT_EVT_HDR report_conn; - tAVDT_DELAY_RPT delay_rpt_cmd; -} tAVDT_CTRL; - -/* This is the control callback function. This function passes control events -** to the application. This function is required for all registered stream -** endpoints and for the AVDT_DiscoverReq() and AVDT_GetCapReq() functions. -** -*/ -typedef void (tAVDT_CTRL_CBACK)(UINT8 handle, BD_ADDR bd_addr, UINT8 event, - tAVDT_CTRL *p_data); - -/* This is the data callback function. It is executed when AVDTP has a media -** packet ready for the application. This function is required for SNK -** endpoints and not applicable for SRC endpoints. -*/ -typedef void (tAVDT_DATA_CBACK)(UINT8 handle, BT_HDR *p_pkt, UINT32 time_stamp, - UINT8 m_pt); - -#if AVDT_MULTIPLEXING == TRUE -/* This is the second version of the data callback function. This version uses -** application buffer assigned by AVDT_SetMediaBuf. Caller can assign different -** buffer during callback or can leave the current buffer for further using. -** This callback is called when AVDTP has a media packet ready for the application. -** This function is required for SNK endpoints and not applicable for SRC endpoints. -*/ -typedef void (tAVDT_MEDIA_CBACK)(UINT8 handle, UINT8 *p_payload, UINT32 payload_len, - UINT32 time_stamp, UINT16 seq_num, UINT8 m_pt, UINT8 marker); -#endif - -#if AVDT_REPORTING == TRUE -/* This is the report callback function. It is executed when AVDTP has a reporting -** packet ready for the application. This function is required for streams -** created with AVDT_PSC_REPORT. -*/ -typedef void (tAVDT_REPORT_CBACK)(UINT8 handle, AVDT_REPORT_TYPE type, - tAVDT_REPORT_DATA *p_data); -#endif - -typedef UINT16 (tAVDT_GETCAP_REQ) (BD_ADDR bd_addr, UINT8 seid, tAVDT_CFG *p_cfg, tAVDT_CTRL_CBACK *p_cback); - -/* This structure contains information required when a stream is created. -** It is passed to the AVDT_CreateStream() function. -*/ -typedef struct { - tAVDT_CFG cfg; /* SEP configuration */ - tAVDT_CTRL_CBACK *p_ctrl_cback; /* Control callback function */ - tAVDT_DATA_CBACK *p_data_cback; /* Data callback function */ -#if AVDT_MULTIPLEXING == TRUE - tAVDT_MEDIA_CBACK *p_media_cback; /* Media callback function. It will be called only if p_data_cback is NULL */ -#endif -#if AVDT_REPORTING == TRUE - tAVDT_REPORT_CBACK *p_report_cback;/* Report callback function. */ -#endif - UINT16 mtu; /* The L2CAP MTU of the transport channel */ - UINT16 flush_to; /* The L2CAP flush timeout of the transport channel */ - UINT8 tsep; /* SEP type */ - UINT8 media_type; /* Media type */ - UINT16 nsc_mask; /* Nonsupported protocol command messages */ -} tAVDT_CS; - -/* AVDT data option mask is used in the write request */ -#define AVDT_DATA_OPT_NONE 0x00 /* No option still add RTP header */ -#define AVDT_DATA_OPT_NO_RTP (0x01 << 0) /* Skip adding RTP header */ - -typedef UINT8 tAVDT_DATA_OPT_MASK; - - - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function AVDT_Register -** -** Description This is the system level registration function for the -** AVDTP protocol. This function initializes AVDTP and -** prepares the protocol stack for its use. This function -** must be called once by the system or platform using AVDTP -** before the other functions of the API an be used. -** -** -** Returns void -** -*******************************************************************************/ -extern void AVDT_Register(tAVDT_REG *p_reg, tAVDT_CTRL_CBACK *p_cback); - -/******************************************************************************* -** -** Function AVDT_Deregister -** -** Description This function is called to deregister use AVDTP protocol. -** It is called when AVDTP is no longer being used by any -** application in the system. Before this function can be -** called, all streams must be removed with AVDT_RemoveStream(). -** -** -** Returns void -** -*******************************************************************************/ -extern void AVDT_Deregister(void); - - -/******************************************************************************* -** -** Function AVDT_SINK_Activate -** -** Description Activate SEP of A2DP Sink. In Use parameter is adjusted. -** In Use will be made false in case of activation. A2DP SRC -** will receive in_use as false and can open A2DP Sink -** connection -** -** Returns void -** -*******************************************************************************/ -extern void AVDT_SINK_Activate(void); - -/******************************************************************************* -** -** Function AVDT_SINK_Deactivate -** -** Description Deactivate SEP of A2DP Sink. In Use parameter is adjusted. -** In Use will be made TRUE in case of activation. A2DP SRC -** will receive in_use as true and will not open A2DP Sink -** connection -** -** Returns void. -** -*******************************************************************************/ -extern void AVDT_SINK_Deactivate(void); - -/******************************************************************************* -** -** Function AVDT_AbortReq -** -** Description Trigger Abort request to pass AVDTP Abort related mandatory -** PTS Test case. -** -** Returns void. -** -*******************************************************************************/ -extern void AVDT_AbortReq(UINT8 handle); - -/******************************************************************************* -** -** Function AVDT_CreateStream -** -** Description Create a stream endpoint. After a stream endpoint is -** created an application can initiate a connection between -** this endpoint and an endpoint on a peer device. In -** addition, a peer device can discover, get the capabilities, -** and connect to this endpoint. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_CreateStream(UINT8 *p_handle, tAVDT_CS *p_cs); - -/******************************************************************************* -** -** Function AVDT_RemoveStream -** -** Description Remove a stream endpoint. This function is called when -** the application is no longer using a stream endpoint. -** If this function is called when the endpoint is connected -** the connection is closed and then the stream endpoint -** is removed. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_RemoveStream(UINT8 handle); - -/******************************************************************************* -** -** Function AVDT_DiscoverReq -** -** Description This function initiates a connection to the AVDTP service -** on the peer device, if not already present, and discovers -** the stream endpoints on the peer device. (Please note -** that AVDTP discovery is unrelated to SDP discovery). -** This function can be called at any time regardless of whether -** there is an AVDTP connection to the peer device. -** -** When discovery is complete, an AVDT_DISCOVER_CFM_EVT -** is sent to the application via its callback function. -** The application must not call AVDT_GetCapReq() or -** AVDT_DiscoverReq() again to the same device until -** discovery is complete. -** -** The memory addressed by sep_info is allocated by the -** application. This memory is written to by AVDTP as part -** of the discovery procedure. This memory must remain -** accessible until the application receives the -** AVDT_DISCOVER_CFM_EVT. -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_DiscoverReq(BD_ADDR bd_addr, tAVDT_SEP_INFO *p_sep_info, - UINT8 max_seps, tAVDT_CTRL_CBACK *p_cback); - - -/******************************************************************************* -** -** Function AVDT_GetCapReq -** -** Description This function initiates a connection to the AVDTP service -** on the peer device, if not already present, and gets the -** capabilities of a stream endpoint on the peer device. -** This function can be called at any time regardless of -** whether there is an AVDTP connection to the peer device. -** -** When the procedure is complete, an AVDT_GETCAP_CFM_EVT is -** sent to the application via its callback function. The -** application must not call AVDT_GetCapReq() or -** AVDT_DiscoverReq() again until the procedure is complete. -** -** The memory pointed to by p_cfg is allocated by the -** application. This memory is written to by AVDTP as part -** of the get capabilities procedure. This memory must -** remain accessible until the application receives -** the AVDT_GETCAP_CFM_EVT. -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_GetCapReq(BD_ADDR bd_addr, UINT8 seid, tAVDT_CFG *p_cfg, - tAVDT_CTRL_CBACK *p_cback); - -/******************************************************************************* -** -** Function AVDT_GetAllCapReq -** -** Description This function initiates a connection to the AVDTP service -** on the peer device, if not already present, and gets the -** capabilities of a stream endpoint on the peer device. -** This function can be called at any time regardless of -** whether there is an AVDTP connection to the peer device. -** -** When the procedure is complete, an AVDT_GETCAP_CFM_EVT is -** sent to the application via its callback function. The -** application must not call AVDT_GetCapReq() or -** AVDT_DiscoverReq() again until the procedure is complete. -** -** The memory pointed to by p_cfg is allocated by the -** application. This memory is written to by AVDTP as part -** of the get capabilities procedure. This memory must -** remain accessible until the application receives -** the AVDT_GETCAP_CFM_EVT. -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_GetAllCapReq(BD_ADDR bd_addr, UINT8 seid, tAVDT_CFG *p_cfg, - tAVDT_CTRL_CBACK *p_cback); - -/******************************************************************************* -** -** Function AVDT_DelayReport -** -** Description This functions sends a Delay Report to the peer device -** that is associated with a particular SEID. -** This function is called by SNK device. -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_DelayReport(UINT8 handle, UINT8 seid, UINT16 delay); - -/******************************************************************************* -** -** Function AVDT_OpenReq -** -** Description This function initiates a connection to the AVDTP service -** on the peer device, if not already present, and connects -** to a stream endpoint on a peer device. When the connection -** is completed, an AVDT_OPEN_CFM_EVT is sent to the -** application via the control callback function for this handle. -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_OpenReq(UINT8 handle, BD_ADDR bd_addr, UINT8 seid, - tAVDT_CFG *p_cfg); - - -/******************************************************************************* -** -** Function AVDT_ConfigRsp -** -** Description Respond to a configure request from the peer device. This -** function must be called if the application receives an -** AVDT_CONFIG_IND_EVT through its control callback. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_ConfigRsp(UINT8 handle, UINT8 label, UINT8 error_code, - UINT8 category); - -/******************************************************************************* -** -** Function AVDT_StartReq -** -** Description Start one or more stream endpoints. This initiates the -** transfer of media packets for the streams. All stream -** endpoints must previously be opened. When the streams -** are started, an AVDT_START_CFM_EVT is sent to the -** application via the control callback function for each stream. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_StartReq(UINT8 *p_handles, UINT8 num_handles); - -/******************************************************************************* -** -** Function AVDT_SuspendReq -** -** Description Suspend one or more stream endpoints. This suspends the -** transfer of media packets for the streams. All stream -** endpoints must previously be open and started. When the -** streams are suspended, an AVDT_SUSPEND_CFM_EVT is sent to -** the application via the control callback function for -** each stream. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_SuspendReq(UINT8 *p_handles, UINT8 num_handles); - -/******************************************************************************* -** -** Function AVDT_CloseReq -** -** Description Close a stream endpoint. This stops the transfer of media -** packets and closes the transport channel associated with -** this stream endpoint. When the stream is closed, an -** AVDT_CLOSE_CFM_EVT is sent to the application via the -** control callback function for this handle. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_CloseReq(UINT8 handle); - -/******************************************************************************* -** -** Function AVDT_ReconfigReq -** -** Description Reconfigure a stream endpoint. This allows the application -** to change the codec or content protection capabilities of -** a stream endpoint after it has been opened. This function -** can only be called if the stream is opened but not started -** or if the stream has been suspended. When the procedure -** is completed, an AVDT_RECONFIG_CFM_EVT is sent to the -** application via the control callback function for this handle. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_ReconfigReq(UINT8 handle, tAVDT_CFG *p_cfg); - -/******************************************************************************* -** -** Function AVDT_ReconfigRsp -** -** Description Respond to a reconfigure request from the peer device. -** This function must be called if the application receives -** an AVDT_RECONFIG_IND_EVT through its control callback. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_ReconfigRsp(UINT8 handle, UINT8 label, UINT8 error_code, - UINT8 category); - -/******************************************************************************* -** -** Function AVDT_SecurityReq -** -** Description Send a security request to the peer device. When the -** security procedure is completed, an AVDT_SECURITY_CFM_EVT -** is sent to the application via the control callback function -** for this handle. (Please note that AVDTP security procedures -** are unrelated to Bluetooth link level security.) -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_SecurityReq(UINT8 handle, UINT8 *p_data, UINT16 len); - -/******************************************************************************* -** -** Function AVDT_SecurityRsp -** -** Description Respond to a security request from the peer device. -** This function must be called if the application receives -** an AVDT_SECURITY_IND_EVT through its control callback. -** (Please note that AVDTP security procedures are unrelated -** to Bluetooth link level security.) -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_SecurityRsp(UINT8 handle, UINT8 label, UINT8 error_code, - UINT8 *p_data, UINT16 len); - -/******************************************************************************* -** -** Function AVDT_WriteReq -** -** Description Send a media packet to the peer device. The stream must -** be started before this function is called. Also, this -** function can only be called if the stream is a SRC. -** -** When AVDTP has sent the media packet and is ready for the -** next packet, an AVDT_WRITE_CFM_EVT is sent to the -** application via the control callback. The application must -** wait for the AVDT_WRITE_CFM_EVT before it makes the next -** call to AVDT_WriteReq(). If the applications calls -** AVDT_WriteReq() before it receives the event the packet -** will not be sent. The application may make its first call -** to AVDT_WriteReq() after it receives an AVDT_START_CFM_EVT -** or AVDT_START_IND_EVT. -** -** The application passes the packet using the BT_HDR structure. -** This structure is described in section 2.1. The offset -** field must be equal to or greater than AVDT_MEDIA_OFFSET. -** This allows enough space in the buffer for the L2CAP and -** AVDTP headers. -** -** The memory pointed to by p_pkt must be a GKI buffer -** allocated by the application. This buffer will be freed -** by the protocol stack; the application must not free -** this buffer. -** -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_WriteReq(UINT8 handle, BT_HDR *p_pkt, UINT32 time_stamp, - UINT8 m_pt); -/******************************************************************************* -** -** Function AVDT_WriteReqOpt -** -** Description Send a media packet to the peer device. The stream must -** be started before this function is called. Also, this -** function can only be called if the stream is a SRC -** -** When AVDTP has sent the media packet and is ready for the -** next packet, an AVDT_WRITE_CFM_EVT is sent to the -** application via the control callback. The application must -** wait for the AVDT_WRITE_CFM_EVT before it makes the next -** call to AVDT_WriteReq(). If the applications calls -** AVDT_WriteReq() before it receives the event the packet -** will not be sent. The application may make its first call -** to AVDT_WriteReq() after it receives an AVDT_START_CFM_EVT -** or AVDT_START_IND_EVT. -** -** The application passes the packet using the BT_HDR structure -** This structure is described in section 2.1. The offset -** field must be equal to or greater than AVDT_MEDIA_OFFSET -** (if NO_RTP is specified, L2CAP_MIN_OFFSET can be used) -** This allows enough space in the buffer for the L2CAP and -** AVDTP headers. -** -** The memory pointed to by p_pkt must be a GKI buffer -** allocated by the application. This buffer will be freed -** by the protocol stack; the application must not free -** this buffer. -** -** The opt parameter allows passing specific options like: -** - NO_RTP : do not add the RTP header to buffer -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_WriteReqOpt(UINT8 handle, BT_HDR *p_pkt, UINT32 time_stamp, - UINT8 m_pt, tAVDT_DATA_OPT_MASK opt); - -/******************************************************************************* -** -** Function AVDT_ConnectReq -** -** Description This function initiates an AVDTP signaling connection -** to the peer device. When the connection is completed, an -** AVDT_CONNECT_IND_EVT is sent to the application via its -** control callback function. If the connection attempt fails -** an AVDT_DISCONNECT_IND_EVT is sent. The security mask -** parameter overrides the outgoing security mask set in -** AVDT_Register(). -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_ConnectReq(BD_ADDR bd_addr, UINT8 sec_mask, - tAVDT_CTRL_CBACK *p_cback); - -/******************************************************************************* -** -** Function AVDT_DisconnectReq -** -** Description This function disconnect an AVDTP signaling connection -** to the peer device. When disconnected an -** AVDT_DISCONNECT_IND_EVT is sent to the application via its -** control callback function. -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_DisconnectReq(BD_ADDR bd_addr, tAVDT_CTRL_CBACK *p_cback); - -/******************************************************************************* -** -** Function AVDT_GetL2CapChannel -** -** Description Get the L2CAP CID used by the handle. -** -** Returns CID if successful, otherwise 0. -** -*******************************************************************************/ -extern UINT16 AVDT_GetL2CapChannel(UINT8 handle); - -/******************************************************************************* -** -** Function AVDT_GetSignalChannel -** -** Description Get the L2CAP CID used by the signal channel of the given handle. -** -** Returns CID if successful, otherwise 0. -** -*******************************************************************************/ -extern UINT16 AVDT_GetSignalChannel(UINT8 handle, BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function AVDT_WriteDataReq -** -** Description Send a media packet to the peer device. The stream must -** be started before this function is called. Also, this -** function can only be called if the stream is a SRC. -** -** When AVDTP has sent the media packet and is ready for the -** next packet, an AVDT_WRITE_CFM_EVT is sent to the -** application via the control callback. The application must -** wait for the AVDT_WRITE_CFM_EVT before it makes the next -** call to AVDT_WriteDataReq(). If the applications calls -** AVDT_WriteDataReq() before it receives the event the packet -** will not be sent. The application may make its first call -** to AVDT_WriteDataReq() after it receives an -** AVDT_START_CFM_EVT or AVDT_START_IND_EVT. -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_WriteDataReq(UINT8 handle, UINT8 *p_data, UINT32 data_len, - UINT32 time_stamp, UINT8 m_pt, UINT8 marker); - -/******************************************************************************* -** -** Function AVDT_SetMediaBuf -** -** Description Assigns buffer for media packets or forbids using of assigned -** buffer if argument p_buf is NULL. This function can only -** be called if the stream is a SNK. -** -** AVDTP uses this buffer to reassemble fragmented media packets. -** When AVDTP receives a complete media packet, it calls the -** p_media_cback assigned by AVDT_CreateStream(). -** This function can be called during callback to assign a -** different buffer for next media packet or can leave the current -** buffer for next packet. -** -** Returns AVDT_SUCCESS if successful, otherwise error. -** -*******************************************************************************/ -extern UINT16 AVDT_SetMediaBuf(UINT8 handle, UINT8 *p_buf, UINT32 buf_len); - -/******************************************************************************* -** -** Function AVDT_SendReport -** -** Description -** -** -** -** Returns -** -*******************************************************************************/ -extern UINT16 AVDT_SendReport(UINT8 handle, AVDT_REPORT_TYPE type, - tAVDT_REPORT_DATA *p_data); - -/****************************************************************************** -** -** Function AVDT_SetTraceLevel -** -** Description Sets the trace level for AVDT. If 0xff is passed, the -** current trace level is returned. -** -** Input Parameters: -** new_level: The level to set the AVDT tracing to: -** 0xff-returns the current setting. -** 0-turns off tracing. -** >= 1-Errors. -** >= 2-Warnings. -** >= 3-APIs. -** >= 4-Events. -** >= 5-Debug. -** -** Returns The new trace level or current trace level if -** the input parameter is 0xff. -** -******************************************************************************/ -extern UINT8 AVDT_SetTraceLevel (UINT8 new_level); - -#ifdef __cplusplus -} -#endif - - -#endif /* AVDT_API_H */ diff --git a/tools/sdk/include/bluedroid/avdt_defs.h b/tools/sdk/include/bluedroid/avdt_defs.h deleted file mode 100644 index ad1d9d1efab..00000000000 --- a/tools/sdk/include/bluedroid/avdt_defs.h +++ /dev/null @@ -1,208 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This contains constants definitions and other information from the AVDTP - * specification. This file is intended for use internal to AVDT only. - * - ******************************************************************************/ -#ifndef AVDT_DEFS_H -#define AVDT_DEFS_H -#include "bt_target.h" - -#if (AVDT_INCLUDED == TRUE) - -/***************************************************************************** -** constants -*****************************************************************************/ - -/* signalling packet type */ -#define AVDT_PKT_TYPE_SINGLE 0 /* single packet */ -#define AVDT_PKT_TYPE_START 1 /* start packet */ -#define AVDT_PKT_TYPE_CONT 2 /* continue packet */ -#define AVDT_PKT_TYPE_END 3 /* end packet */ - -/* signalling message type */ -#define AVDT_MSG_TYPE_CMD 0 /* command */ -#define AVDT_MSG_TYPE_GRJ 1 /* general reject */ -#define AVDT_MSG_TYPE_RSP 2 /* response accept */ -#define AVDT_MSG_TYPE_REJ 3 /* response reject */ - -/* signalling messages */ -#define AVDT_SIG_DISCOVER 1 /* discover */ -#define AVDT_SIG_GETCAP 2 /* get capabilities */ -#define AVDT_SIG_SETCONFIG 3 /* set configuration */ -#define AVDT_SIG_GETCONFIG 4 /* get configuration */ -#define AVDT_SIG_RECONFIG 5 /* reconfigure */ -#define AVDT_SIG_OPEN 6 /* open */ -#define AVDT_SIG_START 7 /* start */ -#define AVDT_SIG_CLOSE 8 /* close */ -#define AVDT_SIG_SUSPEND 9 /* suspend */ -#define AVDT_SIG_ABORT 10 /* abort */ -#define AVDT_SIG_SECURITY 11 /* security control */ -#define AVDT_SIG_GET_ALLCAP 12 /* get all capabilities */ -#define AVDT_SIG_DELAY_RPT 13 /* delay report */ - -/* maximum signal value */ -#define AVDT_SIG_MAX AVDT_SIG_DELAY_RPT - -/* used for general reject */ -#define AVDT_SIG_NONE 0 - -/* some maximum and minimum sizes of signalling messages */ -#define AVDT_DISCOVER_REQ_MIN 1 -#define AVDT_DISCOVER_REQ_MAX 124 - -/* service category information element field values */ -#define AVDT_CAT_TRANS 1 /* Media Transport */ -#define AVDT_CAT_REPORT 2 /* Reporting */ -#define AVDT_CAT_RECOV 3 /* Recovery */ -#define AVDT_CAT_PROTECT 4 /* Content Protection */ -#define AVDT_CAT_HDRCMP 5 /* Header Compression */ -#define AVDT_CAT_MUX 6 /* Multiplexing */ -#define AVDT_CAT_CODEC 7 /* Media Codec */ -#define AVDT_CAT_DELAY_RPT 8 /* Delay Reporting */ -#define AVDT_CAT_MAX_CUR AVDT_CAT_DELAY_RPT - -/* min/max lengths of service category information elements */ -#define AVDT_LEN_TRANS_MIN 0 -#define AVDT_LEN_REPORT_MIN 0 -#define AVDT_LEN_RECOV_MIN 3 -#define AVDT_LEN_PROTECT_MIN 2 -#define AVDT_LEN_HDRCMP_MIN 1 -#define AVDT_LEN_MUX_MIN 3 -#define AVDT_LEN_CODEC_MIN 2 -#define AVDT_LEN_DELAY_RPT_MIN 0 - -#define AVDT_LEN_TRANS_MAX 0 -#define AVDT_LEN_REPORT_MAX 0 -#define AVDT_LEN_RECOV_MAX 3 -#define AVDT_LEN_PROTECT_MAX 255 -#define AVDT_LEN_HDRCMP_MAX 1 -#define AVDT_LEN_MUX_MAX 7 -#define AVDT_LEN_CODEC_MAX 255 -#define AVDT_LEN_DELAY_RPT_MAX 0 - -/* minimum possible size of configuration or capabilities data */ -#define AVDT_LEN_CFG_MIN 2 - -/* minimum and maximum lengths for different message types */ -#define AVDT_LEN_SINGLE 1 -#define AVDT_LEN_SETCONFIG_MIN 2 -#define AVDT_LEN_RECONFIG_MIN 1 -#define AVDT_LEN_MULTI_MIN 1 -#define AVDT_LEN_SECURITY_MIN 1 -#define AVDT_LEN_DELAY_RPT 3 - -/* header lengths for different packet types */ -#define AVDT_LEN_TYPE_SINGLE 2 /* single packet */ -#define AVDT_LEN_TYPE_START 3 /* start packet */ -#define AVDT_LEN_TYPE_CONT 1 /* continue packet */ -#define AVDT_LEN_TYPE_END 1 /* end packet */ - -/* length of general reject message */ -#define AVDT_LEN_GEN_REJ 2 - -/* recovery service capabilities information elements */ -#define AVDT_RECOV_MRWS_MIN 0x01 /* min value for maximum recovery window */ -#define AVDT_RECOV_MRWS_MAX 0x18 /* max value for maximum recovery window */ -#define AVDT_RECOV_MNMP_MIN 0x01 /* min value for maximum number of media packets */ -#define AVDT_RECOV_MNMP_MAX 0x18 /* max value for maximum number of media packets */ - -/* SEID value range */ -#define AVDT_SEID_MIN 0x01 -#define AVDT_SEID_MAX 0x3E - -/* first byte of media packet header */ -#define AVDT_MEDIA_OCTET1 0x80 - -/* for adaptation layer header */ -#define AVDT_ALH_LCODE_MASK 0x03 /* coding of length field */ -#define AVDT_ALH_LCODE_NONE 0x00 /* No length field present. Take length from l2cap */ -#define AVDT_ALH_LCODE_16BIT 0x01 /* 16bit length field */ -#define AVDT_ALH_LCODE_9BITM0 0x02 /* 9 bit length field, MSB = 0, 8 LSBs in 1 octet following */ -#define AVDT_ALH_LCODE_9BITM1 0x03 /* 9 bit length field, MSB = 1, 8 LSBs in 1 octet following */ - -#define AVDT_ALH_FRAG_MASK 0x04 /* set this for continuation packet */ - -/***************************************************************************** -** message parsing and building macros -*****************************************************************************/ - -#define AVDT_MSG_PRS_HDR(p, lbl, pkt, msg) \ - lbl = *(p) >> 4; \ - pkt = (*(p) >> 2) & 0x03; \ - msg = *(p)++ & 0x03; - -#define AVDT_MSG_PRS_DISC(p, seid, in_use, type, tsep) \ - seid = *(p) >> 2; \ - in_use = (*(p)++ >> 1) & 0x01; \ - type = *(p) >> 4; \ - tsep = (*(p)++ >> 3) & 0x01; - -#define AVDT_MSG_PRS_SIG(p, sig) \ - sig = *(p)++ & 0x3F; - -#define AVDT_MSG_PRS_SEID(p, seid) \ - seid = *(p)++ >> 2; - -#define AVDT_MSG_PRS_PKT_TYPE(p, pkt) \ - pkt = (*(p) >> 2) & 0x03; - -#define AVDT_MSG_PRS_OCTET1(p, o_v, o_p, o_x, o_cc) \ - o_v = *(p) >> 6; \ - o_p = (*(p) >> 5) & 0x01; \ - o_x = (*(p) >> 4) & 0x01; \ - o_cc = *(p)++ & 0x0F; - -#define AVDT_MSG_PRS_RPT_OCTET1(p, o_v, o_p, o_cc) \ - o_v = *(p) >> 6; \ - o_p = (*(p) >> 5) & 0x01; \ - o_cc = *(p)++ & 0x1F; - -#define AVDT_MSG_PRS_M_PT(p, m_pt, marker) \ - marker = *(p) >> 7; \ - m_pt = *(p)++ & 0x7F; - -#define AVDT_MSG_BLD_HDR(p, lbl, pkt, msg) \ - *(p)++ = (UINT8) ((lbl) << 4) | ((pkt) << 2) | (msg); - -#define AVDT_MSG_BLD_DISC(p, seid, in_use, type, tsep) \ - *(p)++ = (UINT8) (((seid) << 2) | ((in_use) << 1)); \ - *(p)++ = (UINT8) (((type) << 4) | ((tsep) << 3)); - -#define AVDT_MSG_BLD_SIG(p, sig) \ - *(p)++ = (UINT8) (sig); - -#define AVDT_MSG_BLD_SEID(p, seid) \ - *(p)++ = (UINT8) ((seid) << 2); - -#define AVDT_MSG_BLD_ERR(p, err) \ - *(p)++ = (UINT8) (err); - -#define AVDT_MSG_BLD_PARAM(p, param) \ - *(p)++ = (UINT8) (param); - -#define AVDT_MSG_BLD_NOSP(p, nosp) \ - *(p)++ = (UINT8) (nosp); - -#endif ///AVRC_INCLUDED == TRUE - -#endif /* AVDT_DEFS_H */ - diff --git a/tools/sdk/include/bluedroid/avdt_int.h b/tools/sdk/include/bluedroid/avdt_int.h deleted file mode 100644 index 6555152ac09..00000000000 --- a/tools/sdk/include/bluedroid/avdt_int.h +++ /dev/null @@ -1,748 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains interfaces which are internal to AVDTP. - * - ******************************************************************************/ -#ifndef AVDT_INT_H -#define AVDT_INT_H - -#include "avdt_api.h" -#include "avdtc_api.h" -#include "avdt_defs.h" -#include "l2c_api.h" -#include "btm_api.h" -#include "fixed_queue.h" - -#if (AVRC_INCLUDED == TRUE) - -#ifndef AVDT_DEBUG -#define AVDT_DEBUG FALSE -#endif - -/***************************************************************************** -** constants -*****************************************************************************/ - -/* channel types */ -enum { - AVDT_CHAN_SIG, /* signaling channel */ - AVDT_CHAN_MEDIA, /* media channel */ -#if AVDT_REPORTING == TRUE - AVDT_CHAN_REPORT, /* reporting channel */ -#endif - AVDT_CHAN_NUM_TYPES -}; - -/* protocol service capabilities of this AVDTP implementation */ -/* for now multiplexing will be used only for fragmentation */ -#if ((AVDT_MULTIPLEXING == TRUE) && (AVDT_REPORTING == TRUE)) -#define AVDT_PSC (AVDT_PSC_TRANS | AVDT_PSC_MUX | AVDT_PSC_REPORT | AVDT_PSC_DELAY_RPT) -#define AVDT_LEG_PSC (AVDT_PSC_TRANS | AVDT_PSC_MUX | AVDT_PSC_REPORT) -#else /* AVDT_MULTIPLEXING && AVDT_REPORTING */ - -#if (AVDT_MULTIPLEXING == TRUE) -#define AVDT_PSC (AVDT_PSC_TRANS | AVDT_PSC_MUX | AVDT_PSC_DELAY_RPT) -#define AVDT_LEG_PSC (AVDT_PSC_TRANS | AVDT_PSC_MUX) -#else /* AVDT_MULTIPLEXING */ - -#if (AVDT_REPORTING == TRUE) -#define AVDT_PSC (AVDT_PSC_TRANS | AVDT_PSC_REPORT | AVDT_PSC_DELAY_RPT) -#define AVDT_LEG_PSC (AVDT_PSC_TRANS | AVDT_PSC_REPORT) -#else /* AVDT_REPORTING */ -#define AVDT_PSC (AVDT_PSC_TRANS | AVDT_PSC_DELAY_RPT) -#define AVDT_LEG_PSC (AVDT_PSC_TRANS) -#endif /* AVDT_REPORTING */ - -#endif /* AVDT_MULTIPLEXING */ - -#endif /* AVDT_MULTIPLEXING && AVDT_REPORTING */ - -/* initiator/acceptor signaling roles */ -#define AVDT_CLOSE_ACP 0 -#define AVDT_CLOSE_INT 1 -#define AVDT_OPEN_ACP 2 -#define AVDT_OPEN_INT 3 - -/* states for avdt_scb_verify */ -#define AVDT_VERIFY_OPEN 0 -#define AVDT_VERIFY_STREAMING 1 -#define AVDT_VERIFY_SUSPEND 2 -#define AVDT_VERIFY_START 3 - -/* to distinguish CCB events from SCB events */ -#define AVDT_CCB_MKR 0x80 - -/* offset where AVDTP signaling message header starts in message */ -#define AVDT_HDR_OFFSET (L2CAP_MIN_OFFSET + AVDT_NUM_SEPS) - -/* offset where AVDTP signaling message content starts; -** use the size of a start header since it's the largest possible -** layout of signaling message in a buffer is: -** -** | BT_HDR | SCB handles | L2CAP + HCI header | AVDTP header | data ... | -** -** Note that we "hide" the scb handles at the top of the message buffer. -*/ -#define AVDT_MSG_OFFSET (L2CAP_MIN_OFFSET + AVDT_NUM_SEPS + AVDT_LEN_TYPE_START) - -/* scb transport channel connect timeout value */ -#define AVDT_SCB_TC_CONN_TOUT 10 - -/* scb transport channel disconnect timeout value */ -#define AVDT_SCB_TC_DISC_TOUT 10 - -/* maximum number of command retransmissions */ -#ifndef AVDT_RET_MAX -#define AVDT_RET_MAX 1 -#endif - - -/* ccb state machine states */ -enum { - AVDT_CCB_IDLE_ST, - AVDT_CCB_OPENING_ST, - AVDT_CCB_OPEN_ST, - AVDT_CCB_CLOSING_ST -}; - -/* state machine action enumeration list */ -enum { - AVDT_CCB_CHAN_OPEN, - AVDT_CCB_CHAN_CLOSE, - AVDT_CCB_CHK_CLOSE, - AVDT_CCB_HDL_DISCOVER_CMD, - AVDT_CCB_HDL_DISCOVER_RSP, - AVDT_CCB_HDL_GETCAP_CMD, - AVDT_CCB_HDL_GETCAP_RSP, - AVDT_CCB_HDL_START_CMD, - AVDT_CCB_HDL_START_RSP, - AVDT_CCB_HDL_SUSPEND_CMD, - AVDT_CCB_HDL_SUSPEND_RSP, - AVDT_CCB_SND_DISCOVER_CMD, - AVDT_CCB_SND_DISCOVER_RSP, - AVDT_CCB_SND_GETCAP_CMD, - AVDT_CCB_SND_GETCAP_RSP, - AVDT_CCB_SND_START_CMD, - AVDT_CCB_SND_START_RSP, - AVDT_CCB_SND_SUSPEND_CMD, - AVDT_CCB_SND_SUSPEND_RSP, - AVDT_CCB_CLEAR_CMDS, - AVDT_CCB_CMD_FAIL, - AVDT_CCB_FREE_CMD, - AVDT_CCB_CONG_STATE, - AVDT_CCB_RET_CMD, - AVDT_CCB_SND_CMD, - AVDT_CCB_SND_MSG, - AVDT_CCB_SET_RECONN, - AVDT_CCB_CLR_RECONN, - AVDT_CCB_CHK_RECONN, - AVDT_CCB_CHK_TIMER, - AVDT_CCB_SET_CONN, - AVDT_CCB_SET_DISCONN, - AVDT_CCB_DO_DISCONN, - AVDT_CCB_LL_CLOSED, - AVDT_CCB_LL_OPENED, - AVDT_CCB_DEALLOC, - AVDT_CCB_NUM_ACTIONS -}; - -#define AVDT_CCB_IGNORE AVDT_CCB_NUM_ACTIONS - -/* ccb state machine events */ -enum { - AVDT_CCB_API_DISCOVER_REQ_EVT, - AVDT_CCB_API_GETCAP_REQ_EVT, - AVDT_CCB_API_START_REQ_EVT, - AVDT_CCB_API_SUSPEND_REQ_EVT, - AVDT_CCB_API_DISCOVER_RSP_EVT, - AVDT_CCB_API_GETCAP_RSP_EVT, - AVDT_CCB_API_START_RSP_EVT, - AVDT_CCB_API_SUSPEND_RSP_EVT, - AVDT_CCB_API_CONNECT_REQ_EVT, - AVDT_CCB_API_DISCONNECT_REQ_EVT, - AVDT_CCB_MSG_DISCOVER_CMD_EVT, - AVDT_CCB_MSG_GETCAP_CMD_EVT, - AVDT_CCB_MSG_START_CMD_EVT, - AVDT_CCB_MSG_SUSPEND_CMD_EVT, - AVDT_CCB_MSG_DISCOVER_RSP_EVT, - AVDT_CCB_MSG_GETCAP_RSP_EVT, - AVDT_CCB_MSG_START_RSP_EVT, - AVDT_CCB_MSG_SUSPEND_RSP_EVT, - AVDT_CCB_RCVRSP_EVT, - AVDT_CCB_SENDMSG_EVT, - AVDT_CCB_RET_TOUT_EVT, - AVDT_CCB_RSP_TOUT_EVT, - AVDT_CCB_IDLE_TOUT_EVT, - AVDT_CCB_UL_OPEN_EVT, - AVDT_CCB_UL_CLOSE_EVT, - AVDT_CCB_LL_OPEN_EVT, - AVDT_CCB_LL_CLOSE_EVT, - AVDT_CCB_LL_CONG_EVT -}; - - -/* scb state machine states; these state values are private to this module so -** the scb state cannot be read or set by actions functions -*/ -enum { - AVDT_SCB_IDLE_ST, - AVDT_SCB_CONF_ST, - AVDT_SCB_OPENING_ST, - AVDT_SCB_OPEN_ST, - AVDT_SCB_STREAM_ST, - AVDT_SCB_CLOSING_ST -}; - -/* state machine action enumeration list */ -enum { - AVDT_SCB_HDL_ABORT_CMD, - AVDT_SCB_HDL_ABORT_RSP, - AVDT_SCB_HDL_CLOSE_CMD, - AVDT_SCB_HDL_CLOSE_RSP, - AVDT_SCB_HDL_GETCONFIG_CMD, - AVDT_SCB_HDL_GETCONFIG_RSP, - AVDT_SCB_HDL_OPEN_CMD, - AVDT_SCB_HDL_OPEN_REJ, - AVDT_SCB_HDL_OPEN_RSP, - AVDT_SCB_HDL_PKT, - AVDT_SCB_DROP_PKT, - AVDT_SCB_HDL_RECONFIG_CMD, - AVDT_SCB_HDL_RECONFIG_RSP, - AVDT_SCB_HDL_SECURITY_CMD, - AVDT_SCB_HDL_SECURITY_RSP, - AVDT_SCB_HDL_SETCONFIG_CMD, - AVDT_SCB_HDL_SETCONFIG_REJ, - AVDT_SCB_HDL_SETCONFIG_RSP, - AVDT_SCB_HDL_START_CMD, - AVDT_SCB_HDL_START_RSP, - AVDT_SCB_HDL_SUSPEND_CMD, - AVDT_SCB_HDL_SUSPEND_RSP, - AVDT_SCB_HDL_TC_CLOSE, -#if AVDT_REPORTING == TRUE - AVDT_SCB_HDL_TC_CLOSE_STO, -#endif - AVDT_SCB_HDL_TC_OPEN, -#if AVDT_REPORTING == TRUE - AVDT_SCB_HDL_TC_OPEN_STO, -#endif - AVDT_SCB_SND_DELAY_RPT_REQ, - AVDT_SCB_HDL_DELAY_RPT_CMD, - AVDT_SCB_HDL_DELAY_RPT_RSP, - AVDT_SCB_HDL_WRITE_REQ, - AVDT_SCB_SND_ABORT_REQ, - AVDT_SCB_SND_ABORT_RSP, - AVDT_SCB_SND_CLOSE_REQ, - AVDT_SCB_SND_STREAM_CLOSE, - AVDT_SCB_SND_CLOSE_RSP, - AVDT_SCB_SND_GETCONFIG_REQ, - AVDT_SCB_SND_GETCONFIG_RSP, - AVDT_SCB_SND_OPEN_REQ, - AVDT_SCB_SND_OPEN_RSP, - AVDT_SCB_SND_RECONFIG_REQ, - AVDT_SCB_SND_RECONFIG_RSP, - AVDT_SCB_SND_SECURITY_REQ, - AVDT_SCB_SND_SECURITY_RSP, - AVDT_SCB_SND_SETCONFIG_REQ, - AVDT_SCB_SND_SETCONFIG_REJ, - AVDT_SCB_SND_SETCONFIG_RSP, - AVDT_SCB_SND_TC_CLOSE, - AVDT_SCB_CB_ERR, - AVDT_SCB_CONG_STATE, - AVDT_SCB_REJ_STATE, - AVDT_SCB_REJ_IN_USE, - AVDT_SCB_REJ_NOT_IN_USE, - AVDT_SCB_SET_REMOVE, - AVDT_SCB_FREE_PKT, - AVDT_SCB_CLR_PKT, - AVDT_SCB_CHK_SND_PKT, - AVDT_SCB_TC_TIMER, - AVDT_SCB_CLR_VARS, - AVDT_SCB_DEALLOC, - AVDT_SCB_NUM_ACTIONS -}; - -#define AVDT_SCB_IGNORE AVDT_SCB_NUM_ACTIONS - -/* scb state machine events */ -enum { - AVDT_SCB_API_REMOVE_EVT, - AVDT_SCB_API_WRITE_REQ_EVT, - AVDT_SCB_API_GETCONFIG_REQ_EVT, - AVDT_SCB_API_DELAY_RPT_REQ_EVT, - AVDT_SCB_API_SETCONFIG_REQ_EVT, - AVDT_SCB_API_OPEN_REQ_EVT, - AVDT_SCB_API_CLOSE_REQ_EVT, - AVDT_SCB_API_RECONFIG_REQ_EVT, - AVDT_SCB_API_SECURITY_REQ_EVT, - AVDT_SCB_API_ABORT_REQ_EVT, - AVDT_SCB_API_GETCONFIG_RSP_EVT, - AVDT_SCB_API_SETCONFIG_RSP_EVT, - AVDT_SCB_API_SETCONFIG_REJ_EVT, - AVDT_SCB_API_OPEN_RSP_EVT, - AVDT_SCB_API_CLOSE_RSP_EVT, - AVDT_SCB_API_RECONFIG_RSP_EVT, - AVDT_SCB_API_SECURITY_RSP_EVT, - AVDT_SCB_API_ABORT_RSP_EVT, - AVDT_SCB_MSG_SETCONFIG_CMD_EVT, - AVDT_SCB_MSG_GETCONFIG_CMD_EVT, - AVDT_SCB_MSG_OPEN_CMD_EVT, - AVDT_SCB_MSG_START_CMD_EVT, - AVDT_SCB_MSG_SUSPEND_CMD_EVT, - AVDT_SCB_MSG_CLOSE_CMD_EVT, - AVDT_SCB_MSG_ABORT_CMD_EVT, - AVDT_SCB_MSG_RECONFIG_CMD_EVT, - AVDT_SCB_MSG_SECURITY_CMD_EVT, - AVDT_SCB_MSG_DELAY_RPT_CMD_EVT, - AVDT_SCB_MSG_DELAY_RPT_RSP_EVT, - AVDT_SCB_MSG_SETCONFIG_RSP_EVT, - AVDT_SCB_MSG_GETCONFIG_RSP_EVT, - AVDT_SCB_MSG_OPEN_RSP_EVT, - AVDT_SCB_MSG_START_RSP_EVT, - AVDT_SCB_MSG_SUSPEND_RSP_EVT, - AVDT_SCB_MSG_CLOSE_RSP_EVT, - AVDT_SCB_MSG_ABORT_RSP_EVT, - AVDT_SCB_MSG_RECONFIG_RSP_EVT, - AVDT_SCB_MSG_SECURITY_RSP_EVT, - AVDT_SCB_MSG_SETCONFIG_REJ_EVT, - AVDT_SCB_MSG_OPEN_REJ_EVT, - AVDT_SCB_MSG_START_REJ_EVT, - AVDT_SCB_MSG_SUSPEND_REJ_EVT, - AVDT_SCB_TC_TOUT_EVT, - AVDT_SCB_TC_OPEN_EVT, - AVDT_SCB_TC_CLOSE_EVT, - AVDT_SCB_TC_CONG_EVT, - AVDT_SCB_TC_DATA_EVT, - AVDT_SCB_CC_CLOSE_EVT -}; - -/* adaption layer number of stream routing table entries */ -#if AVDT_REPORTING == TRUE -/* 2 channels(1 media, 1 report) for each SEP and one for signalling */ -#define AVDT_NUM_RT_TBL ((AVDT_NUM_SEPS<<1) + 1) -#else -#define AVDT_NUM_RT_TBL (AVDT_NUM_SEPS + 1) -#endif - -/* adaption layer number of transport channel table entries - moved to target.h -#define AVDT_NUM_TC_TBL (AVDT_NUM_SEPS + AVDT_NUM_LINKS) */ - -/* "states" used in transport channel table */ -#define AVDT_AD_ST_UNUSED 0 /* Unused - unallocated */ -#define AVDT_AD_ST_IDLE 1 /* No connection */ -#define AVDT_AD_ST_ACP 2 /* Waiting to accept a connection */ -#define AVDT_AD_ST_INT 3 /* Initiating a connection */ -#define AVDT_AD_ST_CONN 4 /* Waiting for connection confirm */ -#define AVDT_AD_ST_CFG 5 /* Waiting for configuration complete */ -#define AVDT_AD_ST_OPEN 6 /* Channel opened */ -#define AVDT_AD_ST_SEC_INT 7 /* Security process as INT */ -#define AVDT_AD_ST_SEC_ACP 8 /* Security process as ACP */ - -/* Configuration flags. tAVDT_TC_TBL.cfg_flags */ -#define AVDT_L2C_CFG_IND_DONE (1<<0) -#define AVDT_L2C_CFG_CFM_DONE (1<<1) -#define AVDT_L2C_CFG_CONN_INT (1<<2) -#define AVDT_L2C_CFG_CONN_ACP (1<<3) - - -/* result code for avdt_ad_write_req() (L2CA_DataWrite()) */ -#define AVDT_AD_FAILED L2CAP_DW_FAILED /* FALSE */ -#define AVDT_AD_SUCCESS L2CAP_DW_SUCCESS /* TRUE */ -#define AVDT_AD_CONGESTED L2CAP_DW_CONGESTED /* 2 */ - -/***************************************************************************** -** data types -*****************************************************************************/ - -/* msg union of all message parameter types */ -typedef union { - tAVDT_EVT_HDR hdr; - tAVDT_EVT_HDR single; - tAVDT_SETCONFIG config_cmd; - tAVDT_CONFIG reconfig_cmd; - tAVDT_MULTI multi; - tAVDT_SECURITY security_cmd; - tAVDT_DISCOVER discover_rsp; - tAVDT_CONFIG svccap; - tAVDT_SECURITY security_rsp; - tAVDT_DELAY_RPT delay_rpt_cmd; -} tAVDT_MSG; - -/* data type for AVDT_CCB_API_DISCOVER_REQ_EVT */ -typedef struct { - tAVDT_CTRL_CBACK *p_cback; - tAVDT_SEP_INFO *p_sep_info; - UINT8 num_seps; -} tAVDT_CCB_API_DISCOVER; - -/* data type for AVDT_CCB_API_GETCAP_REQ_EVT */ -typedef struct { - tAVDT_EVT_HDR single; - tAVDT_CTRL_CBACK *p_cback; - tAVDT_CFG *p_cfg; -} tAVDT_CCB_API_GETCAP; - -/* data type for AVDT_CCB_API_CONNECT_REQ_EVT */ -typedef struct { - tAVDT_CTRL_CBACK *p_cback; - UINT8 sec_mask; -} tAVDT_CCB_API_CONNECT; - -/* data type for AVDT_CCB_API_DISCONNECT_REQ_EVT */ -typedef struct { - tAVDT_CTRL_CBACK *p_cback; -} tAVDT_CCB_API_DISCONNECT; - -/* union associated with ccb state machine events */ -typedef union { - tAVDT_CCB_API_DISCOVER discover; - tAVDT_CCB_API_GETCAP getcap; - tAVDT_CCB_API_CONNECT connect; - tAVDT_CCB_API_DISCONNECT disconnect; - tAVDT_MSG msg; - BOOLEAN llcong; - UINT8 err_code; -} tAVDT_CCB_EVT; - -/* channel control block type */ -typedef struct { - BD_ADDR peer_addr; /* BD address of peer */ - TIMER_LIST_ENT timer_entry; /* CCB timer list entry */ - fixed_queue_t *cmd_q; /* Queue for outgoing command messages */ - fixed_queue_t *rsp_q; /* Queue for outgoing response and reject messages */ - tAVDT_CTRL_CBACK *proc_cback; /* Procedure callback function */ - tAVDT_CTRL_CBACK *p_conn_cback; /* Connection/disconnection callback function */ - void *p_proc_data; /* Pointer to data storage for procedure */ - BT_HDR *p_curr_cmd; /* Current command being sent awaiting response */ - BT_HDR *p_curr_msg; /* Current message being sent */ - BT_HDR *p_rx_msg; /* Current message being received */ - BOOLEAN allocated; /* Whether ccb is allocated */ - UINT8 state; /* The CCB state machine state */ - BOOLEAN ll_opened; /* TRUE if LL is opened */ - BOOLEAN proc_busy; /* TRUE when a discover or get capabilities procedure in progress */ - UINT8 proc_param; /* Procedure parameter; either SEID for get capabilities or number of SEPS for discover */ - BOOLEAN cong; /* Whether signaling channel is congested */ - UINT8 label; /* Message header "label" (sequence number) */ - BOOLEAN reconn; /* If TRUE, reinitiate connection after transitioning from CLOSING to IDLE state */ - UINT8 ret_count; /* Command retransmission count */ - UINT8 disc_rsn; /* disconnection reason */ -} tAVDT_CCB; - -/* type for action functions */ -typedef void (*tAVDT_CCB_ACTION)(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); - -/* type for AVDT_SCB_API_WRITE_REQ_EVT */ -typedef struct { - BT_HDR *p_buf; - UINT32 time_stamp; -#if AVDT_MULTIPLEXING == TRUE - fixed_queue_t *frag_q; /* Queue for outgoing media fragments. p_buf should be 0 */ - UINT8 *p_data; - UINT32 data_len; -#endif - UINT8 m_pt; - tAVDT_DATA_OPT_MASK opt; -} tAVDT_SCB_APIWRITE; - -/* type for AVDT_SCB_TC_CLOSE_EVT */ -typedef struct { - UINT8 old_tc_state; /* channel state before closed */ - UINT8 tcid; /* TCID */ - UINT8 type; /* channel type */ - UINT8 disc_rsn; /* disconnection reason */ -} tAVDT_SCB_TC_CLOSE; - -/* type for scb event data */ -typedef union { - tAVDT_MSG msg; - tAVDT_SCB_APIWRITE apiwrite; - tAVDT_DELAY_RPT apidelay; - tAVDT_OPEN open; - tAVDT_SCB_TC_CLOSE close; - BOOLEAN llcong; - BT_HDR *p_pkt; -} tAVDT_SCB_EVT; - -/* stream control block type */ -typedef struct { - tAVDT_CS cs; /* stream creation struct */ - tAVDT_CFG curr_cfg; /* current configuration */ - tAVDT_CFG req_cfg; /* requested configuration */ - TIMER_LIST_ENT timer_entry; /* timer entry */ - BT_HDR *p_pkt; /* packet waiting to be sent */ - tAVDT_CCB *p_ccb; /* ccb associated with this scb */ - UINT16 media_seq; /* media packet sequence number */ - BOOLEAN allocated; /* whether scb is allocated or unused */ - BOOLEAN in_use; /* whether stream being used by peer */ - BOOLEAN sink_activated; /* A2DP Sink activated/de-activated from Application */ - UINT8 role; /* initiator/acceptor role in current procedure */ - BOOLEAN remove; /* whether CB is marked for removal */ - UINT8 state; /* state machine state */ - UINT8 peer_seid; /* SEID of peer stream */ - UINT8 curr_evt; /* current event; set only by state machine */ - BOOLEAN cong; /* Whether media transport channel is congested */ - UINT8 close_code; /* Error code received in close response */ -#if AVDT_MULTIPLEXING == TRUE - fixed_queue_t *frag_q; /* Queue for outgoing media fragments */ - UINT32 frag_off; /* length of already received media fragments */ - UINT32 frag_org_len; /* original length before fragmentation of receiving media packet */ - UINT8 *p_next_frag; /* next fragment to send */ - UINT8 *p_media_buf; /* buffer for media packet assigned by AVDT_SetMediaBuf */ - UINT32 media_buf_len; /* length of buffer for media packet assigned by AVDT_SetMediaBuf */ -#endif -} tAVDT_SCB; - -/* type for action functions */ -typedef void (*tAVDT_SCB_ACTION)(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); - -/* adaption layer type for transport channel table */ -typedef struct { - UINT16 peer_mtu; /* L2CAP mtu of the peer device */ - UINT16 my_mtu; /* Our MTU for this channel */ - UINT16 my_flush_to; /* Our flush timeout for this channel */ - UINT16 lcid; - UINT8 tcid; /* transport channel id */ - UINT8 ccb_idx; /* channel control block associated with this tc */ - UINT8 state; /* transport channel state */ - UINT8 cfg_flags; /* L2CAP configuration flags */ - UINT8 id; -} tAVDT_TC_TBL; - -/* adaption layer type for stream routing table */ -typedef struct { - UINT16 lcid; /* L2CAP LCID of the associated transport channel */ - UINT8 scb_hdl; /* stream control block associated with this tc */ -} tAVDT_RT_TBL; - - -/* adaption layer control block */ -typedef struct { - tAVDT_RT_TBL rt_tbl[AVDT_NUM_LINKS][AVDT_NUM_RT_TBL]; - tAVDT_TC_TBL tc_tbl[AVDT_NUM_TC_TBL]; - UINT8 lcid_tbl[MAX_L2CAP_CHANNELS]; /* map LCID to tc_tbl index */ -} tAVDT_AD; - -/* Control block for AVDT */ -typedef struct { - tAVDT_REG rcb; /* registration control block */ - tAVDT_CCB ccb[AVDT_NUM_LINKS]; /* channel control blocks */ - tAVDT_SCB scb[AVDT_NUM_SEPS]; /* stream control blocks */ - tAVDT_AD ad; /* adaption layer control block */ - tAVDTC_CTRL_CBACK *p_conf_cback; /* conformance callback function */ - tAVDT_CCB_ACTION *p_ccb_act; /* pointer to CCB action functions */ - tAVDT_SCB_ACTION *p_scb_act; /* pointer to SCB action functions */ - tAVDT_CTRL_CBACK *p_conn_cback; /* connection callback function */ - UINT8 trace_level; /* trace level */ -} tAVDT_CB; - - -/***************************************************************************** -** function declarations -*****************************************************************************/ - -/* CCB function declarations */ -extern void avdt_ccb_init(void); -extern void avdt_ccb_event(tAVDT_CCB *p_ccb, UINT8 event, tAVDT_CCB_EVT *p_data); -extern tAVDT_CCB *avdt_ccb_by_bd(BD_ADDR bd_addr); -extern tAVDT_CCB *avdt_ccb_alloc(BD_ADDR bd_addr); -extern void avdt_ccb_dealloc(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern UINT8 avdt_ccb_to_idx(tAVDT_CCB *p_ccb); -extern tAVDT_CCB *avdt_ccb_by_idx(UINT8 idx); - -/* CCB action functions */ -extern void avdt_ccb_chan_open(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_chan_close(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_chk_close(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_hdl_discover_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_hdl_discover_rsp(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_hdl_getcap_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_hdl_getcap_rsp(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_hdl_start_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_hdl_start_rsp(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_hdl_suspend_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_hdl_suspend_rsp(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_discover_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_discover_rsp(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_getcap_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_getcap_rsp(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_start_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_start_rsp(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_suspend_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_suspend_rsp(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_clear_cmds(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_cmd_fail(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_free_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_cong_state(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_ret_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_cmd(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_snd_msg(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_set_reconn(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_clr_reconn(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_chk_reconn(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_chk_timer(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_set_conn(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_set_disconn(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_do_disconn(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_ll_closed(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); -extern void avdt_ccb_ll_opened(tAVDT_CCB *p_ccb, tAVDT_CCB_EVT *p_data); - -/* SCB function prototypes */ -extern void avdt_scb_event(tAVDT_SCB *p_scb, UINT8 event, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_init(void); -extern tAVDT_SCB *avdt_scb_alloc(tAVDT_CS *p_cs); -extern void avdt_scb_dealloc(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern UINT8 avdt_scb_to_hdl(tAVDT_SCB *p_scb); -extern tAVDT_SCB *avdt_scb_by_hdl(UINT8 hdl); -extern UINT8 avdt_scb_verify(tAVDT_CCB *p_ccb, UINT8 state, UINT8 *p_seid, UINT16 num_seid, UINT8 *p_err_code); -extern void avdt_scb_peer_seid_list(tAVDT_MULTI *p_multi); -extern UINT32 avdt_scb_gen_ssrc(tAVDT_SCB *p_scb); - -/* SCB action functions */ -extern void avdt_scb_hdl_abort_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_abort_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_close_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_close_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_getconfig_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_getconfig_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_open_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_open_rej(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_open_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_pkt(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_drop_pkt(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_reconfig_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_reconfig_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_security_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_security_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_setconfig_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_setconfig_rej(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_setconfig_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_start_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_start_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_suspend_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_suspend_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_delay_rpt_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_delay_rpt_cmd(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_delay_rpt_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_tc_close(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_tc_open(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_tc_close_sto(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_tc_open_sto(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_hdl_write_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_abort_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_abort_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_close_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_stream_close(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_close_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_getconfig_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_getconfig_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_open_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_open_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_reconfig_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_reconfig_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_security_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_security_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_setconfig_req(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_setconfig_rej(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_setconfig_rsp(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_snd_tc_close(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_cb_err(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_cong_state(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_rej_state(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_rej_in_use(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_rej_not_in_use(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_set_remove(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_free_pkt(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_chk_snd_pkt(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_clr_pkt(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_tc_timer(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_clr_vars(tAVDT_SCB *p_scb, tAVDT_SCB_EVT *p_data); -extern void avdt_scb_queue_frags(tAVDT_SCB *p_scb, UINT8 **pp_data, UINT32 *p_data_len, fixed_queue_t *pq); - -/* msg function declarations */ -extern BOOLEAN avdt_msg_send(tAVDT_CCB *p_ccb, BT_HDR *p_msg); -extern void avdt_msg_send_cmd(tAVDT_CCB *p_ccb, void *p_scb, UINT8 sig_id, tAVDT_MSG *p_params); -extern void avdt_msg_send_rsp(tAVDT_CCB *p_ccb, UINT8 sig_id, tAVDT_MSG *p_params); -extern void avdt_msg_send_rej(tAVDT_CCB *p_ccb, UINT8 sig_id, tAVDT_MSG *p_params); -extern void avdt_msg_send_grej(tAVDT_CCB *p_ccb, UINT8 sig_id, tAVDT_MSG *p_params); -extern void avdt_msg_ind(tAVDT_CCB *p_ccb, BT_HDR *p_buf); - -/* adaption layer function declarations */ -extern void avdt_ad_init(void); -extern UINT8 avdt_ad_type_to_tcid(UINT8 type, tAVDT_SCB *p_scb); -extern tAVDT_TC_TBL *avdt_ad_tc_tbl_by_st(UINT8 type, tAVDT_CCB *p_ccb, UINT8 state); -extern tAVDT_TC_TBL *avdt_ad_tc_tbl_by_lcid(UINT16 lcid); -extern tAVDT_TC_TBL *avdt_ad_tc_tbl_alloc(tAVDT_CCB *p_ccb); -extern UINT8 avdt_ad_tc_tbl_to_idx(tAVDT_TC_TBL *p_tbl); -extern void avdt_ad_tc_close_ind(tAVDT_TC_TBL *p_tbl, UINT16 reason); -extern void avdt_ad_tc_open_ind(tAVDT_TC_TBL *p_tbl); -extern void avdt_ad_tc_cong_ind(tAVDT_TC_TBL *p_tbl, BOOLEAN is_congested); -extern void avdt_ad_tc_data_ind(tAVDT_TC_TBL *p_tbl, BT_HDR *p_buf); -extern tAVDT_TC_TBL *avdt_ad_tc_tbl_by_type(UINT8 type, tAVDT_CCB *p_ccb, tAVDT_SCB *p_scb); -extern UINT8 avdt_ad_write_req(UINT8 type, tAVDT_CCB *p_ccb, tAVDT_SCB *p_scb, BT_HDR *p_buf); -extern void avdt_ad_open_req(UINT8 type, tAVDT_CCB *p_ccb, tAVDT_SCB *p_scb, UINT8 role); -extern void avdt_ad_close_req(UINT8 type, tAVDT_CCB *p_ccb, tAVDT_SCB *p_scb); - -extern void avdt_process_timeout(TIMER_LIST_ENT *p_tle); - -/***************************************************************************** -** macros -*****************************************************************************/ - -/* we store the scb and the label in the layer_specific field of the -** current cmd -*/ -#define AVDT_BLD_LAYERSPEC(ls, msg, label) \ - ls = (((label) << 4) | (msg)) - -#define AVDT_LAYERSPEC_LABEL(ls) ((UINT8)((ls) >> 4)) - -#define AVDT_LAYERSPEC_MSG(ls) ((UINT8)((ls) & 0x000F)) - -/***************************************************************************** -** global data -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/****************************************************************************** -** Main Control Block -*******************************************************************************/ -#if AVDT_DYNAMIC_MEMORY == FALSE -extern tAVDT_CB avdt_cb; -#else -extern tAVDT_CB *avdt_cb_ptr; -#define avdt_cb (*avdt_cb_ptr) -#endif - - -/* L2CAP callback registration structure */ -extern const tL2CAP_APPL_INFO avdt_l2c_appl; - -/* reject message event lookup table */ -extern const UINT8 avdt_msg_rej_2_evt[]; -#ifdef __cplusplus -} -#endif - -#endif ///AVRC_INCLUDED == TRUE - -#endif /* AVDT_INT_H */ diff --git a/tools/sdk/include/bluedroid/avdtc_api.h b/tools/sdk/include/bluedroid/avdtc_api.h deleted file mode 100644 index 96b20e77bf9..00000000000 --- a/tools/sdk/include/bluedroid/avdtc_api.h +++ /dev/null @@ -1,230 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This interface file contains the interface AVDTP conformance API. These - * additional API functions and callback events are provided for - * conformance testing purposes only. They are not intended to be used by - * an application. - * - ******************************************************************************/ -#ifndef AVDT_CAPI_H -#define AVDT_CAPI_H - -#include "avdt_api.h" - -/* start AVDTC events here to distinguish from AVDT events */ -#define AVDTC_EVT_BEGIN 0x80 - -#define AVDTC_DISCOVER_IND_EVT (0 + AVDTC_EVT_BEGIN) /* Discover indication */ -#define AVDTC_GETCAP_IND_EVT (1 + AVDTC_EVT_BEGIN) /* Get capabilities indication */ -#define AVDTC_SETCONFIG_CFM_EVT (2 + AVDTC_EVT_BEGIN) /* Set configuration confirm */ -#define AVDTC_GETCONFIG_IND_EVT (3 + AVDTC_EVT_BEGIN) /* Get configuration indication */ -#define AVDTC_GETCONFIG_CFM_EVT (4 + AVDTC_EVT_BEGIN) /* Get configuration confirm */ -#define AVDTC_OPEN_IND_EVT (5 + AVDTC_EVT_BEGIN) /* Open indication */ -#define AVDTC_START_IND_EVT (6 + AVDTC_EVT_BEGIN) /* Start indication */ -#define AVDTC_CLOSE_IND_EVT (7 + AVDTC_EVT_BEGIN) /* Close indication */ -#define AVDTC_SUSPEND_IND_EVT (8 + AVDTC_EVT_BEGIN) /* Suspend indication */ -#define AVDTC_ABORT_IND_EVT (9 + AVDTC_EVT_BEGIN) /* Abort indication */ -#define AVDTC_ABORT_CFM_EVT (10 + AVDTC_EVT_BEGIN) /* Abort confirm */ - -typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ - UINT8 seid_list[AVDT_NUM_SEPS]; /* Array of SEID values */ - UINT8 num_seps; /* Number of values in array */ -} tAVDT_MULTI; - -/* Union of all control callback event data structures */ -typedef union { - tAVDT_EVT_HDR hdr; - tAVDT_CONFIG getconfig_cfm; - tAVDT_MULTI start_ind; - tAVDT_MULTI suspend_ind; -} tAVDTC_CTRL; - -typedef void tAVDTC_CTRL_CBACK(UINT8 handle, BD_ADDR bd_addr, UINT8 event, tAVDTC_CTRL *p_data); - -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function AVDTC_Init -** -** Description This function is called to begin using the conformance API. -** It must be called after AVDT_Register() and before any -** other API or conformance API functions are called. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_Init(tAVDTC_CTRL_CBACK *p_cback); - -/******************************************************************************* -** -** Function AVDTC_DiscoverRsp -** -** Description Send a discover response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_DiscoverRsp(BD_ADDR bd_addr, UINT8 label, - tAVDT_SEP_INFO sep_info[], UINT8 num_seps); - -/******************************************************************************* -** -** Function AVDTC_GetCapRsp -** -** Description Send a get capabilities response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_GetCapRsp(BD_ADDR bd_addr, UINT8 label, tAVDT_CFG *p_cap); - -/******************************************************************************* -** -** Function AVDTC_GetAllCapRsp -** -** Description Send a get all capabilities response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_GetAllCapRsp(BD_ADDR bd_addr, UINT8 label, tAVDT_CFG *p_cap); - -/******************************************************************************* -** -** Function AVDTC_GetConfigReq -** -** Description Send a get configuration request. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_GetConfigReq(UINT8 handle); - -/******************************************************************************* -** -** Function AVDTC_GetConfigRsp -** -** Description Send a get configuration response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_GetConfigRsp(UINT8 handle, UINT8 label, tAVDT_CFG *p_cfg); - -/******************************************************************************* -** -** Function AVDTC_OpenReq -** -** Description Send an open request. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_OpenReq(UINT8 handle); - -/******************************************************************************* -** -** Function AVDTC_OpenRsp -** -** Description Send an open response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_OpenRsp(UINT8 handle, UINT8 label); - -/******************************************************************************* -** -** Function AVDTC_StartRsp -** -** Description Send a start response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_StartRsp(UINT8 *p_handles, UINT8 num_handles, UINT8 label); - -/******************************************************************************* -** -** Function AVDTC_CloseRsp -** -** Description Send a close response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_CloseRsp(UINT8 handle, UINT8 label); - -/******************************************************************************* -** -** Function AVDTC_SuspendRsp -** -** Description Send a suspend response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_SuspendRsp(UINT8 *p_handles, UINT8 num_handles, UINT8 label); - -/******************************************************************************* -** -** Function AVDTC_AbortReq -** -** Description Send an abort request. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_AbortReq(UINT8 handle); - -/******************************************************************************* -** -** Function AVDTC_AbortRsp -** -** Description Send an abort response. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_AbortRsp(UINT8 handle, UINT8 label); - -/******************************************************************************* -** -** Function AVDTC_Rej -** -** Description Send a reject message. -** -** Returns void -** -*******************************************************************************/ -extern void AVDTC_Rej(UINT8 handle, BD_ADDR bd_addr, UINT8 cmd, UINT8 label, - UINT8 err_code, UINT8 err_param); - -#ifdef __cplusplus -} -#endif - -#endif /* AVDT_CAPI_H */ diff --git a/tools/sdk/include/bluedroid/avrc_api.h b/tools/sdk/include/bluedroid/avrc_api.h deleted file mode 100644 index 2634c97fb72..00000000000 --- a/tools/sdk/include/bluedroid/avrc_api.h +++ /dev/null @@ -1,653 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2006-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * nterface to AVRCP Application Programming Interface - * - ******************************************************************************/ -#ifndef AVRC_API_H -#define AVRC_API_H -#include "bt_target.h" -#include "avct_api.h" -#include "sdp_api.h" -#include "avrc_defs.h" -#if (AVRC_INCLUDED == TRUE) -/***************************************************************************** -** constants -*****************************************************************************/ - -/* API function return value result codes. */ -#define AVRC_SUCCESS AVCT_SUCCESS /* 0 Function successful */ -#define AVRC_NO_RESOURCES AVCT_NO_RESOURCES /* 1 Not enough resources */ -#define AVRC_BAD_HANDLE AVCT_BAD_HANDLE /* 2 Bad handle */ -#define AVRC_PID_IN_USE AVCT_PID_IN_USE /* 3 PID already in use */ -#define AVRC_NOT_OPEN AVCT_NOT_OPEN /* 4 Connection not open */ -#define AVRC_MSG_TOO_BIG 5 /* 5 the message length exceed the MTU of the browsing channel */ -#define AVRC_FAIL 0x10 /* 0x10 generic failure */ -#define AVRC_BAD_PARAM 0x11 /* 0x11 bad parameter */ - -/* Control role - same as AVCT_TARGET/AVCT_CONTROL */ -#define AVRC_CT_TARGET 1 /* target */ -#define AVRC_CT_CONTROL 2 /* controller */ -#define AVRC_CT_PASSIVE 4 /* If conflict, allow the other side to succeed */ - -/* Connection role */ -#define AVRC_CONN_INT AVCT_INT /* initiator */ -#define AVRC_CONN_ACP AVCT_ACP /* Acceptor */ - - -/* AVRC CTRL events */ -/* AVRC_OPEN_IND_EVT event is sent when the connection is successfully opened. - * This eventis sent in response to an AVRC_Open(). */ -#define AVRC_OPEN_IND_EVT 0 - -/* AVRC_CLOSE_IND_EVT event is sent when a connection is closed. - * This event can result from a call to AVRC_Close() or when the peer closes - * the connection. It is also sent when a connection attempted through - * AVRC_Open() fails. */ -#define AVRC_CLOSE_IND_EVT 1 - -/* AVRC_CONG_IND_EVT event indicates that AVCTP is congested and cannot send - * any more messages. */ -#define AVRC_CONG_IND_EVT 2 - -/* AVRC_UNCONG_IND_EVT event indicates that AVCTP is uncongested and ready to - * send messages. */ -#define AVRC_UNCONG_IND_EVT 3 - -/* AVRC_BROWSE_OPEN_IND_EVT event is sent when the browse channel is successfully opened. -* This eventis sent in response to an AVRC_Open() or AVRC_OpenBrowse() . */ -#define AVRC_BROWSE_OPEN_IND_EVT 4 - -/* AVRC_BROWSE_CLOSE_IND_EVT event is sent when a browse channel is closed. - * This event can result from a call to AVRC_Close(), AVRC_CloseBrowse() or when the peer closes - * the connection. It is also sent when a connection attempted through - * AVRC_OpenBrowse() fails. */ -#define AVRC_BROWSE_CLOSE_IND_EVT 5 - -/* AVRC_BROWSE_CONG_IND_EVT event indicates that AVCTP browse channel is congested and cannot send - * any more messages. */ -#define AVRC_BROWSE_CONG_IND_EVT 6 - -/* AVRC_BROWSE_UNCONG_IND_EVT event indicates that AVCTP browse channel is uncongested and ready to - * send messages. */ -#define AVRC_BROWSE_UNCONG_IND_EVT 7 - -/* AVRC_CMD_TIMEOUT_EVT event indicates timeout waiting for AVRC command response from the peer */ -#define AVRC_CMD_TIMEOUT_EVT 8 - -/* Supported categories */ -#define AVRC_SUPF_CT_CAT1 0x0001 /* Category 1 */ -#define AVRC_SUPF_CT_CAT2 0x0002 /* Category 2 */ -#define AVRC_SUPF_CT_CAT3 0x0004 /* Category 3 */ -#define AVRC_SUPF_CT_CAT4 0x0008 /* Category 4 */ -#define AVRC_SUPF_CT_BROWSE 0x0040 /* Browsing */ - -#define AVRC_SUPF_TG_CAT1 0x0001 /* Category 1 */ -#define AVRC_SUPF_TG_CAT2 0x0002 /* Category 2 */ -#define AVRC_SUPF_TG_CAT3 0x0004 /* Category 3 */ -#define AVRC_SUPF_TG_CAT4 0x0008 /* Category 4 */ -#define AVRC_SUPF_TG_APP_SETTINGS 0x0010 /* Player Application Settings */ -#define AVRC_SUPF_TG_GROUP_NAVI 0x0020 /* Group Navigation */ -#define AVRC_SUPF_TG_BROWSE 0x0040 /* Browsing */ -#define AVRC_SUPF_TG_MULTI_PLAYER 0x0080 /* Muliple Media Player */ - -#define AVRC_META_SUCCESS AVRC_SUCCESS -#define AVRC_META_FAIL AVRC_FAIL -#define AVRC_METADATA_CMD 0x0000 -#define AVRC_METADATA_RESP 0x0001 - - - -/***************************************************************************** -** data type definitions -*****************************************************************************/ - -/* This data type is used in AVRC_FindService() to initialize the SDP database - * to hold the result service search. */ -typedef struct { - UINT32 db_len; /* Length, in bytes, of the discovery database */ - tSDP_DISCOVERY_DB *p_db; /* Pointer to the discovery database */ - UINT16 num_attr;/* The number of attributes in p_attrs */ - UINT16 *p_attrs; /* The attributes filter. If NULL, AVRCP API sets the attribute filter - * to be ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_BT_PROFILE_DESC_LIST, - * ATTR_ID_SUPPORTED_FEATURES, ATTR_ID_SERVICE_NAME and ATTR_ID_PROVIDER_NAME. - * If not NULL, the input is taken as the filter. */ -} tAVRC_SDP_DB_PARAMS; - -/* This callback function returns service discovery information to the - * application after the AVRC_FindService() API function is called. The - * implementation of this callback function must copy the p_service_name - * and p_provider_name parameters passed to it as they are not guaranteed - * to remain after the callback function exits. */ -typedef void (tAVRC_FIND_CBACK) (UINT16 status); - - -/* This is the control callback function. This function passes events - * listed in Table 20 to the application. */ -typedef void (tAVRC_CTRL_CBACK) (UINT8 handle, UINT8 event, UINT16 result, - BD_ADDR peer_addr); - - -/* This is the message callback function. It is executed when AVCTP has - * a message packet ready for the application. The implementation of this - * callback function must copy the tAVRC_MSG structure passed to it as it - * is not guaranteed to remain after the callback function exits. */ -typedef void (tAVRC_MSG_CBACK) (UINT8 handle, UINT8 label, UINT8 opcode, - tAVRC_MSG *p_msg); - -typedef struct { - tAVRC_CTRL_CBACK *p_ctrl_cback; /* pointer to application control callback */ - tAVRC_MSG_CBACK *p_msg_cback; /* pointer to application message callback */ - UINT32 company_id; /* the company ID */ - UINT8 conn; /* Connection role (Initiator/acceptor) */ - UINT8 control; /* Control role (Control/Target) */ -} tAVRC_CONN_CB; - - - -/***************************************************************************** -** external function declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/****************************************************************************** -** -** Function AVRC_AddRecord -** -** Description This function is called to build an AVRCP SDP record. -** Prior to calling this function the application must -** call SDP_CreateRecord() to create an SDP record. -** -** Input Parameters: -** service_uuid: Indicates TG(UUID_SERVCLASS_AV_REM_CTRL_TARGET) -** or CT(UUID_SERVCLASS_AV_REMOTE_CONTROL) -** -** p_service_name: Pointer to a null-terminated character -** string containing the service name. -** If service name is not used set this to NULL. -** -** p_provider_name: Pointer to a null-terminated character -** string containing the provider name. -** If provider name is not used set this to NULL. -** -** categories: Supported categories. -** -** sdp_handle: SDP handle returned by SDP_CreateRecord(). -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_NO_RESOURCES if not enough resources to build the SDP record. -** -******************************************************************************/ -extern UINT16 AVRC_AddRecord(UINT16 service_uuid, char *p_service_name, - char *p_provider_name, UINT16 categories, UINT32 sdp_handle); - -/****************************************************************************** -** -** Function AVRC_FindService -** -** Description This function is called by the application to perform service -** discovery and retrieve AVRCP SDP record information from a -** peer device. Information is returned for the first service -** record found on the server that matches the service UUID. -** The callback function will be executed when service discovery -** is complete. There can only be one outstanding call to -** AVRC_FindService() at a time; the application must wait for -** the callback before it makes another call to the function. -** The application is responsible for allocating memory for the -** discovery database. It is recommended that the size of the -** discovery database be at least 300 bytes. The application -** can deallocate the memory after the callback function has -** executed. -** -** Input Parameters: -** service_uuid: Indicates TG(UUID_SERVCLASS_AV_REM_CTRL_TARGET) -** or CT(UUID_SERVCLASS_AV_REMOTE_CONTROL) -** -** bd_addr: BD address of the peer device. -** -** p_db: SDP discovery database parameters. -** -** p_cback: Pointer to the callback function. -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_PARAMS if discovery database parameters are invalid. -** AVRC_NO_RESOURCES if there are not enough resources to -** perform the service search. -** -******************************************************************************/ -extern UINT16 AVRC_FindService(UINT16 service_uuid, BD_ADDR bd_addr, - tAVRC_SDP_DB_PARAMS *p_db, tAVRC_FIND_CBACK *p_cback); - -/****************************************************************************** -** -** Function AVRC_Open -** -** Description This function is called to open a connection to AVCTP. -** The connection can be either an initiator or acceptor, as -** determined by the p_ccb->stream parameter. -** The connection can be a target, a controller or for both role, -** as determined by the p_ccb->control parameter. -** By definition, a target connection is an acceptor connection -** that waits for an incoming AVCTP connection from the peer. -** The connection remains available to the application until -** the application closes it by calling AVRC_Close(). The -** application does not need to reopen the connection after an -** AVRC_CLOSE_IND_EVT is received. -** -** Input Parameters: -** p_ccb->company_id: Company Identifier. -** -** p_ccb->p_ctrl_cback: Pointer to control callback function. -** -** p_ccb->p_msg_cback: Pointer to message callback function. -** -** p_ccb->conn: AVCTP connection role. This is set to -** AVCTP_INT for initiator connections and AVCTP_ACP -** for acceptor connections. -** -** p_ccb->control: Control role. This is set to -** AVRC_CT_TARGET for target connections, AVRC_CT_CONTROL -** for control connections or (AVRC_CT_TARGET|AVRC_CT_CONTROL) -** for connections that support both roles. -** -** peer_addr: BD address of peer device. This value is -** only used for initiator connections; for acceptor -** connections it can be set to NULL. -** -** Output Parameters: -** p_handle: Pointer to handle. This parameter is only -** valid if AVRC_SUCCESS is returned. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_NO_RESOURCES if there are not enough resources to open -** the connection. -** -******************************************************************************/ -extern UINT16 AVRC_Open(UINT8 *p_handle, tAVRC_CONN_CB *p_ccb, - BD_ADDR_PTR peer_addr); - -/****************************************************************************** -** -** Function AVRC_Close -** -** Description Close a connection opened with AVRC_Open(). -** This function is called when the -** application is no longer using a connection. -** -** Input Parameters: -** handle: Handle of this connection. -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_Close(UINT8 handle); - -/****************************************************************************** -** -** Function AVRC_OpenBrowse -** -** Description This function is called to open a browsing connection to AVCTP. -** The connection can be either an initiator or acceptor, as -** determined by the conn_role. -** The handle is returned by a previous call to AVRC_Open. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_NO_RESOURCES if there are not enough resources to open -** the connection. -** -******************************************************************************/ -extern UINT16 AVRC_OpenBrowse(UINT8 handle, UINT8 conn_role); - -/****************************************************************************** -** -** Function AVRC_CloseBrowse -** -** Description Close a connection opened with AVRC_OpenBrowse(). -** This function is called when the -** application is no longer using a connection. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_CloseBrowse(UINT8 handle); - -/****************************************************************************** -** -** Function AVRC_MsgReq -** -** Description This function is used to send the AVRCP byte stream in p_pkt -** down to AVCTP. -** -** It is expected that p_pkt->offset is at least AVCT_MSG_OFFSET -** p_pkt->layer_specific is AVCT_DATA_CTRL or AVCT_DATA_BROWSE -** p_pkt->event is AVRC_OP_VENDOR, AVRC_OP_PASS_THRU or AVRC_OP_BROWSING -** The above BT_HDR settings are set by the AVRC_Bld* functions. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_MsgReq (UINT8 handle, UINT8 label, UINT8 ctype, BT_HDR *p_pkt); - -/****************************************************************************** -** -** Function AVRC_UnitCmd -** -** Description Send a UNIT INFO command to the peer device. This -** function can only be called for controller role connections. -** Any response message from the peer is passed back through -** the tAVRC_MSG_CBACK callback function. -** -** Input Parameters: -** handle: Handle of this connection. -** -** label: Transaction label. -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_UnitCmd(UINT8 handle, UINT8 label); - -/****************************************************************************** -** -** Function AVRC_SubCmd -** -** Description Send a SUBUNIT INFO command to the peer device. This -** function can only be called for controller role connections. -** Any response message from the peer is passed back through -** the tAVRC_MSG_CBACK callback function. -** -** Input Parameters: -** handle: Handle of this connection. -** -** label: Transaction label. -** -** page: Specifies which part of the subunit type table -** is requested. For AVRCP it is typically zero. -** Value range is 0-7. -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_SubCmd(UINT8 handle, UINT8 label, UINT8 page); - - -/****************************************************************************** -** -** Function AVRC_PassCmd -** -** Description Send a PASS THROUGH command to the peer device. This -** function can only be called for controller role connections. -** Any response message from the peer is passed back through -** the tAVRC_MSG_CBACK callback function. -** -** Input Parameters: -** handle: Handle of this connection. -** -** label: Transaction label. -** -** p_msg: Pointer to PASS THROUGH message structure. -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_PassCmd(UINT8 handle, UINT8 label, tAVRC_MSG_PASS *p_msg); - -/****************************************************************************** -** -** Function AVRC_PassRsp -** -** Description Send a PASS THROUGH response to the peer device. This -** function can only be called for target role connections. -** This function must be called when a PASS THROUGH command -** message is received from the peer through the -** tAVRC_MSG_CBACK callback function. -** -** Input Parameters: -** handle: Handle of this connection. -** -** label: Transaction label. Must be the same value as -** passed with the command message in the callback function. -** -** p_msg: Pointer to PASS THROUGH message structure. -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_PassRsp(UINT8 handle, UINT8 label, tAVRC_MSG_PASS *p_msg); - - -/****************************************************************************** -** -** Function AVRC_VendorCmd -** -** Description Send a VENDOR DEPENDENT command to the peer device. This -** function can only be called for controller role connections. -** Any response message from the peer is passed back through -** the tAVRC_MSG_CBACK callback function. -** -** Input Parameters: -** handle: Handle of this connection. -** -** label: Transaction label. -** -** p_msg: Pointer to VENDOR DEPENDENT message structure. -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_VendorCmd(UINT8 handle, UINT8 label, tAVRC_MSG_VENDOR *p_msg); - - -/****************************************************************************** -** -** Function AVRC_VendorRsp -** -** Description Send a VENDOR DEPENDENT response to the peer device. This -** function can only be called for target role connections. -** This function must be called when a VENDOR DEPENDENT -** command message is received from the peer through the -** tAVRC_MSG_CBACK callback function. -** -** Input Parameters: -** handle: Handle of this connection. -** -** label: Transaction label. Must be the same value as -** passed with the command message in the callback function. -** -** p_msg: Pointer to VENDOR DEPENDENT message structure. -** -** Output Parameters: -** None. -** -** Returns AVRC_SUCCESS if successful. -** AVRC_BAD_HANDLE if handle is invalid. -** -******************************************************************************/ -extern UINT16 AVRC_VendorRsp(UINT8 handle, UINT8 label, tAVRC_MSG_VENDOR *p_msg); - - -/****************************************************************************** -** -** Function AVRC_SetTraceLevel -** -** Description Sets the trace level for AVRC. If 0xff is passed, the -** current trace level is returned. -** -** Input Parameters: -** new_level: The level to set the AVRC tracing to: -** 0xff-returns the current setting. -** 0-turns off tracing. -** >= 1-Errors. -** >= 2-Warnings. -** >= 3-APIs. -** >= 4-Events. -** >= 5-Debug. -** -** Returns The new trace level or current trace level if -** the input parameter is 0xff. -** -******************************************************************************/ -extern UINT8 AVRC_SetTraceLevel (UINT8 new_level); - -/******************************************************************************* -** -** Function AVRC_Init -** -** Description This function is called at stack startup to allocate the -** control block (if using dynamic memory), and initializes the -** control block and tracing level. -** -** Returns void -** -*******************************************************************************/ -extern void AVRC_Init(void); - -/******************************************************************************* -** -** Function AVRC_Deinit -** -** Description This function is called at stack shotdown to free the -** control block (if using dynamic memory), and deinitializes the -** control block and tracing level. -** -** Returns void -** -*******************************************************************************/ -extern void AVRC_Deinit(void); - -/******************************************************************************* -** -** Function AVRC_ParsCommand -** -** Description This function is used to parse the received command. -** -** Returns AVRC_STS_NO_ERROR, if the message in p_data is parsed successfully. -** Otherwise, the error code defined by AVRCP 1.4 -** -*******************************************************************************/ -extern tAVRC_STS AVRC_ParsCommand (tAVRC_MSG *p_msg, tAVRC_COMMAND *p_result, - UINT8 *p_buf, UINT16 buf_len); - -/******************************************************************************* -** -** Function AVRC_ParsResponse -** -** Description This function is used to parse the received response. -** -** Returns AVRC_STS_NO_ERROR, if the message in p_data is parsed successfully. -** Otherwise, the error code defined by AVRCP 1.4 -** -*******************************************************************************/ -extern tAVRC_STS AVRC_ParsResponse (tAVRC_MSG *p_msg, tAVRC_RESPONSE *p_result, - UINT8 *p_buf, UINT16 buf_len); - -/******************************************************************************* -** -** Function AVRC_BldCommand -** -** Description This function builds the given AVRCP command to the given -** GKI buffer -** -** Returns AVRC_STS_NO_ERROR, if the command is built successfully -** Otherwise, the error code. -** -*******************************************************************************/ -extern tAVRC_STS AVRC_BldCommand( tAVRC_COMMAND *p_cmd, BT_HDR **pp_pkt); - -/******************************************************************************* -** -** Function AVRC_BldResponse -** -** Description This function builds the given AVRCP response to the given -** GKI buffer -** -** Returns AVRC_STS_NO_ERROR, if the response is built successfully -** Otherwise, the error code. -** -*******************************************************************************/ -extern tAVRC_STS AVRC_BldResponse( UINT8 handle, tAVRC_RESPONSE *p_rsp, BT_HDR **pp_pkt); - -/************************************************************************** -** -** Function AVRC_IsValidAvcType -** -** Description Check if correct AVC type is specified -** -** Returns returns TRUE if it is valid -** -** -*******************************************************************************/ -extern BOOLEAN AVRC_IsValidAvcType(UINT8 pdu_id, UINT8 avc_type); - -/******************************************************************************* -** -** Function AVRC_IsValidPlayerAttr -** -** Description Check if the given attrib value is a valid one -** -** -** Returns returns TRUE if it is valid -** -*******************************************************************************/ -extern BOOLEAN AVRC_IsValidPlayerAttr(UINT8 attr); - -#ifdef __cplusplus -} -#endif - -#endif ///AVRC_INCLUDED == TRUE - - -#endif /* AVRC_API_H */ diff --git a/tools/sdk/include/bluedroid/avrc_defs.h b/tools/sdk/include/bluedroid/avrc_defs.h deleted file mode 100644 index 8a6254ef858..00000000000 --- a/tools/sdk/include/bluedroid/avrc_defs.h +++ /dev/null @@ -1,1362 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2006-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * AVRCP definition and data types - * - ******************************************************************************/ -#ifndef _AVRC_DEFS_H -#define _AVRC_DEFS_H -#include "bt_target.h" - -#if (AVRC_INCLUDED == TRUE) -/***************************************************************************** -** constants -*****************************************************************************/ - -/* Profile revision numbers */ -#define AVRC_REV_1_0 0x0100 -#define AVRC_REV_1_3 0x0103 -#define AVRC_REV_1_4 0x0104 - -#define AVRC_PACKET_LEN 512 /* Per the spec, you must support 512 byte RC packets */ - -#define AVRC_MIN_CONTROL_MTU 48 /* Per the spec, minimum MTU for the control channel */ -#define AVRC_MIN_BROWSE_MTU 335 /* Per the spec, minimum MTU for the browsing channel */ - -#define AVRC_META_PDU_OFFSET 4 -#define AVRC_SUB_TYPE_LEN 4 -#define AVRC_UID_SIZE 8 -#define AVRC_FEATURE_MASK_SIZE 16 - -/* command type codes */ -#define AVRC_CMD_CTRL 0 /* Instruct a target to perform an operation */ -#define AVRC_CMD_STATUS 1 /* Check a device�s current status */ -#define AVRC_CMD_SPEC_INQ 2 /* Check whether a target supports a particular - control command; all operands are included */ -#define AVRC_CMD_NOTIF 3 /* Used for receiving notification of a change in a device�s state */ -#define AVRC_CMD_GEN_INQ 4 /* Check whether a target supports a particular - control command; operands are not included */ - -/* response type codes */ -#define AVRC_RSP_NOT_IMPL 8 /* The target does not implement the command specified - by the opcode and operand, - or doesn�t implement the specified subunit */ -#define AVRC_RSP_ACCEPT 9 /* The target executed or is executing the command */ -#define AVRC_RSP_REJ 10 /* The target implements the command specified by the - opcode but cannot respond because the current state - of the target doesn�t allow it */ -#define AVRC_RSP_IN_TRANS 11 /* The target implements the status command but it is - in a state of transition; the status command may - be retried at a future time */ -#define AVRC_RSP_IMPL_STBL 12 /* For specific inquiry or general inquiy commands, - the target implements the command; for status - commands, the target returns stable and includes - the status results */ -#define AVRC_RSP_CHANGED 13 /* The response frame contains a notification that the - target device�s state has changed */ -#define AVRC_RSP_INTERIM 15 /* For control commands, the target has accepted the - request but cannot return information within 100 - milliseconds; for notify commands, the target accepted - the command, and will notify the controller of a change - of target state at a future time */ - -/* subunit type */ -#define AVRC_SUB_MONITOR 0x00 /* Monitor */ -#define AVRC_SUB_AUDIO 0x01 /* Audio */ -#define AVRC_SUB_PRINTER 0x02 /* Printer */ -#define AVRC_SUB_DISC 0x03 /* Disc */ -#define AVRC_SUB_TAPE 0x04 /* Tape recorder/player */ -#define AVRC_SUB_TUNER 0x05 /* Tuner */ -#define AVRC_SUB_CA 0x06 /* CA */ -#define AVRC_SUB_CAMERA 0x07 /* Camera */ -#define AVRC_SUB_PANEL 0x09 /* Panel */ -#define AVRC_SUB_BB 0x0A /* Bulletin Board */ -#define AVRC_SUB_CAM_STOR 0x0B /* Camera Storage */ -#define AVRC_SUB_VENDOR 0x1C /* Vendor unique */ -#define AVRC_SUB_EXT 0x1E /* Subunit type extended to next byte */ -#define AVRC_SUB_UNIT 0x1F /* Unit */ - -/* opcodes - defined by 1394ta */ -#define AVRC_OP_UNIT_INFO 0x30 /* Report unit information */ -#define AVRC_OP_SUB_INFO 0x31 /* Report subunit information */ -#define AVRC_OP_VENDOR 0x00 /* Vendor-dependent commands */ -#define AVRC_OP_PASS_THRU 0x7C /* panel subunit opcode */ -/* opcodes 80-9F and E0-FF are not used by 1394ta.Sneak one for the browsing channel */ -#define AVRC_OP_BROWSE 0xFF /* Browsing */ -#define AVRC_OP_INVALID 0xFE /* invalid one */ - -/* Company ID's -*/ -#define AVRC_CO_BLUETOOTH_SIG 0x00FFFFFF -#define AVRC_CO_WIDCOMM 0x00000361 -#define AVRC_CO_BROADCOM 0x00001018 -#define AVRC_CO_METADATA 0x00001958 /* Unique COMPANY ID for Metadata messages */ - -/* State flag for Passthrough commands -*/ -#define AVRC_STATE_PRESS 0 -#define AVRC_STATE_RELEASE 1 - -/* Operation ID list for Passthrough commands -*/ -#define AVRC_ID_SELECT 0x00 /* select */ -#define AVRC_ID_UP 0x01 /* up */ -#define AVRC_ID_DOWN 0x02 /* down */ -#define AVRC_ID_LEFT 0x03 /* left */ -#define AVRC_ID_RIGHT 0x04 /* right */ -#define AVRC_ID_RIGHT_UP 0x05 /* right-up */ -#define AVRC_ID_RIGHT_DOWN 0x06 /* right-down */ -#define AVRC_ID_LEFT_UP 0x07 /* left-up */ -#define AVRC_ID_LEFT_DOWN 0x08 /* left-down */ -#define AVRC_ID_ROOT_MENU 0x09 /* root menu */ -#define AVRC_ID_SETUP_MENU 0x0A /* setup menu */ -#define AVRC_ID_CONT_MENU 0x0B /* contents menu */ -#define AVRC_ID_FAV_MENU 0x0C /* favorite menu */ -#define AVRC_ID_EXIT 0x0D /* exit */ -#define AVRC_ID_0 0x20 /* 0 */ -#define AVRC_ID_1 0x21 /* 1 */ -#define AVRC_ID_2 0x22 /* 2 */ -#define AVRC_ID_3 0x23 /* 3 */ -#define AVRC_ID_4 0x24 /* 4 */ -#define AVRC_ID_5 0x25 /* 5 */ -#define AVRC_ID_6 0x26 /* 6 */ -#define AVRC_ID_7 0x27 /* 7 */ -#define AVRC_ID_8 0x28 /* 8 */ -#define AVRC_ID_9 0x29 /* 9 */ -#define AVRC_ID_DOT 0x2A /* dot */ -#define AVRC_ID_ENTER 0x2B /* enter */ -#define AVRC_ID_CLEAR 0x2C /* clear */ -#define AVRC_ID_CHAN_UP 0x30 /* channel up */ -#define AVRC_ID_CHAN_DOWN 0x31 /* channel down */ -#define AVRC_ID_PREV_CHAN 0x32 /* previous channel */ -#define AVRC_ID_SOUND_SEL 0x33 /* sound select */ -#define AVRC_ID_INPUT_SEL 0x34 /* input select */ -#define AVRC_ID_DISP_INFO 0x35 /* display information */ -#define AVRC_ID_HELP 0x36 /* help */ -#define AVRC_ID_PAGE_UP 0x37 /* page up */ -#define AVRC_ID_PAGE_DOWN 0x38 /* page down */ -#define AVRC_ID_POWER 0x40 /* power */ -#define AVRC_ID_VOL_UP 0x41 /* volume up */ -#define AVRC_ID_VOL_DOWN 0x42 /* volume down */ -#define AVRC_ID_MUTE 0x43 /* mute */ -#define AVRC_ID_PLAY 0x44 /* play */ -#define AVRC_ID_STOP 0x45 /* stop */ -#define AVRC_ID_PAUSE 0x46 /* pause */ -#define AVRC_ID_RECORD 0x47 /* record */ -#define AVRC_ID_REWIND 0x48 /* rewind */ -#define AVRC_ID_FAST_FOR 0x49 /* fast forward */ -#define AVRC_ID_EJECT 0x4A /* eject */ -#define AVRC_ID_FORWARD 0x4B /* forward */ -#define AVRC_ID_BACKWARD 0x4C /* backward */ -#define AVRC_ID_ANGLE 0x50 /* angle */ -#define AVRC_ID_SUBPICT 0x51 /* subpicture */ -#define AVRC_ID_F1 0x71 /* F1 */ -#define AVRC_ID_F2 0x72 /* F2 */ -#define AVRC_ID_F3 0x73 /* F3 */ -#define AVRC_ID_F4 0x74 /* F4 */ -#define AVRC_ID_F5 0x75 /* F5 */ -#define AVRC_ID_VENDOR 0x7E /* vendor unique */ -#define AVRC_KEYPRESSED_RELEASE 0x80 - -/***************************************************************************** -** Metadata transfer definitions -*****************************************************************************/ - -/* Define the Metadata Packet types -*/ -#define AVRC_PKT_SINGLE 0 -#define AVRC_PKT_START 1 -#define AVRC_PKT_CONTINUE 2 -#define AVRC_PKT_END 3 -#define AVRC_PKT_TYPE_MASK 3 - -/* Define the PDUs carried in the vendor dependant data -*/ -#define AVRC_PDU_GET_CAPABILITIES 0x10 -#define AVRC_PDU_LIST_PLAYER_APP_ATTR 0x11 -#define AVRC_PDU_LIST_PLAYER_APP_VALUES 0x12 -#define AVRC_PDU_GET_CUR_PLAYER_APP_VALUE 0x13 -#define AVRC_PDU_SET_PLAYER_APP_VALUE 0x14 -#define AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT 0x15 -#define AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT 0x16 -#define AVRC_PDU_INFORM_DISPLAY_CHARSET 0x17 -#define AVRC_PDU_INFORM_BATTERY_STAT_OF_CT 0x18 -#define AVRC_PDU_GET_ELEMENT_ATTR 0x20 -#define AVRC_PDU_GET_PLAY_STATUS 0x30 -#define AVRC_PDU_REGISTER_NOTIFICATION 0x31 -#define AVRC_PDU_REQUEST_CONTINUATION_RSP 0x40 -#define AVRC_PDU_ABORT_CONTINUATION_RSP 0x41 -/* added in 1.4 */ -#define AVRC_PDU_SET_ABSOLUTE_VOLUME 0x50 -#define AVRC_PDU_SET_ADDRESSED_PLAYER 0x60 -#define AVRC_PDU_SET_BROWSED_PLAYER 0x70 -#define AVRC_PDU_GET_FOLDER_ITEMS 0x71 -#define AVRC_PDU_CHANGE_PATH 0x72 -#define AVRC_PDU_GET_ITEM_ATTRIBUTES 0x73 -#define AVRC_PDU_PLAY_ITEM 0x74 -#define AVRC_PDU_SEARCH 0x80 -#define AVRC_PDU_ADD_TO_NOW_PLAYING 0x90 -#define AVRC_PDU_GENERAL_REJECT 0xA0 - -/* Define the vendor unique id carried in the pass through data -*/ -#define AVRC_PDU_NEXT_GROUP 0x00 -#define AVRC_PDU_PREV_GROUP 0x01 -/* the only pass through vendor unique commands defined by AVRC is the group navigation commands - * The len for vendor unique data is 5 */ -#define AVRC_PASS_THRU_GROUP_LEN 5 - -#define AVRC_PDU_INVALID 0xff -/* 6.15.3 error status code for general reject */ -#define AVRC_STS_BAD_CMD 0x00 /* Invalid command, sent if TG received a PDU that it did not understand. */ -#define AVRC_STS_BAD_PARAM 0x01 /* Invalid parameter, sent if the TG received a PDU with a parameter ID that it did not understand. Sent if there is only one parameter ID in the PDU. */ -#define AVRC_STS_NOT_FOUND 0x02 /* Specified parameter not found., sent if the parameter ID is understood, but content is wrong or corrupted. */ -#define AVRC_STS_INTERNAL_ERR 0x03 /* Internal Error, sent if there are error conditions not covered by a more specific error code. */ -#define AVRC_STS_NO_ERROR 0x04 /* Operation completed without error. This is the status that should be returned if the operation was successful. */ -#define AVRC_STS_UID_CHANGED 0x05 /* UID Changed - The UIDs on the device have changed */ -/* #define AVRC_STS_GEN_ERROR 0x06 Unknown Error - this is changed to "reserved" */ -#define AVRC_STS_BAD_DIR 0x07 /* Invalid Direction - The Direction parameter is invalid - Change Path*/ -#define AVRC_STS_NOT_DIR 0x08 /* Not a Directory - The UID provided does not refer to a folder item Change Path*/ -#define AVRC_STS_NOT_EXIST 0x09 /* Does Not Exist - The UID provided does not refer to any item Change Path, PlayItem, AddToNowPlaying, GetItemAttributes*/ -#define AVRC_STS_BAD_SCOPE 0x0a /* Invalid Scope - The scope parameter is invalid GetFolderItems, PlayItem, AddToNowPlayer, GetItemAttributes, */ -#define AVRC_STS_BAD_RANGE 0x0b /* Range Out of Bounds - The start of range provided is not valid GetFolderItems*/ -#define AVRC_STS_UID_IS_DIR 0x0c /* UID is a Directory - The UID provided refers to a directory, which cannot be handled by this media player PlayItem, AddToNowPlaying */ -#define AVRC_STS_IN_USE 0x0d /* Media in Use - The media is not able to be used for this operation at this time PlayItem, AddToNowPlaying */ -#define AVRC_STS_NOW_LIST_FULL 0x0e /* Now Playing List Full - No more items can be added to the Now Playing List AddToNowPlaying*/ -#define AVRC_STS_SEARCH_NOT_SUP 0x0f /* Search Not Supported - The Browsed Media Player does not support search Search */ -#define AVRC_STS_SEARCH_BUSY 0x10 /* Search in Progress - A search operation is already in progress Search*/ -#define AVRC_STS_BAD_PLAYER_ID 0x11 /* Invalid Player Id - The specified Player Id does not refer to a valid player SetAddressedPlayer, SetBrowsedPlayer*/ -#define AVRC_STS_PLAYER_N_BR 0x12 /* Player Not Browsable - The Player Id supplied refers to a Media Player which does not support browsing. SetBrowsedPlayer */ -#define AVRC_STS_PLAYER_N_ADDR 0x13 /* Player Not Addressed. The Player Id supplied refers to a player which is not currently addressed, and the command is not able to be performed if the player is not set as addressed. Search, SetBrowsedPlayer*/ -#define AVRC_STS_BAD_SEARCH_RES 0x14 /* No valid Search Results - The Search result list does not contain valid entries, e.g. after being invalidated due to change of browsed player GetFolderItems */ -#define AVRC_STS_NO_AVAL_PLAYER 0x15 /* No available players ALL */ -#define AVRC_STS_ADDR_PLAYER_CHG 0x16 /* Addressed Player Changed - Register Notification */ -typedef UINT8 tAVRC_STS; - - -/* Define the Capability IDs -*/ -#define AVRC_CAP_COMPANY_ID 0x02 -#define AVRC_CAP_EVENTS_SUPPORTED 0x03 -#define AVRC_COMPANY_ID_LEN 3 -#define AVRC_CAPABILITY_OFFSET 2 - -/* Define the Player Application Settings IDs -*/ -#define AVRC_PLAYER_SETTING_EQUALIZER 0x01 -#define AVRC_PLAYER_SETTING_REPEAT 0x02 -#define AVRC_PLAYER_SETTING_SHUFFLE 0x03 -#define AVRC_PLAYER_SETTING_SCAN 0x04 -#define AVRC_PLAYER_SETTING_LOW_MENU_EXT 0x80 -#define AVRC_PLAYER_SETTING_HIGH_MENU_EXT 0xff - -/* Define the possible values of the Player Application Settings -*/ -#define AVRC_PLAYER_VAL_OFF 0x01 -#define AVRC_PLAYER_VAL_ON 0x02 -#define AVRC_PLAYER_VAL_SINGLE_REPEAT 0x02 -#define AVRC_PLAYER_VAL_ALL_REPEAT 0x03 -#define AVRC_PLAYER_VAL_GROUP_REPEAT 0x04 -#define AVRC_PLAYER_VAL_ALL_SHUFFLE 0x02 -#define AVRC_PLAYER_VAL_GROUP_SHUFFLE 0x03 -#define AVRC_PLAYER_VAL_ALL_SCAN 0x02 -#define AVRC_PLAYER_VAL_GROUP_SCAN 0x03 - -/* Define the possible values of Battery Status PDU -*/ -#define AVRC_BATTERY_STATUS_NORMAL 0x00 -#define AVRC_BATTERY_STATUS_WARNING 0x01 -#define AVRC_BATTERY_STATUS_CRITICAL 0x02 -#define AVRC_BATTERY_STATUS_EXTERNAL 0x03 -#define AVRC_BATTERY_STATUS_FULL_CHARGE 0x04 -typedef UINT8 tAVRC_BATTERY_STATUS; - -/* Define character set */ -#define AVRC_CHAR_SET_SIZE 2 - -/* Define the Media Attribute IDs -*/ -#define AVRC_MEDIA_ATTR_ID_TITLE 0x00000001 -#define AVRC_MEDIA_ATTR_ID_ARTIST 0x00000002 -#define AVRC_MEDIA_ATTR_ID_ALBUM 0x00000003 -#define AVRC_MEDIA_ATTR_ID_TRACK_NUM 0x00000004 -#define AVRC_MEDIA_ATTR_ID_NUM_TRACKS 0x00000005 -#define AVRC_MEDIA_ATTR_ID_GENRE 0x00000006 -#define AVRC_MEDIA_ATTR_ID_PLAYING_TIME 0x00000007 /* in miliseconds */ -#define AVRC_MAX_NUM_MEDIA_ATTR_ID 7 - -/* Define the possible values of play state -*/ -#define AVRC_PLAYSTATE_RESP_MSG_SIZE 9 -#define AVRC_PLAYSTATE_STOPPED 0x00 /* Stopped */ -#define AVRC_PLAYSTATE_PLAYING 0x01 /* Playing */ -#define AVRC_PLAYSTATE_PAUSED 0x02 /* Paused */ -#define AVRC_PLAYSTATE_FWD_SEEK 0x03 /* Fwd Seek*/ -#define AVRC_PLAYSTATE_REV_SEEK 0x04 /* Rev Seek*/ -#define AVRC_PLAYSTATE_ERROR 0xFF /* Error */ -typedef UINT8 tAVRC_PLAYSTATE; - -/* Define the events that can be registered for notifications -*/ -#define AVRC_EVT_PLAY_STATUS_CHANGE 0x01 -#define AVRC_EVT_TRACK_CHANGE 0x02 -#define AVRC_EVT_TRACK_REACHED_END 0x03 -#define AVRC_EVT_TRACK_REACHED_START 0x04 -#define AVRC_EVT_PLAY_POS_CHANGED 0x05 -#define AVRC_EVT_BATTERY_STATUS_CHANGE 0x06 -#define AVRC_EVT_SYSTEM_STATUS_CHANGE 0x07 -#define AVRC_EVT_APP_SETTING_CHANGE 0x08 -/* added in AVRCP 1.4 */ -#define AVRC_EVT_NOW_PLAYING_CHANGE 0x09 -#define AVRC_EVT_AVAL_PLAYERS_CHANGE 0x0a -#define AVRC_EVT_ADDR_PLAYER_CHANGE 0x0b -#define AVRC_EVT_UIDS_CHANGE 0x0c -#define AVRC_EVT_VOLUME_CHANGE 0x0d - -/* the number of events that can be registered for notifications */ -#define AVRC_NUM_NOTIF_EVENTS 0x0d - -#define AVRC_EVT_MSG_LEN_1 0x01 -#define AVRC_EVT_MSG_LEN_2 0x02 -#define AVRC_EVT_MSG_LEN_5 0x05 -#define AVRC_EVT_MSG_LEN_9 0x09 - -#define AVRC_MAX_VOLUME 0x7F - -/* Define the possible values of system status -*/ -#define AVRC_SYSTEMSTATE_PWR_ON 0x00 -#define AVRC_SYSTEMSTATE_PWR_OFF 0x01 -#define AVRC_SYSTEMSTATE_PWR_UNPLUGGED 0x02 -typedef UINT8 tAVRC_SYSTEMSTATE; - -/* the frequently used character set ids */ -#define AVRC_CHARSET_ID_ASCII ((UINT16) 0x0003) /* ASCII */ -#define AVRC_CHARSET_ID_UTF8 ((UINT16) 0x006a) /* UTF-8 */ -#define AVRC_CHARSET_ID_UTF16 ((UINT16) 0x03f7) /* 1015 */ -#define AVRC_CHARSET_ID_UTF32 ((UINT16) 0x03f9) /* 1017 */ - -/***************************************************************************** -** Advanced Control -*****************************************************************************/ -#define AVRC_ITEM_PLAYER 0x01 -#define AVRC_ITEM_FOLDER 0x02 -#define AVRC_ITEM_MEDIA 0x03 - -#define AVRC_SCOPE_PLAYER_LIST 0x00 /* Media Player Item - Contains all available media players */ -#define AVRC_SCOPE_FILE_SYSTEM 0x01 /* Folder Item, Media Element Item - - The virtual filesystem containing the media content of the browsed player */ -#define AVRC_SCOPE_SEARCH 0x02 /* Media Element Item The results of a search operation on the browsed player */ -#define AVRC_SCOPE_NOW_PLAYING 0x03 /* Media Element Item The Now Playing list (or queue) of the addressed player */ - -#define AVRC_FOLDER_ITEM_COUNT_NONE 0xFF - -/* folder type */ -#define AVRC_FOLDER_TYPE_MIXED 0x00 -#define AVRC_FOLDER_TYPE_TITLES 0x01 -#define AVRC_FOLDER_TYPE_ALNUMS 0x02 -#define AVRC_FOLDER_TYPE_ARTISTS 0x03 -#define AVRC_FOLDER_TYPE_GENRES 0x04 -#define AVRC_FOLDER_TYPE_PLAYLISTS 0x05 -#define AVRC_FOLDER_TYPE_YEARS 0x06 - -/* major player type */ -#define AVRC_MJ_TYPE_AUDIO 0x01 /* Audio */ -#define AVRC_MJ_TYPE_VIDEO 0x02 /* Video */ -#define AVRC_MJ_TYPE_BC_AUDIO 0x04 /* Broadcasting Audio */ -#define AVRC_MJ_TYPE_BC_VIDEO 0x08 /* Broadcasting Video */ -#define AVRC_MJ_TYPE_INVALID 0xF0 - -/* player sub type */ -#define AVRC_SUB_TYPE_NONE 0x00 -#define AVRC_SUB_TYPE_AUDIO_BOOK 0x01 /* Audio Book */ -#define AVRC_SUB_TYPE_PODCAST 0x02 /* Podcast */ -#define AVRC_SUB_TYPE_INVALID 0xFC - -/* media item - media type */ -#define AVRC_MEDIA_TYPE_AUDIO 0x00 -#define AVRC_MEDIA_TYPE_VIDEO 0x01 - -#define AVRC_DIR_UP 0x00 /* Folder Up */ -#define AVRC_DIR_DOWN 0x01 /* Folder Down */ - -#define AVRC_UID_SIZE 8 -typedef UINT8 tAVRC_UID[AVRC_UID_SIZE]; - -/***************************************************************************** -** player attribute - supported features -*****************************************************************************/ -#define AVRC_PF_SELECT_BIT_NO 0 -#define AVRC_PF_SELECT_MASK 0x01 -#define AVRC_PF_SELECT_OFF 0 -#define AVRC_PF_SELECT_SUPPORTED(x) ((x)[AVRC_PF_SELECT_OFF] & AVRC_PF_SELECT_MASK) - -#define AVRC_PF_UP_BIT_NO 1 -#define AVRC_PF_UP_MASK 0x02 -#define AVRC_PF_UP_OFF 0 -#define AVRC_PF_UP_SUPPORTED(x) ((x)[AVRC_PF_UP_OFF] & AVRC_PF_UP_MASK) - -#define AVRC_PF_DOWN_BIT_NO 2 -#define AVRC_PF_DOWN_MASK 0x04 -#define AVRC_PF_DOWN_OFF 0 -#define AVRC_PF_DOWN_SUPPORTED(x) ((x)[AVRC_PF_DOWN_OFF] & AVRC_PF_DOWN_MASK) - -#define AVRC_PF_LEFT_BIT_NO 3 -#define AVRC_PF_LEFT_MASK 0x08 -#define AVRC_PF_LEFT_OFF 0 -#define AVRC_PF_LEFT_SUPPORTED(x) ((x)[AVRC_PF_LEFT_OFF] & AVRC_PF_LEFT_MASK) - -#define AVRC_PF_RIGHT_BIT_NO 4 -#define AVRC_PF_RIGHT_MASK 0x10 -#define AVRC_PF_RIGHT_OFF 0 -#define AVRC_PF_RIGHT_SUPPORTED(x) ((x)[AVRC_PF_RIGHT_OFF] & AVRC_PF_RIGHT_MASK) - -#define AVRC_PF_RIGHTUP_BIT_NO 5 -#define AVRC_PF_RIGHTUP_MASK 0x20 -#define AVRC_PF_RIGHTUP_OFF 0 -#define AVRC_PF_RIGHTUP_SUPPORTED(x) ((x)[AVRC_PF_RIGHTUP_OFF] & AVRC_PF_RIGHTUP_MASK) - -#define AVRC_PF_RIGHTDOWN_BIT_NO 6 -#define AVRC_PF_RIGHTDOWN_MASK 0x40 -#define AVRC_PF_RIGHTDOWN_OFF 0 -#define AVRC_PF_RIGHTDOWN_SUPPORTED(x) ((x)[AVRC_PF_RIGHTDOWN_OFF] & AVRC_PF_RIGHTDOWN_MASK) - -#define AVRC_PF_LEFTUP_BIT_NO 7 -#define AVRC_PF_LEFTUP_MASK 0x80 -#define AVRC_PF_LEFTUP_OFF 0 -#define AVRC_PF_LEFTUP_SUPPORTED(x) ((x)[AVRC_PF_LEFTUP_OFF] & AVRC_PF_LEFTUP_MASK) - -#define AVRC_PF_LEFTDOWN_BIT_NO 8 -#define AVRC_PF_LEFTDOWN_MASK 0x01 -#define AVRC_PF_LEFTDOWN_OFF 1 -#define AVRC_PF_LEFTDOWN_SUPPORTED(x) ((x)[AVRC_PF_LEFTDOWN_OFF] & AVRC_PF_LEFTDOWN_MASK) - -#define AVRC_PF_ROOT_MENU_BIT_NO 9 -#define AVRC_PF_ROOT_MENU_MASK 0x02 -#define AVRC_PF_ROOT_MENU_OFF 1 -#define AVRC_PF_ROOT_MENU_SUPPORTED(x) ((x)[AVRC_PF_ROOT_MENU_OFF] & AVRC_PF_ROOT_MENU_MASK) - -#define AVRC_PF_SETUP_MENU_BIT_NO 10 -#define AVRC_PF_SETUP_MENU_MASK 0x04 -#define AVRC_PF_SETUP_MENU_OFF 1 -#define AVRC_PF_SETUP_MENU_SUPPORTED(x) ((x)[AVRC_PF_SETUP_MENU_OFF] & AVRC_PF_SETUP_MENU_MASK) - -#define AVRC_PF_CONTENTS_MENU_BIT_NO 11 -#define AVRC_PF_CONTENTS_MENU_MASK 0x08 -#define AVRC_PF_CONTENTS_MENU_OFF 1 -#define AVRC_PF_CONTENTS_MENU_SUPPORTED(x) ((x)[AVRC_PF_CONTENTS_MENU_OFF] & AVRC_PF_CONTENTS_MENU_MASK) - -#define AVRC_PF_FAVORITE_MENU_BIT_NO 12 -#define AVRC_PF_FAVORITE_MENU_MASK 0x10 -#define AVRC_PF_FAVORITE_MENU_OFF 1 -#define AVRC_PF_FAVORITE_MENU_SUPPORTED(x) ((x)[AVRC_PF_FAVORITE_MENU_OFF] & AVRC_PF_FAVORITE_MENU_MASK) - -#define AVRC_PF_EXIT_BIT_NO 13 -#define AVRC_PF_EXIT_MASK 0x20 -#define AVRC_PF_EXIT_OFF 1 -#define AVRC_PF_EXIT_SUPPORTED(x) ((x)[AVRC_PF_EXIT_OFF] & AVRC_PF_EXIT_MASK) - -#define AVRC_PF_0_BIT_NO 14 -#define AVRC_PF_0_MASK 0x40 -#define AVRC_PF_0_OFF 1 -#define AVRC_PF_0_SUPPORTED(x) ((x)[AVRC_PF_0_OFF] & AVRC_PF_0_MASK) - -#define AVRC_PF_1_BIT_NO 15 -#define AVRC_PF_1_MASK 0x80 -#define AVRC_PF_1_OFF 1 -#define AVRC_PF_1_SUPPORTED(x) ((x)[AVRC_PF_1_OFF] & AVRC_PF_1_MASK) - -#define AVRC_PF_2_BIT_NO 16 -#define AVRC_PF_2_MASK 0x01 -#define AVRC_PF_2_OFF 2 -#define AVRC_PF_2_SUPPORTED(x) ((x)[AVRC_PF_2_OFF] & AVRC_PF_2_MASK) - -#define AVRC_PF_3_BIT_NO 17 -#define AVRC_PF_3_MASK 0x02 -#define AVRC_PF_3_OFF 2 -#define AVRC_PF_3_SUPPORTED(x) ((x)[AVRC_PF_3_OFF] & AVRC_PF_3_MASK) - -#define AVRC_PF_4_BIT_NO 18 -#define AVRC_PF_4_MASK 0x04 -#define AVRC_PF_4_OFF 2 -#define AVRC_PF_4_SUPPORTED(x) ((x)[AVRC_PF_4_OFF] & AVRC_PF_4_MASK) - -#define AVRC_PF_5_BIT_NO 19 -#define AVRC_PF_5_MASK 0x08 -#define AVRC_PF_5_OFF 2 -#define AVRC_PF_5_SUPPORTED(x) ((x)[AVRC_PF_5_OFF] & AVRC_PF_5_MASK) - -#define AVRC_PF_6_BIT_NO 20 -#define AVRC_PF_6_MASK 0x10 -#define AVRC_PF_6_OFF 2 -#define AVRC_PF_6_SUPPORTED(x) ((x)[AVRC_PF_6_OFF] & AVRC_PF_6_MASK) - -#define AVRC_PF_7_BIT_NO 21 -#define AVRC_PF_7_MASK 0x20 -#define AVRC_PF_7_OFF 2 -#define AVRC_PF_7_SUPPORTED(x) ((x)[AVRC_PF_7_OFF] & AVRC_PF_7_MASK) - -#define AVRC_PF_8_BIT_NO 22 -#define AVRC_PF_8_MASK 0x40 -#define AVRC_PF_8_OFF 2 -#define AVRC_PF_8_SUPPORTED(x) ((x)[AVRC_PF_8_OFF] & AVRC_PF_8_MASK) - -#define AVRC_PF_9_BIT_NO 23 -#define AVRC_PF_9_MASK 0x80 -#define AVRC_PF_9_OFF 2 -#define AVRC_PF_9_SUPPORTED(x) ((x)[AVRC_PF_9_OFF] & AVRC_PF_9_MASK) - -#define AVRC_PF_DOT_BIT_NO 24 -#define AVRC_PF_DOT_MASK 0x01 -#define AVRC_PF_DOT_OFF 3 -#define AVRC_PF_DOT_SUPPORTED(x) ((x)[AVRC_PF_DOT_OFF] & AVRC_PF_DOT_MASK) - -#define AVRC_PF_ENTER_BIT_NO 25 -#define AVRC_PF_ENTER_MASK 0x02 -#define AVRC_PF_ENTER_OFF 3 -#define AVRC_PF_ENTER_SUPPORTED(x) ((x)[AVRC_PF_ENTER_OFF] & AVRC_PF_ENTER_MASK) - -#define AVRC_PF_CLEAR_BIT_NO 26 -#define AVRC_PF_CLEAR_MASK 0x04 -#define AVRC_PF_CLEAR_OFF 3 -#define AVRC_PF_CLEAR_SUPPORTED(x) ((x)[AVRC_PF_CLEAR_OFF] & AVRC_PF_CLEAR_MASK) - -#define AVRC_PF_CHNL_UP_BIT_NO 27 -#define AVRC_PF_CHNL_UP_MASK 0x08 -#define AVRC_PF_CHNL_UP_OFF 3 -#define AVRC_PF_CHNL_UP_SUPPORTED(x) ((x)[AVRC_PF_CHNL_UP_OFF] & AVRC_PF_CHNL_UP_MASK) - -#define AVRC_PF_CHNL_DOWN_BIT_NO 28 -#define AVRC_PF_CHNL_DOWN_MASK 0x10 -#define AVRC_PF_CHNL_DOWN_OFF 3 -#define AVRC_PF_CHNL_DOWN_SUPPORTED(x) ((x)[AVRC_PF_CHNL_DOWN_OFF] & AVRC_PF_CHNL_DOWN_MASK) - -#define AVRC_PF_PREV_CHNL_BIT_NO 29 -#define AVRC_PF_PREV_CHNL_MASK 0x20 -#define AVRC_PF_PREV_CHNL_OFF 3 -#define AVRC_PF_PREV_CHNL_SUPPORTED(x) ((x)[AVRC_PF_PREV_CHNL_OFF] & AVRC_PF_PREV_CHNL_MASK) - -#define AVRC_PF_SOUND_SEL_BIT_NO 30 -#define AVRC_PF_SOUND_SEL_MASK 0x40 -#define AVRC_PF_SOUND_SEL_OFF 3 -#define AVRC_PF_SOUND_SEL_SUPPORTED(x) ((x)[AVRC_PF_SOUND_SEL_OFF] & AVRC_PF_SOUND_SEL_MASK) - -#define AVRC_PF_INPUT_SEL_BIT_NO 31 -#define AVRC_PF_INPUT_SEL_MASK 0x80 -#define AVRC_PF_INPUT_SEL_OFF 3 -#define AVRC_PF_INPUT_SEL_SUPPORTED(x) ((x)[AVRC_PF_INPUT_SEL_OFF] & AVRC_PF_INPUT_SEL_MASK) - -#define AVRC_PF_DISP_INFO_BIT_NO 32 -#define AVRC_PF_DISP_INFO_MASK 0x01 -#define AVRC_PF_DISP_INFO_OFF 4 -#define AVRC_PF_DISP_INFO_SUPPORTED(x) ((x)[AVRC_PF_DISP_INFO_OFF] & AVRC_PF_DISP_INFO_MASK) - -#define AVRC_PF_HELP_BIT_NO 33 -#define AVRC_PF_HELP_MASK 0x02 -#define AVRC_PF_HELP_OFF 4 -#define AVRC_PF_HELP_SUPPORTED(x) ((x)[AVRC_PF_HELP_OFF] & AVRC_PF_HELP_MASK) - -#define AVRC_PF_PAGE_UP_BIT_NO 34 -#define AVRC_PF_PAGE_UP_MASK 0x04 -#define AVRC_PF_PAGE_UP_OFF 4 -#define AVRC_PF_PAGE_UP_SUPPORTED(x) ((x)[AVRC_PF_PAGE_UP_OFF] & AVRC_PF_PAGE_UP_MASK) - -#define AVRC_PF_PAGE_DOWN_BIT_NO 35 -#define AVRC_PF_PAGE_DOWN_MASK 0x08 -#define AVRC_PF_PAGE_DOWN_OFF 4 -#define AVRC_PF_PAGE_DOWN_SUPPORTED(x) ((x)[AVRC_PF_PAGE_DOWN_OFF] & AVRC_PF_PAGE_DOWN_MASK) - -#define AVRC_PF_POWER_BIT_NO 36 -#define AVRC_PF_POWER_MASK 0x10 -#define AVRC_PF_POWER_OFF 4 -#define AVRC_PF_POWER_SUPPORTED(x) ((x)[AVRC_PF_POWER_OFF] & AVRC_PF_POWER_MASK) - -#define AVRC_PF_VOL_UP_BIT_NO 37 -#define AVRC_PF_VOL_UP_MASK 0x20 -#define AVRC_PF_VOL_UP_OFF 4 -#define AVRC_PF_VOL_UP_SUPPORTED(x) ((x)[AVRC_PF_VOL_UP_OFF] & AVRC_PF_VOL_UP_MASK) - -#define AVRC_PF_VOL_DOWN_BIT_NO 38 -#define AVRC_PF_VOL_DOWN_MASK 0x40 -#define AVRC_PF_VOL_DOWN_OFF 4 -#define AVRC_PF_VOL_DOWN_SUPPORTED(x) ((x)[AVRC_PF_VOL_DOWN_OFF] & AVRC_PF_VOL_DOWN_MASK) - -#define AVRC_PF_MUTE_BIT_NO 39 -#define AVRC_PF_MUTE_MASK 0x80 -#define AVRC_PF_MUTE_OFF 4 -#define AVRC_PF_MUTE_SUPPORTED(x) ((x)[AVRC_PF_MUTE_OFF] & AVRC_PF_MUTE_MASK) - -#define AVRC_PF_PLAY_BIT_NO 40 -#define AVRC_PF_PLAY_MASK 0x01 -#define AVRC_PF_PLAY_OFF 5 -#define AVRC_PF_PLAY_SUPPORTED(x) ((x)[AVRC_PF_PLAY_OFF] & AVRC_PF_PLAY_MASK) - -#define AVRC_PF_STOP_BIT_NO 41 -#define AVRC_PF_STOP_MASK 0x02 -#define AVRC_PF_STOP_OFF 5 -#define AVRC_PF_STOP_SUPPORTED(x) ((x)[AVRC_PF_STOP_OFF] & AVRC_PF_STOP_MASK) - -#define AVRC_PF_PAUSE_BIT_NO 42 -#define AVRC_PF_PAUSE_MASK 0x04 -#define AVRC_PF_PAUSE_OFF 5 -#define AVRC_PF_PAUSE_SUPPORTED(x) ((x)[AVRC_PF_PAUSE_OFF] & AVRC_PF_PAUSE_MASK) - -#define AVRC_PF_RECORD_BIT_NO 43 -#define AVRC_PF_RECORD_MASK 0x08 -#define AVRC_PF_RECORD_OFF 5 -#define AVRC_PF_RECORD_SUPPORTED(x) ((x)[AVRC_PF_RECORD_OFF] & AVRC_PF_RECORD_MASK) - -#define AVRC_PF_REWIND_BIT_NO 44 -#define AVRC_PF_REWIND_MASK 0x10 -#define AVRC_PF_REWIND_OFF 5 -#define AVRC_PF_REWIND_SUPPORTED(x) ((x)[AVRC_PF_REWIND_OFF] & AVRC_PF_REWIND_MASK) - -#define AVRC_PF_FAST_FWD_BIT_NO 45 -#define AVRC_PF_FAST_FWD_MASK 0x20 -#define AVRC_PF_FAST_FWD_OFF 5 -#define AVRC_PF_FAST_FWD_SUPPORTED(x) ((x)[AVRC_PF_FAST_FWD_OFF] & AVRC_PF_FAST_FWD_MASK) - -#define AVRC_PF_EJECT_BIT_NO 46 -#define AVRC_PF_EJECT_MASK 0x40 -#define AVRC_PF_EJECT_OFF 5 -#define AVRC_PF_EJECT_SUPPORTED(x) ((x)[AVRC_PF_EJECT_OFF] & AVRC_PF_EJECT_MASK) - -#define AVRC_PF_FORWARD_BIT_NO 47 -#define AVRC_PF_FORWARD_MASK 0x80 -#define AVRC_PF_FORWARD_OFF 5 -#define AVRC_PF_FORWARD_SUPPORTED(x) ((x)[AVRC_PF_FORWARD_OFF] & AVRC_PF_FORWARD_MASK) - -#define AVRC_PF_BACKWARD_BIT_NO 48 -#define AVRC_PF_BACKWARD_MASK 0x01 -#define AVRC_PF_BACKWARD_OFF 6 -#define AVRC_PF_BACKWARD_SUPPORTED(x) ((x)[AVRC_PF_BACKWARD_OFF] & AVRC_PF_BACKWARD_MASK) - -#define AVRC_PF_ANGLE_BIT_NO 49 -#define AVRC_PF_ANGLE_MASK 0x02 -#define AVRC_PF_ANGLE_OFF 6 -#define AVRC_PF_ANGLE_SUPPORTED(x) ((x)[AVRC_PF_ANGLE_OFF] & AVRC_PF_ANGLE_MASK) - -#define AVRC_PF_SUBPICTURE_BIT_NO 50 -#define AVRC_PF_SUBPICTURE_MASK 0x04 -#define AVRC_PF_SUBPICTURE_OFF 6 -#define AVRC_PF_SUBPICTURE_SUPPORTED(x) ((x)[AVRC_PF_SUBPICTURE_OFF] & AVRC_PF_SUBPICTURE_MASK) - -#define AVRC_PF_F1_BIT_NO 51 -#define AVRC_PF_F1_MASK 0x08 -#define AVRC_PF_F1_OFF 6 -#define AVRC_PF_F1_SUPPORTED(x) ((x)[AVRC_PF_F1_OFF] & AVRC_PF_F1_MASK) - -#define AVRC_PF_F2_BIT_NO 52 -#define AVRC_PF_F2_MASK 0x10 -#define AVRC_PF_F2_OFF 6 -#define AVRC_PF_F2_SUPPORTED(x) ((x)[AVRC_PF_F2_OFF] & AVRC_PF_F2_MASK) - -#define AVRC_PF_F3_BIT_NO 53 -#define AVRC_PF_F3_MASK 0x20 -#define AVRC_PF_F3_OFF 6 -#define AVRC_PF_F3_SUPPORTED(x) ((x)[AVRC_PF_F3_OFF] & AVRC_PF_F3_MASK) - -#define AVRC_PF_F4_BIT_NO 54 -#define AVRC_PF_F4_MASK 0x40 -#define AVRC_PF_F4_OFF 6 -#define AVRC_PF_F4_SUPPORTED(x) ((x)[AVRC_PF_F4_OFF] & AVRC_PF_F4_MASK) - -#define AVRC_PF_F5_BIT_NO 55 -#define AVRC_PF_F5_MASK 0x80 -#define AVRC_PF_F5_OFF 6 -#define AVRC_PF_F5_SUPPORTED(x) ((x)[AVRC_PF_F5_OFF] & AVRC_PF_F5_MASK) - -/* Vendor unique. This PASSTHROUGH command is supported. */ -#define AVRC_PF_VENDOR_BIT_NO 56 -#define AVRC_PF_VENDOR_MASK 0x01 -#define AVRC_PF_VENDOR_OFF 7 -#define AVRC_PF_VENDOR_SUPPORTED(x) ((x)[AVRC_PF_VENDOR_OFF] & AVRC_PF_VENDOR_MASK) - -/* Basic Group Navigation. This overrules the SDP entry as it is set per player.7 */ -#define AVRC_PF_GROUP_NAVI_BIT_NO 57 -#define AVRC_PF_GROUP_NAVI_MASK 0x02 -#define AVRC_PF_GROUP_NAVI_OFF 7 -#define AVRC_PF_GROUP_NAVI_SUPPORTED(x) ((x)[AVRC_PF_GROUP_NAVI_OFF] & AVRC_PF_GROUP_NAVI_MASK) - -/* Advanced Control Player. This bit is set if the player supports at least AVRCP 1.4. */ -#define AVRC_PF_ADV_CTRL_BIT_NO 58 -#define AVRC_PF_ADV_CTRL_MASK 0x04 -#define AVRC_PF_ADV_CTRL_OFF 7 -#define AVRC_PF_ADV_CTRL_SUPPORTED(x) ((x)[AVRC_PF_ADV_CTRL_OFF] & AVRC_PF_ADV_CTRL_MASK) - -/* Browsing. This bit is set if the player supports browsing. */ -#define AVRC_PF_BROWSE_BIT_NO 59 -#define AVRC_PF_BROWSE_MASK 0x08 -#define AVRC_PF_BROWSE_OFF 7 -#define AVRC_PF_BROWSE_SUPPORTED(x) ((x)[AVRC_PF_BROWSE_OFF] & AVRC_PF_BROWSE_MASK) - -/* Searching. This bit is set if the player supports searching. */ -#define AVRC_PF_SEARCH_BIT_NO 60 -#define AVRC_PF_SEARCH_MASK 0x10 -#define AVRC_PF_SEARCH_OFF 7 -#define AVRC_PF_SEARCH_SUPPORTED(x) ((x)[AVRC_PF_SEARCH_OFF] & AVRC_PF_SEARCH_MASK) - -/* AddToNowPlaying. This bit is set if the player supports the AddToNowPlaying command. */ -#define AVRC_PF_ADD2NOWPLAY_BIT_NO 61 -#define AVRC_PF_ADD2NOWPLAY_MASK 0x20 -#define AVRC_PF_ADD2NOWPLAY_OFF 7 -#define AVRC_PF_ADD2NOWPLAY_SUPPORTED(x) ((x)[AVRC_PF_ADD2NOWPLAY_OFF] & AVRC_PF_ADD2NOWPLAY_MASK) - -/* UIDs unique in player browse tree. This bit is set if the player is able to maintain unique UIDs across the player browse tree. */ -#define AVRC_PF_UID_UNIQUE_BIT_NO 62 -#define AVRC_PF_UID_UNIQUE_MASK 0x40 -#define AVRC_PF_UID_UNIQUE_OFF 7 -#define AVRC_PF_UID_UNIQUE_SUPPORTED(x) ((x)[AVRC_PF_UID_UNIQUE_OFF] & AVRC_PF_UID_UNIQUE_MASK) - -/* OnlyBrowsableWhenAddressed. This bit is set if the player is only able to be browsed when it is set as the Addressed Player. */ -#define AVRC_PF_BR_WH_ADDR_BIT_NO 63 -#define AVRC_PF_BR_WH_ADDR_MASK 0x80 -#define AVRC_PF_BR_WH_ADDR_OFF 7 -#define AVRC_PF_BR_WH_ADDR_SUPPORTED(x) ((x)[AVRC_PF_BR_WH_ADDR_OFF] & AVRC_PF_BR_WH_ADDR_MASK) - -/* OnlySearchableWhenAddressed. This bit is set if the player is only able to be searched when it is set as the Addressed player. */ -#define AVRC_PF_SEARCH_WH_ADDR_BIT_NO 64 -#define AVRC_PF_SEARCH_WH_ADDR_MASK 0x01 -#define AVRC_PF_SEARCH_WH_ADDR_OFF 8 -#define AVRC_PF_SEARCH_WH_ADDR_SUPPORTED(x) ((x)[AVRC_PF_SEARCH_WH_ADDR_OFF] & AVRC_PF_SEARCH_WH_ADDR_MASK) - -/* NowPlaying. This bit is set if the player supports the NowPlaying folder. Note that for all players that support browsing this bit shall be set */ -#define AVRC_PF_NOW_PLAY_BIT_NO 65 -#define AVRC_PF_NOW_PLAY_MASK 0x02 -#define AVRC_PF_NOW_PLAY_OFF 8 -#define AVRC_PF_NOW_PLAY_SUPPORTED(x) ((x)[AVRC_PF_NOW_PLAY_OFF] & AVRC_PF_NOW_PLAY_MASK) - -/* UIDPersistency. This bit is set if the Player is able to persist UID values between AVRCP Browse Reconnect */ -#define AVRC_PF_UID_PERSIST_BIT_NO 66 -#define AVRC_PF_UID_PERSIST_MASK 0x04 -#define AVRC_PF_UID_PERSIST_OFF 8 -#define AVRC_PF_UID_PERSIST_SUPPORTED(x) ((x)[AVRC_PF_UID_PERSIST_OFF] & AVRC_PF_UID_PERSIST_MASK) - -/***************************************************************************** -** data type definitions -*****************************************************************************/ - -/* -This structure contains the header parameters of an AV/C message. -*/ -typedef struct { - UINT8 ctype; /* Command type. */ - UINT8 subunit_type; /* Subunit type. */ - UINT8 subunit_id; /* Subunit ID. This value is typically ignored in AVRCP, - * except for VENDOR DEPENDENT messages when the value is - * vendor-dependent. Value range is 0-7. */ - UINT8 opcode; /* Op Code (passthrough, vendor, etc) */ -} tAVRC_HDR; - -/* This structure contains a UNIT INFO message. */ -typedef struct { - tAVRC_HDR hdr; /* Message header. */ - UINT32 company_id; /* Company identifier. */ - UINT8 unit_type; /* Unit type. Uses the same values as subunit type. */ - UINT8 unit; /* This value is vendor dependent and typically zero. */ -} tAVRC_MSG_UNIT; - -/* This structure contains a SUBUNIT INFO message. */ -typedef struct { - tAVRC_HDR hdr; /* Message header. */ - UINT8 subunit_type[AVRC_SUB_TYPE_LEN]; - /* Array containing subunit type values. */ - BOOLEAN panel; /* TRUE if the panel subunit type is in the - * subunit_type array, FALSE otherwise. */ - UINT8 page; /* Specifies which part of the subunit type table is - * returned. For AVRCP it is typically zero. - * Value range is 0-7. */ -} tAVRC_MSG_SUB; - -/* This structure contains a VENDOR DEPENDENT message. */ -typedef struct { - tAVRC_HDR hdr; /* Message header. */ - UINT32 company_id; /* Company identifier. */ - UINT8 *p_vendor_data;/* Pointer to vendor dependent data. */ - UINT16 vendor_len; /* Length in bytes of vendor dependent data. */ -} tAVRC_MSG_VENDOR; - -/* PASS THROUGH message structure */ -typedef struct { - tAVRC_HDR hdr; /* hdr.ctype Unused. - * hdr.subunit_type Unused. - * hdr.subunit_id Unused. */ - UINT8 op_id; /* Operation ID. */ - UINT8 state; /* Keypress state. */ - UINT8 *p_pass_data;/* Pointer to data. This parameter is only valid - * when the op_id is AVRC_ID_VENDOR.*/ - UINT8 pass_len; /* Length in bytes of data. This parameter is only - * valid when the op_id is AVRC_ID_VENDOR.*/ -} tAVRC_MSG_PASS; - -/* Command/Response indicator. */ -#define AVRC_CMD AVCT_CMD /* Command message */ -#define AVRC_RSP AVCT_RSP /* Response message */ - -/* Browsing channel message structure */ -typedef struct { - tAVRC_HDR hdr; /* hdr.ctype AVRC_CMD or AVRC_RSP. - * hdr.subunit_type Unused. - * hdr.subunit_id Unused. */ - UINT8 *p_browse_data; /* Pointer to data. */ - UINT16 browse_len; /* Length in bytes of data. */ - BT_HDR *p_browse_pkt; /* The GKI buffer received. Set to NULL, if the callback function wants to keep the buffer */ -} tAVRC_MSG_BROWSE; - -/* This is a union of all message type structures. */ -typedef union { - tAVRC_HDR hdr; /* Message header. */ - tAVRC_MSG_UNIT unit; /* UNIT INFO message. */ - tAVRC_MSG_SUB sub; /* SUBUNIT INFO message. */ - tAVRC_MSG_VENDOR vendor; /* VENDOR DEPENDENT message. */ - tAVRC_MSG_PASS pass; /* PASS THROUGH message. */ - tAVRC_MSG_BROWSE browse; /* messages thru browsing channel */ -} tAVRC_MSG; - -/* macros */ -#define AVRC_IS_VALID_CAP_ID(a) (((a == AVRC_CAP_COMPANY_ID) || (a == AVRC_CAP_EVENTS_SUPPORTED)) ? TRUE : FALSE) - -#define AVRC_IS_VALID_EVENT_ID(a) (((a >= AVRC_EVT_PLAY_STATUS_CHANGE) && \ - (a <= AVRC_EVT_APP_SETTING_CHANGE)) ? TRUE : FALSE) - -#define AVRC_IS_VALID_ATTRIBUTE(a) (((((a > 0) && a <= AVRC_PLAYER_SETTING_SCAN)) || \ - (a >= AVRC_PLAYER_SETTING_LOW_MENU_EXT)) ? TRUE : FALSE) - -#define AVRC_IS_VALID_MEDIA_ATTRIBUTE(a) ((a >= AVRC_MEDIA_ATTR_ID_TITLE) && \ - (a <= AVRC_MEDIA_ATTR_ID_PLAYING_TIME) ? TRUE : FALSE) - -#define AVRC_IS_VALID_BATTERY_STATUS(a) ((a <= AVRC_BATTERY_STATUS_FULL_CHARGE) ? TRUE : FALSE) - -#define AVRC_IS_VALID_SYSTEM_STATUS(a) ((a <= AVRC_SYSTEMSTATE_PWR_UNPLUGGED) ? TRUE : FALSE) - -#define AVRC_IS_VALID_GROUP(a) ((a <= AVRC_PDU_PREV_GROUP) ? TRUE : FALSE) - -/* Company ID is 24-bit integer We can not use the macros in bt_types.h */ -#define AVRC_CO_ID_TO_BE_STREAM(p, u32) {*(p)++ = (UINT8)((u32) >> 16); *(p)++ = (UINT8)((u32) >> 8); *(p)++ = (UINT8)(u32); } -#define AVRC_BE_STREAM_TO_CO_ID(u32, p) {u32 = (((UINT32)(*((p) + 2))) + (((UINT32)(*((p) + 1))) << 8) + (((UINT32)(*(p))) << 16)); (p) += 3;} - -/***************************************************************************** -** data type definitions -*****************************************************************************/ -#define AVRC_MAX_APP_ATTR_SIZE 16 -#define AVRC_MAX_CHARSET_SIZE 16 -#define AVRC_MAX_ELEM_ATTR_SIZE 8 - - -/***************************************************************************** -** Metadata transfer Building/Parsing definitions -*****************************************************************************/ - -typedef struct { - UINT16 charset_id; - UINT16 str_len; - UINT8 *p_str; -} tAVRC_FULL_NAME; - -typedef struct { - UINT16 str_len; - UINT8 *p_str; -} tAVRC_NAME; - - -#ifndef AVRC_CAP_MAX_NUM_COMP_ID -#define AVRC_CAP_MAX_NUM_COMP_ID 4 -#endif - -#ifndef AVRC_CAP_MAX_NUM_EVT_ID -#define AVRC_CAP_MAX_NUM_EVT_ID 16 -#endif - -typedef union { - UINT32 company_id[AVRC_CAP_MAX_NUM_COMP_ID]; - UINT8 event_id[AVRC_CAP_MAX_NUM_EVT_ID]; -} tAVRC_CAPS_PARAM; - -typedef struct { - UINT8 attr_id; - UINT8 attr_val; -} tAVRC_APP_SETTING; - -typedef struct { - UINT8 attr_id; - UINT16 charset_id; - UINT8 str_len; - UINT8 *p_str; -} tAVRC_APP_SETTING_TEXT; - -typedef UINT8 tAVRC_FEATURE_MASK[AVRC_FEATURE_MASK_SIZE]; - -typedef struct { - UINT16 player_id; /* A unique identifier for this media player.*/ - UINT8 major_type; /* Use AVRC_MJ_TYPE_AUDIO, AVRC_MJ_TYPE_VIDEO, AVRC_MJ_TYPE_BC_AUDIO, or AVRC_MJ_TYPE_BC_VIDEO.*/ - UINT32 sub_type; /* Use AVRC_SUB_TYPE_NONE, AVRC_SUB_TYPE_AUDIO_BOOK, or AVRC_SUB_TYPE_PODCAST*/ - UINT8 play_status; /* Use AVRC_PLAYSTATE_STOPPED, AVRC_PLAYSTATE_PLAYING, AVRC_PLAYSTATE_PAUSED, AVRC_PLAYSTATE_FWD_SEEK, - AVRC_PLAYSTATE_REV_SEEK, or AVRC_PLAYSTATE_ERROR*/ - tAVRC_FEATURE_MASK features; /* Supported feature bit mask*/ - tAVRC_FULL_NAME name; /* The player name, name length and character set id.*/ -} tAVRC_ITEM_PLAYER; - -typedef struct { - tAVRC_UID uid; /* The uid of this folder */ - UINT8 type; /* Use AVRC_FOLDER_TYPE_MIXED, AVRC_FOLDER_TYPE_TITLES, - AVRC_FOLDER_TYPE_ALNUMS, AVRC_FOLDER_TYPE_ARTISTS, AVRC_FOLDER_TYPE_GENRES, - AVRC_FOLDER_TYPE_PLAYLISTS, or AVRC_FOLDER_TYPE_YEARS.*/ - BOOLEAN playable; /* TRUE, if the folder can be played. */ - tAVRC_FULL_NAME name; /* The folder name, name length and character set id. */ -} tAVRC_ITEM_FOLDER; - -typedef struct { - UINT32 attr_id; /* Use AVRC_MEDIA_ATTR_ID_TITLE, AVRC_MEDIA_ATTR_ID_ARTIST, AVRC_MEDIA_ATTR_ID_ALBUM, - AVRC_MEDIA_ATTR_ID_TRACK_NUM, AVRC_MEDIA_ATTR_ID_NUM_TRACKS, - AVRC_MEDIA_ATTR_ID_GENRE, AVRC_MEDIA_ATTR_ID_PLAYING_TIME */ - tAVRC_FULL_NAME name; /* The attribute value, value length and character set id. */ -} tAVRC_ATTR_ENTRY; - -typedef struct { - tAVRC_UID uid; /* The uid of this media element item */ - UINT8 type; /* Use AVRC_MEDIA_TYPE_AUDIO or AVRC_MEDIA_TYPE_VIDEO. */ - tAVRC_FULL_NAME name; /* The media name, name length and character set id. */ - UINT8 attr_count; /* The number of attributes in p_attr_list */ - tAVRC_ATTR_ENTRY *p_attr_list; /* Attribute entry list. */ -} tAVRC_ITEM_MEDIA; - -typedef struct { - UINT8 item_type; /* AVRC_ITEM_PLAYER, AVRC_ITEM_FOLDER, or AVRC_ITEM_MEDIA */ - union { - tAVRC_ITEM_PLAYER player; /* The properties of a media player item.*/ - tAVRC_ITEM_FOLDER folder; /* The properties of a folder item.*/ - tAVRC_ITEM_MEDIA media; /* The properties of a media item.*/ - } u; -} tAVRC_ITEM; - -/* GetCapability */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 capability_id; -} tAVRC_GET_CAPS_CMD; - -/* ListPlayerAppValues */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 attr_id; -} tAVRC_LIST_APP_VALUES_CMD; - -/* GetCurAppValue */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 num_attr; - UINT8 attrs[AVRC_MAX_APP_ATTR_SIZE]; -} tAVRC_GET_CUR_APP_VALUE_CMD; - -/* SetAppValue */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 num_val; - tAVRC_APP_SETTING *p_vals; -} tAVRC_SET_APP_VALUE_CMD; - -/* GetAppAttrTxt */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 num_attr; - UINT8 attrs[AVRC_MAX_APP_ATTR_SIZE]; -} tAVRC_GET_APP_ATTR_TXT_CMD; - -/* GetAppValueTxt */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 attr_id; - UINT8 num_val; - UINT8 vals[AVRC_MAX_APP_ATTR_SIZE]; -} tAVRC_GET_APP_VAL_TXT_CMD; - -/* InformCharset */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 num_id; - UINT16 charsets[AVRC_MAX_CHARSET_SIZE]; -} tAVRC_INFORM_CHARSET_CMD; - -/* InformBatteryStatus */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 battery_status; -} tAVRC_BATTERY_STATUS_CMD; - -/* GetElemAttrs */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 num_attr; - UINT32 attrs[AVRC_MAX_ELEM_ATTR_SIZE]; -} tAVRC_GET_ELEM_ATTRS_CMD; - -/* RegNotify */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 event_id; - UINT32 param; -} tAVRC_REG_NOTIF_CMD; - -/* SetAddrPlayer */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT16 player_id; -} tAVRC_SET_ADDR_PLAYER_CMD; - -/* SetBrowsedPlayer */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT16 player_id; -} tAVRC_SET_BR_PLAYER_CMD; - -/* SetAbsVolume */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 volume; -} tAVRC_SET_VOLUME_CMD; - -/* GetFolderItems */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 scope; - UINT32 start_item; - UINT32 end_item; - UINT8 attr_count; - UINT32 *p_attr_list; -} tAVRC_GET_ITEMS_CMD; - -/* ChangePath */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT16 uid_counter; - UINT8 direction; - tAVRC_UID folder_uid; -} tAVRC_CHG_PATH_CMD; - -/* GetItemAttrs */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 scope; - tAVRC_UID uid; - UINT16 uid_counter; - UINT8 attr_count; - UINT32 *p_attr_list; -} tAVRC_GET_ATTRS_CMD; - -/* Search */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - tAVRC_FULL_NAME string; -} tAVRC_SEARCH_CMD; - -/* PlayItem */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 scope; - tAVRC_UID uid; - UINT16 uid_counter; -} tAVRC_PLAY_ITEM_CMD; - -/* AddToNowPlaying */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 scope; - tAVRC_UID uid; - UINT16 uid_counter; -} tAVRC_ADD_TO_PLAY_CMD; - -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ -} tAVRC_CMD; - -/* Continue and Abort */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (assigned by AVRC_BldCommand according to pdu) */ - UINT8 target_pdu; -} tAVRC_NEXT_CMD; - -typedef union { - UINT8 pdu; - tAVRC_CMD cmd; - tAVRC_GET_CAPS_CMD get_caps; /* GetCapability */ - tAVRC_CMD list_app_attr; /* ListPlayerAppAttr */ - tAVRC_LIST_APP_VALUES_CMD list_app_values; /* ListPlayerAppValues */ - tAVRC_GET_CUR_APP_VALUE_CMD get_cur_app_val; /* GetCurAppValue */ - tAVRC_SET_APP_VALUE_CMD set_app_val; /* SetAppValue */ - tAVRC_GET_APP_ATTR_TXT_CMD get_app_attr_txt; /* GetAppAttrTxt */ - tAVRC_GET_APP_VAL_TXT_CMD get_app_val_txt; /* GetAppValueTxt */ - tAVRC_INFORM_CHARSET_CMD inform_charset; /* InformCharset */ - tAVRC_BATTERY_STATUS_CMD inform_battery_status; /* InformBatteryStatus */ - tAVRC_GET_ELEM_ATTRS_CMD get_elem_attrs; /* GetElemAttrs */ - tAVRC_CMD get_play_status; /* GetPlayStatus */ - tAVRC_REG_NOTIF_CMD reg_notif; /* RegNotify */ - tAVRC_NEXT_CMD continu; /* Continue */ - tAVRC_NEXT_CMD abort; /* Abort */ - - tAVRC_SET_ADDR_PLAYER_CMD addr_player; /* SetAddrPlayer */ - tAVRC_SET_VOLUME_CMD volume; /* SetAbsVolume */ - tAVRC_SET_BR_PLAYER_CMD br_player; /* SetBrowsedPlayer */ - tAVRC_GET_ITEMS_CMD get_items; /* GetFolderItems */ - tAVRC_CHG_PATH_CMD chg_path; /* ChangePath */ - tAVRC_GET_ATTRS_CMD get_attrs; /* GetItemAttrs */ - tAVRC_SEARCH_CMD search; /* Search */ - tAVRC_PLAY_ITEM_CMD play_item; /* PlayItem */ - tAVRC_ADD_TO_PLAY_CMD add_to_play; /* AddToNowPlaying */ -} tAVRC_COMMAND; - -/* GetCapability */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 capability_id; - UINT8 count; - tAVRC_CAPS_PARAM param; -} tAVRC_GET_CAPS_RSP; - -/* ListPlayerAppAttr */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 num_attr; - UINT8 attrs[AVRC_MAX_APP_ATTR_SIZE]; -} tAVRC_LIST_APP_ATTR_RSP; - -/* ListPlayerAppValues */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 num_val; - UINT8 vals[AVRC_MAX_APP_ATTR_SIZE]; -} tAVRC_LIST_APP_VALUES_RSP; - -/* GetCurAppValue */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 num_val; - tAVRC_APP_SETTING *p_vals; -} tAVRC_GET_CUR_APP_VALUE_RSP; - -/* GetAppAttrTxt */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 num_attr; - tAVRC_APP_SETTING_TEXT *p_attrs; -} tAVRC_GET_APP_ATTR_TXT_RSP; - -/* GetElemAttrs */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 num_attr; - tAVRC_ATTR_ENTRY *p_attrs; -} tAVRC_GET_ELEM_ATTRS_RSP; - -/* GetPlayStatus */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT32 song_len; - UINT32 song_pos; - UINT8 play_status; -} tAVRC_GET_PLAY_STATUS_RSP; - -/* notification event parameter for AddressedPlayer change */ -typedef struct { - UINT16 player_id; - UINT16 uid_counter; -} tAVRC_ADDR_PLAYER_PARAM; - -#ifndef AVRC_MAX_APP_SETTINGS -#define AVRC_MAX_APP_SETTINGS 8 -#endif - -/* notification event parameter for Player Application setting change */ -typedef struct { - UINT8 num_attr; - UINT8 attr_id[AVRC_MAX_APP_SETTINGS]; - UINT8 attr_value[AVRC_MAX_APP_SETTINGS]; -} tAVRC_PLAYER_APP_PARAM; - -typedef union { - tAVRC_PLAYSTATE play_status; - tAVRC_UID track; - UINT32 play_pos; - tAVRC_BATTERY_STATUS battery_status; - tAVRC_SYSTEMSTATE system_status; - tAVRC_PLAYER_APP_PARAM player_setting; - tAVRC_ADDR_PLAYER_PARAM addr_player; - UINT16 uid_counter; - UINT8 volume; -} tAVRC_NOTIF_RSP_PARAM; - -/* RegNotify */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 event_id; - tAVRC_NOTIF_RSP_PARAM param; -} tAVRC_REG_NOTIF_RSP; - -/* SetAbsVolume */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 volume; -} tAVRC_SET_VOLUME_RSP; - -/* SetBrowsedPlayer */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT16 uid_counter; - UINT32 num_items; - UINT16 charset_id; - UINT8 folder_depth; - tAVRC_NAME *p_folders; -} tAVRC_SET_BR_PLAYER_RSP; - -/* GetFolderItems */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT16 uid_counter; - UINT16 item_count; - tAVRC_ITEM *p_item_list; -} tAVRC_GET_ITEMS_RSP; - -/* ChangePath */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT32 num_items; -} tAVRC_CHG_PATH_RSP; - -/* GetItemAttrs */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT8 attr_count; - tAVRC_ATTR_ENTRY *p_attr_list; -} tAVRC_GET_ATTRS_RSP; - -/* Search */ -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ - UINT16 uid_counter; - UINT32 num_items; -} tAVRC_SEARCH_RSP; - - -typedef struct { - UINT8 pdu; - tAVRC_STS status; - UINT8 opcode; /* Op Code (copied from avrc_cmd.opcode by AVRC_BldResponse user. invalid one to generate according to pdu) */ -} tAVRC_RSP; - -typedef union { - UINT8 pdu; - tAVRC_RSP rsp; - tAVRC_GET_CAPS_RSP get_caps; /* GetCapability */ - tAVRC_LIST_APP_ATTR_RSP list_app_attr; /* ListPlayerAppAttr */ - tAVRC_LIST_APP_VALUES_RSP list_app_values; /* ListPlayerAppValues */ - tAVRC_GET_CUR_APP_VALUE_RSP get_cur_app_val; /* GetCurAppValue */ - tAVRC_RSP set_app_val; /* SetAppValue */ - tAVRC_GET_APP_ATTR_TXT_RSP get_app_attr_txt; /* GetAppAttrTxt */ - tAVRC_GET_APP_ATTR_TXT_RSP get_app_val_txt; /* GetAppValueTxt */ - tAVRC_RSP inform_charset; /* InformCharset */ - tAVRC_RSP inform_battery_status; /* InformBatteryStatus */ - tAVRC_GET_ELEM_ATTRS_RSP get_elem_attrs; /* GetElemAttrs */ - tAVRC_GET_PLAY_STATUS_RSP get_play_status; /* GetPlayStatus */ - tAVRC_REG_NOTIF_RSP reg_notif; /* RegNotify */ - tAVRC_RSP continu; /* Continue */ - tAVRC_RSP abort; /* Abort */ - - tAVRC_RSP addr_player; /* SetAddrPlayer */ - tAVRC_SET_VOLUME_RSP volume; /* SetAbsVolume */ - tAVRC_SET_BR_PLAYER_RSP br_player; /* SetBrowsedPlayer */ - tAVRC_GET_ITEMS_RSP get_items; /* GetFolderItems */ - tAVRC_CHG_PATH_RSP chg_path; /* ChangePath */ - tAVRC_GET_ATTRS_RSP get_attrs; /* GetItemAttrs */ - tAVRC_SEARCH_RSP search; /* Search */ - tAVRC_RSP play_item; /* PlayItem */ - tAVRC_RSP add_to_play; /* AddToNowPlaying */ -} tAVRC_RESPONSE; - -#endif ///AVRC_INCLUDED == TRUE -#endif diff --git a/tools/sdk/include/bluedroid/avrc_int.h b/tools/sdk/include/bluedroid/avrc_int.h deleted file mode 100644 index ed0be01b213..00000000000 --- a/tools/sdk/include/bluedroid/avrc_int.h +++ /dev/null @@ -1,158 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * VRCP internal header file. - * - ******************************************************************************/ - - -#ifndef AVRC_INT_H -#define AVRC_INT_H - -#include "avct_defs.h" -#include "avrc_api.h" - -#if (AVRC_INCLUDED == TRUE) -/* DEBUG FLAGS - * - * #define META_DEBUG_ENABLED - */ -/***************************************************************************** -** Constants -*****************************************************************************/ - -/* Number of attributes in AVRC SDP record. */ -#define AVRC_NUM_ATTR 6 - -/* Number of protocol elements in protocol element list. */ -#define AVRC_NUM_PROTO_ELEMS 2 - -#ifndef AVRC_MIN_CMD_LEN -#define AVRC_MIN_CMD_LEN 20 -#endif - -#define AVRC_UNIT_OPRND_BYTES 5 -#define AVRC_SUB_OPRND_BYTES 4 -#define AVRC_SUBRSP_OPRND_BYTES 3 -#define AVRC_SUB_PAGE_MASK 7 -#define AVRC_SUB_PAGE_SHIFT 4 -#define AVRC_SUB_EXT_CODE 7 -#define AVRC_PASS_OP_ID_MASK 0x7F -#define AVRC_PASS_STATE_MASK 0x80 -#define AVRC_CMD_OPRND_PAD 0xFF - -#define AVRC_CTYPE_MASK 0x0F -#define AVRC_SUBTYPE_MASK 0xF8 -#define AVRC_SUBTYPE_SHIFT 3 -#define AVRC_SUBID_MASK 0x07 -#define AVRC_SUBID_IGNORE 0x07 - -#define AVRC_SINGLE_PARAM_SIZE 1 -#define AVRC_METADATA_PKT_TYPE_MASK 0x03 -#define AVRC_PASS_THOUGH_MSG_MASK 0x80 /* MSB of msg_type indicates the PAS THROUGH msg */ -#define AVRC_VENDOR_UNIQUE_MASK 0x70 /* vendor unique id */ - - -/* Company ID is 24-bit integer We can not use the macros in bt_types.h */ -#define AVRC_CO_ID_TO_BE_STREAM(p, u32) {*(p)++ = (UINT8)((u32) >> 16); *(p)++ = (UINT8)((u32) >> 8); *(p)++ = (UINT8)(u32); } -#define AVRC_BE_STREAM_TO_CO_ID(u32, p) {u32 = (((UINT32)(*((p) + 2))) + (((UINT32)(*((p) + 1))) << 8) + (((UINT32)(*(p))) << 16)); (p) += 3;} - -#define AVRC_AVC_HDR_SIZE 3 /* ctype, subunit*, opcode */ - -#define AVRC_MIN_META_HDR_SIZE 4 /* pdu id(1), packet type(1), param len(2) */ -#define AVRC_MIN_BROWSE_HDR_SIZE 3 /* pdu id(1), param len(2) */ - -#define AVRC_VENDOR_HDR_SIZE 6 /* ctype, subunit*, opcode, CO_ID */ -#define AVRC_MSG_VENDOR_OFFSET 23 -#define AVRC_MIN_VENDOR_SIZE (AVRC_MSG_VENDOR_OFFSET + BT_HDR_SIZE + AVRC_MIN_META_HDR_SIZE) - -#define AVRC_PASS_THRU_SIZE 8 -#define AVRC_MSG_PASS_THRU_OFFSET 25 -#define AVRC_MIN_PASS_THRU_SIZE (AVRC_MSG_PASS_THRU_OFFSET + BT_HDR_SIZE + 4) - -#define AVRC_MIN_BROWSE_SIZE (AVCT_BROWSE_OFFSET + BT_HDR_SIZE + AVRC_MIN_BROWSE_HDR_SIZE) - -#define AVRC_CTRL_PKT_LEN(pf, pk) {pf = (UINT8 *)((pk) + 1) + (pk)->offset + 2;} - -#define AVRC_MAX_CTRL_DATA_LEN (AVRC_PACKET_LEN) - -/***************************************************************************** -** Type definitions -*****************************************************************************/ - -#if (AVRC_METADATA_INCLUDED == TRUE) -/* type for Metadata fragmentation control block */ -typedef struct { - BT_HDR *p_fmsg; /* the fragmented message */ - UINT8 frag_pdu; /* the PDU ID for fragmentation */ - BOOLEAN frag_enabled; /* fragmentation flag */ -} tAVRC_FRAG_CB; - -/* type for Metadata re-assembly control block */ -typedef struct { - BT_HDR *p_rmsg; /* the received message */ - UINT16 rasm_offset; /* re-assembly flag, the offset of the start fragment */ - UINT8 rasm_pdu; /* the PDU ID for re-assembly */ -} tAVRC_RASM_CB; -#endif - -typedef struct { - tAVRC_CONN_CB ccb[AVCT_NUM_CONN]; -#if (AVRC_METADATA_INCLUDED == TRUE) - tAVRC_FRAG_CB fcb[AVCT_NUM_CONN]; - tAVRC_RASM_CB rcb[AVCT_NUM_CONN]; -#endif - tAVRC_FIND_CBACK *p_cback; /* pointer to application callback */ - tSDP_DISCOVERY_DB *p_db; /* pointer to discovery database */ - UINT16 service_uuid; /* service UUID to search */ - UINT8 trace_level; -} tAVRC_CB; - - - -#ifdef __cplusplus -extern "C" -{ -#endif - -/****************************************************************************** -** Main Control Block -*******************************************************************************/ -#if AVRC_DYNAMIC_MEMORY == FALSE -extern tAVRC_CB avrc_cb; -#else -extern tAVRC_CB *avrc_cb_ptr; -#define avrc_cb (*avrc_cb_ptr) -#endif - -extern BOOLEAN avrc_is_valid_pdu_id(UINT8 pdu_id); -extern BOOLEAN avrc_is_valid_player_attrib_value(UINT8 attrib, UINT8 value); -extern BT_HDR *avrc_alloc_ctrl_pkt (UINT8 pdu); -extern tAVRC_STS avrc_pars_pass_thru(tAVRC_MSG_PASS *p_msg, UINT16 *p_vendor_unique_id); -extern UINT8 avrc_opcode_from_pdu(UINT8 pdu); -extern BOOLEAN avrc_is_valid_opcode(UINT8 opcode); - -#ifdef __cplusplus -} -#endif - -#endif ///AVRC_INCLUDED == TRUE - -#endif /* AVRC_INT_H */ diff --git a/tools/sdk/include/bluedroid/bdaddr.h b/tools/sdk/include/bluedroid/bdaddr.h deleted file mode 100644 index 87acad2e00c..00000000000 --- a/tools/sdk/include/bluedroid/bdaddr.h +++ /dev/null @@ -1,63 +0,0 @@ -/****************************************************************************** - * - * 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 _BDADDR_H_ -#define _BDADDR_H_ - -#include -#include - -#include "bt_defs.h" -#include "hash_map.h" - -// Note: the string representation of a bdaddr is expected to have the format -// xx:xx:xx:xx:xx:xx -// where each 'x' is a hex digit. The API presented in this header will accept -// both uppercase and lowercase digits but will only ever produce lowercase -// digits. - -// Returns true if |addr| is the empty address (00:00:00:00:00:00). -// |addr| may not be NULL. -bool bdaddr_is_empty(const bt_bdaddr_t *addr); - -// Returns true if |first| and |second| refer to the same address. Neither -// may be NULL. -bool bdaddr_equals(const bt_bdaddr_t *first, const bt_bdaddr_t *second); - -// Returns destination bdaddr |dest| after copying |src| to |dest|. -// |dest| and |src| must not be NULL. -bt_bdaddr_t *bdaddr_copy(bt_bdaddr_t *dest, const bt_bdaddr_t *src); - -// Makes a string representation of |addr| and places it into |string|. |size| -// refers to the size of |string|'s buffer and must be >= 18. On success, this -// function returns |string|, otherwise it returns NULL. Neither |addr| nor |string| -// may be NULL. -const char *bdaddr_to_string(const bt_bdaddr_t *addr, char *string, size_t size); - -// Returns true if |string| represents a Bluetooth address. |string| may not be NULL. -bool string_is_bdaddr(const char *string); - -// Converts |string| to bt_bdaddr_t and places it in |addr|. If |string| does not -// represent a Bluetooth address, |addr| is not modified and this function returns -// false. Otherwise, it returns true. Neither |string| nor |addr| may be NULL. -bool string_to_bdaddr(const char *string, bt_bdaddr_t *addr); - -// A hash function tailored for bdaddrs. -hash_index_t hash_function_bdaddr(const void *key); - -#endif diff --git a/tools/sdk/include/bluedroid/blufi_int.h b/tools/sdk/include/bluedroid/blufi_int.h deleted file mode 100644 index eab51ad85c4..00000000000 --- a/tools/sdk/include/bluedroid/blufi_int.h +++ /dev/null @@ -1,185 +0,0 @@ -// 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 __BLUFI_INT_H__ -#define __BLUFI_INT_H__ - -#define BTC_BLUFI_GREAT_VER 0x01 //Version + Subversion -#define BTC_BLUFI_SUB_VER 0x02 //Version + Subversion -#define BTC_BLUFI_VERSION ((BTC_BLUFI_GREAT_VER<<8)|BTC_BLUFI_SUB_VER) //Version + Subversion - -/* service engine control block */ -typedef struct { - /* Protocol reference */ - tGATT_IF gatt_if; - UINT8 srvc_inst; - UINT16 handle_srvc; - UINT16 handle_char_p2e; - UINT16 handle_char_e2p; - UINT16 handle_descr_e2p; - UINT16 conn_id; - BOOLEAN is_connected; - BD_ADDR remote_bda; - UINT32 trans_id; - UINT8 congest; - UINT16 frag_size; -#define BLUFI_PREPAIR_BUF_MAX_SIZE 1024 - uint8_t *prepare_buf; - int prepare_len; - /* Control reference */ - esp_blufi_callbacks_t *cbs; - BOOLEAN enabled; - uint8_t send_seq; - uint8_t recv_seq; - uint8_t sec_mode; - uint8_t *aggr_buf; - uint16_t total_len; - uint16_t offset; -} tBLUFI_ENV; - -/* BLUFI protocol */ -struct blufi_hdr{ - uint8_t type; - uint8_t fc; - uint8_t seq; - uint8_t data_len; - uint8_t data[0]; -}; -typedef struct blufi_hdr blufi_hd_t; - -struct blufi_frag_hdr { - uint8_t type; - uint8_t fc; - uint8_t seq; - uint8_t data_len; - uint16_t total_len; - uint8_t content[0]; -}; -typedef struct blufi_frag_hdr blufi_frag_hdr_t; - -#define BLUFI_DATA_SEC_MODE_CHECK_MASK 0x01 -#define BLUFI_DATA_SEC_MODE_ENC_MASK 0x02 -#define BLUFI_CTRL_SEC_MODE_CHECK_MASK 0x10 -#define BLUFI_CTRL_SEC_MODE_ENC_MASK 0x20 - -// packet type -#define BLUFI_TYPE_MASK 0x03 -#define BLUFI_TYPE_SHIFT 0 -#define BLUFI_SUBTYPE_MASK 0xFC -#define BLUFI_SUBTYPE_SHIFT 2 - -#define BLUFI_GET_TYPE(type) ((type) & BLUFI_TYPE_MASK) -#define BLUFI_GET_SUBTYPE(type) (((type) & BLUFI_SUBTYPE_MASK) >>BLUFI_SUBTYPE_SHIFT) -#define BLUFI_BUILD_TYPE(type, subtype) (((type) & BLUFI_TYPE_MASK) | ((subtype)< -#include -#include "bt_trace.h" -#include "bt_target.h" - -#define UNUSED(x) (void)(x) - -#ifndef SIZE_MAX -#define SIZE_MAX 254 -#endif -/*Timer Related Defination*/ - -//by Snake.T -typedef void (TIMER_CBACK)(void *p_tle); -typedef struct _tle { - struct _tle *p_next; - struct _tle *p_prev; - TIMER_CBACK *p_cback; - INT32 ticks; - INT32 ticks_initial; - TIMER_PARAM_TYPE param; - TIMER_PARAM_TYPE data; - UINT16 event; - UINT8 in_use; -} TIMER_LIST_ENT; - -#define alarm_timer_t uint32_t -#define alarm_timer_setfn(timer, cb, data) \ -do { \ -} while (0) -#define alarm_timer_arm(timer, to, periodic) \ -do { \ -} while (0) -#define alarm_timer_disarm(timer) \ -do { \ -} while (0) -#define alarm_timer_now() (0) - - -/*Bluetooth Address*/ -typedef struct { - uint8_t address[6]; -} __attribute__ ((__packed__)) bt_bdaddr_t; - -/** Bluetooth 128-bit UUID */ -typedef struct { - uint8_t uu[16]; -} bt_uuid_t; - -/** Bluetooth Error Status */ -/** We need to build on this */ - -/* relate to ESP_BT_STATUS_xxx in esp_bt_defs.h */ -typedef enum { - BT_STATUS_SUCCESS = 0, - BT_STATUS_FAIL, - BT_STATUS_NOT_READY, - BT_STATUS_NOMEM, - BT_STATUS_BUSY, - BT_STATUS_DONE, /* request already completed */ - BT_STATUS_UNSUPPORTED, - BT_STATUS_PARM_INVALID, - BT_STATUS_UNHANDLED, - BT_STATUS_AUTH_FAILURE, - BT_STATUS_RMT_DEV_DOWN, - BT_STATUS_AUTH_REJECTED, - BT_STATUS_INVALID_STATIC_RAND_ADDR, - BT_STATUS_PENDING, - BT_STATUS_UNACCEPT_CONN_INTERVAL, - BT_STATUS_PARAM_OUT_OF_RANGE, - BT_STATUS_TIMEOUT, - BT_STATUS_MEMORY_FULL, -} bt_status_t; - -#ifndef CPU_LITTLE_ENDIAN -#define CPU_LITTLE_ENDIAN -#endif - -inline uint16_t swap_byte_16(uint16_t x) -{ - return (((x & 0x00ffU) << 8) | - ((x & 0xff00U) >> 8)); -} - -inline uint32_t swap_byte_32(uint32_t x) -{ - return (((x & 0x000000ffUL) << 24) | - ((x & 0x0000ff00UL) << 8) | - ((x & 0x00ff0000UL) >> 8) | - ((x & 0xff000000UL) >> 24)); -} - -#ifndef ntohs -inline uint16_t ntohs(uint16_t x) -{ -#ifdef CPU_LITTLE_ENDIAN - return swap_byte_16(x); -#else - return x; -#endif -} -#endif /* #ifndef ntohs */ - -#ifndef htons -inline uint16_t htons(uint16_t x) -{ -#ifdef CPU_LITTLE_ENDIAN - return swap_byte_16(x); -#else - return x; -#endif -} -#endif /* #ifndef htons */ - -#ifndef ntohl -inline uint32_t ntohl(uint32_t x) -{ -#ifdef CPU_LITTLE_ENDIAN - return swap_byte_32(x); -#else - return x; -#endif -} -#endif /* #ifndef ntohl*/ - -#ifndef htonl -inline uint32_t htonl(uint32_t x) -{ -#ifdef CPU_LITTLE_ENDIAN - return swap_byte_32(x); -#else - return x; -#endif -} -#endif /* #ifndef htonl*/ - -#endif /* _BT_DEFS_H_ */ diff --git a/tools/sdk/include/bluedroid/bt_sdp.h b/tools/sdk/include/bluedroid/bt_sdp.h deleted file mode 100644 index da7f7744d35..00000000000 --- a/tools/sdk/include/bluedroid/bt_sdp.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 __BT_SDP_H__ -#define __BT_SDP_H__ - -#include -// #include "bluetooth.h" -#include "bt_defs.h" - -#define SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH 15 - -/** - * These events are handled by the state machine - */ -typedef enum { - SDP_TYPE_RAW, // Used to carry raw SDP search data for unknown UUIDs - SDP_TYPE_MAP_MAS, // Message Access Profile - Server - SDP_TYPE_MAP_MNS, // Message Access Profile - Client (Notification Server) - SDP_TYPE_PBAP_PSE, // Phone Book Profile - Server - SDP_TYPE_PBAP_PCE, // Phone Book Profile - Client - SDP_TYPE_OPP_SERVER, // Object Push Profile - SDP_TYPE_SAP_SERVER // SIM Access Profile -} bluetooth_sdp_types; - -typedef struct _bluetooth_sdp_hdr { - bluetooth_sdp_types type; - bt_uuid_t uuid; - uint32_t service_name_length; - char *service_name; - int32_t rfcomm_channel_number; - int32_t l2cap_psm; - int32_t profile_version; -} bluetooth_sdp_hdr; - -/** - * Some signals need additional pointers, hence we introduce a - * generic way to handle these pointers. - */ -typedef struct _bluetooth_sdp_hdr_overlay { - bluetooth_sdp_types type; - bt_uuid_t uuid; - uint32_t service_name_length; - char *service_name; - int32_t rfcomm_channel_number; - int32_t l2cap_psm; - int32_t profile_version; - - // User pointers, only used for some signals - see bluetooth_sdp_ops_record - int user1_ptr_len; - uint8_t *user1_ptr; - int user2_ptr_len; - uint8_t *user2_ptr; -} bluetooth_sdp_hdr_overlay; - -typedef struct _bluetooth_sdp_mas_record { - bluetooth_sdp_hdr_overlay hdr; - uint32_t mas_instance_id; - uint32_t supported_features; - uint32_t supported_message_types; -} bluetooth_sdp_mas_record; - -typedef struct _bluetooth_sdp_mns_record { - bluetooth_sdp_hdr_overlay hdr; - uint32_t supported_features; -} bluetooth_sdp_mns_record; - -typedef struct _bluetooth_sdp_pse_record { - bluetooth_sdp_hdr_overlay hdr; - uint32_t supported_features; - uint32_t supported_repositories; -} bluetooth_sdp_pse_record; - -typedef struct _bluetooth_sdp_pce_record { - bluetooth_sdp_hdr_overlay hdr; -} bluetooth_sdp_pce_record; - -typedef struct _bluetooth_sdp_ops_record { - bluetooth_sdp_hdr_overlay hdr; - int supported_formats_list_len; - uint8_t supported_formats_list[SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH]; -} bluetooth_sdp_ops_record; - -typedef struct _bluetooth_sdp_sap_record { - bluetooth_sdp_hdr_overlay hdr; -} bluetooth_sdp_sap_record; - -typedef union { - bluetooth_sdp_hdr_overlay hdr; - bluetooth_sdp_mas_record mas; - bluetooth_sdp_mns_record mns; - bluetooth_sdp_pse_record pse; - bluetooth_sdp_pce_record pce; - bluetooth_sdp_ops_record ops; - bluetooth_sdp_sap_record sap; -} bluetooth_sdp_record; - -#endif /* __BT_SDP_H__ */ diff --git a/tools/sdk/include/bluedroid/bt_target.h b/tools/sdk/include/bluedroid/bt_target.h deleted file mode 100644 index 5be76cc0a1d..00000000000 --- a/tools/sdk/include/bluedroid/bt_target.h +++ /dev/null @@ -1,1909 +0,0 @@ -/****************************************************************************** - * - * Copyright (c) 2014 The Android Open Source Project - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 BT_TARGET_H -#define BT_TARGET_H - -#ifndef BUILDCFG -#define BUILDCFG -#endif - -/* -#if !defined(HAS_BDROID_BUILDCFG) && !defined(HAS_NO_BDROID_BUILDCFG) -#error "An Android.mk file did not include bdroid_CFLAGS and possibly not bdorid_C_INCLUDES" -#endif -*/ - -#ifdef HAS_BDROID_BUILDCFG -#include "bdroid_buildcfg.h" -#endif - -#include "sdkconfig.h" -#include "bt_types.h" /* This must be defined AFTER buildcfg.h */ - -#include "dyn_mem.h" /* defines static and/or dynamic memory for components */ - -/****************************************************************************** -** -** Classic BT features -** -******************************************************************************/ -#if CONFIG_CLASSIC_BT_ENABLED -#define CLASSIC_BT_INCLUDED TRUE -#define BTC_SM_INCLUDED TRUE -#define BTC_PRF_QUEUE_INCLUDED TRUE -#define BTC_GAP_BT_INCLUDED TRUE -#define BTA_SDP_INCLUDED TRUE -#define SDP_INCLUDED TRUE - -#if CONFIG_A2DP_ENABLE -#define BTA_AR_INCLUDED TRUE -#define BTA_AV_INCLUDED TRUE -#define AVDT_INCLUDED TRUE -#define A2D_INCLUDED TRUE -#define AVCT_INCLUDED TRUE -#define AVRC_INCLUDED TRUE -#define BTC_AV_INCLUDED TRUE -#endif /* CONFIG_A2DP_ENABLE */ - -#if CONFIG_A2DP_SINK_ENABLE -#define BTA_AV_SINK_INCLUDED TRUE -#define BTC_AV_SINK_INCLUDED TRUE -#define SBC_DEC_INCLUDED TRUE -#endif /* CONFIG_A2DP_SINK_ENABLE */ - -#if CONFIG_A2DP_SRC_ENABLE -#define BTC_AV_SRC_INCLUDED TRUE -#define SBC_ENC_INCLUDED TRUE -#endif /* CONFIG_A2DP_SRC_ENABLE */ - -#if CONFIG_BT_SPP_ENABLED -#define RFCOMM_INCLUDED TRUE -#define BTA_JV_INCLUDED TRUE -#define BTC_SPP_INCLUDED TRUE -#endif /* CONFIG_BT_SPP_ENABLED */ - -#endif /* #if CONFIG_CLASSIC_BT_ENABLED */ - -#ifndef CLASSIC_BT_INCLUDED -#define CLASSIC_BT_INCLUDED FALSE -#endif /* CLASSIC_BT_INCLUDED */ - -/****************************************************************************** -** -** BLE features -** -******************************************************************************/ -#if (CONFIG_GATTS_ENABLE) -#define GATTS_INCLUDED TRUE -#else -#define GATTS_INCLUDED FALSE -#endif /* CONFIG_GATTS_ENABLE */ - -#if (CONFIG_GATTC_ENABLE) -#define GATTC_INCLUDED TRUE -#else -#define GATTC_INCLUDED FALSE -#endif /* CONFIG_GATTC_ENABLE */ - -#if (CONFIG_SMP_ENABLE) -#define SMP_INCLUDED TRUE -#define BLE_PRIVACY_SPT TRUE -#else -#define SMP_INCLUDED FALSE -#define BLE_PRIVACY_SPT FALSE -#endif /* CONFIG_GATTC_ENABLE */ - -#if (CONFIG_BT_ACL_CONNECTIONS) -#define MAX_ACL_CONNECTIONS CONFIG_BT_ACL_CONNECTIONS -#define GATT_MAX_PHY_CHANNEL CONFIG_BT_ACL_CONNECTIONS -#endif /* CONFIG_BT_ACL_CONNECTIONS */ - -//------------------Added from bdroid_buildcfg.h--------------------- -#ifndef L2CAP_EXTFEA_SUPPORTED_MASK -#define L2CAP_EXTFEA_SUPPORTED_MASK (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_NO_CRC | L2CAP_EXTFEA_FIXED_CHNLS) -#endif - -#ifndef BTUI_OPS_FORMATS -#define BTUI_OPS_FORMATS (BTA_OP_VCARD21_MASK | BTA_OP_ANY_MASK) -#endif - -#ifndef BTA_RFC_MTU_SIZE -#define BTA_RFC_MTU_SIZE (L2CAP_MTU_SIZE-L2CAP_MIN_OFFSET-RFCOMM_DATA_OVERHEAD) -#endif - -#ifndef SBC_NO_PCM_CPY_OPTION -#define SBC_NO_PCM_CPY_OPTION FALSE -#endif - -#ifndef BT_APP_DEMO -#define BT_APP_DEMO TRUE -#endif - -#ifndef BTIF_INCLUDED -#define BTIF_INCLUDED FALSE -#endif - -/****************************************************************************** -** -** BTC-layer components -** -******************************************************************************/ -#ifndef BTC_GAP_BT_INCLUDED -#define BTC_GAP_BT_INCLUDED FALSE -#endif - -#ifndef BTC_PRF_QUEUE_INCLUDED -#define BTC_PRF_QUEUE_INCLUDED FALSE -#endif - -#ifndef BTC_SM_INCLUDED -#define BTC_SM_INCLUDED FALSE -#endif - -#ifndef BTC_AV_INCLUDED -#define BTC_AV_INCLUDED FALSE -#endif - -#ifndef BTC_AV_SINK_INCLUDED -#define BTC_AV_SINK_INCLUDED FALSE -#endif - -#ifndef BTC_AV_SRC_INCLUDED -#define BTC_AV_SRC_INCLUDED FALSE -#endif - -#ifndef BTC_SPP_INCLUDED -#define BTC_SPP_INCLUDED FALSE -#endif - -#ifndef SBC_DEC_INCLUDED -#define SBC_DEC_INCLUDED FALSE -#endif - -#ifndef SBC_ENC_INCLUDED -#define SBC_ENC_INCLUDED FALSE -#endif - -/****************************************************************************** -** -** BTA-layer components -** -******************************************************************************/ -#ifndef BTA_INCLUDED -#define BTA_INCLUDED TRUE -#endif - -#ifndef BTA_PAN_INCLUDED -#define BTA_PAN_INCLUDED FALSE -#endif - -#ifndef BTA_HH_INCLUDED -#define BTA_HH_INCLUDED FALSE -#endif - -#ifndef BTA_HH_ROLE -#define BTA_HH_ROLE BTA_MASTER_ROLE_PREF -#endif - -#ifndef BTA_HH_LE_INCLUDED -#define BTA_HH_LE_INCLUDED FALSE -#endif - -#ifndef BTA_AR_INCLUDED -#define BTA_AR_INCLUDED FALSE -#endif - -#ifndef BTA_AV_INCLUDED -#define BTA_AV_INCLUDED FALSE -#endif - -#ifndef BTA_AV_SINK_INCLUDED -#define BTA_AV_SINK_INCLUDED FALSE -#endif - -#ifndef BTA_JV_INCLUDED -#define BTA_JV_INCLUDED FALSE -#endif - -#ifndef BTA_SDP_INCLUDED -#define BTA_SDP_INCLUDED FALSE -#endif - -/****************************************************************************** -** -** Stack-layer components -** -******************************************************************************/ -#ifndef AVCT_INCLUDED -#define AVCT_INCLUDED FALSE -#endif - -#ifndef AVDT_INCLUDED -#define AVDT_INCLUDED FALSE -#endif - -/****************************************************************************** -** -** Parameter Configurations for components -** -******************************************************************************/ -#ifndef BTA_DISABLE_DELAY -#define BTA_DISABLE_DELAY 200 /* in milliseconds */ -#endif - -#ifndef BTA_SYS_TIMER_PERIOD -#define BTA_SYS_TIMER_PERIOD 100 -#endif - -#ifndef SBC_FOR_EMBEDDED_LINUX -#define SBC_FOR_EMBEDDED_LINUX TRUE -#endif - -#ifndef AVDT_VERSION -#define AVDT_VERSION 0x0102 -#endif - -#ifndef BTA_AG_AT_MAX_LEN -#define BTA_AG_AT_MAX_LEN 512 -#endif - -#ifndef BTA_AVRCP_FF_RW_SUPPORT -#define BTA_AVRCP_FF_RW_SUPPORT FALSE//TRUE -#endif - -#ifndef BTA_AG_SCO_PKT_TYPES -#define BTA_AG_SCO_PKT_TYPES (BTM_SCO_LINK_ONLY_MASK | BTM_SCO_PKT_TYPES_MASK_EV3 | BTM_SCO_PKT_TYPES_MASK_NO_3_EV3 | BTM_SCO_PKT_TYPES_MASK_NO_2_EV5 | BTM_SCO_PKT_TYPES_MASK_NO_3_EV5) -#endif - -#ifndef BTA_AV_RET_TOUT -#define BTA_AV_RET_TOUT 15 -#endif - -#ifndef PORCHE_PAIRING_CONFLICT -#define PORCHE_PAIRING_CONFLICT TRUE -#endif - -#ifndef BTA_AV_CO_CP_SCMS_T -#define BTA_AV_CO_CP_SCMS_T FALSE//FALSE -#endif - -/* This feature is used to eanble interleaved scan*/ -#ifndef BTA_HOST_INTERLEAVE_SEARCH -#define BTA_HOST_INTERLEAVE_SEARCH FALSE//FALSE -#endif - -#ifndef BT_USE_TRACES -#define BT_USE_TRACES FALSE -#endif - -#ifndef BT_TRACE_BTIF -#define BT_TRACE_BTIF TRUE -#endif - -#ifndef BT_TRACE_VERBOSE -#define BT_TRACE_VERBOSE FALSE -#endif - -#ifndef BTA_DM_SDP_DB_SIZE -#define BTA_DM_SDP_DB_SIZE 8000 -#endif - -#ifndef HL_INCLUDED -#define HL_INCLUDED TRUE -#endif - -#ifndef AG_VOICE_SETTINGS -#define AG_VOICE_SETTINGS HCI_DEFAULT_VOICE_SETTINGS -#endif - -#ifndef BTIF_DM_OOB_TEST -#define BTIF_DM_OOB_TEST FALSE//TRUE -#endif - -// How long to wait before activating sniff mode after entering the -// idle state for FTS, OPS connections -#ifndef BTA_FTS_OPS_IDLE_TO_SNIFF_DELAY_MS -#define BTA_FTS_OPS_IDLE_TO_SNIFF_DELAY_MS 7000 -#endif - -//------------------End added from bdroid_buildcfg.h--------------------- - - -/****************************************************************************** -** -** Buffer Size -** -******************************************************************************/ - -#ifndef BT_DEFAULT_BUFFER_SIZE -#define BT_DEFAULT_BUFFER_SIZE (4096 + 16) -#endif - -#ifndef BT_SMALL_BUFFER_SIZE -#define BT_SMALL_BUFFER_SIZE 660 -#endif - -/* Receives HCI events from the lower-layer. */ -#ifndef HCI_CMD_BUF_SIZE -#define HCI_CMD_BUF_SIZE BT_SMALL_BUFFER_SIZE -#endif - -/* Sends SDP data packets. */ -#ifndef SDP_DATA_BUF_SIZE -#define SDP_DATA_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* Sends RFCOMM command packets. */ -#ifndef RFCOMM_CMD_BUF_SIZE -#define RFCOMM_CMD_BUF_SIZE BT_SMALL_BUFFER_SIZE -#endif - -/* Sends RFCOMM data packets. */ -#ifndef RFCOMM_DATA_BUF_SIZE -#define RFCOMM_DATA_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* Sends L2CAP packets to the peer and HCI messages to the controller. */ -#ifndef L2CAP_CMD_BUF_SIZE -#define L2CAP_CMD_BUF_SIZE BT_SMALL_BUFFER_SIZE -#endif - -#ifndef L2CAP_USER_TX_BUF_SIZE -#define L2CAP_USER_TX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -#ifndef L2CAP_USER_RX_BUF_SIZE -#define L2CAP_USER_RX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* Sends L2CAP segmented packets in ERTM mode */ -#ifndef L2CAP_FCR_TX_BUF_SIZE -#define L2CAP_FCR_TX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* Receives L2CAP segmented packets in ERTM mode */ -#ifndef L2CAP_FCR_RX_BUF_SIZE -#define L2CAP_FCR_RX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -#ifndef L2CAP_FCR_ERTM_BUF_SIZE -#define L2CAP_FCR_ERTM_BUF_SIZE (10240 + 24) -#endif - -/* Number of ACL buffers to assign to LE - if the HCI buffer pool is shared with BR/EDR */ -#ifndef L2C_DEF_NUM_BLE_BUF_SHARED -#define L2C_DEF_NUM_BLE_BUF_SHARED 1 -#endif - -/* Used by BTM when it sends HCI commands to the controller. */ -#ifndef BTM_CMD_BUF_SIZE -#define BTM_CMD_BUF_SIZE BT_SMALL_BUFFER_SIZE -#endif - -#ifndef OBX_LRG_DATA_BUF_SIZE -#define OBX_LRG_DATA_BUF_SIZE (8080 + 26) -#endif - -/* Used to send data to L2CAP. */ -#ifndef GAP_DATA_BUF_SIZE -#define GAP_DATA_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* BNEP data and protocol messages. */ -#ifndef BNEP_BUF_SIZE -#define BNEP_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* AVDTP buffer size for protocol messages */ -#ifndef AVDT_CMD_BUF_SIZE -#define AVDT_CMD_BUF_SIZE BT_SMALL_BUFFER_SIZE -#endif - -/* AVDTP buffer size for media packets in case of fragmentation */ -#ifndef AVDT_DATA_BUF_SIZE -#define AVDT_DATA_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -#ifndef PAN_BUF_SIZE -#define PAN_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* Maximum number of buffers to allocate for PAN */ -#ifndef PAN_BUF_MAX -#define PAN_BUF_MAX 100 -#endif - -/* AVCTP buffer size for protocol messages */ -#ifndef AVCT_CMD_BUF_SIZE -#define AVCT_CMD_BUF_SIZE 288 -#endif - -/* AVRCP buffer size for protocol messages */ -#ifndef AVRC_CMD_BUF_SIZE -#define AVRC_CMD_BUF_SIZE 288 -#endif - -/* AVRCP Metadata buffer size for protocol messages */ -#ifndef AVRC_META_CMD_BUF_SIZE -#define AVRC_META_CMD_BUF_SIZE BT_SMALL_BUFFER_SIZE -#endif - -#ifndef BTA_HL_LRG_DATA_BUF_SIZE -#define BTA_HL_LRG_DATA_BUF_SIZE (10240 + 24) -#endif - -/* GATT Server Database buffer size */ -#ifndef GATT_DB_BUF_SIZE -#define GATT_DB_BUF_SIZE 128 -#endif - -/* GATT Data sending buffer size */ -#ifndef GATT_DATA_BUF_SIZE -#define GATT_DATA_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/****************************************************************************** -** -** HCI Services (H4) -** -******************************************************************************/ - -/* Use 2 second for low-resolution systems, override to 1 for high-resolution systems */ -#ifndef BT_1SEC_TIMEOUT -#define BT_1SEC_TIMEOUT (2) -#endif - -/* Quick Timer */ -/* if L2CAP_FCR_INCLUDED is TRUE then it should have 100 millisecond resolution */ -/* if none of them is included then QUICK_TIMER_TICKS_PER_SEC is set to 0 to exclude quick timer */ -#ifndef QUICK_TIMER_TICKS_PER_SEC -#define QUICK_TIMER_TICKS_PER_SEC 10 /* 100ms timer */ -#endif - -/****************************************************************************** -** -** BTM -** -******************************************************************************/ - -/* Cancel Inquiry on incoming SSP */ -#ifndef BTM_NO_SSP_ON_INQUIRY -#define BTM_NO_SSP_ON_INQUIRY FALSE -#endif - -/* Includes SCO if TRUE */ -#ifndef BTM_SCO_INCLUDED -#define BTM_SCO_INCLUDED FALSE //TRUE /* TRUE includes SCO code */ -#endif - -/* Includes SCO if TRUE */ -#ifndef BTM_SCO_HCI_INCLUDED -#define BTM_SCO_HCI_INCLUDED FALSE /* TRUE includes SCO over HCI code */ -#endif - -/* Includes WBS if TRUE */ -#ifndef BTM_WBS_INCLUDED -#define BTM_WBS_INCLUDED FALSE /* TRUE includes WBS code */ -#endif - -/* This is used to work around a controller bug that doesn't like Disconnect -** issued while there is a role switch in progress -*/ -#ifndef BTM_DISC_DURING_RS -#define BTM_DISC_DURING_RS TRUE -#endif - -/************************** -** Initial SCO TX credit -*************************/ -/* max TX SCO data packet size */ -#ifndef BTM_SCO_DATA_SIZE_MAX -#define BTM_SCO_DATA_SIZE_MAX 240 -#endif - -/* The size in bytes of the BTM inquiry database. 5 As Default */ -#ifndef BTM_INQ_DB_SIZE -#define BTM_INQ_DB_SIZE 5 -#endif - -/* The default scan mode */ -#ifndef BTM_DEFAULT_SCAN_TYPE -#define BTM_DEFAULT_SCAN_TYPE BTM_SCAN_TYPE_INTERLACED -#endif - -/* Should connections to unknown devices be allowed when not discoverable? */ -#ifndef BTM_ALLOW_CONN_IF_NONDISCOVER -#define BTM_ALLOW_CONN_IF_NONDISCOVER TRUE -#endif - -/* Sets the Page_Scan_Window: the length of time that the device is performing a page scan. */ -#ifndef BTM_DEFAULT_CONN_WINDOW -#define BTM_DEFAULT_CONN_WINDOW 0x0012 -#endif - -/* Sets the Page_Scan_Activity: the interval between the start of two consecutive page scans. */ -#ifndef BTM_DEFAULT_CONN_INTERVAL -#define BTM_DEFAULT_CONN_INTERVAL 0x0800 -#endif - -/* When automatic inquiry scan is enabled, this sets the inquiry scan window. */ -#ifndef BTM_DEFAULT_DISC_WINDOW -#define BTM_DEFAULT_DISC_WINDOW 0x0012 -#endif - -/* When automatic inquiry scan is enabled, this sets the inquiry scan interval. */ -#ifndef BTM_DEFAULT_DISC_INTERVAL -#define BTM_DEFAULT_DISC_INTERVAL 0x0800 -#endif - -/* -* {SERVICE_CLASS, MAJOR_CLASS, MINOR_CLASS} -* -* SERVICE_CLASS:0x5A (Bit17 -Networking,Bit19 - Capturing,Bit20 -Object Transfer,Bit22 -Telephony) -* MAJOR_CLASS:0x02 - PHONE -* MINOR_CLASS:0x0C - SMART_PHONE -* -*/ -#define BTA_DM_COD_SMARTPHONE {0x5A, 0x02, 0x0C} - -/* -* {SERVICE_CLASS, MAJOR_CLASS, MINOR_CLASS} -* -* SERVICE_CLASS:0x2C (Bit21 - Audio, Bit19 - Capturing) -* MAJOR_CLASS:0x04 - Audio/Video -* MINOR_CLASS:0x05 - LoudSpeaker -*/ -#define BTA_DM_COD_LOUDSPEAKER {0x2C, 0x04, 0x14} - -/* Default class of device */ -#ifndef BTA_DM_COD -#define BTA_DM_COD BTA_DM_COD_LOUDSPEAKER -#endif - -/* The number of SCO links. */ -#ifndef BTM_MAX_SCO_LINKS -#if (CLASSIC_BT_INCLUDED == TRUE) -#define BTM_MAX_SCO_LINKS 1 //3 -#else ///CLASSIC_BT_INCLUDED == TRUE -#define BTM_MAX_SCO_LINKS 0 -#endif ///CLASSIC_BT_INCLUDED == TRUE -#endif - -/* The preferred type of SCO links (2-eSCO, 0-SCO). */ -#ifndef BTM_DEFAULT_SCO_MODE -#define BTM_DEFAULT_SCO_MODE 2 -#endif - -/* The number of security records for peer devices. 100 AS Default*/ -#ifndef BTM_SEC_MAX_DEVICE_RECORDS -#if SMP_INCLUDED == TRUE -#define BTM_SEC_MAX_DEVICE_RECORDS 15 // 100 -#else -#define BTM_SEC_MAX_DEVICE_RECORDS 8 -#endif /* SMP_INCLUDED == TRUE */ -#endif - -/* The number of security records for services. 32 AS Default*/ -#ifndef BTM_SEC_MAX_SERVICE_RECORDS -#define BTM_SEC_MAX_SERVICE_RECORDS 8 // 32 -#endif - -/* If True, force a retrieval of remote device name for each bond in case it's changed */ -#ifndef BTM_SEC_FORCE_RNR_FOR_DBOND -#define BTM_SEC_FORCE_RNR_FOR_DBOND FALSE -#endif - -/* Maximum device name length used in btm database. Up to 248*/ -#ifndef BTM_MAX_REM_BD_NAME_LEN -#define BTM_MAX_REM_BD_NAME_LEN 64 -#endif - -/* Maximum local device name length stored btm database. - '0' disables storage of the local name in BTM */ -#ifndef BTM_MAX_LOC_BD_NAME_LEN -#define BTM_MAX_LOC_BD_NAME_LEN 64 -#endif - -/* Fixed Default String. When this is defined as null string, the device's - * product model name is used as the default local name. - */ -#ifndef BTM_DEF_LOCAL_NAME -#define BTM_DEF_LOCAL_NAME "" -#endif - -/* Maximum service name stored with security authorization (0 if not needed) */ -#ifndef BTM_SEC_SERVICE_NAME_LEN -#define BTM_SEC_SERVICE_NAME_LEN BT_MAX_SERVICE_NAME_LEN -#endif - -/* Maximum length of the service name. */ -#ifndef BT_MAX_SERVICE_NAME_LEN -#define BT_MAX_SERVICE_NAME_LEN 21 -#endif - -/* ACL buffer size in HCI Host Buffer Size command. */ -#ifndef BTM_ACL_BUF_SIZE -#define BTM_ACL_BUF_SIZE 0 -#endif - -/* The maximum number of clients that can register with the power manager. */ -#ifndef BTM_MAX_PM_RECORDS -#define BTM_MAX_PM_RECORDS 2 -#endif - -/* This is set to show debug trace messages for the power manager. */ -#ifndef BTM_PM_DEBUG -#define BTM_PM_DEBUG FALSE -#endif - -/* This is set to TRUE if link is to be unparked due to BTM_CreateSCO API. */ -#ifndef BTM_SCO_WAKE_PARKED_LINK -#define BTM_SCO_WAKE_PARKED_LINK TRUE -#endif - -/* If the user does not respond to security process requests within this many seconds, - * a negative response would be sent automatically. - * 30 is LMP response timeout value */ -#ifndef BTM_SEC_TIMEOUT_VALUE -#define BTM_SEC_TIMEOUT_VALUE 35 -#endif - -/* Maximum number of callbacks that can be registered using BTM_RegisterForVSEvents */ -#ifndef BTM_MAX_VSE_CALLBACKS -#define BTM_MAX_VSE_CALLBACKS 3 -#endif - -/****************************************** -** Lisbon Features -*******************************************/ -/* This is set to TRUE if the FEC is required for EIR packet. */ -#ifndef BTM_EIR_DEFAULT_FEC_REQUIRED -#define BTM_EIR_DEFAULT_FEC_REQUIRED TRUE -#endif - -/* The IO capability of the local device (for Simple Pairing) */ -#ifndef BTM_LOCAL_IO_CAPS -#define BTM_LOCAL_IO_CAPS BTM_IO_CAP_NONE -#endif - -#ifndef BTM_LOCAL_IO_CAPS_BLE -#if (BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE) -#define BTM_LOCAL_IO_CAPS_BLE BTM_IO_CAP_KBDISP -#else -#define BTM_LOCAL_IO_CAPS_BLE 4 -#endif ///BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE -#endif - -/* The default MITM Protection Requirement (for Simple Pairing) - * Possible values are BTM_AUTH_SP_YES or BTM_AUTH_SP_NO */ -#ifndef BTM_DEFAULT_AUTH_REQ -#define BTM_DEFAULT_AUTH_REQ BTM_AUTH_SP_NO -#endif - -/* The default MITM Protection Requirement for dedicated bonding using Simple Pairing - * Possible values are BTM_AUTH_AP_YES or BTM_AUTH_AP_NO */ -#ifndef BTM_DEFAULT_DD_AUTH_REQ -#define BTM_DEFAULT_DD_AUTH_REQ BTM_AUTH_AP_YES -#endif - -/* Include Out-of-Band implementation for Simple Pairing */ -#ifndef BTM_OOB_INCLUDED -#define BTM_OOB_INCLUDED TRUE -#endif - -/* TRUE to include Sniff Subrating */ -#ifndef BTM_SSR_INCLUDED -#define BTM_SSR_INCLUDED FALSE -#endif - -/************************* -** End of Lisbon Features -**************************/ - -/* 4.1/4.2 secure connections feature */ -#ifndef SC_MODE_INCLUDED -// Disable AES-CCM (BT 4.1) for BT Classic to workaround controller AES issue. E0 encryption (BT 4.0) will be used. -#define SC_MODE_INCLUDED FALSE -#endif - -/* Used for conformance testing ONLY */ -#ifndef BTM_BLE_CONFORMANCE_TESTING -#define BTM_BLE_CONFORMANCE_TESTING FALSE -#endif - -/****************************************************************************** -** -** L2CAP -** -******************************************************************************/ - -#ifndef L2CAP_CLIENT_INCLUDED -#define L2CAP_CLIENT_INCLUDED FALSE -#endif - -/* The maximum number of simultaneous applications that can register with LE L2CAP. */ -#ifndef BLE_MAX_L2CAP_CLIENTS -#define BLE_MAX_L2CAP_CLIENTS 15 -#endif - - -/* The maximum number of simultaneous links that L2CAP can support. Up to 7*/ -#ifndef MAX_ACL_CONNECTIONS -#define MAX_L2CAP_LINKS 5 -#else -#define MAX_L2CAP_LINKS MAX_ACL_CONNECTIONS -#endif - -/* The maximum number of simultaneous channels that L2CAP can support. Up to 16*/ -#ifndef MAX_L2CAP_CHANNELS -#if (CLASSIC_BT_INCLUDED == TRUE) -#define MAX_L2CAP_CHANNELS 16 -#else -#if (SMP_INCLUDED == FALSE) -#define MAX_L2CAP_CHANNELS MAX_ACL_CONNECTIONS //This is used in the BLE client when start connected with the peer device -#else -#define MAX_L2CAP_CHANNELS (MAX_ACL_CONNECTIONS * 2) //This is used in the BLE client when start connected with the peer device and in SMP -#endif ///SMP_INCLUDED == FALSE -#endif ///CLASSIC_BT_INCLUDED == TRUE -#endif ///MAX_L2CAP_CHANNELS - -/* The maximum number of simultaneous applications that can register with L2CAP. */ -#ifndef MAX_L2CAP_CLIENTS -#if (CLASSIC_BT_INCLUDED == TRUE) -#define MAX_L2CAP_CLIENTS 8 -#else -#define MAX_L2CAP_CLIENTS 1 //Not support to allocate a channel control block in BLE only mode -#endif ///CLASSIC_BT_INCLUDED == TRUE -#endif - -/* The number of seconds of link inactivity before a link is disconnected. */ -#ifndef L2CAP_LINK_INACTIVITY_TOUT -#define L2CAP_LINK_INACTIVITY_TOUT 4 -#endif - -/* The number of seconds of link inactivity after bonding before a link is disconnected. */ -#ifndef L2CAP_BONDING_TIMEOUT -#define L2CAP_BONDING_TIMEOUT 3 -#endif - -/* The time from the HCI connection complete to disconnect if no channel is established. */ -#ifndef L2CAP_LINK_STARTUP_TOUT -#define L2CAP_LINK_STARTUP_TOUT 60 -#endif - -/* The L2CAP MTU; must be in accord with the HCI ACL pool size. */ -#ifndef L2CAP_MTU_SIZE -#define L2CAP_MTU_SIZE 1691 -#endif - -/* The L2CAP MPS over Bluetooth; must be in accord with the FCR tx pool size and ACL down buffer size. */ -#ifndef L2CAP_MPS_OVER_BR_EDR -#define L2CAP_MPS_OVER_BR_EDR 1010 -#endif - -/* If host flow control enabled, this is the number of buffers the controller can have unacknowledged. */ -#ifndef L2CAP_HOST_FC_ACL_BUFS -#define L2CAP_HOST_FC_ACL_BUFS 20 -#endif - -/* This is set to enable L2CAP to take the ACL link out of park mode when ACL data is to be sent. */ -#ifndef L2CAP_WAKE_PARKED_LINK -#define L2CAP_WAKE_PARKED_LINK TRUE -#endif - -/* Whether link wants to be the master or the slave. */ -#ifndef L2CAP_DESIRED_LINK_ROLE -#define L2CAP_DESIRED_LINK_ROLE HCI_ROLE_SLAVE -#endif - -/* Include Non-Flushable Packet Boundary Flag feature of Lisbon */ -#ifndef L2CAP_NON_FLUSHABLE_PB_INCLUDED -#define L2CAP_NON_FLUSHABLE_PB_INCLUDED TRUE -#endif - -/* Minimum number of ACL credit for high priority link */ -#ifndef L2CAP_HIGH_PRI_MIN_XMIT_QUOTA -#define L2CAP_HIGH_PRI_MIN_XMIT_QUOTA 5 -#endif - -/* used for monitoring HCI ACL credit management */ -#ifndef L2CAP_HCI_FLOW_CONTROL_DEBUG -#define L2CAP_HCI_FLOW_CONTROL_DEBUG TRUE -#endif - -/* Used for calculating transmit buffers off of */ -#ifndef L2CAP_NUM_XMIT_BUFFS -#define L2CAP_NUM_XMIT_BUFFS HCI_ACL_BUF_MAX -#endif - -/* Unicast Connectionless Data */ -#ifndef L2CAP_UCD_INCLUDED -#define L2CAP_UCD_INCLUDED FALSE -#endif - -/* Unicast Connectionless Data MTU */ -#ifndef L2CAP_UCD_MTU -#define L2CAP_UCD_MTU L2CAP_MTU_SIZE -#endif - -/* Unicast Connectionless Data Idle Timeout */ -#ifndef L2CAP_UCD_IDLE_TIMEOUT -#define L2CAP_UCD_IDLE_TIMEOUT 2 -#endif - -/* Unicast Connectionless Data Idle Timeout */ -#ifndef L2CAP_UCD_CH_PRIORITY -#define L2CAP_UCD_CH_PRIORITY L2CAP_CHNL_PRIORITY_MEDIUM -#endif - -/* Used for features using fixed channels; set to zero if no fixed channels supported (BLE, etc.) */ -/* Excluding L2CAP signaling channel and UCD */ -#ifndef L2CAP_NUM_FIXED_CHNLS -#if (CLASSIC_BT_INCLUDED == TRUE) -#define L2CAP_NUM_FIXED_CHNLS 32 -#else -#define L2CAP_NUM_FIXED_CHNLS 3 //There are just three fix channel in the BLE only mode(gatt,signal,smp) -#endif ///CLASSIC_BT_INCLUDED == TRUE -#endif - -/* First fixed channel supported */ -#ifndef L2CAP_FIRST_FIXED_CHNL -#define L2CAP_FIRST_FIXED_CHNL 4 -#endif - -#ifndef L2CAP_LAST_FIXED_CHNL -#define L2CAP_LAST_FIXED_CHNL (L2CAP_FIRST_FIXED_CHNL + L2CAP_NUM_FIXED_CHNLS - 1) -#endif - -/* Round Robin service channels in link */ -#ifndef L2CAP_ROUND_ROBIN_CHANNEL_SERVICE -#define L2CAP_ROUND_ROBIN_CHANNEL_SERVICE TRUE -#endif - -/* Used for calculating transmit buffers off of */ -#ifndef L2CAP_NUM_XMIT_BUFFS -#define L2CAP_NUM_XMIT_BUFFS HCI_ACL_BUF_MAX -#endif - -/* used for monitoring eL2CAP data flow */ -#ifndef L2CAP_ERTM_STATS -#define L2CAP_ERTM_STATS FALSE -#endif - -/* Used for conformance testing ONLY: When TRUE lets scriptwrapper overwrite info response */ -#ifndef L2CAP_CONFORMANCE_TESTING -#define L2CAP_CONFORMANCE_TESTING FALSE -#endif - -/* - * Max bytes per connection to buffer locally before dropping the - * connection if local client does not receive it - default is 1MB - */ -#ifndef L2CAP_MAX_RX_BUFFER -#define L2CAP_MAX_RX_BUFFER 0x100000 -#endif - - -#ifndef TIMER_PARAM_TYPE -#define TIMER_PARAM_TYPE UINT32 -#endif - -/****************************************************************************** -** -** BLE -** -******************************************************************************/ - -#ifndef BLE_INCLUDED -#define BLE_INCLUDED TRUE -#endif - -#ifndef BLE_ANDROID_CONTROLLER_SCAN_FILTER -#define BLE_ANDROID_CONTROLLER_SCAN_FILTER TRUE -#endif - -#ifndef LOCAL_BLE_CONTROLLER_ID -#define LOCAL_BLE_CONTROLLER_ID (1) -#endif - -/* - * Toggles support for general LE privacy features such as remote address - * resolution, local address rotation etc. - */ -#ifndef BLE_PRIVACY_SPT -#define BLE_PRIVACY_SPT FALSE -#endif - -/* - * Enables or disables support for local privacy (ex. address rotation) - */ -#ifndef BLE_LOCAL_PRIVACY_ENABLED -#define BLE_LOCAL_PRIVACY_ENABLED TRUE -#endif - -/* - * Toggles support for vendor specific extensions such as RPA offloading, - * feature discovery, multi-adv etc. - */ -#ifndef BLE_VND_INCLUDED -#define BLE_VND_INCLUDED FALSE -#endif - -#ifndef BTM_BLE_ADV_TX_POWER -#define BTM_BLE_ADV_TX_POWER {-21, -15, -7, 1, 9} -#endif - - -#ifndef BLE_BATCH_SCAN_INCLUDED -#define BLE_BATCH_SCAN_INCLUDED TRUE -#endif - -/****************************************************************************** -** -** ATT/GATT Protocol/Profile Settings -** -******************************************************************************/ -#ifndef GATT_INCLUDED -#if BLE_INCLUDED == TRUE -#define GATT_INCLUDED TRUE -#else -#define GATT_INCLUDED FALSE -#endif -#endif - -#ifndef BTA_GATT_INCLUDED -#if BLE_INCLUDED == TRUE -#define BTA_GATT_INCLUDED TRUE -#else -#define BTA_GATT_INCLUDED FALSE -#endif -#endif - -#if BTA_GATT_INCLUDED == TRUE && BLE_INCLUDED == FALSE -#error "can't have GATT without BLE" -#endif - -#ifndef BLE_LLT_INCLUDED -#define BLE_LLT_INCLUDED TRUE -#endif - -/* Added this marco to fixed the android 7.0 will lead to update connection parameters - collision when the slave sent the HCI_BLE_UPD_LL_CONN_PARAMS comment to the controller - request the master to update connection parameters directly. */ -#ifndef BLE_SLAVE_UPD_CONN_PARAMS -#define BLE_SLAVE_UPD_CONN_PARAMS FALSE -#endif - -#ifndef ATT_INCLUDED -#define ATT_INCLUDED TRUE -#endif - -#ifndef ATT_DEBUG -#define ATT_DEBUG FALSE//TRUE -#endif - -#ifndef BLE_PERIPHERAL_MODE_SUPPORT -#define BLE_PERIPHERAL_MODE_SUPPORT TRUE -#endif - -#ifndef BLE_DELAY_REQUEST_ENC -/* This flag is to work around IPHONE problem, We need to wait for iPhone ready - before send encryption request to iPhone */ -#define BLE_DELAY_REQUEST_ENC FALSE -#endif - -#ifndef GAP_TRANSPORT_SUPPORTED -#define GAP_TRANSPORT_SUPPORTED GATT_TRANSPORT_LE_BR_EDR -#endif - -#ifndef GATTP_TRANSPORT_SUPPORTED -#define GATTP_TRANSPORT_SUPPORTED GATT_TRANSPORT_LE_BR_EDR -#endif - -#ifndef GATT_MAX_SR_PROFILES -#define GATT_MAX_SR_PROFILES 8 /* max is 32 */ -#endif - -#ifndef GATT_MAX_APPS -#define GATT_MAX_APPS 8 /* MAX is 32 note: 2 apps used internally GATT and GAP */ -#endif - -#ifndef GATT_MAX_PHY_CHANNEL -#define GATT_MAX_PHY_CHANNEL 7 -#endif - -/* Used for conformance testing ONLY */ -#ifndef GATT_CONFORMANCE_TESTING -#define GATT_CONFORMANCE_TESTING FALSE -#endif - -/* number of background connection device allowence, ideally to be the same as WL size -*/ -#ifndef GATT_MAX_BG_CONN_DEV -#define GATT_MAX_BG_CONN_DEV 8 /*MAX is 32*/ -#endif - -/****************************************************************************** -** -** GATT -** -******************************************************************************/ -#ifndef GATTC_INCLUDED -#if BLE_INCLUDED == TRUE -#define GATTC_INCLUDED FALSE -#else -#define GATTC_INCLUDED FALSE -#endif -#endif - -#ifndef GATTS_INCLUDED -#if BLE_INCLUDED == TRUE -#define GATTS_INCLUDED TRUE -#else -#define GATTS_INCLUDED FALSE -#endif -#endif - - -#if SMP_INCLUDED == TRUE && BLE_INCLUDED == FALSE -#error "can't have SMP without BLE" -#endif - - -/****************************************************************************** -** -** SMP -** -******************************************************************************/ -#ifndef SMP_INCLUDED -#if BLE_INCLUDED == TRUE -#define SMP_INCLUDED FALSE -#else -#define SMP_INCLUDED FALSE -#endif -#endif - -#if SMP_INCLUDED == TRUE && BLE_INCLUDED == FALSE -#error "can't have SMP without BLE" -#endif - -#ifndef SMP_DEBUG -#define SMP_DEBUG FALSE -#endif - -#ifndef SMP_DEFAULT_AUTH_REQ -#define SMP_DEFAULT_AUTH_REQ SMP_AUTH_NB_ENC_ONLY -#endif - -#ifndef SMP_MAX_ENC_KEY_SIZE -#define SMP_MAX_ENC_KEY_SIZE 16 -#endif - -#ifndef SMP_MIN_ENC_KEY_SIZE -#define SMP_MIN_ENC_KEY_SIZE 7 -#endif - -/* minimum link timeout after SMP pairing is done, leave room for key exchange - and racing condition for the following service connection. - Prefer greater than 0 second, and no less than default inactivity link idle - timer(L2CAP_LINK_INACTIVITY_TOUT) in l2cap) */ -#ifndef SMP_LINK_TOUT_MIN -#if (L2CAP_LINK_INACTIVITY_TOUT > 0) -#define SMP_LINK_TOUT_MIN L2CAP_LINK_INACTIVITY_TOUT -#else -#define SMP_LINK_TOUT_MIN 2 -#endif -#endif -/****************************************************************************** -** -** SDP -** -******************************************************************************/ - -#ifndef SDP_INCLUDED -#define SDP_INCLUDED FALSE -#endif - -/* This is set to enable SDP server functionality. */ -#ifndef SDP_SERVER_ENABLED -#if SDP_INCLUDED == TRUE -#define SDP_SERVER_ENABLED TRUE -#else -#define SDP_SERVER_ENABLED FALSE -#endif -#endif - -/* This is set to enable SDP client functionality. */ -#ifndef SDP_CLIENT_ENABLED -#if SDP_INCLUDED == TRUE -#define SDP_CLIENT_ENABLED TRUE -#else -#define SDP_CLIENT_ENABLED FALSE -#endif -#endif - -/* The maximum number of SDP records the server can support. */ -#ifndef SDP_MAX_RECORDS -#define SDP_MAX_RECORDS 6 /*max is 30*/ -#endif - -/* The maximum number of attributes in each record. */ -#ifndef SDP_MAX_REC_ATTR -#define SDP_MAX_REC_ATTR 8 -#endif - -#ifndef SDP_MAX_PAD_LEN -#define SDP_MAX_PAD_LEN 300 -#endif - -/* The maximum length, in bytes, of an attribute. */ -#ifndef SDP_MAX_ATTR_LEN -#define SDP_MAX_ATTR_LEN 400 -#endif - -/* The maximum number of attribute filters supported by SDP databases. */ -#ifndef SDP_MAX_ATTR_FILTERS -#define SDP_MAX_ATTR_FILTERS 15 -#endif - -/* The maximum number of UUID filters supported by SDP databases. */ -#ifndef SDP_MAX_UUID_FILTERS -#define SDP_MAX_UUID_FILTERS 3 -#endif - -/* The maximum number of record handles retrieved in a search. */ -#ifndef SDP_MAX_DISC_SERVER_RECS -#define SDP_MAX_DISC_SERVER_RECS 21 -#endif - -/* The size of a scratchpad buffer, in bytes, for storing the response to an attribute request. */ -#ifndef SDP_MAX_LIST_BYTE_COUNT -#define SDP_MAX_LIST_BYTE_COUNT 4096 -#endif - -/* The maximum number of parameters in an SDP protocol element. */ -#ifndef SDP_MAX_PROTOCOL_PARAMS -#define SDP_MAX_PROTOCOL_PARAMS 2 -#endif - -/* The maximum number of simultaneous client and server connections. */ -#ifndef SDP_MAX_CONNECTIONS -#define SDP_MAX_CONNECTIONS 2 // 4 -#endif - -/* The MTU size for the L2CAP configuration. */ -#ifndef SDP_MTU_SIZE -#define SDP_MTU_SIZE 672 -#endif - -/* The flush timeout for the L2CAP configuration. */ -#ifndef SDP_FLUSH_TO -#define SDP_FLUSH_TO 0xFFFF -#endif - -/* The name for security authorization. */ -#ifndef SDP_SERVICE_NAME -#define SDP_SERVICE_NAME "Service Discovery" -#endif - -/* The security level for BTM. */ -#ifndef SDP_SECURITY_LEVEL -#define SDP_SECURITY_LEVEL BTM_SEC_NONE -#endif - -/****************************************************************************** -** -** RFCOMM -** -******************************************************************************/ -#ifndef RFCOMM_INCLUDED -#define RFCOMM_INCLUDED FALSE -#endif - -/* The maximum number of ports supported. */ -#ifndef MAX_RFC_PORTS -#define MAX_RFC_PORTS 16 /*max is 30*/ -#endif - -/* The maximum simultaneous links to different devices. */ -#ifndef MAX_ACL_CONNECTIONS -#define MAX_BD_CONNECTIONS 3 /*max is 7*/ -#else -#define MAX_BD_CONNECTIONS MAX_ACL_CONNECTIONS -#endif - -/* The port receive queue low watermark level, in bytes. */ -#ifndef PORT_RX_LOW_WM -#define PORT_RX_LOW_WM (BTA_RFC_MTU_SIZE * PORT_RX_BUF_LOW_WM) -#endif - -/* The port receive queue high watermark level, in bytes. */ -#ifndef PORT_RX_HIGH_WM -#define PORT_RX_HIGH_WM (BTA_RFC_MTU_SIZE * PORT_RX_BUF_HIGH_WM) -#endif - -/* The port receive queue critical watermark level, in bytes. */ -#ifndef PORT_RX_CRITICAL_WM -#define PORT_RX_CRITICAL_WM (BTA_RFC_MTU_SIZE * PORT_RX_BUF_CRITICAL_WM) -#endif - -/* The port receive queue low watermark level, in number of buffers. */ -#ifndef PORT_RX_BUF_LOW_WM -#define PORT_RX_BUF_LOW_WM 4 -#endif - -/* The port receive queue high watermark level, in number of buffers. */ -#ifndef PORT_RX_BUF_HIGH_WM -#define PORT_RX_BUF_HIGH_WM 10 -#endif - -/* The port receive queue critical watermark level, in number of buffers. */ -#ifndef PORT_RX_BUF_CRITICAL_WM -#define PORT_RX_BUF_CRITICAL_WM 15 -#endif - -/* The port transmit queue high watermark level, in bytes. */ -#ifndef PORT_TX_HIGH_WM -#define PORT_TX_HIGH_WM (BTA_RFC_MTU_SIZE * PORT_TX_BUF_HIGH_WM) -#endif - -/* The port transmit queue critical watermark level, in bytes. */ -#ifndef PORT_TX_CRITICAL_WM -#define PORT_TX_CRITICAL_WM (BTA_RFC_MTU_SIZE * PORT_TX_BUF_CRITICAL_WM) -#endif - -/* The port transmit queue high watermark level, in number of buffers. */ -#ifndef PORT_TX_BUF_HIGH_WM -#define PORT_TX_BUF_HIGH_WM 10 -#endif - -/* The port transmit queue high watermark level, in number of buffers. */ -#ifndef PORT_TX_BUF_CRITICAL_WM -#define PORT_TX_BUF_CRITICAL_WM 15 -#endif - -/* The RFCOMM multiplexer preferred flow control mechanism. */ -#ifndef PORT_FC_DEFAULT -#define PORT_FC_DEFAULT PORT_FC_CREDIT -#endif - -/* The maximum number of credits receiver sends to peer when using credit-based flow control. */ -#ifndef PORT_CREDIT_RX_MAX -#define PORT_CREDIT_RX_MAX 16 -#endif - -/* The credit low watermark level. */ -#ifndef PORT_CREDIT_RX_LOW -#define PORT_CREDIT_RX_LOW 8 -#endif - -/****************************************************************************** -** -** OBEX -** -******************************************************************************/ - -/* - * Buffer size to reassemble the SDU. - * It will allow buffers to be used that are larger than the L2CAP_MAX_MTU. - */ -#ifndef OBX_USER_RX_BUF_SIZE -#define OBX_USER_RX_BUF_SIZE OBX_LRG_DATA_BUF_SIZE -#endif - -/* - * Buffer size to hold the SDU. - * It will allow buffers to be used that are larger than the L2CAP_MAX_MTU. - */ -#ifndef OBX_USER_TX_BUF_SIZE -#define OBX_USER_TX_BUF_SIZE OBX_LRG_DATA_BUF_SIZE -#endif - -/* Buffer size used to hold MPS segments during SDU reassembly. */ -#ifndef OBX_FCR_RX_BUF_SIZE -#define OBX_FCR_RX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* - * Buffer size used to hold MPS segments used in (re)transmissions. - * The size of each buffer must be able to hold the maximum MPS segment size - * passed in L2CA_SetFCROptions plus BT_HDR (8) + HCI preamble (4) + - * L2CAP_MIN_OFFSET (11 - as of BT 2.1 + EDR Spec). - */ -#ifndef OBX_FCR_TX_BUF_SIZE -#define OBX_FCR_TX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* This option is application when OBX_14_INCLUDED=TRUE -Size of the transmission window when using enhanced retransmission mode. Not used -in basic and streaming modes. Range: 1 - 63 -*/ -#ifndef OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR -#define OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR 20 -#endif - -/* This option is application when OBX_14_INCLUDED=TRUE -Number of transmission attempts for a single I-Frame before taking -Down the connection. Used In ERTM mode only. Value is Ignored in basic and -Streaming modes. -Range: 0, 1-0xFF -0 - infinite retransmissions -1 - single transmission -*/ -#ifndef OBX_FCR_OPT_MAX_TX_B4_DISCNT -#define OBX_FCR_OPT_MAX_TX_B4_DISCNT 20 -#endif - -/* This option is application when OBX_14_INCLUDED=TRUE -Retransmission Timeout -Range: Minimum 2000 (2 secs) on BR/EDR when supporting PBF. - */ -#ifndef OBX_FCR_OPT_RETX_TOUT -#define OBX_FCR_OPT_RETX_TOUT 2000 -#endif - -/* This option is application when OBX_14_INCLUDED=TRUE -Monitor Timeout -Range: Minimum 12000 (12 secs) on BR/EDR when supporting PBF. -*/ -#ifndef OBX_FCR_OPT_MONITOR_TOUT -#define OBX_FCR_OPT_MONITOR_TOUT 12000 -#endif - -/* This option is application when OBX_14_INCLUDED=TRUE -Maximum PDU payload size. -Suggestion: The maximum amount of data that will fit into a 3-DH5 packet. -Range: 2 octets -*/ -#ifndef OBX_FCR_OPT_MAX_PDU_SIZE -#define OBX_FCR_OPT_MAX_PDU_SIZE L2CAP_MPS_OVER_BR_EDR -#endif - - -/****************************************************************************** -** -** BNEP -** -******************************************************************************/ - -#ifndef BNEP_INCLUDED -#define BNEP_INCLUDED FALSE//TRUE -#endif - -/* BNEP status API call is used mainly to get the L2CAP handle */ -#ifndef BNEP_SUPPORTS_STATUS_API -#define BNEP_SUPPORTS_STATUS_API FALSE//TRUE -#endif - -/* -** When BNEP connection changes roles after the connection is established -** we will do an authentication check again on the new role -*/ -#ifndef BNEP_DO_AUTH_FOR_ROLE_SWITCH -#define BNEP_DO_AUTH_FOR_ROLE_SWITCH FALSE//TRUE -#endif - - -/* Maximum number of protocol filters supported. */ -#ifndef BNEP_MAX_PROT_FILTERS -#define BNEP_MAX_PROT_FILTERS 5 -#endif - -/* Maximum number of multicast filters supported. */ -#ifndef BNEP_MAX_MULTI_FILTERS -#define BNEP_MAX_MULTI_FILTERS 5 -#endif - -/* Minimum MTU size. */ -#ifndef BNEP_MIN_MTU_SIZE -#define BNEP_MIN_MTU_SIZE L2CAP_MTU_SIZE -#endif - -/* Preferred MTU size. */ -#ifndef BNEP_MTU_SIZE -#define BNEP_MTU_SIZE BNEP_MIN_MTU_SIZE -#endif - -/* Maximum number of buffers allowed in transmit data queue. */ -#ifndef BNEP_MAX_XMITQ_DEPTH -#define BNEP_MAX_XMITQ_DEPTH 20 -#endif - -/* Maximum number BNEP of connections supported. */ -#ifndef BNEP_MAX_CONNECTIONS -#define BNEP_MAX_CONNECTIONS 7 -#endif - - -/****************************************************************************** -** -** AVDTP -** -******************************************************************************/ - -#ifndef AVDT_INCLUDED -#define AVDT_INCLUDED TRUE -#endif - -/* Include reporting capability in AVDTP */ -#ifndef AVDT_REPORTING -#define AVDT_REPORTING TRUE -#endif - -/* Include multiplexing capability in AVDTP */ -#ifndef AVDT_MULTIPLEXING -#define AVDT_MULTIPLEXING TRUE -#endif - -/* Number of simultaneous links to different peer devices. */ -#ifndef AVDT_NUM_LINKS -#define AVDT_NUM_LINKS 2 -#endif - -/* Number of simultaneous stream endpoints. */ -#ifndef AVDT_NUM_SEPS -#define AVDT_NUM_SEPS 3 -#endif - -/* Number of transport channels setup per media stream(audio or video) */ -#ifndef AVDT_NUM_CHANNELS - -#if AVDT_REPORTING == TRUE -/* signaling, media and reporting channels */ -#define AVDT_NUM_CHANNELS 3 -#else -/* signaling and media channels */ -#define AVDT_NUM_CHANNELS 2 -#endif // AVDT_REPORTING - -#endif // AVDT_NUM_CHANNELS - -/* Number of transport channels setup by AVDT for all media streams - * AVDT_NUM_CHANNELS * Number of simultaneous streams. - */ -#ifndef AVDT_NUM_TC_TBL -#define AVDT_NUM_TC_TBL 6 -#endif - -/* Maximum size in bytes of the codec capabilities information element. */ -#ifndef AVDT_CODEC_SIZE -#define AVDT_CODEC_SIZE 10 -#endif - -/* Maximum size in bytes of the content protection information element. */ -#ifndef AVDT_PROTECT_SIZE -#define AVDT_PROTECT_SIZE 90 -#endif - -/* Maximum number of GKI buffers in the fragment queue (for video frames). - * Must be less than the number of buffers in the buffer pool of size AVDT_DATA_POOL_SIZE */ -#ifndef AVDT_MAX_FRAG_COUNT -#define AVDT_MAX_FRAG_COUNT 15 -#endif - -/****************************************************************************** -** -** PAN -** -******************************************************************************/ - -#ifndef PAN_INCLUDED -#define PAN_INCLUDED FALSE -#endif - -/* This will enable the PANU role */ -#ifndef PAN_SUPPORTS_ROLE_PANU -#define PAN_SUPPORTS_ROLE_PANU FALSE//TRUE -#endif - -/* This will enable the GN role */ -#ifndef PAN_SUPPORTS_ROLE_GN -#define PAN_SUPPORTS_ROLE_GN FALSE//TRUE -#endif - -/* This will enable the NAP role */ -#ifndef PAN_SUPPORTS_ROLE_NAP -#define PAN_SUPPORTS_ROLE_NAP FALSE//TRUE -#endif - -/* This is just for debugging purposes */ -#ifndef PAN_SUPPORTS_DEBUG_DUMP -#define PAN_SUPPORTS_DEBUG_DUMP FALSE//TRUE -#endif - -/* Maximum number of PAN connections allowed */ -#ifndef MAX_PAN_CONNS -#define MAX_PAN_CONNS 7 -#endif - -/* Default service name for NAP role */ -#ifndef PAN_NAP_DEFAULT_SERVICE_NAME -#define PAN_NAP_DEFAULT_SERVICE_NAME "Network Access Point Service" -#endif - -/* Default service name for GN role */ -#ifndef PAN_GN_DEFAULT_SERVICE_NAME -#define PAN_GN_DEFAULT_SERVICE_NAME "Group Network Service" -#endif - -/* Default service name for PANU role */ -#ifndef PAN_PANU_DEFAULT_SERVICE_NAME -#define PAN_PANU_DEFAULT_SERVICE_NAME "PAN User Service" -#endif - -/* Default description for NAP role service */ -#ifndef PAN_NAP_DEFAULT_DESCRIPTION -#define PAN_NAP_DEFAULT_DESCRIPTION "NAP" -#endif - -/* Default description for GN role service */ -#ifndef PAN_GN_DEFAULT_DESCRIPTION -#define PAN_GN_DEFAULT_DESCRIPTION "GN" -#endif - -/* Default description for PANU role service */ -#ifndef PAN_PANU_DEFAULT_DESCRIPTION -#define PAN_PANU_DEFAULT_DESCRIPTION "PANU" -#endif - -/* Default Security level for PANU role. */ -#ifndef PAN_PANU_SECURITY_LEVEL -#define PAN_PANU_SECURITY_LEVEL 0 -#endif - -/* Default Security level for GN role. */ -#ifndef PAN_GN_SECURITY_LEVEL -#define PAN_GN_SECURITY_LEVEL 0 -#endif - -/* Default Security level for NAP role. */ -#ifndef PAN_NAP_SECURITY_LEVEL -#define PAN_NAP_SECURITY_LEVEL 0 -#endif - -/****************************************************************************** -** -** GAP -** -******************************************************************************/ - -#ifndef GAP_INCLUDED -#define GAP_INCLUDED TRUE -#endif - -/* This is set to enable use of GAP L2CAP connections. */ -#ifndef GAP_CONN_INCLUDED -#if (GAP_INCLUDED == TRUE && CLASSIC_BT_INCLUDED == TRUE) -#define GAP_CONN_INCLUDED TRUE -#else -#define GAP_CONN_INCLUDED FALSE -#endif -#endif - -/* This is set to enable posting event for data write */ -#ifndef GAP_CONN_POST_EVT_INCLUDED -#define GAP_CONN_POST_EVT_INCLUDED FALSE -#endif - -/* The maximum number of simultaneous GAP L2CAP connections. */ -#ifndef GAP_MAX_CONNECTIONS -#define GAP_MAX_CONNECTIONS 10 // 30 -#endif - -/* keep the raw data received from SDP server in database. */ -#ifndef SDP_RAW_DATA_INCLUDED -#define SDP_RAW_DATA_INCLUDED TRUE -#endif - -/* Inquiry duration in 1.28 second units. */ -#ifndef SDP_DEBUG -#define SDP_DEBUG TRUE -#endif - -/****************************************************************************** -** -** HID -** -******************************************************************************/ - -#ifndef HID_CONTROL_BUF_SIZE -#define HID_CONTROL_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -#ifndef HID_INTERRUPT_BUF_SIZE -#define HID_INTERRUPT_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/************************************************************************* -** Definitions for Both HID-Host & Device -*/ -#ifndef HID_MAX_SVC_NAME_LEN -#define HID_MAX_SVC_NAME_LEN 32 -#endif - -#ifndef HID_MAX_SVC_DESCR_LEN -#define HID_MAX_SVC_DESCR_LEN 32 -#endif - -#ifndef HID_MAX_PROV_NAME_LEN -#define HID_MAX_PROV_NAME_LEN 32 -#endif - -/************************************************************************* -** Definitions for HID-Host -*/ -#ifndef HID_HOST_INCLUDED -#define HID_HOST_INCLUDED FALSE -#endif - -#ifndef HID_HOST_MAX_DEVICES -#define HID_HOST_MAX_DEVICES 7 -#endif - -#ifndef HID_HOST_MTU -#define HID_HOST_MTU 640 -#endif - -#ifndef HID_HOST_FLUSH_TO -#define HID_HOST_FLUSH_TO 0xffff -#endif - -#ifndef HID_HOST_MAX_CONN_RETRY -#define HID_HOST_MAX_CONN_RETRY (3) -#endif - -#ifndef HID_HOST_REPAGE_WIN -#define HID_HOST_REPAGE_WIN (2) -#endif - -/************************************************************************* - * A2DP Definitions - */ -#ifndef A2D_INCLUDED -#define A2D_INCLUDED FALSE -#endif - -/****************************************************************************** -** -** AVCTP -** -******************************************************************************/ - -/* Number of simultaneous ACL links to different peer devices. */ -#ifndef AVCT_NUM_LINKS -#define AVCT_NUM_LINKS 2 -#endif - -/* Number of simultaneous AVCTP connections. */ -#ifndef AVCT_NUM_CONN -#define AVCT_NUM_CONN 3 -#endif - -/****************************************************************************** -** -** AVRCP -** -******************************************************************************/ -#ifndef AVRC_INCLUDED -#define AVRC_INCLUDED FALSE -#endif - -#ifndef AVRC_METADATA_INCLUDED -#if AVRC_INCLUDED == TRUE -#define AVRC_METADATA_INCLUDED TRUE -#else -#define AVRC_METADATA_INCLUDED FALSE -#endif -#endif - -#ifndef AVRC_ADV_CTRL_INCLUDED -#if AVRC_INCLUDED == TRUE -#define AVRC_ADV_CTRL_INCLUDED TRUE -#else -#define AVRC_ADV_CTRL_INCLUDED FALSE -#endif -#endif - -#ifndef AVRC_CTLR_INCLUDED -#if AVRC_INCLUDED == TRUE -#define AVRC_CTLR_INCLUDED TRUE -#else -#define AVRC_CTLR_INCLUDED FALSE -#endif -#endif - -/****************************************************************************** -** -** MCAP -** -******************************************************************************/ -#ifndef MCA_INCLUDED -#define MCA_INCLUDED FALSE -#endif - -/* The MTU size for the L2CAP configuration on control channel. 48 is the minimal */ -#ifndef MCA_CTRL_MTU -#define MCA_CTRL_MTU 60 -#endif - -/* The maximum number of registered MCAP instances. */ -#ifndef MCA_NUM_REGS -#define MCA_NUM_REGS 12 -#endif - -/* The maximum number of control channels (to difference devices) per registered MCAP instances. */ -#ifndef MCA_NUM_LINKS -#define MCA_NUM_LINKS 3 -#endif - -/* The maximum number of MDEP (including HDP echo) per registered MCAP instances. */ -#ifndef MCA_NUM_DEPS -#define MCA_NUM_DEPS 13 -#endif - -/* The maximum number of MDL link per control channel. */ -#ifndef MCA_NUM_MDLS -#define MCA_NUM_MDLS 4 -#endif - -/* Buffer size to reassemble the SDU. */ -#ifndef MCA_USER_RX_BUF_SIZE -#define MCA_USER_RX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* Buffer size to hold the SDU. */ -#ifndef MCA_USER_TX_BUF_SIZE -#define MCA_USER_TX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* - * Buffer size used to hold MPS segments during SDU reassembly - */ -#ifndef MCA_FCR_RX_BUF_SIZE -#define MCA_FCR_RX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* - * Default buffer size used to hold MPS segments used in (re)transmissions. - * The size of each buffer must be able to hold the maximum MPS segment size - * passed in tL2CAP_FCR_OPTIONS plus BT_HDR (8) + HCI preamble (4) + - * L2CAP_MIN_OFFSET (11 - as of BT 2.1 + EDR Spec). - */ -#ifndef MCA_FCR_TX_BUF_SIZE -#define MCA_FCR_TX_BUF_SIZE BT_DEFAULT_BUFFER_SIZE -#endif - -/* MCAP control channel FCR Option: -Size of the transmission window when using enhanced retransmission mode. -1 is defined by HDP specification for control channel. -*/ -#ifndef MCA_FCR_OPT_TX_WINDOW_SIZE -#define MCA_FCR_OPT_TX_WINDOW_SIZE 1 -#endif - -/* MCAP control channel FCR Option: -Number of transmission attempts for a single I-Frame before taking -Down the connection. Used In ERTM mode only. Value is Ignored in basic and -Streaming modes. -Range: 0, 1-0xFF -0 - infinite retransmissions -1 - single transmission -*/ -#ifndef MCA_FCR_OPT_MAX_TX_B4_DISCNT -#define MCA_FCR_OPT_MAX_TX_B4_DISCNT 20 -#endif - -/* MCAP control channel FCR Option: Retransmission Timeout -The AVRCP specification set a value in the range of 300 - 2000 ms -Timeout (in msecs) to detect Lost I-Frames. Only used in Enhanced retransmission mode. -Range: Minimum 2000 (2 secs) when supporting PBF. - */ -#ifndef MCA_FCR_OPT_RETX_TOUT -#define MCA_FCR_OPT_RETX_TOUT 2000 -#endif - -/* MCAP control channel FCR Option: Monitor Timeout -The AVRCP specification set a value in the range of 300 - 2000 ms -Timeout (in msecs) to detect Lost S-Frames. Only used in Enhanced retransmission mode. -Range: Minimum 12000 (12 secs) when supporting PBF. -*/ -#ifndef MCA_FCR_OPT_MONITOR_TOUT -#define MCA_FCR_OPT_MONITOR_TOUT 12000 -#endif - -/* MCAP control channel FCR Option: Maximum PDU payload size. -The maximum number of payload octets that the local device can receive in a single PDU. -*/ -#ifndef MCA_FCR_OPT_MPS_SIZE -#define MCA_FCR_OPT_MPS_SIZE 1000 -#endif - -/* Shared transport */ -#ifndef NFC_SHARED_TRANSPORT_ENABLED -#define NFC_SHARED_TRANSPORT_ENABLED FALSE -#endif - -/****************************************************************************** -** -** Sleep Mode (Low Power Mode) -** -******************************************************************************/ - -#ifndef HCILP_INCLUDED -#define HCILP_INCLUDED FALSE//TRUE -#endif - -/****************************************************************************** -** -** APPL - Application Task -** -******************************************************************************/ - -#define L2CAP_FEATURE_REQ_ID 73 -#define L2CAP_FEATURE_RSP_ID 173 - -/****************************************************************************** -** -** BTA -** -******************************************************************************/ -/* BTA EIR canned UUID list (default is dynamic) */ -#ifndef BTA_EIR_CANNED_UUID_LIST -#define BTA_EIR_CANNED_UUID_LIST FALSE -#endif - -/* Number of supported customer UUID in EIR */ -#ifndef BTA_EIR_SERVER_NUM_CUSTOM_UUID -#define BTA_EIR_SERVER_NUM_CUSTOM_UUID 8 -#endif - -/* CHLD override for bluedroid */ -#ifndef BTA_AG_CHLD_VAL_ECC -#define BTA_AG_CHLD_VAL_ECC "(0,1,1x,2,2x,3)" -#endif - -#ifndef BTA_AG_CHLD_VAL -#define BTA_AG_CHLD_VAL "(0,1,2,3)" -#endif - -/* Set the CIND to match HFP 1.5 */ -#ifndef BTA_AG_CIND_INFO -#define BTA_AG_CIND_INFO "(\"call\",(0,1)),(\"callsetup\",(0-3)),(\"service\",(0-1)),(\"signal\",(0-5)),(\"roam\",(0,1)),(\"battchg\",(0-5)),(\"callheld\",(0-2))" -#endif - -#ifndef BTA_DM_AVOID_A2DP_ROLESWITCH_ON_INQUIRY -#define BTA_DM_AVOID_A2DP_ROLESWITCH_ON_INQUIRY FALSE//TRUE -#endif - -/****************************************************************************** -** -** Tracing: Include trace header file here. -** -******************************************************************************/ - -/* Enable/disable BTSnoop memory logging */ -#ifndef BTSNOOP_MEM -#define BTSNOOP_MEM FALSE//TRUE -#endif - -#include "bt_trace.h" - -#endif /* BT_TARGET_H */ diff --git a/tools/sdk/include/bluedroid/bt_trace.h b/tools/sdk/include/bluedroid/bt_trace.h deleted file mode 100644 index d6ded219678..00000000000 --- a/tools/sdk/include/bluedroid/bt_trace.h +++ /dev/null @@ -1,625 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _BT_TRACE_H_ -#define _BT_TRACE_H_ -#include "sdkconfig.h" - -#include -#include "bt_types.h" - -#include "esp_log.h" - -#define TAG "BT" - -#define BT_PRINTF(fmt, ...) ESP_LOGE(TAG, fmt, ##__VA_ARGS__) - -#ifndef assert -#define assert(x) do { if (!(x)) BT_PRINTF("bt host error %s %u\n", __FILE__, __LINE__); } while (0) -#endif - -inline void trc_dump_buffer(const char *prefix, uint8_t *data, uint16_t len) -{ - uint16_t i; - - if (!data || !len) { - return; - } - - if (prefix) { - BT_PRINTF("%s: len %d\n", prefix, len); - } - - for (i = 0; i < len; i+=16) { - BT_PRINTF("%02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n", - *(data + i), *(data + i + 1), *(data + i + 2), *(data + i + 3), *(data + i + 4), *(data + i + 5), *(data + i + 6), *(data + i + 7), - *(data + i + 8), *(data + i + 9), *(data + i + 10), *(data + i + 11), *(data + i + 12), *(data + i + 13), *(data + i + 14), *(data + i + 15)); - } - BT_PRINTF("\n"); -} - -#ifdef BTTRC_DUMP_BUFFER -#define BTTRC_DUMP_BUFFER(_prefix, _data, _len) trc_dump_buffer(_prefix, _data, _len) -#else -#define BTTRC_DUMP_BUFFER(_prefix, _data, _len) -#endif - -//static const char BTE_LOGMSG_MODULE[] = "bte_logmsg_module"; - -/* BTrgs);E tracing IDs for debug purposes */ -/* LayerIDs for stack */ -#define BTTRC_ID_STK_GKI 1 -#define BTTRC_ID_STK_BTU 2 -#define BTTRC_ID_STK_HCI 3 -#define BTTRC_ID_STK_L2CAP 4 -#define BTTRC_ID_STK_RFCM_MX 5 -#define BTTRC_ID_STK_RFCM_PRT 6 -#define BTTRC_ID_STK_OBEX_C 7 -#define BTTRC_ID_STK_OBEX_S 8 -#define BTTRC_ID_STK_AVCT 9 -#define BTTRC_ID_STK_AVDT 10 -#define BTTRC_ID_STK_AVRC 11 -#define BTTRC_ID_STK_BIC 12 -#define BTTRC_ID_STK_BIS 13 -#define BTTRC_ID_STK_BNEP 14 -#define BTTRC_ID_STK_BPP 15 -#define BTTRC_ID_STK_BTM_ACL 16 -#define BTTRC_ID_STK_BTM_PM 17 -#define BTTRC_ID_STK_BTM_DEV_CTRL 18 -#define BTTRC_ID_STK_BTM_SVC_DSC 19 -#define BTTRC_ID_STK_BTM_INQ 20 -#define BTTRC_ID_STK_BTM_SCO 21 -#define BTTRC_ID_STK_BTM_SEC 22 -#define BTTRC_ID_STK_HID 24 -#define BTTRC_ID_STK_HSP2 25 -#define BTTRC_ID_STK_CTP 26 -#define BTTRC_ID_STK_FTC 27 -#define BTTRC_ID_STK_FTS 28 -#define BTTRC_ID_STK_GAP 29 -#define BTTRC_ID_STK_HCRP 31 -#define BTTRC_ID_STK_ICP 32 -#define BTTRC_ID_STK_OPC 33 -#define BTTRC_ID_STK_OPS 34 -#define BTTRC_ID_STK_PAN 35 -#define BTTRC_ID_STK_SAP 36 -#define BTTRC_ID_STK_SDP 37 -#define BTTRC_ID_STK_SLIP 38 -#define BTTRC_ID_STK_SPP 39 -#define BTTRC_ID_STK_TCS 40 -#define BTTRC_ID_STK_VDP 41 -#define BTTRC_ID_STK_MCAP 42 -#define BTTRC_ID_STK_GATT 43 -#define BTTRC_ID_STK_SMP 44 -#define BTTRC_ID_STK_NFC 45 -#define BTTRC_ID_STK_NCI 46 -#define BTTRC_ID_STK_IDEP 47 -#define BTTRC_ID_STK_NDEP 48 -#define BTTRC_ID_STK_LLCP 49 -#define BTTRC_ID_STK_RW 50 -#define BTTRC_ID_STK_CE 51 -#define BTTRC_ID_STK_SNEP 52 -#define BTTRC_ID_STK_NDEF 53 - -/* LayerIDs for BTA */ -#define BTTRC_ID_BTA_ACC 55 /* Advanced Camera Client */ -#define BTTRC_ID_BTA_AG 56 /* audio gateway */ -#define BTTRC_ID_BTA_AV 57 /* Advanced audio */ -#define BTTRC_ID_BTA_BIC 58 /* Basic Imaging Client */ -#define BTTRC_ID_BTA_BIS 59 /* Basic Imaging Server */ -#define BTTRC_ID_BTA_BP 60 /* Basic Printing Client */ -#define BTTRC_ID_BTA_CG 61 -#define BTTRC_ID_BTA_CT 62 /* cordless telephony terminal */ -#define BTTRC_ID_BTA_DG 63 /* data gateway */ -#define BTTRC_ID_BTA_DM 64 /* device manager */ -#define BTTRC_ID_BTA_DM_SRCH 65 /* device manager search */ -#define BTTRC_ID_BTA_DM_SEC 66 /* device manager security */ -#define BTTRC_ID_BTA_FM 67 -#define BTTRC_ID_BTA_FTC 68 /* file transfer client */ -#define BTTRC_ID_BTA_FTS 69 /* file transfer server */ -#define BTTRC_ID_BTA_HIDH 70 -#define BTTRC_ID_BTA_HIDD 71 -#define BTTRC_ID_BTA_JV 72 -#define BTTRC_ID_BTA_OPC 73 /* object push client */ -#define BTTRC_ID_BTA_OPS 74 /* object push server */ -#define BTTRC_ID_BTA_PAN 75 /* Personal Area Networking */ -#define BTTRC_ID_BTA_PR 76 /* Printer client */ -#define BTTRC_ID_BTA_SC 77 /* SIM Card Access server */ -#define BTTRC_ID_BTA_SS 78 /* synchronization server */ -#define BTTRC_ID_BTA_SYS 79 /* system manager */ -#define BTTRC_ID_AVDT_SCB 80 /* avdt scb */ -#define BTTRC_ID_AVDT_CCB 81 /* avdt ccb */ - -// btla-specific ++ -/* LayerIDs added for BTL-A. Probably should modify bte_logmsg.c in future. */ -#define BTTRC_ID_STK_RFCOMM 82 -#define BTTRC_ID_STK_RFCOMM_DATA 83 -#define BTTRC_ID_STK_OBEX 84 -#define BTTRC_ID_STK_A2D 85 -#define BTTRC_ID_STK_BIP 86 - -/* LayerIDs for BT APP */ -#define BTTRC_ID_BTAPP 87 -#define BTTRC_ID_BT_PROTOCOL 88 /* this is a temporary solution to allow dynamic - enable/disable of BT_PROTOCOL_TRACE */ -#define BTTRC_ID_MAX_ID BTTRC_ID_BT_PROTOCOL -// btla-specific -- -#define BTTRC_ID_ALL_LAYERS 0xFF /* all trace layers */ -/* Parameter datatypes used in Trace APIs */ -#define BTTRC_PARAM_UINT8 1 -#define BTTRC_PARAM_UINT16 2 -#define BTTRC_PARAM_UINT32 3 - -/* Enables or disables verbose trace information. */ -#ifndef BT_TRACE_VERBOSE -#define BT_TRACE_VERBOSE FALSE -#endif - -/* Enables or disables all trace messages. */ -#ifndef BT_USE_TRACES -#define BT_USE_TRACES FALSE -#endif - -/****************************************************************************** -** -** Trace Levels -** -** The following values may be used for different levels: -** BT_TRACE_LEVEL_NONE 0 * No trace messages to be generated -** BT_TRACE_LEVEL_ERROR 1 * Error condition trace messages -** BT_TRACE_LEVEL_WARNING 2 * Warning condition trace messages -** BT_TRACE_LEVEL_API 3 * API traces -** BT_TRACE_LEVEL_EVENT 4 * Debug messages for events -** BT_TRACE_LEVEL_DEBUG 5 * Debug messages (general) -******************************************************************************/ - -// btla-specific ++ -/* Core Stack default trace levels */ -#ifndef HCI_INITIAL_TRACE_LEVEL -#define HCI_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef BTM_INITIAL_TRACE_LEVEL -#define BTM_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef L2CAP_INITIAL_TRACE_LEVEL -#define L2CAP_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef RFCOMM_INITIAL_TRACE_LEVEL -#define RFCOMM_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef SDP_INITIAL_TRACE_LEVEL -#define SDP_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef GAP_INITIAL_TRACE_LEVEL -#define GAP_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef BNEP_INITIAL_TRACE_LEVEL -#define BNEP_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef PAN_INITIAL_TRACE_LEVEL -#define PAN_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef A2D_INITIAL_TRACE_LEVEL -#define A2D_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef AVDT_INITIAL_TRACE_LEVEL -#define AVDT_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef AVCT_INITIAL_TRACE_LEVEL -#define AVCT_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef AVRC_INITIAL_TRACE_LEVEL -#define AVRC_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef MCA_INITIAL_TRACE_LEVEL -#define MCA_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef HID_INITIAL_TRACE_LEVEL -#define HID_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef APPL_INITIAL_TRACE_LEVEL -#define APPL_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef BT_TRACE_APPL -#define BT_TRACE_APPL BT_USE_TRACES -#endif - -#ifndef GATT_INITIAL_TRACE_LEVEL -#define GATT_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif - -#ifndef SMP_INITIAL_TRACE_LEVEL -#define SMP_INITIAL_TRACE_LEVEL BT_TRACE_LEVEL_WARNING -#endif -// btla-specific -- - -/* Define common tracing for all */ -#define LOG_LEVEL_ERROR 1 -#define LOG_LEVEL_WARN 2 -#define LOG_LEVEL_INFO 3 -#define LOG_LEVEL_DEBUG 4 -#define LOG_LEVEL_VERBOSE 5 -#ifndef LOG_LEVEL -#define LOG_LEVEL LOG_LEVEL_INFO -#endif - -#if !CONFIG_BT_STACK_NO_LOG -#define LOG_ERROR(fmt, args...) do {if (LOG_LEVEL >= LOG_LEVEL_ERROR) BT_PRINTF(fmt,## args);} while(0) -#define LOG_WARN(fmt, args...) do {if (LOG_LEVEL >= LOG_LEVEL_WARN) BT_PRINTF(fmt,## args);} while(0) -#define LOG_INFO(fmt, args...) do {if (LOG_LEVEL >= LOG_LEVEL_INFO) BT_PRINTF(fmt,## args);} while(0) -#define LOG_DEBUG(fmt, args...) do {if (LOG_LEVEL >= LOG_LEVEL_DEBUG) BT_PRINTF(fmt,## args);} while(0) -#define LOG_VERBOSE(fmt, args...) do {if (LOG_LEVEL >= LOG_LEVEL_VERBOSE) BT_PRINTF(fmt,## args);} while(0) - -/* Define tracing for the HCI unit -*/ -#define HCI_TRACE_ERROR(fmt, args...) {if (btu_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt,## args);} -#define HCI_TRACE_WARNING(fmt, args...) {if (btu_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt,## args);} -#define HCI_TRACE_EVENT(fmt, args...) {if (btu_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt,## args);} -#define HCI_TRACE_DEBUG(fmt, args...) {if (btu_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt,## args);} - -/* Define tracing for BTM -*/ -#define BTM_TRACE_ERROR(fmt, args...) {if (btm_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define BTM_TRACE_WARNING(fmt, args...) {if (btm_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define BTM_TRACE_API(fmt, args...) {if (btm_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define BTM_TRACE_EVENT(fmt, args...) {if (btm_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define BTM_TRACE_DEBUG(fmt, args...) {if (btm_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -/* Define tracing for the L2CAP unit -*/ -#define L2CAP_TRACE_ERROR(fmt, args...) {if (l2cb.l2cap_trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define L2CAP_TRACE_WARNING(fmt, args...) {if (l2cb.l2cap_trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define L2CAP_TRACE_API(fmt, args...) {if (l2cb.l2cap_trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define L2CAP_TRACE_EVENT(fmt, args...) {if (l2cb.l2cap_trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define L2CAP_TRACE_DEBUG(fmt, args...) {if (l2cb.l2cap_trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -/* Define tracing for the SDP unit -*/ -#define SDP_TRACE_ERROR(fmt, args...) {if (sdp_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define SDP_TRACE_WARNING(fmt, args...) {if (sdp_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define SDP_TRACE_API(fmt, args...) {if (sdp_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define SDP_TRACE_EVENT(fmt, args...) {if (sdp_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define SDP_TRACE_DEBUG(fmt, args...) {if (sdp_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -/* Define tracing for the RFCOMM unit -*/ -#define RFCOMM_TRACE_ERROR(fmt, args...) {if (rfc_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define RFCOMM_TRACE_WARNING(fmt, args...) {if (rfc_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define RFCOMM_TRACE_API(fmt, args...) {if (rfc_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define RFCOMM_TRACE_EVENT(fmt, args...) {if (rfc_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define RFCOMM_TRACE_DEBUG(fmt, args...) {if (rfc_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -/* Generic Access Profile traces */ -#define GAP_TRACE_ERROR(fmt, args...) {if (gap_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define GAP_TRACE_EVENT(fmt, args...) {if (gap_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define GAP_TRACE_API(fmt, args...) {if (gap_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define GAP_TRACE_WARNING(fmt, args...) {if (gap_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} - -/* define traces for HID Host */ -#define HIDH_TRACE_ERROR(fmt, args...) {if (hh_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define HIDH_TRACE_WARNING(fmt, args...) {if (hh_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define HIDH_TRACE_API(fmt, args...) {if (hh_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define HIDH_TRACE_EVENT(fmt, args...) {if (hh_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define HIDH_TRACE_DEBUG(fmt, args...) {if (hh_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -/* define traces for BNEP */ - -#define BNEP_TRACE_ERROR(fmt, args...) {if (bnep_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define BNEP_TRACE_WARNING(fmt, args...) {if (bnep_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define BNEP_TRACE_API(fmt, args...) {if (bnep_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define BNEP_TRACE_EVENT(fmt, args...) {if (bnep_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define BNEP_TRACE_DEBUG(fmt, args...) {if (bnep_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -/* define traces for PAN */ - -#define PAN_TRACE_ERROR(fmt, args...) {if (pan_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define PAN_TRACE_WARNING(fmt, args...) {if (pan_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define PAN_TRACE_API(fmt, args...) {if (pan_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define PAN_TRACE_EVENT(fmt, args...) {if (pan_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define PAN_TRACE_DEBUG(fmt, args...) {if (pan_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -/* Define tracing for the A2DP profile -*/ -#define A2D_TRACE_ERROR(fmt, args...) {if (a2d_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define A2D_TRACE_WARNING(fmt, args...) {if (a2d_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define A2D_TRACE_EVENT(fmt, args...) {if (a2d_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define A2D_TRACE_DEBUG(fmt, args...) {if (a2d_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} -#define A2D_TRACE_API(fmt, args...) {if (a2d_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} - -/* AVDTP -*/ -#define AVDT_TRACE_ERROR(fmt, args...) {if (avdt_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define AVDT_TRACE_WARNING(fmt, args...) {if (avdt_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define AVDT_TRACE_EVENT(fmt, args...) {if (avdt_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define AVDT_TRACE_DEBUG(fmt, args...) {if (avdt_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} -#define AVDT_TRACE_API(fmt, args...) {if (avdt_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} - -/* Define tracing for the AVCTP protocol -*/ -#define AVCT_TRACE_ERROR(fmt, args...) {if (avct_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define AVCT_TRACE_WARNING(fmt, args...) {if (avct_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define AVCT_TRACE_EVENT(fmt, args...) {if (avct_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define AVCT_TRACE_DEBUG(fmt, args...) {if (avct_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} -#define AVCT_TRACE_API(fmt, args...) {if (avct_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} - -/* Define tracing for the AVRCP profile -*/ -#define AVRC_TRACE_ERROR(fmt, args...) {if (avrc_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define AVRC_TRACE_WARNING(fmt, args...) {if (avrc_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define AVRC_TRACE_EVENT(fmt, args...) {if (avrc_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define AVRC_TRACE_DEBUG(fmt, args...) {if (avrc_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} -#define AVRC_TRACE_API(fmt, args...) {if (avrc_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} - -/* MCAP -*/ -#define MCA_TRACE_ERROR(fmt, args...) {if (mca_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define MCA_TRACE_WARNING(fmt, args...) {if (mca_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define MCA_TRACE_EVENT(fmt, args...) {if (mca_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define MCA_TRACE_DEBUG(fmt, args...) {if (mca_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} -#define MCA_TRACE_API(fmt, args...) {if (mca_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} - -/* Define tracing for the ATT/GATT unit -*/ -#define GATT_TRACE_ERROR(fmt, args...) {if (gatt_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define GATT_TRACE_WARNING(fmt, args...) {if (gatt_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define GATT_TRACE_API(fmt, args...) {if (gatt_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define GATT_TRACE_EVENT(fmt, args...) {if (gatt_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define GATT_TRACE_DEBUG(fmt, args...) {if (gatt_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -/* Define tracing for the SMP unit -*/ -#define SMP_TRACE_ERROR(fmt, args...) {if (smp_cb.trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define SMP_TRACE_WARNING(fmt, args...) {if (smp_cb.trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define SMP_TRACE_API(fmt, args...) {if (smp_cb.trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define SMP_TRACE_EVENT(fmt, args...) {if (smp_cb.trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define SMP_TRACE_DEBUG(fmt, args...) {if (smp_cb.trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} - -extern UINT8 btif_trace_level; - -// define traces for application -#define BTIF_TRACE_ERROR(fmt, args...) {if (btif_trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define BTIF_TRACE_WARNING(fmt, args...) {if (btif_trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define BTIF_TRACE_API(fmt, args...) {if (btif_trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define BTIF_TRACE_EVENT(fmt, args...) {if (btif_trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define BTIF_TRACE_DEBUG(fmt, args...) {if (btif_trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} -#define BTIF_TRACE_VERBOSE(fmt, args...) {if (btif_trace_level >= BT_TRACE_LEVEL_VERBOSE)BT_PRINTF(fmt, ## args);} - -/* define traces for application */ - -#define APPL_TRACE_ERROR(fmt, args...) {if (appl_trace_level >= BT_TRACE_LEVEL_ERROR) BT_PRINTF(fmt, ## args);} -#define APPL_TRACE_WARNING(fmt, args...) {if (appl_trace_level >= BT_TRACE_LEVEL_WARNING) BT_PRINTF(fmt, ## args);} -#define APPL_TRACE_API(fmt, args...) {if (appl_trace_level >= BT_TRACE_LEVEL_API) BT_PRINTF(fmt, ## args);} -#define APPL_TRACE_EVENT(fmt, args...) {if (appl_trace_level >= BT_TRACE_LEVEL_EVENT) BT_PRINTF(fmt, ## args);} -#define APPL_TRACE_DEBUG(fmt, args...) {if (appl_trace_level >= BT_TRACE_LEVEL_DEBUG) BT_PRINTF(fmt, ## args);} -#define APPL_TRACE_VERBOSE(fmt, args...) {if (appl_trace_level >= BT_TRACE_LEVEL_VERBOSE) BT_PRINTF(fmt, ## args);} - -#else -#define LOG_ERROR(fmt, args...) -#define LOG_WARN(fmt, args...) -#define LOG_INFO(fmt, args...) -#define LOG_DEBUG(fmt, args...) -#define LOG_VERBOSE(fmt, args...) - -/* Define tracing for the HCI unit -*/ -#define HCI_TRACE_ERROR(fmt, args...) -#define HCI_TRACE_WARNING(fmt, args...) -#define HCI_TRACE_EVENT(fmt, args...) -#define HCI_TRACE_DEBUG(fmt, args...) - -/* Define tracing for BTM -*/ -#define BTM_TRACE_ERROR(fmt, args...) -#define BTM_TRACE_WARNING(fmt, args...) -#define BTM_TRACE_API(fmt, args...) -#define BTM_TRACE_EVENT(fmt, args...) -#define BTM_TRACE_DEBUG(fmt, args...) - -/* Define tracing for the L2CAP unit -*/ -#define L2CAP_TRACE_ERROR(fmt, args...) -#define L2CAP_TRACE_WARNING(fmt, args...) -#define L2CAP_TRACE_API(fmt, args...) -#define L2CAP_TRACE_EVENT(fmt, args...) -#define L2CAP_TRACE_DEBUG(fmt, args...) - -/* Define tracing for the SDP unit -*/ -#define SDP_TRACE_ERROR(fmt, args...) -#define SDP_TRACE_WARNING(fmt, args...) -#define SDP_TRACE_API(fmt, args...) -#define SDP_TRACE_EVENT(fmt, args...) -#define SDP_TRACE_DEBUG(fmt, args...) - -/* Define tracing for the RFCOMM unit -*/ -#define RFCOMM_TRACE_ERROR(fmt, args...) -#define RFCOMM_TRACE_WARNING(fmt, args...) -#define RFCOMM_TRACE_API(fmt, args...) -#define RFCOMM_TRACE_EVENT(fmt, args...) -#define RFCOMM_TRACE_DEBUG(fmt, args...) - -/* Generic Access Profile traces */ -#define GAP_TRACE_ERROR(fmt, args...) -#define GAP_TRACE_EVENT(fmt, args...) -#define GAP_TRACE_API(fmt, args...) -#define GAP_TRACE_WARNING(fmt, args...) - -/* define traces for HID Host */ -#define HIDH_TRACE_ERROR(fmt, args...) -#define HIDH_TRACE_WARNING(fmt, args...) -#define HIDH_TRACE_API(fmt, args...) -#define HIDH_TRACE_EVENT(fmt, args...) -#define HIDH_TRACE_DEBUG(fmt, args...) - -/* define traces for BNEP */ - -#define BNEP_TRACE_ERROR(fmt, args...) -#define BNEP_TRACE_WARNING(fmt, args...) -#define BNEP_TRACE_API(fmt, args...) -#define BNEP_TRACE_EVENT(fmt, args...) -#define BNEP_TRACE_DEBUG(fmt, args...) - -/* define traces for PAN */ - -#define PAN_TRACE_ERROR(fmt, args...) -#define PAN_TRACE_WARNING(fmt, args...) -#define PAN_TRACE_API(fmt, args...) -#define PAN_TRACE_EVENT(fmt, args...) -#define PAN_TRACE_DEBUG(fmt, args...) - -/* Define tracing for the A2DP profile -*/ -#define A2D_TRACE_ERROR(fmt, args...) -#define A2D_TRACE_WARNING(fmt, args...) -#define A2D_TRACE_EVENT(fmt, args...) -#define A2D_TRACE_DEBUG(fmt, args...) -#define A2D_TRACE_API(fmt, args...) - -/* AVDTP -*/ -#define AVDT_TRACE_ERROR(fmt, args...) -#define AVDT_TRACE_WARNING(fmt, args...) -#define AVDT_TRACE_EVENT(fmt, args...) -#define AVDT_TRACE_DEBUG(fmt, args...) -#define AVDT_TRACE_API(fmt, args...) - -/* Define tracing for the AVCTP protocol -*/ -#define AVCT_TRACE_ERROR(fmt, args...) -#define AVCT_TRACE_WARNING(fmt, args...) -#define AVCT_TRACE_EVENT(fmt, args...) -#define AVCT_TRACE_DEBUG(fmt, args...) -#define AVCT_TRACE_API(fmt, args...) - -/* Define tracing for the AVRCP profile -*/ -#define AVRC_TRACE_ERROR(fmt, args...) -#define AVRC_TRACE_WARNING(fmt, args...) -#define AVRC_TRACE_EVENT(fmt, args...) -#define AVRC_TRACE_DEBUG(fmt, args...) -#define AVRC_TRACE_API(fmt, args...) - -/* MCAP -*/ -#define MCA_TRACE_ERROR(fmt, args...) -#define MCA_TRACE_WARNING(fmt, args...) -#define MCA_TRACE_EVENT(fmt, args...) -#define MCA_TRACE_DEBUG(fmt, args...) -#define MCA_TRACE_API(fmt, args...) - -/* Define tracing for the ATT/GATT unit -*/ -#define GATT_TRACE_ERROR(fmt, args...) -#define GATT_TRACE_WARNING(fmt, args...) -#define GATT_TRACE_API(fmt, args...) -#define GATT_TRACE_EVENT(fmt, args...) -#define GATT_TRACE_DEBUG(fmt, args...) - -/* Define tracing for the SMP unit -*/ -#define SMP_TRACE_ERROR(fmt, args...) -#define SMP_TRACE_WARNING(fmt, args...) -#define SMP_TRACE_API(fmt, args...) -#define SMP_TRACE_EVENT(fmt, args...) -#define SMP_TRACE_DEBUG(fmt, args...) - -extern UINT8 btif_trace_level; - -// define traces for application -#define BTIF_TRACE_ERROR(fmt, args...) -#define BTIF_TRACE_WARNING(fmt, args...) -#define BTIF_TRACE_API(fmt, args...) -#define BTIF_TRACE_EVENT(fmt, args...) -#define BTIF_TRACE_DEBUG(fmt, args...) -#define BTIF_TRACE_VERBOSE(fmt, args...) - -/* define traces for application */ - -#define APPL_TRACE_ERROR(fmt, args...) -#define APPL_TRACE_WARNING(fmt, args...) -#define APPL_TRACE_API(fmt, args...) -#define APPL_TRACE_EVENT(fmt, args...) -#define APPL_TRACE_DEBUG(fmt, args...) -#define APPL_TRACE_VERBOSE(fmt, args...) -#endif ///CONFIG_BT_STACK_NO_LOG - - -/* Simplified Trace Helper Macro -*/ -#define bdld(fmt, args...) \ - do{\ - if((MY_LOG_LEVEL) >= BT_TRACE_LEVEL_DEBUG) \ - BT_PRINTF(fmt, ## args); \ - }while(0) - -#define bdlw(fmt, args...) \ - do{\ - if((MY_LOG_LEVEL) >= BT_TRACE_LEVEL_DEBUG) \ - BT_PRINTF(fmt, ## args); \ - }while(0) - -#define bdle(fmt, args...) \ - do{\ - if((MY_LOG_LEVEL) >= BT_TRACE_LEVEL_DEBUG) \ - BT_PRINTF(fmt, ## args); \ - }while(0) - -#define bdla(assert_if) \ - do{\ - if(((MY_LOG_LEVEL) >= BT_TRACE_LEVEL_ERROR) && !(assert_if)) \ - BT_PRINTF("%s: assert failed\n", #assert_if); \ - }while(0) - -typedef UINT8 tBTTRC_PARAM_TYPE; -typedef UINT8 tBTTRC_LAYER_ID; -typedef UINT8 tBTTRC_TYPE; - -typedef struct { - tBTTRC_LAYER_ID layer_id; - tBTTRC_TYPE type; /* TODO: use tBTTRC_TYPE instead of "classical level 0-5" */ -} tBTTRC_LEVEL; - -typedef UINT8 (tBTTRC_SET_TRACE_LEVEL)( UINT8 ); - -typedef struct { - const tBTTRC_LAYER_ID layer_id_start; - const tBTTRC_LAYER_ID layer_id_end; - tBTTRC_SET_TRACE_LEVEL *p_f; - const char *trc_name; - UINT8 trace_level; -} tBTTRC_FUNC_MAP; - -/* External declaration for appl_trace_level here to avoid to add the declaration in all the files using APPL_TRACExxx macros */ -extern UINT8 appl_trace_level; - -#endif /*_BT_TRACE_H_*/ diff --git a/tools/sdk/include/bluedroid/bt_types.h b/tools/sdk/include/bluedroid/bt_types.h deleted file mode 100644 index ec44cb87198..00000000000 --- a/tools/sdk/include/bluedroid/bt_types.h +++ /dev/null @@ -1,793 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 BT_TYPES_H -#define BT_TYPES_H - -#include -#include - -#ifndef FALSE -# define FALSE false -#endif - -#ifndef TRUE -# define TRUE true -#endif - -typedef uint8_t UINT8; -typedef uint16_t UINT16; -typedef uint32_t UINT32; -typedef uint64_t UINT64; - -typedef int8_t INT8; -typedef int16_t INT16; -typedef int32_t INT32; -typedef bool BOOLEAN; - -#define PACKED __packed -// #define INLINE __inline - -#define BCM_STRCPY_S(x1,x2,x3) strcpy((x1),(x3)) -#define BCM_STRNCPY_S(x1,x2,x3,x4) strncpy((x1),(x3),(x4)) - -/* READ WELL !! -** -** This section defines global events. These are events that cross layers. -** Any event that passes between layers MUST be one of these events. Tasks -** can use their own events internally, but a FUNDAMENTAL design issue is -** that global events MUST be one of these events defined below. -** -** The convention used is the the event name contains the layer that the -** event is going to. -*/ -#define BT_EVT_MASK 0xFF00 -#define BT_SUB_EVT_MASK 0x00FF -#define BT_STATIC_RAND_ADDR_MASK 0xC0 -/* To Bluetooth Upper Layers */ -/************************************/ -#define BT_EVT_TO_BTU_L2C_EVT 0x0900 /* L2CAP event */ -#define BT_EVT_TO_BTU_HCI_EVT 0x1000 /* HCI Event */ -#define BT_EVT_TO_BTU_HCI_BR_EDR_EVT (0x0000 | BT_EVT_TO_BTU_HCI_EVT) /* event from BR/EDR controller */ -#define BT_EVT_TO_BTU_HCI_AMP1_EVT (0x0001 | BT_EVT_TO_BTU_HCI_EVT) /* event from local AMP 1 controller */ -#define BT_EVT_TO_BTU_HCI_AMP2_EVT (0x0002 | BT_EVT_TO_BTU_HCI_EVT) /* event from local AMP 2 controller */ -#define BT_EVT_TO_BTU_HCI_AMP3_EVT (0x0003 | BT_EVT_TO_BTU_HCI_EVT) /* event from local AMP 3 controller */ - -#define BT_EVT_TO_BTU_HCI_ACL 0x1100 /* ACL Data from HCI */ -#define BT_EVT_TO_BTU_HCI_SCO 0x1200 /* SCO Data from HCI */ -#define BT_EVT_TO_BTU_HCIT_ERR 0x1300 /* HCI Transport Error */ - -#define BT_EVT_TO_BTU_SP_EVT 0x1400 /* Serial Port Event */ -#define BT_EVT_TO_BTU_SP_DATA 0x1500 /* Serial Port Data */ - -#define BT_EVT_TO_BTU_HCI_CMD 0x1600 /* HCI command from upper layer */ - - -#define BT_EVT_TO_BTU_L2C_SEG_XMIT 0x1900 /* L2CAP segment(s) transmitted */ - -#define BT_EVT_PROXY_INCOMING_MSG 0x1A00 /* BlueStackTester event: incoming message from target */ - -#define BT_EVT_BTSIM 0x1B00 /* Insight BTSIM event */ -#define BT_EVT_BTISE 0x1C00 /* Insight Script Engine event */ - -/* To LM */ -/************************************/ -#define BT_EVT_TO_LM_HCI_CMD 0x2000 /* HCI Command */ -#define BT_EVT_TO_LM_HCI_ACL 0x2100 /* HCI ACL Data */ -#define BT_EVT_TO_LM_HCI_SCO 0x2200 /* HCI SCO Data */ -#define BT_EVT_TO_LM_HCIT_ERR 0x2300 /* HCI Transport Error */ -#define BT_EVT_TO_LM_LC_EVT 0x2400 /* LC event */ -#define BT_EVT_TO_LM_LC_LMP 0x2500 /* LC Received LMP command frame */ -#define BT_EVT_TO_LM_LC_ACL 0x2600 /* LC Received ACL data */ -#define BT_EVT_TO_LM_LC_SCO 0x2700 /* LC Received SCO data (not used) */ -#define BT_EVT_TO_LM_LC_ACL_TX 0x2800 /* LMP data transmit complete */ -#define BT_EVT_TO_LM_LC_LMPC_TX 0x2900 /* LMP Command transmit complete */ -#define BT_EVT_TO_LM_LOCAL_ACL_LB 0x2a00 /* Data to be locally loopbacked */ -#define BT_EVT_TO_LM_HCI_ACL_ACK 0x2b00 /* HCI ACL Data ack (not used) */ -#define BT_EVT_TO_LM_DIAG 0x2c00 /* LM Diagnostics commands */ - - -#define BT_EVT_TO_BTM_CMDS 0x2f00 -#define BT_EVT_TO_BTM_PM_MDCHG_EVT (0x0001 | BT_EVT_TO_BTM_CMDS) - -#define BT_EVT_TO_TCS_CMDS 0x3000 - -#define BT_EVT_TO_CTP_CMDS 0x3300 - -/* ftp events */ -#define BT_EVT_TO_FTP_SRVR_CMDS 0x3600 -#define BT_EVT_TO_FTP_CLNT_CMDS 0x3700 - -#define BT_EVT_TO_BTU_SAP 0x3800 /* SIM Access Profile events */ - -/* opp events */ -#define BT_EVT_TO_OPP_SRVR_CMDS 0x3900 -#define BT_EVT_TO_OPP_CLNT_CMDS 0x3a00 - -/* gap events */ -#define BT_EVT_TO_GAP_MSG 0x3b00 - -/* for NFC */ -/************************************/ -#define BT_EVT_TO_NFC_NCI 0x4000 /* NCI Command, Notification or Data*/ -#define BT_EVT_TO_NFC_INIT 0x4100 /* Initialization message */ -#define BT_EVT_TO_NCI_LP 0x4200 /* Low power */ -#define BT_EVT_TO_NFC_ERR 0x4300 /* Error notification to NFC Task */ - -#define BT_EVT_TO_NFCCSIM_NCI 0x4a00 /* events to NFCC simulation (NCI packets) */ - -/* HCISU Events */ - -#define BT_EVT_HCISU 0x5000 - -// btla-specific ++ -#define BT_EVT_TO_HCISU_RECONFIG_EVT (0x0001 | BT_EVT_HCISU) -#define BT_EVT_TO_HCISU_UPDATE_BAUDRATE_EVT (0x0002 | BT_EVT_HCISU) -#define BT_EVT_TO_HCISU_LP_ENABLE_EVT (0x0003 | BT_EVT_HCISU) -#define BT_EVT_TO_HCISU_LP_DISABLE_EVT (0x0004 | BT_EVT_HCISU) -// btla-specific -- -#define BT_EVT_TO_HCISU_LP_APP_SLEEPING_EVT (0x0005 | BT_EVT_HCISU) -#define BT_EVT_TO_HCISU_LP_ALLOW_BT_SLEEP_EVT (0x0006 | BT_EVT_HCISU) -#define BT_EVT_TO_HCISU_LP_WAKEUP_HOST_EVT (0x0007 | BT_EVT_HCISU) -#define BT_EVT_TO_HCISU_LP_RCV_H4IBSS_EVT (0x0008 | BT_EVT_HCISU) -#define BT_EVT_TO_HCISU_H5_RESET_EVT (0x0009 | BT_EVT_HCISU) -#define BT_EVT_HCISU_START_QUICK_TIMER (0x000a | BT_EVT_HCISU) - -#define BT_EVT_DATA_TO_AMP_1 0x5100 -#define BT_EVT_DATA_TO_AMP_15 0x5f00 - -/* HSP Events */ - -#define BT_EVT_BTU_HSP2 0x6000 - -#define BT_EVT_TO_BTU_HSP2_EVT (0x0001 | BT_EVT_BTU_HSP2) - -/* BPP Events */ -#define BT_EVT_TO_BPP_PR_CMDS 0x6100 /* Printer Events */ -#define BT_EVT_TO_BPP_SND_CMDS 0x6200 /* BPP Sender Events */ - -/* BIP Events */ -#define BT_EVT_TO_BIP_CMDS 0x6300 - -/* HCRP Events */ - -#define BT_EVT_BTU_HCRP 0x7000 - -#define BT_EVT_TO_BTU_HCRP_EVT (0x0001 | BT_EVT_BTU_HCRP) -#define BT_EVT_TO_BTU_HCRPM_EVT (0x0002 | BT_EVT_BTU_HCRP) - - -#define BT_EVT_BTU_HFP 0x8000 -#define BT_EVT_TO_BTU_HFP_EVT (0x0001 | BT_EVT_BTU_HFP) - -#define BT_EVT_BTU_IPC_EVT 0x9000 -#define BT_EVT_BTU_IPC_LOGMSG_EVT (0x0000 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_ACL_EVT (0x0001 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_BTU_EVT (0x0002 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_L2C_EVT (0x0003 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_L2C_MSG_EVT (0x0004 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_BTM_EVT (0x0005 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_AVDT_EVT (0x0006 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_SLIP_EVT (0x0007 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_MGMT_EVT (0x0008 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_BTTRC_EVT (0x0009 | BT_EVT_BTU_IPC_EVT) -#define BT_EVT_BTU_IPC_BURST_EVT (0x000A | BT_EVT_BTU_IPC_EVT) - - -/* BTIF Events */ -#define BT_EVT_BTIF 0xA000 -#define BT_EVT_CONTEXT_SWITCH_EVT (0x0001 | BT_EVT_BTIF) - -/* Define the header of each buffer used in the Bluetooth stack. -*/ -typedef struct { - uint16_t event; - uint16_t len; - uint16_t offset; - uint16_t layer_specific; - uint8_t data[]; -} BT_HDR; - -#define BT_HDR_SIZE (sizeof (BT_HDR)) - -#define BT_PSM_SDP 0x0001 -#define BT_PSM_RFCOMM 0x0003 -#define BT_PSM_TCS 0x0005 -#define BT_PSM_CTP 0x0007 -#define BT_PSM_BNEP 0x000F -#define BT_PSM_HIDC 0x0011 -#define BT_PSM_HIDI 0x0013 -#define BT_PSM_UPNP 0x0015 -#define BT_PSM_AVCTP 0x0017 -#define BT_PSM_AVDTP 0x0019 -#define BT_PSM_AVCTP_13 0x001B /* Advanced Control - Browsing */ -#define BT_PSM_UDI_CP 0x001D /* Unrestricted Digital Information Profile C-Plane */ -#define BT_PSM_ATT 0x001F /* Attribute Protocol */ - - -/* These macros extract the HCI opcodes from a buffer -*/ -#define HCI_GET_CMD_HDR_OPCODE(p) (UINT16)((*((UINT8 *)((p) + 1) + p->offset) + \ - (*((UINT8 *)((p) + 1) + p->offset + 1) << 8))) -#define HCI_GET_CMD_HDR_PARAM_LEN(p) (UINT8) (*((UINT8 *)((p) + 1) + p->offset + 2)) - -#define HCI_GET_EVT_HDR_OPCODE(p) (UINT8)(*((UINT8 *)((p) + 1) + p->offset)) -#define HCI_GET_EVT_HDR_PARAM_LEN(p) (UINT8) (*((UINT8 *)((p) + 1) + p->offset + 1)) - - -/******************************************************************************** -** Macros to get and put bytes to and from a stream (Little Endian format). -*/ -#define UINT32_TO_STREAM(p, u32) {*(p)++ = (UINT8)(u32); *(p)++ = (UINT8)((u32) >> 8); *(p)++ = (UINT8)((u32) >> 16); *(p)++ = (UINT8)((u32) >> 24);} -#define UINT24_TO_STREAM(p, u24) {*(p)++ = (UINT8)(u24); *(p)++ = (UINT8)((u24) >> 8); *(p)++ = (UINT8)((u24) >> 16);} -#define UINT16_TO_STREAM(p, u16) {*(p)++ = (UINT8)(u16); *(p)++ = (UINT8)((u16) >> 8);} -#define UINT8_TO_STREAM(p, u8) {*(p)++ = (UINT8)(u8);} -#define INT8_TO_STREAM(p, u8) {*(p)++ = (INT8)(u8);} -#define ARRAY32_TO_STREAM(p, a) {register int ijk; for (ijk = 0; ijk < 32; ijk++) *(p)++ = (UINT8) a[31 - ijk];} -#define ARRAY16_TO_STREAM(p, a) {register int ijk; for (ijk = 0; ijk < 16; ijk++) *(p)++ = (UINT8) a[15 - ijk];} -#define ARRAY8_TO_STREAM(p, a) {register int ijk; for (ijk = 0; ijk < 8; ijk++) *(p)++ = (UINT8) a[7 - ijk];} -#define BDADDR_TO_STREAM(p, a) {register int ijk; for (ijk = 0; ijk < BD_ADDR_LEN; ijk++) *(p)++ = (UINT8) a[BD_ADDR_LEN - 1 - ijk];} -#define LAP_TO_STREAM(p, a) {register int ijk; for (ijk = 0; ijk < LAP_LEN; ijk++) *(p)++ = (UINT8) a[LAP_LEN - 1 - ijk];} -#define DEVCLASS_TO_STREAM(p, a) {register int ijk; for (ijk = 0; ijk < DEV_CLASS_LEN;ijk++) *(p)++ = (UINT8) a[DEV_CLASS_LEN - 1 - ijk];} -#define ARRAY_TO_STREAM(p, a, len) {register int ijk; for (ijk = 0; ijk < len; ijk++) *(p)++ = (UINT8) a[ijk];} -#define REVERSE_ARRAY_TO_STREAM(p, a, len) {register int ijk; for (ijk = 0; ijk < len; ijk++) *(p)++ = (UINT8) a[len - 1 - ijk];} - -#define STREAM_TO_UINT8(u8, p) {u8 = (UINT8)(*(p)); (p) += 1;} -#define STREAM_TO_UINT16(u16, p) {u16 = ((UINT16)(*(p)) + (((UINT16)(*((p) + 1))) << 8)); (p) += 2;} -#define STREAM_TO_UINT24(u32, p) {u32 = (((UINT32)(*(p))) + ((((UINT32)(*((p) + 1)))) << 8) + ((((UINT32)(*((p) + 2)))) << 16) ); (p) += 3;} -#define STREAM_TO_UINT32(u32, p) {u32 = (((UINT32)(*(p))) + ((((UINT32)(*((p) + 1)))) << 8) + ((((UINT32)(*((p) + 2)))) << 16) + ((((UINT32)(*((p) + 3)))) << 24)); (p) += 4;} -#define STREAM_TO_BDADDR(a, p) {register int ijk; register UINT8 *pbda = (UINT8 *)a + BD_ADDR_LEN - 1; for (ijk = 0; ijk < BD_ADDR_LEN; ijk++) *pbda-- = *p++;} -#define STREAM_TO_ARRAY32(a, p) {register int ijk; register UINT8 *_pa = (UINT8 *)a + 31; for (ijk = 0; ijk < 32; ijk++) *_pa-- = *p++;} -#define STREAM_TO_ARRAY16(a, p) {register int ijk; register UINT8 *_pa = (UINT8 *)a + 15; for (ijk = 0; ijk < 16; ijk++) *_pa-- = *p++;} -#define STREAM_TO_ARRAY8(a, p) {register int ijk; register UINT8 *_pa = (UINT8 *)a + 7; for (ijk = 0; ijk < 8; ijk++) *_pa-- = *p++;} -#define STREAM_TO_DEVCLASS(a, p) {register int ijk; register UINT8 *_pa = (UINT8 *)a + DEV_CLASS_LEN - 1; for (ijk = 0; ijk < DEV_CLASS_LEN; ijk++) *_pa-- = *p++;} -#define STREAM_TO_LAP(a, p) {register int ijk; register UINT8 *plap = (UINT8 *)a + LAP_LEN - 1; for (ijk = 0; ijk < LAP_LEN; ijk++) *plap-- = *p++;} -#define STREAM_TO_ARRAY(a, p, len) {register int ijk; for (ijk = 0; ijk < len; ijk++) ((UINT8 *) a)[ijk] = *p++;} -#define REVERSE_STREAM_TO_ARRAY(a, p, len) {register int ijk; register UINT8 *_pa = (UINT8 *)a + len - 1; for (ijk = 0; ijk < len; ijk++) *_pa-- = *p++;} - -#define STREAM_SKIP_UINT8(p) do { (p) += 1; } while (0) -#define STREAM_SKIP_UINT16(p) do { (p) += 2; } while (0) - -/******************************************************************************** -** Macros to get and put bytes to and from a field (Little Endian format). -** These are the same as to stream, except the pointer is not incremented. -*/ -#define UINT32_TO_FIELD(p, u32) {*(UINT8 *)(p) = (UINT8)(u32); *((UINT8 *)(p)+1) = (UINT8)((u32) >> 8); *((UINT8 *)(p)+2) = (UINT8)((u32) >> 16); *((UINT8 *)(p)+3) = (UINT8)((u32) >> 24);} -#define UINT24_TO_FIELD(p, u24) {*(UINT8 *)(p) = (UINT8)(u24); *((UINT8 *)(p)+1) = (UINT8)((u24) >> 8); *((UINT8 *)(p)+2) = (UINT8)((u24) >> 16);} -#define UINT16_TO_FIELD(p, u16) {*(UINT8 *)(p) = (UINT8)(u16); *((UINT8 *)(p)+1) = (UINT8)((u16) >> 8);} -#define UINT8_TO_FIELD(p, u8) {*(UINT8 *)(p) = (UINT8)(u8);} - - -/******************************************************************************** -** Macros to get and put bytes to and from a stream (Big Endian format) -*/ -#define UINT64_TO_BE_STREAM(p, u64) {*(p)++ = (UINT8)((u64) >> 56); *(p)++ = (UINT8)((u64) >> 48); *(p)++ = (UINT8)((u64) >> 40); *(p)++ = (UINT8)((u64) >> 32); *(p)++ = (UINT8)((u64) >> 24); *(p)++ = (UINT8)((u64) >> 16); *(p)++ = (UINT8)((u64) >> 8); *(p)++ = (UINT8)(u64); } -#define UINT32_TO_BE_STREAM(p, u32) {*(p)++ = (UINT8)((u32) >> 24); *(p)++ = (UINT8)((u32) >> 16); *(p)++ = (UINT8)((u32) >> 8); *(p)++ = (UINT8)(u32); } -#define UINT24_TO_BE_STREAM(p, u24) {*(p)++ = (UINT8)((u24) >> 16); *(p)++ = (UINT8)((u24) >> 8); *(p)++ = (UINT8)(u24);} -#define UINT16_TO_BE_STREAM(p, u16) {*(p)++ = (UINT8)((u16) >> 8); *(p)++ = (UINT8)(u16);} -#define UINT8_TO_BE_STREAM(p, u8) {*(p)++ = (UINT8)(u8);} -#define ARRAY_TO_BE_STREAM(p, a, len) {register int ijk; for (ijk = 0; ijk < len; ijk++) *(p)++ = (UINT8) a[ijk];} -#define ARRAY_TO_BE_STREAM_REVERSE(p, a, len) {register int ijk; for (ijk = 0; ijk < len; ijk++) *(p)++ = (UINT8) a[len - ijk - 1];} - -#define BE_STREAM_TO_UINT8(u8, p) {u8 = (UINT8)(*(p)); (p) += 1;} -#define BE_STREAM_TO_UINT16(u16, p) {u16 = (UINT16)(((UINT16)(*(p)) << 8) + (UINT16)(*((p) + 1))); (p) += 2;} -#define BE_STREAM_TO_UINT24(u32, p) {u32 = (((UINT32)(*((p) + 2))) + ((UINT32)(*((p) + 1)) << 8) + ((UINT32)(*(p)) << 16)); (p) += 3;} -#define BE_STREAM_TO_UINT32(u32, p) {u32 = ((UINT32)(*((p) + 3)) + ((UINT32)(*((p) + 2)) << 8) + ((UINT32)(*((p) + 1)) << 16) + ((UINT32)(*(p)) << 24)); (p) += 4;} -#define BE_STREAM_TO_ARRAY(p, a, len) {register int ijk; for (ijk = 0; ijk < len; ijk++) ((UINT8 *) a)[ijk] = *p++;} - - -/******************************************************************************** -** Macros to get and put bytes to and from a field (Big Endian format). -** These are the same as to stream, except the pointer is not incremented. -*/ -#define UINT32_TO_BE_FIELD(p, u32) {*(UINT8 *)(p) = (UINT8)((u32) >> 24); *((UINT8 *)(p)+1) = (UINT8)((u32) >> 16); *((UINT8 *)(p)+2) = (UINT8)((u32) >> 8); *((UINT8 *)(p)+3) = (UINT8)(u32); } -#define UINT24_TO_BE_FIELD(p, u24) {*(UINT8 *)(p) = (UINT8)((u24) >> 16); *((UINT8 *)(p)+1) = (UINT8)((u24) >> 8); *((UINT8 *)(p)+2) = (UINT8)(u24);} -#define UINT16_TO_BE_FIELD(p, u16) {*(UINT8 *)(p) = (UINT8)((u16) >> 8); *((UINT8 *)(p)+1) = (UINT8)(u16);} -#define UINT8_TO_BE_FIELD(p, u8) {*(UINT8 *)(p) = (UINT8)(u8);} - - -/* Common Bluetooth field definitions */ -#define BD_ADDR_LEN 6 /* Device address length */ -typedef UINT8 BD_ADDR[BD_ADDR_LEN]; /* Device address */ -typedef UINT8 *BD_ADDR_PTR; /* Pointer to Device Address */ - -#define AMP_KEY_TYPE_GAMP 0 -#define AMP_KEY_TYPE_WIFI 1 -#define AMP_KEY_TYPE_UWB 2 -typedef UINT8 tAMP_KEY_TYPE; - -#define BT_OCTET8_LEN 8 -typedef UINT8 BT_OCTET8[BT_OCTET8_LEN]; /* octet array: size 16 */ - -#define LINK_KEY_LEN 16 -typedef UINT8 LINK_KEY[LINK_KEY_LEN]; /* Link Key */ - -#define AMP_LINK_KEY_LEN 32 -typedef UINT8 AMP_LINK_KEY[AMP_LINK_KEY_LEN]; /* Dedicated AMP and GAMP Link Keys */ - -#define BT_OCTET16_LEN 16 -typedef UINT8 BT_OCTET16[BT_OCTET16_LEN]; /* octet array: size 16 */ - -#define PIN_CODE_LEN 16 -typedef UINT8 PIN_CODE[PIN_CODE_LEN]; /* Pin Code (upto 128 bits) MSB is 0 */ -typedef UINT8 *PIN_CODE_PTR; /* Pointer to Pin Code */ - -#define BT_OCTET32_LEN 32 -typedef UINT8 BT_OCTET32[BT_OCTET32_LEN]; /* octet array: size 32 */ - -#define DEV_CLASS_LEN 3 -typedef UINT8 DEV_CLASS[DEV_CLASS_LEN]; /* Device class */ -typedef UINT8 *DEV_CLASS_PTR; /* Pointer to Device class */ - -#define EXT_INQ_RESP_LEN 3 -typedef UINT8 EXT_INQ_RESP[EXT_INQ_RESP_LEN];/* Extended Inquiry Response */ -typedef UINT8 *EXT_INQ_RESP_PTR; /* Pointer to Extended Inquiry Response */ - -#define BD_NAME_LEN 248 -typedef UINT8 BD_NAME[BD_NAME_LEN + 1]; /* Device name */ -typedef UINT8 *BD_NAME_PTR; /* Pointer to Device name */ - -#define BD_FEATURES_LEN 8 -typedef UINT8 BD_FEATURES[BD_FEATURES_LEN]; /* LMP features supported by device */ - -#define BT_EVENT_MASK_LEN 8 -typedef UINT8 BT_EVENT_MASK[BT_EVENT_MASK_LEN]; /* Event Mask */ - -#define LAP_LEN 3 -typedef UINT8 LAP[LAP_LEN]; /* IAC as passed to Inquiry (LAP) */ -typedef UINT8 INQ_LAP[LAP_LEN]; /* IAC as passed to Inquiry (LAP) */ - -#define RAND_NUM_LEN 16 -typedef UINT8 RAND_NUM[RAND_NUM_LEN]; - -#define ACO_LEN 12 -typedef UINT8 ACO[ACO_LEN]; /* Authenticated ciphering offset */ - -#define COF_LEN 12 -typedef UINT8 COF[COF_LEN]; /* ciphering offset number */ - -typedef struct { - UINT8 qos_flags; /* TBD */ - UINT8 service_type; /* see below */ - UINT32 token_rate; /* bytes/second */ - UINT32 token_bucket_size; /* bytes */ - UINT32 peak_bandwidth; /* bytes/second */ - UINT32 latency; /* microseconds */ - UINT32 delay_variation; /* microseconds */ -} FLOW_SPEC; - -/* Values for service_type */ -#define NO_TRAFFIC 0 -#define BEST_EFFORT 1 -#define GUARANTEED 2 - -/* Service class of the CoD */ -#define SERV_CLASS_NETWORKING (1 << 1) -#define SERV_CLASS_RENDERING (1 << 2) -#define SERV_CLASS_CAPTURING (1 << 3) -#define SERV_CLASS_OBJECT_TRANSFER (1 << 4) -#define SERV_CLASS_OBJECT_AUDIO (1 << 5) -#define SERV_CLASS_OBJECT_TELEPHONY (1 << 6) -#define SERV_CLASS_OBJECT_INFORMATION (1 << 7) - -/* Second byte */ -#define SERV_CLASS_LIMITED_DISC_MODE (0x20) - -/* Field size definitions. Note that byte lengths are rounded up. */ -#define ACCESS_CODE_BIT_LEN 72 -#define ACCESS_CODE_BYTE_LEN 9 -#define SHORTENED_ACCESS_CODE_BIT_LEN 68 - -typedef UINT8 ACCESS_CODE[ACCESS_CODE_BYTE_LEN]; - -#define SYNTH_TX 1 /* want synth code to TRANSMIT at this freq */ -#define SYNTH_RX 2 /* want synth code to RECEIVE at this freq */ - -#define SYNC_REPS 1 /* repeats of sync word transmitted to start of burst */ - -/* Bluetooth CLK27 */ -#define BT_CLK27 (2 << 26) - -/* Bluetooth CLK12 is 1.28 sec */ -#define BT_CLK12_TO_MS(x) ((x) * 1280) -#define BT_MS_TO_CLK12(x) ((x) / 1280) -#define BT_CLK12_TO_SLOTS(x) ((x) << 11) - -/* Bluetooth CLK is 0.625 msec */ -#define BT_CLK_TO_MS(x) (((x) * 5 + 3) / 8) -#define BT_MS_TO_CLK(x) (((x) * 8 + 2) / 5) - -#define BT_CLK_TO_MICROSECS(x) (((x) * 5000 + 3) / 8) -#define BT_MICROSECS_TO_CLK(x) (((x) * 8 + 2499) / 5000) - -/* Maximum UUID size - 16 bytes, and structure to hold any type of UUID. */ -#define MAX_UUID_SIZE 16 -typedef struct { -#define LEN_UUID_16 2 -#define LEN_UUID_32 4 -#define LEN_UUID_128 16 - - UINT16 len; - - union { - UINT16 uuid16; - UINT32 uuid32; - UINT8 uuid128[MAX_UUID_SIZE]; - } uu; - -} tBT_UUID; - -#define BT_EIR_FLAGS_TYPE 0x01 -#define BT_EIR_MORE_16BITS_UUID_TYPE 0x02 -#define BT_EIR_COMPLETE_16BITS_UUID_TYPE 0x03 -#define BT_EIR_MORE_32BITS_UUID_TYPE 0x04 -#define BT_EIR_COMPLETE_32BITS_UUID_TYPE 0x05 -#define BT_EIR_MORE_128BITS_UUID_TYPE 0x06 -#define BT_EIR_COMPLETE_128BITS_UUID_TYPE 0x07 -#define BT_EIR_SHORTENED_LOCAL_NAME_TYPE 0x08 -#define BT_EIR_COMPLETE_LOCAL_NAME_TYPE 0x09 -#define BT_EIR_TX_POWER_LEVEL_TYPE 0x0A -#define BT_EIR_OOB_BD_ADDR_TYPE 0x0C -#define BT_EIR_OOB_COD_TYPE 0x0D -#define BT_EIR_OOB_SSP_HASH_C_TYPE 0x0E -#define BT_EIR_OOB_SSP_RAND_R_TYPE 0x0F -#define BT_EIR_MANUFACTURER_SPECIFIC_TYPE 0xFF - -#define BT_OOB_COD_SIZE 3 -#define BT_OOB_HASH_C_SIZE 16 -#define BT_OOB_RAND_R_SIZE 16 - -/* Broadcom proprietary UUIDs and reserved PSMs -** -** The lowest 4 bytes byte of the UUID or GUID depends on the feature. Typically, -** the value of those bytes will be the PSM or SCN, but it is up to the features. -*/ -#define BRCM_PROPRIETARY_UUID_BASE 0xDA, 0x23, 0x41, 0x02, 0xA3, 0xBB, 0xC1, 0x71, 0xBA, 0x09, 0x6f, 0x21 -#define BRCM_PROPRIETARY_GUID_BASE 0xda23, 0x4102, 0xa3, 0xbb, 0xc1, 0x71, 0xba, 0x09, 0x6f, 0x21 - -/* We will not allocate a PSM in the reserved range to 3rd party apps -*/ -#define BRCM_RESERVED_PSM_START 0x5AE1 -#define BRCM_RESERVED_PSM_END 0x5AFF - -#define BRCM_UTILITY_SERVICE_PSM 0x5AE1 -#define BRCM_MATCHER_PSM 0x5AE3 - -/* Connection statistics -*/ - -/* Structure to hold connection stats */ -#ifndef BT_CONN_STATS_DEFINED -#define BT_CONN_STATS_DEFINED - -/* These bits are used in the bIsConnected field */ -#define BT_CONNECTED_USING_BREDR 1 -#define BT_CONNECTED_USING_AMP 2 - -typedef struct { - UINT32 is_connected; - INT32 rssi; - UINT32 bytes_sent; - UINT32 bytes_rcvd; - UINT32 duration; -} tBT_CONN_STATS; - -#endif - - -/***************************************************************************** -** Low Energy definitions -** -** Address types -*/ -#define BLE_ADDR_PUBLIC 0x00 -#define BLE_ADDR_RANDOM 0x01 -#define BLE_ADDR_PUBLIC_ID 0x02 -#define BLE_ADDR_RANDOM_ID 0x03 -#define BLE_ADDR_TYPE_MAX BLE_ADDR_RANDOM_ID -#define BLE_ADDR_UNKNOWN_TYPE 0XFF -typedef UINT8 tBLE_ADDR_TYPE; -#define BLE_ADDR_TYPE_MASK (BLE_ADDR_RANDOM | BLE_ADDR_PUBLIC) - -#define BT_TRANSPORT_INVALID 0 -#define BT_TRANSPORT_BR_EDR 1 -#define BT_TRANSPORT_LE 2 -typedef UINT8 tBT_TRANSPORT; - -#define BLE_ADDR_IS_STATIC(x) ((x[0] & 0xC0) == 0xC0) - -typedef struct { - tBLE_ADDR_TYPE type; - BD_ADDR bda; -} tBLE_BD_ADDR; - -/* Device Types -*/ -#define BT_DEVICE_TYPE_BREDR 0x01 -#define BT_DEVICE_TYPE_BLE 0x02 -#define BT_DEVICE_TYPE_DUMO 0x03 -typedef UINT8 tBT_DEVICE_TYPE; -/*****************************************************************************/ - - -/* Define trace levels */ -#define BT_TRACE_LEVEL_NONE 0 /* No trace messages to be generated */ -#define BT_TRACE_LEVEL_ERROR 1 /* Error condition trace messages */ -#define BT_TRACE_LEVEL_WARNING 2 /* Warning condition trace messages */ -#define BT_TRACE_LEVEL_API 3 /* API traces */ -#define BT_TRACE_LEVEL_EVENT 4 /* Debug messages for events */ -#define BT_TRACE_LEVEL_DEBUG 5 /* Full debug messages */ -#define BT_TRACE_LEVEL_VERBOSE 6 /* Verbose debug messages */ - -#define MAX_TRACE_LEVEL 6 - - -/* Define New Trace Type Definition */ -/* TRACE_CTRL_TYPE 0x^^000000*/ -#define TRACE_CTRL_MASK 0xff000000 -#define TRACE_GET_CTRL(x) ((((UINT32)(x)) & TRACE_CTRL_MASK) >> 24) - -#define TRACE_CTRL_GENERAL 0x00000000 -#define TRACE_CTRL_STR_RESOURCE 0x01000000 -#define TRACE_CTRL_SEQ_FLOW 0x02000000 -#define TRACE_CTRL_MAX_NUM 3 - -/* LAYER SPECIFIC 0x00^^0000*/ -#define TRACE_LAYER_MASK 0x00ff0000 -#define TRACE_GET_LAYER(x) ((((UINT32)(x)) & TRACE_LAYER_MASK) >> 16) - -#define TRACE_LAYER_NONE 0x00000000 -#define TRACE_LAYER_USB 0x00010000 -#define TRACE_LAYER_SERIAL 0x00020000 -#define TRACE_LAYER_SOCKET 0x00030000 -#define TRACE_LAYER_RS232 0x00040000 -#define TRACE_LAYER_TRANS_MAX_NUM 5 -#define TRACE_LAYER_TRANS_ALL 0x007f0000 -#define TRACE_LAYER_LC 0x00050000 -#define TRACE_LAYER_LM 0x00060000 -#define TRACE_LAYER_HCI 0x00070000 -#define TRACE_LAYER_L2CAP 0x00080000 -#define TRACE_LAYER_RFCOMM 0x00090000 -#define TRACE_LAYER_SDP 0x000a0000 -#define TRACE_LAYER_TCS 0x000b0000 -#define TRACE_LAYER_OBEX 0x000c0000 -#define TRACE_LAYER_BTM 0x000d0000 -#define TRACE_LAYER_GAP 0x000e0000 -#define TRACE_LAYER_ICP 0x00110000 -#define TRACE_LAYER_HSP2 0x00120000 -#define TRACE_LAYER_SPP 0x00130000 -#define TRACE_LAYER_CTP 0x00140000 -#define TRACE_LAYER_BPP 0x00150000 -#define TRACE_LAYER_HCRP 0x00160000 -#define TRACE_LAYER_FTP 0x00170000 -#define TRACE_LAYER_OPP 0x00180000 -#define TRACE_LAYER_BTU 0x00190000 -#define TRACE_LAYER_GKI 0x001a0000 -#define TRACE_LAYER_BNEP 0x001b0000 -#define TRACE_LAYER_PAN 0x001c0000 -#define TRACE_LAYER_HFP 0x001d0000 -#define TRACE_LAYER_HID 0x001e0000 -#define TRACE_LAYER_BIP 0x001f0000 -#define TRACE_LAYER_AVP 0x00200000 -#define TRACE_LAYER_A2D 0x00210000 -#define TRACE_LAYER_SAP 0x00220000 -#define TRACE_LAYER_AMP 0x00230000 -#define TRACE_LAYER_MCA 0x00240000 -#define TRACE_LAYER_ATT 0x00250000 -#define TRACE_LAYER_SMP 0x00260000 -#define TRACE_LAYER_NFC 0x00270000 -#define TRACE_LAYER_NCI 0x00280000 -#define TRACE_LAYER_LLCP 0x00290000 -#define TRACE_LAYER_NDEF 0x002a0000 -#define TRACE_LAYER_RW 0x002b0000 -#define TRACE_LAYER_CE 0x002c0000 -#define TRACE_LAYER_P2P 0x002d0000 -#define TRACE_LAYER_SNEP 0x002e0000 -#define TRACE_LAYER_CHO 0x002f0000 -#define TRACE_LAYER_NFA 0x00300000 - -#define TRACE_LAYER_MAX_NUM 0x0031 - - -/* TRACE_ORIGINATOR 0x0000^^00*/ -#define TRACE_ORG_MASK 0x0000ff00 -#define TRACE_GET_ORG(x) ((((UINT32)(x)) & TRACE_ORG_MASK) >> 8) - -#define TRACE_ORG_STACK 0x00000000 -#define TRACE_ORG_HCI_TRANS 0x00000100 -#define TRACE_ORG_PROTO_DISP 0x00000200 -#define TRACE_ORG_RPC 0x00000300 -#define TRACE_ORG_GKI 0x00000400 -#define TRACE_ORG_APPL 0x00000500 -#define TRACE_ORG_SCR_WRAPPER 0x00000600 -#define TRACE_ORG_SCR_ENGINE 0x00000700 -#define TRACE_ORG_USER_SCR 0x00000800 -#define TRACE_ORG_TESTER 0x00000900 -#define TRACE_ORG_MAX_NUM 10 /* 32-bit mask; must be < 32 */ -#define TRACE_LITE_ORG_MAX_NUM 6 -#define TRACE_ORG_ALL 0x03ff -#define TRACE_ORG_RPC_TRANS 0x04 - -#define TRACE_ORG_REG 0x00000909 -#define TRACE_ORG_REG_SUCCESS 0x0000090a - -/* TRACE_TYPE 0x000000^^*/ -#define TRACE_TYPE_MASK 0x000000ff -#define TRACE_GET_TYPE(x) (((UINT32)(x)) & TRACE_TYPE_MASK) - -#define TRACE_TYPE_ERROR 0x00000000 -#define TRACE_TYPE_WARNING 0x00000001 -#define TRACE_TYPE_API 0x00000002 -#define TRACE_TYPE_EVENT 0x00000003 -#define TRACE_TYPE_DEBUG 0x00000004 -#define TRACE_TYPE_STACK_ONLY_MAX TRACE_TYPE_DEBUG -#define TRACE_TYPE_TX 0x00000005 -#define TRACE_TYPE_RX 0x00000006 -#define TRACE_TYPE_DEBUG_ASSERT 0x00000007 -#define TRACE_TYPE_GENERIC 0x00000008 -#define TRACE_TYPE_REG 0x00000009 -#define TRACE_TYPE_REG_SUCCESS 0x0000000a -#define TRACE_TYPE_CMD_TX 0x0000000b -#define TRACE_TYPE_EVT_TX 0x0000000c -#define TRACE_TYPE_ACL_TX 0x0000000d -#define TRACE_TYPE_CMD_RX 0x0000000e -#define TRACE_TYPE_EVT_RX 0x0000000f -#define TRACE_TYPE_ACL_RX 0x00000010 -#define TRACE_TYPE_TARGET_TRACE 0x00000011 -#define TRACE_TYPE_SCO_TX 0x00000012 -#define TRACE_TYPE_SCO_RX 0x00000013 - - -#define TRACE_TYPE_MAX_NUM 20 -#define TRACE_TYPE_ALL 0xffff - -/* Define color for script type */ -#define SCR_COLOR_DEFAULT 0 -#define SCR_COLOR_TYPE_COMMENT 1 -#define SCR_COLOR_TYPE_COMMAND 2 -#define SCR_COLOR_TYPE_EVENT 3 -#define SCR_COLOR_TYPE_SELECT 4 - -/* Define protocol trace flag values */ -#define SCR_PROTO_TRACE_HCI_SUMMARY 0x00000001 -#define SCR_PROTO_TRACE_HCI_DATA 0x00000002 -#define SCR_PROTO_TRACE_L2CAP 0x00000004 -#define SCR_PROTO_TRACE_RFCOMM 0x00000008 -#define SCR_PROTO_TRACE_SDP 0x00000010 -#define SCR_PROTO_TRACE_TCS 0x00000020 -#define SCR_PROTO_TRACE_OBEX 0x00000040 -#define SCR_PROTO_TRACE_OAPP 0x00000080 /* OBEX Application Profile */ -#define SCR_PROTO_TRACE_AMP 0x00000100 -#define SCR_PROTO_TRACE_BNEP 0x00000200 -#define SCR_PROTO_TRACE_AVP 0x00000400 -#define SCR_PROTO_TRACE_MCA 0x00000800 -#define SCR_PROTO_TRACE_ATT 0x00001000 -#define SCR_PROTO_TRACE_SMP 0x00002000 -#define SCR_PROTO_TRACE_NCI 0x00004000 -#define SCR_PROTO_TRACE_LLCP 0x00008000 -#define SCR_PROTO_TRACE_NDEF 0x00010000 -#define SCR_PROTO_TRACE_RW 0x00020000 -#define SCR_PROTO_TRACE_CE 0x00040000 -#define SCR_PROTO_TRACE_SNEP 0x00080000 -#define SCR_PROTO_TRACE_CHO 0x00100000 -#define SCR_PROTO_TRACE_ALL 0x001fffff -#define SCR_PROTO_TRACE_HCI_LOGGING_VSE 0x0800 /* Brcm vs event for logmsg and protocol traces */ - -#define MAX_SCRIPT_TYPE 5 - -#define TCS_PSM_INTERCOM 5 -#define TCS_PSM_CORDLESS 7 -#define BT_PSM_BNEP 0x000F -/* Define PSMs HID uses */ -#define HID_PSM_CONTROL 0x0011 -#define HID_PSM_INTERRUPT 0x0013 - -/* Define a function for logging */ -typedef void (BT_LOG_FUNC) (int trace_type, const char *fmt_str, ...); - -/* bd addr length and type */ -#ifndef BD_ADDR_LEN -#define BD_ADDR_LEN 6 -typedef uint8_t BD_ADDR[BD_ADDR_LEN]; -#endif - -// From bd.c - -/***************************************************************************** -** Constants -*****************************************************************************/ - -/* global constant for "any" bd addr */ -static const BD_ADDR bd_addr_any = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; -static const BD_ADDR bd_addr_null = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - -/***************************************************************************** -** Functions -*****************************************************************************/ - -/******************************************************************************* -** -** Function bdcpy -** -** Description Copy bd addr b to a. -** -** -** Returns void -** -*******************************************************************************/ -static inline void bdcpy(BD_ADDR a, const BD_ADDR b) -{ - int i; - - for (i = BD_ADDR_LEN; i != 0; i--) { - *a++ = *b++; - } -} - -/******************************************************************************* -** -** Function bdcmp -** -** Description Compare bd addr b to a. -** -** -** Returns Zero if b==a, nonzero otherwise (like memcmp). -** -*******************************************************************************/ -static inline int bdcmp(const BD_ADDR a, const BD_ADDR b) -{ - int i; - - for (i = BD_ADDR_LEN; i != 0; i--) { - if (*a++ != *b++) { - return -1; - } - } - return 0; -} - -/******************************************************************************* -** -** Function bdcmpany -** -** Description Compare bd addr to "any" bd addr. -** -** -** Returns Zero if a equals bd_addr_any. -** -*******************************************************************************/ -static inline int bdcmpany(const BD_ADDR a) -{ - return bdcmp(a, bd_addr_any); -} - -/******************************************************************************* -** -** Function bdsetany -** -** Description Set bd addr to "any" bd addr. -** -** -** Returns void -** -*******************************************************************************/ -static inline void bdsetany(BD_ADDR a) -{ - bdcpy(a, bd_addr_any); -} -#endif diff --git a/tools/sdk/include/bluedroid/bt_vendor_lib.h b/tools/sdk/include/bluedroid/bt_vendor_lib.h deleted file mode 100644 index e3a8ec8dbf4..00000000000 --- a/tools/sdk/include/bluedroid/bt_vendor_lib.h +++ /dev/null @@ -1,362 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2009-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 BT_VENDOR_LIB_H -#define BT_VENDOR_LIB_H - -#include -//#include -//#include - -/** Struct types */ - - -/** Typedefs and defines */ - -/** Vendor specific operations OPCODE */ -typedef enum { - /* [operation] - * Power on or off the BT Controller. - * [input param] - * A pointer to int type with content of bt_vendor_power_state_t. - * Typecasting conversion: (int *) param. - * [return] - * 0 - default, don't care. - * [callback] - * None. - */ - BT_VND_OP_POWER_CTRL, - - /* [operation] - * Perform any vendor specific initialization or configuration - * on the BT Controller. This is called before stack initialization. - * [input param] - * None. - * [return] - * 0 - default, don't care. - * [callback] - * Must call fwcfg_cb to notify the stack of the completion of vendor - * specific initialization once it has been done. - */ - BT_VND_OP_FW_CFG, - - /* [operation] - * Perform any vendor specific SCO/PCM configuration on the BT Controller. - * This is called after stack initialization. - * [input param] - * None. - * [return] - * 0 - default, don't care. - * [callback] - * Must call scocfg_cb to notify the stack of the completion of vendor - * specific SCO configuration once it has been done. - */ - BT_VND_OP_SCO_CFG, - - /* [operation] - * Open UART port on where the BT Controller is attached. - * This is called before stack initialization. - * [input param] - * A pointer to int array type for open file descriptors. - * The mapping of HCI channel to fd slot in the int array is given in - * bt_vendor_hci_channels_t. - * And, it requires the vendor lib to fill up the content before returning - * the call. - * Typecasting conversion: (int (*)[]) param. - * [return] - * Numbers of opened file descriptors. - * Valid number: - * 1 - CMD/EVT/ACL-In/ACL-Out via the same fd (e.g. UART) - * 2 - CMD/EVT on one fd, and ACL-In/ACL-Out on the other fd - * 4 - CMD, EVT, ACL-In, ACL-Out are on their individual fd - * [callback] - * None. - */ - BT_VND_OP_USERIAL_OPEN, - - /* [operation] - * Close the previously opened UART port. - * [input param] - * None. - * [return] - * 0 - default, don't care. - * [callback] - * None. - */ - BT_VND_OP_USERIAL_CLOSE, - - /* [operation] - * Get the LPM idle timeout in milliseconds. - * The stack uses this information to launch a timer delay before it - * attempts to de-assert LPM WAKE signal once downstream HCI packet - * has been delivered. - * [input param] - * A pointer to uint32_t type which is passed in by the stack. And, it - * requires the vendor lib to fill up the content before returning - * the call. - * Typecasting conversion: (uint32_t *) param. - * [return] - * 0 - default, don't care. - * [callback] - * None. - */ - BT_VND_OP_GET_LPM_IDLE_TIMEOUT, - - /* [operation] - * Enable or disable LPM mode on BT Controller. - * [input param] - * A pointer to uint8_t type with content of bt_vendor_lpm_mode_t. - * Typecasting conversion: (uint8_t *) param. - * [return] - * 0 - default, don't care. - * [callback] - * Must call lpm_cb to notify the stack of the completion of LPM - * disable/enable process once it has been done. - */ - BT_VND_OP_LPM_SET_MODE, - - /* [operation] - * Assert or Deassert LPM WAKE on BT Controller. - * [input param] - * A pointer to uint8_t type with content of bt_vendor_lpm_wake_state_t. - * Typecasting conversion: (uint8_t *) param. - * [return] - * 0 - default, don't care. - * [callback] - * None. - */ - BT_VND_OP_LPM_WAKE_SET_STATE, - - /* [operation] - * Perform any vendor specific commands related to audio state changes. - * [input param] - * a pointer to bt_vendor_op_audio_state_t indicating what audio state is - * set. - * [return] - * 0 - default, don't care. - * [callback] - * None. - */ - BT_VND_OP_SET_AUDIO_STATE, - - /* [operation] - * The epilog call to the vendor module so that it can perform any - * vendor-specific processes (e.g. send a HCI_RESET to BT Controller) - * before the caller calls for cleanup(). - * [input param] - * None. - * [return] - * 0 - default, don't care. - * [callback] - * Must call epilog_cb to notify the stack of the completion of vendor - * specific epilog process once it has been done. - */ - BT_VND_OP_EPILOG, -} bt_vendor_opcode_t; - -/** Power on/off control states */ -typedef enum { - BT_VND_PWR_OFF, - BT_VND_PWR_ON, -} bt_vendor_power_state_t; - -/** Define HCI channel identifier in the file descriptors array - used in BT_VND_OP_USERIAL_OPEN operation. - */ -typedef enum { - CH_CMD, // HCI Command channel - CH_EVT, // HCI Event channel - CH_ACL_OUT, // HCI ACL downstream channel - CH_ACL_IN, // HCI ACL upstream channel - - CH_MAX // Total channels -} bt_vendor_hci_channels_t; - -/** LPM disable/enable request */ -typedef enum { - BT_VND_LPM_DISABLE, - BT_VND_LPM_ENABLE, -} bt_vendor_lpm_mode_t; - -/** LPM WAKE set state request */ -typedef enum { - BT_VND_LPM_WAKE_ASSERT, - BT_VND_LPM_WAKE_DEASSERT, -} bt_vendor_lpm_wake_state_t; - -/** Callback result values */ -typedef enum { - BT_VND_OP_RESULT_SUCCESS, - BT_VND_OP_RESULT_FAIL, -} bt_vendor_op_result_t; - -/** audio (SCO) state changes triggering VS commands for configuration */ -typedef struct { - uint16_t handle; - uint16_t peer_codec; - uint16_t state; -} bt_vendor_op_audio_state_t; - -/* - * Bluetooth Host/Controller Vendor callback structure. - */ - -/* vendor initialization/configuration callback */ -typedef void (*cfg_result_cb)(bt_vendor_op_result_t result); - -/* datapath buffer allocation callback (callout) - * - * Vendor lib needs to request a buffer through the alloc callout function - * from HCI lib if the buffer is for constructing a HCI Command packet which - * will be sent through xmit_cb to BT Controller. - * - * For each buffer allocation, the requested size needs to be big enough to - * accommodate the below header plus a complete HCI packet -- - * typedef struct - * { - * uint16_t event; - * uint16_t len; - * uint16_t offset; - * uint16_t layer_specific; - * } HC_BT_HDR; - * - * HCI lib returns a pointer to the buffer where Vendor lib should use to - * construct a HCI command packet as below format: - * - * -------------------------------------------- - * | HC_BT_HDR | HCI command | - * -------------------------------------------- - * where - * HC_BT_HDR.event = 0x2000; - * HC_BT_HDR.len = Length of HCI command; - * HC_BT_HDR.offset = 0; - * HC_BT_HDR.layer_specific = 0; - * - * For example, a HCI_RESET Command will be formed as - * ------------------------ - * | HC_BT_HDR |03|0c|00| - * ------------------------ - * with - * HC_BT_HDR.event = 0x2000; - * HC_BT_HDR.len = 3; - * HC_BT_HDR.offset = 0; - * HC_BT_HDR.layer_specific = 0; - */ -typedef void *(*malloc_cb)(int size); - -/* datapath buffer deallocation callback (callout) */ -typedef void (*mdealloc_cb)(void *p_buf); - -/* define callback of the cmd_xmit_cb - * - * The callback function which HCI lib will call with the return of command - * complete packet. Vendor lib is responsible for releasing the buffer passed - * in at the p_mem parameter by calling dealloc callout function. - */ -typedef void (*tINT_CMD_CBACK)(void *p_mem); - -/* hci command packet transmit callback (callout) - * - * Vendor lib calls xmit_cb callout function in order to send a HCI Command - * packet to BT Controller. The buffer carrying HCI Command packet content - * needs to be first allocated through the alloc callout function. - * HCI lib will release the buffer for Vendor lib once it has delivered the - * packet content to BT Controller. - * - * Vendor lib needs also provide a callback function (p_cback) which HCI lib - * will call with the return of command complete packet. - * - * The opcode parameter gives the HCI OpCode (combination of OGF and OCF) of - * HCI Command packet. For example, opcode = 0x0c03 for the HCI_RESET command - * packet. - */ -typedef uint8_t (*cmd_xmit_cb)(uint16_t opcode, void *p_buf, tINT_CMD_CBACK p_cback); - -typedef struct { - /** set to sizeof(bt_vendor_callbacks_t) */ - size_t size; - - /* - * Callback and callout functions have implemented in HCI libray - * (libbt-hci.so). - */ - - /* notifies caller result of firmware configuration request */ - cfg_result_cb fwcfg_cb; - - /* notifies caller result of sco configuration request */ - cfg_result_cb scocfg_cb; - - /* notifies caller result of lpm enable/disable */ - cfg_result_cb lpm_cb; - - /* notifies the result of codec setting */ - cfg_result_cb audio_state_cb; - - /* buffer allocation request */ - malloc_cb alloc; - - /* buffer deallocation request */ - mdealloc_cb dealloc; - - /* hci command packet transmit request */ - cmd_xmit_cb xmit_cb; - - /* notifies caller completion of epilog process */ - cfg_result_cb epilog_cb; -} bt_vendor_callbacks_t; - -/* - * Bluetooth Host/Controller VENDOR Interface - */ -typedef struct { - /** Set to sizeof(bt_vndor_interface_t) */ - size_t size; - - /* - * Functions need to be implemented in Vendor libray (libbt-vendor.so). - */ - - /** - * Caller will open the interface and pass in the callback routines - * to the implemenation of this interface. - */ - int (*init)(const bt_vendor_callbacks_t *p_cb, unsigned char *local_bdaddr); - - /** Vendor specific operations */ - int (*op)(bt_vendor_opcode_t opcode, void *param); - - /** Closes the interface */ - void (*cleanup)(void); -} bt_vendor_interface_t; - - -/* - * External shared lib functions/data - */ - -/* Entry point of DLib -- - * Vendor library needs to implement the body of bt_vendor_interface_t - * structure and uses the below name as the variable name. HCI library - * will use this symbol name to get address of the object through the - * dlsym call. - */ -//extern const bt_vendor_interface_t BLUETOOTH_VENDOR_LIB_INTERFACE; - -#endif /* BT_VENDOR_LIB_H */ - diff --git a/tools/sdk/include/bluedroid/bta_api.h b/tools/sdk/include/bluedroid/bta_api.h deleted file mode 100644 index a13c0822739..00000000000 --- a/tools/sdk/include/bluedroid/bta_api.h +++ /dev/null @@ -1,2472 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2014 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the public interface file for BTA, Broadcom's Bluetooth - * application layer for mobile phones. - * - ******************************************************************************/ -#ifndef BTA_API_H -#define BTA_API_H - -#include "bt_target.h" -#include "bt_types.h" -#include "btm_api.h" -// #include "uipc_msg.h" -#include "sdp_api.h" - -#if BLE_INCLUDED == TRUE -#include "btm_ble_api.h" -#endif - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ - -/* Status Return Value */ -#define BTA_SUCCESS 0 /* Successful operation. */ -#define BTA_FAILURE 1 /* Generic failure. */ -#define BTA_PENDING 2 /* API cannot be completed right now */ -#define BTA_BUSY 3 -#define BTA_NO_RESOURCES 4 -#define BTA_WRONG_MODE 5 - -typedef UINT8 tBTA_STATUS; - -/* - * Service ID - * - * NOTES: When you add a new Service ID for BTA AND require to change the value of BTA_MAX_SERVICE_ID, - * make sure that the correct security ID of the new service from Security service definitions (btm_api.h) - * should be added to bta_service_id_to_btm_srv_id_lkup_tbl table in bta_dm_act.c. - */ - -#define BTA_RES_SERVICE_ID 0 /* Reserved */ -#define BTA_SPP_SERVICE_ID 1 /* Serial port profile. */ -#define BTA_DUN_SERVICE_ID 2 /* Dial-up networking profile. */ -#define BTA_A2DP_SOURCE_SERVICE_ID 3 /* A2DP Source profile. */ -#define BTA_LAP_SERVICE_ID 4 /* LAN access profile. */ -#define BTA_HSP_SERVICE_ID 5 /* Headset profile. */ -#define BTA_HFP_SERVICE_ID 6 /* Hands-free profile. */ -#define BTA_OPP_SERVICE_ID 7 /* Object push */ -#define BTA_FTP_SERVICE_ID 8 /* File transfer */ -#define BTA_CTP_SERVICE_ID 9 /* Cordless Terminal */ -#define BTA_ICP_SERVICE_ID 10 /* Intercom Terminal */ -#define BTA_SYNC_SERVICE_ID 11 /* Synchronization */ -#define BTA_BPP_SERVICE_ID 12 /* Basic printing profile */ -#define BTA_BIP_SERVICE_ID 13 /* Basic Imaging profile */ -#define BTA_PANU_SERVICE_ID 14 /* PAN User */ -#define BTA_NAP_SERVICE_ID 15 /* PAN Network access point */ -#define BTA_GN_SERVICE_ID 16 /* PAN Group Ad-hoc networks */ -#define BTA_SAP_SERVICE_ID 17 /* SIM Access profile */ -#define BTA_A2DP_SINK_SERVICE_ID 18 /* A2DP Sink */ -#define BTA_AVRCP_SERVICE_ID 19 /* A/V remote control */ -#define BTA_HID_SERVICE_ID 20 /* HID */ -#define BTA_VDP_SERVICE_ID 21 /* Video distribution */ -#define BTA_PBAP_SERVICE_ID 22 /* PhoneBook Access Server*/ -#define BTA_HSP_HS_SERVICE_ID 23 /* HFP HS role */ -#define BTA_HFP_HS_SERVICE_ID 24 /* HSP HS role */ -#define BTA_MAP_SERVICE_ID 25 /* Message Access Profile */ -#define BTA_MN_SERVICE_ID 26 /* Message Notification Service */ -#define BTA_HDP_SERVICE_ID 27 /* Health Device Profile */ -#define BTA_PCE_SERVICE_ID 28 /* PhoneBook Access Client*/ -#define BTA_SDP_SERVICE_ID 29 /* SDP Search*/ -#if BLE_INCLUDED == TRUE && BTA_GATT_INCLUDED == TRUE -/* BLE profile service ID */ -#define BTA_BLE_SERVICE_ID 30 /* GATT profile */ - -// btla-specific ++ -#define BTA_USER_SERVICE_ID 31 /* User requested UUID */ - -#define BTA_MAX_SERVICE_ID 32 -// btla-specific -- -#else -#define BTA_USER_SERVICE_ID 30 /* User requested UUID */ -#define BTA_MAX_SERVICE_ID 31 -#endif -/* service IDs (BTM_SEC_SERVICE_FIRST_EMPTY + 1) to (BTM_SEC_MAX_SERVICES - 1) - * are used by BTA JV */ -#define BTA_FIRST_JV_SERVICE_ID (BTM_SEC_SERVICE_FIRST_EMPTY + 1) -#define BTA_LAST_JV_SERVICE_ID (BTM_SEC_MAX_SERVICES - 1) - -typedef UINT8 tBTA_SERVICE_ID; - -/* Service ID Mask */ -#define BTA_RES_SERVICE_MASK 0x00000001 /* Reserved */ -#define BTA_SPP_SERVICE_MASK 0x00000002 /* Serial port profile. */ -#define BTA_DUN_SERVICE_MASK 0x00000004 /* Dial-up networking profile. */ -#define BTA_FAX_SERVICE_MASK 0x00000008 /* Fax profile. */ -#define BTA_LAP_SERVICE_MASK 0x00000010 /* LAN access profile. */ -#define BTA_HSP_SERVICE_MASK 0x00000020 /* HSP AG role. */ -#define BTA_HFP_SERVICE_MASK 0x00000040 /* HFP AG role */ -#define BTA_OPP_SERVICE_MASK 0x00000080 /* Object push */ -#define BTA_FTP_SERVICE_MASK 0x00000100 /* File transfer */ -#define BTA_CTP_SERVICE_MASK 0x00000200 /* Cordless Terminal */ -#define BTA_ICP_SERVICE_MASK 0x00000400 /* Intercom Terminal */ -#define BTA_SYNC_SERVICE_MASK 0x00000800 /* Synchronization */ -#define BTA_BPP_SERVICE_MASK 0x00001000 /* Print server */ -#define BTA_BIP_SERVICE_MASK 0x00002000 /* Basic Imaging */ -#define BTA_PANU_SERVICE_MASK 0x00004000 /* PAN User */ -#define BTA_NAP_SERVICE_MASK 0x00008000 /* PAN Network access point */ -#define BTA_GN_SERVICE_MASK 0x00010000 /* PAN Group Ad-hoc networks */ -#define BTA_SAP_SERVICE_MASK 0x00020000 /* PAN Group Ad-hoc networks */ -#define BTA_A2DP_SERVICE_MASK 0x00040000 /* Advanced audio distribution */ -#define BTA_AVRCP_SERVICE_MASK 0x00080000 /* A/V remote control */ -#define BTA_HID_SERVICE_MASK 0x00100000 /* HID */ -#define BTA_VDP_SERVICE_MASK 0x00200000 /* Video distribution */ -#define BTA_PBAP_SERVICE_MASK 0x00400000 /* Phone Book Server */ -#define BTA_HSP_HS_SERVICE_MASK 0x00800000 /* HFP HS role */ -#define BTA_HFP_HS_SERVICE_MASK 0x01000000 /* HSP HS role */ -#define BTA_MAS_SERVICE_MASK 0x02000000 /* Message Access Profile */ -#define BTA_MN_SERVICE_MASK 0x04000000 /* Message Notification Profile */ -#define BTA_HL_SERVICE_MASK 0x08000000 /* Health Device Profile */ -#define BTA_PCE_SERVICE_MASK 0x10000000 /* Phone Book Client */ - -#if BLE_INCLUDED == TRUE && BTA_GATT_INCLUDED == TRUE -#define BTA_BLE_SERVICE_MASK 0x20000000 /* GATT based service */ -// btla-specific ++ -#define BTA_USER_SERVICE_MASK 0x40000000 /* Message Notification Profile */ -// btla-specific -- -#else -// btla-specific ++ -#define BTA_USER_SERVICE_MASK 0x20000000 /* Message Notification Profile */ -// btla-specific -- -#endif - -#if BLE_INCLUDED == TRUE && BTA_GATT_INCLUDED == TRUE -#define BTA_ALL_SERVICE_MASK 0x3FFFFFFF /* All services supported by BTA. */ -#else -#define BTA_ALL_SERVICE_MASK 0x1FFFFFFF /* All services supported by BTA. */ -#endif - -typedef UINT32 tBTA_SERVICE_MASK; - -/* extended service mask, including mask with one or more GATT UUID */ -typedef struct { - tBTA_SERVICE_MASK srvc_mask; - UINT8 num_uuid; - tBT_UUID *p_uuid; -} tBTA_SERVICE_MASK_EXT; - -/* Security Setting Mask */ -#define BTA_SEC_NONE BTM_SEC_NONE /* No security. */ -#define BTA_SEC_AUTHORIZE (BTM_SEC_IN_AUTHORIZE ) /* Authorization required (only needed for out going connection )*/ -#define BTA_SEC_AUTHENTICATE (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_OUT_AUTHENTICATE) /* Authentication required. */ -#define BTA_SEC_ENCRYPT (BTM_SEC_IN_ENCRYPT | BTM_SEC_OUT_ENCRYPT) /* Encryption required. */ -#define BTA_SEC_MODE4_LEVEL4 (BTM_SEC_MODE4_LEVEL4) /* Mode 4 level 4 service, i.e. incoming/outgoing MITM and P-256 encryption */ -#define BTA_SEC_MITM (BTM_SEC_IN_MITM | BTM_SEC_OUT_MITM) /* Man-In-The_Middle protection */ -#define BTA_SEC_IN_16_DIGITS (BTM_SEC_IN_MIN_16_DIGIT_PIN) /* Min 16 digit for pin code */ - -typedef UINT16 tBTA_SEC; - -/* Ignore for Discoverable, Connectable, Pairable and Connectable Paired only device modes */ -#define BTA_DM_IGNORE 0x00FF - -/* Ignore for Discoverable, Connectable only for LE modes */ -#define BTA_DM_LE_IGNORE 0xFF00 - -#define BTA_APP_ID_PAN_MULTI 0xFE /* app id for pan multiple connection */ -#define BTA_ALL_APP_ID 0xFF - -/* Discoverable Modes */ -#define BTA_DM_NON_DISC BTM_NON_DISCOVERABLE /* Device is not discoverable. */ -#define BTA_DM_GENERAL_DISC BTM_GENERAL_DISCOVERABLE /* General discoverable. */ -#define BTA_DM_LIMITED_DISC BTM_LIMITED_DISCOVERABLE /* Limited discoverable. */ -#if ((defined BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) -#define BTA_DM_BLE_NON_DISCOVERABLE BTM_BLE_NON_DISCOVERABLE /* Device is not LE discoverable */ -#define BTA_DM_BLE_GENERAL_DISCOVERABLE BTM_BLE_GENERAL_DISCOVERABLE /* Device is LE General discoverable */ -#define BTA_DM_BLE_LIMITED_DISCOVERABLE BTM_BLE_LIMITED_DISCOVERABLE /* Device is LE Limited discoverable */ -#endif -typedef UINT16 tBTA_DM_DISC; /* this discoverability mode is a bit mask among BR mode and LE mode */ - -/* Connectable Modes */ -#define BTA_DM_NON_CONN BTM_NON_CONNECTABLE /* Device is not connectable. */ -#define BTA_DM_CONN BTM_CONNECTABLE /* Device is connectable. */ -#if ((defined BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) -#define BTA_DM_BLE_NON_CONNECTABLE BTM_BLE_NON_CONNECTABLE /* Device is LE non-connectable. */ -#define BTA_DM_BLE_CONNECTABLE BTM_BLE_CONNECTABLE /* Device is LE connectable. */ -#endif - -// btla-specific ++ -typedef UINT16 tBTA_DM_CONN; - -#define BTA_TRANSPORT_UNKNOWN 0 -#define BTA_TRANSPORT_BR_EDR BT_TRANSPORT_BR_EDR -#define BTA_TRANSPORT_LE BT_TRANSPORT_LE -typedef tBT_TRANSPORT tBTA_TRANSPORT; - -/* Pairable Modes */ -#define BTA_DM_PAIRABLE 1 -#define BTA_DM_NON_PAIRABLE 0 - -/* Connectable Paired Only Mode */ -#define BTA_DM_CONN_ALL 0 -#define BTA_DM_CONN_PAIRED 1 - -/* Inquiry Modes */ -#define BTA_DM_INQUIRY_NONE BTM_INQUIRY_NONE /*No BR inquiry. */ -#define BTA_DM_GENERAL_INQUIRY BTM_GENERAL_INQUIRY /* Perform general inquiry. */ -#define BTA_DM_LIMITED_INQUIRY BTM_LIMITED_INQUIRY /* Perform limited inquiry. */ - -#if ((defined BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) -#define BTA_BLE_INQUIRY_NONE BTM_BLE_INQUIRY_NONE -#define BTA_BLE_GENERAL_INQUIRY BTM_BLE_GENERAL_INQUIRY /* Perform LE general inquiry. */ -#define BTA_BLE_LIMITED_INQUIRY BTM_BLE_LIMITED_INQUIRY /* Perform LE limited inquiry. */ -#endif -typedef UINT8 tBTA_DM_INQ_MODE; - -/* Inquiry Filter Type */ -#define BTA_DM_INQ_CLR BTM_CLR_INQUIRY_FILTER /* Clear inquiry filter. */ -#define BTA_DM_INQ_DEV_CLASS BTM_FILTER_COND_DEVICE_CLASS /* Filter on device class. */ -#define BTA_DM_INQ_BD_ADDR BTM_FILTER_COND_BD_ADDR /* Filter on a specific BD address. */ - -typedef UINT8 tBTA_DM_INQ_FILT; - -/* Authorize Response */ -#define BTA_DM_AUTH_PERM 0 /* Authorized for future connections to the service */ -#define BTA_DM_AUTH_TEMP 1 /* Authorized for current connection only */ -#define BTA_DM_NOT_AUTH 2 /* Not authorized for the service */ - -typedef UINT8 tBTA_AUTH_RESP; - -/* M/S preferred roles */ -#define BTA_ANY_ROLE 0x00 -#define BTA_MASTER_ROLE_PREF 0x01 -#define BTA_MASTER_ROLE_ONLY 0x02 -#define BTA_SLAVE_ROLE_ONLY 0x03 /* Used for PANU only, skip role switch to master */ - -typedef UINT8 tBTA_PREF_ROLES; - -enum { - - BTA_DM_NO_SCATTERNET, /* Device doesn't support scatternet, it might - support "role switch during connection" for - an incoming connection, when it already has - another connection in master role */ - BTA_DM_PARTIAL_SCATTERNET, /* Device supports partial scatternet. It can have - simulateous connection in Master and Slave roles - for short period of time */ - BTA_DM_FULL_SCATTERNET /* Device can have simultaneous connection in master - and slave roles */ - -}; - - -/* Inquiry filter device class condition */ -typedef struct { - DEV_CLASS dev_class; /* device class of interest */ - DEV_CLASS dev_class_mask; /* mask to determine the bits of device class of interest */ -} tBTA_DM_COD_COND; - - -/* Inquiry Filter Condition */ -typedef union { - BD_ADDR bd_addr; /* BD address of device to filter. */ - tBTA_DM_COD_COND dev_class_cond; /* Device class filter condition */ -} tBTA_DM_INQ_COND; - -/* Inquiry Parameters */ -typedef struct { - tBTA_DM_INQ_MODE mode; /* Inquiry mode, limited or general. */ - UINT8 duration; /* Inquiry duration in 1.28 sec units. */ - UINT8 max_resps; /* Maximum inquiry responses. Set to zero for unlimited responses. */ - BOOLEAN report_dup; /* report duplicated inquiry response with higher RSSI value */ - tBTA_DM_INQ_FILT filter_type; /* Filter condition type. */ - tBTA_DM_INQ_COND filter_cond; /* Filter condition data. */ -#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE) - UINT8 intl_duration[4];/*duration array storing the interleave scan's time portions*/ -#endif -} tBTA_DM_INQ; - -typedef struct { - UINT8 bta_dm_eir_min_name_len; /* minimum length of local name when it is shortened */ -#if (BTA_EIR_CANNED_UUID_LIST == TRUE) - UINT8 bta_dm_eir_uuid16_len; /* length of 16-bit UUIDs */ - UINT8 *bta_dm_eir_uuid16; /* 16-bit UUIDs */ -#else - UINT32 uuid_mask[BTM_EIR_SERVICE_ARRAY_SIZE]; /* mask of UUID list in EIR */ -#endif - INT8 *bta_dm_eir_inq_tx_power; /* Inquiry TX power */ - UINT8 bta_dm_eir_flag_len; /* length of flags in bytes */ - UINT8 *bta_dm_eir_flags; /* flags for EIR */ - UINT8 bta_dm_eir_manufac_spec_len; /* length of manufacturer specific in bytes */ - UINT8 *bta_dm_eir_manufac_spec; /* manufacturer specific */ - UINT8 bta_dm_eir_additional_len; /* length of additional data in bytes */ - UINT8 *bta_dm_eir_additional; /* additional data */ -} tBTA_DM_EIR_CONF; - -#if BLE_INCLUDED == TRUE -/* ADV data flag bit definition used for BTM_BLE_AD_TYPE_FLAG */ -#define BTA_BLE_LIMIT_DISC_FLAG BTM_BLE_LIMIT_DISC_FLAG -#define BTA_BLE_GEN_DISC_FLAG BTM_BLE_GEN_DISC_FLAG -#define BTA_BLE_BREDR_NOT_SPT BTM_BLE_BREDR_NOT_SPT -#define BTA_BLE_DMT_CONTROLLER_SPT BTM_BLE_DMT_CONTROLLER_SPT -#define BTA_BLE_DMT_HOST_SPT BTM_BLE_DMT_HOST_SPT -#define BTA_BLE_NON_LIMIT_DISC_FLAG BTM_BLE_NON_LIMIT_DISC_FLAG -#define BTA_BLE_ADV_FLAG_MASK BTM_BLE_ADV_FLAG_MASK -#define BTA_BLE_LIMIT_DISC_MASK BTM_BLE_LIMIT_DISC_MASK - -/* ADV data bit mask */ -#define BTA_BLE_AD_BIT_DEV_NAME BTM_BLE_AD_BIT_DEV_NAME -#define BTA_BLE_AD_BIT_FLAGS BTM_BLE_AD_BIT_FLAGS -#define BTA_BLE_AD_BIT_MANU BTM_BLE_AD_BIT_MANU -#define BTA_BLE_AD_BIT_TX_PWR BTM_BLE_AD_BIT_TX_PWR -#define BTA_BLE_AD_BIT_INT_RANGE BTM_BLE_AD_BIT_INT_RANGE -#define BTA_BLE_AD_BIT_SERVICE BTM_BLE_AD_BIT_SERVICE -#define BTA_BLE_AD_BIT_APPEARANCE BTM_BLE_AD_BIT_APPEARANCE -#define BTA_BLE_AD_BIT_PROPRIETARY BTM_BLE_AD_BIT_PROPRIETARY -#define BTA_DM_BLE_AD_BIT_SERVICE_SOL BTM_BLE_AD_BIT_SERVICE_SOL -#define BTA_DM_BLE_AD_BIT_SERVICE_DATA BTM_BLE_AD_BIT_SERVICE_DATA -#define BTA_DM_BLE_AD_BIT_SIGN_DATA BTM_BLE_AD_BIT_SIGN_DATA -#define BTA_DM_BLE_AD_BIT_SERVICE_128SOL BTM_BLE_AD_BIT_SERVICE_128SOL -#define BTA_DM_BLE_AD_BIT_PUBLIC_ADDR BTM_BLE_AD_BIT_PUBLIC_ADDR -#define BTA_DM_BLE_AD_BIT_RANDOM_ADDR BTM_BLE_AD_BIT_RANDOM_ADDR -#define BTA_DM_BLE_AD_BIT_SERVICE_128 BTM_BLE_AD_BIT_SERVICE_128 /*128-bit Service UUIDs*/ - -typedef tBTM_BLE_AD_MASK tBTA_BLE_AD_MASK; - -/* slave preferred connection interval range */ -typedef struct { - UINT16 low; - UINT16 hi; - -} tBTA_BLE_INT_RANGE; - -/* Service tag supported in the device */ -typedef struct { - UINT8 num_service; - BOOLEAN list_cmpl; - UINT16 *p_uuid; -} tBTA_BLE_SERVICE; - - -typedef struct { - UINT8 len; - UINT8 *p_val; -} tBTA_BLE_MANU; - -typedef struct { - UINT8 adv_type; - UINT8 len; - UINT8 *p_val; /* number of len byte */ -} tBTA_BLE_PROP_ELEM; - -/* vendor proprietary adv type */ -typedef struct { - UINT8 num_elem; - tBTA_BLE_PROP_ELEM *p_elem; -} tBTA_BLE_PROPRIETARY; - -typedef struct { - tBT_UUID service_uuid; - UINT8 len; - UINT8 *p_val; -} tBTA_BLE_SERVICE_DATA; - -typedef tBTM_BLE_128SERVICE tBTA_BLE_128SERVICE; -typedef tBTM_BLE_32SERVICE tBTA_BLE_32SERVICE; - -typedef struct { - tBTA_BLE_INT_RANGE int_range; /* slave prefered conn interval range */ - tBTA_BLE_MANU *p_manu; /* manufacturer data */ - tBTA_BLE_SERVICE *p_services; /* 16 bits services */ - tBTA_BLE_128SERVICE *p_services_128b; /* 128 bits service */ - tBTA_BLE_32SERVICE *p_service_32b; /* 32 bits Service UUID */ - tBTA_BLE_SERVICE *p_sol_services; /* 16 bits services Solicitation UUIDs */ - tBTA_BLE_32SERVICE *p_sol_service_32b; /* List of 32 bit Service Solicitation UUIDs */ - tBTA_BLE_128SERVICE *p_sol_service_128b;/* List of 128 bit Service Solicitation UUIDs */ - tBTA_BLE_PROPRIETARY *p_proprietary; /* proprietary data */ - tBTA_BLE_SERVICE_DATA *p_service_data; /* service data */ - UINT16 appearance; /* appearance data */ - UINT8 flag; - UINT8 tx_power; -} tBTA_BLE_ADV_DATA; - -typedef void (tBTA_SET_ADV_DATA_CMPL_CBACK) (tBTA_STATUS status); - -typedef tBTM_START_ADV_CMPL_CBACK tBTA_START_ADV_CMPL_CBACK; - -typedef tBTM_START_STOP_ADV_CMPL_CBACK tBTA_START_STOP_ADV_CMPL_CBACK; - - -typedef tBTM_ADD_WHITELIST_CBACK tBTA_ADD_WHITELIST_CBACK; - -typedef tBTM_SET_PKT_DATA_LENGTH_CBACK tBTA_SET_PKT_DATA_LENGTH_CBACK; - -typedef tBTM_SET_RAND_ADDR_CBACK tBTA_SET_RAND_ADDR_CBACK; - -typedef tBTM_SET_LOCAL_PRIVACY_CBACK tBTA_SET_LOCAL_PRIVACY_CBACK; - -typedef tBTM_CMPL_CB tBTA_CMPL_CB; - -typedef tBTM_TX_POWER_RESULTS tBTA_TX_POWER_RESULTS; - -typedef tBTM_RSSI_RESULTS tBTA_RSSI_RESULTS; - -/* advertising channel map */ -#define BTA_BLE_ADV_CHNL_37 BTM_BLE_ADV_CHNL_37 -#define BTA_BLE_ADV_CHNL_38 BTM_BLE_ADV_CHNL_38 -#define BTA_BLE_ADV_CHNL_39 BTM_BLE_ADV_CHNL_39 -typedef tBTM_BLE_ADV_CHNL_MAP tBTA_BLE_ADV_CHNL_MAP; /* use as a bit mask */ - -/* advertising filter policy */ -typedef tBTM_BLE_AFP tBTA_BLE_AFP; - -/* adv event type */ -#define BTA_BLE_CONNECT_EVT BTM_BLE_CONNECT_EVT /* Connectable undirected advertising */ -#define BTA_BLE_CONNECT_DIR_EVT BTM_BLE_CONNECT_DIR_EVT /* Connectable directed advertising */ -#define BTA_BLE_DISCOVER_EVT BTM_BLE_DISCOVER_EVT /* Scannable undirected advertising */ -#define BTA_BLE_NON_CONNECT_EVT BTM_BLE_NON_CONNECT_EVT /* Non connectable undirected advertising */ -typedef UINT8 tBTA_BLE_ADV_EVT; - -/* adv tx power level */ -#define BTA_BLE_ADV_TX_POWER_MIN 0 /* minimum tx power */ -#define BTA_BLE_ADV_TX_POWER_LOW 1 /* low tx power */ -#define BTA_BLE_ADV_TX_POWER_MID 2 /* middle tx power */ -#define BTA_BLE_ADV_TX_POWER_UPPER 3 /* upper tx power */ -#define BTA_BLE_ADV_TX_POWER_MAX 4 /* maximum tx power */ -typedef UINT8 tBTA_BLE_ADV_TX_POWER; - -/* advertising instance parameters */ -typedef struct { - UINT16 adv_int_min; /* minimum adv interval */ - UINT16 adv_int_max; /* maximum adv interval */ - tBTA_BLE_ADV_EVT adv_type; /* adv event type */ - tBTA_BLE_ADV_CHNL_MAP channel_map; /* adv channel map */ - tBTA_BLE_AFP adv_filter_policy; /* advertising filter policy */ - tBTA_BLE_ADV_TX_POWER tx_power; /* adv tx power */ -} tBTA_BLE_ADV_PARAMS; - -/* These are the fields returned in each device adv packet. It -** is returned in the results callback if registered. -*/ -typedef struct { - UINT8 conn_mode; - tBTA_BLE_AD_MASK ad_mask; /* mask of the valid adv data field */ - UINT8 flag; - UINT8 tx_power_level; - UINT8 remote_name_len; - UINT8 *p_remote_name; - tBTA_BLE_SERVICE service; -} tBTA_BLE_INQ_DATA; - -enum { - BTA_BLE_BATCH_SCAN_MODE_PASS = 1, - BTA_BLE_BATCH_SCAN_MODE_ACTI = 2, - BTA_BLE_BATCH_SCAN_MODE_PASS_ACTI = 3 -}; -typedef UINT8 tBTA_BLE_BATCH_SCAN_MODE; - -enum { - BTA_BLE_DISCARD_OLD_ITEMS = 0, - BTA_BLE_DISCARD_LOWER_RSSI_ITEMS = 1 -}; -typedef UINT8 tBTA_BLE_DISCARD_RULE; - -enum { - BTA_BLE_ADV_SEEN_FIRST_TIME = 0, - BTA_BLE_ADV_TRACKING_TIMEOUT = 1 -}; -typedef UINT8 tBTA_BLE_ADV_CHANGE_REASON; - -enum { - BTA_BLE_BATCH_SCAN_ENB_EVT = 1, - BTA_BLE_BATCH_SCAN_CFG_STRG_EVT = 2, - BTA_BLE_BATCH_SCAN_DATA_EVT = 3, - BTA_BLE_BATCH_SCAN_THRES_EVT = 4, - BTA_BLE_BATCH_SCAN_PARAM_EVT = 5, - BTA_BLE_BATCH_SCAN_DIS_EVT = 6 -}; -typedef tBTM_BLE_BATCH_SCAN_EVT tBTA_BLE_BATCH_SCAN_EVT; - -typedef tBTM_BLE_TRACK_ADV_ACTION tBTA_BLE_TRACK_ADV_ACTION; -#endif - -/* BLE customer specific feature function type definitions */ -/* data type used on customer specific feature for RSSI monitoring */ -#define BTA_BLE_RSSI_ALERT_HI 0 -#define BTA_BLE_RSSI_ALERT_RANGE 1 -#define BTA_BLE_RSSI_ALERT_LO 2 -typedef UINT8 tBTA_DM_BLE_RSSI_ALERT_TYPE; - -#define BTA_BLE_RSSI_ALERT_NONE BTM_BLE_RSSI_ALERT_NONE /* (0) */ -#define BTA_BLE_RSSI_ALERT_HI_BIT BTM_BLE_RSSI_ALERT_HI_BIT /* (1) */ -#define BTA_BLE_RSSI_ALERT_RANGE_BIT BTM_BLE_RSSI_ALERT_RANGE_BIT /* (1 << 1) */ -#define BTA_BLE_RSSI_ALERT_LO_BIT BTM_BLE_RSSI_ALERT_LO_BIT /* (1 << 2) */ -typedef UINT8 tBTA_DM_BLE_RSSI_ALERT_MASK; - - -typedef void (tBTA_DM_BLE_RSSI_CBACK) (BD_ADDR bd_addr, tBTA_DM_BLE_RSSI_ALERT_TYPE alert_type, INT8 rssi); - -/* max number of filter spot for different filter type */ -#define BTA_DM_BLE_MAX_UUID_FILTER BTM_BLE_MAX_UUID_FILTER /* 8 */ -#define BTA_DM_BLE_MAX_ADDR_FILTER BTM_BLE_MAX_ADDR_FILTER /* 8 */ -#define BTA_DM_BLE_PF_STR_COND_MAX BTM_BLE_PF_STR_COND_MAX /* 4 apply to manu data , or local name */ -#define BTA_DM_BLE_PF_STR_LEN_MAX BTM_BLE_PF_STR_LEN_MAX /* match for first 20 bytes */ - -#define BTA_DM_BLE_PF_LOGIC_OR 0 -#define BTA_DM_BLE_PF_LOGIC_AND 1 -typedef UINT8 tBTA_DM_BLE_PF_LOGIC_TYPE; - -enum { - BTA_DM_BLE_SCAN_COND_ADD, - BTA_DM_BLE_SCAN_COND_DELETE, - BTA_DM_BLE_SCAN_COND_CLEAR = 2 -}; -typedef UINT8 tBTA_DM_BLE_SCAN_COND_OP; - -/* ADV payload filtering vendor specific call event */ -enum { - BTA_BLE_SCAN_PF_ENABLE_EVT = 7, - BTA_BLE_SCAN_PF_COND_EVT -}; - -/* filter selection bit index */ -#define BTA_DM_BLE_PF_ADDR_FILTER BTM_BLE_PF_ADDR_FILTER -#define BTA_DM_BLE_PF_SRVC_DATA BTM_BLE_PF_SRVC_DATA -#define BTA_DM_BLE_PF_SRVC_UUID BTM_BLE_PF_SRVC_UUID -#define BTA_DM_BLE_PF_SRVC_SOL_UUID BTM_BLE_PF_SRVC_SOL_UUID -#define BTA_DM_BLE_PF_LOCAL_NAME BTM_BLE_PF_LOCAL_NAME -#define BTA_DM_BLE_PF_MANU_DATA BTM_BLE_PF_MANU_DATA -#define BTA_DM_BLE_PF_SRVC_DATA_PATTERN BTM_BLE_PF_SRVC_DATA_PATTERN -#define BTA_DM_BLE_PF_TYPE_ALL BTM_BLE_PF_TYPE_ALL -#define BTA_DM_BLE_PF_TYPE_MAX BTM_BLE_PF_TYPE_MAX -typedef UINT8 tBTA_DM_BLE_PF_COND_TYPE; - -typedef union { - UINT16 uuid16_mask; - UINT32 uuid32_mask; - UINT8 uuid128_mask[LEN_UUID_128]; -} tBTA_DM_BLE_PF_COND_MASK; - -typedef struct { - tBLE_BD_ADDR *p_target_addr; /* target address, if NULL, generic UUID filter */ - tBT_UUID uuid; /* UUID condition */ - tBTA_DM_BLE_PF_LOGIC_TYPE cond_logic; /* AND/OR */ - tBTA_DM_BLE_PF_COND_MASK *p_uuid_mask; /* UUID condition mask, if NULL, match exact as UUID condition */ -} tBTA_DM_BLE_PF_UUID_COND; - -typedef struct { - UINT8 data_len; /* <= 20 bytes */ - UINT8 *p_data; -} tBTA_DM_BLE_PF_LOCAL_NAME_COND; - -typedef struct { - UINT16 company_id; /* company ID */ - UINT8 data_len; /* <= 20 bytes */ - UINT8 *p_pattern; - UINT16 company_id_mask; /* UUID value mask */ - UINT8 *p_pattern_mask; /* Manufacturer data matching mask, same length - as data pattern, set to all 0xff, match exact data */ -} tBTA_DM_BLE_PF_MANU_COND; - -typedef struct { - UINT16 uuid; /* service ID */ - UINT8 data_len; /* <= 20 bytes */ - UINT8 *p_pattern; - UINT8 *p_pattern_mask; /* Service data matching mask, same length - as data pattern, set to all 0xff, match exact data */ -} tBTA_DM_BLE_PF_SRVC_PATTERN_COND; - -typedef union { - tBLE_BD_ADDR target_addr; - tBTA_DM_BLE_PF_LOCAL_NAME_COND local_name; /* lcoal name filtering */ - tBTA_DM_BLE_PF_MANU_COND manu_data; /* manufactuer data filtering */ - tBTA_DM_BLE_PF_UUID_COND srvc_uuid; /* service UUID filtering */ - tBTA_DM_BLE_PF_UUID_COND solicitate_uuid; /* solicitated service UUID filtering */ - tBTA_DM_BLE_PF_SRVC_PATTERN_COND srvc_data; /* service data pattern */ -} tBTA_DM_BLE_PF_COND_PARAM; - -typedef UINT8 tBTA_DM_BLE_PF_FILT_INDEX; -typedef UINT8 tBTA_DM_BLE_PF_AVBL_SPACE; - -typedef INT8 tBTA_DM_RSSI_VALUE; -typedef UINT8 tBTA_DM_LINK_QUALITY_VALUE; - - -typedef UINT8 tBTA_SIG_STRENGTH_MASK; - - -/* Security Callback Events */ -#define BTA_DM_ENABLE_EVT 0 /* Enable Event */ -#define BTA_DM_DISABLE_EVT 1 /* Disable Event */ -#define BTA_DM_PIN_REQ_EVT 2 /* PIN request. */ -#define BTA_DM_AUTH_CMPL_EVT 3 /* Authentication complete indication. */ -#define BTA_DM_AUTHORIZE_EVT 4 /* Authorization request. */ -#define BTA_DM_LINK_UP_EVT 5 /* Connection UP event */ -#define BTA_DM_LINK_DOWN_EVT 6 /* Connection DOWN event */ -#define BTA_DM_SIG_STRENGTH_EVT 7 /* Signal strength for bluetooth connection */ -#define BTA_DM_BUSY_LEVEL_EVT 8 /* System busy level */ -#define BTA_DM_BOND_CANCEL_CMPL_EVT 9 /* Bond cancel complete indication */ -#define BTA_DM_SP_CFM_REQ_EVT 10 /* Simple Pairing User Confirmation request. */ -#define BTA_DM_SP_KEY_NOTIF_EVT 11 /* Simple Pairing Passkey Notification */ -#define BTA_DM_SP_RMT_OOB_EVT 12 /* Simple Pairing Remote OOB Data request. */ -#define BTA_DM_SP_KEYPRESS_EVT 13 /* Key press notification event. */ -#define BTA_DM_ROLE_CHG_EVT 14 /* Role Change event. */ -#define BTA_DM_BLE_KEY_EVT 15 /* BLE SMP key event for peer device keys */ -#define BTA_DM_BLE_SEC_REQ_EVT 16 /* BLE SMP security request */ -#define BTA_DM_BLE_PASSKEY_NOTIF_EVT 17 /* SMP passkey notification event */ -#define BTA_DM_BLE_PASSKEY_REQ_EVT 18 /* SMP passkey request event */ -#define BTA_DM_BLE_OOB_REQ_EVT 19 /* SMP OOB request event */ -#define BTA_DM_BLE_LOCAL_IR_EVT 20 /* BLE local IR event */ -#define BTA_DM_BLE_LOCAL_ER_EVT 21 /* BLE local ER event */ -#define BTA_DM_BLE_NC_REQ_EVT 22 /* SMP Numeric Comparison request event */ -// btla-specific ++ -#define BTA_DM_SP_RMT_OOB_EXT_EVT 23 /* Simple Pairing Remote OOB Extended Data request. */ -#define BTA_DM_BLE_AUTH_CMPL_EVT 24 /* BLE Auth complete */ -// btla-specific -- -#define BTA_DM_DEV_UNPAIRED_EVT 25 -#define BTA_DM_HW_ERROR_EVT 26 /* BT Chip H/W error */ -#define BTA_DM_LE_FEATURES_READ 27 /* Cotroller specific LE features are read */ -#define BTA_DM_ENER_INFO_READ 28 /* Energy info read */ -typedef UINT8 tBTA_DM_SEC_EVT; - -/* Structure associated with BTA_DM_ENABLE_EVT */ -typedef struct { - tBTA_STATUS status; -} tBTA_DM_ENABLE; - -/* Structure associated with BTA_DM_PIN_REQ_EVT */ -typedef struct { - /* Note: First 3 data members must be, bd_addr, dev_class, and bd_name in order */ - BD_ADDR bd_addr; /* BD address peer device. */ - DEV_CLASS dev_class; /* Class of Device */ - BD_NAME bd_name; /* Name of peer device. */ - BOOLEAN min_16_digit; /* TRUE if the pin returned must be at least 16 digits */ -} tBTA_DM_PIN_REQ; - -/* BLE related definition */ -#if (SMP_INCLUDED == TRUE) -#define BTA_DM_AUTH_FAIL_BASE (HCI_ERR_MAX_ERR + 10) -#define BTA_DM_AUTH_CONVERT_SMP_CODE(x) (BTA_DM_AUTH_FAIL_BASE + (x)) -#define BTA_DM_AUTH_SMP_PASSKEY_FAIL BTA_DM_AUTH_CONVERT_SMP_CODE (SMP_PASSKEY_ENTRY_FAIL) -#define BTA_DM_AUTH_SMP_OOB_FAIL (BTA_DM_AUTH_FAIL_BASE + SMP_OOB_FAIL) -#define BTA_DM_AUTH_SMP_PAIR_AUTH_FAIL (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_AUTH_FAIL) -#define BTA_DM_AUTH_SMP_CONFIRM_VALUE_FAIL (BTA_DM_AUTH_FAIL_BASE + SMP_CONFIRM_VALUE_ERR) -#define BTA_DM_AUTH_SMP_PAIR_NOT_SUPPORT (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_NOT_SUPPORT) -#define BTA_DM_AUTH_SMP_ENC_KEY_SIZE (BTA_DM_AUTH_FAIL_BASE + SMP_ENC_KEY_SIZE) -#define BTA_DM_AUTH_SMP_INVALID_CMD (BTA_DM_AUTH_FAIL_BASE + SMP_INVALID_CMD) -#define BTA_DM_AUTH_SMP_UNKNOWN_ERR (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_FAIL_UNKNOWN) -#define BTA_DM_AUTH_SMP_REPEATED_ATTEMPT (BTA_DM_AUTH_FAIL_BASE + SMP_REPEATED_ATTEMPTS) -#define BTA_DM_AUTH_SMP_INVALID_PARAMETERS (BTA_DM_AUTH_FAIL_BASE + SMP_INVALID_PARAMETERS) -#define BTA_DM_AUTH_SMP_INTERNAL_ERR (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_INTERNAL_ERR) -#define BTA_DM_AUTH_SMP_UNKNOWN_IO (BTA_DM_AUTH_FAIL_BASE + SMP_UNKNOWN_IO_CAP) -#define BTA_DM_AUTH_SMP_INIT_FAIL (BTA_DM_AUTH_FAIL_BASE + SMP_INIT_FAIL) -#define BTA_DM_AUTH_SMP_CONFIRM_FAIL (BTA_DM_AUTH_FAIL_BASE + SMP_CONFIRM_FAIL) -#define BTA_DM_AUTH_SMP_BUSY (BTA_DM_AUTH_FAIL_BASE + SMP_BUSY) -#define BTA_DM_AUTH_SMP_ENC_FAIL (BTA_DM_AUTH_FAIL_BASE + SMP_ENC_FAIL) -#define BTA_DM_AUTH_SMP_RSP_TIMEOUT (BTA_DM_AUTH_FAIL_BASE + SMP_RSP_TIMEOUT) -#endif ///SMP_INCLUDED == TRUE -/* connection parameter boundary value and dummy value */ -#define BTA_DM_BLE_SCAN_INT_MIN BTM_BLE_SCAN_INT_MIN -#define BTA_DM_BLE_SCAN_INT_MAX BTM_BLE_SCAN_INT_MAX -#define BTA_DM_BLE_SCAN_WIN_MIN BTM_BLE_SCAN_WIN_MIN -#define BTA_DM_BLE_SCAN_WIN_MAX BTM_BLE_SCAN_WIN_MAX -#define BTA_DM_BLE_CONN_INT_MIN BTM_BLE_CONN_INT_MIN -#define BTA_DM_BLE_CONN_INT_MAX BTM_BLE_CONN_INT_MAX -#define BTA_DM_BLE_CONN_LATENCY_MAX BTM_BLE_CONN_LATENCY_MAX -#define BTA_DM_BLE_CONN_SUP_TOUT_MIN BTM_BLE_CONN_SUP_TOUT_MIN -#define BTA_DM_BLE_CONN_SUP_TOUT_MAX BTM_BLE_CONN_SUP_TOUT_MAX -#define BTA_DM_BLE_CONN_PARAM_UNDEF BTM_BLE_CONN_PARAM_UNDEF /* use this value when a specific value not to be overwritten */ - -#if (SMP_INCLUDED == TRUE) -#define BTA_LE_KEY_PENC BTM_LE_KEY_PENC /* encryption information of peer device */ -#define BTA_LE_KEY_PID BTM_LE_KEY_PID /* identity key of the peer device */ -#define BTA_LE_KEY_PCSRK BTM_LE_KEY_PCSRK /* peer SRK */ -#define BTA_LE_KEY_LENC BTM_LE_KEY_LENC /* master role security information:div */ -#define BTA_LE_KEY_LID BTM_LE_KEY_LID /* master device ID key */ -#define BTA_LE_KEY_LCSRK BTM_LE_KEY_LCSRK /* local CSRK has been deliver to peer */ -#endif ///SMP_INCLUDED == TRUE -typedef UINT8 tBTA_LE_KEY_TYPE; /* can be used as a bit mask */ - - -typedef tBTM_LE_PENC_KEYS tBTA_LE_PENC_KEYS ; -typedef tBTM_LE_PCSRK_KEYS tBTA_LE_PCSRK_KEYS; -typedef tBTM_LE_LENC_KEYS tBTA_LE_LENC_KEYS ; -typedef tBTM_LE_LCSRK_KEYS tBTA_LE_LCSRK_KEYS ; -typedef tBTM_LE_PID_KEYS tBTA_LE_PID_KEYS ; - -typedef union { - tBTA_LE_PENC_KEYS penc_key; /* received peer encryption key */ - tBTA_LE_PCSRK_KEYS psrk_key; /* received peer device SRK */ - tBTA_LE_PID_KEYS pid_key; /* peer device ID key */ - tBTA_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys LTK = = d1(ER,DIV,0)*/ - tBTA_LE_LCSRK_KEYS lcsrk_key; /* local device CSRK = d1(ER,DIV,1)*/ - tBTA_LE_PID_KEYS lid_key; /* local device ID key for the particular remote */ -} tBTA_LE_KEY_VALUE; - -#define BTA_BLE_LOCAL_KEY_TYPE_ID 1 -#define BTA_BLE_LOCAL_KEY_TYPE_ER 2 -typedef UINT8 tBTA_DM_BLE_LOCAL_KEY_MASK; - -typedef struct { - BT_OCTET16 ir; - BT_OCTET16 irk; - BT_OCTET16 dhk; -} tBTA_BLE_LOCAL_ID_KEYS; -#if (SMP_INCLUDED == TRUE) -#define BTA_DM_SEC_GRANTED BTA_SUCCESS -#define BTA_DM_SEC_PAIR_NOT_SPT BTA_DM_AUTH_SMP_PAIR_NOT_SUPPORT -#define BTA_DM_SEC_REP_ATTEMPTS BTA_DM_AUTH_SMP_REPEATED_ATTEMPT -#endif ///SMP_INCLUDED == TRUE -typedef UINT8 tBTA_DM_BLE_SEC_GRANT; - - -#define BTA_DM_BLE_ONN_NONE BTM_BLE_CONN_NONE -#define BTA_DM_BLE_CONN_AUTO BTM_BLE_CONN_AUTO -#define BTA_DM_BLE_CONN_SELECTIVE BTM_BLE_CONN_SELECTIVE -typedef UINT8 tBTA_DM_BLE_CONN_TYPE; - -typedef BOOLEAN (tBTA_DM_BLE_SEL_CBACK)(BD_ADDR random_bda, UINT8 *p_remote_name); - -typedef tBTM_LE_UPDATE_CONN_PRAMS tBTA_LE_UPDATE_CONN_PRAMS; -typedef tBTM_UPDATE_CONN_PARAM_CBACK tBTA_UPDATE_CONN_PARAM_CBACK; - - -/* Structure associated with BTA_DM_BLE_SEC_REQ_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - BD_NAME bd_name; /* peer device name */ -} tBTA_DM_BLE_SEC_REQ; - -typedef struct { - BD_ADDR bd_addr; /* peer address */ - tBTM_LE_KEY_TYPE key_type; - tBTM_LE_KEY_VALUE *p_key_value; -} tBTA_DM_BLE_KEY; - -/* Structure associated with BTA_DM_AUTH_CMPL_EVT */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ - BD_NAME bd_name; /* Name of peer device. */ - BOOLEAN key_present; /* Valid link key value in key element */ - LINK_KEY key; /* Link key associated with peer device. */ - UINT8 key_type; /* The type of Link Key */ - BOOLEAN success; /* TRUE of authentication succeeded, FALSE if failed. */ - UINT8 fail_reason; /* The HCI reason/error code for when success=FALSE */ - tBLE_ADDR_TYPE addr_type; /* Peer device address type */ - tBT_DEVICE_TYPE dev_type; -} tBTA_DM_AUTH_CMPL; - - -/* Structure associated with BTA_DM_AUTHORIZE_EVT */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ - BD_NAME bd_name; /* Name of peer device. */ - tBTA_SERVICE_ID service; /* Service ID to authorize. */ -// btla-specific ++ - DEV_CLASS dev_class; -// btla-specific -- -} tBTA_DM_AUTHORIZE; - -/* Structure associated with BTA_DM_LINK_UP_EVT */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ -#if BLE_INCLUDED == TRUE - tBTA_TRANSPORT link_type; -#endif -} tBTA_DM_LINK_UP; - -/* Structure associated with BTA_DM_LINK_DOWN_EVT */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ - UINT8 status; /* connection open/closed */ - UINT8 reason; /* link down reason */ - BOOLEAN is_removed; /* TRUE if device is removed when link is down */ -#if BLE_INCLUDED == TRUE - tBTA_TRANSPORT link_type; -#endif -} tBTA_DM_LINK_DOWN; - -/* Structure associated with BTA_DM_ROLE_CHG_EVT */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ - UINT8 new_role; /* the new connection role */ -} tBTA_DM_ROLE_CHG; - -/* Structure associated with BTA_DM_BUSY_LEVEL_EVT */ -typedef struct { - UINT8 level; /* when paging or inquiring, level is 10. - Otherwise, the number of ACL links */ - UINT8 level_flags; /* indicates individual flags */ -} tBTA_DM_BUSY_LEVEL; - -#define BTA_IO_CAP_OUT BTM_IO_CAP_OUT /* 0 DisplayOnly */ -#define BTA_IO_CAP_IO BTM_IO_CAP_IO /* 1 DisplayYesNo */ -#define BTA_IO_CAP_IN BTM_IO_CAP_IN /* 2 KeyboardOnly */ -#define BTA_IO_CAP_NONE BTM_IO_CAP_NONE /* 3 NoInputNoOutput */ -#if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE -#define BTA_IO_CAP_KBDISP BTM_IO_CAP_KBDISP /* 4 Keyboard display */ -#endif -typedef tBTM_IO_CAP tBTA_IO_CAP; - -#define BTA_AUTH_SP_NO BTM_AUTH_SP_NO /* 0 MITM Protection Not Required - Single Profile/non-bonding - Numeric comparison with automatic accept allowed */ -#define BTA_AUTH_SP_YES BTM_AUTH_SP_YES /* 1 MITM Protection Required - Single Profile/non-bonding - Use IO Capabilities to determine authentication procedure */ -#define BTA_AUTH_AP_NO BTM_AUTH_AP_NO /* 2 MITM Protection Not Required - All Profiles/dedicated bonding - Numeric comparison with automatic accept allowed */ -#define BTA_AUTH_AP_YES BTM_AUTH_AP_YES /* 3 MITM Protection Required - All Profiles/dedicated bonding - Use IO Capabilities to determine authentication procedure */ -#define BTA_AUTH_SPGB_NO BTM_AUTH_SPGB_NO /* 4 MITM Protection Not Required - Single Profiles/general bonding - Numeric comparison with automatic accept allowed */ -#define BTA_AUTH_SPGB_YES BTM_AUTH_SPGB_YES /* 5 MITM Protection Required - Single Profiles/general bonding - Use IO Capabilities to determine authentication procedure */ -typedef tBTM_AUTH_REQ tBTA_AUTH_REQ; - -#define BTA_AUTH_DD_BOND BTM_AUTH_DD_BOND /* 2 this bit is set for dedicated bonding */ -#define BTA_AUTH_GEN_BOND BTM_AUTH_SPGB_NO /* 4 this bit is set for general bonding */ -#define BTA_AUTH_BONDS BTM_AUTH_BONDS /* 6 the general/dedicated bonding bits */ - -#if (SMP_INCLUDED == TRUE) -#define BTA_LE_AUTH_NO_BOND BTM_LE_AUTH_REQ_NO_BOND /* 0*/ -#define BTA_LE_AUTH_BOND BTM_LE_AUTH_REQ_BOND /* 1 << 0 */ -#define BTA_LE_AUTH_REQ_MITM BTM_LE_AUTH_REQ_MITM /* 1 << 2 */ - -#define BTA_LE_AUTH_REQ_SC_ONLY BTM_LE_AUTH_REQ_SC_ONLY /* 1 << 3 */ -#define BTA_LE_AUTH_REQ_SC_BOND BTM_LE_AUTH_REQ_SC_BOND /* 1001 */ -#define BTA_LE_AUTH_REQ_SC_MITM BTM_LE_AUTH_REQ_SC_MITM /* 1100 */ -#define BTA_LE_AUTH_REQ_SC_MITM_BOND BTM_LE_AUTH_REQ_SC_MITM_BOND /* 1101 */ -#endif ///SMP_INCLUDED == TRUE -typedef tBTM_LE_AUTH_REQ tBTA_LE_AUTH_REQ; /* combination of the above bit pattern */ - -#define BTA_OOB_NONE BTM_OOB_NONE -#define BTA_OOB_PRESENT BTM_OOB_PRESENT -#if BTM_OOB_INCLUDED == TRUE -#define BTA_OOB_UNKNOWN BTM_OOB_UNKNOWN -#endif -typedef tBTM_OOB_DATA tBTA_OOB_DATA; - -/* Structure associated with BTA_DM_SP_CFM_REQ_EVT */ -typedef struct { - /* Note: First 3 data members must be, bd_addr, dev_class, and bd_name in order */ - BD_ADDR bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - BD_NAME bd_name; /* peer device name */ - UINT32 num_val; /* the numeric value for comparison. If just_works, do not show this number to UI */ - BOOLEAN just_works; /* TRUE, if "Just Works" association model */ - tBTA_AUTH_REQ loc_auth_req; /* Authentication required for local device */ - tBTA_AUTH_REQ rmt_auth_req; /* Authentication required for peer device */ - tBTA_IO_CAP loc_io_caps; /* IO Capabilities of local device */ - tBTA_AUTH_REQ rmt_io_caps; /* IO Capabilities of remote device */ -} tBTA_DM_SP_CFM_REQ; - -enum { - BTA_SP_KEY_STARTED, /* passkey entry started */ - BTA_SP_KEY_ENTERED, /* passkey digit entered */ - BTA_SP_KEY_ERASED, /* passkey digit erased */ - BTA_SP_KEY_CLEARED, /* passkey cleared */ - BTA_SP_KEY_COMPLT /* passkey entry completed */ -}; -typedef UINT8 tBTA_SP_KEY_TYPE; - -/* Structure associated with BTA_DM_SP_KEYPRESS_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - tBTA_SP_KEY_TYPE notif_type; -} tBTA_DM_SP_KEY_PRESS; - -/* Structure associated with BTA_DM_SP_KEY_NOTIF_EVT */ -typedef struct { - /* Note: First 3 data members must be, bd_addr, dev_class, and bd_name in order */ - BD_ADDR bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - BD_NAME bd_name; /* peer device name */ - UINT32 passkey; /* the numeric value for comparison. If just_works, do not show this number to UI */ -} tBTA_DM_SP_KEY_NOTIF; - -/* Structure associated with BTA_DM_SP_RMT_OOB_EVT */ -typedef struct { - /* Note: First 3 data members must be, bd_addr, dev_class, and bd_name in order */ - BD_ADDR bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - BD_NAME bd_name; /* peer device name */ -} tBTA_DM_SP_RMT_OOB; - -/* Structure associated with BTA_DM_BOND_CANCEL_CMPL_EVT */ -typedef struct { - tBTA_STATUS result; /* TRUE of bond cancel succeeded, FALSE if failed. */ -} tBTA_DM_BOND_CANCEL_CMPL; - -/* Union of all security callback structures */ -typedef union { - tBTA_DM_ENABLE enable; /* BTA enabled */ - tBTA_DM_PIN_REQ pin_req; /* PIN request. */ - tBTA_DM_AUTH_CMPL auth_cmpl; /* Authentication complete indication. */ - tBTA_DM_AUTHORIZE authorize; /* Authorization request. */ - tBTA_DM_LINK_UP link_up; /* ACL connection down event */ - tBTA_DM_LINK_DOWN link_down; /* ACL connection down event */ - tBTA_DM_BUSY_LEVEL busy_level; /* System busy level */ - tBTA_DM_SP_CFM_REQ cfm_req; /* user confirm request */ - tBTA_DM_SP_KEY_NOTIF key_notif; /* passkey notification */ - tBTA_DM_SP_RMT_OOB rmt_oob; /* remote oob */ - tBTA_DM_BOND_CANCEL_CMPL bond_cancel_cmpl; /* Bond Cancel Complete indication */ - tBTA_DM_SP_KEY_PRESS key_press; /* key press notification event */ - tBTA_DM_ROLE_CHG role_chg; /* role change event */ - tBTA_DM_BLE_SEC_REQ ble_req; /* BLE SMP related request */ - tBTA_DM_BLE_KEY ble_key; /* BLE SMP keys used when pairing */ - tBTA_BLE_LOCAL_ID_KEYS ble_id_keys; /* IR event */ - BT_OCTET16 ble_er; /* ER event data */ -} tBTA_DM_SEC; - -/* Security callback */ -typedef void (tBTA_DM_SEC_CBACK)(tBTA_DM_SEC_EVT event, tBTA_DM_SEC *p_data); - -#define BTA_BLE_MULTI_ADV_ILLEGAL 0 - -/* multi adv callback event */ -#define BTA_BLE_MULTI_ADV_ENB_EVT 1 -#define BTA_BLE_MULTI_ADV_DISABLE_EVT 2 -#define BTA_BLE_MULTI_ADV_PARAM_EVT 3 -#define BTA_BLE_MULTI_ADV_DATA_EVT 4 - -typedef UINT8 tBTA_BLE_MULTI_ADV_EVT; - -/* multi adv callback */ -typedef void (tBTA_BLE_MULTI_ADV_CBACK)(tBTA_BLE_MULTI_ADV_EVT event, - UINT8 inst_id, void *p_ref, tBTA_STATUS status); -typedef UINT32 tBTA_DM_BLE_REF_VALUE; - -#define BTA_DM_BLE_PF_ENABLE_EVT BTM_BLE_PF_ENABLE -#define BTA_DM_BLE_PF_CONFIG_EVT BTM_BLE_PF_CONFIG -typedef UINT8 tBTA_DM_BLE_PF_EVT; - -#define BTA_DM_BLE_PF_ENABLE 1 -#define BTA_DM_BLE_PF_CONFIG 2 -typedef UINT8 tBTA_DM_BLE_PF_ACTION; - -/* Config callback */ -typedef void (tBTA_DM_BLE_PF_CFG_CBACK) (tBTA_DM_BLE_PF_ACTION action, - tBTA_DM_BLE_PF_COND_TYPE cfg_cond, - tBTA_DM_BLE_PF_AVBL_SPACE avbl_space, tBTA_STATUS status, - tBTA_DM_BLE_REF_VALUE ref_value); -/* Param callback */ -typedef void (tBTA_DM_BLE_PF_PARAM_CBACK) (UINT8 action_type, tBTA_DM_BLE_PF_AVBL_SPACE avbl_space, - tBTA_DM_BLE_REF_VALUE ref_value, tBTA_STATUS status); - -/* Status callback */ -typedef void (tBTA_DM_BLE_PF_STATUS_CBACK) (UINT8 action, tBTA_STATUS status, - tBTA_DM_BLE_REF_VALUE ref_value); - - -#define BTA_DM_BLE_PF_BRDCAST_ADDR_FILT 1 -#define BTA_DM_BLE_PF_SERV_DATA_CHG_FILT 2 -#define BTA_DM_BLE_PF_SERV_UUID 4 -#define BTA_DM_BLE_PF_SERV_SOLC_UUID 8 -#define BTA_DM_BLE_PF_LOC_NAME_CHECK 16 -#define BTA_DM_BLE_PF_MANUF_NAME_CHECK 32 -#define BTA_DM_BLE_PF_SERV_DATA_CHECK 64 -typedef UINT16 tBTA_DM_BLE_PF_FEAT_SEL; - -#define BTA_DM_BLE_PF_LIST_LOGIC_OR 1 -#define BTA_DM_BLE_PF_LIST_LOGIC_AND 2 -typedef UINT16 tBTA_DM_BLE_PF_LIST_LOGIC_TYPE; - -#define BTA_DM_BLE_PF_FILT_LOGIC_OR 0 -#define BTA_DM_BLE_PF_FILT_LOGIC_AND 1 -typedef UINT16 tBTA_DM_BLE_PF_FILT_LOGIC_TYPE; - -typedef UINT8 tBTA_DM_BLE_PF_RSSI_THRESHOLD; -typedef UINT8 tBTA_DM_BLE_PF_DELIVERY_MODE; -typedef UINT16 tBTA_DM_BLE_PF_TIMEOUT; -typedef UINT8 tBTA_DM_BLE_PF_TIMEOUT_CNT; -typedef UINT16 tBTA_DM_BLE_PF_ADV_TRACK_ENTRIES; - -typedef struct { - tBTA_DM_BLE_PF_FEAT_SEL feat_seln; - tBTA_DM_BLE_PF_LIST_LOGIC_TYPE list_logic_type; - tBTA_DM_BLE_PF_FILT_LOGIC_TYPE filt_logic_type; - tBTA_DM_BLE_PF_RSSI_THRESHOLD rssi_high_thres; - tBTA_DM_BLE_PF_RSSI_THRESHOLD rssi_low_thres; - tBTA_DM_BLE_PF_DELIVERY_MODE dely_mode; - tBTA_DM_BLE_PF_TIMEOUT found_timeout; - tBTA_DM_BLE_PF_TIMEOUT lost_timeout; - tBTA_DM_BLE_PF_TIMEOUT_CNT found_timeout_cnt; - tBTA_DM_BLE_PF_ADV_TRACK_ENTRIES num_of_tracking_entries; -} tBTA_DM_BLE_PF_FILT_PARAMS; - -/* Search callback events */ -#define BTA_DM_INQ_RES_EVT 0 /* Inquiry result for a peer device. */ -#define BTA_DM_INQ_CMPL_EVT 1 /* Inquiry complete. */ -#define BTA_DM_DISC_RES_EVT 2 /* Discovery result for a peer device. */ -#define BTA_DM_DISC_BLE_RES_EVT 3 /* Discovery result for BLE GATT based servoce on a peer device. */ -#define BTA_DM_DISC_CMPL_EVT 4 /* Discovery complete. */ -#define BTA_DM_DI_DISC_CMPL_EVT 5 /* Discovery complete. */ -#define BTA_DM_SEARCH_CANCEL_CMPL_EVT 6 /* Search cancelled */ - -typedef UINT8 tBTA_DM_SEARCH_EVT; - -#define BTA_DM_INQ_RES_IGNORE_RSSI BTM_INQ_RES_IGNORE_RSSI /* 0x7f RSSI value not supplied (ignore it) */ - -/* Structure associated with BTA_DM_INQ_RES_EVT */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ - DEV_CLASS dev_class; /* Device class of peer device. */ - BOOLEAN remt_name_not_required; /* Application sets this flag if it already knows the name of the device */ - /* If the device name is known to application BTA skips the remote name request */ - BOOLEAN is_limited; /* TRUE, if the limited inquiry bit is set in the CoD */ - INT8 rssi; /* The rssi value */ - UINT8 *p_eir; /* received EIR */ -#if (BLE_INCLUDED == TRUE) - UINT8 inq_result_type; - UINT8 ble_addr_type; - tBTM_BLE_EVT_TYPE ble_evt_type; - tBT_DEVICE_TYPE device_type; - UINT8 flag; - UINT8 adv_data_len; - UINT8 scan_rsp_len; -#endif - -} tBTA_DM_INQ_RES; - -/* Structure associated with BTA_DM_INQ_CMPL_EVT */ -typedef struct { - UINT8 num_resps; /* Number of inquiry responses. */ -} tBTA_DM_INQ_CMPL; - -/* Structure associated with BTA_DM_DI_DISC_CMPL_EVT */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ - UINT8 num_record; /* Number of DI record */ - tBTA_STATUS result; -} tBTA_DM_DI_DISC_CMPL; - -/* Structure associated with BTA_DM_DISC_RES_EVT */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ - BD_NAME bd_name; /* Name of peer device. */ - tBTA_SERVICE_MASK services; /* Services found on peer device. */ -// btla-specific ++ - UINT8 *p_raw_data; /* Raw data for discovery DB */ - UINT32 raw_data_size; /* size of raw data */ - tBT_DEVICE_TYPE device_type; /* device type in case it is BLE device */ - UINT32 num_uuids; - UINT8 *p_uuid_list; -// btla-specific -- - tBTA_STATUS result; -} tBTA_DM_DISC_RES; - -/* Structure associated with tBTA_DM_DISC_BLE_RES */ -typedef struct { - BD_ADDR bd_addr; /* BD address peer device. */ - BD_NAME bd_name; /* Name of peer device. */ - tBT_UUID service; /* GATT based Services UUID found on peer device. */ -} tBTA_DM_DISC_BLE_RES; - - -/* Union of all search callback structures */ -typedef union { - tBTA_DM_INQ_RES inq_res; /* Inquiry result for a peer device. */ - tBTA_DM_INQ_CMPL inq_cmpl; /* Inquiry complete. */ - tBTA_DM_DISC_RES disc_res; /* Discovery result for a peer device. */ - tBTA_DM_DISC_BLE_RES disc_ble_res; /* discovery result for GATT based service */ - tBTA_DM_DI_DISC_CMPL di_disc; /* DI discovery result for a peer device */ - -} tBTA_DM_SEARCH; - -/* Search callback */ -typedef void (tBTA_DM_SEARCH_CBACK)(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH *p_data); - -/* Execute call back */ -typedef void (tBTA_DM_EXEC_CBACK) (void *p_param); - -/* Encryption callback*/ -typedef void (tBTA_DM_ENCRYPT_CBACK) (BD_ADDR bd_addr, tBTA_TRANSPORT transport, tBTA_STATUS result); - -/* relate to ESP_BLE_SEC_xxx in esp_gatt_defs.h */ -#if BLE_INCLUDED == TRUE -#define BTA_DM_BLE_SEC_NONE BTM_BLE_SEC_NONE -#define BTA_DM_BLE_SEC_ENCRYPT BTM_BLE_SEC_ENCRYPT -#define BTA_DM_BLE_SEC_NO_MITM BTM_BLE_SEC_ENCRYPT_NO_MITM -#define BTA_DM_BLE_SEC_MITM BTM_BLE_SEC_ENCRYPT_MITM -typedef tBTM_BLE_SEC_ACT tBTA_DM_BLE_SEC_ACT; - -typedef tBTM_BLE_TX_TIME_MS tBTA_DM_BLE_TX_TIME_MS; -typedef tBTM_BLE_RX_TIME_MS tBTA_DM_BLE_RX_TIME_MS; -typedef tBTM_BLE_IDLE_TIME_MS tBTA_DM_BLE_IDLE_TIME_MS; -typedef tBTM_BLE_ENERGY_USED tBTA_DM_BLE_ENERGY_USED; - -#define BTA_DM_CONTRL_UNKNOWN 0 /* Unknown state */ -#define BTA_DM_CONTRL_ACTIVE 1 /* ACL link on, SCO link ongoing, sniff mode */ -#define BTA_DM_CONTRL_SCAN 2 /* Scan state - paging/inquiry/trying to connect*/ -#define BTA_DM_CONTRL_IDLE 3 /* Idle state - page scan, LE advt, inquiry scan */ - -typedef UINT8 tBTA_DM_CONTRL_STATE; - -typedef UINT8 tBTA_DM_BLE_ADV_STATE; -typedef UINT8 tBTA_DM_BLE_ADV_INFO_PRESENT; -typedef UINT8 tBTA_DM_BLE_RSSI_VALUE; -typedef UINT16 tBTA_DM_BLE_ADV_INFO_TIMESTAMP; - -typedef tBTM_BLE_TRACK_ADV_DATA tBTA_DM_BLE_TRACK_ADV_DATA; - -typedef void (tBTA_BLE_SCAN_THRESHOLD_CBACK)(tBTA_DM_BLE_REF_VALUE ref_value); - -typedef void (tBTA_BLE_SCAN_REP_CBACK) (tBTA_DM_BLE_REF_VALUE ref_value, UINT8 report_format, - UINT8 num_records, UINT16 data_len, - UINT8 *p_rep_data, tBTA_STATUS status); - -typedef void (tBTA_BLE_SCAN_SETUP_CBACK) (tBTA_BLE_BATCH_SCAN_EVT evt, - tBTA_DM_BLE_REF_VALUE ref_value, - tBTA_STATUS status); - -typedef void (tBTA_START_STOP_SCAN_CMPL_CBACK) (tBTA_STATUS status); - -typedef void (tBTA_START_STOP_ADV_CMPL_CBACK) (tBTA_STATUS status); - -typedef void (tBTA_BLE_TRACK_ADV_CMPL_CBACK)(int action, tBTA_STATUS status, - tBTA_DM_BLE_PF_AVBL_SPACE avbl_space, - tBTA_DM_BLE_REF_VALUE ref_value); - -typedef void (tBTA_BLE_TRACK_ADV_CBACK)(tBTA_DM_BLE_TRACK_ADV_DATA *p_adv_data); - -typedef void (tBTA_BLE_ENERGY_INFO_CBACK)(tBTA_DM_BLE_TX_TIME_MS tx_time, - tBTA_DM_BLE_RX_TIME_MS rx_time, - tBTA_DM_BLE_IDLE_TIME_MS idle_time, - tBTA_DM_BLE_ENERGY_USED energy_used, - tBTA_DM_CONTRL_STATE ctrl_state, - tBTA_STATUS status); - -#else -typedef UINT8 tBTA_DM_BLE_SEC_ACT; -#endif - -/* Maximum service name length */ -#define BTA_SERVICE_NAME_LEN 35 -#define BTA_SERVICE_DESP_LEN BTA_SERVICE_NAME_LEN -#define BTA_PROVIDER_NAME_LEN BTA_SERVICE_NAME_LEN - - -/* link policy masks */ -#define BTA_DM_LP_SWITCH HCI_ENABLE_MASTER_SLAVE_SWITCH -#define BTA_DM_LP_HOLD HCI_ENABLE_HOLD_MODE -#define BTA_DM_LP_SNIFF HCI_ENABLE_SNIFF_MODE -#define BTA_DM_LP_PARK HCI_ENABLE_PARK_MODE -typedef UINT16 tBTA_DM_LP_MASK; - -/* power mode actions */ -#define BTA_DM_PM_NO_ACTION 0x00 /* no change to the current pm setting */ -#define BTA_DM_PM_PARK 0x10 /* prefers park mode */ -#define BTA_DM_PM_SNIFF 0x20 /* prefers sniff mode */ -#define BTA_DM_PM_SNIFF1 0x21 /* prefers sniff1 mode */ -#define BTA_DM_PM_SNIFF2 0x22 /* prefers sniff2 mode */ -#define BTA_DM_PM_SNIFF3 0x23 /* prefers sniff3 mode */ -#define BTA_DM_PM_SNIFF4 0x24 /* prefers sniff4 mode */ -#define BTA_DM_PM_SNIFF5 0x25 /* prefers sniff5 mode */ -#define BTA_DM_PM_SNIFF6 0x26 /* prefers sniff6 mode */ -#define BTA_DM_PM_SNIFF7 0x27 /* prefers sniff7 mode */ -#define BTA_DM_PM_SNIFF_USER0 0x28 /* prefers user-defined sniff0 mode (testtool only) */ -#define BTA_DM_PM_SNIFF_USER1 0x29 /* prefers user-defined sniff1 mode (testtool only) */ -#define BTA_DM_PM_ACTIVE 0x40 /* prefers active mode */ -#define BTA_DM_PM_RETRY 0x80 /* retry power mode based on current settings */ -#define BTA_DM_PM_SUSPEND 0x04 /* prefers suspend mode */ -#define BTA_DM_PM_NO_PREF 0x01 /* service has no prefernce on power mode setting. eg. connection to service got closed */ - -typedef UINT8 tBTA_DM_PM_ACTION; - -/* index to bta_dm_ssr_spec */ -#define BTA_DM_PM_SSR0 0 -#define BTA_DM_PM_SSR1 1 /* BTA_DM_PM_SSR1 will be dedicated for - HH SSR setting entry, no other profile can use it */ -#define BTA_DM_PM_SSR2 2 -#define BTA_DM_PM_SSR3 3 -#define BTA_DM_PM_SSR4 4 -#define BTA_DM_PM_SSR5 5 -#define BTA_DM_PM_SSR6 6 - -#define BTA_DM_PM_NUM_EVTS 9 - -#ifndef BTA_DM_PM_PARK_IDX -#define BTA_DM_PM_PARK_IDX 5 /* the actual index to bta_dm_pm_md[] for PARK mode */ -#endif - -#ifndef BTA_DM_PM_SNIFF_A2DP_IDX -#define BTA_DM_PM_SNIFF_A2DP_IDX BTA_DM_PM_SNIFF -#endif - -#ifndef BTA_DM_PM_SNIFF_HD_IDLE_IDX -#define BTA_DM_PM_SNIFF_HD_IDLE_IDX BTA_DM_PM_SNIFF2 -#endif - -#ifndef BTA_DM_PM_SNIFF_SCO_OPEN_IDX -#define BTA_DM_PM_SNIFF_SCO_OPEN_IDX BTA_DM_PM_SNIFF3 -#endif - -#ifndef BTA_DM_PM_SNIFF_HD_ACTIVE_IDX -#define BTA_DM_PM_SNIFF_HD_ACTIVE_IDX BTA_DM_PM_SNIFF4 -#endif - -#ifndef BTA_DM_PM_SNIFF_HH_OPEN_IDX -#define BTA_DM_PM_SNIFF_HH_OPEN_IDX BTA_DM_PM_SNIFF2 -#endif - -#ifndef BTA_DM_PM_SNIFF_HH_ACTIVE_IDX -#define BTA_DM_PM_SNIFF_HH_ACTIVE_IDX BTA_DM_PM_SNIFF2 -#endif - -#ifndef BTA_DM_PM_SNIFF_HH_IDLE_IDX -#define BTA_DM_PM_SNIFF_HH_IDLE_IDX BTA_DM_PM_SNIFF2 -#endif - - -#ifndef BTA_DM_PM_HH_OPEN_DELAY -#define BTA_DM_PM_HH_OPEN_DELAY 30000 -#endif - -#ifndef BTA_DM_PM_HH_ACTIVE_DELAY -#define BTA_DM_PM_HH_ACTIVE_DELAY 30000 -#endif - -#ifndef BTA_DM_PM_HH_IDLE_DELAY -#define BTA_DM_PM_HH_IDLE_DELAY 30000 -#endif - -/* The Sniff Parameters defined below must be ordered from highest - * latency (biggest interval) to lowest latency. If there is a conflict - * among the connected services the setting with the lowest latency will - * be selected. If a device should override a sniff parameter then it - * must insure that order is maintained. - */ -#ifndef BTA_DM_PM_SNIFF_MAX -#define BTA_DM_PM_SNIFF_MAX 800 -#define BTA_DM_PM_SNIFF_MIN 400 -#define BTA_DM_PM_SNIFF_ATTEMPT 4 -#define BTA_DM_PM_SNIFF_TIMEOUT 1 -#endif - -#ifndef BTA_DM_PM_SNIFF1_MAX -#define BTA_DM_PM_SNIFF1_MAX 400 -#define BTA_DM_PM_SNIFF1_MIN 200 -#define BTA_DM_PM_SNIFF1_ATTEMPT 4 -#define BTA_DM_PM_SNIFF1_TIMEOUT 1 -#endif - -#ifndef BTA_DM_PM_SNIFF2_MAX -#define BTA_DM_PM_SNIFF2_MAX 180 -#define BTA_DM_PM_SNIFF2_MIN 150 -#define BTA_DM_PM_SNIFF2_ATTEMPT 4 -#define BTA_DM_PM_SNIFF2_TIMEOUT 1 -#endif - -#ifndef BTA_DM_PM_SNIFF3_MAX -#define BTA_DM_PM_SNIFF3_MAX 150 -#define BTA_DM_PM_SNIFF3_MIN 50 -#define BTA_DM_PM_SNIFF3_ATTEMPT 4 -#define BTA_DM_PM_SNIFF3_TIMEOUT 1 -#endif - -#ifndef BTA_DM_PM_SNIFF4_MAX -#define BTA_DM_PM_SNIFF4_MAX 54 -#define BTA_DM_PM_SNIFF4_MIN 30 -#define BTA_DM_PM_SNIFF4_ATTEMPT 4 -#define BTA_DM_PM_SNIFF4_TIMEOUT 1 -#endif - -#ifndef BTA_DM_PM_SNIFF5_MAX -#define BTA_DM_PM_SNIFF5_MAX 36 -#define BTA_DM_PM_SNIFF5_MIN 30 -#define BTA_DM_PM_SNIFF5_ATTEMPT 2 -#define BTA_DM_PM_SNIFF5_TIMEOUT 0 -#endif - -#ifndef BTA_DM_PM_PARK_MAX -#define BTA_DM_PM_PARK_MAX 800 -#define BTA_DM_PM_PARK_MIN 400 -#define BTA_DM_PM_PARK_ATTEMPT 0 -#define BTA_DM_PM_PARK_TIMEOUT 0 -#endif - - -/* Switch callback events */ -#define BTA_DM_SWITCH_CMPL_EVT 0 /* Completion of the Switch API */ - -typedef UINT8 tBTA_DM_SWITCH_EVT; -typedef void (tBTA_DM_SWITCH_CBACK)(tBTA_DM_SWITCH_EVT event, tBTA_STATUS status); - -/* Audio routing out configuration */ -#define BTA_DM_ROUTE_NONE 0x00 /* No Audio output */ -#define BTA_DM_ROUTE_DAC 0x01 /* routing over analog output */ -#define BTA_DM_ROUTE_I2S 0x02 /* routing over digital (I2S) output */ -#define BTA_DM_ROUTE_BT_MONO 0x04 /* routing over SCO */ -#define BTA_DM_ROUTE_BT_STEREO 0x08 /* routing over BT Stereo */ -#define BTA_DM_ROUTE_HOST 0x10 /* routing over Host */ -#define BTA_DM_ROUTE_FMTX 0x20 /* routing over FMTX */ -#define BTA_DM_ROUTE_FMRX 0x40 /* routing over FMRX */ -#define BTA_DM_ROUTE_BTSNK 0x80 /* routing over BT SNK */ - -typedef UINT8 tBTA_DM_ROUTE_PATH; - -#if (SDP_INCLUDED == TRUE) -/* Device Identification (DI) data structure -*/ -/* Used to set the DI record */ -typedef tSDP_DI_RECORD tBTA_DI_RECORD; -/* Used to get the DI record */ -typedef tSDP_DI_GET_RECORD tBTA_DI_GET_RECORD; -/* SDP discovery database */ -typedef tSDP_DISCOVERY_DB tBTA_DISCOVERY_DB; -#endif ///SDP_INCLUDED == TRUE - -#ifndef BTA_DI_NUM_MAX -#define BTA_DI_NUM_MAX 3 -#endif - -/* Device features mask definitions */ -#define BTA_FEATURE_BYTES_PER_PAGE BTM_FEATURE_BYTES_PER_PAGE -#define BTA_EXT_FEATURES_PAGE_MAX BTM_EXT_FEATURES_PAGE_MAX -/* ACL type -*/ -#define BTA_DM_LINK_TYPE_BR_EDR 0x01 -#define BTA_DM_LINK_TYPE_LE 0x02 -#define BTA_DM_LINK_TYPE_ALL 0xFF -typedef UINT8 tBTA_DM_LINK_TYPE; - -#define IMMEDIATE_DELY_MODE 0x00 -#define ONFOUND_DELY_MODE 0x01 -#define BATCH_DELY_MODE 0x02 -#define ALLOW_ALL_FILTER 0x00 -#define LOWEST_RSSI_VALUE 129 - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function BTA_EnableBluetooth -** -** Description This function initializes BTA and prepares BTA and the -** Bluetooth protocol stack for use. This function is -** typically called at startup or when Bluetooth services -** are required by the phone. This function must be called -** before calling any other API function. -** -** -** Returns BTA_SUCCESS if successful. -** BTA_FAIL if internal failure. -** -*******************************************************************************/ -extern tBTA_STATUS BTA_EnableBluetooth(tBTA_DM_SEC_CBACK *p_cback); - -/******************************************************************************* -** -** Function BTA_DisableBluetooth -** -** Description This function disables BTA and the Bluetooth protocol -** stack. It is called when BTA is no longer being used -** by any application in the system. -** -** -** Returns void -** -*******************************************************************************/ -extern tBTA_STATUS BTA_DisableBluetooth(void); - -/******************************************************************************* -** -** Function BTA_EnableTestMode -** -** Description Enables bluetooth device under test mode -** -** -** Returns tBTA_STATUS -** -*******************************************************************************/ -extern tBTA_STATUS BTA_EnableTestMode(void); - -/******************************************************************************* -** -** Function BTA_DisableTestMode -** -** Description Disable bluetooth device under test mode -** -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DisableTestMode(void); - -/******************************************************************************* -** -** Function BTA_DmSetDeviceName -** -** Description This function sets the Bluetooth name of the local device. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSetDeviceName(char *p_name); - -extern void BTA_DmUpdateWhiteList(BOOLEAN add_remove, BD_ADDR remote_addr, tBTA_ADD_WHITELIST_CBACK *add_wl_cb); - -extern void BTA_DmBleReadAdvTxPower(tBTA_CMPL_CB *cmpl_cb); - -extern void BTA_DmBleReadRSSI(BD_ADDR remote_addr, tBTA_CMPL_CB *cmpl_cb); - -/******************************************************************************* -** -** Function BTA_DmSetVisibility -** -** Description This function sets the Bluetooth connectable,discoverable, -** pairable and conn paired only modesmodes of the local device. -** This controls whether other Bluetooth devices can find and connect to -** the local device. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSetVisibility(tBTA_DM_DISC disc_mode, tBTA_DM_CONN conn_mode, UINT8 pairable_mode, UINT8 conn_filter); - -/******************************************************************************* -** -** Function BTA_DmSearch -** -** Description This function searches for peer Bluetooth devices. It -** first performs an inquiry; for each device found from the -** inquiry it gets the remote name of the device. If -** parameter services is nonzero, service discovery will be -** performed on each device for the services specified. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSearch(tBTA_DM_INQ *p_dm_inq, tBTA_SERVICE_MASK services, - tBTA_DM_SEARCH_CBACK *p_cback); - -/******************************************************************************* -** -** Function BTA_DmSearchCancel -** -** Description This function cancels a search that has been initiated -** by calling BTA_DmSearch(). -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSearchCancel(void); - -/******************************************************************************* -** -** Function BTA_DmDiscover -** -** Description This function performs service discovery for the services -** of a particular peer device. -** -** -** Returns void -** -*******************************************************************************/ -#if (SDP_INCLUDED == TRUE) -extern void BTA_DmDiscover(BD_ADDR bd_addr, tBTA_SERVICE_MASK services, - tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search); -// btla-specific ++ -/******************************************************************************* -** -** Function BTA_DmDiscoverUUID -** -** Description This function performs service discovery for the services -** of a particular peer device. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmDiscoverUUID(BD_ADDR bd_addr, tSDP_UUID *uuid, - tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search); -#endif ///SDP_INCLUDED == TRUE -/******************************************************************************* -** -** Function BTA_DmGetCachedRemoteName -** -** Description Retieve cached remote name if available -** -** Returns BTA_SUCCESS if cached name was retrieved -** BTA_FAILURE if cached name is not available -** -*******************************************************************************/ -tBTA_STATUS BTA_DmGetCachedRemoteName(BD_ADDR remote_device, UINT8 **pp_cached_name); -// btla-specific -- - -/******************************************************************************* -** -** Function BTA_DmBond -** -** Description This function initiates a bonding procedure with a peer -** device. The bonding procedure enables authentication -** and optionally encryption on the Bluetooth link. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBond(BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTA_DmBondByTransport -** -** Description This function initiates a bonding procedure with a peer -** device by designated transport. The bonding procedure enables -** authentication and optionally encryption on the Bluetooth link. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBondByTransport(BD_ADDR bd_addr, tBTA_TRANSPORT transport); - - -/******************************************************************************* -** -** Function BTA_DmBondCancel -** -** Description This function cancels a bonding procedure with a peer -** device. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBondCancel(BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTA_DmPinReply -** -** Description This function provides a PIN when one is requested by DM -** during a bonding procedure. The application should call -** this function after the security callback is called with -** a BTA_DM_PIN_REQ_EVT. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmPinReply(BD_ADDR bd_addr, BOOLEAN accept, UINT8 pin_len, - UINT8 *p_pin); - -#if (BTM_OOB_INCLUDED == TRUE) -/******************************************************************************* -** -** Function BTA_DmLocalOob -** -** Description This function retrieves the OOB data from local controller. -** The result is reported by bta_dm_co_loc_oob(). -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmLocalOob(void); -#endif /* BTM_OOB_INCLUDED */ - -/******************************************************************************* -** -** Function BTA_DmConfirm -** -** Description This function accepts or rejects the numerical value of the -** Simple Pairing process on BTA_DM_SP_CFM_REQ_EVT -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmConfirm(BD_ADDR bd_addr, BOOLEAN accept); - -/******************************************************************************* -** -** Function BTA_DmAddDevice -** -** Description This function adds a device to the security database list -** of peer devices. This function would typically be called -** at system startup to initialize the security database with -** known peer devices. This is a direct execution function -** that may lock task scheduling on some platforms. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmAddDevice(BD_ADDR bd_addr, DEV_CLASS dev_class, - LINK_KEY link_key, tBTA_SERVICE_MASK trusted_mask, - BOOLEAN is_trusted, UINT8 key_type, - tBTA_IO_CAP io_cap, UINT8 pin_length); - -/******************************************************************************* -** -** Function BTA_DmRemoveDevice -** -** Description This function removes a device from the security database. -** This is a direct execution function that may lock task -** scheduling on some platforms. -** -** -** Returns BTA_SUCCESS if successful. -** BTA_FAIL if operation failed. -** -*******************************************************************************/ -extern tBTA_STATUS BTA_DmRemoveDevice(BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTA_GetEirService -** -** Description This function is called to get BTA service mask from EIR. -** -** Parameters p_eir - pointer of EIR significant part -** p_services - return the BTA service mask -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GetEirService( UINT8 *p_eir, tBTA_SERVICE_MASK *p_services ); - -/******************************************************************************* -** -** Function BTA_DmGetConnectionState -** -** Description Returns whether the remote device is currently connected. -** -** Returns 0 if the device is NOT connected. -** -*******************************************************************************/ -extern UINT16 BTA_DmGetConnectionState( BD_ADDR bd_addr ); - -#if (SDP_INCLUDED == TRUE) -/******************************************************************************* -** -** Function BTA_DmSetLocalDiRecord -** -** Description This function adds a DI record to the local SDP database. -** -** Returns BTA_SUCCESS if record set sucessfully, otherwise error code. -** -*******************************************************************************/ -extern tBTA_STATUS BTA_DmSetLocalDiRecord( tBTA_DI_RECORD *p_device_info, - UINT32 *p_handle ); -#endif ///SDP_INCLUDED == TRUE -/******************************************************************************* -** -** -** Function BTA_DmCloseACL -** -** Description This function force to close an ACL connection and remove the -** device from the security database list of known devices. -** -** Parameters: bd_addr - Address of the peer device -** remove_dev - remove device or not after link down -** transport - which transport to close - -** -** Returns void. -** -*******************************************************************************/ -extern void BTA_DmCloseACL(BD_ADDR bd_addr, BOOLEAN remove_dev, tBTA_TRANSPORT transport); - -/******************************************************************************* -** -** Function bta_dmexecutecallback -** -** Description This function will request BTA to execute a call back in the context of BTU task -** This API was named in lower case because it is only intended -** for the internal customers(like BTIF). -** -** Returns void -** -*******************************************************************************/ -extern void bta_dmexecutecallback (tBTA_DM_EXEC_CBACK *p_callback, void *p_param); - -#if (BTM_SCO_HCI_INCLUDED == TRUE) -/******************************************************************************* -** -** Function BTA_DmPcmInitSamples -** -** Description initialize the down sample converter. -** -** src_sps: original samples per second (source audio data) -** (ex. 44100, 48000) -** bits: number of bits per pcm sample (16) -** n_channels: number of channels (i.e. mono(1), stereo(2)...) -** -** Returns none -** -*******************************************************************************/ -extern void BTA_DmPcmInitSamples (UINT32 src_sps, UINT32 bits, UINT32 n_channels); - -/************************************************************************************** -** Function BTA_DmPcmResample -** -** Description Down sampling utility to convert higher sampling rate into 8K/16bits -** PCM samples. -** -** Parameters p_src: pointer to the buffer where the original sampling PCM -** are stored. -** in_bytes: Length of the input PCM sample buffer in byte. -** p_dst: pointer to the buffer which is to be used to store -** the converted PCM samples. -** -** -** Returns INT32: number of samples converted. -** -**************************************************************************************/ -extern INT32 BTA_DmPcmResample (void *p_src, UINT32 in_bytes, void *p_dst); -#endif - -#if ((defined BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) -/* BLE related API functions */ -/******************************************************************************* -** -** Function BTA_DmBleSecurityGrant -** -** Description Grant security request access. -** -** Parameters: bd_addr - BD address of the peer -** res - security grant status. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleSecurityGrant(BD_ADDR bd_addr, tBTA_DM_BLE_SEC_GRANT res); - - - -/******************************************************************************* -** -** Function BTA_DmBleSetBgConnType -** -** Description This function is called to set BLE connectable mode for a -** peripheral device. -** -** Parameters bg_conn_type: it can be auto connection, or selective connection. -** p_select_cback: callback function when selective connection procedure -** is being used. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleSetBgConnType(tBTA_DM_BLE_CONN_TYPE bg_conn_type, tBTA_DM_BLE_SEL_CBACK *p_select_cback); - -/******************************************************************************* -** -** Function BTA_DmBlePasskeyReply -** -** Description Send BLE SMP passkey reply. -** -** Parameters: bd_addr - BD address of the peer -** accept - passkey entry sucessful or declined. -** passkey - passkey value, must be a 6 digit number, -** can be lead by 0. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBlePasskeyReply(BD_ADDR bd_addr, BOOLEAN accept, UINT32 passkey); - -/******************************************************************************* -** -** Function BTA_DmBleConfirmReply -** -** Description Send BLE SMP SC user confirmation reply. -** -** Parameters: bd_addr - BD address of the peer -** accept - numbers to compare are the same or different. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleConfirmReply(BD_ADDR bd_addr, BOOLEAN accept); - -/******************************************************************************* -** -** Function BTA_DmAddBleDevice -** -** Description Add a BLE device. This function will be normally called -** during host startup to restore all required information -** for a LE device stored in the NVRAM. -** -** Parameters: bd_addr - BD address of the peer -** dev_type - Remote device's device type. -** addr_type - LE device address type. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmAddBleDevice(BD_ADDR bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_DEVICE_TYPE dev_type); - - -/******************************************************************************* -** -** Function BTA_DmAddBleKey -** -** Description Add/modify LE device information. This function will be -** normally called during host startup to restore all required -** information stored in the NVRAM. -** -** Parameters: bd_addr - BD address of the peer -** p_le_key - LE key values. -** key_type - LE SMP key type. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmAddBleKey (BD_ADDR bd_addr, - tBTA_LE_KEY_VALUE *p_le_key, - tBTA_LE_KEY_TYPE key_type); - -/******************************************************************************* -** -** Function BTA_DmSetBlePrefConnParams -** -** Description This function is called to set the preferred connection -** parameters when default connection parameter is not desired. -** -** Parameters: bd_addr - BD address of the peripheral -** min_conn_int - minimum preferred connection interval -** max_conn_int - maximum preferred connection interval -** slave_latency - preferred slave latency -** supervision_tout - preferred supervision timeout -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSetBlePrefConnParams(BD_ADDR bd_addr, - UINT16 min_conn_int, UINT16 max_conn_int, - UINT16 slave_latency, UINT16 supervision_tout ); - -/******************************************************************************* -** -** Function BTA_DmSetBleConnScanParams -** -** Description This function is called to set scan parameters used in -** BLE connection request -** -** Parameters: scan_interval - scan interval -** scan_window - scan window -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSetBleConnScanParams(UINT32 scan_interval, - UINT32 scan_window); - -/******************************************************************************* -** -** Function BTA_DmSetBleScanParams -** -** Description This function is called to set scan parameters -** -** Parameters: client_if - Client IF -** scan_interval - scan interval -** scan_window - scan window -** scan_mode - scan mode -** scan_param_setup_status_cback - Set scan param status callback -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSetBleScanParams(tGATT_IF client_if, UINT32 scan_interval, - UINT32 scan_window, tBLE_SCAN_MODE scan_mode, - tBLE_SCAN_PARAM_SETUP_CBACK scan_param_setup_status_cback); - - -/******************************************************************************* -** -** Function BTA_DmSetBleScanFilterParams -** -** Description This function is called to set scan parameters -** -** Parameters: client_if - Client IF -** scan_interval - scan interval -** scan_window - scan window -** scan_mode - scan mode -** scan_param_setup_status_cback - Set scan param status callback -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSetBleScanFilterParams(tGATT_IF client_if, UINT32 scan_interval, - UINT32 scan_window, tBLE_SCAN_MODE scan_mode, UINT8 scan_fil_poilcy, - UINT8 addr_type_own, tBLE_SCAN_PARAM_SETUP_CBACK scan_param_setup_cback); - - -/******************************************************************************* -** -** Function BTA_DmSetBleAdvParams -** -** Description This function sets the advertising parameters BLE functionality. -** It is to be called when device act in peripheral or broadcaster -** role. -** -** Parameters: adv_int_min - adv interval minimum -** adv_int_max - adv interval max -** p_dir_bda - directed adv initator address -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSetBleAdvParams (UINT16 adv_int_min, UINT16 adv_int_max, - tBLE_BD_ADDR *p_dir_bda); - -extern void BTA_DmSetBleAdvParamsAll (UINT16 adv_int_min, UINT16 adv_int_max, - UINT8 adv_type, tBLE_ADDR_TYPE addr_type_own, - tBTM_BLE_ADV_CHNL_MAP chnl_map, tBTM_BLE_AFP adv_fil_pol, - tBLE_BD_ADDR *p_dir_bda, tBTA_START_ADV_CMPL_CBACK p_start_adv_cb); - - -/******************************************************************************* -** -** Function BTA_DmSearchExt -** -** Description This function searches for peer Bluetooth devices. It performs -** an inquiry and gets the remote name for devices. Service -** discovery is done if services is non zero -** -** Parameters p_dm_inq: inquiry conditions -** services: if service is not empty, service discovery will be done. -** for all GATT based service condition, put num_uuid, and -** p_uuid is the pointer to the list of UUID values. -** p_cback: callback functino when search is completed. -** -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmSearchExt(tBTA_DM_INQ *p_dm_inq, tBTA_SERVICE_MASK_EXT *p_services, - tBTA_DM_SEARCH_CBACK *p_cback); - -/******************************************************************************* -** -** Function BTA_DmDiscoverExt -** -** Description This function does service discovery for services of a -** peer device. When services.num_uuid is 0, it indicates all -** GATT based services are to be searched; other wise a list of -** UUID of interested services should be provided through -** services.p_uuid. -** -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmDiscoverExt(BD_ADDR bd_addr, tBTA_SERVICE_MASK_EXT *p_services, - tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search); - -/******************************************************************************* -** -** Function BTA_DmDiscoverByTransport -** -** Description This function does service discovery on particular transport -** for services of a -** peer device. When services.num_uuid is 0, it indicates all -** GATT based services are to be searched; other wise a list of -** UUID of interested services should be provided through -** p_services->p_uuid. -** -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmDiscoverByTransport(BD_ADDR bd_addr, tBTA_SERVICE_MASK_EXT *p_services, - tBTA_DM_SEARCH_CBACK *p_cback, BOOLEAN sdp_search, - tBTA_TRANSPORT transport); - -/******************************************************************************* -** -** Function BTA_DmSetEncryption -** -** Description This function is called to ensure that connection is -** encrypted. Should be called only on an open connection. -** Typically only needed for connections that first want to -** bring up unencrypted links, then later encrypt them. -** -** Parameters: bd_addr - Address of the peer device -** transport - transport of the link to be encruypted -** p_callback - Pointer to callback function to indicat the -** link encryption status -** sec_act - This is the security action to indicate -** what knid of BLE security level is required for -** the BLE link if the BLE is supported -** Note: This parameter is ignored for the BR/EDR link -** or the BLE is not supported -** -** Returns void -** -** -*******************************************************************************/ -extern void BTA_DmSetEncryption(BD_ADDR bd_addr, tBTA_TRANSPORT transport, - tBTA_DM_ENCRYPT_CBACK *p_callback, - tBTA_DM_BLE_SEC_ACT sec_act); - - -/******************************************************************************* -** -** Function BTA_DmBleObserve -** -** Description This procedure keep the device listening for advertising -** events from a broadcast device. -** -** Parameters start: start or stop observe. -** duration : Duration of the scan. Continuous scan if 0 is passed -** p_results_cb: Callback to be called with scan results -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleObserve(BOOLEAN start, UINT32 duration, - tBTA_DM_SEARCH_CBACK *p_results_cb, - tBTA_START_STOP_SCAN_CMPL_CBACK *p_start_stop_scan_cb); - -/******************************************************************************* -** -** Function BTA_DmBleScan -** -** Description This procedure keep the device listening for advertising -** events from a broadcast device. -** -** Parameters start: start or stop observe. -** duration : Duration of the scan. Continuous scan if 0 is passed -** p_results_cb: Callback to be called with scan results -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleScan(BOOLEAN start, UINT32 duration, - tBTA_DM_SEARCH_CBACK *p_results_cb, - tBTA_START_STOP_SCAN_CMPL_CBACK *p_start_stop_scan_cb); - -extern void BTA_DmBleStopAdvertising(void); - -extern void BTA_DmSetRandAddress(BD_ADDR rand_addr, tBTA_SET_RAND_ADDR_CBACK *p_set_rand_addr_cback); - -#endif - -#if BLE_INCLUDED == TRUE -// btla-specific -- -/******************************************************************************* -** -** Function BTA_DmBleConfigLocalPrivacy -** -** Description Enable/disable privacy on the local device -** -** Parameters: privacy_enable - enable/disabe privacy on remote device. -** set_local_privacy_cback -callback to be called with result -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleConfigLocalPrivacy(BOOLEAN privacy_enable, tBTA_SET_LOCAL_PRIVACY_CBACK *set_local_privacy_cback); - -/******************************************************************************* -** -** Function BTA_DmBleEnableRemotePrivacy -** -** Description Enable/disable privacy on a remote device -** -** Parameters: bd_addr - BD address of the peer -** privacy_enable - enable/disabe privacy on remote device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleEnableRemotePrivacy(BD_ADDR bd_addr, BOOLEAN privacy_enable); - - -/******************************************************************************* -** -** Function BTA_DmBleSetAdvConfig -** -** Description This function is called to override the BTA default ADV parameters. -** -** Parameters Pointer to User defined ADV data structure -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleSetAdvConfig (tBTA_BLE_AD_MASK data_mask, - tBTA_BLE_ADV_DATA *p_adv_cfg, - tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback); - -/******************************************************************************* -** -** Function BTA_DmBleSetAdvConfigRaw -** -** Description This function is called to set raw Advertising data -** -** Parameters p_raw_adv : raw advertising data. -** raw_adv_len : raw advertising data length. -** p_adv_data_cback : set adv data complete callback. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleSetAdvConfigRaw (UINT8 *p_raw_adv, UINT32 raw_adv_len, - tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback); - -/******************************************************************************* -** -** Function BTA_DmBleSetScanRsp -** -** Description This function is called to override the BTA scan response. -** -** Parameters Pointer to User defined ADV data structure -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleSetScanRsp (tBTA_BLE_AD_MASK data_mask, - tBTA_BLE_ADV_DATA *p_adv_cfg, - tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback); - -/******************************************************************************* -** -** Function BTA_DmBleSetScanRspRaw -** -** Description This function is called to set raw scan response data -** -** Parameters p_raw_scan_rsp : raw scan_rspertising data. -** raw_scan_rsp_len : raw scan_rspertising data length. -** p_scan_rsp_data_cback : set scan_rsp data complete callback. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleSetScanRspRaw (UINT8 *p_raw_scan_rsp, UINT32 raw_scan_rsp_len, - tBTA_SET_ADV_DATA_CMPL_CBACK *p_scan_rsp_data_cback); - -/******************************************************************************* -** -** Function BTA_DmBleBroadcast -** -** Description This function starts or stops LE broadcasting. -** -** Parameters start: start or stop broadcast. -** p_start_stop_adv_cb: stop broadcast completed event -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleBroadcast (BOOLEAN start, tBTA_START_STOP_ADV_CMPL_CBACK *p_start_stop_adv_cb); - - -/******************************************************************************* -** -** Function BTA_BleEnableAdvInstance -** -** Description This function enables the Multi ADV instance feature -** -** Parameters p_params Pointer to ADV param user defined structure -** p_cback Pointer to Multi ADV callback structure -** p_ref - Reference pointer -** -** Returns None -** -*******************************************************************************/ -extern void BTA_BleEnableAdvInstance (tBTA_BLE_ADV_PARAMS *p_params, - tBTA_BLE_MULTI_ADV_CBACK *p_cback, void *p_ref); - -/******************************************************************************* -** -** Function BTA_BleUpdateAdvInstParam -** -** Description This function updates the Multi ADV instance params -** -** Parameters inst_id Instance ID -** p_params Pointer to ADV param user defined structure -** -** Returns None -** -*******************************************************************************/ -extern void BTA_BleUpdateAdvInstParam (UINT8 inst_id, - tBTA_BLE_ADV_PARAMS *p_params); - -/******************************************************************************* -** -** Function BTA_BleCfgAdvInstData -** -** Description This function is called to configure the ADV instance data -** -** Parameters inst_id - Instance ID -** is_scan_rsp - Boolean value Scan response -** Pointer to User defined ADV data structure -** Returns None -** -*******************************************************************************/ -extern void BTA_BleCfgAdvInstData (UINT8 inst_id, BOOLEAN is_scan_rsp, - tBTA_BLE_AD_MASK data_mask, tBTA_BLE_ADV_DATA *p_data); - -/******************************************************************************* -** -** Function BTA_BleDisableAdvInstance -** -** Description This function is called to disable the ADV instance -** -** Parameters inst_id - Instance ID to be disabled -** -** Returns None -** -*******************************************************************************/ -extern void BTA_BleDisableAdvInstance(UINT8 inst_id); - -/******************************************************************************* -** -** Function BTA_DmBleUpdateConnectionParams -** -** Description Update connection parameters, can only be used when connection is up. -** -** Parameters: bd_addr - BD address of the peer -** min_int - minimum connection interval, [0x0004~ 0x4000] -** max_int - maximum connection interval, [0x0004~ 0x4000] -** latency - slave latency [0 ~ 500] -** timeout - supervision timeout [0x000a ~ 0xc80] -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleUpdateConnectionParams(BD_ADDR bd_addr, UINT16 min_int, - UINT16 max_int, UINT16 latency, UINT16 timeout); - -/******************************************************************************* -** -** Function BTA_DmBleDisconnect -** -** Description This function is to disconnect the ble connection -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleDisconnect(BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTA_DmBleSetDataLength -** -** Description This function is to set maximum LE data packet size -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleSetDataLength(BD_ADDR remote_device, UINT16 tx_data_length, tBTA_SET_PKT_DATA_LENGTH_CBACK *p_set_pkt_data_cback); - -/******************************************************************************* -** -** Function BTA_DmBleSetStorageParams -** -** Description This function is called to set the storage parameters -** -** Parameters batch_scan_full_max -Max storage space (in %) allocated to full scanning -** batch_scan_trunc_max -Max storage space (in %) allocated to truncated scanning -** batch_scan_notify_threshold - Setup notification level based on total space -** consumed by both pools. Setting it to 0 will disable threshold notification -** p_setup_cback - Setup callback -** p_thres_cback - Threshold callback -** p_rep_cback - Reports callback -** ref_value - Reference value -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleSetStorageParams(UINT8 batch_scan_full_max, - UINT8 batch_scan_trunc_max, - UINT8 batch_scan_notify_threshold, - tBTA_BLE_SCAN_SETUP_CBACK *p_setup_cback, - tBTA_BLE_SCAN_THRESHOLD_CBACK *p_thres_cback, - tBTA_BLE_SCAN_REP_CBACK *p_rep_cback, - tBTA_DM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTA_DmBleEnableBatchScan -** -** Description This function is called to enable the batch scan -** -** Parameters scan_mode -Batch scan mode -** scan_interval - Scan interval -** scan_window - Scan window -** discard_rule -Discard rules -** addr_type - Address type -** ref_value - Reference value -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleEnableBatchScan(tBTA_BLE_BATCH_SCAN_MODE scan_mode, - UINT32 scan_interval, UINT32 scan_window, - tBTA_BLE_DISCARD_RULE discard_rule, - tBLE_ADDR_TYPE addr_type, - tBTA_DM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTA_DmBleReadScanReports -** -** Description This function is called to read the batch scan reports -** -** Parameters scan_mode -Batch scan mode -** ref_value - Reference value -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleReadScanReports(tBTA_BLE_BATCH_SCAN_MODE scan_type, - tBTA_DM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTA_DmBleDisableBatchScan -** -** Description This function is called to disable the batch scanning -** -** Parameters ref_value - Reference value -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleDisableBatchScan(tBTA_DM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTA_DmEnableScanFilter -** -** Description This function is called to enable the adv data payload filter -** -** Parameters action - enable or disable the APCF feature -** p_cmpl_cback - Command completed callback -** ref_value - Reference value -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmEnableScanFilter(UINT8 action, - tBTA_DM_BLE_PF_STATUS_CBACK *p_cmpl_cback, - tBTA_DM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTA_DmBleScanFilterSetup -** -** Description This function is called to setup the filter params -** -** Parameters p_target: enable the filter condition on a target device; if NULL -** filt_index - Filter index -** p_filt_params -Filter parameters -** ref_value - Reference value -** action - Add, delete or clear -** p_cmpl_back - Command completed callback -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleScanFilterSetup(UINT8 action, - tBTA_DM_BLE_PF_FILT_INDEX filt_index, - tBTA_DM_BLE_PF_FILT_PARAMS *p_filt_params, - tBLE_BD_ADDR *p_target, - tBTA_DM_BLE_PF_PARAM_CBACK *p_cmpl_cback, - tBTA_DM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTA_DmBleCfgFilterCondition -** -** Description This function is called to configure the adv data payload filter -** condition. -** -** Parameters action: to read/write/clear -** cond_type: filter condition type -** filt_index - Filter index -** p_cond: filter condition parameter -** p_cmpl_back - Command completed callback -** ref_value - Reference value -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleCfgFilterCondition(tBTA_DM_BLE_SCAN_COND_OP action, - tBTA_DM_BLE_PF_COND_TYPE cond_type, - tBTA_DM_BLE_PF_FILT_INDEX filt_index, - tBTA_DM_BLE_PF_COND_PARAM *p_cond, - tBTA_DM_BLE_PF_CFG_CBACK *p_cmpl_cback, - tBTA_DM_BLE_REF_VALUE ref_value); - - -/******************************************************************************* -** -** Function BTA_DmBleTrackAdvertiser -** -** Description This function is called to track the advertiser -** -** Parameters ref_value - Reference value -** p_track_adv_cback - ADV callback -** -** Returns None -** -*******************************************************************************/ -extern void BTA_DmBleTrackAdvertiser(tBTA_DM_BLE_REF_VALUE ref_value, - tBTA_BLE_TRACK_ADV_CBACK *p_track_adv_cback); - -/******************************************************************************* -** -** Function BTA_DmBleGetEnergyInfo -** -** Description This function is called to obtain the energy info -** -** Parameters p_cmpl_cback - Command complete callback -** -** Returns void -** -*******************************************************************************/ -extern void BTA_DmBleGetEnergyInfo(tBTA_BLE_ENERGY_INFO_CBACK *p_cmpl_cback); - -/******************************************************************************* -** -** Function BTA_BrcmInit -** -** Description This function initializes Broadcom specific VS handler in BTA -** -** Returns void -** -*******************************************************************************/ -extern void BTA_VendorInit (void); - -/******************************************************************************* -** -** Function BTA_BrcmCleanup -** -** Description This function frees up Broadcom specific VS specific dynamic memory -** -** Returns void -** -*******************************************************************************/ -extern void BTA_VendorCleanup (void); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* BTA_API_H */ diff --git a/tools/sdk/include/bluedroid/bta_ar_api.h b/tools/sdk/include/bluedroid/bta_ar_api.h deleted file mode 100644 index acfac9df44b..00000000000 --- a/tools/sdk/include/bluedroid/bta_ar_api.h +++ /dev/null @@ -1,144 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2004-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the public interface file for the simulatenous advanced - * audio/video streaming (AV) source and sink of BTA, Broadcom's Bluetooth - * application layer for mobile phones. - * - ******************************************************************************/ -#ifndef BTA_AR_API_H -#define BTA_AR_API_H - -#include "avdt_api.h" -#include "avct_api.h" -#include "avrc_api.h" -#include "sdp_api.h" -#include "bta_av_api.h" -#include "bta_sys.h" - -#if (BTA_AR_INCLUDED == TRUE) - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ -/* This event signal to AR user that other profile is connected */ -#define BTA_AR_AVDT_CONN_EVT (AVDT_MAX_EVT + 1) - -/******************************************************************************* -** -** Function bta_ar_init -** -** Description This function is called from bta_sys_init(). -** to initialize the control block -** -** Returns void -** -*******************************************************************************/ -extern void bta_ar_init(void); - -/******************************************************************************* -** -** Function bta_ar_reg_avdt -** -** Description This function is called to register to AVDTP. -** -** Returns void -** -*******************************************************************************/ -extern void bta_ar_reg_avdt(tAVDT_REG *p_reg, tAVDT_CTRL_CBACK *p_cback, tBTA_SYS_ID sys_id); - -/******************************************************************************* -** -** Function bta_ar_dereg_avdt -** -** Description This function is called to de-register from AVDTP. -** -** Returns void -** -*******************************************************************************/ -extern void bta_ar_dereg_avdt(tBTA_SYS_ID sys_id); - -/******************************************************************************* -** -** Function bta_ar_avdt_conn -** -** Description This function is called to let ar know that some AVDTP profile -** is connected for this sys_id. -** If the other sys modules started a timer for PENDING_EVT, -** the timer can be stopped now. -** -** Returns void -** -*******************************************************************************/ -extern void bta_ar_avdt_conn(tBTA_SYS_ID sys_id, BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function bta_ar_reg_avct -** -** Description This function is called to register to AVCTP. -** -** Returns void -** -*******************************************************************************/ -extern void bta_ar_reg_avct(UINT16 mtu, UINT16 mtu_br, UINT8 sec_mask, tBTA_SYS_ID sys_id); - -/******************************************************************************* -** -** Function bta_ar_dereg_avct -** -** Description This function is called to deregister from AVCTP. -** -** Returns void -** -*******************************************************************************/ -extern void bta_ar_dereg_avct(tBTA_SYS_ID sys_id); - -/****************************************************************************** -** -** Function bta_ar_reg_avrc -** -** Description This function is called to register an SDP record for AVRCP. -** -** Returns void -** -******************************************************************************/ -extern void bta_ar_reg_avrc(UINT16 service_uuid, char *p_service_name, - char *p_provider_name, UINT16 categories, tBTA_SYS_ID sys_id); - -/****************************************************************************** -** -** Function bta_ar_dereg_avrc -** -** Description This function is called to de-register/delete an SDP record for AVRCP. -** -** Returns void -** -******************************************************************************/ -extern void bta_ar_dereg_avrc(UINT16 service_uuid, tBTA_SYS_ID sys_id); - - -#ifdef __cplusplus -} -#endif - -#endif ///BTA_AR_INCLUDED == TRUE - -#endif /* BTA_AR_API_H */ diff --git a/tools/sdk/include/bluedroid/bta_ar_int.h b/tools/sdk/include/bluedroid/bta_ar_int.h deleted file mode 100644 index e9997ec7880..00000000000 --- a/tools/sdk/include/bluedroid/bta_ar_int.h +++ /dev/null @@ -1,66 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2008-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the private interface file for the BTA audio/video registration - * module. - * - ******************************************************************************/ -#ifndef BTA_AR_INT_H -#define BTA_AR_INT_H - -#include "bta_av_api.h" - -#if (BTA_AR_INCLUDED == TRUE) - -#ifndef BTA_AR_DEBUG -#define BTA_AR_DEBUG FALSE -#endif - -#define BTA_AR_AV_MASK 0x01 -#define BTA_AR_AVK_MASK 0x02 - -/* data associated with BTA_AR */ -typedef struct { - tAVDT_CTRL_CBACK *p_av_conn_cback; /* av connection callback function */ - tAVDT_CTRL_CBACK *p_avk_conn_cback; /* avk connection callback function */ - UINT8 avdt_registered; - UINT8 avct_registered; - UINT32 sdp_tg_handle; - UINT32 sdp_ct_handle; - UINT16 ct_categories[2]; - UINT8 tg_registered; - tBTA_AV_HNDL hndl; /* Handle associated with the stream that rejected the connection. */ -} tBTA_AR_CB; - -/***************************************************************************** -** Global data -*****************************************************************************/ - -/* control block declaration */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_AR_CB bta_ar_cb; -#else -extern tBTA_AR_CB *bta_ar_cb_ptr; -#define bta_ar_cb (*bta_ar_cb_ptr) -#endif - -#endif ///BTA_AR_INCLUDED == TRUE - -#endif /* BTA_AR_INT_H */ diff --git a/tools/sdk/include/bluedroid/bta_av_api.h b/tools/sdk/include/bluedroid/bta_av_api.h deleted file mode 100644 index a7560c9ebc4..00000000000 --- a/tools/sdk/include/bluedroid/bta_av_api.h +++ /dev/null @@ -1,813 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2004-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the public interface file for the advanced audio/video streaming - * (AV) subsystem of BTA, Broadcom's Bluetooth application layer for mobile - * phones. - * - ******************************************************************************/ -#ifndef BTA_AV_API_H -#define BTA_AV_API_H - -#include "avrc_api.h" -#include "avdt_api.h" -#include "a2d_api.h" -#include "bta_api.h" - -#if (BTA_AV_INCLUDED == TRUE) - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ -/* Set to TRUE if seperate authorization prompt desired for AVCTP besides A2DP authorization */ -/* Typically FALSE when AVRCP is used in conjunction with A2DP */ -#ifndef BTA_AV_WITH_AVCTP_AUTHORIZATION -#define BTA_AV_WITH_AVCTP_AUTHORIZATION FALSE -#endif - -/* AV status values */ -#define BTA_AV_SUCCESS 0 /* successful operation */ -#define BTA_AV_FAIL 1 /* generic failure */ -#define BTA_AV_FAIL_SDP 2 /* service not found */ -#define BTA_AV_FAIL_STREAM 3 /* stream connection failed */ -#define BTA_AV_FAIL_RESOURCES 4 /* no resources */ -#define BTA_AV_FAIL_ROLE 5 /* failed due to role management related issues */ -#define BTA_AV_FAIL_GET_CAP 6 /* get capability failed due to no SEP availale on the peer */ - -typedef UINT8 tBTA_AV_STATUS; - -/* AV features masks */ -#define BTA_AV_FEAT_RCTG 0x0001 /* remote control target */ -#define BTA_AV_FEAT_RCCT 0x0002 /* remote control controller */ -#define BTA_AV_FEAT_PROTECT 0x0004 /* streaming media contect protection */ -#define BTA_AV_FEAT_VENDOR 0x0008 /* remote control vendor dependent commands */ -#define BTA_AV_FEAT_REPORT 0x0020 /* use reporting service for VDP */ -#define BTA_AV_FEAT_METADATA 0x0040 /* remote control Metadata Transfer command/response */ -#define BTA_AV_FEAT_MULTI_AV 0x0080 /* use multi-av, if controller supports it */ -#define BTA_AV_FEAT_BROWSE 0x0010 /* use browsing channel */ -#define BTA_AV_FEAT_MASTER 0x0100 /* stream only as master role */ -#define BTA_AV_FEAT_ADV_CTRL 0x0200 /* remote control Advanced Control command/response */ -#define BTA_AV_FEAT_DELAY_RPT 0x0400 /* allow delay reporting */ -#define BTA_AV_FEAT_ACP_START 0x0800 /* start stream when 2nd SNK was accepted */ - -/* Internal features */ -#define BTA_AV_FEAT_NO_SCO_SSPD 0x8000 /* Do not suspend av streaming as to AG events(SCO or Call) */ - -typedef UINT16 tBTA_AV_FEAT; - -/* AV channel values */ -#define BTA_AV_CHNL_MSK 0xC0 -#define BTA_AV_CHNL_AUDIO 0x40 /* audio channel */ -#define BTA_AV_CHNL_VIDEO 0x80 /* video channel */ -typedef UINT8 tBTA_AV_CHNL; - - -#define BTA_AV_HNDL_MSK 0x3F -typedef UINT8 tBTA_AV_HNDL; -/* handle index to mask */ -#define BTA_AV_HNDL_TO_MSK(h) ((UINT8)(1 << (h))) - -/* tBTA_AV_HNDL to mask */ -#define BTA_AV_HNDL_TYPE_TO_MSK(h) ((UINT8)(1 << (h&BTA_AV_HNDL_MSK))) - -/* offset of codec type in codec info byte array */ -#define BTA_AV_CODEC_TYPE_IDX AVDT_CODEC_TYPE_INDEX /* 2 */ - - - -/* maximum number of streams created: 1 for audio, 1 for video */ -#ifndef BTA_AV_NUM_STRS -#define BTA_AV_NUM_STRS 2 -#endif - -#ifndef BTA_AV_MAX_SEPS -#define BTA_AV_MAX_SEPS 2 -#endif - -#ifndef BTA_AV_MAX_A2DP_MTU -/*#define BTA_AV_MAX_A2DP_MTU 668 //224 (DM5) * 3 - 4(L2CAP header) */ -#define BTA_AV_MAX_A2DP_MTU 1008 -#endif - -#ifndef BTA_AV_MAX_VDP_MTU -#define BTA_AV_MAX_VDP_MTU 1008 -#endif - - -/* codec type */ -#define BTA_AV_CODEC_SBC A2D_MEDIA_CT_SBC /* SBC media codec type */ -#define BTA_AV_CODEC_M12 A2D_MEDIA_CT_M12 /* MPEG-1, 2 Audio media codec type */ -#define BTA_AV_CODEC_M24 A2D_MEDIA_CT_M24 /* MPEG-2, 4 AAC media codec type */ -#define BTA_AV_CODEC_ATRAC A2D_MEDIA_CT_ATRAC /* ATRAC family media codec type */ -#define BTA_AV_CODEC_H263_P0 VDP_MEDIA_CT_H263_P0 /* H.263 baseline (profile 0) */ -#define BTA_AV_CODEC_MPEG4 VDP_MEDIA_CT_MPEG4 /* MPEG-4 Visual Simple Profile */ -#define BTA_AV_CODEC_H263_P3 VDP_MEDIA_CT_H263_P3 /* H.263 profile 3 */ -#define BTA_AV_CODEC_H263_P8 VDP_MEDIA_CT_H263_P8 /* H.263 profile 8 */ -#define BTA_AV_CODEC_VEND VDP_MEDIA_CT_VEND /* Non-VDP */ - -typedef UINT8 tBTA_AV_CODEC; - -/* Company ID in BT assigned numbers */ -#define BTA_AV_BT_VENDOR_ID VDP_BT_VENDOR_ID /* Broadcom Corporation */ - -/* vendor specific codec ID */ -#define BTA_AV_CODEC_ID_H264 VDP_CODEC_ID_H264 /* Non-VDP codec ID - H.264 */ -#define BTA_AV_CODEC_ID_IMG VDP_CODEC_ID_IMG /* Non-VDP codec ID - images/slideshow */ - -/* operation id list for BTA_AvRemoteCmd */ -#define BTA_AV_RC_SELECT AVRC_ID_SELECT /* select */ -#define BTA_AV_RC_UP AVRC_ID_UP /* up */ -#define BTA_AV_RC_DOWN AVRC_ID_DOWN /* down */ -#define BTA_AV_RC_LEFT AVRC_ID_LEFT /* left */ -#define BTA_AV_RC_RIGHT AVRC_ID_RIGHT /* right */ -#define BTA_AV_RC_RIGHT_UP AVRC_ID_RIGHT_UP /* right-up */ -#define BTA_AV_RC_RIGHT_DOWN AVRC_ID_RIGHT_DOWN /* right-down */ -#define BTA_AV_RC_LEFT_UP AVRC_ID_LEFT_UP /* left-up */ -#define BTA_AV_RC_LEFT_DOWN AVRC_ID_LEFT_DOWN /* left-down */ -#define BTA_AV_RC_ROOT_MENU AVRC_ID_ROOT_MENU /* root menu */ -#define BTA_AV_RC_SETUP_MENU AVRC_ID_SETUP_MENU /* setup menu */ -#define BTA_AV_RC_CONT_MENU AVRC_ID_CONT_MENU /* contents menu */ -#define BTA_AV_RC_FAV_MENU AVRC_ID_FAV_MENU /* favorite menu */ -#define BTA_AV_RC_EXIT AVRC_ID_EXIT /* exit */ -#define BTA_AV_RC_0 AVRC_ID_0 /* 0 */ -#define BTA_AV_RC_1 AVRC_ID_1 /* 1 */ -#define BTA_AV_RC_2 AVRC_ID_2 /* 2 */ -#define BTA_AV_RC_3 AVRC_ID_3 /* 3 */ -#define BTA_AV_RC_4 AVRC_ID_4 /* 4 */ -#define BTA_AV_RC_5 AVRC_ID_5 /* 5 */ -#define BTA_AV_RC_6 AVRC_ID_6 /* 6 */ -#define BTA_AV_RC_7 AVRC_ID_7 /* 7 */ -#define BTA_AV_RC_8 AVRC_ID_8 /* 8 */ -#define BTA_AV_RC_9 AVRC_ID_9 /* 9 */ -#define BTA_AV_RC_DOT AVRC_ID_DOT /* dot */ -#define BTA_AV_RC_ENTER AVRC_ID_ENTER /* enter */ -#define BTA_AV_RC_CLEAR AVRC_ID_CLEAR /* clear */ -#define BTA_AV_RC_CHAN_UP AVRC_ID_CHAN_UP /* channel up */ -#define BTA_AV_RC_CHAN_DOWN AVRC_ID_CHAN_DOWN /* channel down */ -#define BTA_AV_RC_PREV_CHAN AVRC_ID_PREV_CHAN /* previous channel */ -#define BTA_AV_RC_SOUND_SEL AVRC_ID_SOUND_SEL /* sound select */ -#define BTA_AV_RC_INPUT_SEL AVRC_ID_INPUT_SEL /* input select */ -#define BTA_AV_RC_DISP_INFO AVRC_ID_DISP_INFO /* display information */ -#define BTA_AV_RC_HELP AVRC_ID_HELP /* help */ -#define BTA_AV_RC_PAGE_UP AVRC_ID_PAGE_UP /* page up */ -#define BTA_AV_RC_PAGE_DOWN AVRC_ID_PAGE_DOWN /* page down */ -#define BTA_AV_RC_POWER AVRC_ID_POWER /* power */ -#define BTA_AV_RC_VOL_UP AVRC_ID_VOL_UP /* volume up */ -#define BTA_AV_RC_VOL_DOWN AVRC_ID_VOL_DOWN /* volume down */ -#define BTA_AV_RC_MUTE AVRC_ID_MUTE /* mute */ -#define BTA_AV_RC_PLAY AVRC_ID_PLAY /* play */ -#define BTA_AV_RC_STOP AVRC_ID_STOP /* stop */ -#define BTA_AV_RC_PAUSE AVRC_ID_PAUSE /* pause */ -#define BTA_AV_RC_RECORD AVRC_ID_RECORD /* record */ -#define BTA_AV_RC_REWIND AVRC_ID_REWIND /* rewind */ -#define BTA_AV_RC_FAST_FOR AVRC_ID_FAST_FOR /* fast forward */ -#define BTA_AV_RC_EJECT AVRC_ID_EJECT /* eject */ -#define BTA_AV_RC_FORWARD AVRC_ID_FORWARD /* forward */ -#define BTA_AV_RC_BACKWARD AVRC_ID_BACKWARD /* backward */ -#define BTA_AV_RC_ANGLE AVRC_ID_ANGLE /* angle */ -#define BTA_AV_RC_SUBPICT AVRC_ID_SUBPICT /* subpicture */ -#define BTA_AV_RC_F1 AVRC_ID_F1 /* F1 */ -#define BTA_AV_RC_F2 AVRC_ID_F2 /* F2 */ -#define BTA_AV_RC_F3 AVRC_ID_F3 /* F3 */ -#define BTA_AV_RC_F4 AVRC_ID_F4 /* F4 */ -#define BTA_AV_RC_F5 AVRC_ID_F5 /* F5 */ -#define BTA_AV_VENDOR AVRC_ID_VENDOR /* vendor unique */ - -typedef UINT8 tBTA_AV_RC; - -/* state flag for pass through command */ -#define BTA_AV_STATE_PRESS AVRC_STATE_PRESS /* key pressed */ -#define BTA_AV_STATE_RELEASE AVRC_STATE_RELEASE /* key released */ - -typedef UINT8 tBTA_AV_STATE; - -/* command codes for BTA_AvVendorCmd */ -#define BTA_AV_CMD_CTRL AVRC_CMD_CTRL -#define BTA_AV_CMD_STATUS AVRC_CMD_STATUS -#define BTA_AV_CMD_SPEC_INQ AVRC_CMD_SPEC_INQ -#define BTA_AV_CMD_NOTIF AVRC_CMD_NOTIF -#define BTA_AV_CMD_GEN_INQ AVRC_CMD_GEN_INQ - -typedef UINT8 tBTA_AV_CMD; - -/* response codes for BTA_AvVendorRsp */ -#define BTA_AV_RSP_NOT_IMPL AVRC_RSP_NOT_IMPL -#define BTA_AV_RSP_ACCEPT AVRC_RSP_ACCEPT -#define BTA_AV_RSP_REJ AVRC_RSP_REJ -#define BTA_AV_RSP_IN_TRANS AVRC_RSP_IN_TRANS -#define BTA_AV_RSP_IMPL_STBL AVRC_RSP_IMPL_STBL -#define BTA_AV_RSP_CHANGED AVRC_RSP_CHANGED -#define BTA_AV_RSP_INTERIM AVRC_RSP_INTERIM - -typedef UINT8 tBTA_AV_CODE; - -/* error codes for BTA_AvProtectRsp */ -#define BTA_AV_ERR_NONE A2D_SUCCESS /* Success, no error */ -#define BTA_AV_ERR_BAD_STATE AVDT_ERR_BAD_STATE /* Message cannot be processed in this state */ -#define BTA_AV_ERR_RESOURCE AVDT_ERR_RESOURCE /* Insufficient resources */ -#define BTA_AV_ERR_BAD_CP_TYPE A2D_BAD_CP_TYPE /* The requested Content Protection Type is not supported */ -#define BTA_AV_ERR_BAD_CP_FORMAT A2D_BAD_CP_FORMAT /* The format of Content Protection Data is not correct */ - -typedef UINT8 tBTA_AV_ERR; - - -/* AV callback events */ -#define BTA_AV_ENABLE_EVT 0 /* AV enabled */ -#define BTA_AV_REGISTER_EVT 1 /* registered to AVDT */ -#define BTA_AV_OPEN_EVT 2 /* connection opened */ -#define BTA_AV_CLOSE_EVT 3 /* connection closed */ -#define BTA_AV_START_EVT 4 /* stream data transfer started */ -#define BTA_AV_STOP_EVT 5 /* stream data transfer stopped */ -#define BTA_AV_PROTECT_REQ_EVT 6 /* content protection request */ -#define BTA_AV_PROTECT_RSP_EVT 7 /* content protection response */ -#define BTA_AV_RC_OPEN_EVT 8 /* remote control channel open */ -#define BTA_AV_RC_CLOSE_EVT 9 /* remote control channel closed */ -#define BTA_AV_REMOTE_CMD_EVT 10 /* remote control command */ -#define BTA_AV_REMOTE_RSP_EVT 11 /* remote control response */ -#define BTA_AV_VENDOR_CMD_EVT 12 /* vendor dependent remote control command */ -#define BTA_AV_VENDOR_RSP_EVT 13 /* vendor dependent remote control response */ -#define BTA_AV_RECONFIG_EVT 14 /* reconfigure response */ -#define BTA_AV_SUSPEND_EVT 15 /* suspend response */ -#define BTA_AV_PENDING_EVT 16 /* incoming connection pending: - * signal channel is open and stream is not open - * after BTA_AV_SIG_TIME_VAL ms */ -#define BTA_AV_META_MSG_EVT 17 /* metadata messages */ -#define BTA_AV_REJECT_EVT 18 /* incoming connection rejected */ -#define BTA_AV_RC_FEAT_EVT 19 /* remote control channel peer supported features update */ -#define BTA_AV_MEDIA_SINK_CFG_EVT 20 /* command to configure codec */ -#define BTA_AV_MEDIA_DATA_EVT 21 /* sending data to Media Task */ -/* Max BTA event */ -#define BTA_AV_MAX_EVT 22 - - -/* function types for call-out functions */ -typedef BOOLEAN (*tBTA_AV_CO_INIT) (UINT8 *p_codec_type, UINT8 *p_codec_info, - UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 index); -typedef void (*tBTA_AV_CO_DISC_RES) (tBTA_AV_HNDL hndl, UINT8 num_seps, - UINT8 num_snk, UINT8 num_src, BD_ADDR addr, UINT16 uuid_local); -typedef UINT8 (*tBTA_AV_CO_GETCFG) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid, - UINT8 *p_num_protect, UINT8 *p_protect_info); -typedef void (*tBTA_AV_CO_SETCFG) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, UINT8 seid, BD_ADDR addr, - UINT8 num_protect, UINT8 *p_protect_info, - UINT8 t_local_sep, UINT8 avdt_handle); -typedef void (*tBTA_AV_CO_OPEN) (tBTA_AV_HNDL hndl, - tBTA_AV_CODEC codec_type, UINT8 *p_codec_info, - UINT16 mtu); -typedef void (*tBTA_AV_CO_CLOSE) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, UINT16 mtu); -typedef void (*tBTA_AV_CO_START) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr); -typedef void (*tBTA_AV_CO_STOP) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type); -typedef void *(*tBTA_AV_CO_DATAPATH) (tBTA_AV_CODEC codec_type, - UINT32 *p_len, UINT32 *p_timestamp); -typedef void (*tBTA_AV_CO_DELAY) (tBTA_AV_HNDL hndl, UINT16 delay); - -/* the call-out functions for one stream */ -typedef struct { - tBTA_AV_CO_INIT init; - tBTA_AV_CO_DISC_RES disc_res; - tBTA_AV_CO_GETCFG getcfg; - tBTA_AV_CO_SETCFG setcfg; - tBTA_AV_CO_OPEN open; - tBTA_AV_CO_CLOSE close; - tBTA_AV_CO_START start; - tBTA_AV_CO_STOP stop; - tBTA_AV_CO_DATAPATH data; - tBTA_AV_CO_DELAY delay; -} tBTA_AV_CO_FUNCTS; - -typedef UINT8 tBTA_AV_EVT; - -/* Event associated with BTA_AV_ENABLE_EVT */ -typedef struct { - tBTA_AV_FEAT features; -} tBTA_AV_ENABLE; - -/* Event associated with BTA_AV_REGISTER_EVT */ -typedef struct { - tBTA_AV_CHNL chnl; /* audio/video */ - tBTA_AV_HNDL hndl; /* Handle associated with the stream. */ - UINT8 app_id; /* ID associated with call to BTA_AvRegister() */ - tBTA_AV_STATUS status; - tBTA_AV_CO_FUNCTS *p_bta_av_cos; -} tBTA_AV_REGISTER; - -/* data associated with BTA_AV_OPEN_EVT */ -#define BTA_AV_EDR_2MBPS 0x01 -#define BTA_AV_EDR_3MBPS 0x02 -typedef UINT8 tBTA_AV_EDR; - -typedef struct { - tBTA_AV_CHNL chnl; - tBTA_AV_HNDL hndl; - BD_ADDR bd_addr; - tBTA_AV_STATUS status; - BOOLEAN starting; - tBTA_AV_EDR edr; /* 0, if peer device does not support EDR */ - UINT8 sep; /* sep type of peer device */ -} tBTA_AV_OPEN; - -/* data associated with BTA_AV_CLOSE_EVT */ -typedef struct { - tBTA_AV_CHNL chnl; - tBTA_AV_HNDL hndl; - UINT8 disc_rsn; /* disconnection reason */ -} tBTA_AV_CLOSE; - -/* data associated with BTA_AV_START_EVT */ -typedef struct { - tBTA_AV_CHNL chnl; - tBTA_AV_HNDL hndl; - tBTA_AV_STATUS status; - BOOLEAN initiator; /* TRUE, if local device initiates the START */ - BOOLEAN suspending; -} tBTA_AV_START; - -/* data associated with BTA_AV_SUSPEND_EVT */ -typedef struct { - tBTA_AV_CHNL chnl; - tBTA_AV_HNDL hndl; - BOOLEAN initiator; /* TRUE, if local device initiates the SUSPEND */ - tBTA_AV_STATUS status; -} tBTA_AV_SUSPEND; - -/* data associated with BTA_AV_RECONFIG_EVT */ -typedef struct { - tBTA_AV_CHNL chnl; - tBTA_AV_HNDL hndl; - tBTA_AV_STATUS status; -} tBTA_AV_RECONFIG; - -/* data associated with BTA_AV_PROTECT_REQ_EVT */ -typedef struct { - tBTA_AV_CHNL chnl; - tBTA_AV_HNDL hndl; - UINT8 *p_data; - UINT16 len; -} tBTA_AV_PROTECT_REQ; - -/* data associated with BTA_AV_PROTECT_RSP_EVT */ -typedef struct { - tBTA_AV_CHNL chnl; - tBTA_AV_HNDL hndl; - UINT8 *p_data; - UINT16 len; - tBTA_AV_ERR err_code; -} tBTA_AV_PROTECT_RSP; - -/* data associated with BTA_AV_RC_OPEN_EVT */ -typedef struct { - UINT8 rc_handle; - BOOLEAN sdp_disc_done; - tBTA_AV_FEAT peer_features; - BD_ADDR peer_addr; - tBTA_AV_STATUS status; -} tBTA_AV_RC_OPEN; - -/* data associated with BTA_AV_RC_CLOSE_EVT */ -typedef struct { - UINT8 rc_handle; - BD_ADDR peer_addr; -} tBTA_AV_RC_CLOSE; - -/* data associated with BTA_AV_RC_FEAT_EVT */ -typedef struct { - UINT8 rc_handle; - tBTA_AV_FEAT peer_features; -} tBTA_AV_RC_FEAT; - -/* data associated with BTA_AV_REMOTE_CMD_EVT */ -typedef struct { - UINT8 rc_handle; - tBTA_AV_RC rc_id; - tBTA_AV_STATE key_state; - UINT8 len; - UINT8 *p_data; - tAVRC_HDR hdr; /* Message header. */ - UINT8 label; -} tBTA_AV_REMOTE_CMD; - -/* data associated with BTA_AV_REMOTE_RSP_EVT */ -typedef struct { - UINT8 rc_handle; - tBTA_AV_RC rc_id; - tBTA_AV_STATE key_state; - UINT8 len; - UINT8 *p_data; - tBTA_AV_CODE rsp_code; - UINT8 label; -} tBTA_AV_REMOTE_RSP; - -/* data associated with BTA_AV_VENDOR_CMD_EVT, BTA_AV_VENDOR_RSP_EVT */ -typedef struct { - UINT8 rc_handle; - UINT16 len; /* Max vendor dependent message is 512 */ - UINT8 label; - tBTA_AV_CODE code; - UINT32 company_id; - UINT8 *p_data; -} tBTA_AV_VENDOR; - -/* data associated with BTA_AV_META_MSG_EVT */ -typedef struct { - UINT8 rc_handle; - UINT16 len; - UINT8 label; - tBTA_AV_CODE code; - UINT32 company_id; - UINT8 *p_data; - tAVRC_MSG *p_msg; -} tBTA_AV_META_MSG; - -/* data associated with BTA_AV_PENDING_EVT */ -typedef struct { - BD_ADDR bd_addr; -} tBTA_AV_PEND; - -/* data associated with BTA_AV_REJECT_EVT */ -typedef struct { - BD_ADDR bd_addr; - tBTA_AV_HNDL hndl; /* Handle associated with the stream that rejected the connection. */ -} tBTA_AV_REJECT; - - -/* union of data associated with AV callback */ -typedef union { - tBTA_AV_CHNL chnl; - tBTA_AV_ENABLE enable; - tBTA_AV_REGISTER registr; - tBTA_AV_OPEN open; - tBTA_AV_CLOSE close; - tBTA_AV_START start; - tBTA_AV_PROTECT_REQ protect_req; - tBTA_AV_PROTECT_RSP protect_rsp; - tBTA_AV_RC_OPEN rc_open; - tBTA_AV_RC_CLOSE rc_close; - tBTA_AV_REMOTE_CMD remote_cmd; - tBTA_AV_REMOTE_RSP remote_rsp; - tBTA_AV_VENDOR vendor_cmd; - tBTA_AV_VENDOR vendor_rsp; - tBTA_AV_RECONFIG reconfig; - tBTA_AV_SUSPEND suspend; - tBTA_AV_PEND pend; - tBTA_AV_META_MSG meta_msg; - tBTA_AV_REJECT reject; - tBTA_AV_RC_FEAT rc_feat; -} tBTA_AV; - -/* union of data associated with AV Media callback */ -typedef union { - BT_HDR *p_data; - UINT8 *codec_info; -} tBTA_AV_MEDIA; - - -#define BTA_AVC_PACKET_LEN AVRC_PACKET_LEN -#define BTA_VENDOR_DATA_OFFSET 6 -#define BTA_VENDOR_HEADER_LEN 4 -#define BTA_MAX_VENDOR_DEPENDENT_DATA_LEN (BTA_AVC_PACKET_LEN-BTA_VENDOR_DATA_OFFSET-BTA_VENDOR_HEADER_LEN) -#define BTA_GROUP_NAVI_MSG_OP_DATA_LEN 5 - -#define BTA_ERROR_INVALID_CMD AVRC_STS_BAD_CMD -#define BTA_ERROR_INVALID_PARAM AVRC_STS_BAD_PARAM -#define BTA_ERROR_BAD_CONTENTS AVRC_STS_NOT_FOUND -#define BTA_ERROR_INTERNAL AVRC_STS_INTERNAL_ERR - -#define BTA_AV_META_SINGLE_PACKET AVRC_PKT_SINGLE - -#define BTA_AV_CO_METADATA AVRC_CO_METADATA - -/* AV callback */ -typedef void (tBTA_AV_CBACK)(tBTA_AV_EVT event, tBTA_AV *p_data); -typedef void (tBTA_AV_DATA_CBACK)(tBTA_AV_EVT event, tBTA_AV_MEDIA *p_data); - -/* type for stream state machine action functions */ -typedef void (*tBTA_AV_ACT)(void *p_cb, void *p_data); - -/* type for registering VDP */ -typedef void (tBTA_AV_REG) (tAVDT_CS *p_cs, char *p_service_name, void *p_data); - -/* AV configuration structure */ -typedef struct { - UINT32 company_id; /* AVRCP Company ID */ - UINT16 avrc_mtu; /* AVRCP MTU at L2CAP for control channel */ - UINT16 avrc_br_mtu; /* AVRCP MTU at L2CAP for browsing channel */ - UINT16 avrc_ct_cat; /* AVRCP controller categories */ - UINT16 avrc_tg_cat; /* AVRCP target categories */ - UINT16 sig_mtu; /* AVDTP signaling channel MTU at L2CAP */ - UINT16 audio_mtu; /* AVDTP audio transport channel MTU at L2CAP */ - const UINT16 *p_audio_flush_to;/* AVDTP audio transport channel flush timeout */ - UINT16 audio_mqs; /* AVDTP audio channel max data queue size */ - UINT16 video_mtu; /* AVDTP video transport channel MTU at L2CAP */ - UINT16 video_flush_to; /* AVDTP video transport channel flush timeout */ - BOOLEAN avrc_group; /* TRUE, to accept AVRC 1.3 group nevigation command */ - UINT8 num_co_ids; /* company id count in p_meta_co_ids */ - UINT8 num_evt_ids; /* event id count in p_meta_evt_ids */ - tBTA_AV_CODE rc_pass_rsp; /* the default response code for pass through commands */ - const UINT32 *p_meta_co_ids;/* the metadata Get Capabilities response for company id */ - const UINT8 *p_meta_evt_ids;/* the the metadata Get Capabilities response for event id */ - const tBTA_AV_ACT *p_act_tbl;/* the action function table for VDP stream */ - tBTA_AV_REG *p_reg; /* action function to register VDP */ - char avrc_controller_name[BTA_SERVICE_NAME_LEN]; /* Default AVRCP controller name */ - char avrc_target_name[BTA_SERVICE_NAME_LEN]; /* Default AVRCP target name*/ -} tBTA_AV_CFG; - -#ifdef __cplusplus -extern "C" -{ -#endif - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ - -/******************************************************************************* -** -** Function BTA_AvEnable -** -** Description Enable the advanced audio/video service. When the enable -** operation is complete the callback function will be -** called with a BTA_AV_ENABLE_EVT. This function must -** be called before other function in the AV API are -** called. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvEnable(tBTA_SEC sec_mask, tBTA_AV_FEAT features, - tBTA_AV_CBACK *p_cback); - -/******************************************************************************* -** -** Function BTA_AvDisable -** -** Description Disable the advanced audio/video service. -** -** -** Returns void -** -*******************************************************************************/ -void BTA_AvDisable(void); - -/******************************************************************************* -** -** Function BTA_AvRegister -** -** Description Register the audio or video service to stack. When the -** operation is complete the callback function will be -** called with a BTA_AV_REGISTER_EVT. This function must -** be called before AVDT stream is open. -** -** -** Returns void -** -*******************************************************************************/ -void BTA_AvRegister(tBTA_AV_CHNL chnl, const char *p_service_name, - UINT8 app_id, tBTA_AV_DATA_CBACK *p_data_cback, tBTA_AV_CO_FUNCTS *bta_av_cos); - -/******************************************************************************* -** -** Function BTA_AvDeregister -** -** Description Deregister the audio or video service -** -** Returns void -** -*******************************************************************************/ -void BTA_AvDeregister(tBTA_AV_HNDL hndl); - -/******************************************************************************* -** -** Function BTA_AvOpen -** -** Description Opens an advanced audio/video connection to a peer device. -** When connection is open callback function is called -** with a BTA_AV_OPEN_EVT. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvOpen(BD_ADDR bd_addr, tBTA_AV_HNDL handle, - BOOLEAN use_rc, tBTA_SEC sec_mask, UINT16 uuid); - -/******************************************************************************* -** -** Function BTA_AvClose -** -** Description Close the current streams. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvClose(tBTA_AV_HNDL handle); - -/******************************************************************************* -** -** Function BTA_AvDisconnect -** -** Description Close the connection to the address. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvDisconnect(BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTA_AvEnable_Sink -** -** Description Enable/Disable A2DP Sink. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvEnable_Sink(int enable); - -/******************************************************************************* -** -** Function BTA_AvStart -** -** Description Start audio/video stream data transfer. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvStart(void); - -/******************************************************************************* -** -** Function BTA_AvStop -** -** Description Stop audio/video stream data transfer. -** If suspend is TRUE, this function sends AVDT suspend signal -** to the connected peer(s). -** -** Returns void -** -*******************************************************************************/ -void BTA_AvStop(BOOLEAN suspend); - -/******************************************************************************* -** -** Function BTA_AvReconfig -** -** Description Reconfigure the audio/video stream. -** If suspend is TRUE, this function tries the suspend/reconfigure -** procedure first. -** If suspend is FALSE or when suspend/reconfigure fails, -** this function closes and re-opens the AVDT connection. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvReconfig(tBTA_AV_HNDL hndl, BOOLEAN suspend, UINT8 sep_info_idx, - UINT8 *p_codec_info, UINT8 num_protect, UINT8 *p_protect_info); - -/******************************************************************************* -** -** Function BTA_AvProtectReq -** -** Description Send a content protection request. This function can only -** be used if AV is enabled with feature BTA_AV_FEAT_PROTECT. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvProtectReq(tBTA_AV_HNDL hndl, UINT8 *p_data, UINT16 len); - -/******************************************************************************* -** -** Function BTA_AvProtectRsp -** -** Description Send a content protection response. This function must -** be called if a BTA_AV_PROTECT_REQ_EVT is received. -** This function can only be used if AV is enabled with -** feature BTA_AV_FEAT_PROTECT. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, UINT8 error_code, UINT8 *p_data, - UINT16 len); - -/******************************************************************************* -** -** Function BTA_AvRemoteCmd -** -** Description Send a remote control command. This function can only -** be used if AV is enabled with feature BTA_AV_FEAT_RCCT. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvRemoteCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_RC rc_id, - tBTA_AV_STATE key_state); - -/******************************************************************************* -** -** Function BTA_AvVendorCmd -** -** Description Send a vendor dependent remote control command. This -** function can only be used if AV is enabled with feature -** BTA_AV_FEAT_VENDOR. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvVendorCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE cmd_code, - UINT8 *p_data, UINT16 len); - -/******************************************************************************* -** -** Function BTA_AvVendorRsp -** -** Description Send a vendor dependent remote control response. -** This function must be called if a BTA_AV_VENDOR_CMD_EVT -** is received. This function can only be used if AV is -** enabled with feature BTA_AV_FEAT_VENDOR. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvVendorRsp(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE rsp_code, - UINT8 *p_data, UINT16 len, UINT32 company_id); - - -/******************************************************************************* -** -** Function BTA_AvOpenRc -** -** Description Open an AVRCP connection toward the device with the -** specified handle -** -** Returns void -** -*******************************************************************************/ -void BTA_AvOpenRc(tBTA_AV_HNDL handle); - -/******************************************************************************* -** -** Function BTA_AvCloseRc -** -** Description Close an AVRCP connection -** -** Returns void -** -*******************************************************************************/ -void BTA_AvCloseRc(UINT8 rc_handle); - -/******************************************************************************* -** -** Function BTA_AvMetaRsp -** -** Description Send a Metadata command/response. The message contained -** in p_pkt can be composed with AVRC utility functions. -** This function can only be used if AV is enabled with feature -** BTA_AV_FEAT_METADATA. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvMetaRsp(UINT8 rc_handle, UINT8 label, tBTA_AV_CODE rsp_code, - BT_HDR *p_pkt); - -/******************************************************************************* -** -** Function BTA_AvMetaCmd -** -** Description Send a Metadata/Advanced Control command. The message contained -** in p_pkt can be composed with AVRC utility functions. -** This function can only be used if AV is enabled with feature -** BTA_AV_FEAT_METADATA. -** This message is sent only when the peer supports the TG role. -*8 The only command makes sense right now is the absolute volume command. -** -** Returns void -** -*******************************************************************************/ -void BTA_AvMetaCmd(UINT8 rc_handle, UINT8 label, tBTA_AV_CMD cmd_code, BT_HDR *p_pkt); - -#ifdef __cplusplus -} -#endif - -#endif ///BTA_AV_INCLUDED == TRUE - -#endif /* BTA_AV_API_H */ diff --git a/tools/sdk/include/bluedroid/bta_av_ci.h b/tools/sdk/include/bluedroid/bta_av_ci.h deleted file mode 100644 index a537b8a4caf..00000000000 --- a/tools/sdk/include/bluedroid/bta_av_ci.h +++ /dev/null @@ -1,77 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2005-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for advanced audio/video call-in functions. - * - ******************************************************************************/ -#ifndef BTA_AV_CI_H -#define BTA_AV_CI_H - -#include "bta_av_api.h" - -#if (BTA_AV_INCLUDED == TRUE) - -/***************************************************************************** -** Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function bta_av_ci_src_data_ready -** -** Description This function sends an event to the AV indicating that -** the phone has audio stream data ready to send and AV -** should call bta_av_co_audio_src_data_path() or -** bta_av_co_video_src_data_path(). -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_ci_src_data_ready(tBTA_AV_CHNL chnl); - -/******************************************************************************* -** -** Function bta_av_ci_setconfig -** -** Description This function must be called in response to function -** bta_av_co_audio_setconfig() or bta_av_co_video_setconfig. -** Parameter err_code is set to an AVDTP status value; -** AVDT_SUCCESS if the codec configuration is ok, -** otherwise error. -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_ci_setconfig(tBTA_AV_HNDL hndl, UINT8 err_code, - UINT8 category, UINT8 num_seid, UINT8 *p_seid, - BOOLEAN recfg_needed, UINT8 avdt_handle); - - -#ifdef __cplusplus -} -#endif - -#endif ///BTA_AV_INCLUDED == TRUE - -#endif /* BTA_AV_CI_H */ diff --git a/tools/sdk/include/bluedroid/bta_av_co.h b/tools/sdk/include/bluedroid/bta_av_co.h deleted file mode 100644 index 3f7f989d6c9..00000000000 --- a/tools/sdk/include/bluedroid/bta_av_co.h +++ /dev/null @@ -1,393 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for advanced audio/video call-out functions. - * - ******************************************************************************/ -#ifndef BTA_AV_CO_H -#define BTA_AV_CO_H - -#include "l2c_api.h" -#include "bta_av_api.h" - -#if (BTA_AV_INCLUDED == TRUE) - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ - -/* TRUE to use SCMS-T content protection */ -#ifndef BTA_AV_CO_CP_SCMS_T -#define BTA_AV_CO_CP_SCMS_T FALSE -#endif - -/* the content protection IDs assigned by BT SIG */ -#define BTA_AV_CP_SCMS_T_ID 0x0002 -#define BTA_AV_CP_DTCP_ID 0x0001 - -#define BTA_AV_CP_LOSC 2 -#define BTA_AV_CP_INFO_LEN 3 - -#define BTA_AV_CP_SCMS_COPY_MASK 3 -#define BTA_AV_CP_SCMS_COPY_FREE 2 -#define BTA_AV_CP_SCMS_COPY_ONCE 1 -#define BTA_AV_CP_SCMS_COPY_NEVER 0 - -#define BTA_AV_CO_DEFAULT_AUDIO_OFFSET AVDT_MEDIA_OFFSET - -enum { - BTA_AV_CO_ST_INIT, - BTA_AV_CO_ST_IN, - BTA_AV_CO_ST_OUT, - BTA_AV_CO_ST_OPEN, - BTA_AV_CO_ST_STREAM -}; - - -/* data type for the Audio Codec Information*/ -typedef struct { - UINT16 bit_rate; /* SBC encoder bit rate in kbps */ - UINT16 bit_rate_busy; /* SBC encoder bit rate in kbps */ - UINT16 bit_rate_swampd;/* SBC encoder bit rate in kbps */ - UINT8 busy_level; /* Busy level indicating the bit-rate to be used */ - UINT8 codec_info[AVDT_CODEC_SIZE]; - UINT8 codec_type; /* Codec type */ -} tBTA_AV_AUDIO_CODEC_INFO; - -/******************************************************************************* -** -** Function bta_av_co_audio_init -** -** Description This callout function is executed by AV when it is -** started by calling BTA_AvEnable(). This function can be -** used by the phone to initialize audio paths or for other -** initialization purposes. -** -** -** Returns Stream codec and content protection capabilities info. -** -*******************************************************************************/ -extern BOOLEAN bta_av_co_audio_init(UINT8 *p_codec_type, UINT8 *p_codec_info, - UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 index); - -/******************************************************************************* -** -** Function bta_av_co_audio_disc_res -** -** Description This callout function is executed by AV to report the -** number of stream end points (SEP) were found during the -** AVDT stream discovery process. -** -** -** Returns void. -** -*******************************************************************************/ -extern void bta_av_co_audio_disc_res(tBTA_AV_HNDL hndl, UINT8 num_seps, - UINT8 num_snk, UINT8 num_src, BD_ADDR addr, UINT16 uuid_local); - -/******************************************************************************* -** -** Function bta_av_co_video_disc_res -** -** Description This callout function is executed by AV to report the -** number of stream end points (SEP) were found during the -** AVDT stream discovery process. -** -** -** Returns void. -** -*******************************************************************************/ -extern void bta_av_co_video_disc_res(tBTA_AV_HNDL hndl, UINT8 num_seps, - UINT8 num_snk, BD_ADDR addr); - -/******************************************************************************* -** -** Function bta_av_co_audio_getconfig -** -** Description This callout function is executed by AV to retrieve the -** desired codec and content protection configuration for the -** audio stream. -** -** -** Returns Stream codec and content protection configuration info. -** -*******************************************************************************/ -extern UINT8 bta_av_co_audio_getconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid, - UINT8 *p_num_protect, UINT8 *p_protect_info); - -/******************************************************************************* -** -** Function bta_av_co_video_getconfig -** -** Description This callout function is executed by AV to retrieve the -** desired codec and content protection configuration for the -** video stream. -** -** -** Returns Stream codec and content protection configuration info. -** -*******************************************************************************/ -extern UINT8 bta_av_co_video_getconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid, - UINT8 *p_num_protect, UINT8 *p_protect_info); - -/******************************************************************************* -** -** Function bta_av_co_audio_setconfig -** -** Description This callout function is executed by AV to set the -** codec and content protection configuration of the audio stream. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_audio_setconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, UINT8 seid, BD_ADDR addr, - UINT8 num_protect, UINT8 *p_protect_info, UINT8 t_local_sep, UINT8 avdt_handle); - -/******************************************************************************* -** -** Function bta_av_co_video_setconfig -** -** Description This callout function is executed by AV to set the -** codec and content protection configuration of the video stream. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_video_setconfig(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, UINT8 seid, BD_ADDR addr, - UINT8 num_protect, UINT8 *p_protect_info); - -/******************************************************************************* -** -** Function bta_av_co_audio_open -** -** Description This function is called by AV when the audio stream connection -** is opened. -** BTA-AV maintains the MTU of A2DP streams. -** If this is the 2nd audio stream, mtu is the smaller of the 2 -** streams. -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_audio_open(tBTA_AV_HNDL hndl, - tBTA_AV_CODEC codec_type, UINT8 *p_codec_info, - UINT16 mtu); - -/******************************************************************************* -** -** Function bta_av_co_video_open -** -** Description This function is called by AV when the video stream connection -** is opened. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_video_open(tBTA_AV_HNDL hndl, - tBTA_AV_CODEC codec_type, UINT8 *p_codec_info, - UINT16 mtu); - -/******************************************************************************* -** -** Function bta_av_co_audio_close -** -** Description This function is called by AV when the audio stream connection -** is closed. -** BTA-AV maintains the MTU of A2DP streams. -** When one stream is closed and no other audio stream is open, -** mtu is reported as 0. -** Otherwise, the MTU remains open is reported. -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_audio_close(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT16 mtu); - -/******************************************************************************* -** -** Function bta_av_co_video_close -** -** Description This function is called by AV when the video stream connection -** is closed. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_video_close(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT16 mtu); - -/******************************************************************************* -** -** Function bta_av_co_audio_start -** -** Description This function is called by AV when the audio streaming data -** transfer is started. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_audio_start(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr); - -/******************************************************************************* -** -** Function bta_av_co_video_start -** -** Description This function is called by AV when the video streaming data -** transfer is started. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_video_start(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr); - -/******************************************************************************* -** -** Function bta_av_co_audio_stop -** -** Description This function is called by AV when the audio streaming data -** transfer is stopped. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_audio_stop(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type); - -/******************************************************************************* -** -** Function bta_av_co_video_stop -** -** Description This function is called by AV when the video streaming data -** transfer is stopped. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_video_stop(tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type); - -/******************************************************************************* -** -** Function bta_av_co_audio_src_data_path -** -** Description This function is called to get the next data buffer from -** the audio codec -** -** Returns NULL if data is not ready. -** Otherwise, a buffer (BT_HDR*) containing the audio data. -** -*******************************************************************************/ -extern void *bta_av_co_audio_src_data_path(tBTA_AV_CODEC codec_type, - UINT32 *p_len, UINT32 *p_timestamp); - -/******************************************************************************* -** -** Function bta_av_co_video_src_data_path -** -** Description This function is called to get the next data buffer from -** the video codec. -** -** Returns NULL if data is not ready. -** Otherwise, a video data buffer (UINT8*). -** -*******************************************************************************/ -extern void *bta_av_co_video_src_data_path(tBTA_AV_CODEC codec_type, - UINT32 *p_len, UINT32 *p_timestamp); - -/******************************************************************************* -** -** Function bta_av_co_audio_drop -** -** Description An Audio packet is dropped. . -** It's very likely that the connected headset with this handle -** is moved far away. The implementation may want to reduce -** the encoder bit rate setting to reduce the packet size. -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_audio_drop(tBTA_AV_HNDL hndl); - -/******************************************************************************* -** -** Function bta_av_co_video_report_conn -** -** Description This function is called by AV when the reporting channel is -** opened (open=TRUE) or closed (open=FALSE). -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_video_report_conn (BOOLEAN open, UINT8 avdt_handle); - -/******************************************************************************* -** -** Function bta_av_co_video_report_rr -** -** Description This function is called by AV when a Receiver Report is -** received -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_video_report_rr (UINT32 packet_lost); - -/******************************************************************************* -** -** Function bta_av_co_audio_delay -** -** Description This function is called by AV when the audio stream connection -** needs to send the initial delay report to the connected SRC. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_audio_delay(tBTA_AV_HNDL hndl, UINT16 delay); - -/******************************************************************************* -** -** Function bta_av_co_video_delay -** -** Description This function is called by AV when the video stream connection -** needs to send the initial delay report to the connected SRC. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_co_video_delay(tBTA_AV_HNDL hndl, UINT16 delay); - -#endif ///BTA_AV_INCLUDED == TRUE - -#endif /* BTA_AV_CO_H */ diff --git a/tools/sdk/include/bluedroid/bta_av_int.h b/tools/sdk/include/bluedroid/bta_av_int.h deleted file mode 100644 index 2409c3a4807..00000000000 --- a/tools/sdk/include/bluedroid/bta_av_int.h +++ /dev/null @@ -1,708 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2004-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the private interface file for the BTA advanced audio/video. - * - ******************************************************************************/ -#ifndef BTA_AV_INT_H -#define BTA_AV_INT_H - -#include "bta_sys.h" -#include "bta_api.h" -#include "bta_av_api.h" -#include "avdt_api.h" -#include "bta_av_co.h" -#include "list.h" - -#if (BTA_AV_INCLUDED == TRUE) - -#define BTA_AV_DEBUG TRUE -/***************************************************************************** -** Constants -*****************************************************************************/ - -enum { - /* these events are handled by the AV main state machine */ - BTA_AV_API_DISABLE_EVT = BTA_SYS_EVT_START(BTA_ID_AV), - BTA_AV_API_REMOTE_CMD_EVT, - BTA_AV_API_VENDOR_CMD_EVT, - BTA_AV_API_VENDOR_RSP_EVT, - BTA_AV_API_META_RSP_EVT, - BTA_AV_API_RC_CLOSE_EVT, - BTA_AV_AVRC_OPEN_EVT, - BTA_AV_AVRC_MSG_EVT, - BTA_AV_AVRC_NONE_EVT, - - /* these events are handled by the AV stream state machine */ - BTA_AV_API_OPEN_EVT, - BTA_AV_API_CLOSE_EVT, - BTA_AV_AP_START_EVT, /* the following 2 events must be in the same order as the *API_*EVT */ - BTA_AV_AP_STOP_EVT, - BTA_AV_API_RECONFIG_EVT, - BTA_AV_API_PROTECT_REQ_EVT, - BTA_AV_API_PROTECT_RSP_EVT, - BTA_AV_API_RC_OPEN_EVT, - BTA_AV_SRC_DATA_READY_EVT, - BTA_AV_CI_SETCONFIG_OK_EVT, - BTA_AV_CI_SETCONFIG_FAIL_EVT, - BTA_AV_SDP_DISC_OK_EVT, - BTA_AV_SDP_DISC_FAIL_EVT, - BTA_AV_STR_DISC_OK_EVT, - BTA_AV_STR_DISC_FAIL_EVT, - BTA_AV_STR_GETCAP_OK_EVT, - BTA_AV_STR_GETCAP_FAIL_EVT, - BTA_AV_STR_OPEN_OK_EVT, - BTA_AV_STR_OPEN_FAIL_EVT, - BTA_AV_STR_START_OK_EVT, - BTA_AV_STR_START_FAIL_EVT, - BTA_AV_STR_CLOSE_EVT, - BTA_AV_STR_CONFIG_IND_EVT, - BTA_AV_STR_SECURITY_IND_EVT, - BTA_AV_STR_SECURITY_CFM_EVT, - BTA_AV_STR_WRITE_CFM_EVT, - BTA_AV_STR_SUSPEND_CFM_EVT, - BTA_AV_STR_RECONFIG_CFM_EVT, - BTA_AV_AVRC_TIMER_EVT, - BTA_AV_AVDT_CONNECT_EVT, - BTA_AV_AVDT_DISCONNECT_EVT, - BTA_AV_ROLE_CHANGE_EVT, - BTA_AV_AVDT_DELAY_RPT_EVT, - BTA_AV_ACP_CONNECT_EVT, - - /* these events are handled outside of the state machine */ - BTA_AV_API_ENABLE_EVT, - BTA_AV_API_REGISTER_EVT, - BTA_AV_API_DEREGISTER_EVT, - BTA_AV_API_DISCONNECT_EVT, - BTA_AV_CI_SRC_DATA_READY_EVT, - BTA_AV_SIG_CHG_EVT, - BTA_AV_SIG_TIMER_EVT, - BTA_AV_SDP_AVRC_DISC_EVT, - BTA_AV_AVRC_CLOSE_EVT, - BTA_AV_CONN_CHG_EVT, - BTA_AV_DEREG_COMP_EVT, -#if (BTA_AV_SINK_INCLUDED == TRUE) - BTA_AV_API_SINK_ENABLE_EVT, -#endif -#if (AVDT_REPORTING == TRUE) - BTA_AV_AVDT_RPT_CONN_EVT, -#endif - BTA_AV_API_START_EVT, /* the following 2 events must be in the same order as the *AP_*EVT */ - BTA_AV_API_STOP_EVT -}; - -/* events for AV control block state machine */ -#define BTA_AV_FIRST_SM_EVT BTA_AV_API_DISABLE_EVT -#define BTA_AV_LAST_SM_EVT BTA_AV_AVRC_NONE_EVT - -/* events for AV stream control block state machine */ -#define BTA_AV_FIRST_SSM_EVT BTA_AV_API_OPEN_EVT - -/* events that do not go through state machine */ -#define BTA_AV_FIRST_NSM_EVT BTA_AV_API_ENABLE_EVT -#define BTA_AV_LAST_NSM_EVT BTA_AV_API_STOP_EVT - -/* API events passed to both SSMs (by bta_av_api_to_ssm) */ -#define BTA_AV_FIRST_A2S_API_EVT BTA_AV_API_START_EVT -#define BTA_AV_FIRST_A2S_SSM_EVT BTA_AV_AP_START_EVT - -#define BTA_AV_LAST_EVT BTA_AV_API_STOP_EVT - -/* maximum number of SEPS in stream discovery results */ -#define BTA_AV_NUM_SEPS 32 - -/* initialization value for AVRC handle */ -#define BTA_AV_RC_HANDLE_NONE 0xFF - -/* size of database for service discovery */ -#define BTA_AV_DISC_BUF_SIZE 1000 - -/* offset of media type in codec info byte array */ -#define BTA_AV_MEDIA_TYPE_IDX 1 - -/* maximum length of AVDTP security data */ -#define BTA_AV_SECURITY_MAX_LEN 400 - -/* check number of buffers queued at L2CAP when this amount of buffers are queued to L2CAP */ -#define BTA_AV_QUEUE_DATA_CHK_NUM L2CAP_HIGH_PRI_MIN_XMIT_QUOTA - -/* the number of ACL links with AVDT */ -#define BTA_AV_NUM_LINKS AVDT_NUM_LINKS - -#define BTA_AV_CO_ID_TO_BE_STREAM(p, u32) {*(p)++ = (UINT8)((u32) >> 16); *(p)++ = (UINT8)((u32) >> 8); *(p)++ = (UINT8)(u32); } -#define BTA_AV_BE_STREAM_TO_CO_ID(u32, p) {u32 = (((UINT32)(*((p) + 2))) + (((UINT32)(*((p) + 1))) << 8) + (((UINT32)(*(p))) << 16)); (p) += 3;} - -/* these bits are defined for bta_av_cb.multi_av */ -#define BTA_AV_MULTI_AV_SUPPORTED 0x01 -#define BTA_AV_MULTI_AV_IN_USE 0x02 - - -/***************************************************************************** -** Data types -*****************************************************************************/ -#if 0 -/* function types for call-out functions */ -typedef BOOLEAN (*tBTA_AV_CO_INIT) (UINT8 *p_codec_type, UINT8 *p_codec_info, - UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 index); -typedef void (*tBTA_AV_CO_DISC_RES) (tBTA_AV_HNDL hndl, UINT8 num_seps, - UINT8 num_snk, UINT8 num_src, BD_ADDR addr, UINT16 uuid_local); -typedef UINT8 (*tBTA_AV_CO_GETCFG) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, UINT8 *p_sep_info_idx, UINT8 seid, - UINT8 *p_num_protect, UINT8 *p_protect_info); -typedef void (*tBTA_AV_CO_SETCFG) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, - UINT8 *p_codec_info, UINT8 seid, BD_ADDR addr, - UINT8 num_protect, UINT8 *p_protect_info, - UINT8 t_local_sep, UINT8 avdt_handle); -typedef void (*tBTA_AV_CO_OPEN) (tBTA_AV_HNDL hndl, - tBTA_AV_CODEC codec_type, UINT8 *p_codec_info, - UINT16 mtu); -typedef void (*tBTA_AV_CO_CLOSE) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, UINT16 mtu); -typedef void (*tBTA_AV_CO_START) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, UINT8 *p_codec_info, BOOLEAN *p_no_rtp_hdr); -typedef void (*tBTA_AV_CO_STOP) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type); -typedef void *(*tBTA_AV_CO_DATAPATH) (tBTA_AV_CODEC codec_type, - UINT32 *p_len, UINT32 *p_timestamp); -typedef void (*tBTA_AV_CO_DELAY) (tBTA_AV_HNDL hndl, UINT16 delay); - -/* the call-out functions for one stream */ -typedef struct { - tBTA_AV_CO_INIT init; - tBTA_AV_CO_DISC_RES disc_res; - tBTA_AV_CO_GETCFG getcfg; - tBTA_AV_CO_SETCFG setcfg; - tBTA_AV_CO_OPEN open; - tBTA_AV_CO_CLOSE close; - tBTA_AV_CO_START start; - tBTA_AV_CO_STOP stop; - tBTA_AV_CO_DATAPATH data; - tBTA_AV_CO_DELAY delay; -} tBTA_AV_CO_FUNCTS; -#endif - -/* data type for BTA_AV_API_ENABLE_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_AV_CBACK *p_cback; - tBTA_AV_FEAT features; - tBTA_SEC sec_mask; -} tBTA_AV_API_ENABLE; - -/* data type for BTA_AV_API_REG_EVT */ -typedef struct { - BT_HDR hdr; - char p_service_name[BTA_SERVICE_NAME_LEN + 1]; - UINT8 app_id; - tBTA_AV_DATA_CBACK *p_app_data_cback; - tBTA_AV_CO_FUNCTS *bta_av_cos; -} tBTA_AV_API_REG; - - -enum { - BTA_AV_RS_NONE, /* straight API call */ - BTA_AV_RS_OK, /* the role switch result - successful */ - BTA_AV_RS_FAIL, /* the role switch result - failed */ - BTA_AV_RS_DONE /* the role switch is done - continue */ -}; -typedef UINT8 tBTA_AV_RS_RES; -/* data type for BTA_AV_API_OPEN_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - BOOLEAN use_rc; - tBTA_SEC sec_mask; - tBTA_AV_RS_RES switch_res; - UINT16 uuid; /* uuid of initiator */ -} tBTA_AV_API_OPEN; - -/* data type for BTA_AV_API_STOP_EVT */ -typedef struct { - BT_HDR hdr; - BOOLEAN suspend; - BOOLEAN flush; -} tBTA_AV_API_STOP; - -/* data type for BTA_AV_API_DISCONNECT_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; -} tBTA_AV_API_DISCNT; - -/* data type for BTA_AV_API_PROTECT_REQ_EVT */ -typedef struct { - BT_HDR hdr; - UINT8 *p_data; - UINT16 len; -} tBTA_AV_API_PROTECT_REQ; - -/* data type for BTA_AV_API_PROTECT_RSP_EVT */ -typedef struct { - BT_HDR hdr; - UINT8 *p_data; - UINT16 len; - UINT8 error_code; -} tBTA_AV_API_PROTECT_RSP; - -/* data type for BTA_AV_API_REMOTE_CMD_EVT */ -typedef struct { - BT_HDR hdr; - tAVRC_MSG_PASS msg; - UINT8 label; -} tBTA_AV_API_REMOTE_CMD; - -/* data type for BTA_AV_API_VENDOR_CMD_EVT and RSP */ -typedef struct { - BT_HDR hdr; - tAVRC_MSG_VENDOR msg; - UINT8 label; -} tBTA_AV_API_VENDOR; - -/* data type for BTA_AV_API_RC_OPEN_EVT */ -typedef struct { - BT_HDR hdr; -} tBTA_AV_API_OPEN_RC; - -/* data type for BTA_AV_API_RC_CLOSE_EVT */ -typedef struct { - BT_HDR hdr; -} tBTA_AV_API_CLOSE_RC; - -/* data type for BTA_AV_API_META_RSP_EVT */ -typedef struct { - BT_HDR hdr; - BOOLEAN is_rsp; - UINT8 label; - tBTA_AV_CODE rsp_code; - BT_HDR *p_pkt; -} tBTA_AV_API_META_RSP; - - -/* data type for BTA_AV_API_RECONFIG_EVT */ -typedef struct { - BT_HDR hdr; - UINT8 codec_info[AVDT_CODEC_SIZE]; /* codec configuration */ - UINT8 *p_protect_info; - UINT8 num_protect; - BOOLEAN suspend; - UINT8 sep_info_idx; -} tBTA_AV_API_RCFG; - -/* data type for BTA_AV_CI_SETCONFIG_OK_EVT and BTA_AV_CI_SETCONFIG_FAIL_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_AV_HNDL hndl; - UINT8 err_code; - UINT8 category; - UINT8 num_seid; - UINT8 *p_seid; - BOOLEAN recfg_needed; - UINT8 avdt_handle; /* local sep type for which this stream will be set up */ -} tBTA_AV_CI_SETCONFIG; - -/* data type for all stream events from AVDTP */ -typedef struct { - BT_HDR hdr; - tAVDT_CFG cfg; /* configuration/capabilities parameters */ - tAVDT_CTRL msg; /* AVDTP callback message parameters */ - BD_ADDR bd_addr; /* bd address */ - UINT8 handle; - UINT8 avdt_event; - BOOLEAN initiator; /* TRUE, if local device initiates the SUSPEND */ -} tBTA_AV_STR_MSG; - -/* data type for BTA_AV_AVRC_MSG_EVT */ -typedef struct { - BT_HDR hdr; - tAVRC_MSG msg; - UINT8 handle; - UINT8 label; - UINT8 opcode; -} tBTA_AV_RC_MSG; - -/* data type for BTA_AV_AVRC_OPEN_EVT, BTA_AV_AVRC_CLOSE_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR peer_addr; - UINT8 handle; -} tBTA_AV_RC_CONN_CHG; - -/* data type for BTA_AV_CONN_CHG_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR peer_addr; - BOOLEAN is_up; -} tBTA_AV_CONN_CHG; - -/* data type for BTA_AV_ROLE_CHANGE_EVT */ -typedef struct { - BT_HDR hdr; - UINT8 new_role; - UINT8 hci_status; -} tBTA_AV_ROLE_RES; - -/* data type for BTA_AV_SDP_DISC_OK_EVT */ -typedef struct { - BT_HDR hdr; - UINT16 avdt_version; /* AVDTP protocol version */ -} tBTA_AV_SDP_RES; - -/* type for SEP control block */ -typedef struct { - UINT8 av_handle; /* AVDTP handle */ - tBTA_AV_CODEC codec_type; /* codec type */ - UINT8 tsep; /* SEP type of local SEP */ - tBTA_AV_DATA_CBACK *p_app_data_cback; /* Application callback for media packets */ -} tBTA_AV_SEP; - - -/* initiator/acceptor role for adaption */ -#define BTA_AV_ROLE_AD_INT 0x00 /* initiator */ -#define BTA_AV_ROLE_AD_ACP 0x01 /* acceptor */ - -/* initiator/acceptor signaling roles */ -#define BTA_AV_ROLE_START_ACP 0x00 -#define BTA_AV_ROLE_START_INT 0x10 /* do not change this value */ - -#define BTA_AV_ROLE_SUSPEND 0x20 /* suspending on start */ -#define BTA_AV_ROLE_SUSPEND_OPT 0x40 /* Suspend on Start option is set */ - -/* union of all event datatypes */ -typedef union { - BT_HDR hdr; - tBTA_AV_API_ENABLE api_enable; - tBTA_AV_API_REG api_reg; - tBTA_AV_API_OPEN api_open; - tBTA_AV_API_STOP api_stop; - tBTA_AV_API_DISCNT api_discnt; - tBTA_AV_API_PROTECT_REQ api_protect_req; - tBTA_AV_API_PROTECT_RSP api_protect_rsp; - tBTA_AV_API_REMOTE_CMD api_remote_cmd; - tBTA_AV_API_VENDOR api_vendor; - tBTA_AV_API_RCFG api_reconfig; - tBTA_AV_CI_SETCONFIG ci_setconfig; - tBTA_AV_STR_MSG str_msg; - tBTA_AV_RC_MSG rc_msg; - tBTA_AV_RC_CONN_CHG rc_conn_chg; - tBTA_AV_CONN_CHG conn_chg; - tBTA_AV_ROLE_RES role_res; - tBTA_AV_SDP_RES sdp_res; - tBTA_AV_API_META_RSP api_meta_rsp; -} tBTA_AV_DATA; - -typedef void (tBTA_AV_VDP_DATA_ACT)(void *p_scb); - -typedef struct { - tBTA_AV_VDP_DATA_ACT *p_act; - UINT8 *p_frame; - UINT16 buf_size; - UINT32 len; - UINT32 offset; - UINT32 timestamp; -} tBTA_AV_VF_INFO; - -typedef union { - tBTA_AV_VF_INFO vdp; /* used for video channels only */ - tBTA_AV_API_OPEN open; /* used only before open and role switch - is needed on another AV channel */ -} tBTA_AV_Q_INFO; - -#define BTA_AV_Q_TAG_OPEN 0x01 /* after API_OPEN, before STR_OPENED */ -#define BTA_AV_Q_TAG_START 0x02 /* before start sending media packets */ -#define BTA_AV_Q_TAG_STREAM 0x03 /* during streaming */ - -#define BTA_AV_WAIT_ACP_CAPS_ON 0x01 /* retriving the peer capabilities */ -#define BTA_AV_WAIT_ACP_CAPS_STARTED 0x02 /* started while retriving peer capabilities */ -#define BTA_AV_WAIT_ROLE_SW_RES_OPEN 0x04 /* waiting for role switch result after API_OPEN, before STR_OPENED */ -#define BTA_AV_WAIT_ROLE_SW_RES_START 0x08 /* waiting for role switch result before streaming */ -#define BTA_AV_WAIT_ROLE_SW_STARTED 0x10 /* started while waiting for role switch result */ -#define BTA_AV_WAIT_ROLE_SW_RETRY 0x20 /* set when retry on timeout */ -#define BTA_AV_WAIT_CHECK_RC 0x40 /* set when the timer is used by role switch */ -#define BTA_AV_WAIT_ROLE_SW_FAILED 0x80 /* role switch failed */ - -#define BTA_AV_WAIT_ROLE_SW_BITS (BTA_AV_WAIT_ROLE_SW_RES_OPEN|BTA_AV_WAIT_ROLE_SW_RES_START|BTA_AV_WAIT_ROLE_SW_STARTED|BTA_AV_WAIT_ROLE_SW_RETRY) - -/* Bitmap for collision, coll_mask */ -#define BTA_AV_COLL_INC_TMR 0x01 /* Timer is running for incoming L2C connection */ -#define BTA_AV_COLL_API_CALLED 0x02 /* API open was called while incoming timer is running */ - -/* type for AV stream control block */ -typedef struct { - const tBTA_AV_ACT *p_act_tbl; /* the action table for stream state machine */ - const tBTA_AV_CO_FUNCTS *p_cos; /* the associated callout functions */ - tSDP_DISCOVERY_DB *p_disc_db; /* pointer to discovery database */ - tBTA_AV_SEP seps[BTA_AV_MAX_SEPS]; - tAVDT_CFG *p_cap; /* buffer used for get capabilities */ - list_t *a2d_list; /* used for audio channels only */ - tBTA_AV_Q_INFO q_info; - tAVDT_SEP_INFO sep_info[BTA_AV_NUM_SEPS]; /* stream discovery results */ - tAVDT_CFG cfg; /* local SEP configuration */ - TIMER_LIST_ENT timer; /* delay timer for AVRC CT */ - BD_ADDR peer_addr; /* peer BD address */ - UINT16 l2c_cid; /* L2CAP channel ID */ - UINT16 stream_mtu; /* MTU of stream */ - UINT16 avdt_version; /* the avdt version of peer device */ - tBTA_SEC sec_mask; /* security mask */ - tBTA_AV_CODEC codec_type; /* codec type */ - UINT8 media_type; /* Media type */ - BOOLEAN cong; /* TRUE if AVDTP congested */ - tBTA_AV_STATUS open_status; /* open failure status */ - tBTA_AV_CHNL chnl; /* the channel: audio/video */ - tBTA_AV_HNDL hndl; /* the handle: ((hdi + 1)|chnl) */ - UINT16 cur_psc_mask; /* Protocol service capabilities mask for current connection */ - UINT8 avdt_handle; /* AVDTP handle */ - UINT8 hdi; /* the index to SCB[] */ - UINT8 num_seps; /* number of seps returned by stream discovery */ - UINT8 num_disc_snks; /* number of discovered snks */ - UINT8 num_disc_srcs; /* number of discovered srcs */ - UINT8 sep_info_idx; /* current index into sep_info */ - UINT8 sep_idx; /* current index into local seps[] */ - UINT8 rcfg_idx; /* reconfig requested index into sep_info */ - UINT8 state; /* state machine state */ - UINT8 avdt_label; /* AVDTP label */ - UINT8 app_id; /* application id */ - UINT8 num_recfg; /* number of reconfigure sent */ - UINT8 role; - UINT8 l2c_bufs; /* the number of buffers queued to L2CAP */ - UINT8 rc_handle; /* connected AVRCP handle */ - BOOLEAN use_rc; /* TRUE if AVRCP is allowed */ - BOOLEAN started; /* TRUE if stream started */ - UINT8 co_started; /* non-zero, if stream started from call-out perspective */ - BOOLEAN recfg_sup; /* TRUE if the first attempt to reconfigure the stream was successfull, else False if command fails */ - BOOLEAN suspend_sup; /* TRUE if Suspend stream is supported, else FALSE if suspend command fails */ - BOOLEAN deregistring; /* TRUE if deregistering */ - BOOLEAN sco_suspend; /* TRUE if SUSPEND is issued automatically for SCO */ - UINT8 coll_mask; /* Mask to check incoming and outgoing collision */ - tBTA_AV_API_OPEN open_api; /* Saved OPEN api message */ - UINT8 wait; /* set 0x1, when getting Caps as ACP, set 0x2, when started */ - UINT8 q_tag; /* identify the associated q_info union member */ - BOOLEAN no_rtp_hdr; /* TRUE if add no RTP header*/ - UINT8 disc_rsn; /* disconenction reason */ - UINT16 uuid_int; /*intended UUID of Initiator to connect to */ -} tBTA_AV_SCB; - -#define BTA_AV_RC_ROLE_MASK 0x10 -#define BTA_AV_RC_ROLE_INT 0x00 -#define BTA_AV_RC_ROLE_ACP 0x10 - -#define BTA_AV_RC_CONN_MASK 0x20 - -/* type for AV RCP control block */ -/* index to this control block is the rc handle */ -typedef struct { - UINT8 status; - UINT8 handle; - UINT8 shdl; /* stream handle (hdi + 1) */ - UINT8 lidx; /* (index+1) to LCB */ - tBTA_AV_FEAT peer_features; /* peer features mask */ -} tBTA_AV_RCB; -#define BTA_AV_NUM_RCB (BTA_AV_NUM_STRS + 2) - -enum { - BTA_AV_LCB_FREE, - BTA_AV_LCB_FIND -}; - -/* type for AV ACL Link control block */ -typedef struct { - BD_ADDR addr; /* peer BD address */ - UINT8 conn_msk; /* handle mask of connected stream handle */ - UINT8 lidx; /* index + 1 */ -} tBTA_AV_LCB; - -/* type for stream state machine action functions */ -typedef void (*tBTA_AV_SACT)(tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); - - -/* type for AV control block */ -typedef struct { - tBTA_AV_SCB *p_scb[BTA_AV_NUM_STRS]; /* stream control block */ - tSDP_DISCOVERY_DB *p_disc_db; /* pointer to discovery database */ - tBTA_AV_CBACK *p_cback; /* application callback function */ - tBTA_AV_RCB rcb[BTA_AV_NUM_RCB]; /* RCB control block */ - tBTA_AV_LCB lcb[BTA_AV_NUM_LINKS + 1]; /* link control block */ - TIMER_LIST_ENT sig_tmr; /* link timer */ - TIMER_LIST_ENT acp_sig_tmr; /* timer to monitor signalling when accepting */ - UINT32 sdp_a2d_handle; /* SDP record handle for audio src */ -#if (BTA_AV_SINK_INCLUDED == TRUE) - UINT32 sdp_a2d_snk_handle; /* SDP record handle for audio snk */ -#endif - UINT32 sdp_vdp_handle; /* SDP record handle for video src */ - tBTA_AV_FEAT features; /* features mask */ - tBTA_SEC sec_mask; /* security mask */ - tBTA_AV_HNDL handle; /* the handle for SDP activity */ - BOOLEAN disabling; /* TRUE if api disabled called */ - UINT8 disc; /* (hdi+1) or (rc_handle|BTA_AV_CHNL_MSK) if p_disc_db is in use */ - UINT8 state; /* state machine state */ - UINT8 conn_rc; /* handle mask of connected RCP channels */ - UINT8 conn_audio; /* handle mask of connected audio channels */ - UINT8 conn_video; /* handle mask of connected video channels */ - UINT8 conn_lcb; /* index mask of used LCBs */ - UINT8 audio_open_cnt; /* number of connected audio channels */ - UINT8 reg_audio; /* handle mask of registered audio channels */ - UINT8 reg_video; /* handle mask of registered video channels */ - UINT8 rc_acp_handle; - UINT8 rc_acp_idx; /* (index + 1) to RCB */ - UINT8 rs_idx; /* (index + 1) to SCB for the one waiting for RS on open */ - BOOLEAN sco_occupied; /* TRUE if SCO is being used or call is in progress */ - UINT8 audio_streams; /* handle mask of streaming audio channels */ - UINT8 video_streams; /* handle mask of streaming video channels */ -} tBTA_AV_CB; - - - -/***************************************************************************** -** Global data -*****************************************************************************/ - -/* control block declaration */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_AV_CB bta_av_cb; -#else -extern tBTA_AV_CB *bta_av_cb_ptr; -#define bta_av_cb (*bta_av_cb_ptr) -#endif - -/* config struct */ -extern tBTA_AV_CFG *p_bta_av_cfg; - -/* rc id config struct */ -extern UINT16 *p_bta_av_rc_id; -extern UINT16 *p_bta_av_rc_id_ac; - -extern const tBTA_AV_SACT bta_av_a2d_action[]; -// extern const tBTA_AV_CO_FUNCTS bta_av_a2d_cos; -extern const tBTA_AV_SACT bta_av_vdp_action[]; -extern tAVDT_CTRL_CBACK *const bta_av_dt_cback[]; -extern void bta_av_stream_data_cback(UINT8 handle, BT_HDR *p_pkt, UINT32 time_stamp, UINT8 m_pt); - -/***************************************************************************** -** Function prototypes -*****************************************************************************/ -/* utility functions */ -extern tBTA_AV_SCB *bta_av_hndl_to_scb(UINT16 handle); -extern BOOLEAN bta_av_chk_start(tBTA_AV_SCB *p_scb); -extern void bta_av_restore_switch (void); -extern UINT16 bta_av_chk_mtu(tBTA_AV_SCB *p_scb, UINT16 mtu); -extern void bta_av_conn_cback(UINT8 handle, BD_ADDR bd_addr, UINT8 event, tAVDT_CTRL *p_data); -extern UINT8 bta_av_rc_create(tBTA_AV_CB *p_cb, UINT8 role, UINT8 shdl, UINT8 lidx); -extern void bta_av_stream_chg(tBTA_AV_SCB *p_scb, BOOLEAN started); -extern BOOLEAN bta_av_is_scb_opening (tBTA_AV_SCB *p_scb); -extern BOOLEAN bta_av_is_scb_incoming (tBTA_AV_SCB *p_scb); -extern void bta_av_set_scb_sst_init (tBTA_AV_SCB *p_scb); -extern BOOLEAN bta_av_is_scb_init (tBTA_AV_SCB *p_scb); -extern void bta_av_set_scb_sst_incoming (tBTA_AV_SCB *p_scb); -extern tBTA_AV_LCB *bta_av_find_lcb(BD_ADDR addr, UINT8 op); - - -/* main functions */ -extern void bta_av_api_deregister(tBTA_AV_DATA *p_data); -extern void bta_av_dup_audio_buf(tBTA_AV_SCB *p_scb, BT_HDR *p_buf); -extern void bta_av_sm_execute(tBTA_AV_CB *p_cb, UINT16 event, tBTA_AV_DATA *p_data); -extern void bta_av_ssm_execute(tBTA_AV_SCB *p_scb, UINT16 event, tBTA_AV_DATA *p_data); -extern BOOLEAN bta_av_hdl_event(BT_HDR *p_msg); -#if (defined(BTA_AV_DEBUG) && BTA_AV_DEBUG == TRUE) -extern char *bta_av_evt_code(UINT16 evt_code); -#endif -extern BOOLEAN bta_av_switch_if_needed(tBTA_AV_SCB *p_scb); -extern BOOLEAN bta_av_link_role_ok(tBTA_AV_SCB *p_scb, UINT8 bits); -extern BOOLEAN bta_av_is_rcfg_sst(tBTA_AV_SCB *p_scb); - -/* nsm action functions */ -extern void bta_av_api_disconnect(tBTA_AV_DATA *p_data); -extern void bta_av_sig_chg(tBTA_AV_DATA *p_data); -extern void bta_av_sig_timer(tBTA_AV_DATA *p_data); -extern void bta_av_rc_disc_done(tBTA_AV_DATA *p_data); -extern void bta_av_rc_closed(tBTA_AV_DATA *p_data); -extern void bta_av_rc_disc(UINT8 disc); -extern void bta_av_conn_chg(tBTA_AV_DATA *p_data); -extern void bta_av_dereg_comp(tBTA_AV_DATA *p_data); - -/* sm action functions */ -extern void bta_av_disable (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_opened (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_remote_cmd (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_vendor_cmd (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_vendor_rsp (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_msg (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_close (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_meta_rsp (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_free_rsp (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); -extern void bta_av_rc_free_msg (tBTA_AV_CB *p_cb, tBTA_AV_DATA *p_data); - -extern tBTA_AV_RCB *bta_av_get_rcb_by_shdl(UINT8 shdl); -extern void bta_av_del_rc(tBTA_AV_RCB *p_rcb); - -/* ssm action functions */ -extern void bta_av_do_disc_a2d (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_cleanup (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_free_sdb (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_config_ind (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_disconnect_req (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_security_req (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_security_rsp (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_setconfig_rsp (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_str_opened (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_security_ind (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_security_cfm (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_do_close (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_connect_req (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_sdp_failed (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_disc_results (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_disc_res_as_acp (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_open_failed (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_getcap_results (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_setconfig_rej (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_discover_req (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_conn_failed (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_do_start (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_str_stopped (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_reconfig (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_data_path (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_start_ok (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_start_failed (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_str_closed (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_clr_cong (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_suspend_cfm (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_rcfg_str_ok (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_rcfg_failed (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_rcfg_connect (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_rcfg_discntd (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_suspend_cont (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_rcfg_cfm (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_rcfg_open (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_security_rej (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_open_rc (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_chk_2nd_start (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_save_caps (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_rej_conn (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_rej_conn (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_set_use_rc (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_cco_close (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_switch_role (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_role_res (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_delay_co (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_open_at_inc (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); - -/* ssm action functions - vdp specific */ -extern void bta_av_do_disc_vdp (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_vdp_str_opened (tBTA_AV_SCB *p_scb, tBTA_AV_DATA *p_data); -extern void bta_av_reg_vdp (tAVDT_CS *p_cs, char *p_service_name, void *p_data); - -#endif ///BTA_AV_INCLUDED == TRUE - -#endif /* BTA_AV_INT_H */ diff --git a/tools/sdk/include/bluedroid/bta_av_sbc.h b/tools/sdk/include/bluedroid/bta_av_sbc.h deleted file mode 100644 index 966ee61bbac..00000000000 --- a/tools/sdk/include/bluedroid/bta_av_sbc.h +++ /dev/null @@ -1,223 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2004-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface to utility functions for dealing with SBC data - * frames and codec capabilities. - * - ******************************************************************************/ -#ifndef BTA_AV_SBC_H -#define BTA_AV_SBC_H - -#if (BTA_AV_INCLUDED == TRUE) - -/***************************************************************************** -** constants -*****************************************************************************/ - -/* SBC packet header size */ -#define BTA_AV_SBC_HDR_SIZE A2D_SBC_MPL_HDR_LEN - -/******************************************************************************* -** -** Function bta_av_sbc_init_up_sample -** -** Description initialize the up sample -** -** src_sps: samples per second (source audio data) -** dst_sps: samples per second (converted audio data) -** bits: number of bits per pcm sample -** n_channels: number of channels (i.e. mono(1), stereo(2)...) -** -** Returns none -** -*******************************************************************************/ -extern void bta_av_sbc_init_up_sample (UINT32 src_sps, UINT32 dst_sps, - UINT16 bits, UINT16 n_channels); - -/******************************************************************************* -** -** Function bta_av_sbc_up_sample -** -** Description Given the source (p_src) audio data and -** source speed (src_sps, samples per second), -** This function converts it to audio data in the desired format -** -** p_src: the data buffer that holds the source audio data -** p_dst: the data buffer to hold the converted audio data -** src_samples: The number of source samples (number of bytes) -** dst_samples: The size of p_dst (number of bytes) -** -** Note: An AE reported an issue with this function. -** When called with bta_av_sbc_up_sample(src, uint8_array_dst..) -** the byte before uint8_array_dst may get overwritten. -** Using uint16_array_dst avoids the problem. -** This issue is related to endian-ness and is hard to resolve -** in a generic manner. -** **************** Please use uint16 array as dst. -** -** Returns The number of bytes used in p_dst -** The number of bytes used in p_src (in *p_ret) -** -*******************************************************************************/ -extern int bta_av_sbc_up_sample (void *p_src, void *p_dst, - UINT32 src_samples, UINT32 dst_samples, - UINT32 *p_ret); - -/******************************************************************************* -** -** Function bta_av_sbc_up_sample_16s (16bits-stereo) -** -** Description Given the source (p_src) audio data and -** source speed (src_sps, samples per second), -** This function converts it to audio data in the desired format -** -** p_src: the data buffer that holds the source audio data -** p_dst: the data buffer to hold the converted audio data -** src_samples: The number of source samples (in uint of 4 bytes) -** dst_samples: The size of p_dst (in uint of 4 bytes) -** -** Returns The number of bytes used in p_dst -** The number of bytes used in p_src (in *p_ret) -** -*******************************************************************************/ -extern int bta_av_sbc_up_sample_16s (void *p_src, void *p_dst, - UINT32 src_samples, UINT32 dst_samples, - UINT32 *p_ret); - -/******************************************************************************* -** -** Function bta_av_sbc_up_sample_16m (16bits-mono) -** -** Description Given the source (p_src) audio data and -** source speed (src_sps, samples per second), -** This function converts it to audio data in the desired format -** -** p_src: the data buffer that holds the source audio data -** p_dst: the data buffer to hold the converted audio data -** src_samples: The number of source samples (in uint of 2 bytes) -** dst_samples: The size of p_dst (in uint of 2 bytes) -** -** Returns The number of bytes used in p_dst -** The number of bytes used in p_src (in *p_ret) -** -*******************************************************************************/ -extern int bta_av_sbc_up_sample_16m (void *p_src, void *p_dst, - UINT32 src_samples, UINT32 dst_samples, - UINT32 *p_ret); - -/******************************************************************************* -** -** Function bta_av_sbc_up_sample_8s (8bits-stereo) -** -** Description Given the source (p_src) audio data and -** source speed (src_sps, samples per second), -** This function converts it to audio data in the desired format -** -** p_src: the data buffer that holds the source audio data -** p_dst: the data buffer to hold the converted audio data -** src_samples: The number of source samples (in uint of 2 bytes) -** dst_samples: The size of p_dst (in uint of 2 bytes) -** -** Returns The number of bytes used in p_dst -** The number of bytes used in p_src (in *p_ret) -** -*******************************************************************************/ -extern int bta_av_sbc_up_sample_8s (void *p_src, void *p_dst, - UINT32 src_samples, UINT32 dst_samples, - UINT32 *p_ret); - -/******************************************************************************* -** -** Function bta_av_sbc_up_sample_8m (8bits-mono) -** -** Description Given the source (p_src) audio data and -** source speed (src_sps, samples per second), -** This function converts it to audio data in the desired format -** -** p_src: the data buffer that holds the source audio data -** p_dst: the data buffer to hold the converted audio data -** src_samples: The number of source samples (number of bytes) -** dst_samples: The size of p_dst (number of bytes) -** -** Returns The number of bytes used in p_dst -** The number of bytes used in p_src (in *p_ret) -** -*******************************************************************************/ -extern int bta_av_sbc_up_sample_8m (void *p_src, void *p_dst, - UINT32 src_samples, UINT32 dst_samples, - UINT32 *p_ret); - -/******************************************************************************* -** -** Function bta_av_sbc_cfg_for_cap -** -** Description Determine the preferred SBC codec configuration for the -** given codec capabilities. The function is passed the -** preferred codec configuration and the peer codec -** capabilities for the stream. The function attempts to -** match the preferred capabilities with the configuration -** as best it can. The resulting codec configuration is -** returned in the same memory used for the capabilities. -** -** Returns 0 if ok, nonzero if error. -** Codec configuration in p_cap. -** -*******************************************************************************/ -extern UINT8 bta_av_sbc_cfg_for_cap(UINT8 *p_peer, tA2D_SBC_CIE *p_cap, tA2D_SBC_CIE *p_pref); - -/******************************************************************************* -** -** Function bta_av_sbc_cfg_in_cap -** -** Description This function checks whether an SBC codec configuration -** is allowable for the given codec capabilities. -** -** Returns 0 if ok, nonzero if error. -** -*******************************************************************************/ -extern UINT8 bta_av_sbc_cfg_in_cap(UINT8 *p_cfg, tA2D_SBC_CIE *p_cap); - -/******************************************************************************* -** -** Function bta_av_sbc_cfg_matches_cap -** -** Description This function checks whether an SBC codec configuration -** matched with capabilities. Here we check subset. -** -** Returns 0 if ok, nonzero if error. -** -*******************************************************************************/ -extern UINT8 bta_av_sbc_cfg_matches_cap(UINT8 *p_cfg, tA2D_SBC_CIE *p_cap); - -/******************************************************************************* -** -** Function bta_av_sbc_bld_hdr -** -** Description This function builds the packet header for MPF1. -** -** Returns void -** -*******************************************************************************/ -extern void bta_av_sbc_bld_hdr(BT_HDR *p_buf, UINT16 fr_per_pkt); - -#endif ///BTA_AV_INCLUDED == TRUE - -#endif /* BTA_AV_SBC_H */ - diff --git a/tools/sdk/include/bluedroid/bta_dm_ci.h b/tools/sdk/include/bluedroid/bta_dm_ci.h deleted file mode 100644 index 9f8a87437a2..00000000000 --- a/tools/sdk/include/bluedroid/bta_dm_ci.h +++ /dev/null @@ -1,80 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2006-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for device mananger call-in functions. - * - ******************************************************************************/ -#ifndef BTA_DM_CI_H -#define BTA_DM_CI_H - -#include "bta_api.h" - -/***************************************************************************** -** Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function bta_dm_ci_io_req -** -** Description This function must be called in response to function -** bta_dm_co_io_req(), if *p_oob_data is set to BTA_OOB_UNKNOWN -** by bta_dm_co_io_req(). -** -** Returns void -** -*******************************************************************************/ -extern void bta_dm_ci_io_req(BD_ADDR bd_addr, tBTA_IO_CAP io_cap, - tBTA_OOB_DATA oob_data, tBTA_AUTH_REQ auth_req); - -/******************************************************************************* -** -** Function bta_dm_ci_rmt_oob -** -** Description This function must be called in response to function -** bta_dm_co_rmt_oob() to provide the OOB data associated -** with the remote device. -** -** Returns void -** -*******************************************************************************/ -extern void bta_dm_ci_rmt_oob(BOOLEAN accept, BD_ADDR bd_addr, - BT_OCTET16 c, BT_OCTET16 r); -/******************************************************************************* -** -** Function bta_dm_sco_ci_data_ready -** -** Description This function sends an event to indicating that the phone -** has SCO data ready.. -** -** Returns void -** -*******************************************************************************/ -extern void bta_dm_sco_ci_data_ready(UINT16 event, UINT16 sco_handle); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/bluedroid/bta_dm_co.h b/tools/sdk/include/bluedroid/bta_dm_co.h deleted file mode 100644 index 2a80aefe86a..00000000000 --- a/tools/sdk/include/bluedroid/bta_dm_co.h +++ /dev/null @@ -1,282 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2006-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for device mananger callout functions. - * - ******************************************************************************/ -#ifndef BTA_DM_CO_H -#define BTA_DM_CO_H - -#include "bta_sys.h" - - -#ifndef BTA_SCO_OUT_PKT_SIZE -#define BTA_SCO_OUT_PKT_SIZE BTM_SCO_DATA_SIZE_MAX -#endif - -#define BTA_SCO_CODEC_PCM 0 /* used for regular SCO */ -#define BTA_SCO_CODEC_SBC 1 /* used for WBS */ -typedef UINT8 tBTA_SCO_CODEC_TYPE; - -#define BTA_DM_SCO_SAMP_RATE_8K 8000 -#define BTA_DM_SCO_SAMP_RATE_16K 16000 - -/* SCO codec information */ -typedef struct { - tBTA_SCO_CODEC_TYPE codec_type; -} tBTA_CODEC_INFO; - -#define BTA_DM_SCO_ROUTE_PCM BTM_SCO_ROUTE_PCM -#define BTA_DM_SCO_ROUTE_HCI BTM_SCO_ROUTE_HCI - -typedef tBTM_SCO_ROUTE_TYPE tBTA_DM_SCO_ROUTE_TYPE; - - -/***************************************************************************** -** Function Declarations -*****************************************************************************/ - -/******************************************************************************* -** -** Function bta_dm_co_io_req -** -** Description This callout function is executed by DM to get IO capabilities -** of the local device for the Simple Pairing process -** -** Parameters bd_addr - The peer device -** *p_io_cap - The local Input/Output capabilities -** *p_oob_data - TRUE, if OOB data is available for the peer device. -** *p_auth_req - TRUE, if MITM protection is required. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_dm_co_io_req(BD_ADDR bd_addr, tBTA_IO_CAP *p_io_cap, - tBTA_OOB_DATA *p_oob_data, tBTA_AUTH_REQ *p_auth_req, - BOOLEAN is_orig); - -/******************************************************************************* -** -** Function bta_dm_co_io_rsp -** -** Description This callout function is executed by DM to report IO capabilities -** of the peer device for the Simple Pairing process -** -** Parameters bd_addr - The peer device -** io_cap - The remote Input/Output capabilities -** oob_data - TRUE, if OOB data is available for the peer device. -** auth_req - TRUE, if MITM protection is required. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_dm_co_io_rsp(BD_ADDR bd_addr, tBTA_IO_CAP io_cap, - tBTA_OOB_DATA oob_data, tBTA_AUTH_REQ auth_req); - -/******************************************************************************* -** -** Function bta_dm_co_lk_upgrade -** -** Description This callout function is executed by DM to check if the -** platform wants allow link key upgrade -** -** Parameters bd_addr - The peer device -** *p_upgrade - TRUE, if link key upgrade is desired. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_dm_co_lk_upgrade(BD_ADDR bd_addr, BOOLEAN *p_upgrade ); - -/******************************************************************************* -** -** Function bta_dm_co_loc_oob -** -** Description This callout function is executed by DM to report the OOB -** data of the local device for the Simple Pairing process -** -** Parameters valid - TRUE, if the local OOB data is retrieved from LM -** c - Simple Pairing Hash C -** r - Simple Pairing Randomnizer R -** -** Returns void. -** -*******************************************************************************/ -extern void bta_dm_co_loc_oob(BOOLEAN valid, BT_OCTET16 c, BT_OCTET16 r); - -/******************************************************************************* -** -** Function bta_dm_co_rmt_oob -** -** Description This callout function is executed by DM to request the OOB -** data for the remote device for the Simple Pairing process -** -** Parameters bd_addr - The peer device -** -** Returns void. -** -*******************************************************************************/ -extern void bta_dm_co_rmt_oob(BD_ADDR bd_addr); - -/***************************************************************************** -** SCO over HCI Function Declarations -*****************************************************************************/ -/******************************************************************************* -** -** Function bta_dm_sco_co_init -** -** Description This function can be used by the phone to initialize audio -** codec or for other initialization purposes before SCO connection -** is opened. -** -** -** Returns Void. -** -*******************************************************************************/ -extern tBTA_DM_SCO_ROUTE_TYPE bta_dm_sco_co_init(UINT32 rx_bw, UINT32 tx_bw, - tBTA_CODEC_INFO *p_codec_info, UINT8 app_id); - - -/******************************************************************************* -** -** Function bta_dm_sco_co_open -** -** Description This function is executed when a SCO connection is open. -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_dm_sco_co_open(UINT16 handle, UINT8 pkt_size, UINT16 event); - -/******************************************************************************* -** -** Function bta_dm_sco_co_close -** -** Description This function is called when a SCO connection is closed -** -** -** Returns void -** -*******************************************************************************/ -extern void bta_dm_sco_co_close(void); - -/******************************************************************************* -** -** Function bta_dm_sco_co_out_data -** -** Description This function is called to send SCO data over HCI. -** -** Returns void -** -*******************************************************************************/ -extern void bta_dm_sco_co_out_data(BT_HDR **p_buf); - -/******************************************************************************* -** -** Function bta_dm_sco_co_in_data -** -** Description This function is called to send incoming SCO data to application. -** -** Returns void -** -*******************************************************************************/ -extern void bta_dm_sco_co_in_data(BT_HDR *p_buf, tBTM_SCO_DATA_FLAG status); - - - -/******************************************************************************* -** -** Function bta_dm_co_ble_io_req -** -** Description This callout function is executed by DM to get BLE IO capabilities -** before SMP pairing gets going. -** -** Parameters bd_addr - The peer device -** *p_io_cap - The local Input/Output capabilities -** *p_oob_data - TRUE, if OOB data is available for the peer device. -** *p_auth_req - Auth request setting (Bonding and MITM required or not) -** *p_max_key_size - max key size local device supported. -** *p_init_key - initiator keys. -** *p_resp_key - responder keys. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_dm_co_ble_io_req(BD_ADDR bd_addr, tBTA_IO_CAP *p_io_cap, - tBTA_OOB_DATA *p_oob_data, - tBTA_LE_AUTH_REQ *p_auth_req, - UINT8 *p_max_key_size, - tBTA_LE_KEY_TYPE *p_init_key, - tBTA_LE_KEY_TYPE *p_resp_key ); - - -/******************************************************************************* -** -** Function bta_dm_co_ble_local_key_reload -** -** Description This callout function is to load the local BLE keys if available -** on the device. -** -** Parameters none -** -** Returns void. -** -*******************************************************************************/ -extern void bta_dm_co_ble_load_local_keys (tBTA_DM_BLE_LOCAL_KEY_MASK *p_key_mask, BT_OCTET16 er, - tBTA_BLE_LOCAL_ID_KEYS *p_id_keys); - -// btla-specific ++ -/******************************************************************************* -** -** Function bta_dm_co_ble_io_req -** -** Description This callout function is executed by DM to get BLE IO capabilities -** before SMP pairing gets going. -** -** Parameters bd_addr - The peer device -** *p_io_cap - The local Input/Output capabilities -** *p_oob_data - TRUE, if OOB data is available for the peer device. -** *p_auth_req - Auth request setting (Bonding and MITM required or not) -** *p_max_key_size - max key size local device supported. -** *p_init_key - initiator keys. -** *p_resp_key - responder keys. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_dm_co_ble_io_req(BD_ADDR bd_addr, tBTA_IO_CAP *p_io_cap, - tBTA_OOB_DATA *p_oob_data, - tBTA_LE_AUTH_REQ *p_auth_req, - UINT8 *p_max_key_size, - tBTA_LE_KEY_TYPE *p_init_key, - tBTA_LE_KEY_TYPE *p_resp_key ); -// btla-specific -- - -extern void bta_dm_co_ble_set_io_cap(UINT8 ble_io_cap); - -extern void bta_dm_co_ble_set_auth_req(UINT8 ble_auth_req); - -extern void bta_dm_co_ble_set_init_key_req(UINT8 init_key); - -extern void bta_dm_co_ble_set_rsp_key_req(UINT8 rsp_key); - -extern void bta_dm_co_ble_set_max_key_size(UINT8 ble_key_size); -#endif diff --git a/tools/sdk/include/bluedroid/bta_dm_int.h b/tools/sdk/include/bluedroid/bta_dm_int.h deleted file mode 100644 index a95bb676ece..00000000000 --- a/tools/sdk/include/bluedroid/bta_dm_int.h +++ /dev/null @@ -1,1257 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the private interface file for the BTA device manager. - * - ******************************************************************************/ -#ifndef BTA_DM_INT_H -#define BTA_DM_INT_H - -#include "bt_target.h" - -#if (BLE_INCLUDED == TRUE && (defined BTA_GATT_INCLUDED) && (BTA_GATT_INCLUDED == TRUE)) -#include "bta_gatt_api.h" -#endif - - - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ - - -#define BTA_COPY_DEVICE_CLASS(coddst, codsrc) {((UINT8 *)(coddst))[0] = ((UINT8 *)(codsrc))[0]; \ - ((UINT8 *)(coddst))[1] = ((UINT8 *)(codsrc))[1]; \ - ((UINT8 *)(coddst))[2] = ((UINT8 *)(codsrc))[2];} - - -#define BTA_DM_MSG_LEN 50 - -#define BTA_SERVICE_ID_TO_SERVICE_MASK(id) (1 << (id)) - -/* DM events */ -enum { - /* device manager local device API events */ - BTA_DM_API_ENABLE_EVT = BTA_SYS_EVT_START(BTA_ID_DM), - BTA_DM_API_DISABLE_EVT, - BTA_DM_API_SET_NAME_EVT, - BTA_DM_API_SET_VISIBILITY_EVT, - - BTA_DM_ACL_CHANGE_EVT, - BTA_DM_API_ADD_DEVICE_EVT, - BTA_DM_API_REMOVE_ACL_EVT, -#if (SMP_INCLUDED == TRUE) - /* security API events */ - BTA_DM_API_BOND_EVT, - BTA_DM_API_BOND_CANCEL_EVT, - BTA_DM_API_PIN_REPLY_EVT, -#endif ///SMP_INCLUDED == TRUE -#if (BTM_SSR_INCLUDED == TRUE) - /* power manger events */ - BTA_DM_PM_BTM_STATUS_EVT, - BTA_DM_PM_TIMER_EVT, -#endif ///BTM_SSR_INCLUDED == TRUE -#if (SMP_INCLUDED == TRUE) - /* simple pairing events */ - BTA_DM_API_CONFIRM_EVT, - - BTA_DM_API_SET_ENCRYPTION_EVT, -#endif ///SMP_INCLUDED == TRUE -#if (BTM_OOB_INCLUDED == TRUE && SMP_INCLUDED == TRUE) - BTA_DM_API_LOC_OOB_EVT, - BTA_DM_CI_IO_REQ_EVT, - BTA_DM_CI_RMT_OOB_EVT, -#endif /* BTM_OOB_INCLUDED */ - - -#if BLE_INCLUDED == TRUE -#if SMP_INCLUDED == TRUE - BTA_DM_API_ADD_BLEKEY_EVT, - BTA_DM_API_ADD_BLEDEVICE_EVT, - BTA_DM_API_BLE_PASSKEY_REPLY_EVT, - BTA_DM_API_BLE_CONFIRM_REPLY_EVT, - BTA_DM_API_BLE_SEC_GRANT_EVT, -#endif ///SMP_INCLUDED == TRUE - BTA_DM_API_BLE_SET_BG_CONN_TYPE, - BTA_DM_API_BLE_CONN_PARAM_EVT, - BTA_DM_API_BLE_CONN_SCAN_PARAM_EVT, - BTA_DM_API_BLE_SCAN_PARAM_EVT, - /*******This event added by Yulong at 2016/10/25 to - support the scan filter setting for the APP******/ - BTA_DM_API_BLE_SCAN_FIL_PARAM_EVT, - BTA_DM_API_BLE_OBSERVE_EVT, - BTA_DM_API_BLE_SCAN_EVT, - BTA_DM_API_UPDATE_CONN_PARAM_EVT, - /*******This event added by Yulong at 2016/9/9 to - support the random address setting for the APP******/ - BTA_DM_API_SET_RAND_ADDR_EVT, - /*******This event added by Yulong at 2016/10/19 to - support stop the ble advertising setting by the APP******/ - BTA_DM_API_BLE_STOP_ADV_EVT, -#if BLE_PRIVACY_SPT == TRUE - BTA_DM_API_LOCAL_PRIVACY_EVT, -#endif - BTA_DM_API_BLE_ADV_PARAM_EVT, - - /*******This event added by Yulong at 2016/10/20 to - support setting the ble advertising param by the APP******/ - BTA_DM_API_BLE_ADV_PARAM_All_EVT, - BTA_DM_API_BLE_SET_ADV_CONFIG_EVT, - /* Add for set raw advertising data */ - BTA_DM_API_BLE_SET_ADV_CONFIG_RAW_EVT, - BTA_DM_API_BLE_SET_SCAN_RSP_EVT, - /* Add for set raw scan response data */ - BTA_DM_API_BLE_SET_SCAN_RSP_RAW_EVT, - BTA_DM_API_BLE_BROADCAST_EVT, - BTA_DM_API_SET_DATA_LENGTH_EVT, - -#if BLE_ANDROID_CONTROLLER_SCAN_FILTER == TRUE - BTA_DM_API_CFG_FILTER_COND_EVT, - BTA_DM_API_SCAN_FILTER_SETUP_EVT, - BTA_DM_API_SCAN_FILTER_ENABLE_EVT, -#endif - BTA_DM_API_BLE_MULTI_ADV_ENB_EVT, - BTA_DM_API_BLE_MULTI_ADV_PARAM_UPD_EVT, - BTA_DM_API_BLE_MULTI_ADV_DATA_EVT, - BTA_DM_API_BLE_MULTI_ADV_DISABLE_EVT, - BTA_DM_API_BLE_SETUP_STORAGE_EVT, - BTA_DM_API_BLE_ENABLE_BATCH_SCAN_EVT, - BTA_DM_API_BLE_DISABLE_BATCH_SCAN_EVT, - BTA_DM_API_BLE_READ_SCAN_REPORTS_EVT, - BTA_DM_API_BLE_TRACK_ADVERTISER_EVT, - BTA_DM_API_BLE_ENERGY_INFO_EVT, - BTA_DM_API_BLE_DISCONNECT_EVT, - -#endif - - BTA_DM_API_ENABLE_TEST_MODE_EVT, - BTA_DM_API_DISABLE_TEST_MODE_EVT, - BTA_DM_API_EXECUTE_CBACK_EVT, - BTA_DM_API_REMOVE_ALL_ACL_EVT, - BTA_DM_API_REMOVE_DEVICE_EVT, - BTA_DM_API_UPDATE_WHITE_LIST_EVT, - BTA_DM_API_BLE_READ_ADV_TX_POWER_EVT, - BTA_DM_API_BLE_READ_RSSI_EVT, - BTA_DM_MAX_EVT -}; - - -/* DM search events */ -enum { - /* DM search API events */ - BTA_DM_API_SEARCH_EVT = BTA_SYS_EVT_START(BTA_ID_DM_SEARCH), - BTA_DM_API_SEARCH_CANCEL_EVT, - BTA_DM_API_DISCOVER_EVT, - BTA_DM_INQUIRY_CMPL_EVT, - BTA_DM_REMT_NAME_EVT, - BTA_DM_SDP_RESULT_EVT, - BTA_DM_SEARCH_CMPL_EVT, - BTA_DM_DISCOVERY_RESULT_EVT, - BTA_DM_API_DI_DISCOVER_EVT, - BTA_DM_DISC_CLOSE_TOUT_EVT, -}; - -/* data type for BTA_DM_API_ENABLE_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_DM_SEC_CBACK *p_sec_cback; -} tBTA_DM_API_ENABLE; - -/* data type for BTA_DM_API_SET_NAME_EVT */ -typedef struct { - BT_HDR hdr; - BD_NAME name; /* max 248 bytes name, plus must be Null terminated */ -} tBTA_DM_API_SET_NAME; - -typedef struct { - BT_HDR hdr; - BOOLEAN add_remove; - BD_ADDR remote_addr; - tBTA_ADD_WHITELIST_CBACK *add_wl_cb; -}tBTA_DM_API_UPDATE_WHITE_LIST; - -typedef struct { - BT_HDR hdr; - tBTA_CMPL_CB *read_tx_power_cb; -}tBTA_DM_API_READ_ADV_TX_POWER; - -typedef struct { - BT_HDR hdr; - BD_ADDR remote_addr; - tBTA_CMPL_CB *read_rssi_cb; -}tBTA_DM_API_READ_RSSI; - -/* data type for BTA_DM_API_SET_VISIBILITY_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_DM_DISC disc_mode; - tBTA_DM_CONN conn_mode; - UINT8 pair_mode; - UINT8 conn_paired_only; -} tBTA_DM_API_SET_VISIBILITY; - -enum { - BTA_DM_RS_NONE, /* straight API call */ - BTA_DM_RS_OK, /* the role switch result - successful */ - BTA_DM_RS_FAIL /* the role switch result - failed */ -}; -typedef UINT8 tBTA_DM_RS_RES; - -/* data type for BTA_DM_API_SEARCH_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_DM_INQ inq_params; - tBTA_SERVICE_MASK services; - tBTA_DM_SEARCH_CBACK *p_cback; - tBTA_DM_RS_RES rs_res; -#if BLE_INCLUDED == TRUE && BTA_GATT_INCLUDED == TRUE - UINT8 num_uuid; - tBT_UUID *p_uuid; -#endif -} tBTA_DM_API_SEARCH; - -#if (SDP_INCLUDED == TRUE) -/* data type for BTA_DM_API_DISCOVER_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tBTA_SERVICE_MASK services; - tBTA_DM_SEARCH_CBACK *p_cback; - BOOLEAN sdp_search; - tBTA_TRANSPORT transport; -#if BLE_INCLUDED == TRUE && BTA_GATT_INCLUDED == TRUE - UINT8 num_uuid; - tBT_UUID *p_uuid; -#endif - tSDP_UUID uuid; -} tBTA_DM_API_DISCOVER; -#endif ///SDP_INCLUDED == TRUE - -/* data type for BTA_DM_API_DI_DISC_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; -#if (SDP_INCLUDED == TRUE) - tBTA_DISCOVERY_DB *p_sdp_db; -#endif ///SDP_INCLUDED == TRUE - UINT32 len; - tBTA_DM_SEARCH_CBACK *p_cback; -} tBTA_DM_API_DI_DISC; - -/* data type for BTA_DM_API_BOND_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tBTA_TRANSPORT transport; -} tBTA_DM_API_BOND; - -/* data type for BTA_DM_API_BOND_CANCEL_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tBTA_TRANSPORT transport; -} tBTA_DM_API_BOND_CANCEL; - -/* data type for BTA_DM_API_PIN_REPLY_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - BOOLEAN accept; - UINT8 pin_len; - UINT8 p_pin[PIN_CODE_LEN]; -} tBTA_DM_API_PIN_REPLY; - -/* data type for BTA_DM_API_LOC_OOB_EVT */ -typedef struct { - BT_HDR hdr; -} tBTA_DM_API_LOC_OOB; - -/* data type for BTA_DM_API_CONFIRM_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - BOOLEAN accept; -} tBTA_DM_API_CONFIRM; - -/* data type for BTA_DM_CI_IO_REQ_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tBTA_IO_CAP io_cap; - tBTA_OOB_DATA oob_data; - tBTA_AUTH_REQ auth_req; -} tBTA_DM_CI_IO_REQ; - -/* data type for BTA_DM_CI_RMT_OOB_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - BT_OCTET16 c; - BT_OCTET16 r; - BOOLEAN accept; -} tBTA_DM_CI_RMT_OOB; - -/* data type for BTA_DM_REMT_NAME_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_DM_SEARCH result; -} tBTA_DM_REM_NAME; - -/* data type for tBTA_DM_DISC_RESULT */ -typedef struct { - BT_HDR hdr; - tBTA_DM_SEARCH result; -} tBTA_DM_DISC_RESULT; - - -/* data type for BTA_DM_INQUIRY_CMPL_EVT */ -typedef struct { - BT_HDR hdr; - UINT8 num; -} tBTA_DM_INQUIRY_CMPL; - -/* data type for BTA_DM_SDP_RESULT_EVT */ -typedef struct { - BT_HDR hdr; - UINT16 sdp_result; -} tBTA_DM_SDP_RESULT; - -/* data type for BTA_DM_ACL_CHANGE_EVT */ -typedef struct { - BT_HDR hdr; - tBTM_BL_EVENT event; - UINT8 busy_level; - UINT8 busy_level_flags; - BOOLEAN is_new; - UINT8 new_role; - BD_ADDR bd_addr; - UINT8 hci_status; -#if BLE_INCLUDED == TRUE - UINT16 handle; - tBT_TRANSPORT transport; -#endif -} tBTA_DM_ACL_CHANGE; - -/* data type for BTA_DM_PM_BTM_STATUS_EVT */ -typedef struct { - - BT_HDR hdr; - BD_ADDR bd_addr; - tBTM_PM_STATUS status; - UINT16 value; - UINT8 hci_status; - -} tBTA_DM_PM_BTM_STATUS; - -/* data type for BTA_DM_PM_TIMER_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tBTA_DM_PM_ACTION pm_request; -} tBTA_DM_PM_TIMER; - - -/* data type for BTA_DM_API_ADD_DEVICE_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - DEV_CLASS dc; - LINK_KEY link_key; - tBTA_SERVICE_MASK tm; - BOOLEAN is_trusted; - UINT8 key_type; - tBTA_IO_CAP io_cap; - BOOLEAN link_key_known; - BOOLEAN dc_known; - BD_NAME bd_name; - UINT8 features[BTA_FEATURE_BYTES_PER_PAGE * (BTA_EXT_FEATURES_PAGE_MAX + 1)]; - UINT8 pin_length; -} tBTA_DM_API_ADD_DEVICE; - -/* data type for BTA_DM_API_REMOVE_ACL_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; -} tBTA_DM_API_REMOVE_DEVICE; - -/* data type for BTA_DM_API_EXECUTE_CBACK_EVT */ -typedef struct { - BT_HDR hdr; - void *p_param; - tBTA_DM_EXEC_CBACK *p_exec_cback; -} tBTA_DM_API_EXECUTE_CBACK; - -/* data type for tBTA_DM_API_SET_ENCRYPTION */ -typedef struct { - BT_HDR hdr; - tBTA_TRANSPORT transport; - tBTA_DM_ENCRYPT_CBACK *p_callback; - tBTA_DM_BLE_SEC_ACT sec_act; - BD_ADDR bd_addr; -} tBTA_DM_API_SET_ENCRYPTION; - -#if BLE_INCLUDED == TRUE -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tBTA_LE_KEY_VALUE blekey; - tBTA_LE_KEY_TYPE key_type; - -} tBTA_DM_API_ADD_BLEKEY; - -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tBT_DEVICE_TYPE dev_type ; - tBLE_ADDR_TYPE addr_type; - -} tBTA_DM_API_ADD_BLE_DEVICE; - -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - BOOLEAN accept; - UINT32 passkey; -} tBTA_DM_API_PASSKEY_REPLY; - -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tBTA_DM_BLE_SEC_GRANT res; -} tBTA_DM_API_BLE_SEC_GRANT; - - -typedef struct { - BT_HDR hdr; - tBTA_DM_BLE_CONN_TYPE bg_conn_type; - tBTA_DM_BLE_SEL_CBACK *p_select_cback; -} tBTA_DM_API_BLE_SET_BG_CONN_TYPE; - -/* set prefered BLE connection parameters for a device */ -typedef struct { - BT_HDR hdr; - BD_ADDR peer_bda; - UINT16 conn_int_min; - UINT16 conn_int_max; - UINT16 supervision_tout; - UINT16 slave_latency; - -} tBTA_DM_API_BLE_CONN_PARAMS; - -typedef struct { - BT_HDR hdr; - BD_ADDR peer_bda; - BOOLEAN privacy_enable; - -} tBTA_DM_API_ENABLE_PRIVACY; - -typedef struct { - BT_HDR hdr; - BOOLEAN privacy_enable; - tBTA_SET_LOCAL_PRIVACY_CBACK *set_local_privacy_cback; -} tBTA_DM_API_LOCAL_PRIVACY; - -/* set scan parameter for BLE connections */ -typedef struct { - BT_HDR hdr; - tBTA_GATTC_IF client_if; - UINT32 scan_int; - UINT32 scan_window; - tBLE_SCAN_MODE scan_mode; - tBLE_SCAN_PARAM_SETUP_CBACK scan_param_setup_cback; -} tBTA_DM_API_BLE_SCAN_PARAMS; - -typedef struct { - BT_HDR hdr; - tBTA_GATTC_IF client_if; - UINT32 scan_int; - UINT32 scan_window; - tBLE_SCAN_MODE scan_mode; - UINT8 addr_type_own; - UINT8 scan_filter_policy; - tBLE_SCAN_PARAM_SETUP_CBACK scan_param_setup_cback; -} tBTA_DM_API_BLE_SCAN_FILTER_PARAMS; - - -/* set scan parameter for BLE connections */ -typedef struct { - BT_HDR hdr; - UINT16 scan_int; - UINT16 scan_window; -} tBTA_DM_API_BLE_CONN_SCAN_PARAMS; - -/* Data type for start/stop observe */ -typedef struct { - BT_HDR hdr; - BOOLEAN start; - UINT32 duration; - tBTA_DM_SEARCH_CBACK *p_cback; - tBTA_START_STOP_SCAN_CMPL_CBACK *p_start_scan_cback; - tBTA_START_STOP_SCAN_CMPL_CBACK *p_stop_scan_cback; - tBTA_START_STOP_ADV_CMPL_CBACK *p_stop_adv_cback; -} tBTA_DM_API_BLE_OBSERVE; - -/* Data type for start/stop scan */ -typedef struct { - BT_HDR hdr; - BOOLEAN start; - UINT32 duration; - tBTA_DM_SEARCH_CBACK *p_cback; - tBTA_START_STOP_SCAN_CMPL_CBACK *p_start_scan_cback; - tBTA_START_STOP_SCAN_CMPL_CBACK *p_stop_scan_cback; - tBTA_START_STOP_ADV_CMPL_CBACK *p_stop_adv_cback; -} tBTA_DM_API_BLE_SCAN; - -typedef struct { - BT_HDR hdr; - BD_ADDR remote_bda; - UINT16 tx_data_length; - tBTA_SET_PKT_DATA_LENGTH_CBACK *p_set_pkt_data_cback; -} tBTA_DM_API_BLE_SET_DATA_LENGTH; - -/* set the address for BLE device - this type added by Yulong at 2016/9/9*/ -typedef struct { - BT_HDR hdr; - tBLE_ADDR_TYPE addr_type; - BD_ADDR address; - tBTA_SET_RAND_ADDR_CBACK *p_set_rand_addr_cback; -} tBTA_DM_APT_SET_DEV_ADDR; - -/* set adv parameter for BLE advertising */ -typedef struct { - BT_HDR hdr; - UINT16 adv_int_min; - UINT16 adv_int_max; - tBLE_BD_ADDR *p_dir_bda; -} tBTA_DM_API_BLE_ADV_PARAMS; - -/* set adv parameter for BLE advertising */ -typedef struct { - BT_HDR hdr; - UINT16 adv_int_min; - UINT16 adv_int_max; - UINT8 adv_type; - tBLE_ADDR_TYPE addr_type_own; - tBTM_BLE_ADV_CHNL_MAP channel_map; - tBTM_BLE_AFP adv_filter_policy; - tBLE_BD_ADDR *p_dir_bda; - tBTA_START_ADV_CMPL_CBACK *p_start_adv_cback; -} tBTA_DM_API_BLE_ADV_PARAMS_ALL; - - -typedef struct { - BT_HDR hdr; - BOOLEAN enable; - -} tBTA_DM_API_BLE_FEATURE; - -/* multi adv data structure */ -typedef struct { - BT_HDR hdr; - tBTA_BLE_MULTI_ADV_CBACK *p_cback; - void *p_ref; - tBTA_BLE_ADV_PARAMS *p_params; -} tBTA_DM_API_BLE_MULTI_ADV_ENB; - -typedef struct { - BT_HDR hdr; - UINT8 inst_id; - tBTA_BLE_ADV_PARAMS *p_params; -} tBTA_DM_API_BLE_MULTI_ADV_PARAM; - -typedef struct { - BT_HDR hdr; - UINT8 inst_id; - BOOLEAN is_scan_rsp; - tBTA_BLE_AD_MASK data_mask; - tBTA_BLE_ADV_DATA *p_data; -} tBTA_DM_API_BLE_MULTI_ADV_DATA; - -typedef struct { - BT_HDR hdr; - UINT8 inst_id; -} tBTA_DM_API_BLE_MULTI_ADV_DISABLE; - -typedef struct { - BT_HDR hdr; - UINT32 data_mask; - tBTA_BLE_ADV_DATA *p_adv_cfg; - tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback; -} tBTA_DM_API_SET_ADV_CONFIG; - -/* raw scan response and raw advertising data use - the same structure */ -typedef struct { - BT_HDR hdr; - UINT8 *p_raw_adv; - UINT32 raw_adv_len; - tBTA_SET_ADV_DATA_CMPL_CBACK *p_adv_data_cback; -} tBTA_DM_API_SET_ADV_CONFIG_RAW; - -typedef struct { - BT_HDR hdr; - UINT8 batch_scan_full_max; - UINT8 batch_scan_trunc_max; - UINT8 batch_scan_notify_threshold; - tBTA_BLE_SCAN_SETUP_CBACK *p_setup_cback; - tBTA_BLE_SCAN_THRESHOLD_CBACK *p_thres_cback; - tBTA_BLE_SCAN_REP_CBACK *p_read_rep_cback; - tBTA_DM_BLE_REF_VALUE ref_value; -} tBTA_DM_API_SET_STORAGE_CONFIG; - -typedef struct { - BT_HDR hdr; - tBTA_BLE_BATCH_SCAN_MODE scan_mode; - UINT32 scan_int; - UINT32 scan_window; - tBTA_BLE_DISCARD_RULE discard_rule; - tBLE_ADDR_TYPE addr_type; - tBTA_DM_BLE_REF_VALUE ref_value; -} tBTA_DM_API_ENABLE_SCAN; - -typedef struct { - BT_HDR hdr; - tBTA_DM_BLE_REF_VALUE ref_value; -} tBTA_DM_API_DISABLE_SCAN; - -typedef struct { - BT_HDR hdr; - tBTA_BLE_BATCH_SCAN_MODE scan_type; - tBTA_DM_BLE_REF_VALUE ref_value; -} tBTA_DM_API_READ_SCAN_REPORTS; - -typedef struct { - BT_HDR hdr; - tBTA_DM_BLE_REF_VALUE ref_value; - tBTA_BLE_TRACK_ADV_CBACK *p_track_adv_cback; -} tBTA_DM_API_TRACK_ADVERTISER; - -typedef struct { - BT_HDR hdr; - tBTA_BLE_ENERGY_INFO_CBACK *p_energy_info_cback; -} tBTA_DM_API_ENERGY_INFO; - -typedef struct { - BT_HDR hdr; - BD_ADDR remote_bda; -} tBTA_DM_API_BLE_DISCONNECT; - -#endif /* BLE_INCLUDED */ - -/* data type for BTA_DM_API_REMOVE_ACL_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - BOOLEAN remove_dev; - tBTA_TRANSPORT transport; - -} tBTA_DM_API_REMOVE_ACL; - -/* data type for BTA_DM_API_REMOVE_ALL_ACL_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_DM_LINK_TYPE link_type; - -} tBTA_DM_API_REMOVE_ALL_ACL; -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - UINT16 min_int; - UINT16 max_int; - UINT16 latency; - UINT16 timeout; -} tBTA_DM_API_UPDATE_CONN_PARAM; - -#if BLE_ANDROID_CONTROLLER_SCAN_FILTER == TRUE -typedef struct { - BT_HDR hdr; - tBTA_DM_BLE_SCAN_COND_OP action; - tBTA_DM_BLE_PF_COND_TYPE cond_type; - tBTA_DM_BLE_PF_FILT_INDEX filt_index; - tBTA_DM_BLE_PF_COND_PARAM *p_cond_param; - tBTA_DM_BLE_PF_CFG_CBACK *p_filt_cfg_cback; - tBTA_DM_BLE_REF_VALUE ref_value; -} tBTA_DM_API_CFG_FILTER_COND; - -typedef struct { - BT_HDR hdr; - UINT8 action; - tBTA_DM_BLE_PF_STATUS_CBACK *p_filt_status_cback; - tBTA_DM_BLE_REF_VALUE ref_value; -} tBTA_DM_API_ENABLE_SCAN_FILTER; - -typedef struct { - BT_HDR hdr; - UINT8 action; - tBTA_DM_BLE_PF_FILT_INDEX filt_index; - tBTA_DM_BLE_PF_FILT_PARAMS filt_params; - tBLE_BD_ADDR *p_target; - tBTA_DM_BLE_PF_PARAM_CBACK *p_filt_param_cback; - tBTA_DM_BLE_REF_VALUE ref_value; -} tBTA_DM_API_SCAN_FILTER_PARAM_SETUP; -#endif - -/* union of all data types */ -typedef union { - /* event buffer header */ - BT_HDR hdr; - tBTA_DM_API_ENABLE enable; - - tBTA_DM_API_SET_NAME set_name; - - tBTA_DM_API_UPDATE_WHITE_LIST white_list; - tBTA_DM_API_READ_ADV_TX_POWER read_tx_power; - tBTA_DM_API_READ_RSSI rssi; - tBTA_DM_API_SET_VISIBILITY set_visibility; - - tBTA_DM_API_ADD_DEVICE add_dev; - - tBTA_DM_API_REMOVE_DEVICE remove_dev; - - tBTA_DM_API_SEARCH search; -#if (SDP_INCLUDED == TRUE) - tBTA_DM_API_DISCOVER discover; -#endif ///SDP_INCLUDED == TRUE - tBTA_DM_API_BOND bond; - - tBTA_DM_API_BOND_CANCEL bond_cancel; - - tBTA_DM_API_PIN_REPLY pin_reply; - - tBTA_DM_API_LOC_OOB loc_oob; - tBTA_DM_API_CONFIRM confirm; - tBTA_DM_CI_IO_REQ ci_io_req; - tBTA_DM_CI_RMT_OOB ci_rmt_oob; - - tBTA_DM_REM_NAME rem_name; - - tBTA_DM_DISC_RESULT disc_result; - - tBTA_DM_INQUIRY_CMPL inq_cmpl; - - tBTA_DM_SDP_RESULT sdp_event; - - tBTA_DM_ACL_CHANGE acl_change; - - tBTA_DM_PM_BTM_STATUS pm_status; - - tBTA_DM_PM_TIMER pm_timer; - - tBTA_DM_API_DI_DISC di_disc; - - tBTA_DM_API_EXECUTE_CBACK exec_cback; - - tBTA_DM_API_SET_ENCRYPTION set_encryption; - -#if BLE_INCLUDED == TRUE - tBTA_DM_API_ADD_BLEKEY add_ble_key; - tBTA_DM_API_ADD_BLE_DEVICE add_ble_device; - tBTA_DM_API_PASSKEY_REPLY ble_passkey_reply; - tBTA_DM_API_BLE_SEC_GRANT ble_sec_grant; - tBTA_DM_API_BLE_SET_BG_CONN_TYPE ble_set_bd_conn_type; - tBTA_DM_API_BLE_CONN_PARAMS ble_set_conn_params; - tBTA_DM_API_BLE_CONN_SCAN_PARAMS ble_set_conn_scan_params; - tBTA_DM_API_BLE_SCAN_PARAMS ble_set_scan_params; - tBTA_DM_API_BLE_SCAN_FILTER_PARAMS ble_set_scan_fil_params; - tBTA_DM_API_BLE_OBSERVE ble_observe; - tBTA_DM_API_BLE_SCAN ble_scan; - tBTA_DM_API_ENABLE_PRIVACY ble_remote_privacy; - tBTA_DM_API_LOCAL_PRIVACY ble_local_privacy; - tBTA_DM_API_BLE_ADV_PARAMS ble_set_adv_params; - tBTA_DM_API_BLE_ADV_PARAMS_ALL ble_set_adv_params_all; - tBTA_DM_API_SET_ADV_CONFIG ble_set_adv_data; - tBTA_DM_API_SET_ADV_CONFIG_RAW ble_set_adv_data_raw; -#if BLE_ANDROID_CONTROLLER_SCAN_FILTER == TRUE - tBTA_DM_API_SCAN_FILTER_PARAM_SETUP ble_scan_filt_param_setup; - tBTA_DM_API_CFG_FILTER_COND ble_cfg_filter_cond; - tBTA_DM_API_ENABLE_SCAN_FILTER ble_enable_scan_filt; -#endif - tBTA_DM_API_UPDATE_CONN_PARAM ble_update_conn_params; - tBTA_DM_API_BLE_SET_DATA_LENGTH ble_set_data_length; - tBTA_DM_APT_SET_DEV_ADDR set_addr; - tBTA_DM_API_BLE_MULTI_ADV_ENB ble_multi_adv_enb; - tBTA_DM_API_BLE_MULTI_ADV_PARAM ble_multi_adv_param; - tBTA_DM_API_BLE_MULTI_ADV_DATA ble_multi_adv_data; - tBTA_DM_API_BLE_MULTI_ADV_DISABLE ble_multi_adv_disable; - - tBTA_DM_API_SET_STORAGE_CONFIG ble_set_storage; - tBTA_DM_API_ENABLE_SCAN ble_enable_scan; - tBTA_DM_API_READ_SCAN_REPORTS ble_read_reports; - tBTA_DM_API_DISABLE_SCAN ble_disable_scan; - tBTA_DM_API_TRACK_ADVERTISER ble_track_advert; - tBTA_DM_API_ENERGY_INFO ble_energy_info; - tBTA_DM_API_BLE_DISCONNECT ble_disconnect; -#endif - - tBTA_DM_API_REMOVE_ACL remove_acl; - tBTA_DM_API_REMOVE_ALL_ACL remove_all_acl; - -} tBTA_DM_MSG; - - -#define BTA_DM_NUM_PEER_DEVICE 7 - -#define BTA_DM_NOT_CONNECTED 0 -#define BTA_DM_CONNECTED 1 -#define BTA_DM_UNPAIRING 2 -typedef UINT8 tBTA_DM_CONN_STATE; - - -#define BTA_DM_DI_NONE 0x00 /* nothing special */ -#define BTA_DM_DI_USE_SSR 0x10 /* set this bit if ssr is supported for this link */ -#define BTA_DM_DI_AV_ACTIVE 0x20 /* set this bit if AV is active for this link */ -#define BTA_DM_DI_SET_SNIFF 0x01 /* set this bit if call BTM_SetPowerMode(sniff) */ -#define BTA_DM_DI_INT_SNIFF 0x02 /* set this bit if call BTM_SetPowerMode(sniff) & enter sniff mode */ -#define BTA_DM_DI_ACP_SNIFF 0x04 /* set this bit if peer init sniff */ -typedef UINT8 tBTA_DM_DEV_INFO; - -/* set power mode request type */ -#define BTA_DM_PM_RESTART 1 -#define BTA_DM_PM_NEW_REQ 2 -#define BTA_DM_PM_EXECUTE 3 -typedef UINT8 tBTA_DM_PM_REQ; - -typedef struct { - BD_ADDR peer_bdaddr; - UINT16 link_policy; - tBTA_DM_CONN_STATE conn_state; - tBTA_PREF_ROLES pref_role; - BOOLEAN in_use; - tBTA_DM_DEV_INFO info; - tBTA_DM_ENCRYPT_CBACK *p_encrypt_cback; -#if (BTM_SSR_INCLUDED == TRUE) - tBTM_PM_STATUS prev_low; /* previous low power mode used */ -#endif - tBTA_DM_PM_ACTION pm_mode_attempted; - tBTA_DM_PM_ACTION pm_mode_failed; - BOOLEAN remove_dev_pending; -#if BLE_INCLUDED == TRUE - UINT16 conn_handle; - tBT_TRANSPORT transport; -#endif -} tBTA_DM_PEER_DEVICE; - - - -/* structure to store list of - active connections */ -typedef struct { - tBTA_DM_PEER_DEVICE peer_device[BTA_DM_NUM_PEER_DEVICE]; - UINT8 count; -#if BLE_INCLUDED == TRUE - UINT8 le_count; -#endif -} tBTA_DM_ACTIVE_LINK; - - -typedef struct { - BD_ADDR peer_bdaddr; - tBTA_SYS_ID id; - UINT8 app_id; - tBTA_SYS_CONN_STATUS state; - BOOLEAN new_request; - -} tBTA_DM_SRVCS; - -#ifndef BTA_DM_NUM_CONN_SRVS -#define BTA_DM_NUM_CONN_SRVS 10 -#endif - -typedef struct { - - UINT8 count; - tBTA_DM_SRVCS conn_srvc[BTA_DM_NUM_CONN_SRVS]; - -} tBTA_DM_CONNECTED_SRVCS; - -typedef struct { -#define BTA_DM_PM_SNIFF_TIMER_IDX 0 -#define BTA_DM_PM_PARK_TIMER_IDX 1 -#define BTA_DM_PM_SUSPEND_TIMER_IDX 2 -#define BTA_DM_PM_MODE_TIMER_MAX 3 - /* - * Keep three different timers for PARK, SNIFF and SUSPEND if TBFC is - * supported. - */ - TIMER_LIST_ENT timer[BTA_DM_PM_MODE_TIMER_MAX]; - - UINT8 srvc_id[BTA_DM_PM_MODE_TIMER_MAX]; - UINT8 pm_action[BTA_DM_PM_MODE_TIMER_MAX]; - UINT8 active; /* number of active timer */ - - BD_ADDR peer_bdaddr; - BOOLEAN in_use; -} tBTA_PM_TIMER; - -extern tBTA_DM_CONNECTED_SRVCS bta_dm_conn_srvcs; - -#define BTA_DM_NUM_PM_TIMER 7 - -/* DM control block */ -typedef struct { - BOOLEAN is_bta_dm_active; - tBTA_DM_ACTIVE_LINK device_list; - tBTA_DM_SEC_CBACK *p_sec_cback; -#if ((defined BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) - tBTA_BLE_SCAN_SETUP_CBACK *p_setup_cback; - tBTA_DM_BLE_PF_CFG_CBACK *p_scan_filt_cfg_cback; - tBTA_DM_BLE_PF_STATUS_CBACK *p_scan_filt_status_cback; - tBTA_DM_BLE_PF_PARAM_CBACK *p_scan_filt_param_cback; - tBTA_BLE_MULTI_ADV_CBACK *p_multi_adv_cback; - tBTA_BLE_ENERGY_INFO_CBACK *p_energy_info_cback; -#endif - UINT16 state; - BOOLEAN disabling; - TIMER_LIST_ENT disable_timer; - UINT32 wbt_sdp_handle; /* WIDCOMM Extensions SDP record handle */ - UINT8 wbt_scn; /* WIDCOMM Extensions SCN */ - UINT8 num_master_only; -#if BTM_SSR_INCLUDED == TRUE - UINT8 pm_id; - tBTA_PM_TIMER pm_timer[BTA_DM_NUM_PM_TIMER]; -#endif ///BTM_SSR_INCLUDED == TRUE - UINT32 role_policy_mask; /* the bits set indicates the modules that wants to remove role switch from the default link policy */ - UINT16 cur_policy; /* current default link policy */ - UINT16 rs_event; /* the event waiting for role switch */ - UINT8 cur_av_count; /* current AV connecions */ - BOOLEAN disable_pair_mode; /* disable pair mode or not */ - BOOLEAN conn_paired_only; /* allow connectable to paired device only or not */ - tBTA_DM_API_SEARCH search_msg; - UINT16 page_scan_interval; - UINT16 page_scan_window; - UINT16 inquiry_scan_interval; - UINT16 inquiry_scan_window; - - /* Storage for pin code request parameters */ - BD_ADDR pin_bd_addr; - DEV_CLASS pin_dev_class; - tBTA_DM_SEC_EVT pin_evt; - UINT32 num_val; /* the numeric value for comparison. If just_works, do not show this number to UI */ - BOOLEAN just_works; /* TRUE, if "Just Works" association model */ -#if ( BTA_EIR_CANNED_UUID_LIST != TRUE ) - /* store UUID list for EIR */ - TIMER_LIST_ENT app_ready_timer; - UINT32 eir_uuid[BTM_EIR_SERVICE_ARRAY_SIZE]; -#if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) - tBT_UUID custom_uuid[BTA_EIR_SERVER_NUM_CUSTOM_UUID]; -#endif - -#endif - - - tBTA_DM_ENCRYPT_CBACK *p_encrypt_cback; - TIMER_LIST_ENT switch_delay_timer; - -} tBTA_DM_CB; - -#ifndef BTA_DM_SDP_DB_SIZE -#define BTA_DM_SDP_DB_SIZE 250 -#endif - -/* DM search control block */ -typedef struct { - - tBTA_DM_SEARCH_CBACK *p_search_cback; - tBTM_INQ_INFO *p_btm_inq_info; - tBTA_SERVICE_MASK services; - tBTA_SERVICE_MASK services_to_search; - tBTA_SERVICE_MASK services_found; -#if (SDP_INCLUDED == TRUE) - tSDP_DISCOVERY_DB *p_sdp_db; -#endif ///SDP_INCLUDED == TRUE - UINT16 state; - BD_ADDR peer_bdaddr; - BOOLEAN name_discover_done; - BD_NAME peer_name; - TIMER_LIST_ENT search_timer; - UINT8 service_index; - tBTA_DM_MSG *p_search_queue; /* search or discover commands during search cancel stored here */ - BOOLEAN wait_disc; - BOOLEAN sdp_results; -#if (SDP_INCLUDED == TRUE) - tSDP_UUID uuid; -#endif ///SDP_INCLUDED == TRUE - UINT8 peer_scn; - BOOLEAN sdp_search; - BOOLEAN cancel_pending; /* inquiry cancel is pending */ - tBTA_TRANSPORT transport; -#if ((defined BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) - tBTA_DM_SEARCH_CBACK *p_scan_cback; -#if ((defined BTA_GATT_INCLUDED) && (BTA_GATT_INCLUDED == TRUE) && SDP_INCLUDED == TRUE) - tBTA_GATTC_IF client_if; - UINT8 num_uuid; - tBT_UUID *p_srvc_uuid; - UINT8 uuid_to_search; - BOOLEAN gatt_disc_active; - UINT16 conn_id; - UINT8 *p_ble_rawdata; - UINT32 ble_raw_size; - UINT32 ble_raw_used; - TIMER_LIST_ENT gatt_close_timer; /* GATT channel close delay timer */ - BD_ADDR pending_close_bda; /* pending GATT channel remote device address */ -#endif -#endif - - -} tBTA_DM_SEARCH_CB; - -/* DI control block */ -typedef struct { -#if (SDP_INCLUDED == TRUE) - tSDP_DISCOVERY_DB *p_di_db; /* pointer to the DI discovery database */ -#endif ///SDP_INCLUDED == TRUE - UINT8 di_num; /* total local DI record number */ - UINT32 di_handle[BTA_DI_NUM_MAX]; /* local DI record handle, the first one is primary record */ -} tBTA_DM_DI_CB; - -/* DM search state */ -enum { - - BTA_DM_SEARCH_IDLE, - BTA_DM_SEARCH_ACTIVE, - BTA_DM_SEARCH_CANCELLING, - BTA_DM_DISCOVER_ACTIVE - -}; - - - -typedef struct { - DEV_CLASS dev_class; /* local device class */ - UINT16 policy_settings; /* link policy setting hold, sniff, park, MS switch */ - UINT16 page_timeout; /* timeout for page in slots */ - UINT16 link_timeout; /* link supervision timeout in slots */ - BOOLEAN avoid_scatter; /* TRUE to avoid scatternet when av is streaming (be the master) */ - -} tBTA_DM_CFG; - -extern const UINT32 bta_service_id_to_btm_srv_id_lkup_tbl[]; - - -typedef struct { - UINT8 id; - UINT8 app_id; - UINT8 cfg; - -} tBTA_DM_RM ; - -extern tBTA_DM_CFG *p_bta_dm_cfg; -extern tBTA_DM_RM *p_bta_dm_rm_cfg; - -typedef struct { - - UINT8 id; - UINT8 app_id; - UINT8 spec_idx; /* index of spec table to use */ - -} tBTA_DM_PM_CFG; - - -typedef struct { - - tBTA_DM_PM_ACTION power_mode; - UINT16 timeout; - -} tBTA_DM_PM_ACTN; - -typedef struct { - - UINT8 allow_mask; /* mask of sniff/hold/park modes to allow */ -#if (BTM_SSR_INCLUDED == TRUE) - UINT8 ssr; /* set SSR on conn open/unpark */ -#endif - tBTA_DM_PM_ACTN actn_tbl [BTA_DM_PM_NUM_EVTS][2]; - -} tBTA_DM_PM_SPEC; - -typedef struct { - UINT16 max_lat; - UINT16 min_rmt_to; - UINT16 min_loc_to; -} tBTA_DM_SSR_SPEC; - -typedef struct { - UINT16 manufacturer; - UINT16 lmp_sub_version; - UINT8 lmp_version; -} tBTA_DM_LMP_VER_INFO; - -extern tBTA_DM_PM_CFG *p_bta_dm_pm_cfg; -extern tBTA_DM_PM_SPEC *p_bta_dm_pm_spec; -extern tBTM_PM_PWR_MD *p_bta_dm_pm_md; -#if (BTM_SSR_INCLUDED == TRUE) -extern tBTA_DM_SSR_SPEC *p_bta_dm_ssr_spec; -#endif - -/* update dynamic BRCM Aware EIR data */ -extern const tBTA_DM_EIR_CONF bta_dm_eir_cfg; -extern tBTA_DM_EIR_CONF *p_bta_dm_eir_cfg; - -/* DM control block */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_DM_CB bta_dm_cb; -#else -extern tBTA_DM_CB *bta_dm_cb_ptr; -#define bta_dm_cb (*bta_dm_cb_ptr) -#endif - -/* DM search control block */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_DM_SEARCH_CB bta_dm_search_cb; -#else -extern tBTA_DM_SEARCH_CB *bta_dm_search_cb_ptr; -#define bta_dm_search_cb (*bta_dm_search_cb_ptr) -#endif - -/* DI control block */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_DM_DI_CB bta_dm_di_cb; -#else -extern tBTA_DM_DI_CB *bta_dm_di_cb_ptr; -#define bta_dm_di_cb (*bta_dm_di_cb_ptr) -#endif - -extern BOOLEAN bta_dm_sm_execute(BT_HDR *p_msg); -extern void bta_dm_sm_disable( void ); -extern void bta_dm_sm_deinit(void); -extern BOOLEAN bta_dm_search_sm_execute(BT_HDR *p_msg); -extern void bta_dm_search_sm_disable( void ); - - -extern void bta_dm_enable (tBTA_DM_MSG *p_data); -extern void bta_dm_disable (tBTA_DM_MSG *p_data); -extern void bta_dm_set_dev_name (tBTA_DM_MSG *p_data); -extern void bta_dm_update_white_list(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_read_adv_tx_power(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_read_rssi(tBTA_DM_MSG *p_data); -extern void bta_dm_set_visibility (tBTA_DM_MSG *p_data); - -extern void bta_dm_set_scan_config(tBTA_DM_MSG *p_data); -extern void bta_dm_vendor_spec_command(tBTA_DM_MSG *p_data); -extern void bta_dm_bond (tBTA_DM_MSG *p_data); -extern void bta_dm_bond_cancel (tBTA_DM_MSG *p_data); -extern void bta_dm_pin_reply (tBTA_DM_MSG *p_data); -extern void bta_dm_acl_change(tBTA_DM_MSG *p_data); -extern void bta_dm_add_device (tBTA_DM_MSG *p_data); -extern void bta_dm_remove_device (tBTA_DM_MSG *p_data); -extern void bta_dm_close_acl(tBTA_DM_MSG *p_data); - - -extern void bta_dm_pm_btm_status(tBTA_DM_MSG *p_data); -extern void bta_dm_pm_timer(tBTA_DM_MSG *p_data); -extern void bta_dm_add_ampkey (tBTA_DM_MSG *p_data); - -#if BLE_INCLUDED == TRUE -extern void bta_dm_add_blekey (tBTA_DM_MSG *p_data); -extern void bta_dm_add_ble_device (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_passkey_reply (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_confirm_reply (tBTA_DM_MSG *p_data); -extern void bta_dm_security_grant (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_bg_conn_type (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_conn_params (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_scan_params(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_scan_fil_params(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_conn_scan_params (tBTA_DM_MSG *p_data); -#if ((defined BTA_GATT_INCLUDED) && (BTA_GATT_INCLUDED == TRUE) && SDP_INCLUDED == TRUE) && (GATTC_INCLUDED == TRUE) -extern void bta_dm_close_gatt_conn(tBTA_DM_MSG *p_data); -#endif /* ((defined BTA_GATT_INCLUDED) && (BTA_GATT_INCLUDED == TRUE) && SDP_INCLUDED == TRUE) && (GATTC_INCLUDED == TRUE) */ -extern void bta_dm_ble_observe (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_scan (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_update_conn_params (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_disconnect (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_rand_address(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_stop_advertising(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_config_local_privacy (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_adv_params (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_adv_params_all(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_adv_config (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_adv_config_raw (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_scan_rsp (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_scan_rsp_raw (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_broadcast (tBTA_DM_MSG *p_data); -extern void bta_dm_ble_set_data_length(tBTA_DM_MSG *p_data); - -#if BLE_ANDROID_CONTROLLER_SCAN_FILTER == TRUE -extern void bta_dm_cfg_filter_cond (tBTA_DM_MSG *p_data); -extern void bta_dm_scan_filter_param_setup (tBTA_DM_MSG *p_data); -extern void bta_dm_enable_scan_filter(tBTA_DM_MSG *p_data); -#endif -extern void btm_dm_ble_multi_adv_disable(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_multi_adv_data(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_multi_adv_upd_param(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_multi_adv_enb(tBTA_DM_MSG *p_data); - -extern void bta_dm_ble_setup_storage(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_enable_batch_scan(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_disable_batch_scan(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_read_scan_reports(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_track_advertiser(tBTA_DM_MSG *p_data); -extern void bta_dm_ble_get_energy_info(tBTA_DM_MSG *p_data); - -#endif -extern void bta_dm_set_encryption(tBTA_DM_MSG *p_data); -extern void bta_dm_confirm(tBTA_DM_MSG *p_data); -#if (BTM_OOB_INCLUDED == TRUE) -extern void bta_dm_loc_oob(tBTA_DM_MSG *p_data); -extern void bta_dm_ci_io_req_act(tBTA_DM_MSG *p_data); -extern void bta_dm_ci_rmt_oob_act(tBTA_DM_MSG *p_data); -#endif /* BTM_OOB_INCLUDED */ - -extern void bta_dm_init_pm(void); -extern void bta_dm_disable_pm(void); - -extern UINT8 bta_dm_get_av_count(void); -extern void bta_dm_search_start (tBTA_DM_MSG *p_data); -extern void bta_dm_search_cancel (tBTA_DM_MSG *p_data); -extern void bta_dm_discover (tBTA_DM_MSG *p_data); -#if (SDP_INCLUDED == TRUE) -extern void bta_dm_di_disc (tBTA_DM_MSG *p_data); -#endif ///SDP_INCLUDED == TRUE -extern void bta_dm_inq_cmpl (tBTA_DM_MSG *p_data); -extern void bta_dm_rmt_name (tBTA_DM_MSG *p_data); -#if (SDP_INCLUDED == TRUE) -extern void bta_dm_sdp_result (tBTA_DM_MSG *p_data); -#endif ///SDP_INCLUDED == TRUE -extern void bta_dm_search_cmpl (tBTA_DM_MSG *p_data); -extern void bta_dm_free_sdp_db (tBTA_DM_MSG *p_data); -extern void bta_dm_disc_result (tBTA_DM_MSG *p_data); -extern void bta_dm_search_result (tBTA_DM_MSG *p_data); -extern void bta_dm_discovery_cmpl (tBTA_DM_MSG *p_data); -extern void bta_dm_queue_search (tBTA_DM_MSG *p_data); -extern void bta_dm_queue_disc (tBTA_DM_MSG *p_data); -extern void bta_dm_search_clear_queue (tBTA_DM_MSG *p_data); -extern void bta_dm_search_cancel_cmpl (tBTA_DM_MSG *p_data); -extern void bta_dm_search_cancel_notify (tBTA_DM_MSG *p_data); -extern void bta_dm_search_cancel_transac_cmpl(tBTA_DM_MSG *p_data); -extern void bta_dm_disc_rmt_name (tBTA_DM_MSG *p_data); -extern tBTA_DM_PEER_DEVICE *bta_dm_find_peer_device(BD_ADDR peer_addr); - -extern void bta_dm_pm_active(BD_ADDR peer_addr); - -void bta_dm_eir_update_uuid(UINT16 uuid16, BOOLEAN adding); - -extern void bta_dm_enable_test_mode(tBTA_DM_MSG *p_data); -extern void bta_dm_disable_test_mode(tBTA_DM_MSG *p_data); -extern void bta_dm_execute_callback(tBTA_DM_MSG *p_data); - - -extern void bta_dm_remove_all_acl(tBTA_DM_MSG *p_data); -#endif /* BTA_DM_INT_H */ diff --git a/tools/sdk/include/bluedroid/bta_gatt_api.h b/tools/sdk/include/bluedroid/bta_gatt_api.h deleted file mode 100644 index 3d36961b0bb..00000000000 --- a/tools/sdk/include/bluedroid/bta_gatt_api.h +++ /dev/null @@ -1,1458 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2013 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the public interface file for BTA GATT. - * - ******************************************************************************/ - -#ifndef BTA_GATT_API_H -#define BTA_GATT_API_H - -#include "bta_api.h" -#include "gatt_api.h" -#include "list.h" - -#ifndef BTA_GATT_INCLUDED -#warning BTA_GATT_INCLUDED not defined -#define BTA_GATT_INCLUDED FALSE -#endif - -#if ((BLE_INCLUDED == FALSE) && (BTA_GATT_INCLUDED == TRUE)) -#undef BTA_GATT_INCLUDED -#define BTA_GATT_INCLUDED FALSE -#endif - - -#ifndef BTA_GATT_DEBUG -#define BTA_GATT_DEBUG FALSE -#endif - -typedef enum { - BTGATT_DB_PRIMARY_SERVICE, - BTGATT_DB_SECONDARY_SERVICE, - BTGATT_DB_CHARACTERISTIC, - BTGATT_DB_DESCRIPTOR, - BTGATT_DB_INCLUDED_SERVICE, -}bt_gatt_db_attribute_type_t; - -typedef enum { - GATT_OP_GET_SVC_BY_UUID, - GATT_OP_GET_ALL_CHAR, - GATT_OP_GET_ALL_DESCRI, - GATT_OP_GET_CHAR_BY_UUID, - GATT_OP_GET_DESCRI_BY_UUID, - GATT_OP_GET_DESCRI_BY_HANDLE, - GATT_OP_GET_INCLUDE_SVC, -}bt_gatt_get_db_op_t; - -typedef struct { - bt_gatt_db_attribute_type_t type; - UINT16 attribute_handle; - UINT16 start_handle; - UINT16 end_handle; - UINT16 id; - UINT8 properties; - bt_uuid_t uuid; -}btgatt_db_element_t; - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ -/************************** -** Common Definitions -***************************/ -/* GATT ID */ -typedef struct { - tBT_UUID uuid; /* uuid of the attribute */ - UINT8 inst_id; /* instance ID */ -} __attribute__((packed)) tBTA_GATT_ID; - -/* relate to ESP_GATT_xxx in esp_gatt_def.h */ -/* Success code and error codes */ -#define BTA_GATT_OK GATT_SUCCESS -#define BTA_GATT_INVALID_HANDLE GATT_INVALID_HANDLE /* 0x0001 */ -#define BTA_GATT_READ_NOT_PERMIT GATT_READ_NOT_PERMIT /* 0x0002 */ -#define BTA_GATT_WRITE_NOT_PERMIT GATT_WRITE_NOT_PERMIT /* 0x0003 */ -#define BTA_GATT_INVALID_PDU GATT_INVALID_PDU /* 0x0004 */ -#define BTA_GATT_INSUF_AUTHENTICATION GATT_INSUF_AUTHENTICATION /* 0x0005 */ -#define BTA_GATT_REQ_NOT_SUPPORTED GATT_REQ_NOT_SUPPORTED /* 0x0006 */ -#define BTA_GATT_INVALID_OFFSET GATT_INVALID_OFFSET /* 0x0007 */ -#define BTA_GATT_INSUF_AUTHORIZATION GATT_INSUF_AUTHORIZATION /* 0x0008 */ -#define BTA_GATT_PREPARE_Q_FULL GATT_PREPARE_Q_FULL /* 0x0009 */ -#define BTA_GATT_NOT_FOUND GATT_NOT_FOUND /* 0x000a */ -#define BTA_GATT_NOT_LONG GATT_NOT_LONG /* 0x000b */ -#define BTA_GATT_INSUF_KEY_SIZE GATT_INSUF_KEY_SIZE /* 0x000c */ -#define BTA_GATT_INVALID_ATTR_LEN GATT_INVALID_ATTR_LEN /* 0x000d */ -#define BTA_GATT_ERR_UNLIKELY GATT_ERR_UNLIKELY /* 0x000e */ -#define BTA_GATT_INSUF_ENCRYPTION GATT_INSUF_ENCRYPTION /* 0x000f */ -#define BTA_GATT_UNSUPPORT_GRP_TYPE GATT_UNSUPPORT_GRP_TYPE /* 0x0010 */ -#define BTA_GATT_INSUF_RESOURCE GATT_INSUF_RESOURCE /* 0x0011 */ - - -#define BTA_GATT_NO_RESOURCES GATT_NO_RESOURCES /* 0x80 */ -#define BTA_GATT_INTERNAL_ERROR GATT_INTERNAL_ERROR /* 0x81 */ -#define BTA_GATT_WRONG_STATE GATT_WRONG_STATE /* 0x82 */ -#define BTA_GATT_DB_FULL GATT_DB_FULL /* 0x83 */ -#define BTA_GATT_BUSY GATT_BUSY /* 0x84 */ -#define BTA_GATT_ERROR GATT_ERROR /* 0x85 */ -#define BTA_GATT_CMD_STARTED GATT_CMD_STARTED /* 0x86 */ -#define BTA_GATT_ILLEGAL_PARAMETER GATT_ILLEGAL_PARAMETER /* 0x87 */ -#define BTA_GATT_PENDING GATT_PENDING /* 0x88 */ -#define BTA_GATT_AUTH_FAIL GATT_AUTH_FAIL /* 0x89 */ -#define BTA_GATT_MORE GATT_MORE /* 0x8a */ -#define BTA_GATT_INVALID_CFG GATT_INVALID_CFG /* 0x8b */ -#define BTA_GATT_SERVICE_STARTED GATT_SERVICE_STARTED /* 0x8c */ -#define BTA_GATT_ENCRYPED_MITM GATT_ENCRYPED_MITM /* GATT_SUCCESS */ -#define BTA_GATT_ENCRYPED_NO_MITM GATT_ENCRYPED_NO_MITM /* 0x8d */ -#define BTA_GATT_NOT_ENCRYPTED GATT_NOT_ENCRYPTED /* 0x8e */ -#define BTA_GATT_CONGESTED GATT_CONGESTED /* 0x8f */ - -#define BTA_GATT_DUP_REG GATT_DUP_REG /* 0x90 */ -#define BTA_GATT_ALREADY_OPEN GATT_ALREADY_OPEN /* 0x91 */ -#define BTA_GATT_CANCEL GATT_CANCEL /* 0x92 */ - -/* 0xE0 ~ 0xFC reserved for future use */ -#define BTA_GATT_STACK_RSP GATT_STACK_RSP /* 0xE0 */ -#define BTA_GATT_APP_RSP GATT_APP_RSP /* 0xE1 */ -//Error caused by customer application or stack bug -#define BTA_GATT_UNKNOWN_ERROR GATT_UNKNOWN_ERROR /* 0XEF */ - /* 0xE0 ~ 0xFC reserved for future use */ -#define BTA_GATT_CCC_CFG_ERR GATT_CCC_CFG_ERR /* 0xFD Client Characteristic Configuration Descriptor Improperly Configured */ -#define BTA_GATT_PRC_IN_PROGRESS GATT_PRC_IN_PROGRESS /* 0xFE Procedure Already in progress */ -#define BTA_GATT_OUT_OF_RANGE GATT_OUT_OF_RANGE /* 0xFFAttribute value out of range */ - -typedef UINT8 tBTA_GATT_STATUS; - -#define BTA_GATT_INVALID_CONN_ID GATT_INVALID_CONN_ID - - -/* Client callback function events */ -#define BTA_GATTC_REG_EVT 0 /* GATT client is registered. */ -#define BTA_GATTC_DEREG_EVT 1 /* GATT client deregistered event */ -#define BTA_GATTC_OPEN_EVT 2 /* GATTC open request status event */ -#define BTA_GATTC_READ_CHAR_EVT 3 /* GATT read characteristic event */ -#define BTA_GATTC_WRITE_CHAR_EVT 4 /* GATT write characteristic or char descriptor event */ -#define BTA_GATTC_CLOSE_EVT 5 /* GATTC close request status event */ -#define BTA_GATTC_SEARCH_CMPL_EVT 6 /* GATT discovery complete event */ -#define BTA_GATTC_SEARCH_RES_EVT 7 /* GATT discovery result event */ -#define BTA_GATTC_READ_DESCR_EVT 8 /* GATT read characterisitc descriptor event */ -#define BTA_GATTC_WRITE_DESCR_EVT 9 /* GATT write characteristic descriptor event */ -#define BTA_GATTC_NOTIF_EVT 10 /* GATT attribute notification event */ -#define BTA_GATTC_PREP_WRITE_EVT 11 /* GATT prepare write event */ -#define BTA_GATTC_EXEC_EVT 12 /* execute write complete event */ -#define BTA_GATTC_ACL_EVT 13 /* ACL up event */ -#define BTA_GATTC_CANCEL_OPEN_EVT 14 /* cancel open event */ -#define BTA_GATTC_SRVC_CHG_EVT 15 /* service change event */ -#define BTA_GATTC_LISTEN_EVT 16 /* listen event */ -#define BTA_GATTC_ENC_CMPL_CB_EVT 17 /* encryption complete callback event */ -#define BTA_GATTC_CFG_MTU_EVT 18 /* configure MTU complete event */ -#define BTA_GATTC_ADV_DATA_EVT 19 /* ADV data event */ -#define BTA_GATTC_MULT_ADV_ENB_EVT 20 /* Enable Multi ADV event */ -#define BTA_GATTC_MULT_ADV_UPD_EVT 21 /* Update parameter event */ -#define BTA_GATTC_MULT_ADV_DATA_EVT 22 /* Multi ADV data event */ -#define BTA_GATTC_MULT_ADV_DIS_EVT 23 /* Disable Multi ADV event */ -#define BTA_GATTC_CONGEST_EVT 24 /* Congestion event */ -#define BTA_GATTC_BTH_SCAN_ENB_EVT 25 /* Enable batch scan event */ -#define BTA_GATTC_BTH_SCAN_CFG_EVT 26 /* Config storage event */ -#define BTA_GATTC_BTH_SCAN_RD_EVT 27 /* Batch scan reports read event */ -#define BTA_GATTC_BTH_SCAN_THR_EVT 28 /* Batch scan threshold event */ -#define BTA_GATTC_BTH_SCAN_PARAM_EVT 29 /* Batch scan param event */ -#define BTA_GATTC_BTH_SCAN_DIS_EVT 30 /* Disable batch scan event */ -#define BTA_GATTC_SCAN_FLT_CFG_EVT 31 /* Scan filter config event */ -#define BTA_GATTC_SCAN_FLT_PARAM_EVT 32 /* Param filter event */ -#define BTA_GATTC_SCAN_FLT_STATUS_EVT 33 /* Filter status event */ -#define BTA_GATTC_ADV_VSC_EVT 34 /* ADV VSC event */ -#define BTA_GATTC_CONNECT_EVT 35 /* GATTC CONNECT event */ -#define BTA_GATTC_DISCONNECT_EVT 36 /* GATTC DISCONNECT event */ -#define BTA_GATTC_READ_MULTIPLE_EVT 37 /* GATTC Read mutiple event */ -#define BTA_GATTC_QUEUE_FULL_EVT 38 /* GATTC queue full event */ - -typedef UINT8 tBTA_GATTC_EVT; - -typedef tGATT_IF tBTA_GATTC_IF; - -typedef UINT8 tBTA_ADDR_TYPE; - -typedef struct { - UINT16 unit; /* as UUIUD defined by SIG */ - UINT16 descr; /* as UUID as defined by SIG */ - tGATT_FORMAT format; - INT8 exp; - UINT8 name_spc; /* The name space of the description */ -} tBTA_GATT_CHAR_PRES; - -#define BTA_GATT_CLT_CONFIG_NONE GATT_CLT_CONFIG_NONE /* 0x0000 */ -#define BTA_GATT_CLT_CONFIG_NOTIFICATION GATT_CLT_CONFIG_NOTIFICATION /* 0x0001 */ -#define BTA_GATT_CLT_CONFIG_INDICATION GATT_CLT_CONFIG_INDICATION /* 0x0002 */ -typedef UINT16 tBTA_GATT_CLT_CHAR_CONFIG; - -/* characteristic descriptor: server configuration value -*/ -#define BTA_GATT_SVR_CONFIG_NONE GATT_SVR_CONFIG_NONE /* 0x0000 */ -#define BTA_GATT_SVR_CONFIG_BROADCAST GATT_SVR_CONFIG_BROADCAST /* 0x0001 */ -typedef UINT16 tBTA_GATT_SVR_CHAR_CONFIG; - -/* Characteristic Aggregate Format attribute value -*/ -#define BTA_GATT_AGGR_HANDLE_NUM_MAX 10 -typedef struct { - UINT8 num_handle; - UINT16 handle_list[BTA_GATT_AGGR_HANDLE_NUM_MAX]; -} tBTA_GATT_CHAR_AGGRE; -typedef tGATT_VALID_RANGE tBTA_GATT_VALID_RANGE; - -typedef struct { - UINT16 len; - UINT8 *p_value; -} tBTA_GATT_UNFMT; - -#define BTA_GATT_MAX_ATTR_LEN GATT_MAX_ATTR_LEN - -#define BTA_GATTC_TYPE_WRITE GATT_WRITE -#define BTA_GATTC_TYPE_WRITE_NO_RSP GATT_WRITE_NO_RSP -typedef UINT8 tBTA_GATTC_WRITE_TYPE; - -/* relate to ESP_GATT_CONN_xxx in esp_gatt_defs.h */ -#define BTA_GATT_CONN_UNKNOWN 0 -#define BTA_GATT_CONN_L2C_FAILURE GATT_CONN_L2C_FAILURE /* general l2cap resource failure */ -#define BTA_GATT_CONN_TIMEOUT GATT_CONN_TIMEOUT /* 0x08 connection timeout */ -#define BTA_GATT_CONN_TERMINATE_PEER_USER GATT_CONN_TERMINATE_PEER_USER /* 0x13 connection terminate by peer user */ -#define BTA_GATT_CONN_TERMINATE_LOCAL_HOST GATT_CONN_TERMINATE_LOCAL_HOST/* 0x16 connectionterminated by local host */ -#define BTA_GATT_CONN_FAIL_ESTABLISH GATT_CONN_FAIL_ESTABLISH /* 0x03E connection fail to establish */ -#define BTA_GATT_CONN_LMP_TIMEOUT GATT_CONN_LMP_TIMEOUT /* 0x22 connection fail for LMP response tout */ -#define BTA_GATT_CONN_CANCEL GATT_CONN_CANCEL /* 0x0100 L2CAP connection cancelled */ -#define BTA_GATT_CONN_NONE 0x0101 /* 0x0101 no connection to cancel */ -typedef UINT16 tBTA_GATT_REASON; - -typedef struct { - tBTA_GATT_ID id; - BOOLEAN is_primary; -} tBTA_GATT_SRVC_ID; - - -#define BTA_GATTC_MULTI_MAX GATT_MAX_READ_MULTI_HANDLES - -typedef struct { - UINT8 num_attr; - UINT16 handles[BTA_GATTC_MULTI_MAX]; -}tBTA_GATTC_MULTI; - -/* relate to ESP_GATT_xxx in esp_gatt_def.h */ -#define BTA_GATT_AUTH_REQ_NONE GATT_AUTH_REQ_NONE -#define BTA_GATT_AUTH_REQ_NO_MITM GATT_AUTH_REQ_NO_MITM /* unauthenticated encryption */ -#define BTA_GATT_AUTH_REQ_MITM GATT_AUTH_REQ_MITM /* authenticated encryption */ -#define BTA_GATT_AUTH_REQ_SIGNED_NO_MITM GATT_AUTH_REQ_SIGNED_NO_MITM -#define BTA_GATT_AUTH_REQ_SIGNED_MITM GATT_AUTH_REQ_SIGNED_MITM - -typedef tGATT_AUTH_REQ tBTA_GATT_AUTH_REQ; - -enum { - BTA_GATTC_ATTR_TYPE_INCL_SRVC, - BTA_GATTC_ATTR_TYPE_CHAR, - BTA_GATTC_ATTR_TYPE_CHAR_DESCR, - BTA_GATTC_ATTR_TYPE_SRVC -}; -typedef UINT8 tBTA_GATTC_ATTR_TYPE; - - -typedef struct { - tBT_UUID uuid; - UINT16 s_handle; - UINT16 e_handle; /* used for service only */ - UINT8 attr_type; - UINT8 id; - UINT8 prop; /* used when attribute type is characteristic */ - BOOLEAN is_primary; /* used when attribute type is service */ - UINT16 incl_srvc_handle; /* used when attribute type is included service */ -}tBTA_GATTC_NV_ATTR; - -/* callback data structure */ -typedef struct { - tBTA_GATT_STATUS status; - tBTA_GATTC_IF client_if; - tBT_UUID app_uuid; -}tBTA_GATTC_REG; - -typedef struct { - UINT16 conn_id; - tBTA_GATT_STATUS status; - UINT16 handle; - tBTA_GATT_UNFMT *p_value; -}tBTA_GATTC_READ; - -typedef struct { - UINT16 conn_id; - tBTA_GATT_STATUS status; - UINT16 handle; - UINT16 offset; -}tBTA_GATTC_WRITE; - -typedef struct { - UINT16 conn_id; - tBTA_GATT_STATUS status; -} tBTA_GATTC_EXEC_CMPL; - -typedef struct { - UINT16 conn_id; - tBTA_GATT_STATUS status; -} tBTA_GATTC_SEARCH_CMPL; - -typedef struct { - UINT16 conn_id; - UINT16 start_handle; - UINT16 end_handle; - tBTA_GATT_ID service_uuid; -}tBTA_GATTC_SRVC_RES; - -typedef struct { - UINT16 conn_id; - tBTA_GATT_STATUS status; - UINT16 mtu; -} tBTA_GATTC_CFG_MTU; - -typedef struct { - tBTA_GATT_STATUS status; - UINT16 conn_id; - tBTA_GATTC_IF client_if; - BD_ADDR remote_bda; - tBTA_TRANSPORT transport; - UINT16 mtu; -} tBTA_GATTC_OPEN; - -typedef struct { - tBTA_GATT_STATUS status; - UINT16 conn_id; - tBTA_GATTC_IF client_if; - BD_ADDR remote_bda; - tBTA_GATT_REASON reason; /* disconnect reason code, not useful when connect event is reported */ -} tBTA_GATTC_CLOSE; - -typedef struct { - UINT16 conn_id; - BD_ADDR bda; - UINT16 handle; - UINT16 len; - UINT8 value[BTA_GATT_MAX_ATTR_LEN]; - BOOLEAN is_notify; -} tBTA_GATTC_NOTIFY; - -typedef struct { - UINT16 conn_id; - BOOLEAN congested; /* congestion indicator */ -} tBTA_GATTC_CONGEST; - -typedef struct { - tBTA_GATT_STATUS status; - UINT16 conn_id; - BOOLEAN is_full; -} tBTA_GATTC_QUEUE_FULL; - -typedef struct { - tBTA_GATT_STATUS status; - tBTA_GATTC_IF client_if; - UINT16 conn_id; - BD_ADDR remote_bda; -}tBTA_GATTC_OPEN_CLOSE; - -typedef struct { - tBTA_GATTC_IF client_if; - BD_ADDR remote_bda; -} tBTA_GATTC_ENC_CMPL_CB; - -typedef struct { - UINT16 conn_id; - tBTA_GATTC_IF client_if; - BD_ADDR remote_bda; -} tBTA_GATTC_CONNECT; - -typedef struct { - tGATT_DISCONN_REASON reason; - UINT16 conn_id; - tBTA_GATTC_IF client_if; - BD_ADDR remote_bda; -} tBTA_GATTC_DISCONNECT; - -typedef struct { - UINT16 conn_id; - BD_ADDR remote_bda; -} tBTA_GATTC_SERVICE_CHANGE; - -typedef union { - tBTA_GATT_STATUS status; - - tBTA_GATTC_SEARCH_CMPL search_cmpl; /* discovery complete */ - tBTA_GATTC_SRVC_RES srvc_res; /* discovery result */ - tBTA_GATTC_REG reg_oper; /* registration data */ - tBTA_GATTC_OPEN open; - tBTA_GATTC_CONNECT connect; - tBTA_GATTC_CLOSE close; - tBTA_GATTC_DISCONNECT disconnect; - tBTA_GATTC_READ read; /* read attribute/descriptor data */ - tBTA_GATTC_WRITE write; /* write complete data */ - tBTA_GATTC_EXEC_CMPL exec_cmpl; /* execute complete */ - tBTA_GATTC_NOTIFY notify; /* notification/indication event data */ - tBTA_GATTC_ENC_CMPL_CB enc_cmpl; - tBTA_GATTC_CFG_MTU cfg_mtu; /* configure MTU operation */ - tBTA_GATTC_CONGEST congest; - tBTA_GATTC_QUEUE_FULL queue_full; - tBTA_GATTC_SERVICE_CHANGE srvc_chg; /* service change event */ -} tBTA_GATTC; - -/* GATTC enable callback function */ -typedef void (tBTA_GATTC_ENB_CBACK)(tBTA_GATT_STATUS status); - -/* Client callback function */ -typedef void (tBTA_GATTC_CBACK)(tBTA_GATTC_EVT event, tBTA_GATTC *p_data); - -/* GATT Server Data Structure */ -/* Server callback function events */ -#define BTA_GATTS_REG_EVT 0 -#define BTA_GATTS_READ_EVT GATTS_REQ_TYPE_READ /* 1 */ -#define BTA_GATTS_WRITE_EVT GATTS_REQ_TYPE_WRITE /* 2 */ -#define BTA_GATTS_EXEC_WRITE_EVT GATTS_REQ_TYPE_WRITE_EXEC /* 3 */ -#define BTA_GATTS_MTU_EVT GATTS_REQ_TYPE_MTU /* 4 */ -#define BTA_GATTS_CONF_EVT GATTS_REQ_TYPE_CONF /* 5 */ -#define BTA_GATTS_DEREG_EVT 6 -#define BTA_GATTS_CREATE_EVT 7 -#define BTA_GATTS_ADD_INCL_SRVC_EVT 8 -#define BTA_GATTS_ADD_CHAR_EVT 9 -#define BTA_GATTS_ADD_CHAR_DESCR_EVT 10 -#define BTA_GATTS_DELELTE_EVT 11 -#define BTA_GATTS_START_EVT 12 -#define BTA_GATTS_STOP_EVT 13 -#define BTA_GATTS_CONNECT_EVT 14 -#define BTA_GATTS_DISCONNECT_EVT 15 -#define BTA_GATTS_OPEN_EVT 16 -#define BTA_GATTS_CANCEL_OPEN_EVT 17 -#define BTA_GATTS_CLOSE_EVT 18 -#define BTA_GATTS_LISTEN_EVT 19 -#define BTA_GATTS_CONGEST_EVT 20 -#define BTA_GATTS_SET_ATTR_VAL_EVT 23 - -typedef UINT8 tBTA_GATTS_EVT; -typedef tGATT_IF tBTA_GATTS_IF; - -/* Attribute permissions -*/ -#define BTA_GATT_PERM_READ GATT_PERM_READ /* bit 0 - 0x0001 */ -#define BTA_GATT_PERM_READ_ENCRYPTED GATT_PERM_READ_ENCRYPTED /* bit 1 - 0x0002 */ -#define BTA_GATT_PERM_READ_ENC_MITM GATT_PERM_READ_ENC_MITM /* bit 2 - 0x0004 */ -#define BTA_GATT_PERM_WRITE GATT_PERM_WRITE /* bit 4 - 0x0010 */ -#define BTA_GATT_PERM_WRITE_ENCRYPTED GATT_PERM_WRITE_ENCRYPTED /* bit 5 - 0x0020 */ -#define BTA_GATT_PERM_WRITE_ENC_MITM GATT_PERM_WRITE_ENC_MITM /* bit 6 - 0x0040 */ -#define BTA_GATT_PERM_WRITE_SIGNED GATT_PERM_WRITE_SIGNED /* bit 7 - 0x0080 */ -#define BTA_GATT_PERM_WRITE_SIGNED_MITM GATT_PERM_WRITE_SIGNED_MITM /* bit 8 - 0x0100 */ -typedef UINT16 tBTA_GATT_PERM; -typedef tGATT_ATTR_VAL tBTA_GATT_ATTR_VAL; -typedef tGATTS_ATTR_CONTROL tBTA_GATTS_ATTR_CONTROL; - -#define BTA_GATTS_INVALID_APP 0xff - -#define BTA_GATTS_INVALID_IF 0 - -/* definition of characteristic properties */ -#define BTA_GATT_CHAR_PROP_BIT_BROADCAST GATT_CHAR_PROP_BIT_BROADCAST /* 0x01 */ -#define BTA_GATT_CHAR_PROP_BIT_READ GATT_CHAR_PROP_BIT_READ /* 0x02 */ -#define BTA_GATT_CHAR_PROP_BIT_WRITE_NR GATT_CHAR_PROP_BIT_WRITE_NR /* 0x04 */ -#define BTA_GATT_CHAR_PROP_BIT_WRITE GATT_CHAR_PROP_BIT_WRITE /* 0x08 */ -#define BTA_GATT_CHAR_PROP_BIT_NOTIFY GATT_CHAR_PROP_BIT_NOTIFY /* 0x10 */ -#define BTA_GATT_CHAR_PROP_BIT_INDICATE GATT_CHAR_PROP_BIT_INDICATE /* 0x20 */ -#define BTA_GATT_CHAR_PROP_BIT_AUTH GATT_CHAR_PROP_BIT_AUTH /* 0x40 */ -#define BTA_GATT_CHAR_PROP_BIT_EXT_PROP GATT_CHAR_PROP_BIT_EXT_PROP /* 0x80 */ -typedef UINT8 tBTA_GATT_CHAR_PROP; - -#ifndef BTA_GATTC_CHAR_DESCR_MAX -#define BTA_GATTC_CHAR_DESCR_MAX 7 -#endif - -/*********************** NV callback Data Definitions ********************** -*/ -typedef struct { - tBT_UUID app_uuid128; - tBT_UUID svc_uuid; - UINT16 svc_inst; - UINT16 s_handle; - UINT16 e_handle; - BOOLEAN is_primary; /* primary service or secondary */ -} tBTA_GATTS_HNDL_RANGE; - -#define BTA_GATTS_SRV_CHG_CMD_ADD_CLIENT GATTS_SRV_CHG_CMD_ADD_CLIENT -#define BTA_GATTS_SRV_CHG_CMD_UPDATE_CLIENT GATTS_SRV_CHG_CMD_UPDATE_CLIENT -#define BTA_GATTS_SRV_CHG_CMD_REMOVE_CLIENT GATTS_SRV_CHG_CMD_REMOVE_CLIENT -#define BTA_GATTS_SRV_CHG_CMD_READ_NUM_CLENTS GATTS_SRV_CHG_CMD_READ_NUM_CLENTS -#define BTA_GATTS_SRV_CHG_CMD_READ_CLENT GATTS_SRV_CHG_CMD_READ_CLENT -typedef tGATTS_SRV_CHG_CMD tBTA_GATTS_SRV_CHG_CMD; - -typedef tGATTS_SRV_CHG tBTA_GATTS_SRV_CHG; -typedef tGATTS_SRV_CHG_REQ tBTA_GATTS_SRV_CHG_REQ; -typedef tGATTS_SRV_CHG_RSP tBTA_GATTS_SRV_CHG_RSP; - -#define BTA_GATT_TRANSPORT_LE GATT_TRANSPORT_LE -#define BTA_GATT_TRANSPORT_BR_EDR GATT_TRANSPORT_BR_EDR -#define BTA_GATT_TRANSPORT_LE_BR_EDR GATT_TRANSPORT_LE_BR_EDR -typedef UINT8 tBTA_GATT_TRANSPORT; - -/* attribute value */ -typedef tGATT_VALUE tBTA_GATT_VALUE; - -/* attribute response data */ -typedef tGATTS_RSP tBTA_GATTS_RSP; - -/* relate to ESP_GATT_PREP_WRITE_xxx in esp_gatt_defs.h */ -/* attribute request data from the client */ -#define BTA_GATT_PREP_WRITE_CANCEL 0x00 -#define BTA_GATT_PREP_WRITE_EXEC 0x01 -typedef tGATT_EXEC_FLAG tBTA_GATT_EXEC_FLAG; - -/* read request always based on UUID */ -typedef tGATT_READ_REQ tBTA_GATT_READ_REQ; - -/* write request data */ -typedef tGATT_WRITE_REQ tBTA_GATT_WRITE_REQ; - -/* callback data for server access request from client */ -typedef tGATTS_DATA tBTA_GATTS_REQ_DATA; - -typedef struct { - tBTA_GATT_STATUS status; - BD_ADDR remote_bda; - UINT32 trans_id; - UINT16 conn_id; - tBTA_GATTS_REQ_DATA *p_data; - UINT16 data_len; - UINT8 *value; -} tBTA_GATTS_REQ; - -typedef struct { - tBTA_GATTS_IF server_if; - tBTA_GATT_STATUS status; - tBT_UUID uuid; -}tBTA_GATTS_REG_OPER; - - -typedef struct { - tBTA_GATTS_IF server_if; - UINT16 service_id; - UINT16 svc_instance; - BOOLEAN is_primary; - tBTA_GATT_STATUS status; - tBT_UUID uuid; -}tBTA_GATTS_CREATE; - -typedef struct { - tBTA_GATTS_IF server_if; - UINT16 service_id; - UINT16 attr_id; - tBTA_GATT_STATUS status; - tBT_UUID char_uuid; -}tBTA_GATTS_ADD_RESULT; -typedef struct{ - tBTA_GATTS_IF server_if; - UINT16 service_id; - UINT16 attr_id; - tBTA_GATT_STATUS status; -}tBAT_GATTS_ATTR_VAL_RESULT; - -typedef struct { - tBTA_GATTS_IF server_if; - UINT16 service_id; - tBTA_GATT_STATUS status; -} tBTA_GATTS_SRVC_OPER; - - -typedef struct { - tBTA_GATTS_IF server_if; - BD_ADDR remote_bda; - UINT16 conn_id; - tBTA_GATT_REASON reason; /* report disconnect reason */ - tBTA_GATT_TRANSPORT transport; -} tBTA_GATTS_CONN; - -typedef struct { - UINT16 conn_id; - BOOLEAN congested; /* report channel congestion indicator */ -} tBTA_GATTS_CONGEST; - -typedef struct { - UINT16 conn_id; /* connection ID */ - tBTA_GATT_STATUS status; /* notification/indication status */ -} tBTA_GATTS_CONF; - -typedef struct { - tBTA_GATT_STATUS status; - UINT16 conn_id; /* connection ID */ -} tBTA_GATTS_CLOSE; - -typedef struct { - tBTA_GATT_STATUS status; - tBTA_GATTS_IF server_if; -} tBTA_GATTS_OPEN; - -typedef struct { - tBTA_GATT_STATUS status; - tBTA_GATTS_IF server_if; -} tBTA_GATTS_CANCEL_OPEN; -/* GATTS callback data */ -typedef union { - tBTA_GATTS_REG_OPER reg_oper; - tBTA_GATTS_CREATE create; - tBTA_GATTS_SRVC_OPER srvc_oper; - tBTA_GATT_STATUS status; /* BTA_GATTS_LISTEN_EVT */ - tBTA_GATTS_ADD_RESULT add_result; /* add included service: BTA_GATTS_ADD_INCL_SRVC_EVT - add char : BTA_GATTS_ADD_CHAR_EVT - add char descriptor: BTA_GATTS_ADD_CHAR_DESCR_EVT */ - tBAT_GATTS_ATTR_VAL_RESULT attr_val; - tBTA_GATTS_REQ req_data; - tBTA_GATTS_CONN conn; /* BTA_GATTS_CONN_EVT */ - tBTA_GATTS_CONGEST congest; /* BTA_GATTS_CONGEST_EVT callback data */ - tBTA_GATTS_CONF confirm; /* BTA_GATTS_CONF_EVT callback data */ - tBTA_GATTS_CLOSE close; /* BTA_GATTS_CLOSE_EVT callback data */ - tBTA_GATTS_OPEN open; /* BTA_GATTS_OPEN_EVT callback data */ - tBTA_GATTS_CANCEL_OPEN cancel_open; /* tBTA_GATTS_CANCEL_OPEN callback data */ - -} tBTA_GATTS; - -/* GATTC wait for service change ccc timer callback data */ -typedef struct { - UINT16 conn_id; - BD_ADDR remote_bda; - UINT8 count; - UINT8 last_status; -}tBTA_GATTC_WAIT_CCC_TIMER; - -/* GATTS enable callback function */ -typedef void (tBTA_GATTS_ENB_CBACK)(tBTA_GATT_STATUS status); - -/* Server callback function */ -typedef void (tBTA_GATTS_CBACK)(tBTA_GATTS_EVT event, tBTA_GATTS *p_data); -typedef struct -{ - tBT_UUID uuid; - BOOLEAN is_primary; - UINT16 handle; - UINT16 s_handle; - UINT16 e_handle; - list_t *characteristics; /* list of tBTA_GATTC_CHARACTERISTIC */ - list_t *included_svc; /* list of tBTA_GATTC_INCLUDED_SVC */ -} __attribute__((packed)) tBTA_GATTC_SERVICE; - -typedef struct -{ - tBT_UUID uuid; - UINT16 handle; - tBTA_GATT_CHAR_PROP properties; - tBTA_GATTC_SERVICE *service; /* owning service*/ - list_t *descriptors; /* list of tBTA_GATTC_DESCRIPTOR */ -} __attribute__((packed)) tBTA_GATTC_CHARACTERISTIC; - -typedef struct -{ - tBT_UUID uuid; - UINT16 handle; - tBTA_GATTC_CHARACTERISTIC *characteristic; /* owning characteristic */ -} __attribute__((packed)) tBTA_GATTC_DESCRIPTOR; - -typedef struct -{ - tBT_UUID uuid; - UINT16 handle; - UINT16 incl_srvc_s_handle; - tBTA_GATTC_SERVICE *owning_service; /* owning service*/ - tBTA_GATTC_SERVICE *included_service; -} __attribute__((packed)) tBTA_GATTC_INCLUDED_SVC; - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ - -#ifdef __cplusplus -extern "C" -{ -#endif - -/************************** -** Client Functions -***************************/ - -/******************************************************************************* -** -** Function BTA_GATTC_Disable -** -** Description This function is called to disable the GATTC module -** -** Parameters None. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_Disable(void); - -/******************************************************************************* -** -** Function BTA_GATTC_AppRegister -** -** Description This function is called to register application callbacks -** with BTA GATTC module. -** -** Parameters p_app_uuid - applicaiton UUID -** p_client_cb - pointer to the application callback function. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_AppRegister(tBT_UUID *p_app_uuid, tBTA_GATTC_CBACK *p_client_cb); - -/******************************************************************************* -** -** Function BTA_GATTC_AppDeregister -** -** Description This function is called to deregister an application -** from BTA GATTC module. -** -** Parameters client_if - client interface identifier. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_AppDeregister (tBTA_GATTC_IF client_if); - -/******************************************************************************* -** -** Function BTA_GATTC_Open -** -** Description Open a direct connection or add a background auto connection -** bd address -** -** Parameters client_if: server interface. -** remote_bda: remote device BD address. -** remote_addr_type: remote device BD address type. -** is_direct: direct connection or background auto connection -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTC_Open(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, tBTA_ADDR_TYPE remote_addr_type, - BOOLEAN is_direct, tBTA_GATT_TRANSPORT transport); - -/******************************************************************************* -** -** Function BTA_GATTC_CancelOpen -** -** Description Open a direct connection or add a background auto connection -** bd address -** -** Parameters client_if: server interface. -** remote_bda: remote device BD address. -** is_direct: direct connection or background auto connection -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTC_CancelOpen(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, BOOLEAN is_direct); - -/******************************************************************************* -** -** Function BTA_GATTC_Close -** -** Description Close a connection to a GATT server. -** -** Parameters conn_id: connection ID to be closed. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTC_Close(UINT16 conn_id); - -/******************************************************************************* -** -** Function BTA_GATTC_ServiceSearchRequest -** -** Description This function is called to request a GATT service discovery -** on a GATT server. This function report service search result -** by a callback event, and followed by a service search complete -** event. -** -** Parameters conn_id: connection ID. -** p_srvc_uuid: a UUID of the service application is interested in. -** If Null, discover for all services. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_ServiceSearchRequest(UINT16 conn_id, tBT_UUID *p_srvc_uuid); - -/******************************************************************************* -** -** Function BTA_GATTC_GetServices -** -** Description This function is called to find the services on the given server. -** -** Parameters conn_id: connection ID which identify the server. -** -** Returns returns list_t of tBTA_GATTC_SERVICE or NULL. -** -*******************************************************************************/ -extern const list_t* BTA_GATTC_GetServices(UINT16 conn_id); - -/******************************************************************************* -** -** Function BTA_GATTC_GetCharacteristic -** -** Description This function is called to find the characteristic on the given server. -** -** Parameters conn_id: connection ID which identify the server. -** handle: characteristic handle -** -** Returns returns pointer to tBTA_GATTC_CHARACTERISTIC or NULL. -** -*******************************************************************************/ -extern const tBTA_GATTC_CHARACTERISTIC* BTA_GATTC_GetCharacteristic(UINT16 conn_id, UINT16 handle); - -/******************************************************************************* -** -** Function BTA_GATTC_GetDescriptor -** -** Description This function is called to find the characteristic on the given server. -** -** Parameters conn_id: connection ID which identify the server. -** handle: descriptor handle -** -** Returns returns pointer to tBTA_GATTC_DESCRIPTOR or NULL. -** -*******************************************************************************/ -extern const tBTA_GATTC_DESCRIPTOR* BTA_GATTC_GetDescriptor(UINT16 conn_id, UINT16 handle); - -extern void BTA_GATTC_GetServiceWithUUID(UINT16 conn_id, tBT_UUID *svc_uuid, - btgatt_db_element_t **db, int *count); - -extern void BTA_GATTC_GetAllChar(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, - btgatt_db_element_t **db, int *count); - -extern void BTA_GATTC_GetAllDescriptor(UINT16 conn_id, UINT16 char_handle, - btgatt_db_element_t **db, int *count); - -extern void BTA_GATTC_GetCharByUUID(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, tBT_UUID char_uuid, - btgatt_db_element_t **db, int *count); - -extern void BTA_GATTC_GetDescrByUUID(UINT16 conn_id, uint16_t start_handle, uint16_t end_handle, - tBT_UUID char_uuid, tBT_UUID descr_uuid, - btgatt_db_element_t **db, int *count); - -extern void BTA_GATTC_GetDescrByCharHandle(UINT16 conn_id, UINT16 char_handle, tBT_UUID descr_uuid, - btgatt_db_element_t **db, int *count); - -extern void BTA_GATTC_GetIncludeService(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, - tBT_UUID *incl_uuid, btgatt_db_element_t **db, int *count); - -extern void BTA_GATTC_GetDBSize(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, int *count); - -extern void BTA_GATTC_GetDBSizeByType(UINT16 conn_id, bt_gatt_db_attribute_type_t type, - UINT16 start_handle, UINT16 end_handle, UINT16 char_handle, int *count); - -/******************************************************************************* -** -** Function BTA_GATTC_GetGattDb -** -** Description This function is called to get gatt db. -** -** Parameters conn_id: connection ID which identify the server. -** db: output parameter which will contain gatt db copy. -** Caller is responsible for freeing it. -** count: number of elements in db. -** -*******************************************************************************/ -extern void BTA_GATTC_GetGattDb(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, - btgatt_db_element_t **db, int *count); - -/******************************************************************************* -** -** Function BTA_GATTC_ReadCharacteristic -** -** Description This function is called to read a characteristics value -** -** Parameters conn_id - connectino ID. -** handle - characteritic handle to read. -** -** Returns None -** -*******************************************************************************/ -void BTA_GATTC_ReadCharacteristic(UINT16 conn_id, UINT16 handle, tBTA_GATT_AUTH_REQ auth_req); - -/******************************************************************************* -** -** Function BTA_GATTC_ReadCharDescr -** -** Description This function is called to read a descriptor value. -** -** Parameters conn_id - connection ID. -** handle - descriptor handle to read. -** -** Returns None -** -*******************************************************************************/ -void BTA_GATTC_ReadCharDescr (UINT16 conn_id, UINT16 handle, tBTA_GATT_AUTH_REQ auth_req); - -/******************************************************************************* -** -** Function BTA_GATTC_WriteCharValue -** -** Description This function is called to write characteristic value. -** -** Parameters conn_id - connection ID. -** handle - characteristic handle to write. -** write_type - type of write. -** len: length of the data to be written. -** p_value - the value to be written. -** -** Returns None -** -*******************************************************************************/ -void BTA_GATTC_WriteCharValue ( UINT16 conn_id, - UINT16 handle, - tBTA_GATTC_WRITE_TYPE write_type, - UINT16 len, - UINT8 *p_value, - tBTA_GATT_AUTH_REQ auth_req); - -/******************************************************************************* -** -** Function BTA_GATTC_WriteCharDescr -** -** Description This function is called to write descriptor value. -** -** Parameters conn_id - connection ID -** handle - descriptor handle to write. -** write_type - type of write. -** p_value - the value to be written. -** -** Returns None -** -*******************************************************************************/ -void BTA_GATTC_WriteCharDescr (UINT16 conn_id, - UINT16 handle, - tBTA_GATTC_WRITE_TYPE write_type, - tBTA_GATT_UNFMT *p_data, - tBTA_GATT_AUTH_REQ auth_req); - -/******************************************************************************* -** -** Function BTA_GATTC_SendIndConfirm -** -** Description This function is called to send handle value confirmation. -** -** Parameters conn_id - connection ID. -** handle - characteristic handle to confirm. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_SendIndConfirm (UINT16 conn_id, UINT16 handle); - -/******************************************************************************* -** -** Function BTA_GATTC_RegisterForNotifications -** -** Description This function is called to register for notification of a service. -** -** Parameters client_if - client interface. -** remote_bda - target GATT server. -** handle - GATT characteristic handle. -** -** Returns OK if registration succeed, otherwise failed. -** -*******************************************************************************/ -extern tBTA_GATT_STATUS BTA_GATTC_RegisterForNotifications (tBTA_GATTC_IF client_if, - BD_ADDR remote_bda, - UINT16 handle); - -/******************************************************************************* -** -** Function BTA_GATTC_DeregisterForNotifications -** -** Description This function is called to de-register for notification of a servbice. -** -** Parameters client_if - client interface. -** remote_bda - target GATT server. -** handle - GATT characteristic handle. -** -** Returns OK if deregistration succeed, otherwise failed. -** -*******************************************************************************/ -extern tBTA_GATT_STATUS BTA_GATTC_DeregisterForNotifications (tBTA_GATTC_IF client_if, - BD_ADDR remote_bda, - UINT16 handle); - -/******************************************************************************* -** -** Function BTA_GATTC_PrepareWrite -** -** Description This function is called to prepare write a characteristic value. -** -** Parameters conn_id - connection ID. -** handle - GATT characteritic handle. -** offset - offset of the write value. -** len - length of the data to be written. -** p_value - the value to be written. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_PrepareWrite (UINT16 conn_id, - UINT16 handle, - UINT16 offset, - UINT16 len, - UINT8 *p_value, - tBTA_GATT_AUTH_REQ auth_req); - -/******************************************************************************* -** -** Function BTA_GATTC_PrepareWriteCharDescr -** -** Description This function is called to prepare write a characteristic descriptor value. -** -** Parameters conn_id - connection ID. -** p_char_descr_id - GATT characteritic descriptor ID of the service. -** offset - offset of the write value. -** len: length of the data to be written. -** p_value - the value to be written. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_PrepareWriteCharDescr (UINT16 conn_id, - UINT16 handle, - UINT16 offset, - tBTA_GATT_UNFMT *p_data, - tBTA_GATT_AUTH_REQ auth_req); -/******************************************************************************* -** -** Function BTA_GATTC_ExecuteWrite -** -** Description This function is called to execute write a prepare write sequence. -** -** Parameters conn_id - connection ID. -** is_execute - execute or cancel. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_ExecuteWrite (UINT16 conn_id, BOOLEAN is_execute); - -/******************************************************************************* -** -** Function BTA_GATTC_ReadMultiple -** -** Description This function is called to read multiple characteristic or -** characteristic descriptors. -** -** Parameters conn_id - connection ID. -** p_read_multi - read multiple parameters. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTC_ReadMultiple(UINT16 conn_id, tBTA_GATTC_MULTI *p_read_multi, - tBTA_GATT_AUTH_REQ auth_req); - - -/******************************************************************************* -** -** Function BTA_GATTC_Refresh -** -** Description Refresh the server cache of the remote device -** -** Parameters remote_bda: remote device BD address. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTC_Refresh(BD_ADDR remote_bda); - - -/******************************************************************************* -** -** Function BTA_GATTC_Listen -** -** Description Start advertisement to listen for connection request. -** -** Parameters client_if: server interface. -** start: to start or stop listening for connection -** remote_bda: remote device BD address, if listen to all device -** use NULL. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTC_Listen(tBTA_GATTC_IF client_if, BOOLEAN start, BD_ADDR_PTR target_bda); - -/******************************************************************************* -** -** Function BTA_GATTC_Broadcast -** -** Description Start broadcasting (non-connectable advertisements) -** -** Parameters client_if: client interface. -** start: to start or stop listening for connection -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTC_Broadcast(tBTA_GATTC_IF client_if, BOOLEAN start); - - -/******************************************************************************* -** -** Function BTA_GATTC_ConfigureMTU -** -** Description Configure the MTU size in the GATT channel. This can be done -** only once per connection. -** -** Parameters conn_id: connection ID. -** -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTC_ConfigureMTU (UINT16 conn_id); - -/******************************************************************************* -** BTA GATT Server API -********************************************************************************/ - -/******************************************************************************* -** -** Function BTA_GATTS_Init -** -** Description This function is called to initalize GATTS module -** -** Parameters None -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTS_Init(); - -/******************************************************************************* -** -** Function BTA_GATTS_Disable -** -** Description This function is called to disable GATTS module -** -** Parameters None. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTS_Disable(void); - -/******************************************************************************* -** -** Function BTA_GATTS_AppRegister -** -** Description This function is called to register application callbacks -** with BTA GATTS module. -** -** Parameters p_app_uuid - applicaiton UUID -** p_cback - pointer to the application callback function. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTS_AppRegister(tBT_UUID *p_app_uuid, tBTA_GATTS_CBACK *p_cback); - - -/******************************************************************************* -** -** Function BTA_GATTS_AppDeregister -** -** Description De-register with BTA GATT Server. -** -** Parameters server_if: server interface -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTS_AppDeregister(tBTA_GATTS_IF server_if); - -/******************************************************************************* -** -** Function BTA_GATTS_CreateService -** -** Description Create a service. When service creation is done, a callback -** event BTA_GATTS_CREATE_SRVC_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. -** -** Parameters server_if: server interface. -** p_service_uuid: service UUID. -** inst: instance ID number of this service. -** num_handle: numble of handle requessted for this service. -** is_primary: is this service a primary one or not. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTS_CreateService(tBTA_GATTS_IF server_if, tBT_UUID *p_service_uuid, - UINT8 inst, UINT16 num_handle, BOOLEAN is_primary); - -/******************************************************************************* -** -** Function BTA_GATTS_AddIncludeService -** -** Description This function is called to add an included service. After included -** service is included, a callback event BTA_GATTS_ADD_INCL_SRVC_EVT -** is reported the included service ID. -** -** Parameters service_id: service ID to which this included service is to -** be added. -** included_service_id: the service ID to be included. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTS_AddIncludeService(UINT16 service_id, UINT16 included_service_id); - -/******************************************************************************* -** -** Function BTA_GATTS_AddCharacteristic -** -** Description This function is called to add a characteristic into a service. -** -** Parameters service_id: service ID to which this included service is to -** be added. -** p_char_uuid : Characteristic UUID. -** perm : Characteristic value declaration attribute permission. -** property : Characteristic Properties -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTS_AddCharacteristic (UINT16 service_id, tBT_UUID *p_char_uuid, - tBTA_GATT_PERM perm, tBTA_GATT_CHAR_PROP property, tGATT_ATTR_VAL *attr_val, - tBTA_GATTS_ATTR_CONTROL *control); - -/******************************************************************************* -** -** Function BTA_GATTS_AddCharDescriptor -** -** Description This function is called to add characteristic descriptor. When -** it's done, a callback event BTA_GATTS_ADD_DESCR_EVT is called -** to report the status and an ID number for this descriptor. -** -** Parameters service_id: service ID to which this charatceristic descriptor is to -** be added. -** perm: descriptor access permission. -** p_descr_uuid: descriptor UUID. -** p_descr_params: descriptor value if it's read only descriptor. -** -** Returns returns status. -** -*******************************************************************************/ -extern void BTA_GATTS_AddCharDescriptor (UINT16 service_id, - tBTA_GATT_PERM perm, - tBT_UUID *p_descr_uuid, tBTA_GATT_ATTR_VAL *attr_val, - tBTA_GATTS_ATTR_CONTROL *control); - -/******************************************************************************* -** -** Function BTA_GATTS_DeleteService -** -** Description This function is called to delete a service. When this is done, -** a callback event BTA_GATTS_DELETE_EVT is report with the status. -** -** Parameters service_id: service_id to be deleted. -** -** Returns returns none. -** -*******************************************************************************/ -extern void BTA_GATTS_DeleteService(UINT16 service_id); - -/******************************************************************************* -** -** Function BTA_GATTS_StartService -** -** Description This function is called to start a service. -** -** Parameters service_id: the service ID to be started. -** sup_transport: supported trasnport. -** -** Returns None. -** -*******************************************************************************/ -extern void BTA_GATTS_StartService(UINT16 service_id, tBTA_GATT_TRANSPORT sup_transport); - -/******************************************************************************* -** -** Function BTA_GATTS_StopService -** -** Description This function is called to stop a service. -** -** Parameters service_id - service to be topped. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTS_StopService(UINT16 service_id); - -/******************************************************************************* -** -** Function BTA_GATTS_HandleValueIndication -** -** Description This function is called to read a characteristics descriptor. -** -** Parameters conn_id - connection identifier. -** attr_id - attribute ID to indicate. -** data_len - indicate data length. -** p_data: data to indicate. -** need_confirm - if this indication expects a confirmation or not. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTS_HandleValueIndication (UINT16 conn_id, UINT16 attr_id, - UINT16 data_len, - UINT8 *p_data, - BOOLEAN need_confirm); - -/******************************************************************************* -** -** Function BTA_GATTS_SendRsp -** -** Description This function is called to send a response to a request. -** -** Parameters conn_id - connection identifier. -** trans_id - transaction ID. -** status - response status -** p_msg - response data. -** -** Returns None -** -*******************************************************************************/ -extern void BTA_GATTS_SendRsp (UINT16 conn_id, UINT32 trans_id, - tBTA_GATT_STATUS status, tBTA_GATTS_RSP *p_msg); - - - -/******************************************************************************* -** -** Function BTA_SetAttributeValue -** -** Description This function is called to set the attribute value in the gatt database -** -** Parameters attr_handle - the attribute value handle. -** length - the value length which has been set to the attribute. -** value - the pointer to the value -** -** Returns None -** -*******************************************************************************/ -extern void BTA_SetAttributeValue(UINT16 attr_handle, UINT16 length, UINT8 *value); - - -/******************************************************************************* -** -** Function BTA_GetAttributeValue -** -** Description This function is called to get the attribute value in the gatt database -** -** Parameters attr_handle - the attribute value handle. -** length - the value length which has been set to the attribute. -** value - the pointer to the value -** -** Returns tBTA_GATT_STATUS -** -*******************************************************************************/ -extern tBTA_GATT_STATUS BTA_GetAttributeValue(UINT16 attr_handle, UINT16 *length, UINT8 **value); - -/******************************************************************************* -** -** Function BTA_GATTS_Open -** -** Description Open a direct open connection or add a background auto connection -** bd address -** -** Parameters server_if: server interface. -** remote_bda: remote device BD address. -** is_direct: direct connection or background auto connection -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTS_Open(tBTA_GATTS_IF server_if, BD_ADDR remote_bda, - BOOLEAN is_direct, tBTA_GATT_TRANSPORT transport); - - -/******************************************************************************* -** -** Function BTA_GATTS_CancelOpen -** -** Description Cancel a direct open connection or remove a background auto connection -** bd address -** -** Parameters server_if: server interface. -** remote_bda: remote device BD address. -** is_direct: direct connection or background auto connection -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTS_CancelOpen(tBTA_GATTS_IF server_if, BD_ADDR remote_bda, BOOLEAN is_direct); - - -/******************************************************************************* -** -** Function BTA_GATTS_Close -** -** Description Close a connection a remote device. -** -** Parameters conn_id: connection ID to be closed. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTS_Close(UINT16 conn_id); - -/******************************************************************************* -** -** Function BTA_GATTS_Listen -** -** Description Start advertisement to listen for connection request for a -** GATT server -** -** Parameters server_if: server interface. -** start: to start or stop listening for connection -** remote_bda: remote device BD address, if listen to all device -** use NULL. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_GATTS_Listen(tBTA_GATTS_IF server_if, BOOLEAN start, - BD_ADDR_PTR target_bda); - - -#ifdef __cplusplus - -} -#endif - - -#endif /* BTA_GATT_API_H */ diff --git a/tools/sdk/include/bluedroid/bta_gatt_common.h b/tools/sdk/include/bluedroid/bta_gatt_common.h deleted file mode 100644 index f6bc884b6a9..00000000000 --- a/tools/sdk/include/bluedroid/bta_gatt_common.h +++ /dev/null @@ -1,36 +0,0 @@ -/****************************************************************************** -* 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. - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains the action functions for gatts and gattc. - * - * - ******************************************************************************/ - -#include "bt_types.h" - - -#ifdef __cplusplus -extern "C" -{ -#endif - -extern void BTA_GATT_SetLocalMTU(uint16_t mtu); - -#ifdef __cplusplus -} -#endif diff --git a/tools/sdk/include/bluedroid/bta_gattc_ci.h b/tools/sdk/include/bluedroid/bta_gattc_ci.h deleted file mode 100644 index 12b3a421736..00000000000 --- a/tools/sdk/include/bluedroid/bta_gattc_ci.h +++ /dev/null @@ -1,117 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for GATT call-in functions. - * - ******************************************************************************/ -#ifndef BTA_GATTC_CI_H -#define BTA_GATTC_CI_H - -#include "bta_gatt_api.h" - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ - -/* Open Complete Event */ -typedef struct { - BT_HDR hdr; - tBTA_GATT_STATUS status; -} tBTA_GATTC_CI_EVT; - -#define BTA_GATTC_NV_LOAD_MAX 10 - -/* Read Ready Event */ -typedef struct { - BT_HDR hdr; - tBTA_GATT_STATUS status; - UINT16 num_attr; - tBTA_GATTC_NV_ATTR attr[BTA_GATTC_NV_LOAD_MAX]; -} tBTA_GATTC_CI_LOAD; - - -/***************************************************************************** -** Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function bta_gattc_ci_cache_open -** -** Description This function sends an event to indicate server cache open -** completed. -** -** Parameters server_bda - server BDA of this cache. -** status - BTA_GATT_OK if full buffer of data, -** BTA_GATT_FAIL if an error has occurred. -** -** Returns void -** -*******************************************************************************/ -extern void bta_gattc_ci_cache_open(BD_ADDR server_bda, UINT16 evt, - tBTA_GATT_STATUS status, UINT16 conn_id); - -/******************************************************************************* -** -** Function bta_gattc_ci_cache_load -** -** Description This function sends an event to BTA indicating the phone has -** load the servere cache and ready to send it to the stack. -** -** Parameters server_bda - server BDA of this cache. -** num_bytes_read - number of bytes read into the buffer -** specified in the read callout-function. -** status - BTA_GATT_OK if full buffer of data, -** BTA_GATT_FAIL if an error has occurred. -** -** Returns void -** -*******************************************************************************/ -extern void bta_gattc_ci_cache_load(BD_ADDR server_bda, UINT16 evt, - UINT16 num_attr, tBTA_GATTC_NV_ATTR *p_atrr, - tBTA_GATT_STATUS status, UINT16 conn_id); - -/******************************************************************************* -** -** Function bta_gattc_ci_save -** -** Description This function sends an event to BTA indicating the phone has -** save the server cache. -** -** Parameters server_bda - server BDA of this cache. -** status - BTA_GATT_OK if full buffer of data, -** BTA_GATT_FAIL if an error has occurred. -** -** Returns void -** -*******************************************************************************/ -extern void bta_gattc_ci_cache_save(BD_ADDR server_bda, UINT16 evt, - tBTA_GATT_STATUS status, UINT16 conn_id); - - -#ifdef __cplusplus -} -#endif - -#endif /* BTA_GATTC_CI_H */ diff --git a/tools/sdk/include/bluedroid/bta_gattc_co.h b/tools/sdk/include/bluedroid/bta_gattc_co.h deleted file mode 100644 index f84f9d354c1..00000000000 --- a/tools/sdk/include/bluedroid/bta_gattc_co.h +++ /dev/null @@ -1,114 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2009-2013 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for BTA GATT client call-out functions. - * - ******************************************************************************/ -#ifndef BTA_GATTC_CO_H -#define BTA_GATTC_CO_H - -#include "bta_gatt_api.h" - -/******************************************************************************* -** -** Function bta_gattc_co_cache_open -** -** Description This callout function is executed by GATTC when a GATT server -** cache is ready to be sent. -** -** Parameter server_bda: server bd address of this cache belongs to -** evt: call in event to be passed in when cache open is done. -** conn_id: connection ID of this cache operation attach to. -** to_save: open cache to save or to load. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_gattc_co_cache_open(BD_ADDR server_bda, UINT16 evt, - UINT16 conn_id, BOOLEAN to_save); - -/******************************************************************************* -** -** Function bta_gattc_co_cache_close -** -** Description This callout function is executed by GATTC when a GATT server -** cache is written completely. -** -** Parameter server_bda: server bd address of this cache belongs to -** conn_id: connection ID of this cache operation attach to. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_gattc_co_cache_close(BD_ADDR server_bda, UINT16 conn_id); - -/******************************************************************************* -** -** Function bta_gattc_co_cache_save -** -** Description This callout function is executed by GATT when a server cache -** is available to save. -** -** Parameter server_bda: server bd address of this cache belongs to -** evt: call in event to be passed in when cache save is done. -** num_attr: number of attribute to be save. -** p_attr: pointer to the list of attributes to save. -** attr_index: starting attribute index of the save operation. -** conn_id: connection ID of this cache operation attach to. -** Returns -** -*******************************************************************************/ -extern void bta_gattc_co_cache_save(BD_ADDR server_bda, UINT16 evt, - UINT16 num_attr, tBTA_GATTC_NV_ATTR *p_attr, - UINT16 attr_index, UINT16 conn_id); - -/******************************************************************************* -** -** Function bta_gattc_co_cache_load -** -** Description This callout function is executed by GATT when server cache -** is required to load. -** -** Parameter server_bda: server bd address of this cache belongs to -** evt: call in event to be passed in when cache save is done. -** num_attr: number of attribute to be save. -** attr_index: starting attribute index of the save operation. -** conn_id: connection ID of this cache operation attach to. -** Returns -** -*******************************************************************************/ -extern void bta_gattc_co_cache_load(BD_ADDR server_bda, UINT16 evt, - UINT16 start_index, UINT16 conn_id); - -/******************************************************************************* -** -** Function bta_gattc_co_cache_reset -** -** Description This callout function is executed by GATTC to reset cache in -** application -** -** Parameter server_bda: server bd address of this cache belongs to -** -** Returns void. -** -*******************************************************************************/ -extern void bta_gattc_co_cache_reset(BD_ADDR server_bda); - -#endif /* BTA_GATT_CO_H */ diff --git a/tools/sdk/include/bluedroid/bta_gattc_int.h b/tools/sdk/include/bluedroid/bta_gattc_int.h deleted file mode 100644 index 8ce71871699..00000000000 --- a/tools/sdk/include/bluedroid/bta_gattc_int.h +++ /dev/null @@ -1,522 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the private file for the file transfer client (FTC). - * - ******************************************************************************/ -#ifndef BTA_GATTC_INT_H -#define BTA_GATTC_INT_H - -#include "bt_target.h" -#include "bta_sys.h" -#include "bta_gatt_api.h" -#include "bta_gattc_ci.h" -#include "bta_gattc_co.h" -#include "fixed_queue.h" -#include "mutex.h" - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ -enum { - BTA_GATTC_API_OPEN_EVT = BTA_SYS_EVT_START(BTA_ID_GATTC), - BTA_GATTC_INT_OPEN_FAIL_EVT, - BTA_GATTC_API_CANCEL_OPEN_EVT, - BTA_GATTC_INT_CANCEL_OPEN_OK_EVT, - - BTA_GATTC_API_READ_EVT, - BTA_GATTC_API_WRITE_EVT, - BTA_GATTC_API_EXEC_EVT, - BTA_GATTC_API_CFG_MTU_EVT, - - BTA_GATTC_API_CLOSE_EVT, - - BTA_GATTC_API_SEARCH_EVT, - BTA_GATTC_API_CONFIRM_EVT, - BTA_GATTC_API_READ_MULTI_EVT, - BTA_GATTC_API_REFRESH_EVT, - - BTA_GATTC_INT_CONN_EVT, - BTA_GATTC_INT_DISCOVER_EVT, - BTA_GATTC_DISCOVER_CMPL_EVT, - BTA_GATTC_OP_CMPL_EVT, - BTA_GATTC_INT_DISCONN_EVT, - - BTA_GATTC_INT_START_IF_EVT, - BTA_GATTC_API_REG_EVT, - BTA_GATTC_API_DEREG_EVT, - BTA_GATTC_API_LISTEN_EVT, - BTA_GATTC_API_BROADCAST_EVT, - BTA_GATTC_API_DISABLE_EVT, - BTA_GATTC_ENC_CMPL_EVT -}; -typedef UINT16 tBTA_GATTC_INT_EVT; - -#define BTA_GATTC_SERVICE_CHANGED_LEN 4 - -/* max client application GATTC can support */ -#ifndef BTA_GATTC_CL_MAX -#if (GATT_MAX_PHY_CHANNEL > 3) - #define BTA_GATTC_CL_MAX GATT_MAX_PHY_CHANNEL -#else - #define BTA_GATTC_CL_MAX 3 // The origin value is 10 -#endif -#endif - -/* max known devices GATTC can support */ -#ifndef BTA_GATTC_KNOWN_SR_MAX -#if (GATT_MAX_PHY_CHANNEL > 3) - #define BTA_GATTC_KNOWN_SR_MAX GATT_MAX_PHY_CHANNEL -#else - #define BTA_GATTC_KNOWN_SR_MAX 3 // The origin value is 10 -#endif -#endif - -#define BTA_GATTC_CONN_MAX GATT_MAX_PHY_CHANNEL - -#ifndef BTA_GATTC_CLCB_MAX -#define BTA_GATTC_CLCB_MAX GATT_CL_MAX_LCB -#endif - -#define BTA_GATTC_WRITE_PREPARE GATT_WRITE_PREPARE -#define BTA_GATTC_INVALID_HANDLE 0 - -/* internal strucutre for GATTC register API */ -typedef struct { - BT_HDR hdr; - tBT_UUID app_uuid; - tBTA_GATTC_CBACK *p_cback; -} tBTA_GATTC_API_REG; - -typedef struct { - BT_HDR hdr; - tBTA_GATTC_IF client_if; -} tBTA_GATTC_INT_START_IF; - -typedef tBTA_GATTC_INT_START_IF tBTA_GATTC_API_DEREG; -typedef tBTA_GATTC_INT_START_IF tBTA_GATTC_INT_DEREG; - -typedef struct { - BT_HDR hdr; - BD_ADDR remote_bda; - tBTA_ADDR_TYPE remote_addr_type; - tBTA_GATTC_IF client_if; - BOOLEAN is_direct; - tBTA_TRANSPORT transport; -} tBTA_GATTC_API_OPEN; - -typedef tBTA_GATTC_API_OPEN tBTA_GATTC_API_CANCEL_OPEN; - -typedef struct { - BT_HDR hdr; - tBTA_GATT_AUTH_REQ auth_req; - UINT16 handle; - tBTA_GATTC_EVT cmpl_evt; -} tBTA_GATTC_API_READ; - -typedef struct { - BT_HDR hdr; - tBTA_GATT_AUTH_REQ auth_req; - UINT16 handle; - tBTA_GATTC_EVT cmpl_evt; - tBTA_GATTC_WRITE_TYPE write_type; - UINT16 offset; - UINT16 len; - UINT8 *p_value; -} tBTA_GATTC_API_WRITE; - -typedef struct { - BT_HDR hdr; - BOOLEAN is_execute; -} tBTA_GATTC_API_EXEC; - -typedef struct { - BT_HDR hdr; - UINT16 handle; -} tBTA_GATTC_API_CONFIRM; - -typedef tGATT_CL_COMPLETE tBTA_GATTC_CMPL; - -typedef struct { - BT_HDR hdr; - UINT8 op_code; - tGATT_STATUS status; - tBTA_GATTC_CMPL *p_cmpl; -} tBTA_GATTC_OP_CMPL; - -typedef struct { - BT_HDR hdr; - tBT_UUID *p_srvc_uuid; -} tBTA_GATTC_API_SEARCH; - -typedef struct { - BT_HDR hdr; - tBTA_GATT_AUTH_REQ auth_req; - UINT8 num_attr; - UINT16 handles[GATT_MAX_READ_MULTI_HANDLES]; - tBTA_GATTC_EVT cmpl_evt; -}tBTA_GATTC_API_READ_MULTI; - -typedef struct { - BT_HDR hdr; - BD_ADDR_PTR remote_bda; - tBTA_GATTC_IF client_if; - BOOLEAN start; -} tBTA_GATTC_API_LISTEN; - - -typedef struct { - BT_HDR hdr; -} tBTA_GATTC_API_CFG_MTU; - -typedef struct { - BT_HDR hdr; - BD_ADDR remote_bda; - tBTA_GATTC_IF client_if; - UINT8 role; - tBT_TRANSPORT transport; - tGATT_DISCONN_REASON reason; - BOOLEAN already_connect; -} tBTA_GATTC_INT_CONN; - -typedef struct { - BT_HDR hdr; - BD_ADDR remote_bda; - tBTA_GATTC_IF client_if; -} tBTA_GATTC_ENC_CMPL; - -typedef union { - BT_HDR hdr; - tBTA_GATTC_API_REG api_reg; - tBTA_GATTC_API_DEREG api_dereg; - tBTA_GATTC_API_OPEN api_conn; - tBTA_GATTC_API_CANCEL_OPEN api_cancel_conn; - tBTA_GATTC_API_READ api_read; - tBTA_GATTC_API_SEARCH api_search; - tBTA_GATTC_API_WRITE api_write; - tBTA_GATTC_API_CONFIRM api_confirm; - tBTA_GATTC_API_EXEC api_exec; - tBTA_GATTC_API_READ_MULTI api_read_multi; - tBTA_GATTC_API_CFG_MTU api_mtu; - tBTA_GATTC_OP_CMPL op_cmpl; - tBTA_GATTC_INT_CONN int_conn; - tBTA_GATTC_ENC_CMPL enc_cmpl; - - tBTA_GATTC_INT_START_IF int_start_if; - tBTA_GATTC_INT_DEREG int_dereg; - /* if peripheral role is supported */ - tBTA_GATTC_API_LISTEN api_listen; - -} tBTA_GATTC_DATA; - - -/* GATT server cache on the client */ -typedef struct { - tBT_UUID uuid; - UINT16 s_handle; - UINT16 e_handle; - // this field is set only for characteristic - UINT16 char_decl_handle; - BOOLEAN is_primary; - tBTA_GATT_CHAR_PROP property; -} tBTA_GATTC_ATTR_REC; - - -#define BTA_GATTC_MAX_CACHE_CHAR 40 -#define BTA_GATTC_ATTR_LIST_SIZE (BTA_GATTC_MAX_CACHE_CHAR * sizeof(tBTA_GATTC_ATTR_REC)) - -#ifndef BTA_GATTC_CACHE_SRVR_SIZE -#define BTA_GATTC_CACHE_SRVR_SIZE 600 -#endif - -enum { - BTA_GATTC_IDLE_ST = 0, /* Idle */ - BTA_GATTC_W4_CONN_ST, /* Wait for connection - (optional) */ - BTA_GATTC_CONN_ST, /* connected state */ - BTA_GATTC_DISCOVER_ST /* discover is in progress */ -}; -typedef UINT8 tBTA_GATTC_STATE; - -typedef struct { - BOOLEAN in_use; - BD_ADDR server_bda; - BOOLEAN connected; - -#define BTA_GATTC_SERV_IDLE 0 -#define BTA_GATTC_SERV_LOAD 1 -#define BTA_GATTC_SERV_SAVE 2 -#define BTA_GATTC_SERV_DISC 3 -#define BTA_GATTC_SERV_DISC_ACT 4 - - UINT8 state; - - list_t *p_srvc_cache; /* list of tBTA_GATTC_SERVICE */ - UINT8 update_count; /* indication received */ - UINT8 num_clcb; /* number of associated CLCB */ - - - tBTA_GATTC_ATTR_REC *p_srvc_list; - UINT8 cur_srvc_idx; - UINT8 cur_char_idx; - UINT8 next_avail_idx; - UINT8 total_srvc; - UINT8 total_char; - UINT16 total_attr; - UINT8 srvc_hdl_chg; /* service handle change indication pending */ - UINT16 attr_index; /* cahce NV saving/loading attribute index */ - - UINT16 mtu; -} tBTA_GATTC_SERV; - -#ifndef BTA_GATTC_NOTIF_REG_MAX -#define BTA_GATTC_NOTIF_REG_MAX 7//15 -#endif - -typedef struct { - BOOLEAN in_use; - BD_ADDR remote_bda; - UINT16 handle; -}tBTA_GATTC_NOTIF_REG; - -typedef struct { - tBTA_GATTC_CBACK *p_cback; - BOOLEAN in_use; - tBTA_GATTC_IF client_if; /* client interface with BTE stack for this application */ - UINT8 num_clcb; /* number of associated CLCB */ - BOOLEAN dereg_pending; - tBT_UUID app_uuid; - tBTA_GATTC_NOTIF_REG notif_reg[BTA_GATTC_NOTIF_REG_MAX]; -} tBTA_GATTC_RCB; - -/* client channel is a mapping between a BTA client(cl_id) and a remote BD address */ -typedef struct { - UINT16 bta_conn_id; /* client channel ID, unique for clcb */ - BD_ADDR bda; - tBTA_TRANSPORT transport; /* channel transport */ - tBTA_GATTC_RCB *p_rcb; /* pointer to the registration CB */ - tBTA_GATTC_SERV *p_srcb; /* server cache CB */ - tBTA_GATTC_DATA *p_q_cmd; /* command in queue waiting for execution */ - list_t *p_cmd_list; /* The list to store the command to be sent */ - BOOLEAN is_full; /* The gattc command queue is full or not */ -#define BTA_GATTC_NO_SCHEDULE 0 -#define BTA_GATTC_DISC_WAITING 0x01 -#define BTA_GATTC_REQ_WAITING 0x10 - - UINT8 auto_update; /* auto update is waiting */ - BOOLEAN disc_active; - BOOLEAN in_use; - tBTA_GATTC_STATE state; - tBTA_GATT_STATUS status; - UINT16 reason; -} tBTA_GATTC_CLCB; - -/* background connection tracking information */ -#if GATT_MAX_APPS <= 8 -typedef UINT8 tBTA_GATTC_CIF_MASK ; -#elif GATT_MAX_APPS <= 16 -typedef UINT16 tBTA_GATTC_CIF_MASK; -#elif GATT_MAX_APPS <= 32 -typedef UINT32 tBTA_GATTC_CIF_MASK; -#endif - -typedef struct { - BOOLEAN in_use; - BD_ADDR remote_bda; - tBTA_GATTC_CIF_MASK cif_mask; - tBTA_GATTC_CIF_MASK cif_adv_mask; - -} tBTA_GATTC_BG_TCK; - -typedef struct { - BOOLEAN in_use; - BD_ADDR remote_bda; - TIMER_LIST_ENT service_change_ccc_timer; /* wait for discovering remote device's service change ccc handle */ - BOOLEAN ccc_timer_used; /* service_change_ccc_timer started */ - BOOLEAN service_change_ccc_written; /* has written remote device's service change ccc */ -} tBTA_GATTC_CONN; - -enum { - BTA_GATTC_STATE_DISABLED, - BTA_GATTC_STATE_ENABLING, - BTA_GATTC_STATE_ENABLED, - BTA_GATTC_STATE_DISABLING -}; - -typedef struct { - UINT8 state; - osi_mutex_t write_ccc_mutex; - tBTA_GATTC_CONN conn_track[BTA_GATTC_CONN_MAX]; - tBTA_GATTC_BG_TCK bg_track[BTA_GATTC_KNOWN_SR_MAX]; - tBTA_GATTC_RCB cl_rcb[BTA_GATTC_CL_MAX]; - - tBTA_GATTC_CLCB clcb[BTA_GATTC_CLCB_MAX]; - tBTA_GATTC_SERV known_server[BTA_GATTC_KNOWN_SR_MAX]; -}tBTA_GATTC_CB; - -typedef enum { - SERVICE_CHANGE_CCC_WRITTEN_SUCCESS = 0, - SERVICE_CHANGE_CACHE_NOT_FOUND, - SERVICE_CHANGE_SERVICE_NOT_FOUND, - SERVICE_CHANGE_CHAR_NOT_FOUND, - SERVICE_CHANGE_CCC_NOT_FOUND, - SERVICE_CHANGE_WRITE_CCC_FAILED -}tBTA_GATTC_FIND_SERVICE_CB; - - -/***************************************************************************** -** Global data -*****************************************************************************/ - -/* GATTC control block */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_GATTC_CB bta_gattc_cb; -#else -extern tBTA_GATTC_CB *bta_gattc_cb_ptr; -#define bta_gattc_cb (*bta_gattc_cb_ptr) -#endif - -/***************************************************************************** -** Function prototypes -*****************************************************************************/ -extern BOOLEAN bta_gattc_hdl_event(BT_HDR *p_msg); -extern BOOLEAN bta_gattc_sm_execute(tBTA_GATTC_CLCB *p_clcb, UINT16 event, tBTA_GATTC_DATA *p_data); - -/* function processed outside SM */ -extern void bta_gattc_disable(tBTA_GATTC_CB *p_cb); -extern void bta_gattc_register(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_start_if(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_process_api_open (tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg); -extern void bta_gattc_process_api_open_cancel (tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg); -extern void bta_gattc_deregister(tBTA_GATTC_CB *p_cb, tBTA_GATTC_RCB *p_clreg); -extern void bta_gattc_process_enc_cmpl(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg); - -/* function within state machine */ -extern void bta_gattc_open(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_open_fail(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_open_error(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); - -extern void bta_gattc_cancel_open(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_cancel_open_error(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); - -extern void bta_gattc_conn(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_conncback(tBTA_GATTC_RCB *p_rcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_disconncback(tBTA_GATTC_RCB *p_rcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_close(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_close_fail(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_disc_close(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); - -extern void bta_gattc_start_discover(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_read(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_write(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_op_cmpl(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_q_cmd(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_free_command_data(tBTA_GATTC_CLCB *p_clcb); -extern void bta_gattc_search(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_fail(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_confirm(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_execute(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_read_multi(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_ci_open(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_ci_close(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_ignore_op_cmpl(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -extern void bta_gattc_restart_discover(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_msg); -extern void bta_gattc_init_bk_conn(tBTA_GATTC_API_OPEN *p_data, tBTA_GATTC_RCB *p_clreg); -extern void bta_gattc_cancel_bk_conn(tBTA_GATTC_API_CANCEL_OPEN *p_data); -extern void bta_gattc_send_open_cback( tBTA_GATTC_RCB *p_clreg, tBTA_GATT_STATUS status, - BD_ADDR remote_bda, UINT16 conn_id, tBTA_TRANSPORT transport, UINT16 mtu); -extern void bta_gattc_send_connect_cback( tBTA_GATTC_RCB *p_clreg, BD_ADDR remote_bda, UINT16 conn_id); -extern void bta_gattc_send_disconnect_cback( tBTA_GATTC_RCB *p_clreg, tGATT_DISCONN_REASON reason, - BD_ADDR remote_bda, UINT16 conn_id); -extern void bta_gattc_process_api_refresh(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg); -extern void bta_gattc_cfg_mtu(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); -#if BLE_INCLUDED == TRUE -extern void bta_gattc_listen(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg); -extern void bta_gattc_broadcast(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg); -#endif -/* utility functions */ -extern tBTA_GATTC_CLCB *bta_gattc_find_clcb_by_cif (UINT8 client_if, BD_ADDR remote_bda, tBTA_TRANSPORT transport); -extern tBTA_GATTC_CLCB *bta_gattc_find_clcb_by_conn_id (UINT16 conn_id); -extern tBTA_GATTC_CLCB *bta_gattc_clcb_alloc(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, tBTA_TRANSPORT transport); -extern void bta_gattc_clcb_dealloc(tBTA_GATTC_CLCB *p_clcb); -extern tBTA_GATTC_CLCB *bta_gattc_find_alloc_clcb(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, tBTA_TRANSPORT transport); -extern tBTA_GATTC_RCB *bta_gattc_cl_get_regcb(UINT8 client_if); -extern tBTA_GATTC_SERV *bta_gattc_find_srcb(BD_ADDR bda); -extern tBTA_GATTC_SERV *bta_gattc_srcb_alloc(BD_ADDR bda); -extern tBTA_GATTC_SERV *bta_gattc_find_scb_by_cid (UINT16 conn_id); -extern tBTA_GATTC_CLCB *bta_gattc_find_int_conn_clcb(tBTA_GATTC_DATA *p_msg); -extern tBTA_GATTC_CLCB *bta_gattc_find_int_disconn_clcb(tBTA_GATTC_DATA *p_msg); - -extern BOOLEAN bta_gattc_enqueue(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data); - -extern BOOLEAN bta_gattc_uuid_compare (const tBT_UUID *p_src, const tBT_UUID *p_tar, BOOLEAN is_precise); -extern BOOLEAN bta_gattc_check_notif_registry(tBTA_GATTC_RCB *p_clreg, tBTA_GATTC_SERV *p_srcb, tBTA_GATTC_NOTIFY *p_notify); -extern BOOLEAN bta_gattc_mark_bg_conn (tBTA_GATTC_IF client_if, BD_ADDR_PTR remote_bda, BOOLEAN add, BOOLEAN is_listen); -extern BOOLEAN bta_gattc_check_bg_conn (tBTA_GATTC_IF client_if, BD_ADDR remote_bda, UINT8 role); -extern UINT8 bta_gattc_num_reg_app(void); -extern void bta_gattc_clear_notif_registration(tBTA_GATTC_SERV *p_srcb, UINT16 conn_id, UINT16 start_handle, UINT16 end_handle); -extern tBTA_GATTC_SERV * bta_gattc_find_srvr_cache(BD_ADDR bda); - -/* discovery functions */ -extern void bta_gattc_disc_res_cback (UINT16 conn_id, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES *p_data); -extern void bta_gattc_disc_cmpl_cback (UINT16 conn_id, tGATT_DISC_TYPE disc_type, tGATT_STATUS status); -extern tBTA_GATT_STATUS bta_gattc_discover_procedure(UINT16 conn_id, tBTA_GATTC_SERV *p_server_cb, UINT8 disc_type); -extern tBTA_GATT_STATUS bta_gattc_discover_pri_service(UINT16 conn_id, tBTA_GATTC_SERV *p_server_cb, UINT8 disc_type); -extern void bta_gattc_search_service(tBTA_GATTC_CLCB *p_clcb, tBT_UUID *p_uuid); -extern const list_t* bta_gattc_get_services(UINT16 conn_id); -extern const tBTA_GATTC_SERVICE* bta_gattc_get_service_for_handle(UINT16 conn_id, UINT16 handle); -tBTA_GATTC_CHARACTERISTIC* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV *p_srcb, UINT16 handle); -extern tBTA_GATTC_CHARACTERISTIC* bta_gattc_get_characteristic(UINT16 conn_id, UINT16 handle); -extern tBTA_GATTC_DESCRIPTOR* bta_gattc_get_descriptor(UINT16 conn_id, UINT16 handle); -extern void bta_gattc_get_db_size_handle(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, int *count); -extern void bta_gattc_get_db_size_with_type_handle(UINT16 conn_id, bt_gatt_db_attribute_type_t type, - UINT16 start_handle, UINT16 end_handle, UINT16 char_handle, int *count); -extern void bta_gattc_get_service_with_uuid(UINT16 conn_id, tBT_UUID *svc_uuid, - btgatt_db_element_t **svc_db, - int *count); - -extern void bta_gattc_get_db_with_opration(UINT16 conn_id, - bt_gatt_get_db_op_t op, - UINT16 char_handle, - tBT_UUID *incl_uuid, - tBT_UUID *char_uuid, - tBT_UUID *descr_uuid, - UINT16 start_handle, UINT16 end_handle, - btgatt_db_element_t **char_db, - int *count); - -extern void bta_gattc_get_gatt_db(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, btgatt_db_element_t **db, int *count); - -extern tBTA_GATT_STATUS bta_gattc_init_cache(tBTA_GATTC_SERV *p_srvc_cb); -extern void bta_gattc_rebuild_cache(tBTA_GATTC_SERV *p_srcv, UINT16 num_attr, tBTA_GATTC_NV_ATTR *attr); -extern void bta_gattc_cache_save(tBTA_GATTC_SERV *p_srvc_cb, UINT16 conn_id); -extern void bta_gattc_reset_discover_st(tBTA_GATTC_SERV *p_srcb, tBTA_GATT_STATUS status); - -extern tBTA_GATTC_CONN *bta_gattc_conn_alloc(BD_ADDR remote_bda); -extern tBTA_GATTC_CONN *bta_gattc_conn_find(BD_ADDR remote_bda); -extern tBTA_GATTC_CONN *bta_gattc_conn_find_alloc(BD_ADDR remote_bda); -extern BOOLEAN bta_gattc_conn_dealloc(BD_ADDR remote_bda); - -extern bool bta_gattc_cache_load(tBTA_GATTC_CLCB *p_clcb); -extern void bta_gattc_cache_reset(BD_ADDR server_bda); -extern void bta_gattc_deinit(void); - -#endif /* BTA_GATTC_INT_H */ diff --git a/tools/sdk/include/bluedroid/bta_gatts_co.h b/tools/sdk/include/bluedroid/bta_gatts_co.h deleted file mode 100644 index 78e001b764d..00000000000 --- a/tools/sdk/include/bluedroid/bta_gatts_co.h +++ /dev/null @@ -1,81 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2010-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for BTA GATT server call-out functions. - * - ******************************************************************************/ -#ifndef BTA_GATTS_CO_H -#define BTA_GATTS_CO_H - -#include "bta_gatt_api.h" - -/******************************************************************************* -** -** Function bta_gatts_co_update_handle_range -** -** Description This callout function is executed by GATTS when a GATT server -** handle range ios to be added or removed. -** -** Parameter is_add: true is to add a handle range; otherwise is to delete. -** p_hndl_range: handle range. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_gatts_co_update_handle_range(BOOLEAN is_add, tBTA_GATTS_HNDL_RANGE *p_hndl_range); - -/******************************************************************************* -** -** Function bta_gatts_co_srv_chg -** -** Description This call-out is to read/write/remove service change related -** informaiton. The request consists of the cmd and p_req and the -** response is returned in p_rsp -** -** Parameter cmd - request command -** p_req - request paramters -** p_rsp - response data for the request -** -** Returns TRUE - if the request is processed successfully and -** the response is returned in p_rsp. -** FASLE - if the request can not be processed -** -*******************************************************************************/ -extern BOOLEAN bta_gatts_co_srv_chg(tBTA_GATTS_SRV_CHG_CMD cmd, - tBTA_GATTS_SRV_CHG_REQ *p_req, - tBTA_GATTS_SRV_CHG_RSP *p_rsp); - -/******************************************************************************* -** -** Function bta_gatts_co_load_handle_range -** -** Description This callout function is executed by GATTS when a GATT server -** handle range is requested to be loaded from NV. -** -** Parameter -** -** Returns void. -** -*******************************************************************************/ -extern BOOLEAN bta_gatts_co_load_handle_range(UINT8 index, - tBTA_GATTS_HNDL_RANGE *p_handle); - - -#endif /* BTA_GATTS_CO_H */ diff --git a/tools/sdk/include/bluedroid/bta_gatts_int.h b/tools/sdk/include/bluedroid/bta_gatts_int.h deleted file mode 100644 index 9d04423f3d3..00000000000 --- a/tools/sdk/include/bluedroid/bta_gatts_int.h +++ /dev/null @@ -1,255 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the private file for the BTA GATT server. - * - ******************************************************************************/ -#ifndef BTA_GATTS_INT_H -#define BTA_GATTS_INT_H - -#include "bt_target.h" -#include "bta_sys.h" -#include "bta_gatt_api.h" -#include "gatt_api.h" - - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ -enum { - BTA_GATTS_API_REG_EVT = BTA_SYS_EVT_START(BTA_ID_GATTS), - BTA_GATTS_INT_START_IF_EVT, - BTA_GATTS_API_DEREG_EVT, - BTA_GATTS_API_CREATE_SRVC_EVT, - BTA_GATTS_API_INDICATION_EVT, - - BTA_GATTS_API_ADD_INCL_SRVC_EVT, - BTA_GATTS_API_ADD_CHAR_EVT, - BTA_GATTS_API_ADD_DESCR_EVT, - BTA_GATTS_API_DEL_SRVC_EVT, - BTA_GATTS_API_START_SRVC_EVT, - BTA_GATTS_API_STOP_SRVC_EVT, - BTA_GATTS_API_RSP_EVT, - BTA_GATTS_API_SET_ATTR_VAL_EVT, - BTA_GATTS_API_OPEN_EVT, - BTA_GATTS_API_CANCEL_OPEN_EVT, - BTA_GATTS_API_CLOSE_EVT, - BTA_GATTS_API_LISTEN_EVT, - BTA_GATTS_API_DISABLE_EVT -}; -typedef UINT16 tBTA_GATTS_INT_EVT; - -/* max number of application allowed on device */ -#define BTA_GATTS_MAX_APP_NUM GATT_MAX_SR_PROFILES - -/* max number of services allowed in the device */ -#define BTA_GATTS_MAX_SRVC_NUM GATT_MAX_SR_PROFILES - -/* internal strucutre for GATTC register API */ -typedef struct { - BT_HDR hdr; - tBT_UUID app_uuid; - tBTA_GATTS_CBACK *p_cback; -} tBTA_GATTS_API_REG; - -typedef struct { - BT_HDR hdr; - tBTA_GATTS_IF server_if; -} tBTA_GATTS_INT_START_IF; - -typedef tBTA_GATTS_INT_START_IF tBTA_GATTS_API_DEREG; - -typedef struct { - BT_HDR hdr; - tBTA_GATTS_IF server_if; - tBT_UUID service_uuid; - UINT16 num_handle; - UINT8 inst; - BOOLEAN is_pri; - -} tBTA_GATTS_API_CREATE_SRVC; - -typedef struct { - BT_HDR hdr; - tBT_UUID char_uuid; - tBTA_GATT_PERM perm; - tBTA_GATT_CHAR_PROP property; - tBTA_GATTS_ATTR_CONTROL control; - tBTA_GATT_ATTR_VAL attr_val; -} tBTA_GATTS_API_ADD_CHAR; - -typedef struct { - BT_HDR hdr; - UINT16 included_service_id; -} tBTA_GATTS_API_ADD_INCL_SRVC; - -typedef struct { - BT_HDR hdr; - tBT_UUID descr_uuid; - tBTA_GATT_PERM perm; - tBTA_GATTS_ATTR_CONTROL control; - tBTA_GATT_ATTR_VAL attr_val; -} tBTA_GATTS_API_ADD_DESCR; - -typedef struct { - BT_HDR hdr; - UINT16 attr_id; - UINT16 len; - BOOLEAN need_confirm; - UINT8 value[BTA_GATT_MAX_ATTR_LEN]; -} tBTA_GATTS_API_INDICATION; - -typedef struct { - BT_HDR hdr; - UINT32 trans_id; - tBTA_GATT_STATUS status; - tBTA_GATTS_RSP *p_rsp; -} tBTA_GATTS_API_RSP; - -typedef struct{ - BT_HDR hdr; - UINT16 length; - UINT8 *value; -}tBTA_GATTS_API_SET_ATTR_VAL; - -typedef struct { - BT_HDR hdr; - tBTA_GATT_TRANSPORT transport; -} tBTA_GATTS_API_START; - - -typedef struct { - BT_HDR hdr; - BD_ADDR remote_bda; - tBTA_GATTS_IF server_if; - BOOLEAN is_direct; - tBTA_GATT_TRANSPORT transport; - -} tBTA_GATTS_API_OPEN; - -typedef tBTA_GATTS_API_OPEN tBTA_GATTS_API_CANCEL_OPEN; - -typedef struct { - BT_HDR hdr; - BD_ADDR_PTR remote_bda; - tBTA_GATTS_IF server_if; - BOOLEAN start; -} tBTA_GATTS_API_LISTEN; - -typedef union { - BT_HDR hdr; - tBTA_GATTS_API_REG api_reg; - tBTA_GATTS_API_DEREG api_dereg; - tBTA_GATTS_API_CREATE_SRVC api_create_svc; - tBTA_GATTS_API_ADD_INCL_SRVC api_add_incl_srvc; - tBTA_GATTS_API_ADD_CHAR api_add_char; - tBTA_GATTS_API_ADD_DESCR api_add_char_descr; - tBTA_GATTS_API_START api_start; - tBTA_GATTS_API_INDICATION api_indicate; - tBTA_GATTS_API_RSP api_rsp; - tBTA_GATTS_API_SET_ATTR_VAL api_set_val; - tBTA_GATTS_API_OPEN api_open; - tBTA_GATTS_API_CANCEL_OPEN api_cancel_open; - - tBTA_GATTS_INT_START_IF int_start_if; - /* if peripheral role is supported */ - tBTA_GATTS_API_LISTEN api_listen; -} tBTA_GATTS_DATA; - -/* application registration control block */ -typedef struct { - BOOLEAN in_use; - tBT_UUID app_uuid; - tBTA_GATTS_CBACK *p_cback; - tBTA_GATTS_IF gatt_if; -} tBTA_GATTS_RCB; - -/* service registration control block */ -typedef struct { - tBT_UUID service_uuid; /* service UUID */ - UINT16 service_id; /* service handle */ - UINT8 inst_num; /* instance ID */ - UINT8 rcb_idx; - UINT8 idx; /* self index of serviec CB */ - BOOLEAN in_use; - -} tBTA_GATTS_SRVC_CB; - - -/* GATT server control block */ -typedef struct { - BOOLEAN enabled; - tBTA_GATTS_RCB rcb[BTA_GATTS_MAX_APP_NUM]; - tBTA_GATTS_SRVC_CB srvc_cb[BTA_GATTS_MAX_SRVC_NUM]; -} tBTA_GATTS_CB; - - - -/***************************************************************************** -** Global data -*****************************************************************************/ - -/* GATTC control block */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_GATTS_CB bta_gatts_cb; -#else -extern tBTA_GATTS_CB *bta_gatts_cb_ptr; -#define bta_gatts_cb (*bta_gatts_cb_ptr) -#endif - -/***************************************************************************** -** Function prototypes -*****************************************************************************/ -extern BOOLEAN bta_gatts_hdl_event(BT_HDR *p_msg); - -extern void bta_gatts_api_disable(tBTA_GATTS_CB *p_cb); -extern void bta_gatts_api_enable(tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_data); -extern void bta_gatts_register(tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_start_if(tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_deregister(tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_create_srvc(tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_add_include_srvc(tBTA_GATTS_SRVC_CB *p_srvc_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_add_char(tBTA_GATTS_SRVC_CB *p_srvc_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_add_char_descr(tBTA_GATTS_SRVC_CB *p_srvc_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_set_attr_value(tBTA_GATTS_SRVC_CB *p_srvc_cb, tBTA_GATTS_DATA *p_msg); -extern tGATT_STATUS bta_gatts_get_attr_value(UINT16 attr_handle, UINT16 *length, UINT8 **value); -extern void bta_gatts_delete_service(tBTA_GATTS_SRVC_CB *p_srvc_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_start_service(tBTA_GATTS_SRVC_CB *p_srvc_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_stop_service(tBTA_GATTS_SRVC_CB *p_srvc_cb, tBTA_GATTS_DATA *p_msg); - -extern void bta_gatts_send_rsp(tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_indicate_handle (tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); - - -extern void bta_gatts_open (tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_cancel_open (tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_close (tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); -extern void bta_gatts_listen(tBTA_GATTS_CB *p_cb, tBTA_GATTS_DATA *p_msg); - -extern BOOLEAN bta_gatts_uuid_compare(tBT_UUID tar, tBT_UUID src); -extern tBTA_GATTS_RCB *bta_gatts_find_app_rcb_by_app_if(tBTA_GATTS_IF server_if); -extern UINT8 bta_gatts_find_app_rcb_idx_by_app_if(tBTA_GATTS_CB *p_cb, tBTA_GATTS_IF server_if); -extern UINT8 bta_gatts_alloc_srvc_cb(tBTA_GATTS_CB *p_cb, UINT8 rcb_idx); -extern tBTA_GATTS_SRVC_CB *bta_gatts_find_srvc_cb_by_srvc_id(tBTA_GATTS_CB *p_cb, UINT16 service_id); -extern tBTA_GATTS_SRVC_CB *bta_gatts_find_srvc_cb_by_attr_id(tBTA_GATTS_CB *p_cb, UINT16 attr_id); -extern void bta_gatts_deinit(void); - -#endif /* BTA_GATTS_INT_H */ - diff --git a/tools/sdk/include/bluedroid/bta_hh_api.h b/tools/sdk/include/bluedroid/bta_hh_api.h deleted file mode 100644 index aa9fd0a236f..00000000000 --- a/tools/sdk/include/bluedroid/bta_hh_api.h +++ /dev/null @@ -1,545 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 BTA_HH_API_H -#define BTA_HH_API_H - -#include "bta_api.h" -#include "hidh_api.h" -#if defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE) - -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) -#include "gatt_api.h" -#endif - -/***************************************************************************** -** Constants and Type Definitions -*****************************************************************************/ -#ifndef BTA_HH_DEBUG -#define BTA_HH_DEBUG TRUE -#endif - -#ifndef BTA_HH_SSR_MAX_LATENCY_DEF -#define BTA_HH_SSR_MAX_LATENCY_DEF 800 /* 500 ms*/ -#endif - -#ifndef BTA_HH_SSR_MIN_TOUT_DEF -#define BTA_HH_SSR_MIN_TOUT_DEF 2 -#endif - -/* BTA HID Host callback events */ -#define BTA_HH_ENABLE_EVT 0 /* HH enabled */ -#define BTA_HH_DISABLE_EVT 1 /* HH disabled */ -#define BTA_HH_OPEN_EVT 2 /* connection opened */ -#define BTA_HH_CLOSE_EVT 3 /* connection closed */ -#define BTA_HH_GET_RPT_EVT 4 /* BTA_HhGetReport callback */ -#define BTA_HH_SET_RPT_EVT 5 /* BTA_HhSetReport callback */ -#define BTA_HH_GET_PROTO_EVT 6 /* BTA_GetProtoMode callback */ -#define BTA_HH_SET_PROTO_EVT 7 /* BTA_HhSetProtoMode callback */ -#define BTA_HH_GET_IDLE_EVT 8 /* BTA_HhGetIdle comes callback */ -#define BTA_HH_SET_IDLE_EVT 9 /* BTA_HhSetIdle finish callback */ -#define BTA_HH_GET_DSCP_EVT 10 /* Get report descriptor */ -#define BTA_HH_ADD_DEV_EVT 11 /* Add Device callback */ -#define BTA_HH_RMV_DEV_EVT 12 /* remove device finished */ -#define BTA_HH_VC_UNPLUG_EVT 13 /* virtually unplugged */ -#define BTA_HH_DATA_EVT 15 -#define BTA_HH_API_ERR_EVT 16 /* API error is caught */ -#define BTA_HH_UPDATE_SCPP_EVT 17 /* update scan paramter complete */ - -typedef UINT16 tBTA_HH_EVT; - -/* application ID(none-zero) for each type of device */ -#define BTA_HH_APP_ID_MI 1 -#define BTA_HH_APP_ID_KB 2 -#define BTA_HH_APP_ID_RMC 3 -#define BTA_HH_APP_ID_3DSG 4 -#define BTA_HH_APP_ID_JOY 5 -#define BTA_HH_APP_ID_GPAD 6 -#define BTA_HH_APP_ID_LE 0xff - -/* defined the minimum offset */ -#define BTA_HH_MIN_OFFSET L2CAP_MIN_OFFSET+1 - -/* HID_HOST_MAX_DEVICES can not exceed 15 for th design of BTA HH */ -#define BTA_HH_IDX_INVALID 0xff -#define BTA_HH_MAX_KNOWN HID_HOST_MAX_DEVICES - -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) -/* GATT_MAX_PHY_CHANNEL can not exceed 14 for the design of BTA HH */ -#define BTA_HH_LE_MAX_KNOWN GATT_MAX_PHY_CHANNEL -#define BTA_HH_MAX_DEVICE (HID_HOST_MAX_DEVICES + GATT_MAX_PHY_CHANNEL) -#else -#define BTA_HH_MAX_DEVICE HID_HOST_MAX_DEVICES -#endif -/* invalid device handle */ -#define BTA_HH_INVALID_HANDLE 0xff - -/* type of protocol mode */ -#define BTA_HH_PROTO_RPT_MODE (0x00) -#define BTA_HH_PROTO_BOOT_MODE (0x01) -#define BTA_HH_PROTO_UNKNOWN (0xff) -typedef UINT8 tBTA_HH_PROTO_MODE; - -enum { - BTA_HH_KEYBD_RPT_ID = 1, - BTA_HH_MOUSE_RPT_ID -}; -typedef UINT8 tBTA_HH_BOOT_RPT_ID; - -/* type of devices, bit mask */ -#define BTA_HH_DEVT_UNKNOWN 0x00 -#define BTA_HH_DEVT_JOS 0x01 /* joy stick */ -#define BTA_HH_DEVT_GPD 0x02 /* game pad */ -#define BTA_HH_DEVT_RMC 0x03 /* remote control */ -#define BTA_HH_DEVT_SED 0x04 /* sensing device */ -#define BTA_HH_DEVT_DGT 0x05 /* Digitizer tablet */ -#define BTA_HH_DEVT_CDR 0x06 /* card reader */ -#define BTA_HH_DEVT_KBD 0x10 /* keyboard */ -#define BTA_HH_DEVT_MIC 0x20 /* pointing device */ -#define BTA_HH_DEVT_COM 0x30 /* Combo keyboard/pointing */ -#define BTA_HH_DEVT_OTHER 0x80 -typedef UINT8 tBTA_HH_DEVT; - -enum { - BTA_HH_OK, - BTA_HH_HS_HID_NOT_READY, /* handshake error : device not ready */ - BTA_HH_HS_INVALID_RPT_ID, /* handshake error : invalid report ID */ - BTA_HH_HS_TRANS_NOT_SPT, /* handshake error : transaction not spt */ - BTA_HH_HS_INVALID_PARAM, /* handshake error : invalid paremter */ - BTA_HH_HS_ERROR, /* handshake error : unspecified HS error */ - BTA_HH_ERR, /* general BTA HH error */ - BTA_HH_ERR_SDP, /* SDP error */ - BTA_HH_ERR_PROTO, /* SET_Protocol error, - only used in BTA_HH_OPEN_EVT callback */ - - BTA_HH_ERR_DB_FULL, /* device database full error, used in - BTA_HH_OPEN_EVT/BTA_HH_ADD_DEV_EVT */ - BTA_HH_ERR_TOD_UNSPT, /* type of device not supported */ - BTA_HH_ERR_NO_RES, /* out of system resources */ - BTA_HH_ERR_AUTH_FAILED, /* authentication fail */ - BTA_HH_ERR_HDL, - BTA_HH_ERR_SEC -}; -typedef UINT8 tBTA_HH_STATUS; - - -#define BTA_HH_VIRTUAL_CABLE HID_VIRTUAL_CABLE -#define BTA_HH_NORMALLY_CONNECTABLE HID_NORMALLY_CONNECTABLE -#define BTA_HH_RECONN_INIT HID_RECONN_INIT -#define BTA_HH_SDP_DISABLE HID_SDP_DISABLE -#define BTA_HH_BATTERY_POWER HID_BATTERY_POWER -#define BTA_HH_REMOTE_WAKE HID_REMOTE_WAKE -#define BTA_HH_SUP_TOUT_AVLBL HID_SUP_TOUT_AVLBL -#define BTA_HH_SEC_REQUIRED HID_SEC_REQUIRED -typedef UINT16 tBTA_HH_ATTR_MASK; - -/* supported type of device and corresponding application ID */ -typedef struct { - tBTA_HH_DEVT tod; /* type of device */ - UINT8 app_id; /* corresponding application ID */ -} tBTA_HH_SPT_TOD; - -/* configuration struct */ -typedef struct { - UINT8 max_devt_spt; /* max number of types of devices spt */ - tBTA_HH_SPT_TOD *p_devt_list; /* supported types of device list */ - UINT16 sdp_db_size; -} tBTA_HH_CFG; - -enum { - BTA_HH_RPTT_RESRV, /* reserved */ - BTA_HH_RPTT_INPUT, /* input report */ - BTA_HH_RPTT_OUTPUT, /* output report */ - BTA_HH_RPTT_FEATURE /* feature report */ -}; -typedef UINT8 tBTA_HH_RPT_TYPE; - -/* HID_CONTROL operation code used in BTA_HhSendCtrl() -*/ -enum { - BTA_HH_CTRL_NOP = 0 + HID_PAR_CONTROL_NOP ,/* mapping from BTE */ - BTA_HH_CTRL_HARD_RESET, /* hard reset */ - BTA_HH_CTRL_SOFT_RESET, /* soft reset */ - BTA_HH_CTRL_SUSPEND, /* enter suspend */ - BTA_HH_CTRL_EXIT_SUSPEND, /* exit suspend */ - BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG /* virtual unplug */ -}; -typedef UINT8 tBTA_HH_TRANS_CTRL_TYPE; - -typedef tHID_DEV_DSCP_INFO tBTA_HH_DEV_DESCR; - -#define BTA_HH_SSR_PARAM_INVALID HID_SSR_PARAM_INVALID - -/* id DI is not existing in remote device, vendor_id in tBTA_HH_DEV_DSCP_INFO will be set to 0xffff */ -#define BTA_HH_VENDOR_ID_INVALID 0xffff - - -/* report descriptor information */ -typedef struct { - UINT16 vendor_id; /* vendor ID */ - UINT16 product_id; /* product ID */ - UINT16 version; /* version */ - UINT16 ssr_max_latency; /* SSR max latency, BTA_HH_SSR_PARAM_INVALID if unknown */ - UINT16 ssr_min_tout; /* SSR min timeout, BTA_HH_SSR_PARAM_INVALID if unknown */ - UINT8 ctry_code; /*Country Code.*/ -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) -#define BTA_HH_LE_REMOTE_WAKE 0x01 -#define BTA_HH_LE_NORMAL_CONN 0x02 - - UINT8 flag; -#endif - tBTA_HH_DEV_DESCR descriptor; -} tBTA_HH_DEV_DSCP_INFO; - -/* callback event data for BTA_HH_OPEN_EVT */ -typedef struct { - BD_ADDR bda; /* HID device bd address */ - tBTA_HH_STATUS status; /* operation status */ - UINT8 handle; /* device handle */ -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) - BOOLEAN le_hid; /* is LE devices? */ - BOOLEAN scps_supported; /* scan parameter service supported */ -#endif - -} tBTA_HH_CONN; - -typedef tBTA_HH_CONN tBTA_HH_DEV_INFO; - -/* callback event data */ -typedef struct { - tBTA_HH_STATUS status; /* operation status */ - UINT8 handle; /* device handle */ -} tBTA_HH_CBDATA; - -enum { - BTA_HH_MOD_CTRL_KEY, - BTA_HH_MOD_SHFT_KEY, - BTA_HH_MOD_ALT_KEY, - BTA_HH_MOD_GUI_KEY, - BTA_HH_MOD_MAX_KEY -}; - -/* parsed boot mode keyboard report */ -typedef struct { - UINT8 this_char[6]; /* virtual key code */ - BOOLEAN mod_key[BTA_HH_MOD_MAX_KEY]; - /* ctrl, shift, Alt, GUI */ - /* modifier key: is Shift key pressed */ - /* modifier key: is Ctrl key pressed */ - /* modifier key: is Alt key pressed */ - /* modifier key: GUI up/down */ - BOOLEAN caps_lock; /* is caps locked */ - BOOLEAN num_lock; /* is Num key pressed */ -} tBTA_HH_KEYBD_RPT; - -/* parsed boot mode mouse report */ -typedef struct { - UINT8 mouse_button; /* mouse button is clicked */ - INT8 delta_x; /* displacement x */ - INT8 delta_y; /* displacement y */ -} tBTA_HH_MICE_RPT; - -/* parsed Boot report */ -typedef struct { - tBTA_HH_BOOT_RPT_ID dev_type; /* type of device report */ - union { - tBTA_HH_KEYBD_RPT keybd_rpt; /* keyboard report */ - tBTA_HH_MICE_RPT mice_rpt; /* mouse report */ - } data_rpt; -} tBTA_HH_BOOT_RPT; - -/* handshake data */ -typedef struct { - tBTA_HH_STATUS status; /* handshake status */ - UINT8 handle; /* device handle */ - union { - tBTA_HH_PROTO_MODE proto_mode; /* GET_PROTO_EVT :protocol mode */ - BT_HDR *p_rpt_data; /* GET_RPT_EVT : report data */ - UINT8 idle_rate; /* GET_IDLE_EVT : idle rate */ - } rsp_data; - -} tBTA_HH_HSDATA; - -/* union of data associated with HD callback */ -typedef union { - tBTA_HH_DEV_INFO dev_info; /* BTA_HH_ADD_DEV_EVT, BTA_HH_RMV_DEV_EVT */ - tBTA_HH_CONN conn; /* BTA_HH_OPEN_EVT */ - tBTA_HH_CBDATA dev_status; /* BTA_HH_CLOSE_EVT, - BTA_HH_SET_PROTO_EVT - BTA_HH_SET_RPT_EVT - BTA_HH_SET_IDLE_EVT - BTA_HH_UPDATE_SCPP_EVT */ - - tBTA_HH_STATUS status; /* BTA_HH_ENABLE_EVT */ - tBTA_HH_DEV_DSCP_INFO dscp_info; /* BTA_HH_GET_DSCP_EVT */ - tBTA_HH_HSDATA hs_data; /* GET_ transaction callback - BTA_HH_GET_RPT_EVT - BTA_HH_GET_PROTO_EVT - BTA_HH_GET_IDLE_EVT */ -} tBTA_HH; - -/* BTA HH callback function */ -typedef void (tBTA_HH_CBACK) (tBTA_HH_EVT event, tBTA_HH *p_data); - - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function BTA_HhRegister -** -** Description This function enable HID host and registers HID-Host with -** lower layers. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhEnable(tBTA_SEC sec_mask, tBTA_HH_CBACK *p_cback); - -/******************************************************************************* -** -** Function BTA_HhDeregister -** -** Description This function is called when the host is about power down. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhDisable(void); - -/******************************************************************************* -** -** Function BTA_HhOpen -** -** Description This function is called to start an inquiry and read SDP -** record of responding devices; connect to a device if only -** one active HID device is found. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhOpen (BD_ADDR dev_bda, tBTA_HH_PROTO_MODE mode, - tBTA_SEC sec_mask); - -/******************************************************************************* -** -** Function BTA_HhClose -** -** Description This function disconnects the device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhClose(UINT8 dev_handle); - -/******************************************************************************* -** -** Function BTA_HhSetProtoMode -** -** Description This function set the protocol mode at specified HID handle -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhSetProtoMode(UINT8 handle, tBTA_HH_PROTO_MODE t_type); - -/******************************************************************************* -** -** Function BTA_HhGetProtoMode -** -** Description This function get the protocol mode of a specified HID device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhGetProtoMode(UINT8 dev_handle); -/******************************************************************************* -** -** Function BTA_HhSetReport -** -** Description send SET_REPORT to device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhSetReport(UINT8 dev_handle, tBTA_HH_RPT_TYPE r_type, - BT_HDR *p_data); - -/******************************************************************************* -** -** Function BTA_HhGetReport -** -** Description Send a GET_REPORT to HID device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhGetReport(UINT8 dev_handle, tBTA_HH_RPT_TYPE r_type, - UINT8 rpt_id, UINT16 buf_size); -/******************************************************************************* -** -** Function BTA_HhSetIdle -** -** Description send SET_IDLE to device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhSetIdle(UINT8 dev_handle, UINT16 idle_rate); - -/******************************************************************************* -** -** Function BTA_HhGetIdle -** -** Description Send a GET_IDLE to HID device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhGetIdle(UINT8 dev_handle); - -/******************************************************************************* -** -** Function BTA_HhSendCtrl -** -** Description Send HID_CONTROL request to a HID device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhSendCtrl(UINT8 dev_handle, - tBTA_HH_TRANS_CTRL_TYPE c_type); - -/******************************************************************************* -** -** Function BTA_HhSetIdle -** -** Description send SET_IDLE to device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhSetIdle(UINT8 dev_handle, UINT16 idle_rate); - - -/******************************************************************************* -** -** Function BTA_HhGetIdle -** -** Description Send a GET_IDLE from HID device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhGetIdle(UINT8 dev_handle); - -/******************************************************************************* -** -** Function BTA_HhSendData -** -** Description Send DATA transaction to a HID device. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhSendData(UINT8 dev_handle, BD_ADDR dev_bda, BT_HDR *p_buf); - -/******************************************************************************* -** -** Function BTA_HhGetDscpInfo -** -** Description Get report descriptor of the device -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhGetDscpInfo(UINT8 dev_handle); - -/******************************************************************************* -** Function BTA_HhAddDev -** -** Description Add a virtually cabled device into HID-Host device list -** to manage and assign a device handle for future API call, -** host applciation call this API at start-up to initialize its -** virtually cabled devices. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhAddDev(BD_ADDR bda, tBTA_HH_ATTR_MASK attr_mask, - UINT8 sub_class, UINT8 app_id, - tBTA_HH_DEV_DSCP_INFO dscp_info); -/******************************************************************************* -** -** Function BTA_HhRemoveDev -** -** Description Remove a device from the HID host devices list. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhRemoveDev(UINT8 dev_handle ); - -/******************************************************************************* -** -** Parsing Utility Functions -** -*******************************************************************************/ -/******************************************************************************* -** -** Function BTA_HhParseBootRpt -** -** Description This utility function parse a boot mode report. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhParseBootRpt(tBTA_HH_BOOT_RPT *p_data, UINT8 *p_report, - UINT16 report_len); - -#if BTA_HH_LE_INCLUDED == TRUE -/******************************************************************************* -** -** Function BTA_HhUpdateLeScanParam -** -** Description Update the scan paramteters if connected to a LE hid device as -** report host. -** -** Returns void -** -*******************************************************************************/ -extern void BTA_HhUpdateLeScanParam(UINT8 dev_handle, UINT16 scan_int, UINT16 scan_win); -#endif -/* test commands */ -extern void bta_hh_le_hid_read_rpt_clt_cfg(BD_ADDR bd_addr, UINT8 rpt_id); - - - -#ifdef __cplusplus -} -#endif - -#endif ///defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE) - - -#endif /* BTA_HH_API_H */ diff --git a/tools/sdk/include/bluedroid/bta_hh_co.h b/tools/sdk/include/bluedroid/bta_hh_co.h deleted file mode 100644 index 9cbb155025c..00000000000 --- a/tools/sdk/include/bluedroid/bta_hh_co.h +++ /dev/null @@ -1,132 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2005-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for hid host call-out functions. - * - ******************************************************************************/ -#ifndef BTA_HH_CO_H -#define BTA_HH_CO_H - -#include "bta_hh_api.h" - -typedef struct { - UINT16 rpt_uuid; - UINT8 rpt_id; - tBTA_HH_RPT_TYPE rpt_type; - UINT8 inst_id; - UINT8 prop; -} tBTA_HH_RPT_CACHE_ENTRY; - -/******************************************************************************* -** -** Function bta_hh_co_data -** -** Description This callout function is executed by HH when data is received -** in interupt channel. -** -** -** Returns void. -** -*******************************************************************************/ -extern void bta_hh_co_data(UINT8 dev_handle, UINT8 *p_rpt, UINT16 len, - tBTA_HH_PROTO_MODE mode, UINT8 sub_class, - UINT8 ctry_code, BD_ADDR peer_addr, UINT8 app_id); - -/******************************************************************************* -** -** Function bta_hh_co_open -** -** Description This callout function is executed by HH when connection is -** opened, and application may do some device specific -** initialization. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class, - UINT16 attr_mask, UINT8 app_id); - -/******************************************************************************* -** -** Function bta_hh_co_close -** -** Description This callout function is executed by HH when connection is -** closed, and device specific finalizatio nmay be needed. -** -** Returns void. -** -*******************************************************************************/ -extern void bta_hh_co_close(UINT8 dev_handle, UINT8 app_id); - -#if (BLE_INCLUDED == TRUE && BTA_HH_LE_INCLUDED == TRUE) -/******************************************************************************* -** -** Function bta_hh_le_co_rpt_info -** -** Description This callout function is to convey the report information on -** a HOGP device to the application. Application can save this -** information in NV if device is bonded and load it back when -** stack reboot. -** -** Parameters remote_bda - remote device address -** p_entry - report entry pointer -** app_id - application id -** -** Returns void. -** -*******************************************************************************/ -extern void bta_hh_le_co_rpt_info(BD_ADDR remote_bda, - tBTA_HH_RPT_CACHE_ENTRY *p_entry, - UINT8 app_id); - -/******************************************************************************* -** -** Function bta_hh_le_co_cache_load -** -** Description This callout function is to request the application to load the -** cached HOGP report if there is any. When cache reading is completed, -** bta_hh_le_ci_cache_load() is called by the application. -** -** Parameters remote_bda - remote device address -** p_num_rpt: number of cached report -** app_id - application id -** -** Returns the acched report array -** -*******************************************************************************/ -extern tBTA_HH_RPT_CACHE_ENTRY *bta_hh_le_co_cache_load (BD_ADDR remote_bda, - UINT8 *p_num_rpt, - UINT8 app_id); - -/******************************************************************************* -** -** Function bta_hh_le_co_reset_rpt_cache -** -** Description This callout function is to reset the HOGP device cache. -** -** Parameters remote_bda - remote device address -** -** Returns none -** -*******************************************************************************/ -extern void bta_hh_le_co_reset_rpt_cache (BD_ADDR remote_bda, UINT8 app_id); - -#endif /* #if (BLE_INCLUDED == TRUE && BTA_HH_LE_INCLUDED == TRUE) */ -#endif /* BTA_HH_CO_H */ diff --git a/tools/sdk/include/bluedroid/bta_hh_int.h b/tools/sdk/include/bluedroid/bta_hh_int.h deleted file mode 100644 index e3d296ee766..00000000000 --- a/tools/sdk/include/bluedroid/bta_hh_int.h +++ /dev/null @@ -1,401 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2005-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains BTA HID Host internal definitions - * - ******************************************************************************/ - -#ifndef BTA_HH_INT_H -#define BTA_HH_INT_H - -#include "bta_sys.h" -#include "utl.h" -#include "bta_hh_api.h" - -//#if BTA_HH_LE_INCLUDED == TRUE -#include "bta_gatt_api.h" -//#endif -#if defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE) - -/* can be moved to bta_api.h */ -#define BTA_HH_MAX_RPT_CHARS 8 - -#if (BTA_GATT_INCLUDED == FALSE || BLE_INCLUDED == FALSE) -#undef BTA_HH_LE_INCLUDED -#define BTA_HH_LE_INCLUDED FALSE -#endif - -/* state machine events, these events are handled by the state machine */ -enum { - BTA_HH_API_OPEN_EVT = BTA_SYS_EVT_START(BTA_ID_HH), - BTA_HH_API_CLOSE_EVT, - BTA_HH_INT_OPEN_EVT, - BTA_HH_INT_CLOSE_EVT, - BTA_HH_INT_DATA_EVT, - BTA_HH_INT_CTRL_DATA, - BTA_HH_INT_HANDSK_EVT, - BTA_HH_SDP_CMPL_EVT, - BTA_HH_API_WRITE_DEV_EVT, - BTA_HH_API_GET_DSCP_EVT, - BTA_HH_API_MAINT_DEV_EVT, - BTA_HH_OPEN_CMPL_EVT, -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) - BTA_HH_GATT_CLOSE_EVT, - BTA_HH_GATT_OPEN_EVT, - BTA_HH_START_ENC_EVT, - BTA_HH_ENC_CMPL_EVT, - BTA_HH_GATT_READ_CHAR_CMPL_EVT, - BTA_HH_GATT_WRITE_CHAR_CMPL_EVT, - BTA_HH_GATT_READ_DESCR_CMPL_EVT, - BTA_HH_GATT_WRITE_DESCR_CMPL_EVT, - BTA_HH_API_SCPP_UPDATE_EVT, - BTA_HH_GATT_ENC_CMPL_EVT, -#endif - - /* not handled by execute state machine */ - BTA_HH_API_ENABLE_EVT, - BTA_HH_API_DISABLE_EVT, - BTA_HH_DISC_CMPL_EVT -}; -typedef UINT16 tBTA_HH_INT_EVT; /* HID host internal events */ - -#define BTA_HH_INVALID_EVT (BTA_HH_DISC_CMPL_EVT + 1) - -/* event used to map between BTE event and BTA event */ -#define BTA_HH_FST_TRANS_CB_EVT BTA_HH_GET_RPT_EVT -#define BTA_HH_FST_BTE_TRANS_EVT HID_TRANS_GET_REPORT - -/* sub event code used for device maintainence API call */ -#define BTA_HH_ADD_DEV 0 -#define BTA_HH_REMOVE_DEV 1 - -/* state machine states */ -enum { - BTA_HH_NULL_ST, - BTA_HH_IDLE_ST, - BTA_HH_W4_CONN_ST, - BTA_HH_CONN_ST -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) - , BTA_HH_W4_SEC -#endif - , BTA_HH_INVALID_ST /* Used to check invalid states before executing SM function */ - -}; -typedef UINT8 tBTA_HH_STATE; - -/* data structure used to send a command/data to HID device */ -typedef struct { - BT_HDR hdr; - UINT8 t_type; - UINT8 param; - UINT8 rpt_id; -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) - UINT8 srvc_id; -#endif - UINT16 data; - BT_HDR *p_data; -} tBTA_HH_CMD_DATA; - -/* data type for BTA_HH_API_ENABLE_EVT */ -typedef struct { - BT_HDR hdr; - UINT8 sec_mask; - UINT8 service_name[BTA_SERVICE_NAME_LEN + 1]; - tBTA_HH_CBACK *p_cback; -} tBTA_HH_API_ENABLE; - -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - UINT8 sec_mask; - tBTA_HH_PROTO_MODE mode; -} tBTA_HH_API_CONN; - -/* internal event data from BTE HID callback */ -typedef struct { - BT_HDR hdr; - BD_ADDR addr; - UINT32 data; - BT_HDR *p_data; -} tBTA_HH_CBACK_DATA; - -typedef struct { - BT_HDR hdr; - BD_ADDR bda; - UINT16 attr_mask; - UINT16 sub_event; - UINT8 sub_class; - UINT8 app_id; - tBTA_HH_DEV_DSCP_INFO dscp_info; -} tBTA_HH_MAINT_DEV; - -#if BTA_HH_LE_INCLUDED == TRUE -typedef struct { - BT_HDR hdr; - UINT16 conn_id; - tBTA_GATT_REASON reason; /* disconnect reason code, not useful when connect event is reported */ - -} tBTA_HH_LE_CLOSE; - -typedef struct { - BT_HDR hdr; - UINT16 scan_int; - UINT16 scan_win; -} tBTA_HH_SCPP_UPDATE; -#endif -/* union of all event data types */ -typedef union { - BT_HDR hdr; - tBTA_HH_API_ENABLE api_enable; - tBTA_HH_API_CONN api_conn; - tBTA_HH_CMD_DATA api_sndcmd; - tBTA_HH_CBACK_DATA hid_cback; - tBTA_HH_STATUS status; - tBTA_HH_MAINT_DEV api_maintdev; -#if BTA_HH_LE_INCLUDED == TRUE - tBTA_HH_LE_CLOSE le_close; - tBTA_GATTC_OPEN le_open; - tBTA_HH_SCPP_UPDATE le_scpp_update; - tBTA_GATTC_ENC_CMPL_CB le_enc_cmpl; -#endif -} tBTA_HH_DATA; - -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) -typedef struct { - UINT8 index; - BOOLEAN in_use; - UINT8 inst_id; /* share service instance ID and report instance ID, as - hi 4 for service instance ID, low 4 as charatceristic instance ID */ - tBTA_HH_RPT_TYPE rpt_type; - UINT16 uuid; - UINT8 prop; - UINT8 rpt_id; - BOOLEAN client_cfg_exist; - UINT16 client_cfg_value; -} tBTA_HH_LE_RPT; - -#ifndef BTA_HH_LE_RPT_MAX -#define BTA_HH_LE_RPT_MAX 20 -#endif - -typedef struct { - BOOLEAN in_use; - tBTA_HH_LE_RPT report[BTA_HH_LE_RPT_MAX]; - -#define BTA_HH_LE_PROTO_MODE_BIT 0x01 -#define BTA_HH_LE_CP_BIT 0x02 - UINT8 option_char; /* control point char exisit or not */ - - BOOLEAN expl_incl_srvc; - UINT8 incl_srvc_inst; /* assuming only one included service : battery service */ - UINT8 cur_expl_char_idx; /* currently discovering service index */ - UINT8 *rpt_map; - UINT16 ext_rpt_ref; - tBTA_HH_DEV_DESCR descriptor; - -} tBTA_HH_LE_HID_SRVC; - -#ifndef BTA_HH_LE_HID_SRVC_MAX -#define BTA_HH_LE_HID_SRVC_MAX 1 -#endif - -/* convert a HID handle to the LE CB index */ -#define BTA_HH_GET_LE_CB_IDX(x) (((x) >> 4) - 1) -/* convert a GATT connection ID to HID device handle, it is the hi 4 bits of a UINT8 */ -#define BTA_HH_GET_LE_DEV_HDL(x) (UINT8)(((x) + 1) << 4) -/* check to see if th edevice handle is a LE device handle */ -#define BTA_HH_IS_LE_DEV_HDL(x) ((x) & 0xf0) -#define BTA_HH_IS_LE_DEV_HDL_VALID(x) (((x)>>4) <= BTA_HH_LE_MAX_KNOWN) -#endif - -/* device control block */ -typedef struct { - tBTA_HH_DEV_DSCP_INFO dscp_info; /* report descriptor and DI information */ - BD_ADDR addr; /* BD-Addr of the HID device */ - UINT16 attr_mask; /* attribute mask */ - UINT16 w4_evt; /* W4_handshake event name */ - UINT8 index; /* index number referenced to handle index */ - UINT8 sub_class; /* Cod sub class */ - UINT8 sec_mask; /* security mask */ - UINT8 app_id; /* application ID for this connection */ - UINT8 hid_handle; /* device handle : low 4 bits for regular HID: HID_HOST_MAX_DEVICES can not exceed 15; - high 4 bits for LE HID: GATT_MAX_PHY_CHANNEL can not exceed 15 */ - BOOLEAN vp; /* virtually unplug flag */ - BOOLEAN in_use; /* control block currently in use */ - BOOLEAN incoming_conn; /* is incoming connection? */ - UINT8 incoming_hid_handle; /* temporary handle for incoming connection? */ - BOOLEAN opened; /* TRUE if device successfully opened HID connection */ - tBTA_HH_PROTO_MODE mode; /* protocol mode */ - tBTA_HH_STATE state; /* CB state */ - -#if (BTA_HH_LE_INCLUDED == TRUE) -#define BTA_HH_LE_DISC_NONE 0x00 -#define BTA_HH_LE_DISC_HIDS 0x01 -#define BTA_HH_LE_DISC_DIS 0x02 -#define BTA_HH_LE_DISC_SCPS 0x04 - - UINT8 disc_active; - tBTA_HH_STATUS status; - tBTA_GATT_REASON reason; - BOOLEAN is_le_device; - tBTA_HH_LE_HID_SRVC hid_srvc[BTA_HH_LE_HID_SRVC_MAX]; - UINT16 conn_id; - BOOLEAN in_bg_conn; - UINT8 total_srvc; - UINT8 clt_cfg_idx; - UINT8 cur_srvc_index; /* currently discovering service index */ - BOOLEAN scps_supported; - -#define BTA_HH_LE_SCPS_NOTIFY_NONE 0 -#define BTA_HH_LE_SCPS_NOTIFY_SPT 0x01 -#define BTA_HH_LE_SCPS_NOTIFY_ENB 0x02 - UINT8 scps_notify; /* scan refresh supported/notification enabled */ -#endif - - BOOLEAN security_pending; -} tBTA_HH_DEV_CB; - -/* key board parsing control block */ -typedef struct { - BOOLEAN mod_key[4]; /* ctrl, shift(upper), Alt, GUI */ - BOOLEAN num_lock; - BOOLEAN caps_lock; - UINT8 last_report[BTA_HH_MAX_RPT_CHARS]; -} tBTA_HH_KB_CB; - -/****************************************************************************** -** Main Control Block -*******************************************************************************/ -typedef struct { - tBTA_HH_KB_CB kb_cb; /* key board control block, - suppose BTA will connect - to only one keyboard at - the same time */ - tBTA_HH_DEV_CB kdev[BTA_HH_MAX_DEVICE]; /* device control block */ - tBTA_HH_DEV_CB *p_cur; /* current device control - block idx, used in sdp */ - UINT8 cb_index[BTA_HH_MAX_KNOWN]; /* maintain a CB index - map to dev handle */ -#if (defined BTA_HH_LE_INCLUDED && BTA_HH_LE_INCLUDED == TRUE) - UINT8 le_cb_index[BTA_HH_MAX_DEVICE]; /* maintain a CB index map to LE dev handle */ - tBTA_GATTC_IF gatt_if; -#endif - tBTA_HH_CBACK *p_cback; /* Application callbacks */ - tSDP_DISCOVERY_DB *p_disc_db; - UINT8 trace_level; /* tracing level */ - UINT8 cnt_num; /* connected device number */ - BOOLEAN w4_disable; /* w4 disable flag */ -} -tBTA_HH_CB; - -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_HH_CB bta_hh_cb; -#else -extern tBTA_HH_CB *bta_hh_cb_ptr; -#define bta_hh_cb (*bta_hh_cb_ptr) -#endif - -/* from bta_hh_cfg.c */ -extern tBTA_HH_CFG *p_bta_hh_cfg; - -/***************************************************************************** -** Function prototypes -*****************************************************************************/ -extern BOOLEAN bta_hh_hdl_event(BT_HDR *p_msg); -extern void bta_hh_sm_execute(tBTA_HH_DEV_CB *p_cb, UINT16 event, - tBTA_HH_DATA *p_data); - -/* action functions */ -extern void bta_hh_api_disc_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_open_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_close_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_data_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_ctrl_dat_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_start_sdp(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_sdp_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_write_dev_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_get_dscp_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_handsk_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_maint_dev_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_open_cmpl_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_open_failure(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); - -/* utility functions */ -extern UINT8 bta_hh_find_cb(BD_ADDR bda); -extern void bta_hh_parse_keybd_rpt(tBTA_HH_BOOT_RPT *p_kb_data, - UINT8 *p_report, UINT16 report_len); -extern void bta_hh_parse_mice_rpt(tBTA_HH_BOOT_RPT *p_kb_data, - UINT8 *p_report, UINT16 report_len); -extern BOOLEAN bta_hh_tod_spt(tBTA_HH_DEV_CB *p_cb, UINT8 sub_class); -extern void bta_hh_clean_up_kdev(tBTA_HH_DEV_CB *p_cb); - -extern void bta_hh_add_device_to_list(tBTA_HH_DEV_CB *p_cb, UINT8 handle, - UINT16 attr_mask, - tHID_DEV_DSCP_INFO *p_dscp_info, - UINT8 sub_class, UINT16 max_latency, UINT16 min_tout, UINT8 app_id); -extern void bta_hh_update_di_info(tBTA_HH_DEV_CB *p_cb, UINT16 vendor_id, UINT16 product_id, - UINT16 version, UINT8 flag); -extern void bta_hh_cleanup_disable(tBTA_HH_STATUS status); - -extern UINT8 bta_hh_dev_handle_to_cb_idx(UINT8 dev_handle); - -/* action functions used outside state machine */ -extern void bta_hh_api_enable(tBTA_HH_DATA *p_data); -extern void bta_hh_api_disable(void); -extern void bta_hh_disc_cmpl(void); - -extern tBTA_HH_STATUS bta_hh_read_ssr_param(BD_ADDR bd_addr, UINT16 *p_max_ssr_lat, UINT16 *p_min_ssr_tout); - -/* functions for LE HID */ -extern void bta_hh_le_enable(void); -extern BOOLEAN bta_hh_le_is_hh_gatt_if(tBTA_GATTC_IF client_if); -extern void bta_hh_le_deregister(void); -extern BOOLEAN bta_hh_is_le_device(tBTA_HH_DEV_CB *p_cb, BD_ADDR remote_bda); -extern void bta_hh_le_open_conn(tBTA_HH_DEV_CB *p_cb, BD_ADDR remote_bda); -extern void bta_hh_le_api_disc_act(tBTA_HH_DEV_CB *p_cb); -extern void bta_hh_le_get_dscp_act(tBTA_HH_DEV_CB *p_cb); -extern void bta_hh_le_write_dev_act(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern UINT8 bta_hh_le_add_device(tBTA_HH_DEV_CB *p_cb, tBTA_HH_MAINT_DEV *p_dev_info); -extern void bta_hh_le_remove_dev_bg_conn(tBTA_HH_DEV_CB *p_cb); -extern void bta_hh_le_open_fail(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_gatt_open(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_gatt_close(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_start_security(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_start_srvc_discovery(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_w4_le_read_char_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_le_read_char_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_w4_le_read_descr_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_le_read_descr_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_w4_le_write_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_le_write_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_le_write_char_descr_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_start_security(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_security_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_le_update_scpp(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); -extern void bta_hh_le_notify_enc_cmpl(tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_data); -extern void bta_hh_ci_load_rpt (tBTA_HH_DEV_CB *p_cb, tBTA_HH_DATA *p_buf); - -#if BTA_HH_DEBUG -extern void bta_hh_trace_dev_db(void); -#endif - -#endif ///defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE) -#endif - diff --git a/tools/sdk/include/bluedroid/bta_jv_api.h b/tools/sdk/include/bluedroid/bta_jv_api.h deleted file mode 100644 index a9279a846b4..00000000000 --- a/tools/sdk/include/bluedroid/bta_jv_api.h +++ /dev/null @@ -1,884 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2006-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the public interface file the BTA Java I/F - * - ******************************************************************************/ -#ifndef BTA_JV_API_H -#define BTA_JV_API_H - -#include "bt_target.h" -#include "bt_types.h" -#include "bta_api.h" -#include "btm_api.h" -#include "l2c_api.h" -#include "rfcdefs.h" -#include "sdp_api.h" - -#if (defined BTA_JV_INCLUDED && BTA_JV_INCLUDED == TRUE) -/***************************************************************************** -** Constants and data types -*****************************************************************************/ -/* status values */ -#define BTA_JV_SUCCESS 0 /* Successful operation. */ -#define BTA_JV_FAILURE 1 /* Generic failure. */ -#define BTA_JV_BUSY 2 /* Temporarily can not handle this request. */ -#define BTA_JV_NO_DATA 3 /* no data. */ -#define BTA_JV_NO_RESOURCE 4 /* No more set pm control block */ - -typedef UINT8 tBTA_JV_STATUS; -#define BTA_JV_INTERNAL_ERR (-1) /* internal error. */ - -#define BTA_JV_MAX_UUIDS SDP_MAX_UUID_FILTERS -#define BTA_JV_MAX_ATTRS SDP_MAX_ATTR_FILTERS -#define BTA_JV_MAX_SDP_REC SDP_MAX_RECORDS -#define BTA_JV_MAX_L2C_CONN GAP_MAX_CONNECTIONS /* GAP handle is used as index, hence do not change this value */ -#define BTA_JV_MAX_SCN PORT_MAX_RFC_PORTS /* same as BTM_MAX_SCN (in btm_int.h) */ -#define BTA_JV_MAX_RFC_CONN MAX_RFC_PORTS - -#ifndef BTA_JV_DEF_RFC_MTU -#define BTA_JV_DEF_RFC_MTU (3*330) -#endif - -#ifndef BTA_JV_MAX_RFC_SR_SESSION -#define BTA_JV_MAX_RFC_SR_SESSION MAX_BD_CONNECTIONS -#endif - -/* BTA_JV_MAX_RFC_SR_SESSION can not be bigger than MAX_BD_CONNECTIONS */ -#if (BTA_JV_MAX_RFC_SR_SESSION > MAX_BD_CONNECTIONS) -#undef BTA_JV_MAX_RFC_SR_SESSION -#define BTA_JV_MAX_RFC_SR_SESSION MAX_BD_CONNECTIONS -#endif - -#define BTA_JV_FIRST_SERVICE_ID BTA_FIRST_JV_SERVICE_ID -#define BTA_JV_LAST_SERVICE_ID BTA_LAST_JV_SERVICE_ID -#define BTA_JV_NUM_SERVICE_ID (BTA_LAST_JV_SERVICE_ID - BTA_FIRST_JV_SERVICE_ID + 1) - -/* Discoverable modes */ -enum { - BTA_JV_DISC_NONE, - BTA_JV_DISC_LIMITED, - BTA_JV_DISC_GENERAL -}; -typedef UINT16 tBTA_JV_DISC; - -#define BTA_JV_ROLE_SLAVE BTM_ROLE_SLAVE -#define BTA_JV_ROLE_MASTER BTM_ROLE_MASTER -typedef UINT32 tBTA_JV_ROLE; - -#define BTA_JV_SERVICE_LMTD_DISCOVER BTM_COD_SERVICE_LMTD_DISCOVER /* 0x0020 */ -#define BTA_JV_SERVICE_POSITIONING BTM_COD_SERVICE_POSITIONING /* 0x0100 */ -#define BTA_JV_SERVICE_NETWORKING BTM_COD_SERVICE_NETWORKING /* 0x0200 */ -#define BTA_JV_SERVICE_RENDERING BTM_COD_SERVICE_RENDERING /* 0x0400 */ -#define BTA_JV_SERVICE_CAPTURING BTM_COD_SERVICE_CAPTURING /* 0x0800 */ -#define BTA_JV_SERVICE_OBJ_TRANSFER BTM_COD_SERVICE_OBJ_TRANSFER /* 0x1000 */ -#define BTA_JV_SERVICE_AUDIO BTM_COD_SERVICE_AUDIO /* 0x2000 */ -#define BTA_JV_SERVICE_TELEPHONY BTM_COD_SERVICE_TELEPHONY /* 0x4000 */ -#define BTA_JV_SERVICE_INFORMATION BTM_COD_SERVICE_INFORMATION /* 0x8000 */ - -/* JV ID type */ -#define BTA_JV_PM_ID_1 1 /* PM example profile 1 */ -#define BTA_JV_PM_ID_2 2 /* PM example profile 2 */ -#define BTA_JV_PM_ID_CLEAR 0 /* Special JV ID used to clear PM profile */ -#define BTA_JV_PM_ALL 0xFF /* Generic match all id, see bta_dm_cfg.c */ -typedef UINT8 tBTA_JV_PM_ID; - -#define BTA_JV_PM_HANDLE_CLEAR 0xFF /* Special JV ID used to clear PM profile */ - -/* define maximum number of registered PM entities. should be in sync with bta pm! */ -#ifndef BTA_JV_PM_MAX_NUM -#define BTA_JV_PM_MAX_NUM 5 -#endif - -/* JV pm connection states */ -enum { - BTA_JV_CONN_OPEN = 0, /* Connection opened state */ - BTA_JV_CONN_CLOSE, /* Connection closed state */ - BTA_JV_APP_OPEN, /* JV Application opened state */ - BTA_JV_APP_CLOSE, /* JV Application closed state */ - BTA_JV_SCO_OPEN, /* SCO connection opened state */ - BTA_JV_SCO_CLOSE, /* SCO connection opened state */ - BTA_JV_CONN_IDLE, /* Connection idle state */ - BTA_JV_CONN_BUSY, /* Connection busy state */ - BTA_JV_MAX_CONN_STATE /* Max number of connection state */ -}; -typedef UINT8 tBTA_JV_CONN_STATE; - -/* JV Connection types */ -#define BTA_JV_CONN_TYPE_RFCOMM 0 -#define BTA_JV_CONN_TYPE_L2CAP 1 -#define BTA_JV_CONN_TYPE_L2CAP_LE 2 - -/* Java I/F callback events */ -/* events received by tBTA_JV_DM_CBACK */ -#define BTA_JV_ENABLE_EVT 0 /* JV enabled */ -#define BTA_JV_GET_SCN_EVT 6 /* Reserved an SCN */ -#define BTA_JV_GET_PSM_EVT 7 /* Reserved a PSM */ -#define BTA_JV_DISCOVERY_COMP_EVT 8 /* SDP discovery complete */ -#define BTA_JV_CREATE_RECORD_EVT 11 /* the result for BTA_JvCreateRecord */ -/* events received by tBTA_JV_L2CAP_CBACK */ -#define BTA_JV_L2CAP_OPEN_EVT 16 /* open status of L2CAP connection */ -#define BTA_JV_L2CAP_CLOSE_EVT 17 /* L2CAP connection closed */ -#define BTA_JV_L2CAP_START_EVT 18 /* L2CAP server started */ -#define BTA_JV_L2CAP_CL_INIT_EVT 19 /* L2CAP client initiated a connection */ -#define BTA_JV_L2CAP_DATA_IND_EVT 20 /* L2CAP connection received data */ -#define BTA_JV_L2CAP_CONG_EVT 21 /* L2CAP connection congestion status changed */ -#define BTA_JV_L2CAP_READ_EVT 22 /* the result for BTA_JvL2capRead */ -#define BTA_JV_L2CAP_RECEIVE_EVT 23 /* the result for BTA_JvL2capReceive*/ -#define BTA_JV_L2CAP_WRITE_EVT 24 /* the result for BTA_JvL2capWrite*/ -#define BTA_JV_L2CAP_WRITE_FIXED_EVT 25 /* the result for BTA_JvL2capWriteFixed */ - -/* events received by tBTA_JV_RFCOMM_CBACK */ -#define BTA_JV_RFCOMM_OPEN_EVT 26 /* open status of RFCOMM Client connection */ -#define BTA_JV_RFCOMM_CLOSE_EVT 27 /* RFCOMM connection closed */ -#define BTA_JV_RFCOMM_START_EVT 28 /* RFCOMM server started */ -#define BTA_JV_RFCOMM_CL_INIT_EVT 29 /* RFCOMM client initiated a connection */ -#define BTA_JV_RFCOMM_DATA_IND_EVT 30 /* RFCOMM connection received data */ -#define BTA_JV_RFCOMM_CONG_EVT 31 /* RFCOMM connection congestion status changed */ -#define BTA_JV_RFCOMM_READ_EVT 32 /* the result for BTA_JvRfcommRead */ -#define BTA_JV_RFCOMM_WRITE_EVT 33 /* the result for BTA_JvRfcommWrite*/ -#define BTA_JV_RFCOMM_SRV_OPEN_EVT 34 /* open status of Server RFCOMM connection */ -#define BTA_JV_MAX_EVT 35 /* max number of JV events */ - -typedef UINT16 tBTA_JV_EVT; - -/* data associated with BTA_JV_SET_DISCOVER_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - tBTA_JV_DISC disc_mode; /* The current discoverable mode */ -} tBTA_JV_SET_DISCOVER; - -/* data associated with BTA_JV_DISCOVERY_COMP_EVT_ */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT8 scn_num; /* num of channel */ - UINT8 scn[BTA_JV_MAX_SCN]; /* channel # */ -} tBTA_JV_DISCOVERY_COMP; - -/* data associated with BTA_JV_CREATE_RECORD_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The SDP handle */ -} tBTA_JV_CREATE_RECORD; - -/* data associated with BTA_JV_L2CAP_OPEN_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - BD_ADDR rem_bda; /* The peer address */ - INT32 tx_mtu; /* The transmit MTU */ -} tBTA_JV_L2CAP_OPEN; - -/* data associated with BTA_JV_L2CAP_OPEN_EVT for LE sockets */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - BD_ADDR rem_bda; /* The peer address */ - INT32 tx_mtu; /* The transmit MTU */ - void **p_p_cback; /* set them for new socket */ - void **p_user_data;/* set them for new socket */ - -} tBTA_JV_L2CAP_LE_OPEN; - - -/* data associated with BTA_JV_L2CAP_CLOSE_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - BOOLEAN async; /* FALSE, if local initiates disconnect */ -} tBTA_JV_L2CAP_CLOSE; - -/* data associated with BTA_JV_L2CAP_START_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT8 sec_id; /* security ID used by this server */ -} tBTA_JV_L2CAP_START; - -/* data associated with BTA_JV_L2CAP_CL_INIT_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT8 sec_id; /* security ID used by this client */ -} tBTA_JV_L2CAP_CL_INIT; - -/* data associated with BTA_JV_L2CAP_CONG_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - BOOLEAN cong; /* TRUE, congested. FALSE, uncongested */ -} tBTA_JV_L2CAP_CONG; - -/* data associated with BTA_JV_L2CAP_READ_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT32 req_id; /* The req_id in the associated BTA_JvL2capRead() */ - UINT8 *p_data; /* This points the same location as the p_data - * parameter in BTA_JvL2capRead () */ - UINT16 len; /* The length of the data read. */ -} tBTA_JV_L2CAP_READ; - -/* data associated with BTA_JV_L2CAP_RECEIVE_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT32 req_id; /* The req_id in the associated BTA_JvL2capReceive() */ - UINT8 *p_data; /* This points the same location as the p_data - * parameter in BTA_JvL2capReceive () */ - UINT16 len; /* The length of the data read. */ -} tBTA_JV_L2CAP_RECEIVE; - -/* data associated with BTA_JV_L2CAP_WRITE_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT32 req_id; /* The req_id in the associated BTA_JvL2capWrite() */ - UINT16 len; /* The length of the data written. */ - BOOLEAN cong; /* congestion status */ -} tBTA_JV_L2CAP_WRITE; - - -/* data associated with BTA_JV_L2CAP_WRITE_FIXED_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT16 channel; /* The connection channel */ - BD_ADDR addr; /* The peer address */ - UINT32 req_id; /* The req_id in the associated BTA_JvL2capWrite() */ - UINT16 len; /* The length of the data written. */ - BOOLEAN cong; /* congestion status */ -} tBTA_JV_L2CAP_WRITE_FIXED; - -/* data associated with BTA_JV_RFCOMM_OPEN_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - BD_ADDR rem_bda; /* The peer address */ -} tBTA_JV_RFCOMM_OPEN; -/* data associated with BTA_JV_RFCOMM_SRV_OPEN_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT32 new_listen_handle; /* The new listen handle */ - BD_ADDR rem_bda; /* The peer address */ -} tBTA_JV_RFCOMM_SRV_OPEN; - - -/* data associated with BTA_JV_RFCOMM_CLOSE_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 port_status; /* PORT status */ - UINT32 handle; /* The connection handle */ - BOOLEAN async; /* FALSE, if local initiates disconnect */ -} tBTA_JV_RFCOMM_CLOSE; - -/* data associated with BTA_JV_RFCOMM_START_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT8 sec_id; /* security ID used by this server */ - BOOLEAN use_co; /* TRUE to use co_rfc_data */ -} tBTA_JV_RFCOMM_START; - -/* data associated with BTA_JV_RFCOMM_CL_INIT_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT8 sec_id; /* security ID used by this client */ - BOOLEAN use_co; /* TRUE to use co_rfc_data */ -} tBTA_JV_RFCOMM_CL_INIT; -/*data associated with BTA_JV_L2CAP_DATA_IND_EVT & BTA_JV_RFCOMM_DATA_IND_EVT */ -typedef struct { - UINT32 handle; /* The connection handle */ - BT_HDR *p_buf; /* The incoming data */ -} tBTA_JV_DATA_IND; - -/*data associated with BTA_JV_L2CAP_DATA_IND_EVT if used for LE */ -typedef struct { - UINT32 handle; /* The connection handle */ - BT_HDR *p_buf; /* The incoming data */ -} tBTA_JV_LE_DATA_IND; - - -/* data associated with BTA_JV_RFCOMM_CONG_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - BOOLEAN cong; /* TRUE, congested. FALSE, uncongested */ -} tBTA_JV_RFCOMM_CONG; - -/* data associated with BTA_JV_RFCOMM_READ_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT32 req_id; /* The req_id in the associated BTA_JvRfcommRead() */ - UINT8 *p_data; /* This points the same location as the p_data - * parameter in BTA_JvRfcommRead () */ - UINT16 len; /* The length of the data read. */ -} tBTA_JV_RFCOMM_READ; - -/* data associated with BTA_JV_RFCOMM_WRITE_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Whether the operation succeeded or failed. */ - UINT32 handle; /* The connection handle */ - UINT32 req_id; /* The req_id in the associated BTA_JvRfcommWrite() */ - int len; /* The length of the data written. */ - BOOLEAN cong; /* congestion status */ -} tBTA_JV_RFCOMM_WRITE; - -/* data associated with BTA_JV_API_SET_PM_PROFILE_EVT */ -typedef struct { - tBTA_JV_STATUS status; /* Status of the operation */ - UINT32 handle; /* Connection handle */ - tBTA_JV_PM_ID app_id; /* JV app ID */ -} tBTA_JV_SET_PM_PROFILE; - -/* data associated with BTA_JV_API_NOTIFY_PM_STATE_CHANGE_EVT */ -typedef struct { - UINT32 handle; /* Connection handle */ - tBTA_JV_CONN_STATE state; /* JV connection stata */ -} tBTA_JV_NOTIFY_PM_STATE_CHANGE; - - -/* union of data associated with JV callback */ -typedef union { - tBTA_JV_STATUS status; /* BTA_JV_ENABLE_EVT */ - tBTA_JV_DISCOVERY_COMP disc_comp; /* BTA_JV_DISCOVERY_COMP_EVT */ - tBTA_JV_SET_DISCOVER set_discover; /* BTA_JV_SET_DISCOVER_EVT */ - UINT8 scn; /* BTA_JV_GET_SCN_EVT */ - UINT16 psm; /* BTA_JV_GET_PSM_EVT */ - tBTA_JV_CREATE_RECORD create_rec; /* BTA_JV_CREATE_RECORD_EVT */ - tBTA_JV_L2CAP_OPEN l2c_open; /* BTA_JV_L2CAP_OPEN_EVT */ - tBTA_JV_L2CAP_CLOSE l2c_close; /* BTA_JV_L2CAP_CLOSE_EVT */ - tBTA_JV_L2CAP_START l2c_start; /* BTA_JV_L2CAP_START_EVT */ - tBTA_JV_L2CAP_CL_INIT l2c_cl_init; /* BTA_JV_L2CAP_CL_INIT_EVT */ - tBTA_JV_L2CAP_CONG l2c_cong; /* BTA_JV_L2CAP_CONG_EVT */ - tBTA_JV_L2CAP_READ l2c_read; /* BTA_JV_L2CAP_READ_EVT */ - tBTA_JV_L2CAP_WRITE l2c_write; /* BTA_JV_L2CAP_WRITE_EVT */ - tBTA_JV_RFCOMM_OPEN rfc_open; /* BTA_JV_RFCOMM_OPEN_EVT */ - tBTA_JV_RFCOMM_SRV_OPEN rfc_srv_open; /* BTA_JV_RFCOMM_SRV_OPEN_EVT */ - tBTA_JV_RFCOMM_CLOSE rfc_close; /* BTA_JV_RFCOMM_CLOSE_EVT */ - tBTA_JV_RFCOMM_START rfc_start; /* BTA_JV_RFCOMM_START_EVT */ - tBTA_JV_RFCOMM_CL_INIT rfc_cl_init; /* BTA_JV_RFCOMM_CL_INIT_EVT */ - tBTA_JV_RFCOMM_CONG rfc_cong; /* BTA_JV_RFCOMM_CONG_EVT */ - tBTA_JV_RFCOMM_READ rfc_read; /* BTA_JV_RFCOMM_READ_EVT */ - tBTA_JV_RFCOMM_WRITE rfc_write; /* BTA_JV_RFCOMM_WRITE_EVT */ - tBTA_JV_DATA_IND data_ind; /* BTA_JV_L2CAP_DATA_IND_EVT - BTA_JV_RFCOMM_DATA_IND_EVT */ - tBTA_JV_LE_DATA_IND le_data_ind; /* BTA_JV_L2CAP_LE_DATA_IND_EVT */ - tBTA_JV_L2CAP_LE_OPEN l2c_le_open; /* BTA_JV_L2CAP_OPEN_EVT */ - tBTA_JV_L2CAP_WRITE_FIXED l2c_write_fixed; /* BTA_JV_L2CAP_WRITE_FIXED_EVT */ -} tBTA_JV; - -/* JAVA DM Interface callback */ -typedef void (tBTA_JV_DM_CBACK)(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data); - -/* JAVA RFCOMM interface callback */ -typedef void *(tBTA_JV_RFCOMM_CBACK)(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data); - -/* JAVA L2CAP interface callback */ -typedef void (tBTA_JV_L2CAP_CBACK)(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_Data); - -/* JV configuration structure */ -typedef struct { - UINT16 sdp_raw_size; /* The size of p_sdp_raw_data */ - UINT16 sdp_db_size; /* The size of p_sdp_db */ - UINT8 *p_sdp_raw_data; /* The data buffer to keep raw data */ - tSDP_DISCOVERY_DB *p_sdp_db; /* The data buffer to keep SDP database */ -} tBTA_JV_CFG; - -/******************************************************************************* -** -** Function BTA_JvEnable -** -** Description Enable the Java I/F service. When the enable -** operation is complete the callback function will be -** called with a BTA_JV_ENABLE_EVT. This function must -** be called before other functions in the JV API are -** called. -** -** Returns BTA_JV_SUCCESS if successful. -** BTA_JV_FAIL if internal failure. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvEnable(tBTA_JV_DM_CBACK *p_cback); - -/******************************************************************************* -** -** Function BTA_JvDisable -** -** Description Disable the Java I/F -** -** Returns void -** -*******************************************************************************/ -extern void BTA_JvDisable(void); - -/******************************************************************************* -** -** Function BTA_JvIsEnable -** -** Description Get the JV registration status. -** -** Returns TRUE, if registered -** -*******************************************************************************/ -extern BOOLEAN BTA_JvIsEnable(void); - -/******************************************************************************* -** -** Function BTA_JvIsEncrypted -** -** Description This function checks if the link to peer device is encrypted -** -** Returns TRUE if encrypted. -** FALSE if not. -** -*******************************************************************************/ -extern BOOLEAN BTA_JvIsEncrypted(BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTA_JvGetChannelId -** -** Description This function reserves a SCN/PSM for applications running -** over RFCOMM or L2CAP. It is primarily called by -** server profiles/applications to register their SCN/PSM into the -** SDP database. The SCN is reported by the tBTA_JV_DM_CBACK -** callback with a BTA_JV_GET_SCN_EVT. -** If the SCN/PSM reported is 0, that means all SCN resources are -** exhausted. -** The channel parameter can be used to request a specific -** channel. If the request on the specific channel fails, the -** SCN/PSM returned in the EVT will be 0 - no attempt to request -** a new channel will be made. set channel to <= 0 to automatically -** assign an channel ID. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvGetChannelId(int conn_type, void *user_data, - INT32 channel); - -/******************************************************************************* -** -** Function BTA_JvFreeChannel -** -** Description This function frees a SCN/PSM that was used -** by an application running over RFCOMM or L2CAP. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvFreeChannel(UINT16 channel, int conn_type); - -/******************************************************************************* -** -** Function BTA_JvStartDiscovery -** -** Description This function performs service discovery for the services -** provided by the given peer device. When the operation is -** complete the tBTA_JV_DM_CBACK callback function will be -** called with a BTA_JV_DISCOVERY_COMP_EVT. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvStartDiscovery(BD_ADDR bd_addr, UINT16 num_uuid, - tSDP_UUID *p_uuid_list, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvCreateRecordByUser -** -** Description Create a service record in the local SDP database by user in -** tBTA_JV_DM_CBACK callback with a BTA_JV_CREATE_RECORD_EVT. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvCreateRecordByUser(const char *name, UINT32 channel, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvDeleteRecord -** -** Description Delete a service record in the local SDP database. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvDeleteRecord(UINT32 handle); - -/******************************************************************************* -** -** Function BTA_JvL2capConnectLE -** -** Description Initiate a connection as an LE L2CAP client to the given BD -** Address. -** When the connection is initiated or failed to initiate, -** tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_CL_INIT_EVT -** When the connection is established or failed, -** tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_OPEN_EVT -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capConnectLE(tBTA_SEC sec_mask, tBTA_JV_ROLE role, - const tL2CAP_ERTM_INFO *ertm_info, UINT16 remote_chan, - UINT16 rx_mtu, tL2CAP_CFG_INFO *cfg, - BD_ADDR peer_bd_addr, tBTA_JV_L2CAP_CBACK *p_cback, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvL2capConnect -** -** Description Initiate a connection as a L2CAP client to the given BD -** Address. -** When the connection is initiated or failed to initiate, -** tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_CL_INIT_EVT -** When the connection is established or failed, -** tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_OPEN_EVT -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capConnect(tBTA_SEC sec_mask, tBTA_JV_ROLE role, - const tL2CAP_ERTM_INFO *ertm_info, UINT16 remote_psm, - UINT16 rx_mtu, tL2CAP_CFG_INFO *cfg, - BD_ADDR peer_bd_addr, tBTA_JV_L2CAP_CBACK *p_cback, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvL2capClose -** -** Description This function closes an L2CAP client connection -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capClose(UINT32 handle); - -/******************************************************************************* -** -** Function BTA_JvL2capCloseLE -** -** Description This function closes an L2CAP client connection for Fixed Channels -** Function is idempotent and no callbacks are called! -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capCloseLE(UINT32 handle); - -/******************************************************************************* -** -** Function BTA_JvL2capStartServer -** -** Description This function starts an L2CAP server and listens for an L2CAP -** connection from a remote Bluetooth device. When the server -** is started successfully, tBTA_JV_L2CAP_CBACK is called with -** BTA_JV_L2CAP_START_EVT. When the connection is established, -** tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_OPEN_EVT. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capStartServer(tBTA_SEC sec_mask, tBTA_JV_ROLE role, - const tL2CAP_ERTM_INFO *ertm_info, - UINT16 local_psm, UINT16 rx_mtu, tL2CAP_CFG_INFO *cfg, - tBTA_JV_L2CAP_CBACK *p_cback, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvL2capStartServerLE -** -** Description This function starts an LE L2CAP server and listens for an L2CAP -** connection from a remote Bluetooth device on a fixed channel -** over an LE link. When the server -** is started successfully, tBTA_JV_L2CAP_CBACK is called with -** BTA_JV_L2CAP_START_EVT. When the connection is established, -** tBTA_JV_L2CAP_CBACK is called with BTA_JV_L2CAP_OPEN_EVT. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capStartServerLE(tBTA_SEC sec_mask, tBTA_JV_ROLE role, - const tL2CAP_ERTM_INFO *ertm_info, - UINT16 local_chan, UINT16 rx_mtu, tL2CAP_CFG_INFO *cfg, - tBTA_JV_L2CAP_CBACK *p_cback, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvL2capStopServerLE -** -** Description This function stops the LE L2CAP server. If the server has an -** active connection, it would be closed. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capStopServerLE(UINT16 local_chan, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvL2capStopServerLE -** -** Description This function stops the LE L2CAP server. If the server has an -** active connection, it would be closed. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capStopServer(UINT16 local_psm, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvL2capRead -** -** Description This function reads data from an L2CAP connection -** When the operation is complete, tBTA_JV_L2CAP_CBACK is -** called with BTA_JV_L2CAP_READ_EVT. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capRead(UINT32 handle, UINT32 req_id, - UINT8 *p_data, UINT16 len); - -/******************************************************************************* -** -** Function BTA_JvL2capReceive -** -** Description This function reads data from an L2CAP connection -** When the operation is complete, tBTA_JV_L2CAP_CBACK is -** called with BTA_JV_L2CAP_RECEIVE_EVT. -** If there are more data queued in L2CAP than len, the extra data will be discarded. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capReceive(UINT32 handle, UINT32 req_id, - UINT8 *p_data, UINT16 len); - -/******************************************************************************* -** -** Function BTA_JvL2capReady -** -** Description This function determined if there is data to read from -** an L2CAP connection -** -** Returns BTA_JV_SUCCESS, if data queue size is in *p_data_size. -** BTA_JV_FAILURE, if error. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capReady(UINT32 handle, UINT32 *p_data_size); - -/******************************************************************************* -** -** Function BTA_JvL2capWrite -** -** Description This function writes data to an L2CAP connection -** When the operation is complete, tBTA_JV_L2CAP_CBACK is -** called with BTA_JV_L2CAP_WRITE_EVT. Works for -** PSM-based connections -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capWrite(UINT32 handle, UINT32 req_id, - UINT8 *p_data, UINT16 len, void *user_data); - - -/******************************************************************************* -** -** Function BTA_JvL2capWriteFixed -** -** Description This function writes data to an L2CAP connection -** When the operation is complete, tBTA_JV_L2CAP_CBACK is -** called with BTA_JV_L2CAP_WRITE_FIXED_EVT. Works for -** fixed-channel connections -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvL2capWriteFixed(UINT16 channel, BD_ADDR *addr, UINT32 req_id, - tBTA_JV_L2CAP_CBACK *p_cback, - UINT8 *p_data, UINT16 len, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvRfcommConnect -** -** Description This function makes an RFCOMM conection to a remote BD -** Address. -** When the connection is initiated or failed to initiate, -** tBTA_JV_RFCOMM_CBACK is called with BTA_JV_RFCOMM_CL_INIT_EVT -** When the connection is established or failed, -** tBTA_JV_RFCOMM_CBACK is called with BTA_JV_RFCOMM_OPEN_EVT -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvRfcommConnect(tBTA_SEC sec_mask, - tBTA_JV_ROLE role, UINT8 remote_scn, BD_ADDR peer_bd_addr, - tBTA_JV_RFCOMM_CBACK *p_cback, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvRfcommClose -** -** Description This function closes an RFCOMM connection -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvRfcommClose(UINT32 handle, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvRfcommStartServer -** -** Description This function starts listening for an RFCOMM connection -** request from a remote Bluetooth device. When the server is -** started successfully, tBTA_JV_RFCOMM_CBACK is called -** with BTA_JV_RFCOMM_START_EVT. -** When the connection is established, tBTA_JV_RFCOMM_CBACK -** is called with BTA_JV_RFCOMM_OPEN_EVT. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask, - tBTA_JV_ROLE role, UINT8 local_scn, UINT8 max_session, - tBTA_JV_RFCOMM_CBACK *p_cback, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvRfcommStopServer -** -** Description This function stops the RFCOMM server. If the server has an -** active connection, it would be closed. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvRfcommStopServer(UINT32 handle, void *user_data); - -/******************************************************************************* -** -** Function BTA_JvRfcommRead -** -** Description This function reads data from an RFCOMM connection -** When the operation is complete, tBTA_JV_RFCOMM_CBACK is -** called with BTA_JV_RFCOMM_READ_EVT. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvRfcommRead(UINT32 handle, UINT32 req_id, - UINT8 *p_data, UINT16 len); - -/******************************************************************************* -** -** Function BTA_JvRfcommReady -** -** Description This function determined if there is data to read from -** an RFCOMM connection -** -** Returns BTA_JV_SUCCESS, if data queue size is in *p_data_size. -** BTA_JV_FAILURE, if error. -** -*******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvRfcommReady(UINT32 handle, UINT32 *p_data_size); - -/******************************************************************************* -** -** Function BTA_JvRfcommWrite -** -** Description This function writes data to an RFCOMM connection -** When the operation is complete, tBTA_JV_RFCOMM_CBACK is -** called with BTA_JV_RFCOMM_WRITE_EVT. -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -// extern tBTA_JV_STATUS BTA_JvRfcommWrite(UINT32 handle, UINT32 req_id); -extern tBTA_JV_STATUS BTA_JvRfcommWrite(UINT32 handle, UINT32 req_id, int len, UINT8 *p_data); - -/******************************************************************************* - ** - ** Function BTA_JVSetPmProfile - ** - ** Description This function set or free power mode profile for different JV application - ** - ** Parameters: handle, JV handle from RFCOMM or L2CAP - ** app_id: app specific pm ID, can be BTA_JV_PM_ALL, see bta_dm_cfg.c for details - ** BTA_JV_PM_ID_CLEAR: removes pm management on the handle. init_st is ignored and - ** BTA_JV_CONN_CLOSE is called implicitely - ** init_st: state after calling this API. typically it should be BTA_JV_CONN_OPEN - ** - ** Returns BTA_JV_SUCCESS, if the request is being processed. - ** BTA_JV_FAILURE, otherwise. - ** - ** NOTE: BTA_JV_PM_ID_CLEAR: In general no need to be called as jv pm calls automatically - ** BTA_JV_CONN_CLOSE to remove in case of connection close! - ** - *******************************************************************************/ -extern tBTA_JV_STATUS BTA_JvSetPmProfile(UINT32 handle, tBTA_JV_PM_ID app_id, - tBTA_JV_CONN_STATE init_st); - -/******************************************************************************* -** -** Function BTA_JvRfcommGetPortHdl -** -** Description This function fetches the rfcomm port handle -** -** Returns BTA_JV_SUCCESS, if the request is being processed. -** BTA_JV_FAILURE, otherwise. -** -*******************************************************************************/ -UINT16 BTA_JvRfcommGetPortHdl(UINT32 handle); - -#endif ///defined BTA_JV_INCLUDED && BTA_JV_INCLUDED == TRUE -#endif /* BTA_JV_API_H */ diff --git a/tools/sdk/include/bluedroid/bta_jv_co.h b/tools/sdk/include/bluedroid/bta_jv_co.h deleted file mode 100644 index e68096c15ce..00000000000 --- a/tools/sdk/include/bluedroid/bta_jv_co.h +++ /dev/null @@ -1,55 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2007-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for java interface call-out functions. - * - ******************************************************************************/ -#ifndef BTA_JV_CO_H -#define BTA_JV_CO_H - -#include "bta_jv_api.h" - -#if (defined BTA_JV_INCLUDED && BTA_JV_INCLUDED == TRUE) -/***************************************************************************** -** Function Declarations -*****************************************************************************/ - - -/******************************************************************************* -** -** Function bta_jv_co_rfc_data -** -** Description This function is called by JV to send data to the java glue -** code when the RX data path is configured to use a call-out -** -** Returns void -** -*******************************************************************************/ - -extern int bta_co_rfc_data_incoming(void *user_data, BT_HDR *p_buf); -extern int bta_co_rfc_data_outgoing_size(void *user_data, int *size); -extern int bta_co_rfc_data_outgoing(void *user_data, UINT8 *buf, UINT16 size); - -extern int bta_co_l2cap_data_incoming(void *user_data, BT_HDR *p_buf); -extern int bta_co_l2cap_data_outgoing_size(void *user_data, int *size); -extern int bta_co_l2cap_data_outgoing(void *user_data, UINT8 *buf, UINT16 size); - -#endif ///defined BTA_JV_INCLUDED && BTA_JV_INCLUDED == TRUE -#endif /* BTA_DG_CO_H */ diff --git a/tools/sdk/include/bluedroid/bta_jv_int.h b/tools/sdk/include/bluedroid/bta_jv_int.h deleted file mode 100644 index 2ef9ace3efb..00000000000 --- a/tools/sdk/include/bluedroid/bta_jv_int.h +++ /dev/null @@ -1,429 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2006-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the private interface file for the BTA Java I/F - * - ******************************************************************************/ -#ifndef BTA_JV_INT_H -#define BTA_JV_INT_H - -#include "bta_sys.h" -#include "bta_api.h" -#include "bta_jv_api.h" -#include "rfcdefs.h" -#include "port_api.h" -#include "sdp_api.h" - -#include "bt_target.h" -#if (defined BTA_JV_INCLUDED && BTA_JV_INCLUDED == TRUE) -/***************************************************************************** -** Constants -*****************************************************************************/ - -enum { - /* these events are handled by the state machine */ - BTA_JV_API_ENABLE_EVT = BTA_SYS_EVT_START(BTA_ID_JV), - BTA_JV_API_DISABLE_EVT, - BTA_JV_API_GET_CHANNEL_EVT, - BTA_JV_API_FREE_SCN_EVT, - BTA_JV_API_START_DISCOVERY_EVT, - BTA_JV_API_CREATE_RECORD_EVT, - BTA_JV_API_DELETE_RECORD_EVT, - BTA_JV_API_L2CAP_CONNECT_EVT, - BTA_JV_API_L2CAP_CLOSE_EVT, - BTA_JV_API_L2CAP_START_SERVER_EVT, - BTA_JV_API_L2CAP_STOP_SERVER_EVT, - BTA_JV_API_L2CAP_READ_EVT, - BTA_JV_API_L2CAP_WRITE_EVT, - BTA_JV_API_RFCOMM_CONNECT_EVT, - BTA_JV_API_RFCOMM_CLOSE_EVT, - BTA_JV_API_RFCOMM_START_SERVER_EVT, - BTA_JV_API_RFCOMM_STOP_SERVER_EVT, - BTA_JV_API_RFCOMM_READ_EVT, - BTA_JV_API_RFCOMM_WRITE_EVT, - BTA_JV_API_SET_PM_PROFILE_EVT, - BTA_JV_API_PM_STATE_CHANGE_EVT, - BTA_JV_API_L2CAP_CONNECT_LE_EVT, - BTA_JV_API_L2CAP_START_SERVER_LE_EVT, - BTA_JV_API_L2CAP_STOP_SERVER_LE_EVT, - BTA_JV_API_L2CAP_WRITE_FIXED_EVT, - BTA_JV_API_L2CAP_CLOSE_FIXED_EVT, - BTA_JV_MAX_INT_EVT -}; - -#ifndef BTA_JV_RFC_EV_MASK -#define BTA_JV_RFC_EV_MASK (PORT_EV_RXCHAR | PORT_EV_TXEMPTY | PORT_EV_FC | PORT_EV_FCS) -#endif - -/* data type for BTA_JV_API_ENABLE_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_JV_DM_CBACK *p_cback; -} tBTA_JV_API_ENABLE; - -/* data type for BTA_JV_API_START_DISCOVERY_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - UINT16 num_uuid; - tSDP_UUID uuid_list[BTA_JV_MAX_UUIDS]; - UINT16 num_attr; - UINT16 attr_list[BTA_JV_MAX_ATTRS]; - void *user_data; /* piggyback caller's private data*/ -} tBTA_JV_API_START_DISCOVERY; - -enum { - BTA_JV_PM_FREE_ST = 0, /* empty PM slot */ - BTA_JV_PM_IDLE_ST, - BTA_JV_PM_BUSY_ST -}; - -/* BTA JV PM control block */ -typedef struct { - UINT32 handle; /* The connection handle */ - UINT8 state; /* state: see above enum */ - tBTA_JV_PM_ID app_id; /* JV app specific id indicating power table to use */ - BD_ADDR peer_bd_addr; /* Peer BD address */ -} tBTA_JV_PM_CB; - -enum { - BTA_JV_ST_NONE = 0, - BTA_JV_ST_CL_OPENING, - BTA_JV_ST_CL_OPEN, - BTA_JV_ST_CL_CLOSING, - BTA_JV_ST_SR_LISTEN, - BTA_JV_ST_SR_OPEN, - BTA_JV_ST_SR_CLOSING -} ; -typedef UINT8 tBTA_JV_STATE; -#define BTA_JV_ST_CL_MAX BTA_JV_ST_CL_CLOSING -/* JV L2CAP control block */ -typedef struct { - tBTA_JV_L2CAP_CBACK *p_cback; /* the callback function */ - UINT16 psm; /* the psm used for this server connection */ - tBTA_JV_STATE state; /* the state of this control block */ - tBTA_SERVICE_ID sec_id; /* service id */ - UINT32 handle; /* the handle reported to java app (same as gap handle) */ - BOOLEAN cong; /* TRUE, if congested */ - tBTA_JV_PM_CB *p_pm_cb; /* ptr to pm control block, NULL: unused */ - void *user_data; /* user data for callback from higher layers */ -} tBTA_JV_L2C_CB; - -#define BTA_JV_RFC_HDL_MASK 0xFF -#define BTA_JV_RFCOMM_MASK 0x80 -#define BTA_JV_ALL_APP_ID 0xFF -#define BTA_JV_RFC_HDL_TO_SIDX(r) (((r)&0xFF00) >> 8) -#define BTA_JV_RFC_H_S_TO_HDL(h, s) ((h)|(s<<8)) - -/* port control block */ -typedef struct { - UINT32 handle; /* the rfcomm session handle at jv */ - UINT16 port_handle;/* port handle */ - tBTA_JV_STATE state; /* the state of this control block */ - UINT8 max_sess; /* max sessions */ - void *user_data; /* piggyback caller's private data*/ - BOOLEAN cong; /* TRUE, if congested */ - tBTA_JV_PM_CB *p_pm_cb; /* ptr to pm control block, NULL: unused */ -} tBTA_JV_PCB; - -/* JV RFCOMM control block */ -typedef struct { - tBTA_JV_RFCOMM_CBACK *p_cback; /* the callback function */ - UINT16 rfc_hdl[BTA_JV_MAX_RFC_SR_SESSION]; - tBTA_SERVICE_ID sec_id; /* service id */ - UINT8 handle; /* index: the handle reported to java app */ - UINT8 scn; /* the scn of the server */ - UINT8 max_sess; /* max sessions */ - int curr_sess; /* current sessions count*/ -} tBTA_JV_RFC_CB; - -/* data type for BTA_JV_API_L2CAP_CONNECT_EVT & BTA_JV_API_L2CAP_CONNECT_LE_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_SEC sec_mask; - tBTA_JV_ROLE role; - union { - UINT16 remote_psm; - UINT16 remote_chan; - }; - UINT16 rx_mtu; - BD_ADDR peer_bd_addr; - INT32 has_cfg; - tL2CAP_CFG_INFO cfg; - INT32 has_ertm_info; - tL2CAP_ERTM_INFO ertm_info; - tBTA_JV_L2CAP_CBACK *p_cback; - void *user_data; -} tBTA_JV_API_L2CAP_CONNECT; - -/* data type for BTA_JV_API_L2CAP_SERVER_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_SEC sec_mask; - tBTA_JV_ROLE role; - union { - UINT16 local_psm; - UINT16 local_chan; - }; - UINT16 rx_mtu; - INT32 has_cfg; - tL2CAP_CFG_INFO cfg; - INT32 has_ertm_info; - tL2CAP_ERTM_INFO ertm_info; - tBTA_JV_L2CAP_CBACK *p_cback; - void *user_data; -} tBTA_JV_API_L2CAP_SERVER; - -/* data type for BTA_JV_API_L2CAP_CLOSE_EVT */ -typedef struct { - BT_HDR hdr; - UINT32 handle; - tBTA_JV_L2C_CB *p_cb; -} tBTA_JV_API_L2CAP_CLOSE; - -/* data type for BTA_JV_API_L2CAP_READ_EVT */ -typedef struct { - BT_HDR hdr; - UINT32 handle; - UINT32 req_id; - tBTA_JV_L2CAP_CBACK *p_cback; - UINT8 *p_data; - UINT16 len; - void *user_data; -} tBTA_JV_API_L2CAP_READ; - -/* data type for BTA_JV_API_L2CAP_WRITE_EVT */ -typedef struct { - BT_HDR hdr; - UINT32 handle; - UINT32 req_id; - tBTA_JV_L2C_CB *p_cb; - UINT8 *p_data; - UINT16 len; - void *user_data; -} tBTA_JV_API_L2CAP_WRITE; - -/* data type for BTA_JV_API_L2CAP_WRITE_FIXED_EVT */ -typedef struct { - BT_HDR hdr; - UINT16 channel; - BD_ADDR addr; - UINT32 req_id; - tBTA_JV_L2CAP_CBACK *p_cback; - UINT8 *p_data; - UINT16 len; - void *user_data; -} tBTA_JV_API_L2CAP_WRITE_FIXED; - -/* data type for BTA_JV_API_RFCOMM_CONNECT_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_SEC sec_mask; - tBTA_JV_ROLE role; - UINT8 remote_scn; - BD_ADDR peer_bd_addr; - tBTA_JV_RFCOMM_CBACK *p_cback; - void *user_data; -} tBTA_JV_API_RFCOMM_CONNECT; - -/* data type for BTA_JV_API_RFCOMM_SERVER_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_SEC sec_mask; - tBTA_JV_ROLE role; - UINT8 local_scn; - UINT8 max_session; - UINT32 handle; - tBTA_JV_RFCOMM_CBACK *p_cback; - void *user_data; -} tBTA_JV_API_RFCOMM_SERVER; - -/* data type for BTA_JV_API_RFCOMM_READ_EVT */ -typedef struct { - BT_HDR hdr; - UINT32 handle; - UINT32 req_id; - UINT8 *p_data; - UINT16 len; - tBTA_JV_RFC_CB *p_cb; - tBTA_JV_PCB *p_pcb; -} tBTA_JV_API_RFCOMM_READ; - -/* data type for BTA_JV_API_SET_PM_PROFILE_EVT */ -typedef struct { - BT_HDR hdr; - UINT32 handle; - tBTA_JV_PM_ID app_id; - tBTA_JV_CONN_STATE init_st; -} tBTA_JV_API_SET_PM_PROFILE; - -/* data type for BTA_JV_API_PM_STATE_CHANGE_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_JV_PM_CB *p_cb; - tBTA_JV_CONN_STATE state; -} tBTA_JV_API_PM_STATE_CHANGE; - -/* data type for BTA_JV_API_RFCOMM_WRITE_EVT */ -typedef struct { - BT_HDR hdr; - UINT32 handle; - UINT32 req_id; - UINT8 *p_data; - int len; - tBTA_JV_RFC_CB *p_cb; - tBTA_JV_PCB *p_pcb; -} tBTA_JV_API_RFCOMM_WRITE; - -/* data type for BTA_JV_API_RFCOMM_CLOSE_EVT */ -typedef struct { - BT_HDR hdr; - UINT32 handle; - tBTA_JV_RFC_CB *p_cb; - tBTA_JV_PCB *p_pcb; - void *user_data; -} tBTA_JV_API_RFCOMM_CLOSE; - -/* data type for BTA_JV_API_CREATE_RECORD_EVT */ -typedef struct { - BT_HDR hdr; -#define ESP_SDP_SERVER_NAME_MAX (32) - char name[ESP_SDP_SERVER_NAME_MAX + 1]; - INT32 channel; - void *user_data; -} tBTA_JV_API_CREATE_RECORD; - -/* data type for BTA_JV_API_ADD_ATTRIBUTE_EVT */ -typedef struct { - BT_HDR hdr; - UINT32 handle; - UINT16 attr_id; - UINT8 *p_value; - INT32 value_size; -} tBTA_JV_API_ADD_ATTRIBUTE; - -/* data type for BTA_JV_API_FREE_SCN_EVT */ -typedef struct { - BT_HDR hdr; - INT32 type; /* One of BTA_JV_CONN_TYPE_ */ - UINT16 scn; -} tBTA_JV_API_FREE_CHANNEL; - -/* data type for BTA_JV_API_ALLOC_CHANNEL_EVT */ -typedef struct { - BT_HDR hdr; - INT32 type; /* One of BTA_JV_CONN_TYPE_ */ - INT32 channel; /* optionally request a specific channel */ - void *user_data; -} tBTA_JV_API_ALLOC_CHANNEL; -/* union of all data types */ -typedef union { - /* GKI event buffer header */ - BT_HDR hdr; - tBTA_JV_API_ENABLE enable; - tBTA_JV_API_START_DISCOVERY start_discovery; - tBTA_JV_API_ALLOC_CHANNEL alloc_channel; - tBTA_JV_API_FREE_CHANNEL free_channel; - tBTA_JV_API_CREATE_RECORD create_record; - tBTA_JV_API_ADD_ATTRIBUTE add_attr; - tBTA_JV_API_L2CAP_CONNECT l2cap_connect; - tBTA_JV_API_L2CAP_READ l2cap_read; - tBTA_JV_API_L2CAP_WRITE l2cap_write; - tBTA_JV_API_L2CAP_CLOSE l2cap_close; - tBTA_JV_API_L2CAP_SERVER l2cap_server; - tBTA_JV_API_RFCOMM_CONNECT rfcomm_connect; - tBTA_JV_API_RFCOMM_READ rfcomm_read; - tBTA_JV_API_RFCOMM_WRITE rfcomm_write; - tBTA_JV_API_SET_PM_PROFILE set_pm; - tBTA_JV_API_PM_STATE_CHANGE change_pm_state; - tBTA_JV_API_RFCOMM_CLOSE rfcomm_close; - tBTA_JV_API_RFCOMM_SERVER rfcomm_server; - tBTA_JV_API_L2CAP_WRITE_FIXED l2cap_write_fixed; -} tBTA_JV_MSG; - -/* JV control block */ -typedef struct { - /* the SDP handle reported to JV user is the (index + 1) to sdp_handle[]. - * if sdp_handle[i]==0, it's not used. - * otherwise sdp_handle[i] is the stack SDP handle. */ - UINT32 sdp_handle[BTA_JV_MAX_SDP_REC]; /* SDP records created */ - UINT8 *p_sel_raw_data;/* the raw data of last service select */ - tBTA_JV_DM_CBACK *p_dm_cback; - tBTA_JV_L2C_CB l2c_cb[BTA_JV_MAX_L2C_CONN]; /* index is GAP handle (index) */ - tBTA_JV_RFC_CB rfc_cb[BTA_JV_MAX_RFC_CONN]; - tBTA_JV_PCB port_cb[MAX_RFC_PORTS]; /* index of this array is - the port_handle, */ - UINT8 sec_id[BTA_JV_NUM_SERVICE_ID]; /* service ID */ - BOOLEAN scn[BTA_JV_MAX_SCN]; /* SCN allocated by java */ - UINT16 free_psm_list[BTA_JV_MAX_L2C_CONN]; /* PSMs freed by java - (can be reused) */ - UINT8 sdp_active; /* see BTA_JV_SDP_ACT_* */ - tSDP_UUID uuid; /* current uuid of sdp discovery*/ - tBTA_JV_PM_CB pm_cb[BTA_JV_PM_MAX_NUM]; /* PM on a per JV handle bases */ -} tBTA_JV_CB; - -enum { - BTA_JV_SDP_ACT_NONE = 0, - BTA_JV_SDP_ACT_YES, /* waiting for SDP result */ - BTA_JV_SDP_ACT_CANCEL /* waiting for cancel complete */ -}; - -/* JV control block */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_JV_CB bta_jv_cb; -#else -extern tBTA_JV_CB *bta_jv_cb_ptr; -#define bta_jv_cb (*bta_jv_cb_ptr) -#endif - -/* config struct */ -extern tBTA_JV_CFG *p_bta_jv_cfg; - -extern BOOLEAN bta_jv_sm_execute(BT_HDR *p_msg); - -extern void bta_jv_enable (tBTA_JV_MSG *p_data); -extern void bta_jv_disable (tBTA_JV_MSG *p_data); -extern void bta_jv_get_channel_id (tBTA_JV_MSG *p_data); -extern void bta_jv_free_scn (tBTA_JV_MSG *p_data); -extern void bta_jv_start_discovery (tBTA_JV_MSG *p_data); -extern void bta_jv_create_record (tBTA_JV_MSG *p_data); -extern void bta_jv_delete_record (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_connect (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_close (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_start_server (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_stop_server (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_read (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_write (tBTA_JV_MSG *p_data); -extern void bta_jv_rfcomm_connect (tBTA_JV_MSG *p_data); -extern void bta_jv_rfcomm_close (tBTA_JV_MSG *p_data); -extern void bta_jv_rfcomm_start_server (tBTA_JV_MSG *p_data); -extern void bta_jv_rfcomm_stop_server (tBTA_JV_MSG *p_data); -extern void bta_jv_rfcomm_read (tBTA_JV_MSG *p_data); -extern void bta_jv_rfcomm_write (tBTA_JV_MSG *p_data); -extern void bta_jv_set_pm_profile (tBTA_JV_MSG *p_data); -extern void bta_jv_change_pm_state(tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_connect_le (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_start_server_le (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_stop_server_le (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_write_fixed (tBTA_JV_MSG *p_data); -extern void bta_jv_l2cap_close_fixed (tBTA_JV_MSG *p_data); - -#endif ///defined BTA_JV_INCLUDED && BTA_JV_INCLUDED == TRUE -#endif /* BTA_JV_INT_H */ diff --git a/tools/sdk/include/bluedroid/bta_sdp_api.h b/tools/sdk/include/bluedroid/bta_sdp_api.h deleted file mode 100644 index 6f27f5ccb0a..00000000000 --- a/tools/sdk/include/bluedroid/bta_sdp_api.h +++ /dev/null @@ -1,147 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the public interface file for the BTA SDP I/F - * - ******************************************************************************/ -#ifndef BTA_SDP_API_H -#define BTA_SDP_API_H - -#include "bt_sdp.h" -#include "bt_target.h" -#include "bt_types.h" -#include "bta_api.h" -#include "btm_api.h" - -#if (SDP_INCLUDED == TRUE) -/* status values */ -#define BTA_SDP_SUCCESS 0 /* Successful operation. */ -#define BTA_SDP_FAILURE 1 /* Generic failure. */ -#define BTA_SDP_BUSY 2 /* Temporarily can not handle this request. */ - -typedef UINT8 tBTA_SDP_STATUS; - -/* SDP I/F callback events */ -/* events received by tBTA_SDP_DM_CBACK */ -#define BTA_SDP_ENABLE_EVT 0 /* SDP service i/f enabled*/ -#define BTA_SDP_SEARCH_EVT 1 /* SDP Service started */ -#define BTA_SDP_SEARCH_COMP_EVT 2 /* SDP search complete */ -#define BTA_SDP_CREATE_RECORD_USER_EVT 3 /* SDP search complete */ -#define BTA_SDP_REMOVE_RECORD_USER_EVT 4 /* SDP search complete */ -#define BTA_SDP_MAX_EVT 5 /* max number of SDP events */ - -#define BTA_SDP_MAX_RECORDS 15 - -typedef UINT16 tBTA_SDP_EVT; - -/* data associated with BTA_SDP_DISCOVERY_COMP_EVT */ -typedef struct { - tBTA_SDP_STATUS status; - BD_ADDR remote_addr; - tBT_UUID uuid; - int record_count; - bluetooth_sdp_record records[BTA_SDP_MAX_RECORDS]; -} tBTA_SDP_SEARCH_COMP; - -typedef union { - tBTA_SDP_STATUS status; /* BTA_SDP_SEARCH_EVT */ - tBTA_SDP_SEARCH_COMP sdp_search_comp; /* BTA_SDP_SEARCH_COMP_EVT */ -} tBTA_SDP; - -/* SDP DM Interface callback */ -typedef void (tBTA_SDP_DM_CBACK)(tBTA_SDP_EVT event, tBTA_SDP *p_data, void *user_data); - -/* MCE configuration structure */ -typedef struct { - UINT16 sdp_db_size; /* The size of p_sdp_db */ -#if (SDP_INCLUDED == TRUE) - tSDP_DISCOVERY_DB *p_sdp_db; /* The data buffer to keep SDP database */ -#endif ///SDP_INCLUDED == TRUE -} tBTA_SDP_CFG; - -#ifdef __cplusplus -extern "C" -{ -#endif -/******************************************************************************* -** -** Function BTA_SdpEnable -** -** Description Enable the SDP I/F service. When the enable -** operation is complete the callback function will be -** called with a BTA_SDP_ENABLE_EVT. This function must -** be called before other functions in the MCE API are -** called. -** -** Returns BTA_SDP_SUCCESS if successful. -** BTA_SDP_FAIL if internal failure. -** -*******************************************************************************/ -extern tBTA_SDP_STATUS BTA_SdpEnable(tBTA_SDP_DM_CBACK *p_cback); - -/******************************************************************************* -** -** Function BTA_SdpSearch -** -** Description Start a search for sdp records for a specific BD_ADDR with a -** specific profile uuid. -** When the search operation is completed, the callback function -** will be called with a BTA_SDP_SEARCH_EVT. -** Returns BTA_SDP_SUCCESS if successful. -** BTA_SDP_FAIL if internal failure. -** -*******************************************************************************/ -extern tBTA_SDP_STATUS BTA_SdpSearch(BD_ADDR bd_addr, tSDP_UUID *uuid); - -/******************************************************************************* -** -** Function BTA_SdpCreateRecordByUser -** -** Description This function is used to request a callback to create a SDP -** record. The registered callback will be called with event -** BTA_SDP_CREATE_RECORD_USER_EVT. -** -** Returns BTA_SDP_SUCCESS, if the request is being processed. -** BTA_SDP_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_SDP_STATUS BTA_SdpCreateRecordByUser(void *user_data); - -/******************************************************************************* -** -** Function BTA_SdpRemoveRecordByUser -** -** Description This function is used to request a callback to remove a SDP -** record. The registered callback will be called with event -** BTA_SDP_REMOVE_RECORD_USER_EVT. -** -** Returns BTA_SDP_SUCCESS, if the request is being processed. -** BTA_SDP_FAILURE, otherwise. -** -*******************************************************************************/ -extern tBTA_SDP_STATUS BTA_SdpRemoveRecordByUser(void *user_data); - -#ifdef __cplusplus -} -#endif - -#endif ///SDP_INCLUDED == TRUE - -#endif /* BTA_SDP_API_H */ diff --git a/tools/sdk/include/bluedroid/bta_sdp_int.h b/tools/sdk/include/bluedroid/bta_sdp_int.h deleted file mode 100644 index 9dee3fc9631..00000000000 --- a/tools/sdk/include/bluedroid/bta_sdp_int.h +++ /dev/null @@ -1,112 +0,0 @@ - - -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the private interface file for the BTA SDP I/F - * - ******************************************************************************/ -#ifndef BTA_SDP_INT_H -#define BTA_SDP_INT_H - -#include "bta_sys.h" -#include "bta_api.h" -#include "bta_sdp_api.h" - -#if (SDP_INCLUDED == TRUE) -/***************************************************************************** -** Constants -*****************************************************************************/ - -enum { - /* these events are handled by the state machine */ - BTA_SDP_API_ENABLE_EVT = BTA_SYS_EVT_START(BTA_ID_SDP), - BTA_SDP_API_SEARCH_EVT, - BTA_SDP_API_CREATE_RECORD_USER_EVT, - BTA_SDP_API_REMOVE_RECORD_USER_EVT, - BTA_SDP_MAX_INT_EVT -}; - -enum { - BTA_SDP_ACTIVE_NONE = 0, - BTA_SDP_ACTIVE_YES /* waiting for SDP result */ -}; - - - -/* data type for BTA_SDP_API_ENABLE_EVT */ -typedef struct { - BT_HDR hdr; - tBTA_SDP_DM_CBACK *p_cback; -} tBTA_SDP_API_ENABLE; - -/* data type for BTA_SDP_API_SEARCH_EVT */ -typedef struct { - BT_HDR hdr; - BD_ADDR bd_addr; - tSDP_UUID uuid; -} tBTA_SDP_API_SEARCH; - -/* data type for BTA_SDP_API_SEARCH_EVT */ -typedef struct { - BT_HDR hdr; - void *user_data; -} tBTA_SDP_API_RECORD_USER; - -/* union of all data types */ -typedef union { - /* event buffer header */ - BT_HDR hdr; - tBTA_SDP_API_ENABLE enable; - tBTA_SDP_API_SEARCH get_search; - tBTA_SDP_API_RECORD_USER record; -} tBTA_SDP_MSG; - -/* SDP control block */ -typedef struct { - UINT8 sdp_active; /* see BTA_SDP_SDP_ACT_* */ - BD_ADDR remote_addr; - tBTA_SDP_DM_CBACK *p_dm_cback; -} tBTA_SDP_CB; - - -/* SDP control block */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_SDP_CB bta_sdp_cb; -#else -extern tBTA_SDP_CB *bta_sdp_cb_ptr; -#define bta_sdp_cb (*bta_sdp_cb_ptr) -#endif - -/* config struct */ -extern tBTA_SDP_CFG *p_bta_sdp_cfg; - -extern BOOLEAN bta_sdp_sm_execute(BT_HDR *p_msg); - -extern void bta_sdp_enable (tBTA_SDP_MSG *p_data); -extern void bta_sdp_search (tBTA_SDP_MSG *p_data); -extern void bta_sdp_create_record(tBTA_SDP_MSG *p_data); -extern void bta_sdp_remove_record(tBTA_SDP_MSG *p_data); - -#endif ///SDP_INCLUDED == TRUE - -#endif /* BTA_SDP_INT_H */ - diff --git a/tools/sdk/include/bluedroid/bta_sys.h b/tools/sdk/include/bluedroid/bta_sys.h deleted file mode 100644 index 01190086939..00000000000 --- a/tools/sdk/include/bluedroid/bta_sys.h +++ /dev/null @@ -1,283 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the public interface file for the BTA system manager. - * - ******************************************************************************/ -#ifndef BTA_SYS_H -#define BTA_SYS_H - -#include "bt_target.h" -#include "bt_defs.h" - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ - -/* vendor specific event handler function type */ -typedef BOOLEAN (tBTA_SYS_VS_EVT_HDLR)(UINT16 evt, void *p); - -/* event handler function type */ -typedef BOOLEAN (tBTA_SYS_EVT_HDLR)(BT_HDR *p_msg); - -/* disable function type */ -typedef void (tBTA_SYS_DISABLE)(void); - - -/* HW modules */ -enum { - BTA_SYS_HW_BLUETOOTH, - BTA_SYS_HW_RT, - - BTA_SYS_MAX_HW_MODULES -}; - -typedef UINT16 tBTA_SYS_HW_MODULE; - -#ifndef BTA_DM_NUM_JV_ID -#define BTA_DM_NUM_JV_ID 2 -#endif - -/* SW sub-systems */ -#define BTA_ID_SYS 0 /* system manager */ -/* BLUETOOTH PART - from 0 to BTA_ID_BLUETOOTH_MAX */ -#define BTA_ID_DM 1 /* device manager */ -#define BTA_ID_DM_SEARCH 2 /* device manager search */ -#define BTA_ID_DM_SEC 3 /* device manager security */ -#define BTA_ID_DG 4 /* data gateway */ -#define BTA_ID_AG 5 /* audio gateway */ -#define BTA_ID_OPC 6 /* object push client */ -#define BTA_ID_OPS 7 /* object push server */ -#define BTA_ID_FTS 8 /* file transfer server */ -#define BTA_ID_CT 9 /* cordless telephony terminal */ -#define BTA_ID_FTC 10 /* file transfer client */ -#define BTA_ID_SS 11 /* synchronization server */ -#define BTA_ID_PR 12 /* Printer client */ -#define BTA_ID_BIC 13 /* Basic Imaging Client */ -#define BTA_ID_PAN 14 /* Personal Area Networking */ -#define BTA_ID_BIS 15 /* Basic Imaging Server */ -#define BTA_ID_ACC 16 /* Advanced Camera Client */ -#define BTA_ID_SC 17 /* SIM Card Access server */ -#define BTA_ID_AV 18 /* Advanced audio/video */ -#define BTA_ID_AVK 19 /* Audio/video sink */ -#define BTA_ID_HD 20 /* HID Device */ -#define BTA_ID_CG 21 /* Cordless Gateway */ -#define BTA_ID_BP 22 /* Basic Printing Client */ -#define BTA_ID_HH 23 /* Human Interface Device Host */ -#define BTA_ID_PBS 24 /* Phone Book Access Server */ -#define BTA_ID_PBC 25 /* Phone Book Access Client */ -#define BTA_ID_JV 26 /* Java */ -#define BTA_ID_HS 27 /* Headset */ -#define BTA_ID_MSE 28 /* Message Server Equipment */ -#define BTA_ID_MCE 29 /* Message Client Equipment */ -#define BTA_ID_HL 30 /* Health Device Profile*/ -#define BTA_ID_GATTC 31 /* GATT Client */ -#define BTA_ID_GATTS 32 /* GATT Client */ -#define BTA_ID_SDP 33 /* SDP Client */ -#define BTA_ID_BLUETOOTH_MAX 34 /* last BT profile */ - -/* GENERIC */ -#define BTA_ID_PRM 38 -#define BTA_ID_SYSTEM 39 /* platform-specific */ -#define BTA_ID_SWRAP 40 /* Insight script wrapper */ -#define BTA_ID_MIP 41 /* Multicase Individual Polling */ -#define BTA_ID_RT 42 /* Audio Routing module: This module is always on. */ - - -/* JV */ -#define BTA_ID_JV1 44 /* JV1 */ -#define BTA_ID_JV2 45 /* JV2 */ - -#define BTA_ID_MAX (44 + BTA_DM_NUM_JV_ID) - -typedef UINT8 tBTA_SYS_ID; - - -#define BTA_SYS_CONN_OPEN 0x00 -#define BTA_SYS_CONN_CLOSE 0x01 -#define BTA_SYS_APP_OPEN 0x02 -#define BTA_SYS_APP_CLOSE 0x03 -#define BTA_SYS_SCO_OPEN 0x04 -#define BTA_SYS_SCO_CLOSE 0x05 -#define BTA_SYS_CONN_IDLE 0x06 -#define BTA_SYS_CONN_BUSY 0x07 - -/* for link policy */ -#define BTA_SYS_PLCY_SET 0x10 /* set the link policy to the given addr */ -#define BTA_SYS_PLCY_CLR 0x11 /* clear the link policy to the given addr */ -#define BTA_SYS_PLCY_DEF_SET 0x12 /* set the default link policy */ -#define BTA_SYS_PLCY_DEF_CLR 0x13 /* clear the default link policy */ -#define BTA_SYS_ROLE_CHANGE 0x14 /* role change */ - -typedef UINT8 tBTA_SYS_CONN_STATUS; - -/* Bitmask of sys features */ -#define BTA_SYS_FEAT_PCM2 0x0001 -#define BTA_SYS_FEAT_PCM2_MASTER 0x0002 - -/* tBTA_PREF_ROLES */ -typedef UINT8 tBTA_SYS_PREF_ROLES; - -/* conn callback for role / low power manager*/ -typedef void (tBTA_SYS_CONN_CBACK)(tBTA_SYS_CONN_STATUS status, UINT8 id, UINT8 app_id, BD_ADDR peer_addr); - -/* conn callback for role / low power manager*/ -typedef void (tBTA_SYS_SSR_CFG_CBACK)(UINT8 id, UINT8 app_id, UINT16 latency, UINT16 tout); - -#if (BTA_EIR_CANNED_UUID_LIST != TRUE) -/* eir callback for adding/removeing UUID */ -typedef void (tBTA_SYS_EIR_CBACK)(UINT16 uuid16, BOOLEAN adding); -#endif - -/* registration structure */ -typedef struct { - tBTA_SYS_EVT_HDLR *evt_hdlr; - tBTA_SYS_DISABLE *disable; -} tBTA_SYS_REG; - -/* data type to send events to BTA SYS HW manager */ -typedef struct { - BT_HDR hdr; - tBTA_SYS_HW_MODULE hw_module; -} tBTA_SYS_HW_MSG; - -/***************************************************************************** -** Global data -*****************************************************************************/ - -/* trace level */ -extern UINT8 appl_trace_level; - -/***************************************************************************** -** Macros -*****************************************************************************/ - -/* Calculate start of event enumeration; id is top 8 bits of event */ -#define BTA_SYS_EVT_START(id) ((id) << 8) - -/***************************************************************************** -** events for BTA SYS HW manager -*****************************************************************************/ - -/* events sent to SYS HW manager - must be kept synchronized with tables in bta_sys_main.c */ -enum { - /* device manager local device API events */ - BTA_SYS_API_ENABLE_EVT = BTA_SYS_EVT_START(BTA_ID_SYS), - BTA_SYS_EVT_ENABLED_EVT, - BTA_SYS_EVT_STACK_ENABLED_EVT, - BTA_SYS_API_DISABLE_EVT, - BTA_SYS_EVT_DISABLED_EVT, - BTA_SYS_ERROR_EVT, - - BTA_SYS_MAX_EVT -}; - - - -/* SYS HW status events - returned by SYS HW manager to other modules. */ -enum { - BTA_SYS_HW_OFF_EVT, - BTA_SYS_HW_ON_EVT, - BTA_SYS_HW_STARTING_EVT, - BTA_SYS_HW_STOPPING_EVT, - BTA_SYS_HW_ERROR_EVT - -}; -typedef UINT8 tBTA_SYS_HW_EVT; - -/* HW enable callback type */ -typedef void (tBTA_SYS_HW_CBACK)(tBTA_SYS_HW_EVT status); - -/***************************************************************************** -** Function declarations -*****************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -extern void bta_sys_init(void); -extern void bta_sys_free(void); -extern void bta_sys_event(BT_HDR *p_msg); -extern void bta_sys_set_trace_level(UINT8 level); -extern void bta_sys_register(UINT8 id, const tBTA_SYS_REG *p_reg); -extern void bta_sys_deregister(UINT8 id); -extern BOOLEAN bta_sys_is_register(UINT8 id); -extern UINT16 bta_sys_get_sys_features(void); -extern void bta_sys_sendmsg(void *p_msg); -extern void bta_sys_start_timer(TIMER_LIST_ENT *p_tle, UINT16 type, INT32 timeout_ms); -extern void bta_sys_stop_timer(TIMER_LIST_ENT *p_tle); -extern void bta_sys_free_timer(TIMER_LIST_ENT *p_tle); -extern void bta_sys_disable(tBTA_SYS_HW_MODULE module); -extern UINT32 bta_sys_get_remaining_ticks(TIMER_LIST_ENT *p_target_tle); - -extern void bta_sys_hw_register( tBTA_SYS_HW_MODULE module, tBTA_SYS_HW_CBACK *cback); -extern void bta_sys_hw_unregister( tBTA_SYS_HW_MODULE module ); - - -extern void bta_sys_rm_register(tBTA_SYS_CONN_CBACK *p_cback); -extern void bta_sys_pm_register(tBTA_SYS_CONN_CBACK *p_cback); - -extern void bta_sys_policy_register(tBTA_SYS_CONN_CBACK *p_cback); -extern void bta_sys_sco_register(tBTA_SYS_CONN_CBACK *p_cback); - - -extern void bta_sys_conn_open(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_conn_close(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_app_open(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_app_close(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_sco_open(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_sco_close(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_sco_use(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_sco_unuse(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_idle(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); -extern void bta_sys_busy(UINT8 id, UINT8 app_id, BD_ADDR peer_addr); - -#if (BTM_SSR_INCLUDED == TRUE) -extern void bta_sys_ssr_cfg_register(tBTA_SYS_SSR_CFG_CBACK *p_cback); -extern void bta_sys_chg_ssr_config (UINT8 id, UINT8 app_id, UINT16 max_latency, UINT16 min_tout); -#endif - -extern void bta_sys_role_chg_register(tBTA_SYS_CONN_CBACK *p_cback); -extern void bta_sys_notify_role_chg(BD_ADDR_PTR p_bda, UINT8 new_role, UINT8 hci_status); -extern void bta_sys_collision_register(UINT8 bta_id, tBTA_SYS_CONN_CBACK *p_cback); -extern void bta_sys_notify_collision (BD_ADDR_PTR p_bda); - -#if (BTA_EIR_CANNED_UUID_LIST != TRUE) -extern void bta_sys_eir_register(tBTA_SYS_EIR_CBACK *p_cback); -extern void bta_sys_add_uuid(UINT16 uuid16); -extern void bta_sys_remove_uuid(UINT16 uuid16); -#else -#define bta_sys_eir_register(ut) -#define bta_sys_add_uuid(ut) -#define bta_sys_remove_uuid(ut) -#endif - -extern void bta_sys_set_policy (UINT8 id, UINT8 policy, BD_ADDR peer_addr); -extern void bta_sys_clear_policy (UINT8 id, UINT8 policy, BD_ADDR peer_addr); -extern void bta_sys_set_default_policy (UINT8 id, UINT8 policy); -extern void bta_sys_clear_default_policy (UINT8 id, UINT8 policy); -extern BOOLEAN bta_sys_vs_hdl(UINT16 evt, void *p); - -#ifdef __cplusplus -} -#endif - -#endif /* BTA_SYS_H */ diff --git a/tools/sdk/include/bluedroid/bta_sys_int.h b/tools/sdk/include/bluedroid/bta_sys_int.h deleted file mode 100644 index aa2596d96cc..00000000000 --- a/tools/sdk/include/bluedroid/bta_sys_int.h +++ /dev/null @@ -1,101 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the private interface file for the BTA system manager. - * - ******************************************************************************/ -#ifndef BTA_SYS_INT_H -#define BTA_SYS_INT_H - -/***************************************************************************** -** Constants and data types -*****************************************************************************/ - -/***************************************************************************** -** state table -*****************************************************************************/ - -/* SYS HW state */ -enum { - BTA_SYS_HW_OFF, - BTA_SYS_HW_STARTING, - BTA_SYS_HW_ON, - BTA_SYS_HW_STOPPING -}; -typedef UINT8 tBTA_SYS_HW_STATE; - -/* Collision callback */ -#define MAX_COLLISION_REG 5 - -typedef struct { - UINT8 id[MAX_COLLISION_REG]; - tBTA_SYS_CONN_CBACK *p_coll_cback[MAX_COLLISION_REG]; -} tBTA_SYS_COLLISION; - -/* system manager control block */ -typedef struct { - tBTA_SYS_REG *reg[BTA_ID_MAX]; /* registration structures */ - BOOLEAN is_reg[BTA_ID_MAX]; /* registration structures */ - tBTA_SYS_HW_STATE state; - tBTA_SYS_HW_CBACK *sys_hw_cback[BTA_SYS_MAX_HW_MODULES]; /* enable callback for each HW modules */ - UINT32 sys_hw_module_active; /* bitmask of all active modules */ - UINT16 sys_features; /* Bitmask of sys features */ - - tBTA_SYS_CONN_CBACK *prm_cb; /* role management callback registered by DM */ - tBTA_SYS_CONN_CBACK *ppm_cb; /* low power management callback registered by DM */ - tBTA_SYS_CONN_CBACK *p_policy_cb; /* link policy change callback registered by DM */ - tBTA_SYS_CONN_CBACK *p_sco_cb; /* SCO connection change callback registered by AV */ - tBTA_SYS_CONN_CBACK *p_role_cb; /* role change callback registered by AV */ - tBTA_SYS_COLLISION colli_reg; /* collision handling module */ -#if (BTA_EIR_CANNED_UUID_LIST != TRUE) - tBTA_SYS_EIR_CBACK *eir_cb; /* add/remove UUID into EIR */ -#endif -#if (BTM_SSR_INCLUDED == TRUE) - tBTA_SYS_SSR_CFG_CBACK *p_ssr_cb; -#endif - /* VS event handler */ - tBTA_SYS_VS_EVT_HDLR *p_vs_evt_hdlr; - -} tBTA_SYS_CB; - -/***************************************************************************** -** Global variables -*****************************************************************************/ - -/* system manager control block */ -#if BTA_DYNAMIC_MEMORY == FALSE -extern tBTA_SYS_CB bta_sys_cb; -#else -extern tBTA_SYS_CB *bta_sys_cb_ptr; -#define bta_sys_cb (*bta_sys_cb_ptr) -#endif - -/* functions used for BTA SYS HW state machine */ -void bta_sys_hw_btm_cback( tBTM_DEV_STATUS status ); -void bta_sys_hw_error(tBTA_SYS_HW_MSG *p_sys_hw_msg); -void bta_sys_hw_api_enable( tBTA_SYS_HW_MSG *p_sys_hw_msg ); -void bta_sys_hw_api_disable(tBTA_SYS_HW_MSG *p_sys_hw_msg); -void bta_sys_hw_evt_enabled(tBTA_SYS_HW_MSG *p_sys_hw_msg); -void bta_sys_hw_evt_disabled(tBTA_SYS_HW_MSG *p_sys_hw_msg); -void bta_sys_hw_evt_stack_enabled(tBTA_SYS_HW_MSG *p_sys_hw_msg); - -BOOLEAN bta_sys_sm_execute(BT_HDR *p_msg); - -#endif /* BTA_SYS_INT_H */ diff --git a/tools/sdk/include/bluedroid/btc_a2dp.h b/tools/sdk/include/bluedroid/btc_a2dp.h deleted file mode 100644 index 6243eb43bd7..00000000000 --- a/tools/sdk/include/bluedroid/btc_a2dp.h +++ /dev/null @@ -1,108 +0,0 @@ -// 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. - -/******************************************************************************* - * - * Filename: btc_a2dp.h - * - * Description: Common definitions for A2DP - * - *******************************************************************************/ - -#ifndef __BTC_A2DP_H__ -#define __BTC_A2DP_H__ - -#include -#include "bt_target.h" -#include "bta_api.h" -#include "btc_av_api.h" -#include "esp_a2dp_api.h" - -#if BTC_AV_INCLUDED - -/******************************************************************************* - ** Constants - *******************************************************************************/ -#define BTC_AV_SUCCESS (0) -/** - * AV (Audio Video source) Errors - */ -#define BTC_ERROR_SRV_AV_NOT_ENABLED 700 /* AV is not enabled */ -#define BTC_ERROR_SRV_AV_FEEDING_NOT_SUPPORTED 701 /* Requested Feeding not supported */ -#define BTC_ERROR_SRV_AV_BUSY 702 /* Another operation ongoing */ -#define BTC_ERROR_SRV_AV_NOT_OPENED 703 /* No AV link opened */ -#define BTC_ERROR_SRV_AV_NOT_STARTED 704 /* AV is not started */ -#define BTC_ERROR_SRV_AV_CP_NOT_SUPPORTED 705 /* Content protection is not supported by all headsets */ - -/* Transcoding definition for TxTranscoding and RxTranscoding */ -#define BTC_MEDIA_TRSCD_OFF 0 -#define BTC_MEDIA_TRSCD_PCM_2_SBC 1 /* Tx */ - - -/******************************************************************************* - ** Data types - *******************************************************************************/ -typedef int tBTC_AV_STATUS; - -/******************************************************************************* - ** Public functions - *******************************************************************************/ - -void btc_a2dp_on_init(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_on_idle - ** - ** Description Process 'idle' request from BTC AV state machine during - ** initialization - ** - *******************************************************************************/ -void btc_a2dp_on_idle(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_on_started - ** - ** Description Process 'start' request from BTC AV state machine to prepare - ** for A2DP streaming - ** - ** Return TRUE if an ACK for the local command is sent - ** - *******************************************************************************/ -BOOLEAN btc_a2dp_on_started(tBTA_AV_START *p_av, BOOLEAN pending_start); - -/******************************************************************************* - ** - ** Function btc_a2dp_on_stopped - ** - ** Description Process 'stop' request from BTC AV state machine to stop - ** A2DP streaming - ** - *******************************************************************************/ -void btc_a2dp_on_stopped(tBTA_AV_SUSPEND *p_av); - -/******************************************************************************* - ** - ** Function btc_a2dp_on_suspended - ** - ** Description Process 'stop' request from BTC AV state machine to suspend - ** A2DP streaming - ** - *******************************************************************************/ -void btc_a2dp_on_suspended(tBTA_AV_SUSPEND *p_av); - -#endif /* #if BTC_AV_INCLUDED */ - -#endif /* __BTC_A2DP_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_a2dp_control.h b/tools/sdk/include/bluedroid/btc_a2dp_control.h deleted file mode 100644 index e1d5e2ff66c..00000000000 --- a/tools/sdk/include/bluedroid/btc_a2dp_control.h +++ /dev/null @@ -1,110 +0,0 @@ -// 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. - -/******************************************************************************* - * - * Filename: btc_a2dp_control.h - * - *******************************************************************************/ - -#ifndef __BTC_A2DP_CONTROL_H__ -#define __BTC_A2DP_CONTROL_H__ - -#include -#include "bt_target.h" -#include "bta_api.h" -#include "btc_av_api.h" -#include "esp_a2dp_api.h" - -#if BTC_AV_INCLUDED -/******************************************************************************* - ** Public functions - *******************************************************************************/ - -/******************************************************************************* - ** - ** Function btc_a2dp_control_media_ctrl - ** - ** Description Handle the media_ctrl command - ** - *******************************************************************************/ -void btc_a2dp_control_media_ctrl(esp_a2d_media_ctrl_t ctrl); - - -/******************************************************************************* - ** - ** Function btc_a2dp_control_datapath_ctrl - ** - ** Description Handle the media datapath event, which is adapted from UIPC - ** data channel from bluedroid - ** - *******************************************************************************/ -void btc_a2dp_control_datapath_ctrl(uint32_t dp_evt); - - -/******************************************************************************* - ** - ** Function btc_a2dp_control_command_ack - ** - ** Description Acknowledge the pending media_ctrl command - ** - *******************************************************************************/ -void btc_a2dp_control_command_ack(int status); - - -/******************************************************************************* - ** - ** Function btc_a2dp_control_get_datachnl_stat - ** - ** Description Check whether the data channel state is open - ** - ** Return TRUE if the data channel state is open - ** - *******************************************************************************/ -BOOLEAN btc_a2dp_control_get_datachnl_stat(void); - - -/******************************************************************************* - ** - ** Function btc_a2dp_control_set_datachnl_stat - ** - ** Description Set the data channel state flag - ** - *******************************************************************************/ -void btc_a2dp_control_set_datachnl_stat(BOOLEAN open); - - -/******************************************************************************* - ** - ** Function btc_a2dp_control_init - ** - ** Description Initialize the A2DP control module. It should be called during - ** the startup stage of A2DP streaming. - ** - *******************************************************************************/ -bool btc_a2dp_control_init(void); - - -/******************************************************************************* - ** - ** Function btc_a2dp_control_cleanup - ** - ** Description Cleanup the A2DP control module - ** - *******************************************************************************/ -void btc_a2dp_control_cleanup(void); - -#endif /* #if BTC_AV_INCLUDED */ - -#endif /* __BTC_A2DP_CONTROL_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_a2dp_sink.h b/tools/sdk/include/bluedroid/btc_a2dp_sink.h deleted file mode 100644 index 772ffea6d84..00000000000 --- a/tools/sdk/include/bluedroid/btc_a2dp_sink.h +++ /dev/null @@ -1,139 +0,0 @@ -// 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. - -/******************************************************************************* - * - * Filename: btc_a2dp_sink.h - * - *******************************************************************************/ - -#ifndef __BTC_A2DP_SINK_H__ -#define __BTC_A2DP_SINK_H__ - -#include -#include "bt_target.h" -#include "bta_api.h" -#include "btc_av_api.h" -#include "esp_a2dp_api.h" - -#if BTC_AV_SINK_INCLUDED -/******************************************************************************* - ** Data types - *******************************************************************************/ -typedef struct { - BT_HDR hdr; - UINT8 codec_info[AVDT_CODEC_SIZE]; -} tBTC_MEDIA_SINK_CFG_UPDATE; - -/******************************************************************************* - ** Public functions - *******************************************************************************/ - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_startup - ** - ** Description Initialize and startup the A2DP sink module. This function - ** should be called by the BTC AV state machine prior to using - ** the module. - ** - ** Returns true if success - ** - *******************************************************************************/ -bool btc_a2dp_sink_startup(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_shutdown - ** - ** Description Shutdown and cleanup the A2DP sink module - ** - *******************************************************************************/ -void btc_a2dp_sink_shutdown(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_rx_flush_req - ** - ** Description Request to flush audio decoding pipe - ** - ** Returns TRUE if success - ** - *******************************************************************************/ -BOOLEAN btc_a2dp_sink_rx_flush_req(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_enque_buf - ** - ** Description Enqueue a Advance Audio media buffer to be processed by btc media task. - ** - ** Returns size of the queue - ** - *******************************************************************************/ -UINT8 btc_a2dp_sink_enque_buf(BT_HDR *p_buf); - - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_on_idle - ** - ** Description Process 'idle' request from the BTC AV state machine during - ** initialization - ** - *******************************************************************************/ -void btc_a2dp_sink_on_idle(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_on_stopped - ** - ** Description Process 'stop' request from the BTC AV state machine to stop - ** A2DP streaming - ** - *******************************************************************************/ -void btc_a2dp_sink_on_stopped(tBTA_AV_SUSPEND *p_av); - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_on_suspended - ** - ** Description Process 'suspend' request from the BTC AV state machine to - ** suspend A2DP streaming - ** - *******************************************************************************/ -void btc_a2dp_sink_on_suspended(tBTA_AV_SUSPEND *p_av); - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_set_rx_flush - ** - ** Description enable/disabel discarding of received A2DP frames - ** - *******************************************************************************/ -void btc_a2dp_sink_set_rx_flush(BOOLEAN enable); - -/******************************************************************************* - ** - ** Function btc_a2dp_sink_reset_decoder - ** - ** Description Reset decoder parameters according to configuration from remote - ** device - ** - *******************************************************************************/ -void btc_a2dp_sink_reset_decoder(UINT8 *p_av); - -#endif /* #if BTC_AV_SINK_INCLUDED */ - -#endif /* __BTC_A2DP_SINK_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_a2dp_source.h b/tools/sdk/include/bluedroid/btc_a2dp_source.h deleted file mode 100644 index 214c9e72355..00000000000 --- a/tools/sdk/include/bluedroid/btc_a2dp_source.h +++ /dev/null @@ -1,244 +0,0 @@ -// 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. - -/******************************************************************************* - * - * Filename: btc_a2dp_source.h - * - *******************************************************************************/ - -#ifndef __BTC_A2DP_SOURCE_H__ -#define __BTC_A2DP_SOURCE_H__ - -#include -#include "bt_target.h" -#include "bta_api.h" -#include "btc_av_api.h" -#include "esp_a2dp_api.h" - -#if BTC_AV_SRC_INCLUDED -/******************************************************************************* - ** Data types - *******************************************************************************/ - -/* tBTC_MEDIA_INIT_AUDIO msg structure */ -typedef struct { - BT_HDR hdr; - UINT16 SamplingFreq; /* 16k, 32k, 44.1k or 48k*/ - UINT8 ChannelMode; /* mono, dual, stereo or joint stereo*/ - UINT8 NumOfSubBands; /* 4 or 8 */ - UINT8 NumOfBlocks; /* 4, 8, 12 or 16*/ - UINT8 AllocationMethod; /* loudness or SNR*/ - UINT16 MtuSize; /* peer mtu size */ -} tBTC_MEDIA_INIT_AUDIO; - -/* tBTC_MEDIA_UPDATE_AUDIO msg structure */ -typedef struct { - BT_HDR hdr; - UINT16 MinMtuSize; /* Minimum peer mtu size */ - UINT8 MaxBitPool; /* Maximum peer bitpool */ - UINT8 MinBitPool; /* Minimum peer bitpool */ -} tBTC_MEDIA_UPDATE_AUDIO; - -/* tBTC_MEDIA_INIT_AUDIO_FEEDING msg structure */ -typedef struct { - BT_HDR hdr; - tBTC_AV_FEEDING_MODE feeding_mode; - tBTC_AV_MEDIA_FEEDINGS feeding; -} tBTC_MEDIA_INIT_AUDIO_FEEDING; - -/******************************************************************************* - ** Public functions - *******************************************************************************/ - -/******************************************************************************* - ** - ** Function btc_a2dp_source_startup - ** - ** Description Initialize and startup the A2DP source module. This function - ** should be called by the BTC AV state machine prior to using - ** the module - ** - ** Returns TRUE is success - ** - *******************************************************************************/ -bool btc_a2dp_source_startup(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_shutdown - ** - ** Description Shutdown and cleanup the A2DP source module. - ** - *******************************************************************************/ -void btc_a2dp_source_shutdown(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_enc_init_req - ** - ** Description Request to initialize the media task encoder - ** - ** Returns TRUE is success - ** - *******************************************************************************/ -BOOLEAN btc_a2dp_source_enc_init_req(tBTC_MEDIA_INIT_AUDIO *p_msg); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_enc_udpate_req - ** - ** Description Request to update the media task encoder - ** - ** Returns TRUE is success - ** - *******************************************************************************/ -BOOLEAN btc_a2dp_source_enc_update_req(tBTC_MEDIA_UPDATE_AUDIO *p_msg); - - -/******************************************************************************* - ** - ** Function btc_a2dp_source_start_audio_req - ** - ** Description Request to start audio encoding task - ** - ** Returns TRUE is success - ** - *******************************************************************************/ -BOOLEAN btc_a2dp_source_start_audio_req(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_stop_audio_req - ** - ** Description Request to stop audio encoding task - ** - ** Returns TRUE is success - ** - *******************************************************************************/ -BOOLEAN btc_a2dp_source_stop_audio_req(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_tx_flush_req - ** - ** Description Request to flush audio encoding pipe - ** - ** Returns TRUE is success - ** - *******************************************************************************/ -BOOLEAN btc_a2dp_source_tx_flush_req(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_audio_readbuf - ** - ** Description Read an audio buffer from the BTC media TX queue - ** - ** Returns pointer on a aa buffer ready to send - ** - *******************************************************************************/ -BT_HDR *btc_a2dp_source_audio_readbuf(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_audio_feeding_init_req - ** - ** Description Request to initialize audio feeding - ** - ** Returns TRUE if success - ** - *******************************************************************************/ - -BOOLEAN btc_a2dp_source_audio_feeding_init_req(tBTC_MEDIA_INIT_AUDIO_FEEDING *p_msg); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_is_streaming - ** - ** Description Check whether A2DP source is in streaming state - ** - *******************************************************************************/ -bool btc_a2dp_source_is_streaming(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_is_task_shutting_down - ** - ** Description Check whether A2DP source media task is shutting down - ** - *******************************************************************************/ -bool btc_a2dp_source_is_task_shutting_down(void); - - -/******************************************************************************* - ** - ** Function btc_a2dp_source_on_idle - ** - ** Description Request 'idle' request from BTC AV state machine during - ** initialization - ** - *******************************************************************************/ -void btc_a2dp_source_on_idle(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_on_stopped - ** - ** Description Process 'stop' request from the BTC AV state machine to stop - ** A2DP streaming - ** - *******************************************************************************/ -void btc_a2dp_source_on_stopped(tBTA_AV_SUSPEND *p_av); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_on_suspended - ** - ** Description Process 'suspend' request from the BTC AV state machine to stop - ** A2DP streaming - ** - *******************************************************************************/ -void btc_a2dp_source_on_suspended(tBTA_AV_SUSPEND *p_av); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_setup_codec - ** - ** Description initialize the encoder parameters - ** - *******************************************************************************/ -void btc_a2dp_source_setup_codec(void); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_set_tx_flush - ** - ** Description enable/disable discarding of transmitted frames - ** - *******************************************************************************/ -void btc_a2dp_source_set_tx_flush(BOOLEAN enable); - -/******************************************************************************* - ** - ** Function btc_a2dp_source_encoder_update - ** - ** Description update changed SBC encoder parameters - ** - *******************************************************************************/ -void btc_a2dp_source_encoder_update(void); - -#endif /* #if BTC_AV_SRC_INCLUDED */ - -#endif /* __BTC_A2DP_SOURCE_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_alarm.h b/tools/sdk/include/bluedroid/btc_alarm.h deleted file mode 100644 index ca9640a3f41..00000000000 --- a/tools/sdk/include/bluedroid/btc_alarm.h +++ /dev/null @@ -1,30 +0,0 @@ -// 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 __BTC_ALARM_H__ -#define __BTC_ALARM_H__ - -#include -#include "alarm.h" - -/* btc_alarm_args_t */ -typedef struct { - osi_alarm_callback_t cb; - void *cb_data; -} btc_alarm_args_t; - -void btc_alarm_handler(btc_msg_t *msg); - -#endif /* __BTC_ALARM_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_av.h b/tools/sdk/include/bluedroid/btc_av.h deleted file mode 100644 index 312958b0c95..00000000000 --- a/tools/sdk/include/bluedroid/btc_av.h +++ /dev/null @@ -1,208 +0,0 @@ -// 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. - - -/******************************************************************************* - * - * Filename: btc_av.h - * - * Description: Main API header file for all BTC AV functions accessed - * from internal stack. - * - *******************************************************************************/ - -#ifndef __BTC_AV_H__ -#define __BTC_AV_H__ - -#include "bt_target.h" -#include "esp_a2dp_api.h" -#include "btc_task.h" -#include "btc_common.h" -#include "btc_sm.h" -#include "bta_av_api.h" - -#if (BTC_AV_INCLUDED == TRUE) -/******************************************************************************* -** Type definitions for callback functions -********************************************************************************/ - -enum { - BTC_AV_DATAPATH_OPEN_EVT, // original UIPC_OPEN_EVT for data channel in bluedroid - BTC_AV_DATAPATH_MAX_EVT, -}; - -typedef enum { - BTC_AV_CONNECT_REQ_EVT = BTA_AV_MAX_EVT, - BTC_AV_DISCONNECT_REQ_EVT, - BTC_AV_START_STREAM_REQ_EVT, - BTC_AV_STOP_STREAM_REQ_EVT, - BTC_AV_SUSPEND_STREAM_REQ_EVT, - BTC_AV_SINK_CONFIG_REQ_EVT, -} btc_av_sm_event_t; - -typedef enum { -#if BTC_AV_SINK_INCLUDED - BTC_AV_SINK_API_INIT_EVT = 0, - BTC_AV_SINK_API_DEINIT_EVT, - BTC_AV_SINK_API_CONNECT_EVT, - BTC_AV_SINK_API_DISCONNECT_EVT, - BTC_AV_SINK_API_REG_DATA_CB_EVT, -#endif /* BTC_AV_SINK_INCLUDED */ -#if BTC_AV_SRC_INCLUDED - BTC_AV_SRC_API_INIT_EVT, - BTC_AV_SRC_API_DEINIT_EVT, - BTC_AV_SRC_API_CONNECT_EVT, - BTC_AV_SRC_API_DISCONNECT_EVT, - BTC_AV_SRC_API_REG_DATA_CB_EVT, -#endif /* BTC_AV_SRC_INCLUDED */ - BTC_AV_API_MEDIA_CTRL_EVT, - BTC_AV_DATAPATH_CTRL_EVT, -} btc_av_act_t; - -/* btc_av_args_t */ -typedef union { -#if BTC_AV_SINK_INCLUDED - // BTC_AV_SINK_CONFIG_REQ_EVT -- internal event - esp_a2d_mcc_t mcc; - // BTC_AV_SINK_API_CONNECT_EVT - bt_bdaddr_t connect; - // BTC_AV_SINK_API_REG_DATA_CB_EVT - esp_a2d_sink_data_cb_t data_cb; -#endif /* BTC_AV_SINK_INCLUDED */ -#if BTC_AV_SRC_INCLUDED - // BTC_AV_SRC_API_REG_DATA_CB_EVT - esp_a2d_source_data_cb_t src_data_cb; - // BTC_AV_SRC_API_CONNECT - bt_bdaddr_t src_connect; -#endif /* BTC_AV_SRC_INCLUDED */ - // BTC_AV_API_MEDIA_CTRL_EVT - esp_a2d_media_ctrl_t ctrl; - // BTC_AV_DATAPATH_CTRL_EVT - uint32_t dp_evt; -} btc_av_args_t; - -/******************************************************************************* -** BTC AV API -********************************************************************************/ - -void btc_a2dp_call_handler(btc_msg_t *msg); - -void btc_a2dp_cb_handler(btc_msg_t *msg); - -void btc_a2dp_sink_reg_data_cb(esp_a2d_sink_data_cb_t callback); - -void btc_a2dp_src_reg_data_cb(esp_a2d_source_data_cb_t callback); -/******************************************************************************* -** -** Function btc_av_get_sm_handle -** -** Description Fetches current av SM handle -** -** Returns None -** -*******************************************************************************/ - -btc_sm_handle_t btc_av_get_sm_handle(void); - -/******************************************************************************* -** -** Function btc_av_stream_ready -** -** Description Checks whether AV is ready for starting a stream -** -** Returns None -** -*******************************************************************************/ - -BOOLEAN btc_av_stream_ready(void); - -/******************************************************************************* -** -** Function btc_av_stream_started_ready -** -** Description Checks whether AV ready for media start in streaming state -** -** Returns None -** -*******************************************************************************/ - -BOOLEAN btc_av_stream_started_ready(void); - -/******************************************************************************* -** -** Function btc_dispatch_sm_event -** -** Description Send event to AV statemachine -** -** Returns None -** -*******************************************************************************/ - -/* used to pass events to AV statemachine from other tasks */ -void btc_dispatch_sm_event(btc_av_sm_event_t event, void *p_data, int len); - -/******************************************************************************* -** -** Function btc_av_is_connected -** -** Description Checks if av has a connected sink -** -** Returns BOOLEAN -** -*******************************************************************************/ - -BOOLEAN btc_av_is_connected(void); - - -/******************************************************************************* - * - * Function btc_av_get_peer_sep - * - * Description Get the stream endpoint type. - * - * Returns The stream endpoint type: either AVDT_TSEP_SRC or - * AVDT_TSEP_SNK. - * - ******************************************************************************/ - -uint8_t btc_av_get_peer_sep(void); - -/******************************************************************************* -** -** Function btc_av_is_peer_edr -** -** Description Check if the connected a2dp device supports -** EDR or not. Only when connected this function -** will accurately provide a true capability of -** remote peer. If not connected it will always be false. -** -** Returns TRUE if remote device is capable of EDR -** -*******************************************************************************/ - -BOOLEAN btc_av_is_peer_edr(void); - -/****************************************************************************** -** -** Function btc_av_clear_remote_suspend_flag -** -** Description Clears remote suspended flag -** -** Returns Void -********************************************************************************/ -void btc_av_clear_remote_suspend_flag(void); - -#endif ///BTC_AV_INCLUDED == TRUE - -#endif /* __BTC_AV_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_av_api.h b/tools/sdk/include/bluedroid/btc_av_api.h deleted file mode 100644 index 7d5f376d6fa..00000000000 --- a/tools/sdk/include/bluedroid/btc_av_api.h +++ /dev/null @@ -1,201 +0,0 @@ -// 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. - - -/***************************************************************************** - ** - ** Name: btc_av_api.h - ** - ** Description: This is the public interface file for the advanced - ** audio/video streaming (AV) subsystem of BTC. - ** - *****************************************************************************/ - -#ifndef __BTC_AV_API_H__ -#define __BTC_AV_API_H__ - -#include "bt_target.h" -#include "bta_av_api.h" -#include "a2d_api.h" -#include "a2d_sbc.h" - -#if (BTC_AV_INCLUDED == TRUE) -/***************************************************************************** - ** Constants and data types - *****************************************************************************/ - -/* Codec type */ -#define BTC_AV_CODEC_NONE 0xFF -#define BTC_AV_CODEC_SBC A2D_MEDIA_CT_SBC /* SBC media codec type */ - -#define BTC_AV_CODEC_PCM 0x5 /* Raw PCM */ - -typedef UINT8 tBTC_AV_CODEC_ID; - -/* AV features masks */ -#define BTC_AV_FEAT_RCTG BTA_AV_FEAT_RCTG /* remote control target */ -#define BTC_AV_FEAT_RCCT BTA_AV_FEAT_RCCT /* remote control controller */ -#define BTC_AV_FEAT_METADATA BTA_AV_FEAT_METADATA /* remote control Metadata Transfer command/response */ - -typedef UINT16 tBTC_AV_FEAT; - -/* AV channel values */ -#define BTC_AV_CHNL_MSK BTA_AV_CHNL_MSK -#define BTC_AV_CHNL_AUDIO BTA_AV_CHNL_AUDIO /* audio channel */ -#define BTC_AV_CHNL_VIDEO BTA_AV_CHNL_VIDEO /* video channel */ -typedef UINT8 tBTC_AV_CHNL; - -typedef UINT8 tBTC_AV_HNDL; - -/* Operation id list for BTC_AvRemoteCmd */ -#define BTC_AV_ID_SELECT 0x00 /* select */ -#define BTC_AV_ID_UP 0x01 /* up */ -#define BTC_AV_ID_DOWN 0x02 /* down */ -#define BTC_AV_ID_LEFT 0x03 /* left */ -#define BTC_AV_ID_RIGHT 0x04 /* right */ -#define BTC_AV_ID_RIGHT_UP 0x05 /* right-up */ -#define BTC_AV_ID_RIGHT_DOWN 0x06 /* right-down */ -#define BTC_AV_ID_LEFT_UP 0x07 /* left-up */ -#define BTC_AV_ID_LEFT_DOWN 0x08 /* left-down */ -#define BTC_AV_ID_ROOT_MENU 0x09 /* root menu */ -#define BTC_AV_ID_SETUP_MENU 0x0A /* setup menu */ -#define BTC_AV_ID_CONT_MENU 0x0B /* contents menu */ -#define BTC_AV_ID_FAV_MENU 0x0C /* favorite menu */ -#define BTC_AV_ID_EXIT 0x0D /* exit */ -#define BTC_AV_ID_0 0x20 /* 0 */ -#define BTC_AV_ID_1 0x21 /* 1 */ -#define BTC_AV_ID_2 0x22 /* 2 */ -#define BTC_AV_ID_3 0x23 /* 3 */ -#define BTC_AV_ID_4 0x24 /* 4 */ -#define BTC_AV_ID_5 0x25 /* 5 */ -#define BTC_AV_ID_6 0x26 /* 6 */ -#define BTC_AV_ID_7 0x27 /* 7 */ -#define BTC_AV_ID_8 0x28 /* 8 */ -#define BTC_AV_ID_9 0x29 /* 9 */ -#define BTC_AV_ID_DOT 0x2A /* dot */ -#define BTC_AV_ID_ENTER 0x2B /* enter */ -#define BTC_AV_ID_CLEAR 0x2C /* clear */ -#define BTC_AV_ID_CHAN_UP 0x30 /* channel up */ -#define BTC_AV_ID_CHAN_DOWN 0x31 /* channel down */ -#define BTC_AV_ID_PREV_CHAN 0x32 /* previous channel */ -#define BTC_AV_ID_SOUND_SEL 0x33 /* sound select */ -#define BTC_AV_ID_INPUT_SEL 0x34 /* input select */ -#define BTC_AV_ID_DISP_INFO 0x35 /* display information */ -#define BTC_AV_ID_HELP 0x36 /* help */ -#define BTC_AV_ID_PAGE_UP 0x37 /* page up */ -#define BTC_AV_ID_PAGE_DOWN 0x38 /* page down */ -#define BTC_AV_ID_POWER 0x40 /* power */ -#define BTC_AV_ID_VOL_UP 0x41 /* volume up */ -#define BTC_AV_ID_VOL_DOWN 0x42 /* volume down */ -#define BTC_AV_ID_MUTE 0x43 /* mute */ -#define BTC_AV_ID_PLAY 0x44 /* play */ -#define BTC_AV_ID_STOP 0x45 /* stop */ -#define BTC_AV_ID_PAUSE 0x46 /* pause */ -#define BTC_AV_ID_RECORD 0x47 /* record */ -#define BTC_AV_ID_REWIND 0x48 /* rewind */ -#define BTC_AV_ID_FAST_FOR 0x49 /* fast forward */ -#define BTC_AV_ID_EJECT 0x4A /* eject */ -#define BTC_AV_ID_FORWARD 0x4B /* forward */ -#define BTC_AV_ID_BACKWARD 0x4C /* backward */ -#define BTC_AV_ID_ANGLE 0x50 /* angle */ -#define BTC_AV_ID_SUBPICT 0x51 /* subpicture */ -#define BTC_AV_ID_F1 0x71 /* F1 */ -#define BTC_AV_ID_F2 0x72 /* F2 */ -#define BTC_AV_ID_F3 0x73 /* F3 */ -#define BTC_AV_ID_F4 0x74 /* F4 */ -#define BTC_AV_ID_F5 0x75 /* F5 */ -#define BTC_AV_ID_VENDOR 0x7E /* vendor unique */ -#define BTC_AV_KEYPRESSED_RELEASE 0x80 - -typedef UINT8 tBTC_AV_RC; - -/* State flag for pass through command */ -#define BTC_AV_STATE_PRESS 0 /* key pressed */ -#define BTC_AV_STATE_RELEASE 1 /* key released */ - -typedef UINT8 tBTC_AV_STATE; - -typedef UINT8 tBTC_AV_RC_HNDL; - -/* Command codes for BTC_AvVendorCmd */ -#define BTC_AV_CMD_CTRL 0 -#define BTC_AV_CMD_STATUS 1 -#define BTC_AV_CMD_SPEC_INQ 2 -#define BTC_AV_CMD_NOTIF 3 -#define BTC_AV_CMD_GEN_INQ 4 - -typedef UINT8 tBTC_AV_CMD; - -/* AV callback events */ -#define BTC_AV_OPEN_EVT 0 /* connection opened */ -#define BTC_AV_CLOSE_EVT 1 /* connection closed */ -#define BTC_AV_START_EVT 2 /* stream data transfer started */ -#define BTC_AV_STOP_EVT 3 /* stream data transfer stopped */ -#define BTC_AV_RC_OPEN_EVT 4 /* remote control channel open */ -#define BTC_AV_RC_CLOSE_EVT 5 /* remote control channel closed */ -#define BTC_AV_REMOTE_CMD_EVT 6 /* remote control command */ -#define BTC_AV_REMOTE_RSP_EVT 7 /* remote control response */ -#define BTC_AV_META_MSG_EVT 8 /* metadata messages */ - -typedef UINT8 tBTC_AV_EVT; - -#define BTC_AV_FEEDING_ASYNCHRONOUS 0 /* asynchronous feeding, use tx av timer */ -#define BTC_AV_FEEDING_SYNCHRONOUS 1 /* synchronous feeding, no av tx timer */ - -#define BTC_AV_MAX_SYNCHRONOUS_LATENCY 80 /* max latency in ms for BTC_AV_FEEDING_SYNCHRONOUS */ -#define BTC_AV_MIN_SYNCHRONOUS_LATENCY 4 /* min latency in ms for BTC_AV_FEEDING_SYNCHRONOUS */ - -typedef UINT8 tBTC_AV_FEEDING_MODE; - -#define BTC_AV_CHANNEL_MODE_MONO A2D_SBC_IE_CH_MD_MONO -#define BTC_AV_CHANNEL_MODE_STEREO A2D_SBC_IE_CH_MD_STEREO -#define BTC_AV_CHANNEL_MODE_JOINT A2D_SBC_IE_CH_MD_JOINT -#define BTC_AV_CHANNEL_MODE_DUAL A2D_SBC_IE_CH_MD_DUAL - -typedef UINT8 tBTC_AV_CHANNEL_MODE; - -/** - * Structure used to configure the AV codec capabilities/config - */ -typedef struct { - tBTC_AV_CODEC_ID id; /* Codec ID (in terms of BTC) */ - UINT8 info[AVDT_CODEC_SIZE]; /* Codec info (can be config or capabilities) */ -} tBTC_AV_CODEC_INFO; - -/** - * Structure used to configure the AV media feeding - */ -typedef struct { - UINT16 sampling_freq; /* 44100, 48000 etc */ - UINT16 num_channel; /* 1 for mono or 2 stereo */ - UINT8 bit_per_sample; /* Number of bits per sample (8, 16) */ -} tBTC_AV_MEDIA_FEED_CFG_PCM; - -typedef union { - tBTC_AV_MEDIA_FEED_CFG_PCM pcm; /* Raw PCM feeding format */ -} tBTC_AV_MEDIA_FEED_CFG; - -typedef struct { - tBTC_AV_CODEC_ID format; /* Media codec identifier */ - tBTC_AV_MEDIA_FEED_CFG cfg; /* Media codec configuration */ -} tBTC_AV_MEDIA_FEEDINGS; - - -#ifdef __cplusplus -} -#endif - -#endif ///BTC_AV_INCLUDED == TRUE - -#endif /* __BTC_AV_API_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_av_co.h b/tools/sdk/include/bluedroid/btc_av_co.h deleted file mode 100644 index cacaa01d8ff..00000000000 --- a/tools/sdk/include/bluedroid/btc_av_co.h +++ /dev/null @@ -1,172 +0,0 @@ -// 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 __BTC_AV_CO_H__ -#define __BTC_AV_CO_H__ - -#include "btc_a2dp.h" - -#if (BTA_AV_INCLUDED == TRUE) -/******************************************************************************* -** Constants & Macros -********************************************************************************/ - -enum { - BTC_SV_AV_AA_SBC_INDEX = 0, - BTC_SV_AV_AA_SBC_SINK_INDEX, - BTC_SV_AV_AA_SEP_INDEX /* Last index */ -}; - - -/******************************************************************************* -** Functions -********************************************************************************/ - -/******************************************************************************* - ** - ** Function bta_av_co_cp_is_active - ** - ** Description Get the current configuration of content protection - ** - ** Returns TRUE if the current streaming has CP, FALSE otherwise - ** - *******************************************************************************/ -BOOLEAN bta_av_co_cp_is_active(void); - -/******************************************************************************* - ** - ** Function bta_av_co_cp_get_flag - ** - ** Description Get content protection flag - ** BTA_AV_CP_SCMS_COPY_NEVER - ** BTA_AV_CP_SCMS_COPY_ONCE - ** BTA_AV_CP_SCMS_COPY_FREE - ** - ** Returns The current flag value - ** - *******************************************************************************/ -UINT8 bta_av_co_cp_get_flag(void); - -/******************************************************************************* - ** - ** Function bta_av_co_cp_set_flag - ** - ** Description Set content protection flag - ** BTA_AV_CP_SCMS_COPY_NEVER - ** BTA_AV_CP_SCMS_COPY_ONCE - ** BTA_AV_CP_SCMS_COPY_FREE - ** - ** Returns TRUE if setting the SCMS flag is supported else FALSE - ** - *******************************************************************************/ -BOOLEAN bta_av_co_cp_set_flag(UINT8 cp_flag); - -/******************************************************************************* - ** - ** Function bta_av_co_audio_codec_reset - ** - ** Description Reset the current codec configuration - ** - ** Returns void - ** - *******************************************************************************/ -void bta_av_co_audio_codec_reset(void); - -/******************************************************************************* - ** - ** Function bta_av_co_audio_codec_supported - ** - ** Description Check if all opened connections are compatible with a codec - ** configuration - ** - ** Returns TRUE if all opened devices support this codec, FALSE otherwise - ** - *******************************************************************************/ -BOOLEAN bta_av_co_audio_codec_supported(tBTC_AV_STATUS *p_status); - -/******************************************************************************* - ** - ** Function bta_av_co_audio_set_codec - ** - ** Description Set the current codec configuration from the feeding type. - ** This function is starting to modify the configuration, it - ** should be protected. - ** - ** Returns TRUE if successful, FALSE otherwise - ** - *******************************************************************************/ -BOOLEAN bta_av_co_audio_set_codec(const tBTC_AV_MEDIA_FEEDINGS *p_feeding, tBTC_AV_STATUS *p_status); - -/******************************************************************************* - ** - ** Function bta_av_co_audio_get_sbc_config - ** - ** Description Retrieves the SBC codec configuration. If the codec in use - ** is not SBC, return the default SBC codec configuration. - ** - ** Returns TRUE if codec is SBC, FALSE otherwise - ** - *******************************************************************************/ -BOOLEAN bta_av_co_audio_get_sbc_config(tA2D_SBC_CIE *p_sbc_config, UINT16 *p_minmtu); - -/******************************************************************************* - ** - ** Function bta_av_co_audio_discard_config - ** - ** Description Discard the codec configuration of a connection - ** - ** Returns Nothing - ** - *******************************************************************************/ -void bta_av_co_audio_discard_config(tBTA_AV_HNDL hndl); - -/******************************************************************************* - ** - ** Function bta_av_co_init - ** - ** Description Initialization - ** - ** Returns Nothing - ** - *******************************************************************************/ -void bta_av_co_init(void); - - -/******************************************************************************* - ** - ** Function bta_av_co_peer_cp_supported - ** - ** Description Checks if the peer supports CP - ** - ** Returns TRUE if the peer supports CP - ** - *******************************************************************************/ -BOOLEAN bta_av_co_peer_cp_supported(tBTA_AV_HNDL hndl); - -/******************************************************************************* - ** - ** Function bta_av_co_get_remote_bitpool_pref - ** - ** Description Check if remote side did a setconfig within the limits - ** of our exported bitpool range. If set we will set the - ** remote preference. - ** - ** Returns TRUE if config set, FALSE otherwize - ** - *******************************************************************************/ -BOOLEAN bta_av_co_get_remote_bitpool_pref(UINT8 *min, UINT8 *max); - -#endif ///BTA_AV_INCLUDED == TRUE - -#endif diff --git a/tools/sdk/include/bluedroid/btc_avrc.h b/tools/sdk/include/bluedroid/btc_avrc.h deleted file mode 100644 index 836696433ff..00000000000 --- a/tools/sdk/include/bluedroid/btc_avrc.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2012 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 __BTC_AVRC_H__ -#define __BTC_AVRC_H__ - -#include -#include -#include "bt_defs.h" -#include "bt_types.h" -#include "bta_av_api.h" - -#if (BTC_AV_INCLUDED == TRUE) -#ifndef BTC_AVRC_TGT_INCLUDED -#define BTC_AVRC_TGT_INCLUDED FALSE -#endif - -typedef enum { - BTC_AVRC_CTRL_API_INIT_EVT = 0, - BTC_AVRC_CTRL_API_DEINIT_EVT, - BTC_AVRC_CTRL_API_SND_PTCMD_EVT, - BTC_AVRC_STATUS_API_SND_META_EVT, - BTC_AVRC_STATUS_API_SND_PLAY_STATUS_EVT, - BTC_AVRC_NOTIFY_API_SND_REG_NOTIFY_EVT, - BTC_AVRC_CTRL_API_SET_PLAYER_SETTING_EVT -} btc_avrc_act_t; - -typedef struct { - uint8_t tl; /* transaction label */ - uint8_t key_code; - uint8_t key_state; -} pt_cmd_t; - -typedef struct { - uint8_t tl; - uint8_t attr_mask; -} md_cmd_t; - -typedef struct { - uint8_t tl; - uint8_t event_id; - uint32_t event_parameter; -} rn_cmd_t; - -typedef struct { - uint8_t tl; - uint8_t attr_id; - uint8_t value_id; -} ps_cmd_t; - -/* btc_avrc_args_t */ -typedef union { - pt_cmd_t pt_cmd; - md_cmd_t md_cmd; - rn_cmd_t rn_cmd; - ps_cmd_t ps_cmd; -} btc_avrc_args_t; - -/** BT-RC Controller callback structure. */ -typedef void (* btrc_passthrough_rsp_callback) (int id, int key_state); - -typedef void (* btrc_connection_state_callback) (bool state, bt_bdaddr_t *bd_addr); - -void btc_rc_handler(tBTA_AV_EVT event, tBTA_AV *p_data); - -BOOLEAN btc_rc_get_connected_peer(BD_ADDR peer_addr); - -/******************************************************************************* -** BTC AVRC API -********************************************************************************/ -void btc_avrc_call_handler(btc_msg_t *msg); - -#endif ///BTC_AV_INCLUDED == TRUE - -#endif /* __BTC_AVRC_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_ble_storage.h b/tools/sdk/include/bluedroid/btc_ble_storage.h deleted file mode 100644 index 0d4d43e7c74..00000000000 --- a/tools/sdk/include/bluedroid/btc_ble_storage.h +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (C) 2014 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 __BTC_BLE_STORAGE_H__ -#define __BTC_BLE_STORAGE_H__ -#include "bt_types.h" -#include "bt_target.h" -#include "esp_gap_ble_api.h" - -#if (SMP_INCLUDED == TRUE) -#define BTC_LE_LOCAL_KEY_IR (1<<0) -#define BTC_LE_LOCAL_KEY_IRK (1<<1) -#define BTC_LE_LOCAL_KEY_DHK (1<<2) -#define BTC_LE_LOCAL_KEY_ER (1<<3) - -#define BTC_BLE_STORAGE_DEV_TYPE_STR "DevType" -#define BTC_BLE_STORAGE_ADDR_TYPE_STR "AddrType" -#define BTC_BLE_STORAGE_LINK_KEY_STR "LinkKey" -#define BTC_BLE_STORAGE_LE_KEY_PENC_STR "LE_KEY_PENC" -#define BTC_BLE_STORAGE_LE_KEY_PID_STR "LE_KEY_PID" -#define BTC_BLE_STORAGE_LE_KEY_PCSRK_STR "LE_KEY_PCSRK" -#define BTC_BLE_STORAGE_LE_KEY_LENC_STR "LE_KEY_LENC" -#define BTC_BLE_STORAGE_LE_KEY_LID_STR "LE_KEY_LID" -#define BTC_BLE_STORAGE_LE_KEY_LCSRK_STR "LE_KEY_LCSRK" - -#define BTC_BLE_STORAGE_LOCAL_ADAPTER_STR "Adapter" -#define BTC_BLE_STORAGE_LE_LOCAL_KEY_IR_STR "LE_LOCAL_KEY_IR" -#define BTC_BLE_STORAGE_LE_LOCAL_KEY_IRK_STR "LE_LOCAL_KEY_IRK" -#define BTC_BLE_STORAGE_LE_LOCAL_KEY_DHK_STR "LE_LOCAL_KEY_DHK" -#define BTC_BLE_STORAGE_LE_LOCAL_KEY_ER_STR "LE_LOCAL_KEY_ER" - -/************************************************************************************ -** Local type definitions -************************************************************************************/ -typedef struct -{ - BT_OCTET16 sp_c; - BT_OCTET16 sp_r; - BD_ADDR oob_bdaddr; /* peer bdaddr*/ -} btc_dm_oob_cb_t; - - -void btc_storage_save(void); - -bt_status_t btc_storage_add_ble_bonding_key( bt_bdaddr_t *remote_bd_addr, char *key, uint8_t key_type, uint8_t key_length); - -bt_status_t btc_storage_get_ble_bonding_key(bt_bdaddr_t *remote_bd_addr, uint8_t key_type, char *key_value, int key_length); - -bt_status_t btc_storage_remove_ble_bonding_keys(bt_bdaddr_t *remote_bd_addr); - -bool btc_storage_compare_address_key_value(bt_bdaddr_t *remote_bd_addr, uint8_t key_type, void *key_value, int key_length); - -bt_status_t btc_storage_add_ble_local_key(char *key, uint8_t key_type, uint8_t key_length); - -bt_status_t btc_storage_remove_ble_local_keys(void); - -bt_status_t btc_storage_get_ble_local_key(uint8_t key_type, char *key_value, int key_len); - -bt_status_t btc_storage_get_remote_addr_type(bt_bdaddr_t *remote_bd_addr, int *addr_type); - -bt_status_t btc_storage_set_remote_addr_type(bt_bdaddr_t *remote_bd_addr, uint8_t addr_type, bool flush); - -bt_status_t btc_storage_remove_remote_addr_type(bt_bdaddr_t *remote_bd_addr, bool flush); - -bt_status_t btc_storage_set_ble_dev_type(bt_bdaddr_t *bd_addr, bool flush); - -bt_status_t btc_storage_remove_ble_dev_type(bt_bdaddr_t *remote_bd_addr, bool flush); - -bt_status_t btc_storage_load_bonded_ble_devices(void); - -bt_status_t btc_storage_get_bonded_ble_devices_list(esp_ble_bond_dev_t *bond_dev, int dev_num); - -int btc_storage_get_num_ble_bond_devices(void); - -#endif ///SMP_INCLUDED == TRUE -#endif ///__BTC_BLE_STORAGE_H__ diff --git a/tools/sdk/include/bluedroid/btc_blufi_prf.h b/tools/sdk/include/bluedroid/btc_blufi_prf.h deleted file mode 100644 index 06154673a89..00000000000 --- a/tools/sdk/include/bluedroid/btc_blufi_prf.h +++ /dev/null @@ -1,70 +0,0 @@ -// 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 __BTC_BLUFI_PRF_H__ -#define __BTC_BLUFI_PRF_H__ - -#include "bt_target.h" -#include "btc_task.h" -#include "esp_blufi_api.h" - -typedef enum { - BTC_BLUFI_ACT_INIT = 0, - BTC_BLUFI_ACT_DEINIT, - BTC_BLUFI_ACT_SEND_CFG_REPORT, - BTC_BLUFI_ACT_SEND_WIFI_LIST, - BTC_BLUFI_ACT_SEND_ERR_INFO, - BTC_BLUFI_ACT_SEND_CUSTOM_DATA, -} btc_blufi_act_t; - -typedef union { - struct blufi_cfg_report { - wifi_mode_t opmode; - esp_blufi_sta_conn_state_t sta_conn_state; - uint8_t softap_conn_num; - esp_blufi_extra_info_t *extra_info; - int extra_info_len; - } wifi_conn_report; - /* - BTC_BLUFI_ACT_SEND_WIFI_LIST - */ - struct blufi_wifi_list { - uint16_t apCount; - esp_blufi_ap_record_t *list; - } wifi_list; - /* - BTC_BLUFI_ACT_SEND_ERR_INFO - */ - struct blufi_error_infor { - esp_blufi_error_state_t state; - } blufi_err_infor; - /* - BTC_BLUFI_ACT_SEND_CUSTOM_DATA - */ - struct blufi_custom_data { - uint8_t *data; - uint32_t data_len; - } custom_data; -} btc_blufi_args_t; - -void btc_blufi_cb_handler(btc_msg_t *msg); -void btc_blufi_call_handler(btc_msg_t *msg); -void btc_blufi_set_callbacks(esp_blufi_callbacks_t *callbacks); - -void btc_blufi_call_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); -void btc_blufi_call_deep_free(btc_msg_t *msg); - -uint16_t btc_blufi_get_version(void); - -#endif /* __BTC_BLUFI_PRF_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_common.h b/tools/sdk/include/bluedroid/btc_common.h deleted file mode 100644 index 62246289716..00000000000 --- a/tools/sdk/include/bluedroid/btc_common.h +++ /dev/null @@ -1,35 +0,0 @@ -// 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 __BTC_COMMON_H__ -#define __BTC_COMMON_H__ - -#include "bt_trace.h" -#include "bt_types.h" -#include "osi.h" - -#define BTC_ASSERTC(cond, msg, val) if (!(cond)) { LOG_ERROR( \ - "### ASSERT : %s line %d %s (%d) ###", __FILE__, __LINE__, msg, val);} - -#define BTC_HAL_CBACK(P_CB, P_CBACK, ...)\ - if (P_CB && P_CB->P_CBACK) { \ - LOG_INFO("HAL %s->%s", #P_CB, #P_CBACK); \ - P_CB->P_CBACK(__VA_ARGS__); \ - } \ - else { \ - BTC_ASSERTC(0, "Callback is NULL", 0); \ - } - -#endif /* __BTC_COMMON_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_config.h b/tools/sdk/include/bluedroid/btc_config.h deleted file mode 100644 index 79f6137e851..00000000000 --- a/tools/sdk/include/bluedroid/btc_config.h +++ /dev/null @@ -1,58 +0,0 @@ -// 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 __BTC_CONFIG_H__ -#define __BTC_CONFIG_H__ - -#include -#include - -#include "bt_types.h" - -typedef struct btc_config_section_iter_t btc_config_section_iter_t; - -bool btc_config_init(void); -bool btc_config_shut_down(void); -bool btc_config_clean_up(void); - -bool btc_config_has_section(const char *section); -bool btc_config_exist(const char *section, const char *key); -bool btc_config_get_int(const char *section, const char *key, int *value); -bool btc_config_set_int(const char *section, const char *key, int value); -bool btc_config_get_str(const char *section, const char *key, char *value, int *size_bytes); -bool btc_config_set_str(const char *section, const char *key, const char *value); -bool btc_config_get_bin(const char *section, const char *key, uint8_t *value, size_t *length); -bool btc_config_set_bin(const char *section, const char *key, const uint8_t *value, size_t length); -bool btc_config_remove(const char *section, const char *key); -bool btc_config_remove_section(const char *section); - -size_t btc_config_get_bin_length(const char *section, const char *key); - -const btc_config_section_iter_t *btc_config_section_begin(void); -const btc_config_section_iter_t *btc_config_section_end(void); -const btc_config_section_iter_t *btc_config_section_next(const btc_config_section_iter_t *section); -const char *btc_config_section_name(const btc_config_section_iter_t *section); - -void btc_config_flush(void); -int btc_config_clear(void); - -// TODO(zachoverflow): Eww...we need to move these out. These are peer specific, not config general. -bool btc_get_address_type(const BD_ADDR bd_addr, int *p_addr_type); -bool btc_compare_address_key_value(const char *section, char *key_type, void *key_value, int key_length); -bool btc_get_device_type(const BD_ADDR bd_addr, int *p_device_type); - -void btc_config_lock(void); -void btc_config_unlock(void); - -#endif diff --git a/tools/sdk/include/bluedroid/btc_dev.h b/tools/sdk/include/bluedroid/btc_dev.h deleted file mode 100644 index dd2e8663a95..00000000000 --- a/tools/sdk/include/bluedroid/btc_dev.h +++ /dev/null @@ -1,38 +0,0 @@ -// 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 __BTC_DEV_H__ -#define __BTC_DEV_H__ - -#include "esp_bt_defs.h" -#include "esp_bt_device.h" -#include "btc_task.h" - -typedef enum { - BTC_DEV_ACT_SET_DEVICE_NAME -} btc_dev_act_t; - -/* btc_dev_args_t */ -typedef union { - // BTC_BT_GAP_ACT_SET_DEV_NAME - struct set_bt_dev_name_args { -#define ESP_DEV_DEVICE_NAME_MAX (32) - char device_name[ESP_DEV_DEVICE_NAME_MAX + 1]; - } set_dev_name; -} btc_dev_args_t; - -void btc_dev_call_handler(btc_msg_t *msg); - -#endif /* __BTC_DEV_H__ */ - diff --git a/tools/sdk/include/bluedroid/btc_dm.h b/tools/sdk/include/bluedroid/btc_dm.h deleted file mode 100644 index 44f4d84c199..00000000000 --- a/tools/sdk/include/bluedroid/btc_dm.h +++ /dev/null @@ -1,86 +0,0 @@ -// 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 __BTC_DM_H__ -#define __BTC_DM_H__ - -#include "btc_task.h" -#include "esp_bt_defs.h" -#include "bta_api.h" - -typedef enum { - BTC_DM_SEC_ACT -} btc_dm_sec_act_t; - -/* btc_dm_args_t */ -typedef union { - //BTC_DM_SEC_ACT - tBTA_DM_SEC sec; -} btc_dm_sec_args_t; - -typedef struct -{ - bool is_penc_key_rcvd; - tBTM_LE_PENC_KEYS penc_key; /* received peer encryption key */ - bool is_pcsrk_key_rcvd; - tBTM_LE_PCSRK_KEYS pcsrk_key; /* received peer device SRK */ - bool is_pid_key_rcvd; - tBTM_LE_PID_KEYS pid_key; /* peer device ID key */ - bool is_lenc_key_rcvd; - tBTM_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys LTK = = d1(ER,DIV,0)*/ - bool is_lcsrk_key_rcvd; - tBTM_LE_LCSRK_KEYS lcsrk_key; /* local device CSRK = d1(ER,DIV,1)*/ - bool is_lidk_key_rcvd; /* local identity key received */ -} btc_dm_ble_cb_t; - -typedef struct -{ - bt_bdaddr_t static_bdaddr; - BD_ADDR bd_addr; - btc_dm_ble_cb_t ble; -} btc_dm_pairing_cb_t; - -typedef struct -{ - uint8_t ir[BT_OCTET16_LEN]; - uint8_t irk[BT_OCTET16_LEN]; - uint8_t dhk[BT_OCTET16_LEN]; -} btc_dm_local_key_id_t; - -typedef struct -{ - bool is_er_rcvd; - uint8_t er[BT_OCTET16_LEN]; - bool is_id_keys_rcvd; - btc_dm_local_key_id_t id_keys; /* ID kyes */ -} btc_dm_local_key_cb_t; - - - -// void btc_dm_call_handler(btc_msg_t *msg); -void btc_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC *data); -void btc_dm_sec_cb_handler(btc_msg_t *msg); -void btc_dm_sec_arg_deep_copy(btc_msg_t *msg, void *dst, void *src); - -bt_status_t btc_dm_enable_service(tBTA_SERVICE_ID service_id); -bt_status_t btc_dm_disable_service(tBTA_SERVICE_ID service_id); - -#if (SMP_INCLUDED == TRUE) -void btc_dm_load_ble_local_keys(void); - -void btc_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK *p_key_mask, BT_OCTET16 er, - tBTA_BLE_LOCAL_ID_KEYS *p_id_keys); -#endif - -#endif /* __BTC_DM_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_gap_ble.h b/tools/sdk/include/bluedroid/btc_gap_ble.h deleted file mode 100644 index ba744702b29..00000000000 --- a/tools/sdk/include/bluedroid/btc_gap_ble.h +++ /dev/null @@ -1,165 +0,0 @@ -// 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 __BTC_GAP_BLE_H__ -#define __BTC_GAP_BLE_H__ - -#include "esp_bt_defs.h" -#include "esp_gap_ble_api.h" - -#define BLE_ISVALID_PARAM(x, min, max) (((x) >= (min) && (x) <= (max)) || ((x) == ESP_BLE_CONN_PARAM_UNDEF)) - -typedef enum { - BTC_GAP_BLE_ACT_CFG_ADV_DATA = 0, - BTC_GAP_BLE_ACT_SET_SCAN_PARAM, - BTC_GAP_BLE_ACT_START_SCAN, - BTC_GAP_BLE_ACT_STOP_SCAN, - BTC_GAP_BLE_ACT_START_ADV, - BTC_GAP_BLE_ACT_STOP_ADV, - BTC_GAP_BLE_ACT_UPDATE_CONN_PARAM, - BTC_GAP_BLE_ACT_SET_PKT_DATA_LEN, - BTC_GAP_BLE_ACT_SET_RAND_ADDRESS, - BTC_GAP_BLE_ACT_CONFIG_LOCAL_PRIVACY, - BTC_GAP_BLE_ACT_UPDATE_WHITE_LIST, - BTC_GAP_BLE_ACT_SET_CONN_PARAMS, - BTC_GAP_BLE_ACT_SET_DEV_NAME, - BTC_GAP_BLE_ACT_CFG_ADV_DATA_RAW, - BTC_GAP_BLE_ACT_CFG_SCAN_RSP_DATA_RAW, - BTC_GAP_BLE_ACT_READ_RSSI, - BTC_GAP_BLE_SET_ENCRYPTION_EVT, - BTC_GAP_BLE_SET_SECURITY_PARAM_EVT, - BTC_GAP_BLE_SECURITY_RSP_EVT, - BTC_GAP_BLE_PASSKEY_REPLY_EVT, - BTC_GAP_BLE_CONFIRM_REPLY_EVT, - BTC_GAP_BLE_DISCONNECT_EVT, - BTC_GAP_BLE_REMOVE_BOND_DEV_EVT, -} btc_gap_ble_act_t; - -/* btc_ble_gap_args_t */ -typedef union { - //BTC_GAP_BLE_ACT_CFG_ADV_DATA = 0, - struct config_adv_data_args { - esp_ble_adv_data_t adv_data; - } cfg_adv_data; - //BTC_GAP_BLE_ACT_SET_SCAN_PARAM, - struct set_scan_params_args { - esp_ble_scan_params_t scan_params; - } set_scan_param; - //BTC_GAP_BLE_ACT_START_SCAN, - struct start_scan_args { - uint32_t duration; - } start_scan; - //BTC_GAP_BLE_ACT_STOP_SCAN, no args - //BTC_GAP_BLE_ACT_START_ADV, - struct start_adv_args { - esp_ble_adv_params_t adv_params; - } start_adv; - //BTC_GAP_BLE_ACT_STOP_ADV, no args - //BTC_GAP_BLE_ACT_UPDATE_CONN_PARAM, - struct conn_update_params_args { - esp_ble_conn_update_params_t conn_params; - } conn_update_params; - //BTC_GAP_BLE_ACT_SET_PKT_DATA_LEN - struct set_pkt_data_len_args { - esp_bd_addr_t remote_device; - uint16_t tx_data_length; - } set_pkt_data_len; - //BTC_GAP_BLE_ACT_SET_RAND_ADDRESS, - struct set_rand_addr_args { - esp_bd_addr_t rand_addr; - } set_rand_addr; - //BTC_GAP_BLE_ACT_CONFIG_LOCAL_PRIVACY, - struct cfg_local_privacy_args { - bool privacy_enable; - } cfg_local_privacy; - //BTC_GAP_BLE_ACT_UPDATE_WHITE_LIST - struct update_white_list_args { - bool add_remove; - esp_bd_addr_t remote_bda; - }update_white_list; - //BTC_GAP_BLE_ACT_SET_CONN_PARAMS - struct set_conn_params_args { - esp_bd_addr_t bd_addr; - uint16_t min_conn_int; - uint16_t max_conn_int; - uint16_t slave_latency; - uint16_t supervision_tout; - }set_conn_params; - //BTC_GAP_BLE_ACT_SET_DEV_NAME, - struct set_dev_name_args { -#define ESP_GAP_DEVICE_NAME_MAX (32) - char device_name[ESP_GAP_DEVICE_NAME_MAX + 1]; - } set_dev_name; - //BTC_GAP_BLE_ACT_CFG_ADV_DATA_RAW, - struct config_adv_data_raw_args { - uint8_t *raw_adv; - uint32_t raw_adv_len; - } cfg_adv_data_raw; - //BTC_GAP_BLE_ACT_CFG_SCAN_RSP_DATA_RAW, - struct config_scan_rsp_data_raw_args { - uint8_t *raw_scan_rsp; - uint32_t raw_scan_rsp_len; - } cfg_scan_rsp_data_raw; - //BTC_GAP_BLE_SET_ENCRYPTION_EVT - struct set_encryption_args { - esp_bd_addr_t bd_addr; - esp_ble_sec_act_t sec_act; - } set_encryption; - //BTC_GAP_BLE_SET_SECURITY_PARAM_EVT - struct set_security_param_args { - esp_ble_sm_param_t param_type; - uint8_t len; - uint8_t *value; - } set_security_param; - //BTC_GAP_BLE_SECURITY_RSP_EVT - struct enc_rsp_args { - esp_bd_addr_t bd_addr; - bool accept; - } sec_rsp; - //BTC_GAP_BLE_PASSKEY_REPLY_EVT - struct enc_passkey_reply_args { - esp_bd_addr_t bd_addr; - bool accept; - uint32_t passkey; - } enc_passkey_replay; - //BTC_GAP_BLE_CONFIRM_REPLY_EVT - struct enc_comfirm_reply_args { - esp_bd_addr_t bd_addr; - bool accept; - } enc_comfirm_replay; - //BTC_GAP_BLE_DISCONNECT_EVT - struct disconnect_args { - esp_bd_addr_t remote_device; - } disconnect; - //BTC_GAP_BLE_REMOVE_BOND_DEV_EVT - struct remove_bond_device_args { - esp_bd_addr_t bd_addr; - } remove_bond_device; - //BTC_GAP_BLE_ACT_READ_RSSI - struct read_rssi_args { - esp_bd_addr_t remote_addr; - } read_rssi; -} btc_ble_gap_args_t; - -void btc_gap_ble_call_handler(btc_msg_t *msg); -void btc_gap_ble_cb_handler(btc_msg_t *msg); -void btc_get_whitelist_size(uint16_t *length); -void btc_gap_ble_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); -void btc_gap_ble_arg_deep_free(btc_msg_t *msg); -void btc_gap_ble_cb_deep_free(btc_msg_t *msg); -void btc_gap_ble_cb_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); -void btc_gap_callback_init(void); -void btc_gap_ble_deinit(void); - -#endif /* __BTC_GAP_BLE_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_gap_bt.h b/tools/sdk/include/bluedroid/btc_gap_bt.h deleted file mode 100644 index 01b07096526..00000000000 --- a/tools/sdk/include/bluedroid/btc_gap_bt.h +++ /dev/null @@ -1,67 +0,0 @@ -// 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 __BTC_GAP_BT_H__ -#define __BTC_GAP_BT_H__ - -#include "bt_target.h" -#include "esp_bt_defs.h" -#include "esp_gap_bt_api.h" -#include "btc_task.h" - -#if (BTC_GAP_BT_INCLUDED == TRUE) - -typedef enum { - BTC_GAP_BT_ACT_SET_SCAN_MODE = 0, - BTC_GAP_BT_ACT_REG_CB, - BTC_GAP_BT_ACT_START_DISCOVERY, - BTC_GAP_BT_ACT_SEARCH_DEVICES, - BTC_GAP_BT_ACT_CANCEL_DISCOVERY, - BTC_GAP_BT_ACT_GET_REMOTE_SERVICES, - BTC_GAP_BT_ACT_SEARCH_SERVICES, - BTC_GAP_BT_ACT_GET_REMOTE_SERVICE_RECORD, - BTC_GAP_BT_ACT_SEARCH_SERVICE_RECORD, -} btc_gap_bt_act_t; - -/* btc_bt_gap_args_t */ -typedef union { - // BTC_BT_GAP_ACT_SET_SCAN_MODE, - struct set_bt_scan_mode_args { - esp_bt_scan_mode_t mode; - } set_scan_mode; - - // BTC_GAP_BT_ACT_START_DISCOVERY - struct start_disc_args { - esp_bt_inq_mode_t mode; - uint8_t inq_len; - uint8_t num_rsps; - } start_disc; - - // BTC_BT_GAP_ACT_GET_REMOTE_SERVICES - bt_bdaddr_t bda; - - // BTC_BT_GAP_ACT_GET_REMTOE_SERVICE_RECORD - struct get_rmt_srv_rcd_args { - bt_bdaddr_t bda; - esp_bt_uuid_t uuid; - } get_rmt_srv_rcd; -} btc_gap_bt_args_t; - -void btc_gap_bt_call_handler(btc_msg_t *msg); - -void btc_gap_bt_busy_level_updated(uint8_t bl_flags); - -#endif /* #if BTC_GAP_BT_INCLUDED */ - -#endif /* __BTC_GAP_BT_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_gatt_common.h b/tools/sdk/include/bluedroid/btc_gatt_common.h deleted file mode 100644 index 41b0fee54ea..00000000000 --- a/tools/sdk/include/bluedroid/btc_gatt_common.h +++ /dev/null @@ -1,37 +0,0 @@ -// 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 __BTC_GATT_COMMON_H__ -#define __BTC_GATT_COMMON_H__ - -#include "future.h" -#include "bt_types.h" -#include "bta_api.h" -#include "btc_main.h" -#include "btc_task.h" - -typedef enum { - BTC_GATT_ACT_SET_LOCAL_MTU = 0, -} btc_gatt_com_act_t; - -/* btc_ble_gattc_args_t */ -typedef union { - //BTC_GATT_ACT_SET_LOCAL_MTU, - struct set_mtu_arg { - uint16_t mtu; - } set_mtu; -} btc_ble_gatt_com_args_t; - -void btc_gatt_com_call_handler(btc_msg_t *msg); -#endif /* __BTC_GATT_COMMON_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_gatt_util.h b/tools/sdk/include/bluedroid/btc_gatt_util.h deleted file mode 100644 index 99083f74f92..00000000000 --- a/tools/sdk/include/bluedroid/btc_gatt_util.h +++ /dev/null @@ -1,40 +0,0 @@ -// 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 __BTC_GATT_UTIL_H__ -#define __BTC_GATT_UTIL_H__ - -#include "bt_types.h" -#include "bta_gatt_api.h" -#include "esp_bt_defs.h" -#include "esp_gatt_defs.h" -#include "esp_gattc_api.h" - -#define BTC_GATT_CREATE_CONN_ID(gatt_if, conn_id) ((uint16_t) ((((uint8_t)(conn_id)) << 8) | ((uint8_t)(gatt_if)))) -#define BTC_GATT_GET_CONN_ID(conn_id) (((uint16_t)(conn_id)) >> 8) -#define BTC_GATT_GET_GATT_IF(conn_id) ((uint8_t)(conn_id)) - -void btc128_to_bta_uuid(tBT_UUID *p_dest, uint8_t *p_src); -void btc_to_bta_uuid(tBT_UUID *p_dest, esp_bt_uuid_t *p_src); -void btc_to_bta_gatt_id(tBTA_GATT_ID *p_dest, esp_gatt_id_t *p_src); -void btc_to_bta_srvc_id(tBTA_GATT_SRVC_ID *p_dest, esp_gatt_srvc_id_t *p_src); -void btc_to_bta_response(tBTA_GATTS_RSP *rsp_struct, esp_gatt_rsp_t *p_rsp); - -void bta_to_btc_uuid(esp_bt_uuid_t *p_dest, tBT_UUID *p_src); -void bta_to_btc_gatt_id(esp_gatt_id_t *p_dest, tBTA_GATT_ID *p_src); -void bta_to_btc_srvc_id(esp_gatt_srvc_id_t *p_dest, tBTA_GATT_SRVC_ID *p_src); - -uint16_t set_read_value(uint8_t *gattc_if, esp_ble_gattc_cb_param_t *p_dest, tBTA_GATTC_READ *p_src); - -#endif /* __BTC_GATT_UTIL_H__*/ diff --git a/tools/sdk/include/bluedroid/btc_gattc.h b/tools/sdk/include/bluedroid/btc_gattc.h deleted file mode 100644 index 3391dd1c9f0..00000000000 --- a/tools/sdk/include/bluedroid/btc_gattc.h +++ /dev/null @@ -1,227 +0,0 @@ -// 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 __BTC_GATTC_H__ -#define __BTC_GATTC_H__ - -#include "btc_task.h" -#include "esp_bt_defs.h" -#include "esp_gatt_defs.h" -#include "esp_gattc_api.h" - -typedef enum { - BTC_GATTC_ACT_APP_REGISTER = 0, - BTC_GATTC_ACT_APP_UNREGISTER, - BTC_GATTC_ACT_OPEN, - BTC_GATTC_ACT_CLOSE, - BTC_GATTC_ACT_CFG_MTU, - BTC_GATTC_ACT_SEARCH_SERVICE, - BTC_GATTC_ACT_READ_CHAR, - BTC_GATTC_ACT_READ_MULTIPLE_CHAR, - BTC_GATTC_ACT_READ_CHAR_DESCR, - BTC_GATTC_ACT_WRITE_CHAR, - BTC_GATTC_ACT_WRITE_CHAR_DESCR, - BTC_GATTC_ACT_PREPARE_WRITE, - BTC_GATTC_ACT_PREPARE_WRITE_CHAR_DESCR, - BTC_GATTC_ACT_EXECUTE_WRITE, - BTC_GATTC_ACT_REG_FOR_NOTIFY, - BTC_GATTC_ACT_UNREG_FOR_NOTIFY, - BTC_GATTC_ACT_CACHE_REFRESH, -} btc_gattc_act_t; - -/* btc_ble_gattc_args_t */ -typedef union { - //BTC_GATTC_ACT_APP_REGISTER, - struct app_reg_arg { - uint16_t app_id; - } app_reg; - //BTC_GATTC_ACT_APP_UNREGISTER, - struct app_unreg_arg { - esp_gatt_if_t gattc_if; - } app_unreg; - //BTC_GATTC_ACT_OPEN, - struct open_arg { - esp_gatt_if_t gattc_if; - esp_bd_addr_t remote_bda; - esp_ble_addr_type_t remote_addr_type; - bool is_direct; - } open; - //BTC_GATTC_ACT_CLOSE, - struct close_arg { - uint16_t conn_id; - } close; - //BTC_GATTC_ACT_CFG_MTU, - struct cfg_mtu_arg { - uint16_t conn_id; - } cfg_mtu; - //BTC_GATTC_ACT_SEARCH_SERVICE, - struct search_srvc_arg { - uint16_t conn_id; - bool filter_uuid_enable; - esp_bt_uuid_t filter_uuid; - } search_srvc; - //BTC_GATTC_ACT_GET_CHAR, - struct get_char_arg { - uint16_t conn_id; - uint16_t handle; - } get_char; - //BTC_GATTC_ACT_GET_DESCR, - struct get_descr_arg { - uint16_t conn_id; - uint16_t handle; - } get_descr; - //BTC_GATTC_ACT_GET_FIRST_INCL_SERVICE, - struct get_first_incl_srvc_arg { - uint16_t conn_id; - uint16_t handle; - } get_first_incl_srvc; - //BTC_GATTC_ACT_GET_NEXT_INCL_SERVICE, - struct get_next_incl_srvc_arg { - uint16_t conn_id; - uint16_t handle; - } get_next_incl_srvc; - //BTC_GATTC_ACT_READ_CHAR, - struct read_char_arg { - uint16_t conn_id; - uint16_t handle; - esp_gatt_auth_req_t auth_req; - } read_char; - //BTC_GATTC_ACT_READ_MULTIPLE_CHAR - struct read_multiple_arg { - uint16_t conn_id; - uint8_t num_attr; - uint16_t handles[ESP_GATT_MAX_READ_MULTI_HANDLES]; - esp_gatt_auth_req_t auth_req; - } read_multiple; - //BTC_GATTC_ACT_READ_CHAR_DESCR, - struct read_descr_arg { - uint16_t conn_id; - uint16_t handle; - esp_gatt_auth_req_t auth_req; - } read_descr; - //BTC_GATTC_ACT_WRITE_CHAR, - struct write_char_arg { - uint16_t conn_id; - uint16_t value_len; - uint16_t handle; - uint8_t *value; - esp_gatt_write_type_t write_type; - esp_gatt_auth_req_t auth_req; - } write_char; - //BTC_GATTC_ACT_WRITE_CHAR_DESCR, - struct write_descr_arg { - uint16_t conn_id; - uint16_t value_len; - uint16_t handle; - uint8_t *value; - esp_gatt_write_type_t write_type; - esp_gatt_auth_req_t auth_req; - } write_descr; - //BTC_GATTC_ACT_PREPARE_WRITE, - struct prep_write_arg { - uint16_t conn_id; - uint16_t handle; - uint16_t offset; - uint16_t value_len; - uint8_t *value; - esp_gatt_auth_req_t auth_req; - } prep_write; - //BTC_GATTC_ACT_PREPARE_WRITE_CHAR_DESCR, - struct prep_write_descr_arg { - uint16_t conn_id; - uint16_t handle; - uint16_t offset; - uint16_t value_len; - uint8_t *value; - esp_gatt_auth_req_t auth_req; - } prep_write_descr; - //BTC_GATTC_ACT_EXECUTE_WRITE, - struct exec_write_arg { - uint16_t conn_id; - bool is_execute; - } exec_write; - //BTC_GATTC_ACT_REG_FOR_NOTIFY, - struct reg_for_notify_arg { - esp_gatt_if_t gattc_if; - esp_bd_addr_t remote_bda; - uint16_t handle; - } reg_for_notify; - //BTC_GATTC_ACT_UNREG_FOR_NOTIFY - struct unreg_for_notify_arg { - esp_gatt_if_t gattc_if; - esp_bd_addr_t remote_bda; - uint16_t handle; - } unreg_for_notify; - //BTC_GATTC_ACT_CACHE_REFRESH, - struct cache_refresh_arg { - esp_bd_addr_t remote_bda; - } cache_refresh; -} btc_ble_gattc_args_t; - -void btc_gattc_call_handler(btc_msg_t *msg); -void btc_gattc_cb_handler(btc_msg_t *msg); -void btc_gattc_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); -esp_gatt_status_t btc_ble_gattc_get_service(uint16_t conn_id, esp_bt_uuid_t *svc_uuid, - esp_gattc_service_elem_t *result, - uint16_t *count, uint16_t offset); -esp_gatt_status_t btc_ble_gattc_get_all_char(uint16_t conn_id, - uint16_t start_handle, - uint16_t end_handle, - esp_gattc_char_elem_t *result, - uint16_t *count, uint16_t offset); -esp_gatt_status_t btc_ble_gattc_get_all_descr(uint16_t conn_id, - uint16_t char_handle, - esp_gattc_descr_elem_t *result, - uint16_t *count, uint16_t offset); -esp_gatt_status_t btc_ble_gattc_get_char_by_uuid(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); -esp_gatt_status_t btc_ble_gattc_get_descr_by_uuid(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); - -esp_gatt_status_t btc_ble_gattc_get_descr_by_char_handle(uint16_t conn_id, - uint16_t char_handle, - esp_bt_uuid_t descr_uuid, - esp_gattc_descr_elem_t *result, - uint16_t *count); - -esp_gatt_status_t btc_ble_gattc_get_include_service(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); - -esp_gatt_status_t btc_ble_gattc_get_attr_count(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); - -esp_gatt_status_t btc_ble_gattc_get_db(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, - esp_gattc_db_elem_t *db, uint16_t *count); - - - - -#endif /* __BTC_GATTC_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_gatts.h b/tools/sdk/include/bluedroid/btc_gatts.h deleted file mode 100644 index 00f73875c15..00000000000 --- a/tools/sdk/include/bluedroid/btc_gatts.h +++ /dev/null @@ -1,153 +0,0 @@ -// 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 __BTC_GATTS_H__ -#define __BTC_GATTS_H__ - -#include "btc_task.h" -#include "esp_bt_defs.h" -#include "esp_gatt_defs.h" -#include "esp_gatts_api.h" - -typedef enum { - BTC_GATTS_ACT_APP_REGISTER = 0, - BTC_GATTS_ACT_APP_UNREGISTER, - BTC_GATTS_ACT_CREATE_SERVICE, - BTC_GATTS_ACT_CREATE_ATTR_TAB, - BTC_GATTS_ACT_DELETE_SERVICE, - BTC_GATTS_ACT_START_SERVICE, - BTC_GATTS_ACT_STOP_SERVICE, - BTC_GATTS_ACT_ADD_INCLUDE_SERVICE, - BTC_GATTS_ACT_ADD_CHAR, - BTC_GATTS_ACT_ADD_CHAR_DESCR, - BTC_GATTS_ACT_SEND_INDICATE, - BTC_GATTS_ACT_SEND_RESPONSE, - BTC_GATTS_ACT_SET_ATTR_VALUE, - BTC_GATTS_ACT_OPEN, - BTC_GATTS_ACT_CLOSE, -} btc_gatts_act_t; - -/* btc_ble_gatts_args_t */ -typedef union { - //BTC_GATTS_ACT_APP_REGISTER = 0, - struct app_reg_args { - uint16_t app_id; - } app_reg; - - //BTC_GATTS_ACT_APP_UNREGISTER, - struct app_unreg_args { - esp_gatt_if_t gatts_if; - } app_unreg; - - //BTC_GATTS_ACT_CREATE_SERVICE, - struct create_srvc_args { - esp_gatt_if_t gatts_if; - esp_gatt_srvc_id_t service_id; - uint16_t num_handle; - } create_srvc; - - //BTC_GATTS_ACT_CREATE_ATTR_TAB - struct create_attr_tab_args{ - esp_gatt_if_t gatts_if; - uint8_t srvc_inst_id; - uint8_t max_nb_attr; - esp_gatts_attr_db_t *gatts_attr_db; - }create_attr_tab; - - //BTC_GATTS_ACT_DELETE_SERVICE, - struct delete_srvc_args { - uint16_t service_handle; - } delete_srvc; - - //BTC_GATTS_ACT_START_SERVICE, - struct start_srvc_args { - uint16_t service_handle; - } start_srvc; - - //BTC_GATTS_ACT_STOP_SERVICE, - struct stop_srvc_args { - uint16_t service_handle; - } stop_srvc; - - //BTC_GATTS_ACT_ADD_INCLUDE_SERVICE, - struct add_incl_srvc_args { - uint16_t service_handle; - uint16_t included_service_handle; - } add_incl_srvc; - - //BTC_GATTS_ACT_ADD_CHAR, - struct add_char_args { - uint16_t service_handle; - esp_bt_uuid_t char_uuid; - esp_gatt_perm_t perm; - esp_gatt_char_prop_t property; - esp_attr_control_t attr_control; - esp_attr_value_t char_val; - } add_char; - - //BTC_GATTS_ACT_ADD_CHAR_DESCR, - struct add_descr_args { - uint16_t service_handle; - esp_bt_uuid_t descr_uuid; - esp_gatt_perm_t perm; - esp_attr_control_t attr_control; - esp_attr_value_t descr_val; - } add_descr; - - //BTC_GATTS_ACT_SEND_INDICATE, - struct send_indicate_args { - uint16_t conn_id; - uint16_t attr_handle; - bool need_confirm; - uint16_t value_len; - uint8_t *value; - } send_ind; - - //BTC_GATTS_ACT_SEND_RESPONSE, - struct send_rsp_args { - uint16_t conn_id; - uint32_t trans_id; - esp_gatt_status_t status; - esp_gatt_rsp_t *rsp; - } send_rsp; - - //BTC_GATTS_SET_ATTR_VALUE - struct set_attr_val_args { - uint16_t handle; - uint16_t length; - uint8_t *value; - } set_attr_val; - - //BTC_GATTS_ACT_OPEN, - struct open_args { - esp_gatt_if_t gatts_if; - esp_bd_addr_t remote_bda; - bool is_direct; - } open; - - //BTC_GATTS_ACT_CLOSE, - struct close_args { - uint16_t conn_id; - } close; - -} btc_ble_gatts_args_t; - - -void btc_gatts_call_handler(btc_msg_t *msg); -void btc_gatts_cb_handler(btc_msg_t *msg); -void btc_gatts_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); -esp_gatt_status_t btc_gatts_get_attr_value(uint16_t attr_handle, uint16_t *length, uint8_t **value); - - -#endif /* __BTC_GATTS_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_main.h b/tools/sdk/include/bluedroid/btc_main.h deleted file mode 100644 index b95ae0bbec2..00000000000 --- a/tools/sdk/include/bluedroid/btc_main.h +++ /dev/null @@ -1,64 +0,0 @@ -// 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 __BTC_BT_MAIN_H__ -#define __BTC_BT_MAIN_H__ - -#include "future.h" -#include "bt_types.h" -#include "bta_api.h" -#include "btc_main.h" -#include "btc_task.h" - -typedef enum { - BTC_MAIN_ACT_INIT = 0, - BTC_MAIN_ACT_DEINIT, - BTC_MAIN_ACT_ENABLE, - BTC_MAIN_ACT_DISABLE, -} btc_main_act_t; - -typedef enum { - BTC_MAIN_INIT_FUTURE = 0, - BTC_MAIN_DEINIT_FUTURE, - BTC_MAIN_ENABLE_FUTURE, - BTC_MAIN_DISABLE_FUTURE, - BTC_MAIN_FUTURE_NUM, -} btc_main_future_type_t; - -future_t **btc_main_get_future_p(btc_main_future_type_t type); - -#if 0 -typedef union { - struct btc_main_init_args { - future_t *future; - } init; - struct btc_main_deinit_args { - future_t *future; - } deinit; - struct btc_main_init_args { - future_t *future; - } enable; - struct btc_main_init_args { - future_t *future; - } disable; -} btc_main_args_t; - -bt_status_t btc_enable_bluetooth(future_t *future); -void btc_disable_bluetooth(future_t *future); -bt_status_t btc_init_bluetooth(future_t *future); -void btc_deinit_bluetooth(future_t *future); -#endif - -void btc_main_call_handler(btc_msg_t *msg); -#endif /* __BTC_BT_MAIN_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_manage.h b/tools/sdk/include/bluedroid/btc_manage.h deleted file mode 100644 index 8789f543dd1..00000000000 --- a/tools/sdk/include/bluedroid/btc_manage.h +++ /dev/null @@ -1,28 +0,0 @@ -// 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 __BTC_MANAGE_H__ -#define __BTC_MANAGE_H__ - -#include "bta_api.h" -#include "btc_task.h" -#include "esp_bt_defs.h" - -/* reset gatt callback table */ -void esp_profile_cb_reset(void); - -int btc_profile_cb_set(btc_pid_t profile_id, void *cb); -void *btc_profile_cb_get(btc_pid_t profile_id); - -#endif /* __BTC_MANAGE_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_profile_queue.h b/tools/sdk/include/bluedroid/btc_profile_queue.h deleted file mode 100644 index 39b897e96cb..00000000000 --- a/tools/sdk/include/bluedroid/btc_profile_queue.h +++ /dev/null @@ -1,55 +0,0 @@ -// 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. - -/******************************************************************************* - * - * Filename: btc_profile_queue.h - * - * Description: Bluetooth remote device connection queuing - * - *******************************************************************************/ - -#ifndef __BTC_PROFILE_QUEUE_H__ -#define __BTC_PROFILE_QUEUE_H__ - -#include "bt_defs.h" -#include "btc_task.h" - -typedef enum { - BTC_PRF_QUE_CONNECT = 0, - BTC_PRF_QUE_ADVANCE -} btc_prf_que_act_t; - -typedef bt_status_t (*btc_connect_cb_t) (bt_bdaddr_t *bda, uint16_t uuid); - -typedef struct connect_node_t { - bt_bdaddr_t bda; - uint16_t uuid; - bool busy; - btc_connect_cb_t connect_cb; -} connect_node_t; - -/* btc_prf_que_args_t */ -typedef union { - // BTC_PRF_QUE_CONNECT - connect_node_t connect_node; -} btc_prf_que_args_t; - -bt_status_t btc_queue_connect(uint16_t uuid, const bt_bdaddr_t *bda, btc_connect_cb_t connect_cb); -void btc_queue_advance(void); -bt_status_t btc_queue_connect_next(void); -void btc_queue_release(void); - -void btc_profile_queue_handler(btc_msg_t *msg); -#endif /* __BTC_PROFILE_QUEUE_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_sm.h b/tools/sdk/include/bluedroid/btc_sm.h deleted file mode 100644 index b8e95b99003..00000000000 --- a/tools/sdk/include/bluedroid/btc_sm.h +++ /dev/null @@ -1,115 +0,0 @@ -// 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. - - -/***************************************************************************** - * - * Filename: btc_sm.h - * - * Description: Generic BTC state machine API - * - *****************************************************************************/ - -#ifndef __BTC_SM_H__ -#define __BTC_SM_H__ - -/***************************************************************************** -** Constants & Macros -******************************************************************************/ - -/* Generic Enter/Exit state machine events */ -#define BTC_SM_ENTER_EVT 0xFFFF -#define BTC_SM_EXIT_EVT 0xFFFE - - -/***************************************************************************** -** Type definitions and return values -******************************************************************************/ -typedef UINT32 btc_sm_state_t; -typedef UINT32 btc_sm_event_t; -typedef void *btc_sm_handle_t; -typedef BOOLEAN (* btc_sm_handler_t)(btc_sm_event_t event, void *data); - - -/***************************************************************************** -** Functions -** -** NOTE: THESE APIs SHOULD BE INVOKED ONLY IN THE BTC CONTEXT -** -******************************************************************************/ - -/***************************************************************************** -** -** Function btc_sm_init -** -** Description Initializes the state machine with the state handlers -** The caller should ensure that the table and the corresponding -** states match. The location that 'p_handlers' points to shall -** be available until the btc_sm_shutdown API is invoked. -** -** Returns Returns a pointer to the initialized state machine handle. -** -******************************************************************************/ -btc_sm_handle_t btc_sm_init(const btc_sm_handler_t *p_handlers, - btc_sm_state_t initial_state); - -/***************************************************************************** -** -** Function btc_sm_shutdown -** -** Description Tears down the state machine -** -** Returns None -** -******************************************************************************/ -void btc_sm_shutdown(btc_sm_handle_t handle); - -/***************************************************************************** -** -** Function btc_sm_get_state -** -** Description Fetches the current state of the state machine -** -** Returns Current state -** -******************************************************************************/ -btc_sm_state_t btc_sm_get_state(btc_sm_handle_t handle); - -/***************************************************************************** -** -** Function btc_sm_dispatch -** -** Description Dispatches the 'event' along with 'data' to the current state handler -** -** Returns Returns BT_STATUS_OK on success, BT_STATUS_FAIL otherwise -** -******************************************************************************/ -bt_status_t btc_sm_dispatch(btc_sm_handle_t handle, btc_sm_event_t event, - void *data); - -/***************************************************************************** -** -** Function btc_sm_change_state -** -** Description Make a transition to the new 'state'. The 'BTC_SM_EXIT_EVT' -** shall be invoked before exiting the current state. The -** 'BTC_SM_ENTER_EVT' shall be invoked before entering the new state -** -** -** Returns Returns BT_STATUS_OK on success, BT_STATUS_FAIL otherwise -** -******************************************************************************/ -bt_status_t btc_sm_change_state(btc_sm_handle_t handle, btc_sm_state_t state); - -#endif /* __BTC_SM_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_spp.h b/tools/sdk/include/bluedroid/btc_spp.h deleted file mode 100644 index 631c69646e7..00000000000 --- a/tools/sdk/include/bluedroid/btc_spp.h +++ /dev/null @@ -1,89 +0,0 @@ -// 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 __BTC_SPP_H__ -#define __BTC_SPP_H__ - -#include "btc_task.h" -#include "esp_bt_defs.h" -#include "esp_spp_api.h" -#include "bt_target.h" -#include "bta_jv_api.h" - -#if (defined BTC_SPP_INCLUDED && BTC_SPP_INCLUDED == TRUE) - -#define ESP_SPP_MAX_SESSION BTA_JV_MAX_RFC_SR_SESSION -#define ESP_SPP_SERVER_NAME_MAX 32 - -typedef enum { - BTC_SPP_ACT_INIT = 0, - BTC_SPP_ACT_UNINIT, - BTC_SPP_ACT_START_DISCOVERY, - BTC_SPP_ACT_CONNECT, - BTC_SPP_ACT_DISCONNECT, - BTC_SPP_ACT_START_SRV, - BTC_SPP_ACT_WRITE, -} btc_spp_act_t; - -/* btc_spp_args_t */ -typedef union { - //BTC_SPP_ACT_INIT - struct init_arg { - } init; - //BTC_SPP_ACT_UNINIT - struct uninit_arg { - } uninit; - - //BTC_SPP_ACT_START_DISCOVERY - struct start_discovery_arg { - BD_ADDR bd_addr; - UINT16 num_uuid; - tSDP_UUID *p_uuid_list; - } start_discovery; - //BTC_SPP_ACT_CONNECT - struct connect_arg { - esp_spp_sec_t sec_mask; - esp_spp_role_t role; - UINT8 remote_scn; - esp_bd_addr_t peer_bd_addr; - } connect; - //BTC_SPP_ACT_DISCONNECT - struct disconnect_arg { - UINT32 handle; - } disconnect; - //BTC_SPP_ACT_START_SRV - struct start_srv_arg { - esp_spp_sec_t sec_mask; - esp_spp_role_t role; - UINT8 local_scn; - UINT8 max_session; - char name[ESP_SPP_SERVER_NAME_MAX + 1]; - } start_srv; - //BTC_SPP_ACT_WRITE - struct write_arg { - UINT32 handle; - int len; - UINT8 *p_data; - } write; - -} btc_spp_args_t; - - -void btc_spp_call_handler(btc_msg_t *msg); -void btc_spp_cb_handler(btc_msg_t *msg); -void btc_spp_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); - - -#endif ///defined BTC_SPP_INCLUDED && BTC_SPP_INCLUDED == TRUE -#endif ///__BTC_SPP_H__ \ No newline at end of file diff --git a/tools/sdk/include/bluedroid/btc_storage.h b/tools/sdk/include/bluedroid/btc_storage.h deleted file mode 100644 index 9e69b4139e8..00000000000 --- a/tools/sdk/include/bluedroid/btc_storage.h +++ /dev/null @@ -1,68 +0,0 @@ -// 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 __BTC_STORAGE_H__ -#define __BTC_STORAGE_H__ - -#include -#include "bt_defs.h" -#include "bt_types.h" - - -#define BTC_STORAGE_DEV_CLASS_STR "DevClass" -#define BTC_STORAGE_LINK_KEY_STR "LinkKey" /* same as the ble */ -#define BTC_STORAGE_LINK_KEY_TYPE_STR "LinkKeyType" -#define BTC_STORAGE_PIN_LENGTH_STR "PinLength" - -/******************************************************************************* -** -** Function btc_storage_add_bonded_device -** -** Description BTC storage API - Adds the newly bonded device to NVRAM -** along with the link-key, Key type and Pin key length -** -** Returns BT_STATUS_SUCCESS if the store was successful, -** BT_STATUS_FAIL otherwise -** -*******************************************************************************/ -bt_status_t btc_storage_add_bonded_device(bt_bdaddr_t *remote_bd_addr, - LINK_KEY link_key, - uint8_t key_type, - uint8_t pin_length); - -/******************************************************************************* -** -** Function btc_storage_remove_bonded_device -** -** Description BTC storage API - Deletes the bonded device from NVRAM -** -** Returns BT_STATUS_SUCCESS if the deletion was successful, -** BT_STATUS_FAIL otherwise -** -*******************************************************************************/ -bt_status_t btc_storage_remove_bonded_device(bt_bdaddr_t *remote_bd_addr); - -/******************************************************************************* -** -** Function btc_storage_remove_bonded_device -** -** Description BTC storage API - Deletes the bonded device from NVRAM -** -** Returns BT_STATUS_SUCCESS if the deletion was successful, -** BT_STATUS_FAIL otherwise -** -*******************************************************************************/ -bt_status_t btc_storage_load_bonded_devices(void); - -#endif /* BTC_STORAGE_H */ diff --git a/tools/sdk/include/bluedroid/btc_task.h b/tools/sdk/include/bluedroid/btc_task.h deleted file mode 100644 index 16388c685bb..00000000000 --- a/tools/sdk/include/bluedroid/btc_task.h +++ /dev/null @@ -1,73 +0,0 @@ -// 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 __BTC_TASK_H__ -#define __BTC_TASK_H__ - -#include -#include "bt_target.h" -#include "bt_defs.h" -#include "thread.h" - -typedef struct btc_msg { - uint8_t sig; //event signal - uint8_t aid; //application id - uint8_t pid; //profile id - uint8_t act; //profile action, defined in seprerate header files - void *arg; //param for btc function or function param -} btc_msg_t; - -typedef enum { - BTC_SIG_API_CALL = 0, // APP TO STACK - BTC_SIG_API_CB, // STACK TO APP - BTC_SIG_NUM, -} btc_sig_t; //btc message type - -typedef enum { - BTC_PID_MAIN_INIT = 0, - BTC_PID_DEV, - BTC_PID_GATTS, -#if (GATTC_INCLUDED == TRUE) - BTC_PID_GATTC, -#endif ///GATTC_INCLUDED == TRUE - BTC_PID_GATT_COMMON, - BTC_PID_GAP_BLE, - BTC_PID_BLE_HID, - BTC_PID_SPPLIKE, - BTC_PID_BLUFI, - BTC_PID_DM_SEC, - BTC_PID_ALARM, -#if CONFIG_CLASSIC_BT_ENABLED - BTC_PID_GAP_BT, - BTC_PID_PRF_QUE, - BTC_PID_A2DP, - BTC_PID_AVRC, - BTC_PID_SPP, -#endif /* CONFIG_CLASSIC_BT_ENABLED */ - BTC_PID_NUM, -} btc_pid_t; //btc profile id - -typedef struct { - void (* btc_call)(btc_msg_t *msg); - void (* btc_cb)(btc_msg_t *msg); -} btc_func_t; - -typedef void (* btc_arg_deep_copy_t)(btc_msg_t *msg, void *dst, void *src); - -bt_status_t btc_transfer_context(btc_msg_t *msg, void *arg, int arg_len, btc_arg_deep_copy_t copy_func); - -int btc_init(void); -void btc_deinit(void); - -#endif /* __BTC_TASK_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_util.h b/tools/sdk/include/bluedroid/btc_util.h deleted file mode 100644 index d2bfdcca877..00000000000 --- a/tools/sdk/include/bluedroid/btc_util.h +++ /dev/null @@ -1,47 +0,0 @@ -// 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 __BTC_UTIL_H__ -#define __BTC_UTIL_H__ - -#include -#include "bt_types.h" -#include "bt_defs.h" -#include "esp_bt_defs.h" - -/******************************************************************************* -** Constants & Macros -********************************************************************************/ -#define CASE_RETURN_STR(const) case const: return #const; - -/******************************************************************************* -** Type definitions for callback functions -********************************************************************************/ -typedef char bdstr_t[18]; - - -/******************************************************************************* -** Functions -********************************************************************************/ -const char *dump_rc_event(UINT8 event); -const char *dump_rc_notification_event_id(UINT8 event_id); -const char *dump_rc_pdu(UINT8 pdu); - -UINT32 devclass2uint(DEV_CLASS dev_class); -void uint2devclass(UINT32 dev, DEV_CLASS dev_class); -void uuid128_be_to_esp_uuid(esp_bt_uuid_t *u, uint8_t* uuid128); - -void uuid_to_string_legacy(bt_uuid_t *p_uuid, char *str); - -#endif /* __BTC_UTIL_H__ */ diff --git a/tools/sdk/include/bluedroid/bte.h b/tools/sdk/include/bluedroid/bte.h deleted file mode 100644 index 171967cfc38..00000000000 --- a/tools/sdk/include/bluedroid/bte.h +++ /dev/null @@ -1,116 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2001-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * this file contains constants and definitions for the bte project - * - ******************************************************************************/ -#ifndef BTE_H -#define BTE_H - -//#include -//#include -//#include -#include "bt_target.h" - -/* by default on shutdown, baudrate is reset 115kbits. this should NOT be need for platforms - * that kill BTE driver and remove/reset BT chip - */ -#ifndef BTE_RESET_BAUD_ON_BT_DISABLE -#define BTE_RESET_BAUD_ON_BT_DISABLE TRUE -#endif - -/* Target Modes (based on jumper settings on hardware [see user manual]) */ -enum { - /* BTE BBY */ - /* J3 J4 SW3-3 SW3-2 SW3-1 */ - /* -------------------------------------------- */ - BTE_MODE_SERIAL_APP, /* OUT OUT OFF OFF OFF Sample serial port application */ - BTE_MODE_APPL, /* IN OUT OFF OFF ON Target used with Tester through RPC */ - BTE_MODE_RESERVED, /* OUT IN OFF ON OFF Reserved */ - BTE_MODE_SAMPLE_APPS, /* IN IN OFF ON ON Sample applications (ICP/HSP) */ - BTE_MODE_DONGLE, /* not yet supported ON OFF OFF Dongle mode */ - BTE_MODE_APPL_PROTOCOL_TRACE, /* this is a fake mode do allow protocol tracing in application without rpc */ - BTE_MODE_INVALID -}; - -extern volatile UINT8 bte_target_mode; /* indicates the mode that the board is running in */ - -/* Startup options */ -extern UINT32 bte_startup_options; /* Switch and jumper settings at startup */ -void bte_get_startup_options(UINT32 *p_options); /* Platform specific function for getting startup options */ - -#define BTE_OPTIONS_TARGET_MODE_MASK 0x00000007 /* bits 2-0 indicate target mode (QuickConnect: jp3 & jp4, BBY: SW3-1 & SW3-2)*/ - - -/**************************************************************************** - * Definitions to define which type of application gets built - ****************************************************************************/ -#define BUILD_HCITOOL FALSE -#define BUILD_L2PING FALSE - - -#define LINUX_FM_DRIVER_INCLUDED FALSE - - -/* hcisu userial operations. should probably go into bt_types to avoid collisions! */ -#define BT_EVT_TO_HCISU_USERIAL_OP (0x0080 | BT_EVT_HCISU) -/* operation for above hcisu event */ -#define BT_HCISU_USERIAL_OPEN (0) /* open serial port calling USERIAL_Open() */ -#define BT_HCISU_USERIAL_CLOSE (1) /* close userial port */ -/* options associated with close op */ -#define BT_HCISU_USERIAL_CL_NO_DIS_BT 0 /* do not touch bt_wake and power gpio */ -#define BT_HCISU_USERIAL_CL_DIS_BT 1 /* put power and bt_wake into defined off state to preserve - power */ -/* status codes for callback */ -/* -#define BTE_HCISU_USERIAL_FAIL 0 -#define BTE_HCISU_USERIAL_OK 1 -typedef void (tUSERIAL_MSG_CBACK) (int status); -typedef struct tHCISU_USERIAL_MSG_tag { - BT_HDR hdr; - tUSERIAL_MSG_CBACK *p_cback; - UINT8 port; // port number - UINT8 op; - UINT8 option; // option for operation. depends on operation -} tHCISU_USERIAL_MSG; - -extern void bte_hcisu_userial_oper( tUSERIAL_MSG_CBACK *p_cback, UINT8 port, UINT8 op, UINT8 option ); -*/ - -/* Pointer to function for sending HCI commands and data to the HCI tranport */ -extern int (*p_bte_hci_send)(UINT16 port, BT_HDR *p_msg); - - -/* Protocol trace mask */ -extern UINT32 bte_proto_trace_mask; - -typedef struct tBAUD_REG_tag { - UINT8 DHBR; - UINT8 DLBR; - UINT8 ExplicitBaudRate0; - UINT8 ExplicitBaudRate1; - UINT8 ExplicitBaudRate2; - UINT8 ExplicitBaudRate3; -} tBAUD_REG; - - -extern const tBAUD_REG baud_rate_regs[]; - -#endif /* BTE_H */ diff --git a/tools/sdk/include/bluedroid/bte_appl.h b/tools/sdk/include/bluedroid/bte_appl.h deleted file mode 100644 index 4850250b8ac..00000000000 --- a/tools/sdk/include/bluedroid/bte_appl.h +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This is the interface file for the bte application task - * - ******************************************************************************/ - -#pragma once - -typedef struct { -#if ((BLE_INCLUDED == TRUE) && (SMP_INCLUDED == TRUE)) - UINT8 ble_auth_req; - UINT8 ble_io_cap; - UINT8 ble_init_key; - UINT8 ble_resp_key; - UINT8 ble_max_key_size; -#endif -} tBTE_APPL_CFG; - -extern tBTE_APPL_CFG bte_appl_cfg; diff --git a/tools/sdk/include/bluedroid/btm_api.h b/tools/sdk/include/bluedroid/btm_api.h deleted file mode 100644 index b685cdb7783..00000000000 --- a/tools/sdk/include/bluedroid/btm_api.h +++ /dev/null @@ -1,4101 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains the Bluetooth Manager (BTM) API function external - * definitions. - * - ******************************************************************************/ -#ifndef BTM_API_H -#define BTM_API_H - -#include "bt_defs.h" -#include "bt_target.h" -#include "hcidefs.h" - -#if SDP_INCLUDED == TRUE -#include "sdp_api.h" -#endif - -#if SMP_INCLUDED == TRUE -#include "smp_api.h" -#endif -/***************************************************************************** -** DEVICE CONTROL and COMMON -*****************************************************************************/ -/***************************** -** Device Control Constants -******************************/ -/* Maximum number of bytes allowed for vendor specific command parameters */ -#define BTM_MAX_VENDOR_SPECIFIC_LEN HCI_COMMAND_SIZE - -/* BTM application return status codes */ -enum { - BTM_SUCCESS = 0, /* 0 Command succeeded */ - BTM_CMD_STARTED, /* 1 Command started OK. */ - BTM_BUSY, /* 2 Device busy with another command */ - BTM_NO_RESOURCES, /* 3 No resources to issue command */ - BTM_MODE_UNSUPPORTED, /* 4 Request for 1 or more unsupported modes */ - BTM_ILLEGAL_VALUE, /* 5 Illegal parameter value */ - BTM_WRONG_MODE, /* 6 Device in wrong mode for request */ - BTM_UNKNOWN_ADDR, /* 7 Unknown remote BD address */ - BTM_DEVICE_TIMEOUT, /* 8 Device timeout */ - BTM_BAD_VALUE_RET, /* 9 A bad value was received from HCI */ - BTM_ERR_PROCESSING, /* 10 Generic error */ - BTM_NOT_AUTHORIZED, /* 11 Authorization failed */ - BTM_DEV_RESET, /* 12 Device has been reset */ - BTM_CMD_STORED, /* 13 request is stored in control block */ - BTM_ILLEGAL_ACTION, /* 14 state machine gets illegal command */ - BTM_DELAY_CHECK, /* 15 delay the check on encryption */ - BTM_SCO_BAD_LENGTH, /* 16 Bad SCO over HCI data length */ - BTM_SUCCESS_NO_SECURITY, /* 17 security passed, no security set */ - BTM_FAILED_ON_SECURITY, /* 18 security failed */ - BTM_REPEATED_ATTEMPTS, /* 19 repeated attempts for LE security requests */ - BTM_MODE4_LEVEL4_NOT_SUPPORTED, /* 20 Secure Connections Only Mode can't be supported */ - BTM_PEER_LE_DATA_LEN_UNSUPPORTED, /* 21 peer setting data length is unsupported*/ - BTM_CONTROL_LE_DATA_LEN_UNSUPPORTED,/* 22 controller setting data length is unsupported*/ - BTM_SET_PRIVACY_SUCCESS, /* 23 enable/disable local privacy success */ - BTM_SET_PRIVACY_FAIL, /* 24 enable/disable local privacy failed*/ - BTM_SET_STATIC_RAND_ADDR_FAIL, /* 25 Command failed */ - BTM_INVALID_STATIC_RAND_ADDR, /* 26 invalid static rand addr */ -}; - -typedef uint8_t tBTM_STATUS; - -#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE) -typedef enum { - BTM_BR_ONE, /*0 First state or BR/EDR scan 1*/ - BTM_BLE_ONE, /*1BLE scan 1*/ - BTM_BR_TWO, /*2 BR/EDR scan 2*/ - BTM_BLE_TWO, /*3 BLE scan 2*/ - BTM_FINISH, /*4 End of Interleave Scan, or normal scan*/ - BTM_NO_INTERLEAVING /*5 No Interleaving*/ -} btm_inq_state; -#endif - - - -/************************* -** Device Control Types -**************************/ -#define BTM_DEVICE_ROLE_BR 0x01 -#define BTM_DEVICE_ROLE_DUAL 0x02 -#define BTM_MAX_DEVICE_ROLE BTM_DEVICE_ROLE_DUAL -typedef UINT8 tBTM_DEVICE_ROLE; - -/* Device name of peer (may be truncated to save space in BTM database) */ -typedef UINT8 tBTM_BD_NAME[BTM_MAX_REM_BD_NAME_LEN + 1]; - -/* Structure returned with local version information */ -typedef struct { - UINT8 hci_version; - UINT16 hci_revision; - UINT8 lmp_version; - UINT16 manufacturer; - UINT16 lmp_subversion; -} tBTM_VERSION_INFO; - -/* Structure returned with Vendor Specific Command complete callback */ -typedef struct { - UINT16 opcode; - UINT16 param_len; - UINT8 *p_param_buf; -} tBTM_VSC_CMPL; - -#define BTM_VSC_CMPL_DATA_SIZE (BTM_MAX_VENDOR_SPECIFIC_LEN + sizeof(tBTM_VSC_CMPL)) -/************************************************** -** Device Control and General Callback Functions -***************************************************/ -/* Callback function for when device status changes. Appl must poll for -** what the new state is (BTM_IsDeviceUp). The event occurs whenever the stack -** has detected that the controller status has changed. This asynchronous event -** is enabled/disabled by calling BTM_RegisterForDeviceStatusNotif(). -*/ -enum { - BTM_DEV_STATUS_UP, - BTM_DEV_STATUS_DOWN, - BTM_DEV_STATUS_CMD_TOUT -}; - -typedef UINT8 tBTM_DEV_STATUS; - -typedef struct { - UINT16 rx_len; - UINT16 tx_len; -}tBTM_LE_SET_PKT_DATA_LENGTH_PARAMS; - -typedef struct { - UINT16 min_conn_int; - UINT16 max_conn_int; - UINT16 conn_int; - UINT16 slave_latency; - UINT16 supervision_tout; -}tBTM_LE_UPDATE_CONN_PRAMS; - -typedef enum{ - BTM_WHITELIST_REMOVE = 0X00, - BTM_WHITELIST_ADD = 0X01, -}tBTM_WL_OPERATION; - - -typedef void (tBTM_DEV_STATUS_CB) (tBTM_DEV_STATUS status); - - -/* Callback function for when a vendor specific event occurs. The length and -** array of returned parameter bytes are included. This asynchronous event -** is enabled/disabled by calling BTM_RegisterForVSEvents(). -*/ -typedef void (tBTM_VS_EVT_CB) (UINT8 len, UINT8 *p); - - -/* General callback function for notifying an application that a synchronous -** BTM function is complete. The pointer contains the address of any returned data. -*/ -typedef void (tBTM_CMPL_CB) (void *p1); - -/* VSC callback function for notifying an application that a synchronous -** BTM function is complete. The pointer contains the address of any returned data. -*/ -typedef void (tBTM_VSC_CMPL_CB) (tBTM_VSC_CMPL *p1); - -/* Callback for apps to check connection and inquiry filters. -** Parameters are the BD Address of remote and the Dev Class of remote. -** If the app returns none zero, the connection or inquiry result will be dropped. -*/ -typedef UINT8 (tBTM_FILTER_CB) (BD_ADDR bd_addr, DEV_CLASS dc); - -typedef void (tBTM_UPDATE_CONN_PARAM_CBACK) (UINT8 status, BD_ADDR bd_addr, tBTM_LE_UPDATE_CONN_PRAMS *update_conn_params); - -typedef void (tBTM_SET_PKT_DATA_LENGTH_CBACK) (UINT8 status, tBTM_LE_SET_PKT_DATA_LENGTH_PARAMS *data_length_params); - -typedef void (tBTM_SET_RAND_ADDR_CBACK) (UINT8 status); - -typedef void (tBTM_ADD_WHITELIST_CBACK) (UINT8 status, tBTM_WL_OPERATION wl_opration); - -typedef void (tBTM_SET_LOCAL_PRIVACY_CBACK) (UINT8 status); - - -/***************************************************************************** -** DEVICE DISCOVERY - Inquiry, Remote Name, Discovery, Class of Device -*****************************************************************************/ -/******************************* -** Device Discovery Constants -********************************/ -/* Discoverable modes */ -#define BTM_NON_DISCOVERABLE 0 -#define BTM_LIMITED_DISCOVERABLE 1 -#define BTM_GENERAL_DISCOVERABLE 2 -#define BTM_DISCOVERABLE_MASK (BTM_LIMITED_DISCOVERABLE|BTM_GENERAL_DISCOVERABLE) -#define BTM_MAX_DISCOVERABLE BTM_GENERAL_DISCOVERABLE -/* high byte for BLE Discoverable modes */ -#define BTM_BLE_NON_DISCOVERABLE 0x0000 -#define BTM_BLE_LIMITED_DISCOVERABLE 0x0100 -#define BTM_BLE_GENERAL_DISCOVERABLE 0x0200 -#define BTM_BLE_MAX_DISCOVERABLE BTM_BLE_GENERAL_DISCOVERABLE -#define BTM_BLE_DISCOVERABLE_MASK (BTM_BLE_NON_DISCOVERABLE|BTM_BLE_LIMITED_DISCOVERABLE|BTM_BLE_GENERAL_DISCOVERABLE) - -/* Connectable modes */ -#define BTM_NON_CONNECTABLE 0 -#define BTM_CONNECTABLE 1 -#define BTM_CONNECTABLE_MASK (BTM_NON_CONNECTABLE | BTM_CONNECTABLE) -/* high byte for BLE Connectable modes */ -#define BTM_BLE_NON_CONNECTABLE 0x0000 -#define BTM_BLE_CONNECTABLE 0x0100 -#define BTM_BLE_MAX_CONNECTABLE BTM_BLE_CONNECTABLE -#define BTM_BLE_CONNECTABLE_MASK (BTM_BLE_NON_CONNECTABLE | BTM_BLE_CONNECTABLE) - -/* Inquiry modes - * Note: These modes are associated with the inquiry active values (BTM_*ACTIVE) */ -#define BTM_INQUIRY_NONE 0 -#define BTM_GENERAL_INQUIRY 0x01 -#define BTM_LIMITED_INQUIRY 0x02 -#define BTM_BR_INQUIRY_MASK (BTM_GENERAL_INQUIRY | BTM_LIMITED_INQUIRY) - -/* high byte of inquiry mode for BLE inquiry mode */ -#define BTM_BLE_INQUIRY_NONE 0x00 -#define BTM_BLE_GENERAL_INQUIRY 0x10 -#define BTM_BLE_LIMITED_INQUIRY 0x20 -#define BTM_BLE_INQUIRY_MASK (BTM_BLE_GENERAL_INQUIRY|BTM_BLE_LIMITED_INQUIRY) - -/* BTM_IsInquiryActive return values (Bit Mask) - * Note: These bit masks are associated with the inquiry modes (BTM_*_INQUIRY) */ -#define BTM_INQUIRY_INACTIVE 0x0 /* no inquiry in progress */ -#define BTM_GENERAL_INQUIRY_ACTIVE BTM_GENERAL_INQUIRY /* a general inquiry is in progress */ -#define BTM_LIMITED_INQUIRY_ACTIVE BTM_LIMITED_INQUIRY /* a limited inquiry is in progress */ -#define BTM_PERIODIC_INQUIRY_ACTIVE 0x8 /* a periodic inquiry is active */ -#define BTM_SSP_INQUIRY_ACTIVE 0x4 /* SSP is active, so inquiry is disallowed (work around for FW bug) */ -#define BTM_LE_GENERAL_INQUIRY_ACTIVE BTM_BLE_GENERAL_INQUIRY /* a general inquiry is in progress */ -#define BTM_LE_LIMITED_INQUIRY_ACTIVE BTM_BLE_LIMITED_INQUIRY /* a limited inquiry is in progress */ - -/* inquiry activity mask */ -#define BTM_BR_INQ_ACTIVE_MASK (BTM_GENERAL_INQUIRY_ACTIVE|BTM_LIMITED_INQUIRY_ACTIVE|BTM_PERIODIC_INQUIRY_ACTIVE) /* BR/EDR inquiry activity mask */ -#define BTM_BLE_SCAN_ACTIVE_MASK 0x01F0 /* LE scan activity mask */ -#define BTM_BLE_INQ_ACTIVE_MASK (BTM_LE_GENERAL_INQUIRY_ACTIVE|BTM_LE_LIMITED_INQUIRY_ACTIVE) /* LE inquiry activity mask*/ -#define BTM_INQUIRY_ACTIVE_MASK (BTM_BR_INQ_ACTIVE_MASK | BTM_BLE_INQ_ACTIVE_MASK) /* inquiry activity mask */ - -/* Define scan types */ -#define BTM_SCAN_TYPE_STANDARD 0 -#define BTM_SCAN_TYPE_INTERLACED 1 /* 1.2 devices only */ - -/* Define inquiry results mode */ -#define BTM_INQ_RESULT_STANDARD 0 -#define BTM_INQ_RESULT_WITH_RSSI 1 -#define BTM_INQ_RESULT_EXTENDED 2 - -#define BTM_INQ_RES_IGNORE_RSSI 0x7f /* RSSI value not supplied (ignore it) */ - -/* Inquiry Filter Condition types (see tBTM_INQ_PARMS) */ -#define BTM_CLR_INQUIRY_FILTER 0 /* Inquiry Filtering is turned off */ -#define BTM_FILTER_COND_DEVICE_CLASS HCI_FILTER_COND_DEVICE_CLASS /* Filter on device class */ -#define BTM_FILTER_COND_BD_ADDR HCI_FILTER_COND_BD_ADDR /* Filter on device addr */ - -/* State of the remote name retrieval during inquiry operations. -** Used in the tBTM_INQ_INFO structure, and returned in the -** BTM_InqDbRead, BTM_InqDbFirst, and BTM_InqDbNext functions. -** The name field is valid when the state returned is -** BTM_INQ_RMT_NAME_DONE */ -#define BTM_INQ_RMT_NAME_EMPTY 0 -#define BTM_INQ_RMT_NAME_PENDING 1 -#define BTM_INQ_RMT_NAME_DONE 2 -#define BTM_INQ_RMT_NAME_FAILED 3 - -/********************************* - *** Class of Device constants *** - *********************************/ -#define BTM_FORMAT_TYPE_1 0x00 - -/**************************** -** minor device class field -*****************************/ - -/* 0x00 is used as unclassified for all minor device classes */ -#define BTM_COD_MINOR_UNCLASSIFIED 0x00 - -/* minor device class field for Computer Major Class */ -/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ -#define BTM_COD_MINOR_DESKTOP_WORKSTATION 0x04 -#define BTM_COD_MINOR_SERVER_COMPUTER 0x08 -#define BTM_COD_MINOR_LAPTOP 0x0C -#define BTM_COD_MINOR_HANDHELD_PC_PDA 0x10 /* clam shell */ -#define BTM_COD_MINOR_PALM_SIZE_PC_PDA 0x14 -#define BTM_COD_MINOR_WEARABLE_COMPUTER 0x18 /* watch sized */ - -/* minor device class field for Phone Major Class */ -/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ -#define BTM_COD_MINOR_CELLULAR 0x04 -#define BTM_COD_MINOR_CORDLESS 0x08 -#define BTM_COD_MINOR_SMART_PHONE 0x0C -#define BTM_COD_MINOR_WIRED_MDM_V_GTWY 0x10 /* wired modem or voice gatway */ -#define BTM_COD_MINOR_ISDN_ACCESS 0x14 - -/* minor device class field for LAN Access Point Major Class */ -/* Load Factor Field bit 5-7 */ -#define BTM_COD_MINOR_FULLY_AVAILABLE 0x00 -#define BTM_COD_MINOR_1_17_UTILIZED 0x20 -#define BTM_COD_MINOR_17_33_UTILIZED 0x40 -#define BTM_COD_MINOR_33_50_UTILIZED 0x60 -#define BTM_COD_MINOR_50_67_UTILIZED 0x80 -#define BTM_COD_MINOR_67_83_UTILIZED 0xA0 -#define BTM_COD_MINOR_83_99_UTILIZED 0xC0 -#define BTM_COD_MINOR_NO_SERVICE_AVAILABLE 0xE0 -/* sub-Field bit 2-4 */ -/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ - -/* minor device class field for Audio/Video Major Class */ -/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ -#define BTM_COD_MINOR_CONFM_HEADSET 0x04 -#define BTM_COD_MINOR_CONFM_HANDSFREE 0x08 -#define BTM_COD_MINOR_MICROPHONE 0x10 -#define BTM_COD_MINOR_LOUDSPEAKER 0x14 -#define BTM_COD_MINOR_HEADPHONES 0x18 -#define BTM_COD_MINOR_PORTABLE_AUDIO 0x1C -#define BTM_COD_MINOR_CAR_AUDIO 0x20 -#define BTM_COD_MINOR_SET_TOP_BOX 0x24 -#define BTM_COD_MINOR_HIFI_AUDIO 0x28 -#define BTM_COD_MINOR_VCR 0x2C -#define BTM_COD_MINOR_VIDEO_CAMERA 0x30 -#define BTM_COD_MINOR_CAMCORDER 0x34 -#define BTM_COD_MINOR_VIDEO_MONITOR 0x38 -#define BTM_COD_MINOR_VIDDISP_LDSPKR 0x3C -#define BTM_COD_MINOR_VIDEO_CONFERENCING 0x40 -#define BTM_COD_MINOR_GAMING_TOY 0x48 - -/* minor device class field for Peripheral Major Class */ -/* Bits 6-7 independently specify mouse, keyboard, or combo mouse/keyboard */ -#define BTM_COD_MINOR_KEYBOARD 0x40 -#define BTM_COD_MINOR_POINTING 0x80 -#define BTM_COD_MINOR_COMBO 0xC0 -/* Bits 2-5 OR'd with selection from bits 6-7 */ -/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ -#define BTM_COD_MINOR_JOYSTICK 0x04 -#define BTM_COD_MINOR_GAMEPAD 0x08 -#define BTM_COD_MINOR_REMOTE_CONTROL 0x0C -#define BTM_COD_MINOR_SENSING_DEVICE 0x10 -#define BTM_COD_MINOR_DIGITIZING_TABLET 0x14 -#define BTM_COD_MINOR_CARD_READER 0x18 /* e.g. SIM card reader */ -#define BTM_COD_MINOR_DIGITAL_PAN 0x1C -#define BTM_COD_MINOR_HAND_SCANNER 0x20 -#define BTM_COD_MINOR_HAND_GESTURAL_INPUT 0x24 - -/* minor device class field for Imaging Major Class */ -/* Bits 5-7 independently specify display, camera, scanner, or printer */ -#define BTM_COD_MINOR_DISPLAY 0x10 -#define BTM_COD_MINOR_CAMERA 0x20 -#define BTM_COD_MINOR_SCANNER 0x40 -#define BTM_COD_MINOR_PRINTER 0x80 -/* Bits 2-3 Reserved */ -/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ - -/* minor device class field for Wearable Major Class */ -/* Bits 2-7 meaningful */ -#define BTM_COD_MINOR_WRIST_WATCH 0x04 -#define BTM_COD_MINOR_PAGER 0x08 -#define BTM_COD_MINOR_JACKET 0x0C -#define BTM_COD_MINOR_HELMET 0x10 -#define BTM_COD_MINOR_GLASSES 0x14 - -/* minor device class field for Toy Major Class */ -/* Bits 2-7 meaningful */ -#define BTM_COD_MINOR_ROBOT 0x04 -#define BTM_COD_MINOR_VEHICLE 0x08 -#define BTM_COD_MINOR_DOLL_ACTION_FIGURE 0x0C -#define BTM_COD_MINOR_CONTROLLER 0x10 -#define BTM_COD_MINOR_GAME 0x14 - -/* minor device class field for Health Major Class */ -/* Bits 2-7 meaningful */ -#define BTM_COD_MINOR_BLOOD_MONITOR 0x04 -#define BTM_COD_MINOR_THERMOMETER 0x08 -#define BTM_COD_MINOR_WEIGHING_SCALE 0x0C -#define BTM_COD_MINOR_GLUCOSE_METER 0x10 -#define BTM_COD_MINOR_PULSE_OXIMETER 0x14 -#define BTM_COD_MINOR_HEART_PULSE_MONITOR 0x18 -#define BTM_COD_MINOR_HEALTH_DATA_DISPLAY 0x1C -#define BTM_COD_MINOR_STEP_COUNTER 0x20 -#define BTM_COD_MINOR_BODY_COM_ANALYZER 0x24 -#define BTM_COD_MINOR_PEAK_FLOW_MONITOR 0x28 -#define BTM_COD_MINOR_MEDICATION_MONITOR 0x2C -#define BTM_COD_MINOR_KNEE_PROSTHESIS 0x30 -#define BTM_COD_MINOR_ANKLE_PROSTHESIS 0x34 - - -/*************************** -** major device class field -****************************/ -#define BTM_COD_MAJOR_MISCELLANEOUS 0x00 -#define BTM_COD_MAJOR_COMPUTER 0x01 -#define BTM_COD_MAJOR_PHONE 0x02 -#define BTM_COD_MAJOR_LAN_ACCESS_PT 0x03 -#define BTM_COD_MAJOR_AUDIO 0x04 -#define BTM_COD_MAJOR_PERIPHERAL 0x05 -#define BTM_COD_MAJOR_IMAGING 0x06 -#define BTM_COD_MAJOR_WEARABLE 0x07 -#define BTM_COD_MAJOR_TOY 0x08 -#define BTM_COD_MAJOR_HEALTH 0x09 -#define BTM_COD_MAJOR_UNCLASSIFIED 0x1F - -/*************************** -** service class fields -****************************/ -#define BTM_COD_SERVICE_LMTD_DISCOVER 0x0020 -#define BTM_COD_SERVICE_POSITIONING 0x0100 -#define BTM_COD_SERVICE_NETWORKING 0x0200 -#define BTM_COD_SERVICE_RENDERING 0x0400 -#define BTM_COD_SERVICE_CAPTURING 0x0800 -#define BTM_COD_SERVICE_OBJ_TRANSFER 0x1000 -#define BTM_COD_SERVICE_AUDIO 0x2000 -#define BTM_COD_SERVICE_TELEPHONY 0x4000 -#define BTM_COD_SERVICE_INFORMATION 0x8000 - -/* class of device field macros */ -#define BTM_COD_FORMAT_TYPE(u8, pd) {u8 = pd[2]&0x03;} -#define BTM_COD_MINOR_CLASS(u8, pd) {u8 = pd[2]&0xFC;} -#define BTM_COD_MAJOR_CLASS(u8, pd) {u8 = pd[1]&0x1F;} -#define BTM_COD_SERVICE_CLASS(u16, pd) {u16 = pd[0]; u16<<=8; u16 += pd[1]&0xE0;} - -/* to set the fields (assumes that format type is always 0) */ -#define FIELDS_TO_COD(pd, mn, mj, sv) {pd[2] = mn; pd[1] = \ - mj+ ((sv)&BTM_COD_SERVICE_CLASS_LO_B); \ - pd[0] = (sv) >> 8;} - -/* the COD masks */ -#define BTM_COD_FORMAT_TYPE_MASK 0x03 -#define BTM_COD_MINOR_CLASS_MASK 0xFC -#define BTM_COD_MAJOR_CLASS_MASK 0x1F -#define BTM_COD_SERVICE_CLASS_LO_B 0x00E0 -#define BTM_COD_SERVICE_CLASS_MASK 0xFFE0 - - -/* BTM service definitions -** Used for storing EIR data to bit mask -*/ -enum { - BTM_EIR_UUID_SERVCLASS_SERVICE_DISCOVERY_SERVER, - /* BTM_EIR_UUID_SERVCLASS_BROWSE_GROUP_DESCRIPTOR, */ - /* BTM_EIR_UUID_SERVCLASS_PUBLIC_BROWSE_GROUP, */ - BTM_EIR_UUID_SERVCLASS_SERIAL_PORT, - BTM_EIR_UUID_SERVCLASS_LAN_ACCESS_USING_PPP, - BTM_EIR_UUID_SERVCLASS_DIALUP_NETWORKING, - BTM_EIR_UUID_SERVCLASS_IRMC_SYNC, - BTM_EIR_UUID_SERVCLASS_OBEX_OBJECT_PUSH, - BTM_EIR_UUID_SERVCLASS_OBEX_FILE_TRANSFER, - BTM_EIR_UUID_SERVCLASS_IRMC_SYNC_COMMAND, - BTM_EIR_UUID_SERVCLASS_HEADSET, - BTM_EIR_UUID_SERVCLASS_CORDLESS_TELEPHONY, - BTM_EIR_UUID_SERVCLASS_AUDIO_SOURCE, - BTM_EIR_UUID_SERVCLASS_AUDIO_SINK, - BTM_EIR_UUID_SERVCLASS_AV_REM_CTRL_TARGET, - /* BTM_EIR_UUID_SERVCLASS_ADV_AUDIO_DISTRIBUTION, */ - BTM_EIR_UUID_SERVCLASS_AV_REMOTE_CONTROL, - /* BTM_EIR_UUID_SERVCLASS_VIDEO_CONFERENCING, */ - BTM_EIR_UUID_SERVCLASS_INTERCOM, - BTM_EIR_UUID_SERVCLASS_FAX, - BTM_EIR_UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, - /* BTM_EIR_UUID_SERVCLASS_WAP, */ - /* BTM_EIR_UUID_SERVCLASS_WAP_CLIENT, */ - BTM_EIR_UUID_SERVCLASS_PANU, - BTM_EIR_UUID_SERVCLASS_NAP, - BTM_EIR_UUID_SERVCLASS_GN, - BTM_EIR_UUID_SERVCLASS_DIRECT_PRINTING, - /* BTM_EIR_UUID_SERVCLASS_REFERENCE_PRINTING, */ - BTM_EIR_UUID_SERVCLASS_IMAGING, - BTM_EIR_UUID_SERVCLASS_IMAGING_RESPONDER, - BTM_EIR_UUID_SERVCLASS_IMAGING_AUTO_ARCHIVE, - BTM_EIR_UUID_SERVCLASS_IMAGING_REF_OBJECTS, - BTM_EIR_UUID_SERVCLASS_HF_HANDSFREE, - BTM_EIR_UUID_SERVCLASS_AG_HANDSFREE, - BTM_EIR_UUID_SERVCLASS_DIR_PRT_REF_OBJ_SERVICE, - /* BTM_EIR_UUID_SERVCLASS_REFLECTED_UI, */ - BTM_EIR_UUID_SERVCLASS_BASIC_PRINTING, - BTM_EIR_UUID_SERVCLASS_PRINTING_STATUS, - BTM_EIR_UUID_SERVCLASS_HUMAN_INTERFACE, - BTM_EIR_UUID_SERVCLASS_CABLE_REPLACEMENT, - BTM_EIR_UUID_SERVCLASS_HCRP_PRINT, - BTM_EIR_UUID_SERVCLASS_HCRP_SCAN, - /* BTM_EIR_UUID_SERVCLASS_COMMON_ISDN_ACCESS, */ - /* BTM_EIR_UUID_SERVCLASS_VIDEO_CONFERENCING_GW, */ - /* BTM_EIR_UUID_SERVCLASS_UDI_MT, */ - /* BTM_EIR_UUID_SERVCLASS_UDI_TA, */ - /* BTM_EIR_UUID_SERVCLASS_VCP, */ - BTM_EIR_UUID_SERVCLASS_SAP, - BTM_EIR_UUID_SERVCLASS_PBAP_PCE, - BTM_EIR_UUID_SERVCLASS_PBAP_PSE, - /* BTM_EIR_UUID_SERVCLASS_TE_PHONE_ACCESS, */ - /* BTM_EIR_UUID_SERVCLASS_ME_PHONE_ACCESS, */ - BTM_EIR_UUID_SERVCLASS_PHONE_ACCESS, - BTM_EIR_UUID_SERVCLASS_HEADSET_HS, - BTM_EIR_UUID_SERVCLASS_PNP_INFORMATION, - /* BTM_EIR_UUID_SERVCLASS_GENERIC_NETWORKING, */ - /* BTM_EIR_UUID_SERVCLASS_GENERIC_FILETRANSFER, */ - /* BTM_EIR_UUID_SERVCLASS_GENERIC_AUDIO, */ - /* BTM_EIR_UUID_SERVCLASS_GENERIC_TELEPHONY, */ - /* BTM_EIR_UUID_SERVCLASS_UPNP_SERVICE, */ - /* BTM_EIR_UUID_SERVCLASS_UPNP_IP_SERVICE, */ - /* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_PAN, */ - /* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_LAP, */ - /* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_L2CAP, */ - BTM_EIR_UUID_SERVCLASS_VIDEO_SOURCE, - BTM_EIR_UUID_SERVCLASS_VIDEO_SINK, - /* BTM_EIR_UUID_SERVCLASS_VIDEO_DISTRIBUTION */ - /* BTM_EIR_UUID_SERVCLASS_HDP_PROFILE */ - BTM_EIR_UUID_SERVCLASS_MESSAGE_ACCESS, - BTM_EIR_UUID_SERVCLASS_MESSAGE_NOTIFICATION, - BTM_EIR_UUID_SERVCLASS_HDP_SOURCE, - BTM_EIR_UUID_SERVCLASS_HDP_SINK, - BTM_EIR_MAX_SERVICES -}; - -/* search result in EIR of inquiry database */ -#define BTM_EIR_FOUND 0 -#define BTM_EIR_NOT_FOUND 1 -#define BTM_EIR_UNKNOWN 2 - -typedef UINT8 tBTM_EIR_SEARCH_RESULT; - -#define BTM_EIR_FLAGS_TYPE HCI_EIR_FLAGS_TYPE /* 0x01 */ -#define BTM_EIR_MORE_16BITS_UUID_TYPE HCI_EIR_MORE_16BITS_UUID_TYPE /* 0x02 */ -#define BTM_EIR_COMPLETE_16BITS_UUID_TYPE HCI_EIR_COMPLETE_16BITS_UUID_TYPE /* 0x03 */ -#define BTM_EIR_MORE_32BITS_UUID_TYPE HCI_EIR_MORE_32BITS_UUID_TYPE /* 0x04 */ -#define BTM_EIR_COMPLETE_32BITS_UUID_TYPE HCI_EIR_COMPLETE_32BITS_UUID_TYPE /* 0x05 */ -#define BTM_EIR_MORE_128BITS_UUID_TYPE HCI_EIR_MORE_128BITS_UUID_TYPE /* 0x06 */ -#define BTM_EIR_COMPLETE_128BITS_UUID_TYPE HCI_EIR_COMPLETE_128BITS_UUID_TYPE /* 0x07 */ -#define BTM_EIR_SHORTENED_LOCAL_NAME_TYPE HCI_EIR_SHORTENED_LOCAL_NAME_TYPE /* 0x08 */ -#define BTM_EIR_COMPLETE_LOCAL_NAME_TYPE HCI_EIR_COMPLETE_LOCAL_NAME_TYPE /* 0x09 */ -#define BTM_EIR_TX_POWER_LEVEL_TYPE HCI_EIR_TX_POWER_LEVEL_TYPE /* 0x0A */ -#define BTM_EIR_MANUFACTURER_SPECIFIC_TYPE HCI_EIR_MANUFACTURER_SPECIFIC_TYPE /* 0xFF */ - -/* the following EIR tags are defined to OOB, not regular EIR data */ -#define BTM_EIR_OOB_BD_ADDR_TYPE HCI_EIR_OOB_BD_ADDR_TYPE /* 6 bytes */ -#define BTM_EIR_OOB_COD_TYPE HCI_EIR_OOB_COD_TYPE /* 3 bytes */ -#define BTM_EIR_OOB_SSP_HASH_C_TYPE HCI_EIR_OOB_SSP_HASH_C_TYPE /* 16 bytes */ -#define BTM_EIR_OOB_SSP_RAND_R_TYPE HCI_EIR_OOB_SSP_RAND_R_TYPE /* 16 bytes */ - -#define BTM_OOB_MANDATORY_SIZE 8 /* include 2 bytes length & 6 bytes bd_addr */ -#define BTM_OOB_DATA_LEN_SIZE 2 -#define BTM_OOB_BD_ADDR_SIZE 6 -#define BTM_OOB_COD_SIZE BT_OOB_COD_SIZE -#define BTM_OOB_HASH_C_SIZE BT_OOB_HASH_C_SIZE -#define BTM_OOB_RAND_R_SIZE BT_OOB_RAND_R_SIZE - - -#if BLE_INCLUDED == TRUE -#define BTM_BLE_SEC_NONE 0 -#define BTM_BLE_SEC_ENCRYPT 1 /* encrypt the link using current key */ -#define BTM_BLE_SEC_ENCRYPT_NO_MITM 2 -#define BTM_BLE_SEC_ENCRYPT_MITM 3 -typedef UINT8 tBTM_BLE_SEC_ACT; -#endif -/************************************************************************************************ -** BTM Services MACROS handle array of UINT32 bits for more than 32 services -*************************************************************************************************/ -/* Determine the number of UINT32's necessary for services */ -#define BTM_EIR_ARRAY_BITS 32 /* Number of bits in each array element */ -#define BTM_EIR_SERVICE_ARRAY_SIZE (((UINT32)BTM_EIR_MAX_SERVICES / BTM_EIR_ARRAY_BITS) + \ - (((UINT32)BTM_EIR_MAX_SERVICES % BTM_EIR_ARRAY_BITS) ? 1 : 0)) - -/* MACRO to set the service bit mask in a bit stream */ -#define BTM_EIR_SET_SERVICE(p, service) (((UINT32 *)(p))[(((UINT32)(service)) / BTM_EIR_ARRAY_BITS)] |= \ - ((UINT32)1 << (((UINT32)(service)) % BTM_EIR_ARRAY_BITS))) - - -/* MACRO to clear the service bit mask in a bit stream */ -#define BTM_EIR_CLR_SERVICE(p, service) (((UINT32 *)(p))[(((UINT32)(service)) / BTM_EIR_ARRAY_BITS)] &= \ - ~((UINT32)1 << (((UINT32)(service)) % BTM_EIR_ARRAY_BITS))) - -/* MACRO to check the service bit mask in a bit stream */ -#define BTM_EIR_HAS_SERVICE(p, service) ((((UINT32 *)(p))[(((UINT32)(service)) / BTM_EIR_ARRAY_BITS)] & \ - ((UINT32)1 << (((UINT32)(service)) % BTM_EIR_ARRAY_BITS))) >> (((UINT32)(service)) % BTM_EIR_ARRAY_BITS)) - -/* start of EIR in HCI buffer, 4 bytes = HCI Command(2) + Length(1) + FEC_Req(1) */ -#define BTM_HCI_EIR_OFFSET (BT_HDR_SIZE + 4) - -/*************************** -** Device Discovery Types -****************************/ -/* Definitions of the parameters passed to BTM_StartInquiry and -** BTM_SetPeriodicInquiryMode. -*/ -typedef struct { /* contains the two device class condition fields */ - DEV_CLASS dev_class; - DEV_CLASS dev_class_mask; -} tBTM_COD_COND; - - -typedef union { /* contains the inquiry filter condition */ - BD_ADDR bdaddr_cond; - tBTM_COD_COND cod_cond; -} tBTM_INQ_FILT_COND; - - -typedef struct { /* contains the parameters passed to the inquiry functions */ - UINT8 mode; /* general or limited */ - UINT8 duration; /* duration of the inquiry (1.28 sec increments) */ - UINT8 max_resps; /* maximum number of responses to return */ - BOOLEAN report_dup; /* report duplicated inquiry response with higher RSSI value */ - UINT8 filter_cond_type; /* new devices, BD ADDR, COD, or No filtering */ - tBTM_INQ_FILT_COND filter_cond; /* filter value based on filter cond type */ -#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE) - UINT8 intl_duration[4]; /*duration array storing the interleave scan's time portions*/ -#endif -} tBTM_INQ_PARMS; - -#define BTM_INQ_RESULT_BR 0x01 -#define BTM_INQ_RESULT_BLE 0x02 - -#if (BLE_INCLUDED == TRUE) -#define BTM_BLE_EVT_CONN_ADV 0x00 -#define BTM_BLE_EVT_CONN_DIR_ADV 0x01 -#define BTM_BLE_EVT_DISC_ADV 0x02 -#define BTM_BLE_EVT_NON_CONN_ADV 0x03 -#define BTM_BLE_EVT_SCAN_RSP 0x04 -typedef UINT8 tBTM_BLE_EVT_TYPE; -#endif - -/* These are the fields returned in each device's response to the inquiry. It -** is returned in the results callback if registered. -*/ -typedef struct { - UINT16 clock_offset; - BD_ADDR remote_bd_addr; - DEV_CLASS dev_class; - UINT8 page_scan_rep_mode; - UINT8 page_scan_per_mode; - UINT8 page_scan_mode; - INT8 rssi; /* Set to BTM_INQ_RES_IGNORE_RSSI if not valid */ - UINT32 eir_uuid[BTM_EIR_SERVICE_ARRAY_SIZE]; - BOOLEAN eir_complete_list; -#if (BLE_INCLUDED == TRUE) - tBT_DEVICE_TYPE device_type; - UINT8 inq_result_type; - UINT8 ble_addr_type; - tBTM_BLE_EVT_TYPE ble_evt_type; - UINT8 flag; - UINT8 adv_data_len; - UINT8 scan_rsp_len; -#endif -} tBTM_INQ_RESULTS; - - -/* This is the inquiry response information held in its database by BTM, and available -** to applications via BTM_InqDbRead, BTM_InqDbFirst, and BTM_InqDbNext. -*/ -typedef struct { - tBTM_INQ_RESULTS results; - - BOOLEAN appl_knows_rem_name; /* set by application if it knows the remote name of the peer device. - This is later used by application to determine if remote name request is - required to be done. Having the flag here avoid duplicate store of inquiry results */ -#if ( BLE_INCLUDED == TRUE) - UINT16 remote_name_len; - tBTM_BD_NAME remote_name; - UINT8 remote_name_state; - UINT8 remote_name_type; -#endif - -} tBTM_INQ_INFO; - - -/* Structure returned with inquiry complete callback */ -typedef struct { - tBTM_STATUS status; - UINT8 num_resp; /* Number of results from the current inquiry */ -} tBTM_INQUIRY_CMPL; - - -/* Structure returned with remote name request */ -typedef struct { - UINT16 status; - BD_ADDR bd_addr; - UINT16 length; - BD_NAME remote_bd_name; -} tBTM_REMOTE_DEV_NAME; - -typedef struct { - UINT8 pcm_intf_rate; /* PCM interface rate: 0: 128kbps, 1: 256 kbps; - 2:512 bps; 3: 1024kbps; 4: 2048kbps */ - UINT8 frame_type; /* frame type: 0: short; 1: long */ - UINT8 sync_mode; /* sync mode: 0: slave; 1: master */ - UINT8 clock_mode; /* clock mode: 0: slave; 1: master */ - -} tBTM_SCO_PCM_PARAM; - -/**************************************** -** Device Discovery Callback Functions -*****************************************/ -/* Callback function for asynchronous notifications when the BTM inquiry DB -** changes. First param is inquiry database, second is if added to or removed -** from the inquiry database. -*/ -typedef void (tBTM_INQ_DB_CHANGE_CB) (void *p1, BOOLEAN is_new); - -/* Callback function for notifications when the BTM gets inquiry response. -** First param is inquiry results database, second is pointer of EIR. -*/ -typedef void (tBTM_INQ_RESULTS_CB) (tBTM_INQ_RESULTS *p_inq_results, UINT8 *p_eir); - -/***************************************************************************** -** ACL CHANNEL MANAGEMENT -*****************************************************************************/ -/****************** -** ACL Constants -*******************/ - -/* ACL modes */ -#define BTM_ACL_MODE_NORMAL HCI_MODE_ACTIVE -#define BTM_ACL_MODE_HOLD HCI_MODE_HOLD -#define BTM_ACL_MODE_SNIFF HCI_MODE_SNIFF -#define BTM_ACL_MODE_PARK HCI_MODE_PARK - -/* Returned with structure in role switch callback (tBTM_ROLE_SWITCH_CMPL) */ -#define BTM_ROLE_MASTER HCI_ROLE_MASTER -#define BTM_ROLE_SLAVE HCI_ROLE_SLAVE -#define BTM_ROLE_UNDEFINED 0xff /* undefined value (error status) */ - -/* ACL Packet Types */ -#define BTM_ACL_PKT_TYPES_MASK_DM1 HCI_PKT_TYPES_MASK_DM1 -#define BTM_ACL_PKT_TYPES_MASK_DH1 HCI_PKT_TYPES_MASK_DH1 -#define BTM_ACL_PKT_TYPES_MASK_DM3 HCI_PKT_TYPES_MASK_DM3 -#define BTM_ACL_PKT_TYPES_MASK_DH3 HCI_PKT_TYPES_MASK_DH3 -#define BTM_ACL_PKT_TYPES_MASK_DM5 HCI_PKT_TYPES_MASK_DM5 -#define BTM_ACL_PKT_TYPES_MASK_DH5 HCI_PKT_TYPES_MASK_DH5 -#define BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 HCI_PKT_TYPES_MASK_NO_2_DH1 -#define BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 HCI_PKT_TYPES_MASK_NO_3_DH1 -#define BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 HCI_PKT_TYPES_MASK_NO_2_DH3 -#define BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 HCI_PKT_TYPES_MASK_NO_3_DH3 -#define BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 HCI_PKT_TYPES_MASK_NO_2_DH5 -#define BTM_ACL_PKT_TYPES_MASK_NO_3_DH5 HCI_PKT_TYPES_MASK_NO_3_DH5 - -/*************** -** ACL Types -****************/ - -/* Structure returned with Role Switch information (in tBTM_CMPL_CB callback function) -** in response to BTM_SwitchRole call. -*/ -typedef struct { - UINT8 hci_status; /* HCI status returned with the event */ - UINT8 role; /* BTM_ROLE_MASTER or BTM_ROLE_SLAVE */ - BD_ADDR remote_bd_addr; /* Remote BD addr involved with the switch */ -} tBTM_ROLE_SWITCH_CMPL; - -/* Structure returned with QoS information (in tBTM_CMPL_CB callback function) -** in response to BTM_SetQoS call. -*/ -typedef struct { - FLOW_SPEC flow; - UINT16 handle; - UINT8 status; -} tBTM_QOS_SETUP_CMPL; - - -/* Structure returned with read RSSI event (in tBTM_CMPL_CB callback function) -** in response to BTM_ReadRSSI call. -*/ -typedef struct { - tBTM_STATUS status; - UINT8 hci_status; - INT8 rssi; - BD_ADDR rem_bda; -} tBTM_RSSI_RESULTS; - -/* Structure returned with read current TX power event (in tBTM_CMPL_CB callback function) -** in response to BTM_ReadTxPower call. -*/ -typedef struct { - tBTM_STATUS status; - UINT8 hci_status; - INT8 tx_power; - BD_ADDR rem_bda; -} tBTM_TX_POWER_RESULTS; - -/* Structure returned with read link quality event (in tBTM_CMPL_CB callback function) -** in response to BTM_ReadLinkQuality call. -*/ -typedef struct { - tBTM_STATUS status; - UINT8 hci_status; - UINT8 link_quality; - BD_ADDR rem_bda; -} tBTM_LINK_QUALITY_RESULTS; - -/* Structure returned with read inq tx power quality event (in tBTM_CMPL_CB callback function) -** in response to BTM_ReadInquiryRspTxPower call. -*/ -typedef struct { - tBTM_STATUS status; - UINT8 hci_status; - INT8 tx_power; -} tBTM_INQ_TXPWR_RESULTS; - -enum { - BTM_BL_CONN_EVT, - BTM_BL_DISCN_EVT, - BTM_BL_UPDATE_EVT, - BTM_BL_ROLE_CHG_EVT, - BTM_BL_COLLISION_EVT -}; -typedef UINT8 tBTM_BL_EVENT; -typedef UINT16 tBTM_BL_EVENT_MASK; - -#define BTM_BL_CONN_MASK 0x0001 -#define BTM_BL_DISCN_MASK 0x0002 -#define BTM_BL_UPDATE_MASK 0x0004 -#define BTM_BL_ROLE_CHG_MASK 0x0008 - -/* Device features mask definitions */ -#define BTM_FEATURE_BYTES_PER_PAGE HCI_FEATURE_BYTES_PER_PAGE -#define BTM_EXT_FEATURES_PAGE_MAX HCI_EXT_FEATURES_PAGE_MAX - -/* the data type associated with BTM_BL_CONN_EVT */ -typedef struct { - tBTM_BL_EVENT event; /* The event reported. */ - BD_ADDR_PTR p_bda; /* The address of the newly connected device */ - DEV_CLASS_PTR p_dc; /* The device class */ - BD_NAME_PTR p_bdn; /* The device name */ - UINT8 *p_features; /* pointer to the remote device's features page[0] (supported features page) */ -#if BLE_INCLUDED == TRUE - UINT16 handle; /* connection handle */ - tBT_TRANSPORT transport; /* link is LE or not */ -#endif -} tBTM_BL_CONN_DATA; - -/* the data type associated with BTM_BL_DISCN_EVT */ -typedef struct { - tBTM_BL_EVENT event; /* The event reported. */ - BD_ADDR_PTR p_bda; /* The address of the disconnected device */ -#if BLE_INCLUDED == TRUE - UINT16 handle; /* disconnected connection handle */ - tBT_TRANSPORT transport; /* link is LE link or not */ -#endif -} tBTM_BL_DISCN_DATA; - -/* Busy-Level shall have the inquiry_paging mask set when - * inquiry/paging is in progress, Else the number of ACL links */ -#define BTM_BL_INQUIRY_PAGING_MASK 0x10 -#define BTM_BL_INQUIRY_STARTED (BTM_BL_INQUIRY_PAGING_MASK | 0x1) -#define BTM_BL_INQUIRY_CANCELLED (BTM_BL_INQUIRY_PAGING_MASK | 0x2) -#define BTM_BL_INQUIRY_COMPLETE (BTM_BL_INQUIRY_PAGING_MASK | 0x3) -#define BTM_BL_PAGING_STARTED (BTM_BL_INQUIRY_PAGING_MASK | 0x4) -#define BTM_BL_PAGING_COMPLETE (BTM_BL_INQUIRY_PAGING_MASK | 0x5) -/* the data type associated with BTM_BL_UPDATE_EVT */ -typedef struct { - tBTM_BL_EVENT event; /* The event reported. */ - UINT8 busy_level;/* when paging or inquiring, level is 10. - * Otherwise, the number of ACL links. */ - UINT8 busy_level_flags; /* Notifies actual inquiry/page activities */ -} tBTM_BL_UPDATE_DATA; - -/* the data type associated with BTM_BL_ROLE_CHG_EVT */ -typedef struct { - tBTM_BL_EVENT event; /* The event reported. */ - BD_ADDR_PTR p_bda; /* The address of the peer connected device */ - UINT8 new_role; - UINT8 hci_status; /* HCI status returned with the event */ -} tBTM_BL_ROLE_CHG_DATA; - -typedef union { - tBTM_BL_EVENT event; /* The event reported. */ - tBTM_BL_CONN_DATA conn; /* The data associated with BTM_BL_CONN_EVT */ - tBTM_BL_DISCN_DATA discn; /* The data associated with BTM_BL_DISCN_EVT */ - tBTM_BL_UPDATE_DATA update; /* The data associated with BTM_BL_UPDATE_EVT */ - tBTM_BL_ROLE_CHG_DATA role_chg;/*The data associated with BTM_BL_ROLE_CHG_EVT */ -} tBTM_BL_EVENT_DATA; - -/* Callback function for notifications when the BTM busy level -** changes. -*/ -typedef void (tBTM_BL_CHANGE_CB) (tBTM_BL_EVENT_DATA *p_data); - -/*************************** -** ACL Callback Functions -****************************/ -/* Callback function for notifications when the BTM ACL connection DB -** changes. First param is BD address, second is if added or removed. -** Registered through BTM_AclRegisterForChanges call. -*/ -#if BLE_INCLUDED == TRUE -typedef void (tBTM_ACL_DB_CHANGE_CB) (BD_ADDR p_bda, DEV_CLASS p_dc, - BD_NAME p_bdn, UINT8 *features, - BOOLEAN is_new, UINT16 handle, - tBT_TRANSPORT transport); -#else -typedef void (tBTM_ACL_DB_CHANGE_CB) (BD_ADDR p_bda, DEV_CLASS p_dc, - BD_NAME p_bdn, UINT8 *features, - BOOLEAN is_new); -#endif -/***************************************************************************** -** SCO CHANNEL MANAGEMENT -*****************************************************************************/ -/****************** -** SCO Constants -*******************/ - -/* Define an invalid SCO index and an invalid HCI handle */ -#define BTM_INVALID_SCO_INDEX 0xFFFF -#define BTM_INVALID_HCI_HANDLE 0xFFFF - -/* Define an invalid SCO disconnect reason */ -#define BTM_INVALID_SCO_DISC_REASON 0xFFFF - -/* Define first active SCO index */ -#define BTM_FIRST_ACTIVE_SCO_INDEX BTM_MAX_SCO_LINKS - -/* Define SCO packet types used in APIs */ -#define BTM_SCO_PKT_TYPES_MASK_HV1 HCI_ESCO_PKT_TYPES_MASK_HV1 -#define BTM_SCO_PKT_TYPES_MASK_HV2 HCI_ESCO_PKT_TYPES_MASK_HV2 -#define BTM_SCO_PKT_TYPES_MASK_HV3 HCI_ESCO_PKT_TYPES_MASK_HV3 -#define BTM_SCO_PKT_TYPES_MASK_EV3 HCI_ESCO_PKT_TYPES_MASK_EV3 -#define BTM_SCO_PKT_TYPES_MASK_EV4 HCI_ESCO_PKT_TYPES_MASK_EV4 -#define BTM_SCO_PKT_TYPES_MASK_EV5 HCI_ESCO_PKT_TYPES_MASK_EV5 -#define BTM_SCO_PKT_TYPES_MASK_NO_2_EV3 HCI_ESCO_PKT_TYPES_MASK_NO_2_EV3 -#define BTM_SCO_PKT_TYPES_MASK_NO_3_EV3 HCI_ESCO_PKT_TYPES_MASK_NO_3_EV3 -#define BTM_SCO_PKT_TYPES_MASK_NO_2_EV5 HCI_ESCO_PKT_TYPES_MASK_NO_2_EV5 -#define BTM_SCO_PKT_TYPES_MASK_NO_3_EV5 HCI_ESCO_PKT_TYPES_MASK_NO_3_EV5 - -#define BTM_SCO_LINK_ONLY_MASK (BTM_SCO_PKT_TYPES_MASK_HV1 | \ - BTM_SCO_PKT_TYPES_MASK_HV2 | \ - BTM_SCO_PKT_TYPES_MASK_HV3) - -#define BTM_ESCO_LINK_ONLY_MASK (BTM_SCO_PKT_TYPES_MASK_EV3 | \ - BTM_SCO_PKT_TYPES_MASK_EV4 | \ - BTM_SCO_PKT_TYPES_MASK_EV5) - -#define BTM_SCO_LINK_ALL_PKT_MASK (BTM_SCO_LINK_ONLY_MASK | \ - BTM_ESCO_LINK_ONLY_MASK) - -#define BTM_VALID_SCO_ALL_PKT_TYPE HCI_VALID_SCO_ALL_PKT_TYPE - -/* Passed in BTM_CreateSco if the packet type parameter should be ignored */ -#define BTM_IGNORE_SCO_PKT_TYPE 0 - -/*************** -** SCO Types -****************/ -#define BTM_LINK_TYPE_SCO HCI_LINK_TYPE_SCO -#define BTM_LINK_TYPE_ESCO HCI_LINK_TYPE_ESCO -typedef UINT8 tBTM_SCO_TYPE; - - -/******************* -** SCO Routing Path -********************/ -#define BTM_SCO_ROUTE_PCM HCI_BRCM_SCO_ROUTE_PCM -#define BTM_SCO_ROUTE_HCI HCI_BRCM_SCO_ROUTE_HCI -typedef UINT8 tBTM_SCO_ROUTE_TYPE; - - -/******************* -** SCO Codec Types -********************/ -// TODO(google) This should use common definitions -// in hci/include/hci_audio.h -#define BTM_SCO_CODEC_NONE 0x0000 -#define BTM_SCO_CODEC_CVSD 0x0001 -#define BTM_SCO_CODEC_MSBC 0x0002 -typedef UINT16 tBTM_SCO_CODEC_TYPE; - - - -/******************* -** SCO Air Mode Types -********************/ -#define BTM_SCO_AIR_MODE_U_LAW 0 -#define BTM_SCO_AIR_MODE_A_LAW 1 -#define BTM_SCO_AIR_MODE_CVSD 2 -#define BTM_SCO_AIR_MODE_TRANSPNT 3 -typedef UINT8 tBTM_SCO_AIR_MODE_TYPE; - -/******************* -** SCO Voice Settings -********************/ -#define BTM_VOICE_SETTING_CVSD ((UINT16) (HCI_INP_CODING_LINEAR | \ - HCI_INP_DATA_FMT_2S_COMPLEMENT | \ - HCI_INP_SAMPLE_SIZE_16BIT | \ - HCI_AIR_CODING_FORMAT_CVSD)) - -#define BTM_VOICE_SETTING_TRANS ((UINT16) (HCI_INP_CODING_LINEAR | \ - HCI_INP_DATA_FMT_2S_COMPLEMENT | \ - HCI_INP_SAMPLE_SIZE_16BIT | \ - HCI_AIR_CODING_FORMAT_TRANSPNT)) - -/******************* -** SCO Data Status -********************/ -enum { - BTM_SCO_DATA_CORRECT, - BTM_SCO_DATA_PAR_ERR, - BTM_SCO_DATA_NONE, - BTM_SCO_DATA_PAR_LOST -}; -typedef UINT8 tBTM_SCO_DATA_FLAG; - -/*************************** -** SCO Callback Functions -****************************/ -typedef void (tBTM_SCO_CB) (UINT16 sco_inx); -typedef void (tBTM_SCO_DATA_CB) (UINT16 sco_inx, BT_HDR *p_data, tBTM_SCO_DATA_FLAG status); - -/****************** -** eSCO Constants -*******************/ -#define BTM_64KBITS_RATE 0x00001f40 /* 64 kbits/sec data rate */ - -/* Retransmission effort */ -#define BTM_ESCO_RETRANS_OFF 0 -#define BTM_ESCO_RETRANS_POWER 1 -#define BTM_ESCO_RETRANS_QUALITY 2 -#define BTM_ESCO_RETRANS_DONTCARE 0xff - -/* Max Latency Don't Care */ -#define BTM_ESCO_MAX_LAT_DONTCARE 0xffff - -/*************** -** eSCO Types -****************/ -/* tBTM_ESCO_CBACK event types */ -#define BTM_ESCO_CHG_EVT 1 -#define BTM_ESCO_CONN_REQ_EVT 2 -typedef UINT8 tBTM_ESCO_EVT; - -/* Passed into BTM_SetEScoMode() */ -typedef struct { - UINT32 tx_bw; - UINT32 rx_bw; - UINT16 max_latency; - UINT16 voice_contfmt; /* Voice Settings or Content Format */ - UINT16 packet_types; - UINT8 retrans_effort; -} tBTM_ESCO_PARAMS; - -typedef struct { - UINT16 max_latency; - UINT16 packet_types; - UINT8 retrans_effort; -} tBTM_CHG_ESCO_PARAMS; - -/* Returned by BTM_ReadEScoLinkParms() */ -typedef struct { - UINT16 rx_pkt_len; - UINT16 tx_pkt_len; - BD_ADDR bd_addr; - UINT8 link_type; /* BTM_LINK_TYPE_SCO or BTM_LINK_TYPE_ESCO */ - UINT8 tx_interval; - UINT8 retrans_window; - UINT8 air_mode; -} tBTM_ESCO_DATA; - -typedef struct { - UINT16 sco_inx; - UINT16 rx_pkt_len; - UINT16 tx_pkt_len; - BD_ADDR bd_addr; - UINT8 hci_status; - UINT8 tx_interval; - UINT8 retrans_window; -} tBTM_CHG_ESCO_EVT_DATA; - -typedef struct { - UINT16 sco_inx; - BD_ADDR bd_addr; - DEV_CLASS dev_class; - tBTM_SCO_TYPE link_type; -} tBTM_ESCO_CONN_REQ_EVT_DATA; - -typedef union { - tBTM_CHG_ESCO_EVT_DATA chg_evt; - tBTM_ESCO_CONN_REQ_EVT_DATA conn_evt; -} tBTM_ESCO_EVT_DATA; - -/*************************** -** eSCO Callback Functions -****************************/ -typedef void (tBTM_ESCO_CBACK) (tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA *p_data); - - -/***************************************************************************** -** SECURITY MANAGEMENT -*****************************************************************************/ -/******************************* -** Security Manager Constants -********************************/ - -/* Security Mode (BTM_SetSecurityMode) */ -#define BTM_SEC_MODE_UNDEFINED 0 -#define BTM_SEC_MODE_NONE 1 -#define BTM_SEC_MODE_SERVICE 2 -#define BTM_SEC_MODE_LINK 3 -#define BTM_SEC_MODE_SP 4 -#define BTM_SEC_MODE_SP_DEBUG 5 -#define BTM_SEC_MODE_SC 6 - -/* Maximum Number of BTM Security Modes */ -#define BTM_SEC_MODES_MAX 7 - -/* Security Service Levels [bit mask] (BTM_SetSecurityLevel) -** Encryption should not be used without authentication -*/ -#define BTM_SEC_NONE 0x0000 /* Nothing required */ -#define BTM_SEC_IN_AUTHORIZE 0x0001 /* Inbound call requires authorization */ -#define BTM_SEC_IN_AUTHENTICATE 0x0002 /* Inbound call requires authentication */ -#define BTM_SEC_IN_ENCRYPT 0x0004 /* Inbound call requires encryption */ -#define BTM_SEC_OUT_AUTHORIZE 0x0008 /* Outbound call requires authorization */ -#define BTM_SEC_OUT_AUTHENTICATE 0x0010 /* Outbound call requires authentication */ -#define BTM_SEC_OUT_ENCRYPT 0x0020 /* Outbound call requires encryption */ -#define BTM_SEC_MODE4_LEVEL4 0x0040 /* Secure Connections Only Mode */ -#define BTM_SEC_FORCE_MASTER 0x0100 /* Need to switch connection to be master */ -#define BTM_SEC_ATTEMPT_MASTER 0x0200 /* Try to switch connection to be master */ -#define BTM_SEC_FORCE_SLAVE 0x0400 /* Need to switch connection to be master */ -#define BTM_SEC_ATTEMPT_SLAVE 0x0800 /* Try to switch connection to be slave */ -#define BTM_SEC_IN_MITM 0x1000 /* inbound Do man in the middle protection */ -#define BTM_SEC_OUT_MITM 0x2000 /* outbound Do man in the middle protection */ -#define BTM_SEC_IN_MIN_16_DIGIT_PIN 0x4000 /* enforce a minimum of 16 digit for sec mode 2 */ - -/* Security Flags [bit mask] (BTM_GetSecurityFlags) -*/ -#define BTM_SEC_FLAG_AUTHORIZED 0x01 -#define BTM_SEC_FLAG_AUTHENTICATED 0x02 -#define BTM_SEC_FLAG_ENCRYPTED 0x04 -#define BTM_SEC_FLAG_LKEY_KNOWN 0x10 -#define BTM_SEC_FLAG_LKEY_AUTHED 0x20 - -/* PIN types */ -#define BTM_PIN_TYPE_VARIABLE HCI_PIN_TYPE_VARIABLE -#define BTM_PIN_TYPE_FIXED HCI_PIN_TYPE_FIXED - -/* Link Key types used to generate the new link key. -** returned in link key notification callback function -*/ -#define BTM_LKEY_TYPE_COMBINATION HCI_LKEY_TYPE_COMBINATION -#define BTM_LKEY_TYPE_LOCAL_UNIT HCI_LKEY_TYPE_LOCAL_UNIT -#define BTM_LKEY_TYPE_REMOTE_UNIT HCI_LKEY_TYPE_REMOTE_UNIT -#define BTM_LKEY_TYPE_DEBUG_COMB HCI_LKEY_TYPE_DEBUG_COMB -#define BTM_LKEY_TYPE_UNAUTH_COMB HCI_LKEY_TYPE_UNAUTH_COMB -#define BTM_LKEY_TYPE_AUTH_COMB HCI_LKEY_TYPE_AUTH_COMB -#define BTM_LKEY_TYPE_CHANGED_COMB HCI_LKEY_TYPE_CHANGED_COMB - -#define BTM_LKEY_TYPE_UNAUTH_COMB_P_256 HCI_LKEY_TYPE_UNAUTH_COMB_P_256 -#define BTM_LKEY_TYPE_AUTH_COMB_P_256 HCI_LKEY_TYPE_AUTH_COMB_P_256 - -#define BTM_LTK_DERIVED_LKEY_OFFSET 0x20 /* "easy" requirements for LK derived from LTK */ -#define BTM_LKEY_TYPE_IGNORE 0xff /* used when event is response from - hci return link keys request */ - -typedef UINT8 tBTM_LINK_KEY_TYPE; - -/* Protocol level security (BTM_SetSecurityLevel) */ -#define BTM_SEC_PROTO_L2CAP 0 -#define BTM_SEC_PROTO_SDP 1 -#define BTM_SEC_PROTO_TCS 2 -#define BTM_SEC_PROTO_RFCOMM 3 -#define BTM_SEC_PROTO_OBEX 4 -#define BTM_SEC_PROTO_BNEP 5 -#define BTM_SEC_PROTO_HID 6 /* HID */ -#define BTM_SEC_PROTO_AVDT 7 -#define BTM_SEC_PROTO_MCA 8 - -/* Determine the number of UINT32's necessary for security services */ -#define BTM_SEC_ARRAY_BITS 32 /* Number of bits in each array element */ -#define BTM_SEC_SERVICE_ARRAY_SIZE (((UINT32)BTM_SEC_MAX_SERVICES / BTM_SEC_ARRAY_BITS) + \ - (((UINT32)BTM_SEC_MAX_SERVICES % BTM_SEC_ARRAY_BITS) ? 1 : 0)) - -/* Security service definitions (BTM_SetSecurityLevel) -** Used for Authorization APIs -*/ -#define BTM_SEC_SERVICE_SDP_SERVER 0 -#define BTM_SEC_SERVICE_SERIAL_PORT 1 -#define BTM_SEC_SERVICE_LAN_ACCESS 2 -#define BTM_SEC_SERVICE_DUN 3 -#define BTM_SEC_SERVICE_IRMC_SYNC 4 -#define BTM_SEC_SERVICE_IRMC_SYNC_CMD 5 -#define BTM_SEC_SERVICE_OBEX 6 -#define BTM_SEC_SERVICE_OBEX_FTP 7 -#define BTM_SEC_SERVICE_HEADSET 8 -#define BTM_SEC_SERVICE_CORDLESS 9 -#define BTM_SEC_SERVICE_INTERCOM 10 -#define BTM_SEC_SERVICE_FAX 11 -#define BTM_SEC_SERVICE_HEADSET_AG 12 -#define BTM_SEC_SERVICE_PNP_INFO 13 -#define BTM_SEC_SERVICE_GEN_NET 14 -#define BTM_SEC_SERVICE_GEN_FILE 15 -#define BTM_SEC_SERVICE_GEN_AUDIO 16 -#define BTM_SEC_SERVICE_GEN_TEL 17 -#define BTM_SEC_SERVICE_CTP_DATA 18 -#define BTM_SEC_SERVICE_HCRP_CTRL 19 -#define BTM_SEC_SERVICE_HCRP_DATA 20 -#define BTM_SEC_SERVICE_HCRP_NOTIF 21 -#define BTM_SEC_SERVICE_BPP_JOB 22 -#define BTM_SEC_SERVICE_BPP_STATUS 23 -#define BTM_SEC_SERVICE_BPP_REF 24 -#define BTM_SEC_SERVICE_BNEP_PANU 25 -#define BTM_SEC_SERVICE_BNEP_GN 26 -#define BTM_SEC_SERVICE_BNEP_NAP 27 -#define BTM_SEC_SERVICE_HF_HANDSFREE 28 -#define BTM_SEC_SERVICE_AG_HANDSFREE 29 -#define BTM_SEC_SERVICE_TE_PHONE_ACCESS 30 -#define BTM_SEC_SERVICE_ME_PHONE_ACCESS 31 - -#define BTM_SEC_SERVICE_HIDH_SEC_CTRL 32 -#define BTM_SEC_SERVICE_HIDH_NOSEC_CTRL 33 -#define BTM_SEC_SERVICE_HIDH_INTR 34 -#define BTM_SEC_SERVICE_BIP 35 -#define BTM_SEC_SERVICE_BIP_REF 36 -#define BTM_SEC_SERVICE_AVDTP 37 -#define BTM_SEC_SERVICE_AVDTP_NOSEC 38 -#define BTM_SEC_SERVICE_AVCTP 39 -#define BTM_SEC_SERVICE_SAP 40 -#define BTM_SEC_SERVICE_PBAP 41 -#define BTM_SEC_SERVICE_RFC_MUX 42 -#define BTM_SEC_SERVICE_AVCTP_BROWSE 43 -#define BTM_SEC_SERVICE_MAP 44 -#define BTM_SEC_SERVICE_MAP_NOTIF 45 -#define BTM_SEC_SERVICE_MCAP_CTRL 46 -#define BTM_SEC_SERVICE_MCAP_DATA 47 -#define BTM_SEC_SERVICE_HDP_SNK 48 -#define BTM_SEC_SERVICE_HDP_SRC 49 -#define BTM_SEC_SERVICE_ATT 50 - -/* Update these as services are added */ -#define BTM_SEC_SERVICE_FIRST_EMPTY 51 - -#ifndef BTM_SEC_MAX_SERVICES -#define BTM_SEC_MAX_SERVICES 65 -#endif - -/************************************************************************************************ -** Security Services MACROS handle array of UINT32 bits for more than 32 trusted services -*************************************************************************************************/ -/* MACRO to set the security service bit mask in a bit stream */ -#define BTM_SEC_SET_SERVICE(p, service) (((UINT32 *)(p))[(((UINT32)(service)) / BTM_SEC_ARRAY_BITS)] |= \ - ((UINT32)1 << (((UINT32)(service)) % BTM_SEC_ARRAY_BITS))) - - -/* MACRO to clear the security service bit mask in a bit stream */ -#define BTM_SEC_CLR_SERVICE(p, service) (((UINT32 *)(p))[(((UINT32)(service)) / BTM_SEC_ARRAY_BITS)] &= \ - ~((UINT32)1 << (((UINT32)(service)) % BTM_SEC_ARRAY_BITS))) - -/* MACRO to check the security service bit mask in a bit stream (Returns TRUE or FALSE) */ -#define BTM_SEC_IS_SERVICE_TRUSTED(p, service) (((((UINT32 *)(p))[(((UINT32)(service)) / BTM_SEC_ARRAY_BITS)]) & \ - (UINT32)(((UINT32)1 << (((UINT32)(service)) % BTM_SEC_ARRAY_BITS)))) ? TRUE : FALSE) - -/* MACRO to copy two trusted device bitmask */ -#define BTM_SEC_COPY_TRUSTED_DEVICE(p_src, p_dst) {UINT32 trst; for (trst = 0; trst < BTM_SEC_SERVICE_ARRAY_SIZE; trst++) \ - ((UINT32 *)(p_dst))[trst] = ((UINT32 *)(p_src))[trst];} - -/* MACRO to clear two trusted device bitmask */ -#define BTM_SEC_CLR_TRUSTED_DEVICE(p_dst) {UINT32 trst; for (trst = 0; trst < BTM_SEC_SERVICE_ARRAY_SIZE; trst++) \ - ((UINT32 *)(p_dst))[trst] = 0;} - -/* Following bits can be provided by host in the trusted_mask array */ -/* 0..31 bits of mask[0] (Least Significant Word) */ -#define BTM_SEC_TRUST_SDP_SERVER (1 << BTM_SEC_SERVICE_SDP_SERVER) -#define BTM_SEC_TRUST_SERIAL_PORT (1 << BTM_SEC_SERVICE_SERIAL_PORT) -#define BTM_SEC_TRUST_LAN_ACCESS (1 << BTM_SEC_SERVICE_LAN_ACCESS) -#define BTM_SEC_TRUST_DUN (1 << BTM_SEC_SERVICE_DUN) -#define BTM_SEC_TRUST_IRMC_SYNC (1 << BTM_SEC_SERVICE_IRMC_SYNC) -#define BTM_SEC_TRUST_IRMC_SYNC_CMD (1 << BTM_SEC_SERVICE_IRMC_SYNC_CMD) -#define BTM_SEC_TRUST_OBEX (1 << BTM_SEC_SERVICE_OBEX) -#define BTM_SEC_TRUST_OBEX_FTP (1 << BTM_SEC_SERVICE_OBEX_FTP) -#define BTM_SEC_TRUST_HEADSET (1 << BTM_SEC_SERVICE_HEADSET) -#define BTM_SEC_TRUST_CORDLESS (1 << BTM_SEC_SERVICE_CORDLESS) -#define BTM_SEC_TRUST_INTERCOM (1 << BTM_SEC_SERVICE_INTERCOM) -#define BTM_SEC_TRUST_FAX (1 << BTM_SEC_SERVICE_FAX) -#define BTM_SEC_TRUST_HEADSET_AG (1 << BTM_SEC_SERVICE_HEADSET_AG) -#define BTM_SEC_TRUST_PNP_INFO (1 << BTM_SEC_SERVICE_PNP_INFO) -#define BTM_SEC_TRUST_GEN_NET (1 << BTM_SEC_SERVICE_GEN_NET) -#define BTM_SEC_TRUST_GEN_FILE (1 << BTM_SEC_SERVICE_GEN_FILE) -#define BTM_SEC_TRUST_GEN_AUDIO (1 << BTM_SEC_SERVICE_GEN_AUDIO) -#define BTM_SEC_TRUST_GEN_TEL (1 << BTM_SEC_SERVICE_GEN_TEL) -#define BTM_SEC_TRUST_CTP_DATA (1 << BTM_SEC_SERVICE_CTP_DATA) -#define BTM_SEC_TRUST_HCRP_CTRL (1 << BTM_SEC_SERVICE_HCRP_CTRL) -#define BTM_SEC_TRUST_HCRP_DATA (1 << BTM_SEC_SERVICE_HCRP_DATA) -#define BTM_SEC_TRUST_HCRP_NOTIF (1 << BTM_SEC_SERVICE_HCRP_NOTIF) -#define BTM_SEC_TRUST_BPP_JOB (1 << BTM_SEC_SERVICE_JOB) -#define BTM_SEC_TRUST_BPP_STATUS (1 << BTM_SEC_SERVICE_STATUS) -#define BTM_SEC_TRUST_BPP_REF (1 << BTM_SEC_SERVICE_REF) -#define BTM_SEC_TRUST_BNEP_PANU (1 << BTM_SEC_SERVICE_BNEP_PANU) -#define BTM_SEC_TRUST_BNEP_GN (1 << BTM_SEC_SERVICE_BNEP_GN) -#define BTM_SEC_TRUST_BNEP_NAP (1 << BTM_SEC_SERVICE_BNEP_NAP) -#define BTM_SEC_TRUST_HFP_HF (1 << BTM_SEC_SERVICE_HF_HANDSFREE) -#define BTM_SEC_TRUST_HFP_AG (1 << BTM_SEC_SERVICE_AG_HANDSFREE) -#define BTM_SEC_TRUST_TE_PHONE_ACCESS (1 << BTM_SEC_SERVICE_TE_PHONE_ACCESS) -#define BTM_SEC_TRUST_ME_PHONE_ACCESS (1 << BTM_SEC_SERVICE_ME_PHONE_ACCESS) - -/* 0..31 bits of mask[1] (Most Significant Word) */ -#define BTM_SEC_TRUST_HIDH_CTRL (1 << (BTM_SEC_SERVICE_HIDH_SEC_CTRL - 32)) -#define BTM_SEC_TRUST_HIDH_NOSEC_CTRL (1 << (BTM_SEC_SERVICE_HIDH_NOSEC_CTRL - 32)) -#define BTM_SEC_TRUST_HIDH_INTR (1 << (BTM_SEC_SERVICE_HIDH_INTR - 32)) -#define BTM_SEC_TRUST_BIP (1 << (BTM_SEC_SERVICE_BIP - 32)) -#define BTM_SEC_TRUST_BIP_REF (1 << (BTM_SEC_SERVICE_BIP_REF - 32)) -#define BTM_SEC_TRUST_AVDTP (1 << (BTM_SEC_SERVICE_AVDTP - 32)) -#define BTM_SEC_TRUST_AVDTP_NOSEC (1 << (BTM_SEC_SERVICE_AVDTP_NOSEC - 32)) -#define BTM_SEC_TRUST_AVCTP (1 << (BTM_SEC_SERVICE_AVCTP - 32)) -#define BTM_SEC_TRUST_SAP (1 << (BTM_SEC_SERVICE_SAP - 32)) -#define BTM_SEC_TRUST_PBAP (1 << (BTM_SEC_SERVICE_PBAP - 32)) -#define BTM_SEC_TRUST_RFC_MUX (1 << (BTM_SEC_SERVICE_RFC_MUX - 32)) -#define BTM_SEC_TRUST_AVCTP_BROWSE (1 << (BTM_SEC_SERVICE_AVCTP_BROWSE - 32)) -#define BTM_SEC_TRUST_MAP (1 << (BTM_SEC_SERVICE_MAP - 32)) -#define BTM_SEC_TRUST_MAP_NOTIF (1 << (BTM_SEC_SERVICE_MAP_NOTIF - 32)) -#define BTM_SEC_TRUST_MCAP_CTRL (1 << (BTM_SEC_SERVICE_MCAP_CTRL - 32)) -#define BTM_SEC_TRUST_MCAP_DATA (1 << (BTM_SEC_SERVICE_MCAP_DATA - 32)) -#define BTM_SEC_TRUST_HDP_SNK (1 << (BTM_SEC_SERVICE_HDP_SNK - 32)) -#define BTM_SEC_TRUST_HDP_SRC (1 << (BTM_SEC_SERVICE_HDP_SRC - 32)) - -#define BTM_SEC_TRUST_ALL 0xFFFFFFFF /* for each array element */ - -/**************************************** -** Security Manager Callback Functions -*****************************************/ -/* Authorize device for service. Parameters are -** BD Address of remote -** Device Class of remote -** BD Name of remote -** Service name -** Service Id (NULL - unknown service or unused -** [BTM_SEC_SERVICE_NAME_LEN set to 0]) -** Is originator of the connection -** Result of the operation -*/ -typedef UINT8 (tBTM_AUTHORIZE_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class, - tBTM_BD_NAME bd_name, UINT8 *service_name, - UINT8 service_id, BOOLEAN is_originator); - -/* Get PIN for the connection. Parameters are -** BD Address of remote -** Device Class of remote -** BD Name of remote -** Flag indicating the minimum pin code length to be 16 digits -*/ -typedef UINT8 (tBTM_PIN_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class, - tBTM_BD_NAME bd_name, BOOLEAN min_16_digit); - -/* New Link Key for the connection. Parameters are -** BD Address of remote -** Link Key -** Key Type: Combination, Local Unit, or Remote Unit -*/ -typedef UINT8 (tBTM_LINK_KEY_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class, - tBTM_BD_NAME bd_name, UINT8 *key, - UINT8 key_type); - - -/* Remote Name Resolved. Parameters are -** BD Address of remote -** BD Name of remote -*/ -typedef void (tBTM_RMT_NAME_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dc, - tBTM_BD_NAME bd_name); - - -/* Authentication complete for the connection. Parameters are -** BD Address of remote -** Device Class of remote -** BD Name of remote -** -*/ -typedef UINT8 (tBTM_AUTH_COMPLETE_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class, - tBTM_BD_NAME bd_name, int result); - -enum { - BTM_SP_IO_REQ_EVT, /* received IO_CAPABILITY_REQUEST event */ - BTM_SP_IO_RSP_EVT, /* received IO_CAPABILITY_RESPONSE event */ - BTM_SP_CFM_REQ_EVT, /* received USER_CONFIRMATION_REQUEST event */ - BTM_SP_KEY_NOTIF_EVT, /* received USER_PASSKEY_NOTIFY event */ - BTM_SP_KEY_REQ_EVT, /* received USER_PASSKEY_REQUEST event */ - BTM_SP_KEYPRESS_EVT, /* received KEYPRESS_NOTIFY event */ - BTM_SP_LOC_OOB_EVT, /* received result for READ_LOCAL_OOB_DATA command */ - BTM_SP_RMT_OOB_EVT, /* received REMOTE_OOB_DATA_REQUEST event */ - BTM_SP_COMPLT_EVT, /* received SIMPLE_PAIRING_COMPLETE event */ - BTM_SP_UPGRADE_EVT /* check if the application wants to upgrade the link key */ -}; -typedef UINT8 tBTM_SP_EVT; - -/* relate to ESP_IO_CAP_xxx in esp_gap_ble_api.h */ -#define BTM_IO_CAP_OUT 0 /* DisplayOnly */ -#define BTM_IO_CAP_IO 1 /* DisplayYesNo */ -#define BTM_IO_CAP_IN 2 /* KeyboardOnly */ -#define BTM_IO_CAP_NONE 3 /* NoInputNoOutput */ -#if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE -#define BTM_IO_CAP_KBDISP 4 /* Keyboard display */ -#define BTM_IO_CAP_MAX 5 -#else -#define BTM_IO_CAP_MAX 4 -#endif - -typedef UINT8 tBTM_IO_CAP; - -#define BTM_MAX_PASSKEY_VAL (999999) -#define BTM_MIN_PASSKEY_VAL (0) - -#define BTM_AUTH_SP_NO 0 /* MITM Protection Not Required - Single Profile/non-bonding - Numeric comparison with automatic accept allowed */ -#define BTM_AUTH_SP_YES 1 /* MITM Protection Required - Single Profile/non-bonding - Use IO Capabilities to determine authentication procedure */ -#define BTM_AUTH_AP_NO 2 /* MITM Protection Not Required - All Profiles/dedicated bonding - Numeric comparison with automatic accept allowed */ -#define BTM_AUTH_AP_YES 3 /* MITM Protection Required - All Profiles/dedicated bonding - Use IO Capabilities to determine authentication procedure */ -#define BTM_AUTH_SPGB_NO 4 /* MITM Protection Not Required - Single Profiles/general bonding - Numeric comparison with automatic accept allowed */ -#define BTM_AUTH_SPGB_YES 5 /* MITM Protection Required - Single Profiles/general bonding - Use IO Capabilities to determine authentication procedure */ -#define BTM_AUTH_DD_BOND 2 /* this bit is ORed to the BTM_AUTH_SP_* when IO exchange for dedicated bonding */ -#define BTM_AUTH_GB_BIT 4 /* the genernal bonding bit */ -#define BTM_AUTH_BONDS 6 /* the general/dedicated bonding bits */ -#define BTM_AUTH_YN_BIT 1 /* this is the Yes or No bit */ - -#define BTM_BLE_ENC_KEY_MASK (1 << 0) -#define BTM_BLE_ID_KEY_MASK (1 << 1) -#define BTM_BLE_CSR_KEY_MASK (1 << 2) -#define BTM_BLE_LINK_KEY_MASK (1 << 3) - -#define BTM_BLE_INITIATOR_KEY_SIZE 15 -#define BTM_BLE_RESPONDER_KEY_SIZE 15 -#define BTM_BLE_MAX_KEY_SIZE 16 -#define BTM_BLE_MIN_KEY_SIZE 7 - -typedef UINT8 tBTM_AUTH_REQ; - -enum { - BTM_OOB_NONE, - BTM_OOB_PRESENT -#if BTM_OOB_INCLUDED == TRUE - , BTM_OOB_UNKNOWN -#endif -}; -typedef UINT8 tBTM_OOB_DATA; - -/* data type for BTM_SP_IO_REQ_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - tBTM_IO_CAP io_cap; /* local IO capabilities */ - tBTM_OOB_DATA oob_data; /* OOB data present (locally) for the peer device */ - tBTM_AUTH_REQ auth_req; /* Authentication required (for local device) */ - BOOLEAN is_orig; /* TRUE, if local device initiated the SP process */ -} tBTM_SP_IO_REQ; - -/* data type for BTM_SP_IO_RSP_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - tBTM_IO_CAP io_cap; /* peer IO capabilities */ - tBTM_OOB_DATA oob_data; /* OOB data present at peer device for the local device */ - tBTM_AUTH_REQ auth_req; /* Authentication required for peer device */ -} tBTM_SP_IO_RSP; - -/* data type for BTM_SP_CFM_REQ_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - tBTM_BD_NAME bd_name; /* peer device name */ - UINT32 num_val; /* the numeric value for comparison. If just_works, do not show this number to UI */ - BOOLEAN just_works; /* TRUE, if "Just Works" association model */ - tBTM_AUTH_REQ loc_auth_req; /* Authentication required for local device */ - tBTM_AUTH_REQ rmt_auth_req; /* Authentication required for peer device */ - tBTM_IO_CAP loc_io_caps; /* IO Capabilities of the local device */ - tBTM_IO_CAP rmt_io_caps; /* IO Capabilities of the remot device */ -} tBTM_SP_CFM_REQ; - -/* data type for BTM_SP_KEY_REQ_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - tBTM_BD_NAME bd_name; /* peer device name */ -} tBTM_SP_KEY_REQ; - -/* data type for BTM_SP_KEY_NOTIF_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - tBTM_BD_NAME bd_name; /* peer device name */ - UINT32 passkey; /* passkey */ -} tBTM_SP_KEY_NOTIF; - -enum { - BTM_SP_KEY_STARTED, /* 0 - passkey entry started */ - BTM_SP_KEY_ENTERED, /* 1 - passkey digit entered */ - BTM_SP_KEY_ERASED, /* 2 - passkey digit erased */ - BTM_SP_KEY_CLEARED, /* 3 - passkey cleared */ - BTM_SP_KEY_COMPLT, /* 4 - passkey entry completed */ - BTM_SP_KEY_OUT_OF_RANGE /* 5 - out of range */ -}; -typedef UINT8 tBTM_SP_KEY_TYPE; - -/* data type for BTM_SP_KEYPRESS_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - tBTM_SP_KEY_TYPE notif_type; -} tBTM_SP_KEYPRESS; - -/* data type for BTM_SP_LOC_OOB_EVT */ -typedef struct { - tBTM_STATUS status; /* */ - BT_OCTET16 c; /* Simple Pairing Hash C */ - BT_OCTET16 r; /* Simple Pairing Randomnizer R */ -} tBTM_SP_LOC_OOB; - -/* data type for BTM_SP_RMT_OOB_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - tBTM_BD_NAME bd_name; /* peer device name */ -} tBTM_SP_RMT_OOB; - - -/* data type for BTM_SP_COMPLT_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - tBTM_BD_NAME bd_name; /* peer device name */ - tBTM_STATUS status; /* status of the simple pairing process */ -} tBTM_SP_COMPLT; - -/* data type for BTM_SP_UPGRADE_EVT */ -typedef struct { - BD_ADDR bd_addr; /* peer address */ - BOOLEAN upgrade; /* TRUE, to upgrade the link key */ -} tBTM_SP_UPGRADE; - -typedef union { - tBTM_SP_IO_REQ io_req; /* BTM_SP_IO_REQ_EVT */ - tBTM_SP_IO_RSP io_rsp; /* BTM_SP_IO_RSP_EVT */ - tBTM_SP_CFM_REQ cfm_req; /* BTM_SP_CFM_REQ_EVT */ - tBTM_SP_KEY_NOTIF key_notif; /* BTM_SP_KEY_NOTIF_EVT */ - tBTM_SP_KEY_REQ key_req; /* BTM_SP_KEY_REQ_EVT */ - tBTM_SP_KEYPRESS key_press; /* BTM_SP_KEYPRESS_EVT */ - tBTM_SP_LOC_OOB loc_oob; /* BTM_SP_LOC_OOB_EVT */ - tBTM_SP_RMT_OOB rmt_oob; /* BTM_SP_RMT_OOB_EVT */ - tBTM_SP_COMPLT complt; /* BTM_SP_COMPLT_EVT */ - tBTM_SP_UPGRADE upgrade; /* BTM_SP_UPGRADE_EVT */ -} tBTM_SP_EVT_DATA; - -/* Simple Pairing Events. Called by the stack when Simple Pairing related -** events occur. -*/ -typedef UINT8 (tBTM_SP_CALLBACK) (tBTM_SP_EVT event, tBTM_SP_EVT_DATA *p_data); - - -typedef void (tBTM_MKEY_CALLBACK) (BD_ADDR bd_addr, UINT8 status, UINT8 key_flag) ; - -/* Encryption enabled/disabled complete: Optionally passed with BTM_SetEncryption. -** Parameters are -** BD Address of remote -** optional data passed in by BTM_SetEncryption -** tBTM_STATUS - result of the operation -*/ -typedef void (tBTM_SEC_CBACK) (BD_ADDR bd_addr, tBT_TRANSPORT trasnport, - void *p_ref_data, tBTM_STATUS result); - -/* Bond Cancel complete. Parameters are -** Result of the cancel operation -** -*/ -typedef void (tBTM_BOND_CANCEL_CMPL_CALLBACK) (tBTM_STATUS result); - -/* LE related event and data structure -*/ -/* relate to ESP_LE_KEY_xxx in esp_gap_ble_api.h */ -#if (SMP_INCLUDED == TRUE) -#define BTM_LE_IO_REQ_EVT SMP_IO_CAP_REQ_EVT /* received IO_CAPABILITY_REQUEST event */ -#define BTM_LE_SEC_REQUEST_EVT SMP_SEC_REQUEST_EVT /* security request event */ -#define BTM_LE_KEY_NOTIF_EVT SMP_PASSKEY_NOTIF_EVT /* received USER_PASSKEY_NOTIFY event */ -#define BTM_LE_KEY_REQ_EVT SMP_PASSKEY_REQ_EVT /* received USER_PASSKEY_REQUEST event */ -#define BTM_LE_OOB_REQ_EVT SMP_OOB_REQ_EVT /* OOB data request event */ -#define BTM_LE_NC_REQ_EVT SMP_NC_REQ_EVT /* Numeric Comparison request event */ -#define BTM_LE_PR_KEYPR_NOT_EVT SMP_PEER_KEYPR_NOT_EVT /* Peer keypress notification recd event */ -/* SC OOB request event (both local and peer OOB data) can be expected in response */ -#define BTM_LE_SC_OOB_REQ_EVT SMP_SC_OOB_REQ_EVT -/* SC OOB local data set is created (as result of SMP_CrLocScOobData(...)) */ -#define BTM_LE_SC_LOC_OOB_EVT SMP_SC_LOC_OOB_DATA_UP_EVT -#define BTM_LE_BR_KEYS_REQ_EVT SMP_BR_KEYS_REQ_EVT /* SMP over BR keys request event */ -#define BTM_LE_COMPLT_EVT SMP_COMPLT_EVT /* SMP complete event */ -#define BTM_LE_LAST_FROM_SMP BTM_LE_BR_KEYS_REQ_EVT -#define BTM_LE_KEY_EVT BTM_LE_LAST_FROM_SMP + 1 /* KEY update event */ -#endif ///SMP_INCLUDED == TRUE -typedef UINT8 tBTM_LE_EVT; - -#if (BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE) -#define BTM_LE_KEY_NONE 0 -#define BTM_LE_KEY_PENC SMP_SEC_KEY_TYPE_ENC /* encryption information of peer device */ -#define BTM_LE_KEY_PID SMP_SEC_KEY_TYPE_ID /* identity key of the peer device */ -#define BTM_LE_KEY_PCSRK SMP_SEC_KEY_TYPE_CSRK /* peer SRK */ -#define BTM_LE_KEY_PLK SMP_SEC_KEY_TYPE_LK -#define BTM_LE_KEY_LLK (SMP_SEC_KEY_TYPE_LK << 4) -#define BTM_LE_KEY_LENC (SMP_SEC_KEY_TYPE_ENC << 4) /* master role security information:div */ -#define BTM_LE_KEY_LID (SMP_SEC_KEY_TYPE_ID << 4) /* master device ID key */ -#define BTM_LE_KEY_LCSRK (SMP_SEC_KEY_TYPE_CSRK << 4) /* local CSRK has been deliver to peer */ -#endif ///BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE -typedef UINT8 tBTM_LE_KEY_TYPE; - -/* relate to ESP_LE_AUTH_xxx in esp_gap_ble_api.h */ -#if (SMP_INCLUDED == TRUE) -#define BTM_LE_AUTH_REQ_NO_BOND SMP_AUTH_NO_BOND /* 0 */ -#define BTM_LE_AUTH_REQ_BOND SMP_AUTH_GEN_BOND /* 1 << 0 */ -#define BTM_LE_AUTH_REQ_MITM SMP_AUTH_YN_BIT /* 1 << 2 */ -#endif ///SMP_INCLUDED == TRUE -typedef UINT8 tBTM_LE_AUTH_REQ; -#if (SMP_INCLUDED == TRUE) -#define BTM_LE_SC_SUPPORT_BIT SMP_SC_SUPPORT_BIT /* (1 << 3) */ -#define BTM_LE_KP_SUPPORT_BIT SMP_KP_SUPPORT_BIT /* (1 << 4) */ - -#define BTM_LE_AUTH_REQ_SC_ONLY SMP_AUTH_SC_ENC_ONLY /* 1 << 3 */ -#define BTM_LE_AUTH_REQ_SC_BOND SMP_AUTH_SC_GB /* 1001 */ -#define BTM_LE_AUTH_REQ_SC_MITM SMP_AUTH_SC_MITM_NB /* 1100 */ -#define BTM_LE_AUTH_REQ_SC_MITM_BOND SMP_AUTH_SC_MITM_GB /* 1101 */ -#define BTM_LE_AUTH_REQ_MASK SMP_AUTH_MASK /* 0x1D */ - -/* LE security level */ -#define BTM_LE_SEC_NONE SMP_SEC_NONE -#define BTM_LE_SEC_UNAUTHENTICATE SMP_SEC_UNAUTHENTICATE /* 1 */ -#define BTM_LE_SEC_AUTHENTICATED SMP_SEC_AUTHENTICATED /* 4 */ -#endif ///SMP_INCLUDED == TRUE -typedef UINT8 tBTM_LE_SEC; - - -typedef struct { - tBTM_IO_CAP io_cap; /* local IO capabilities */ - UINT8 oob_data; /* OOB data present (locally) for the peer device */ - tBTM_LE_AUTH_REQ auth_req; /* Authentication request (for local device) contain bonding and MITM info */ - UINT8 max_key_size; /* max encryption key size */ - tBTM_LE_KEY_TYPE init_keys; /* keys to be distributed, bit mask */ - tBTM_LE_KEY_TYPE resp_keys; /* keys to be distributed, bit mask */ -} tBTM_LE_IO_REQ; - -#if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE -/* data type for tBTM_LE_COMPLT */ -typedef struct { - UINT8 reason; - UINT8 sec_level; - BOOLEAN is_pair_cancel; - BOOLEAN smp_over_br; -} tBTM_LE_COMPLT; -#endif - -/* BLE encryption keys */ -typedef struct { - BT_OCTET16 ltk; - BT_OCTET8 rand; - UINT16 ediv; - UINT8 sec_level; - UINT8 key_size; -} tBTM_LE_PENC_KEYS; - -/* BLE CSRK keys */ -typedef struct { - UINT32 counter; - BT_OCTET16 csrk; - UINT8 sec_level; -} tBTM_LE_PCSRK_KEYS; - -/* BLE Encryption reproduction keys */ -typedef struct { - BT_OCTET16 ltk; - UINT16 div; - UINT8 key_size; - UINT8 sec_level; -} tBTM_LE_LENC_KEYS; - -/* BLE SRK keys */ -typedef struct { - UINT32 counter; - UINT16 div; - UINT8 sec_level; - BT_OCTET16 csrk; -} tBTM_LE_LCSRK_KEYS; - -typedef struct { - BT_OCTET16 irk; - tBLE_ADDR_TYPE addr_type; - BD_ADDR static_addr; -} tBTM_LE_PID_KEYS; - -typedef union { - tBTM_LE_PENC_KEYS penc_key; /* received peer encryption key */ - tBTM_LE_PCSRK_KEYS pcsrk_key; /* received peer device SRK */ - tBTM_LE_PID_KEYS pid_key; /* peer device ID key */ - tBTM_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys LTK = = d1(ER,DIV,0)*/ - tBTM_LE_LCSRK_KEYS lcsrk_key; /* local device CSRK = d1(ER,DIV,1)*/ -} tBTM_LE_KEY_VALUE; - -typedef struct { - tBTM_LE_KEY_TYPE key_type; - tBTM_LE_KEY_VALUE *p_key_value; -} tBTM_LE_KEY; - -typedef union { - tBTM_LE_IO_REQ io_req; /* BTM_LE_IO_REQ_EVT */ - UINT32 key_notif; /* BTM_LE_KEY_NOTIF_EVT */ - /* BTM_LE_NC_REQ_EVT */ - /* no callback data for BTM_LE_KEY_REQ_EVT */ - /* and BTM_LE_OOB_REQ_EVT */ -#if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE - tBTM_LE_COMPLT complt; /* BTM_LE_COMPLT_EVT */ - tSMP_OOB_DATA_TYPE req_oob_type; -#endif - tBTM_LE_KEY key; -} tBTM_LE_EVT_DATA; - -/* Simple Pairing Events. Called by the stack when Simple Pairing related -** events occur. -*/ -typedef UINT8 (tBTM_LE_CALLBACK) (tBTM_LE_EVT event, BD_ADDR bda, tBTM_LE_EVT_DATA *p_data); - -#define BTM_BLE_KEY_TYPE_ID 1 -#define BTM_BLE_KEY_TYPE_ER 2 -#define BTM_BLE_KEY_TYPE_COUNTER 3 //tobe obsolete - -typedef struct { - BT_OCTET16 ir; - BT_OCTET16 irk; - BT_OCTET16 dhk; - -} tBTM_BLE_LOCAL_ID_KEYS; - -typedef union { - tBTM_BLE_LOCAL_ID_KEYS id_keys; - BT_OCTET16 er; -} tBTM_BLE_LOCAL_KEYS; - - -/* New LE identity key for local device. -*/ -typedef void (tBTM_LE_KEY_CALLBACK) (UINT8 key_type, tBTM_BLE_LOCAL_KEYS *p_key); - - -/*************************** -** Security Manager Types -****************************/ -/* Structure that applications use to register with BTM_SecRegister */ -typedef struct { - tBTM_AUTHORIZE_CALLBACK *p_authorize_callback; - tBTM_PIN_CALLBACK *p_pin_callback; - tBTM_LINK_KEY_CALLBACK *p_link_key_callback; - tBTM_AUTH_COMPLETE_CALLBACK *p_auth_complete_callback; - tBTM_BOND_CANCEL_CMPL_CALLBACK *p_bond_cancel_cmpl_callback; - tBTM_SP_CALLBACK *p_sp_callback; -#if BLE_INCLUDED == TRUE -#if SMP_INCLUDED == TRUE - tBTM_LE_CALLBACK *p_le_callback; -#endif - tBTM_LE_KEY_CALLBACK *p_le_key_callback; -#endif -} tBTM_APPL_INFO; - -/* Callback function for when a link supervision timeout event occurs. -** This asynchronous event is enabled/disabled by calling BTM_RegForLstoEvt(). -*/ -typedef void (tBTM_LSTO_CBACK) (BD_ADDR remote_bda, UINT16 timeout); - -/***************************************************************************** -** POWER MANAGEMENT -*****************************************************************************/ -/**************************** -** Power Manager Constants -*****************************/ -/* BTM Power manager status codes */ -enum { - BTM_PM_STS_ACTIVE = HCI_MODE_ACTIVE, - BTM_PM_STS_HOLD = HCI_MODE_HOLD, - BTM_PM_STS_SNIFF = HCI_MODE_SNIFF, - BTM_PM_STS_PARK = HCI_MODE_PARK, - BTM_PM_STS_SSR, /* report the SSR parameters in HCI_SNIFF_SUB_RATE_EVT */ - BTM_PM_STS_PENDING, /* when waiting for status from controller */ - BTM_PM_STS_ERROR /* when HCI command status returns error */ -}; -typedef UINT8 tBTM_PM_STATUS; - -/* BTM Power manager modes */ -enum { - BTM_PM_MD_ACTIVE = BTM_PM_STS_ACTIVE, - BTM_PM_MD_HOLD = BTM_PM_STS_HOLD, - BTM_PM_MD_SNIFF = BTM_PM_STS_SNIFF, - BTM_PM_MD_PARK = BTM_PM_STS_PARK, - BTM_PM_MD_FORCE = 0x10 /* OR this to force ACL link to a certain mode */ -}; -typedef UINT8 tBTM_PM_MODE; - -#define BTM_PM_SET_ONLY_ID 0x80 - -/* Operation codes */ -#define BTM_PM_REG_SET 1 /* The module wants to set the desired power mode */ -#define BTM_PM_REG_NOTIF 2 /* The module wants to receive mode change event */ -#define BTM_PM_DEREG 4 /* The module does not want to involve with PM anymore */ - -/************************ -** Power Manager Types -*************************/ -typedef struct { - UINT16 max; - UINT16 min; - UINT16 attempt; - UINT16 timeout; - tBTM_PM_MODE mode; -} tBTM_PM_PWR_MD; - -/************************************* -** Power Manager Callback Functions -**************************************/ -typedef void (tBTM_PM_STATUS_CBACK) (BD_ADDR p_bda, tBTM_PM_STATUS status, - UINT16 value, UINT8 hci_status); - - -/************************ -** Stored Linkkey Types -*************************/ -#define BTM_CB_EVT_DELETE_STORED_LINK_KEYS 4 - -typedef struct { - UINT8 event; - UINT8 status; - UINT16 num_keys; - -} tBTM_DELETE_STORED_LINK_KEY_COMPLETE; - -/* MIP evnets, callbacks */ -enum { - BTM_MIP_MODE_CHG_EVT, - BTM_MIP_DISCONNECT_EVT, - BTM_MIP_PKTS_COMPL_EVT, - BTM_MIP_RXDATA_EVT -}; -typedef UINT8 tBTM_MIP_EVT; - -typedef struct { - tBTM_MIP_EVT event; - BD_ADDR bd_addr; - UINT16 mip_id; -} tBTM_MIP_MODE_CHANGE; - -typedef struct { - tBTM_MIP_EVT event; - UINT16 mip_id; - UINT8 disc_reason; -} tBTM_MIP_CONN_TIMEOUT; - -#define BTM_MIP_MAX_RX_LEN 17 - -typedef struct { - tBTM_MIP_EVT event; - UINT16 mip_id; - UINT8 rx_len; - UINT8 rx_data[BTM_MIP_MAX_RX_LEN]; -} tBTM_MIP_RXDATA; - -typedef struct { - tBTM_MIP_EVT event; - BD_ADDR bd_addr; - UINT8 data[11]; /* data[0] shows Vender-specific device type */ -} tBTM_MIP_EIR_HANDSHAKE; - -typedef struct { - tBTM_MIP_EVT event; - UINT16 num_sent; /* Number of packets completed at the controller */ -} tBTM_MIP_PKTS_COMPL; - -typedef union { - tBTM_MIP_EVT event; - tBTM_MIP_MODE_CHANGE mod_chg; - tBTM_MIP_CONN_TIMEOUT conn_tmo; - tBTM_MIP_EIR_HANDSHAKE eir; - tBTM_MIP_PKTS_COMPL completed; - tBTM_MIP_RXDATA rxdata; -} tBTM_MIP_EVENT_DATA; - -/* MIP event callback function */ -typedef void (tBTM_MIP_EVENTS_CB) (tBTM_MIP_EVT event, tBTM_MIP_EVENT_DATA data); - -/* MIP Device query callback function */ -typedef BOOLEAN (tBTM_MIP_QUERY_CB) (BD_ADDR dev_addr, UINT8 *p_mode, LINK_KEY link_key); - -#define BTM_CONTRL_ACTIVE 1 /* ACL link on, SCO link ongoing, sniff mode */ -#define BTM_CONTRL_SCAN 2 /* Scan state - paging/inquiry/trying to connect*/ -#define BTM_CONTRL_IDLE 3 /* Idle state - page scan, LE advt, inquiry scan */ - -typedef UINT8 tBTM_CONTRL_STATE; - -/***************************************************************************** -** EXTERNAL FUNCTION DECLARATIONS -*****************************************************************************/ -/* -#ifdef __cplusplus -extern "C" { -#endif -*/ -/***************************************************************************** -** DEVICE CONTROL and COMMON FUNCTIONS -*****************************************************************************/ - -/******************************************************************************* -** -** Function BTM_DeviceReset -** -** Description This function is called to reset the controller.The Callback function -** if provided is called when startup of the device has -** completed. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_DeviceReset (tBTM_CMPL_CB *p_cb); - - -/******************************************************************************* -** -** Function BTM_IsDeviceUp -** -** Description This function is called to check if the device is up. -** -** Returns TRUE if device is up, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_IsDeviceUp (void); - - -/******************************************************************************* -** -** Function BTM_SetLocalDeviceName -** -** Description This function is called to set the local device name. -** -** Returns BTM_CMD_STARTED if successful, otherwise an error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetLocalDeviceName (char *p_name); - -/******************************************************************************* -** -** Function BTM_SetDeviceClass -** -** Description This function is called to set the local device class -** -** Returns BTM_SUCCESS if successful, otherwise an error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetDeviceClass (DEV_CLASS dev_class); - - -/******************************************************************************* -** -** Function BTM_ReadLocalDeviceName -** -** Description This function is called to read the local device name. -** -** Returns status of the operation -** If success, BTM_SUCCESS is returned and p_name points stored -** local device name -** If BTM doesn't store local device name, BTM_NO_RESOURCES is -** is returned and p_name is set to NULL -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadLocalDeviceName (char **p_name); - -/******************************************************************************* -** -** Function BTM_ReadLocalDeviceNameFromController -** -** Description Get local device name from controller. Do not use cached -** name (used to get chip-id prior to btm reset complete). -** -** Returns BTM_CMD_STARTED if successful, otherwise an error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadLocalDeviceNameFromController (tBTM_CMPL_CB *p_rln_cmpl_cback); - -/******************************************************************************* -** -** Function BTM_ReadDeviceClass -** -** Description This function is called to read the local device class -** -** Returns pointer to the device class -** -*******************************************************************************/ -//extern -UINT8 *BTM_ReadDeviceClass (void); - - -/******************************************************************************* -** -** Function BTM_ReadLocalFeatures -** -** Description This function is called to read the local features -** -** Returns pointer to the local features string -** -*******************************************************************************/ -//extern -UINT8 *BTM_ReadLocalFeatures (void); - -/******************************************************************************* -** -** Function BTM_RegisterForDeviceStatusNotif -** -** Description This function is called to register for device status -** change notifications. -** -** Returns pointer to previous caller's callback function or NULL if first -** registration. -** -*******************************************************************************/ -//extern -tBTM_DEV_STATUS_CB *BTM_RegisterForDeviceStatusNotif (tBTM_DEV_STATUS_CB *p_cb); - - -/******************************************************************************* -** -** Function BTM_RegisterForVSEvents -** -** Description This function is called to register/deregister for vendor -** specific HCI events. -** -** If is_register=TRUE, then the function will be registered; -** if is_register=FALSE, then the function will be deregistered. -** -** Returns BTM_SUCCESS if successful, -** BTM_BUSY if maximum number of callbacks have already been -** registered. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_RegisterForVSEvents (tBTM_VS_EVT_CB *p_cb, BOOLEAN is_register); - - -/******************************************************************************* -** -** Function BTM_VendorSpecificCommand -** -** Description Send a vendor specific HCI command to the controller. -** -** Returns -** BTM_SUCCESS Command sent. Does not expect command complete -** event. (command cmpl callback param is NULL) -** BTM_CMD_STARTED Command sent. Waiting for command cmpl event. -** BTM_BUSY Command not sent. Waiting for cmd cmpl event for -** prior command. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_VendorSpecificCommand(UINT16 opcode, - UINT8 param_len, - UINT8 *p_param_buf, - tBTM_VSC_CMPL_CB *p_cb); - - -/******************************************************************************* -** -** Function BTM_AllocateSCN -** -** Description Look through the Server Channel Numbers for a free one to be -** used with an RFCOMM connection. -** -** Returns Allocated SCN number or 0 if none. -** -*******************************************************************************/ -//extern -#if (CLASSIC_BT_INCLUDED == TRUE) -UINT8 BTM_AllocateSCN(void); - -// btla-specific ++ -/******************************************************************************* -** -** Function BTM_TryAllocateSCN -** -** Description Try to allocate a fixed server channel -** -** Returns Returns TRUE if server channel was available -** -*******************************************************************************/ -//extern -BOOLEAN BTM_TryAllocateSCN(UINT8 scn); -// btla-specific -- - - -/******************************************************************************* -** -** Function BTM_FreeSCN -** -** Description Free the specified SCN. -** -** Returns TRUE if successful, FALSE if SCN is not in use or invalid -** -*******************************************************************************/ -//extern -BOOLEAN BTM_FreeSCN(UINT8 scn); -#endif ///CLASSIC_BT_INCLUDED == TRUE - - -/******************************************************************************* -** -** Function BTM_SetTraceLevel -** -** Description This function sets the trace level for BTM. If called with -** a value of 0xFF, it simply returns the current trace level. -** -** Returns The new or current trace level -** -*******************************************************************************/ -//extern -UINT8 BTM_SetTraceLevel (UINT8 new_level); - - -/******************************************************************************* -** -** Function BTM_WritePageTimeout -** -** Description Send HCI Wite Page Timeout. -** -** Returns -** BTM_SUCCESS Command sent. -** BTM_NO_RESOURCES If out of resources to send the command. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_WritePageTimeout(UINT16 timeout); - -/******************************************************************************* -** -** Function BTM_WriteVoiceSettings -** -** Description Send HCI Write Voice Settings command. -** See hcidefs.h for settings bitmask values. -** -** Returns -** BTM_SUCCESS Command sent. -** BTM_NO_RESOURCES If out of resources to send the command. -** -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_WriteVoiceSettings(UINT16 settings); - -/******************************************************************************* -** -** Function BTM_EnableTestMode -** -** Description Send HCI the enable device under test command. -** -** Note: Controller can only be taken out of this mode by -** resetting the controller. -** -** Returns -** BTM_SUCCESS Command sent. -** BTM_NO_RESOURCES If out of resources to send the command. -** -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_EnableTestMode(void); - - -/***************************************************************************** -** DEVICE DISCOVERY FUNCTIONS - Inquiry, Remote Name, Discovery, Class of Device -*****************************************************************************/ - -/******************************************************************************* -** -** Function BTM_SetDiscoverability -** -** Description This function is called to set the device into or out of -** discoverable mode. Discoverable mode means inquiry -** scans are enabled. If a value of '0' is entered for window or -** interval, the default values are used. -** -** Returns BTM_SUCCESS if successful -** BTM_BUSY if a setting of the filter is already in progress -** BTM_NO_RESOURCES if couldn't get a memory pool buffer -** BTM_ILLEGAL_VALUE if a bad parameter was detected -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetDiscoverability (UINT16 inq_mode, UINT16 window, - UINT16 interval); - - -/******************************************************************************* -** -** Function BTM_ReadDiscoverability -** -** Description This function is called to read the current discoverability -** mode of the device. -** -** Output Params: p_window - current inquiry scan duration -** p_interval - current inquiry scan interval -** -** Returns BTM_NON_DISCOVERABLE, BTM_LIMITED_DISCOVERABLE, or -** BTM_GENERAL_DISCOVERABLE -** -*******************************************************************************/ -//extern -UINT16 BTM_ReadDiscoverability (UINT16 *p_window, - UINT16 *p_interval); - - -/******************************************************************************* -** -** Function BTM_SetPeriodicInquiryMode -** -** Description This function is called to set the device periodic inquiry mode. -** If the duration is zero, the periodic inquiry mode is cancelled. -** -** Parameters: p_inqparms - pointer to the inquiry information -** mode - GENERAL or LIMITED inquiry -** duration - length in 1.28 sec intervals (If '0', the inquiry is CANCELLED) -** max_resps - maximum amount of devices to search for before ending the inquiry -** filter_cond_type - BTM_CLR_INQUIRY_FILTER, BTM_FILTER_COND_DEVICE_CLASS, or -** BTM_FILTER_COND_BD_ADDR -** filter_cond - value for the filter (based on filter_cond_type) -** -** max_delay - maximum amount of time between successive inquiries -** min_delay - minimum amount of time between successive inquiries -** p_results_cb - callback returning pointer to results (tBTM_INQ_RESULTS) -** -** Returns BTM_CMD_STARTED if successfully started -** BTM_ILLEGAL_VALUE if a bad parameter is detected -** BTM_NO_RESOURCES if could not allocate a message buffer -** BTM_SUCCESS - if cancelling the periodic inquiry -** BTM_BUSY - if an inquiry is already active -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetPeriodicInquiryMode (tBTM_INQ_PARMS *p_inqparms, - UINT16 max_delay, UINT16 min_delay, - tBTM_INQ_RESULTS_CB *p_results_cb); - - -/******************************************************************************* -** -** Function BTM_StartInquiry -** -** Description This function is called to start an inquiry. -** -** Parameters: p_inqparms - pointer to the inquiry information -** mode - GENERAL or LIMITED inquiry -** duration - length in 1.28 sec intervals (If '0', the inquiry is CANCELLED) -** max_resps - maximum amount of devices to search for before ending the inquiry -** filter_cond_type - BTM_CLR_INQUIRY_FILTER, BTM_FILTER_COND_DEVICE_CLASS, or -** BTM_FILTER_COND_BD_ADDR -** filter_cond - value for the filter (based on filter_cond_type) -** -** p_results_cb - Pointer to the callback routine which gets called -** upon receipt of an inquiry result. If this field is -** NULL, the application is not notified. -** -** p_cmpl_cb - Pointer to the callback routine which gets called -** upon completion. If this field is NULL, the -** application is not notified when completed. -** Returns tBTM_STATUS -** BTM_CMD_STARTED if successfully initiated -** BTM_BUSY if already in progress -** BTM_ILLEGAL_VALUE if parameter(s) are out of range -** BTM_NO_RESOURCES if could not allocate resources to start the command -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_StartInquiry (tBTM_INQ_PARMS *p_inqparms, - tBTM_INQ_RESULTS_CB *p_results_cb, - tBTM_CMPL_CB *p_cmpl_cb); - - -/******************************************************************************* -** -** Function BTM_IsInquiryActive -** -** Description This function returns a bit mask of the current inquiry state -** -** Returns BTM_INQUIRY_INACTIVE if inactive (0) -** BTM_LIMITED_INQUIRY_ACTIVE if a limted inquiry is active -** BTM_GENERAL_INQUIRY_ACTIVE if a general inquiry is active -** BTM_PERIODIC_INQUIRY_ACTIVE if a periodic inquiry is active -** -*******************************************************************************/ -//extern -UINT16 BTM_IsInquiryActive (void); - - -/******************************************************************************* -** -** Function BTM_CancelInquiry -** -** Description This function cancels an inquiry if active -** -** Returns BTM_SUCCESS if successful -** BTM_NO_RESOURCES if could not allocate a message buffer -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_CancelInquiry(void); - - -/******************************************************************************* -** -** Function BTM_CancelPeriodicInquiry -** -** Description This function cancels a periodic inquiry -** -** Returns -** BTM_NO_RESOURCES if could not allocate a message buffer -** BTM_SUCCESS - if cancelling the periodic inquiry -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_CancelPeriodicInquiry(void); - - -/******************************************************************************* -** -** Function BTM_SetConnectability -** -** Description This function is called to set the device into or out of -** connectable mode. Discoverable mode means page scans enabled. -** -** Returns BTM_SUCCESS if successful -** BTM_ILLEGAL_VALUE if a bad parameter is detected -** BTM_NO_RESOURCES if could not allocate a message buffer -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetConnectability (UINT16 page_mode, UINT16 window, - UINT16 interval); - - -/******************************************************************************* -** -** Function BTM_ReadConnectability -** -** Description This function is called to read the current discoverability -** mode of the device. -** Output Params p_window - current page scan duration -** p_interval - current time between page scans -** -** Returns BTM_NON_CONNECTABLE or BTM_CONNECTABLE -** -*******************************************************************************/ -//extern -UINT16 BTM_ReadConnectability (UINT16 *p_window, UINT16 *p_interval); - - -/******************************************************************************* -** -** Function BTM_SetInquiryMode -** -** Description This function is called to set standard, with RSSI -** mode or extended of the inquiry for local device. -** -** Input Params: BTM_INQ_RESULT_STANDARD, BTM_INQ_RESULT_WITH_RSSI or -** BTM_INQ_RESULT_EXTENDED -** -** Returns BTM_SUCCESS if successful -** BTM_NO_RESOURCES if couldn't get a memory pool buffer -** BTM_ILLEGAL_VALUE if a bad parameter was detected -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetInquiryMode (UINT8 mode); - -/******************************************************************************* -** -** Function BTM_SetInquiryScanType -** -** Description This function is called to set the iquiry scan-type to -** standard or interlaced. -** -** Input Params: BTM_SCAN_TYPE_STANDARD or BTM_SCAN_TYPE_INTERLACED -** -** Returns BTM_SUCCESS if successful -** BTM_MODE_UNSUPPORTED if not a 1.2 device -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetInquiryScanType (UINT16 scan_type); - -/******************************************************************************* -** -** Function BTM_SetPageScanType -** -** Description This function is called to set the page scan-type to -** standard or interlaced. -** -** Input Params: BTM_SCAN_TYPE_STANDARD or BTM_SCAN_TYPE_INTERLACED -** -** Returns BTM_SUCCESS if successful -** BTM_MODE_UNSUPPORTED if not a 1.2 device -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ - -//extern -tBTM_STATUS BTM_SetPageScanType (UINT16 scan_type); - -/******************************************************************************* -** -** Function BTM_ReadRemoteDeviceName -** -** Description This function initiates a remote device HCI command to the -** controller and calls the callback when the process has completed. -** -** Input Params: remote_bda - device address of name to retrieve -** p_cb - callback function called when BTM_CMD_STARTED -** is returned. -** A pointer to tBTM_REMOTE_DEV_NAME is passed to the -** callback. -** -** Returns -** BTM_CMD_STARTED is returned if the request was successfully sent -** to HCI. -** BTM_BUSY if already in progress -** BTM_UNKNOWN_ADDR if device address is bad -** BTM_NO_RESOURCES if could not allocate resources to start the command -** BTM_WRONG_MODE if the device is not up. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadRemoteDeviceName (BD_ADDR remote_bda, - tBTM_CMPL_CB *p_cb, - tBT_TRANSPORT transport); - - -/******************************************************************************* -** -** Function BTM_CancelRemoteDeviceName -** -** Description This function initiates the cancel request for the specified -** remote device. -** -** Input Params: None -** -** Returns -** BTM_CMD_STARTED is returned if the request was successfully sent -** to HCI. -** BTM_NO_RESOURCES if could not allocate resources to start the command -** BTM_WRONG_MODE if there is not an active remote name request. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_CancelRemoteDeviceName (void); - -/******************************************************************************* -** -** Function BTM_ReadRemoteVersion -** -** Description This function is called to read a remote device's version -** -** Returns BTM_SUCCESS if successful, otherwise an error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadRemoteVersion (BD_ADDR addr, - UINT8 *lmp_version, - UINT16 *manufacturer, - UINT16 *lmp_sub_version); - -/******************************************************************************* -** -** Function BTM_ReadRemoteFeatures -** -** Description This function is called to read a remote device's -** supported features mask (features mask located at page 0) -** -** Note: The size of device features mask page is -** BTM_FEATURE_BYTES_PER_PAGE bytes. -** -** Returns pointer to the remote supported features mask -** -*******************************************************************************/ -//extern -UINT8 *BTM_ReadRemoteFeatures (BD_ADDR addr); - -/******************************************************************************* -** -** Function BTM_ReadRemoteExtendedFeatures -** -** Description This function is called to read a specific extended features -** page of the remote device -** -** Note1: The size of device features mask page is -** BTM_FEATURE_BYTES_PER_PAGE bytes. -** Note2: The valid device features mask page number depends on -** the remote device capabilities. It is expected to be in the -** range [0 - BTM_EXT_FEATURES_PAGE_MAX]. - -** Returns pointer to the remote extended features mask -** or NULL if page_number is not valid -** -*******************************************************************************/ -//extern -UINT8 *BTM_ReadRemoteExtendedFeatures (BD_ADDR addr, UINT8 page_number); - -/******************************************************************************* -** -** Function BTM_ReadNumberRemoteFeaturesPages -** -** Description This function is called to retrieve the number of feature pages -** read from the remote device -** -** Returns number of features pages read from the remote device -** -*******************************************************************************/ -//extern -UINT8 BTM_ReadNumberRemoteFeaturesPages (BD_ADDR addr); - -/******************************************************************************* -** -** Function BTM_ReadAllRemoteFeatures -** -** Description This function is called to read all features of the remote device -** -** Returns pointer to the byte[0] of the page[0] of the remote device -** feature mask. -** -** Note: the function returns the pointer to the array of the size -** BTM_FEATURE_BYTES_PER_PAGE * (BTM_EXT_FEATURES_PAGE_MAX + 1). -** -*******************************************************************************/ -//extern -UINT8 *BTM_ReadAllRemoteFeatures (BD_ADDR addr); - -/******************************************************************************* -** -** Function BTM_InqDbRead -** -** Description This function looks through the inquiry database for a match -** based on Bluetooth Device Address. This is the application's -** interface to get the inquiry details of a specific BD address. -** -** Returns pointer to entry, or NULL if not found -** -*******************************************************************************/ -//extern -tBTM_INQ_INFO *BTM_InqDbRead (BD_ADDR p_bda); - - -/******************************************************************************* -** -** Function BTM_InqDbFirst -** -** Description This function looks through the inquiry database for the first -** used entry, and returns that. This is used in conjunction with -** BTM_InqDbNext by applications as a way to walk through the -** inquiry database. -** -** Returns pointer to first in-use entry, or NULL if DB is empty -** -*******************************************************************************/ -//extern -tBTM_INQ_INFO *BTM_InqDbFirst (void); - - -/******************************************************************************* -** -** Function BTM_InqDbNext -** -** Description This function looks through the inquiry database for the next -** used entry, and returns that. If the input parameter is NULL, -** the first entry is returned. -** -** Returns pointer to next in-use entry, or NULL if no more found. -** -*******************************************************************************/ -//extern -tBTM_INQ_INFO *BTM_InqDbNext (tBTM_INQ_INFO *p_cur); - - -/******************************************************************************* -** -** Function BTM_ClearInqDb -** -** Description This function is called to clear out a device or all devices -** from the inquiry database. -** -** Parameter p_bda - (input) BD_ADDR -> Address of device to clear -** (NULL clears all entries) -** -** Returns BTM_BUSY if an inquiry, get remote name, or event filter -** is active, otherwise BTM_SUCCESS -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ClearInqDb (BD_ADDR p_bda); - -/******************************************************************************* -** -** Function BTM_ReadInquiryRspTxPower -** -** Description This command will read the inquiry Transmit Power level used -** to transmit the FHS and EIR data packets. -** This can be used directly in the Tx Power Level EIR data type. -** -** Returns BTM_SUCCESS if successful -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadInquiryRspTxPower (tBTM_CMPL_CB *p_cb); - -#if SDP_INCLUDED == TRUE -/******************************************************************************* -** -** Function BTM_StartDiscovery -** -** Description This function is called by an application (or profile) -** when it wants to trigger an service discovery using the -** BTM's discovery database. -** -** Returns tBTM_STATUS -** BTM_CMD_STARTED if the discovery was initiated -** BTM_BUSY if one is already in progress -** BTM_UNKNOWN_ADDR if no addresses are in the INQ DB -** BTM_ERR_PROCESSING if err initiating the command -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_StartDiscovery (tBTM_CMPL_CB *p_cmpl_cb, - BD_ADDR_PTR p_rem_addr); - - -/******************************************************************************* -** -** Function BTM_FindAttribute -** -** Description This function is called by an application (or profile) -** when it wants to see if an attribute exists in the BTM -** discovery database. -** -** Returns Pointer to matching record, or NULL -** -*******************************************************************************/ -//extern -tSDP_DISC_REC *BTM_FindAttribute (UINT16 attr_id, - tSDP_DISC_REC *p_start_rec); - - -/******************************************************************************* -** -** Function BTM_FindService -** -** Description This function is called by an application (or profile) -** when it wants to see if a service exists in the BTM -** discovery database. -** -** Returns Pointer to matching record, or NULL -** -*******************************************************************************/ -//extern -tSDP_DISC_REC *BTM_FindService (UINT16 service_uuid, - tSDP_DISC_REC *p_start_rec); - - -/******************************************************************************* -** -** Function BTM_SetDiscoveryParams -** -** Description This function is called to set the BTM default discovery parameters. -** These UUID and attribute filters are used during the call to -** BTM_StartDiscovery. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_SetDiscoveryParams (UINT16 num_uuid, tSDP_UUID *p_uuid_list, - UINT16 num_attr, UINT16 *p_attr_list); -#endif /*SDP_INCLUDED*/ - -/***************************************************************************** -** ACL CHANNEL MANAGEMENT FUNCTIONS -*****************************************************************************/ -/******************************************************************************* -** -** Function BTM_SetLinkPolicy -** -** Description Create and send HCI "Write Policy Set" command -** -** Returns BTM_CMD_STARTED if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetLinkPolicy (BD_ADDR remote_bda, - UINT16 *settings); - -/******************************************************************************* -** -** Function BTM_SetDefaultLinkPolicy -** -** Description Set the default value for HCI "Write Policy Set" command -** to use when an ACL link is created. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_SetDefaultLinkPolicy (UINT16 settings); - - -/******************************************************************************* -** -** Function BTM_SetDefaultLinkSuperTout -** -** Description Set the default value for HCI "Write Link Supervision Timeout" -** command to use when an ACL link is created. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_SetDefaultLinkSuperTout (UINT16 timeout); - - -/******************************************************************************* -** -** Function BTM_SetLinkSuperTout -** -** Description Create and send HCI "Write Link Supervision Timeout" command -** -** Returns BTM_CMD_STARTED if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetLinkSuperTout (BD_ADDR remote_bda, - UINT16 timeout); -/******************************************************************************* -** -** Function BTM_GetLinkSuperTout -** -** Description Read the link supervision timeout value of the connection -** -** Returns status of the operation -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_GetLinkSuperTout (BD_ADDR remote_bda, - UINT16 *p_timeout); - -/******************************************************************************* -** -** Function BTM_IsAclConnectionUp -** -** Description This function is called to check if an ACL connection exists -** to a specific remote BD Address. -** -** Returns TRUE if connection is up, else FALSE. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_IsAclConnectionUp (BD_ADDR remote_bda, tBT_TRANSPORT transport); - - -/******************************************************************************* -** -** Function BTM_GetRole -** -** Description This function is called to get the role of the local device -** for the ACL connection with the specified remote device -** -** Returns BTM_SUCCESS if connection exists. -** BTM_UNKNOWN_ADDR if no active link with bd addr specified -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_GetRole (BD_ADDR remote_bd_addr, UINT8 *p_role); - - - -/******************************************************************************* -** -** Function BTM_SwitchRole -** -** Description This function is called to switch role between master and -** slave. If role is already set it will do nothing. If the -** command was initiated, the callback function is called upon -** completion. -** -** Returns BTM_SUCCESS if already in specified role. -** BTM_CMD_STARTED if command issued to controller. -** BTM_NO_RESOURCES if couldn't allocate memory to issue command -** BTM_UNKNOWN_ADDR if no active link with bd addr specified -** BTM_MODE_UNSUPPORTED if local device does not support role switching -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SwitchRole (BD_ADDR remote_bd_addr, - UINT8 new_role, - tBTM_CMPL_CB *p_cb); - -/******************************************************************************* -** -** Function BTM_ReadRSSI -** -** Description This function is called to read the link policy settings. -** The address of link policy results are returned in the callback. -** (tBTM_RSSI_RESULTS) -** -** Returns BTM_CMD_STARTED if command issued to controller. -** BTM_NO_RESOURCES if couldn't allocate memory to issue command -** BTM_UNKNOWN_ADDR if no active link with bd addr specified -** BTM_BUSY if command is already in progress -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadRSSI (BD_ADDR remote_bda, tBTM_CMPL_CB *p_cb); - - -/******************************************************************************* -** -** Function BTM_ReadTxPower -** -** Description This function is called to read the current connection -** TX power of the connection. The TX power level results -** are returned in the callback. -** (tBTM_RSSI_RESULTS) -** -** Returns BTM_CMD_STARTED if command issued to controller. -** BTM_NO_RESOURCES if couldn't allocate memory to issue command -** BTM_UNKNOWN_ADDR if no active link with bd addr specified -** BTM_BUSY if command is already in progress -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadTxPower (BD_ADDR remote_bda, - tBT_TRANSPORT transport, tBTM_CMPL_CB *p_cb); - -tBTM_STATUS BTM_BleReadAdvTxPower(tBTM_CMPL_CB *p_cb); - -void BTM_BleGetWhiteListSize(uint16_t *length); - - -/******************************************************************************* -** -** Function BTM_ReadLinkQuality -** -** Description This function is called to read the link quality. -** The value of the link quality is returned in the callback. -** (tBTM_LINK_QUALITY_RESULTS) -** -** Returns BTM_CMD_STARTED if command issued to controller. -** BTM_NO_RESOURCES if couldn't allocate memory to issue command -** BTM_UNKNOWN_ADDR if no active link with bd addr specified -** BTM_BUSY if command is already in progress -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadLinkQuality (BD_ADDR remote_bda, tBTM_CMPL_CB *p_cb); - -/******************************************************************************* -** -** Function BTM_RegBusyLevelNotif -** -** Description This function is called to register a callback to receive -** busy level change events. -** -** Returns BTM_SUCCESS if successfully registered, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_RegBusyLevelNotif (tBTM_BL_CHANGE_CB *p_cb, UINT8 *p_level, - tBTM_BL_EVENT_MASK evt_mask); - -/******************************************************************************* -** -** Function BTM_AclRegisterForChanges -** -** Description This function is called to register a callback to receive -** ACL database change events, i.e. new connection or removed. -** -** Returns BTM_SUCCESS if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_AclRegisterForChanges (tBTM_ACL_DB_CHANGE_CB *p_cb); - -/******************************************************************************* -** -** Function BTM_GetNumAclLinks -** -** Description This function is called to count the number of -** ACL links that are active. -** -** Returns UINT16 Number of active ACL links -** -*******************************************************************************/ -//extern -UINT16 BTM_GetNumAclLinks (void); - -/******************************************************************************* -** -** Function BTM_SetQoS -** -** Description This function is called to setup QoS -** -** Returns BTM_CMD_STARTED if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetQoS(BD_ADDR bd, FLOW_SPEC *p_flow, - tBTM_CMPL_CB *p_cb); - - -/***************************************************************************** -** (e)SCO CHANNEL MANAGEMENT FUNCTIONS -*****************************************************************************/ -/******************************************************************************* -** -** Function BTM_CreateSco -** -** Description This function is called to create an SCO connection. If the -** "is_orig" flag is TRUE, the connection will be originated, -** otherwise BTM will wait for the other side to connect. -** -** Returns BTM_UNKNOWN_ADDR if the ACL connection is not up -** BTM_BUSY if another SCO being set up to -** the same BD address -** BTM_NO_RESOURCES if the max SCO limit has been reached -** BTM_CMD_STARTED if the connection establishment is started. -** In this case, "*p_sco_inx" is filled in -** with the sco index used for the connection. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_CreateSco (BD_ADDR remote_bda, BOOLEAN is_orig, - UINT16 pkt_types, UINT16 *p_sco_inx, - tBTM_SCO_CB *p_conn_cb, - tBTM_SCO_CB *p_disc_cb); - - -/******************************************************************************* -** -** Function BTM_RemoveSco -** -** Description This function is called to remove a specific SCO connection. -** -** Returns BTM_CMD_STARTED if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_RemoveSco (UINT16 sco_inx); - - -/******************************************************************************* -** -** Function BTM_SetScoPacketTypes -** -** Description This function is called to set the packet types used for -** a specific SCO connection, -** -** Parameters pkt_types - One or more of the following -** BTM_SCO_PKT_TYPES_MASK_HV1 -** BTM_SCO_PKT_TYPES_MASK_HV2 -** BTM_SCO_PKT_TYPES_MASK_HV3 -** BTM_SCO_PKT_TYPES_MASK_EV3 -** BTM_SCO_PKT_TYPES_MASK_EV4 -** BTM_SCO_PKT_TYPES_MASK_EV5 -** -** BTM_SCO_LINK_ALL_MASK - enables all supported types -** -** Returns BTM_CMD_STARTED if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetScoPacketTypes (UINT16 sco_inx, UINT16 pkt_types); - - -/******************************************************************************* -** -** Function BTM_ReadScoPacketTypes -** -** Description This function is read the packet types used for a specific -** SCO connection. -** -** Returns One or more of the following (bitmask) -** BTM_SCO_PKT_TYPES_MASK_HV1 -** BTM_SCO_PKT_TYPES_MASK_HV2 -** BTM_SCO_PKT_TYPES_MASK_HV3 -** BTM_SCO_PKT_TYPES_MASK_EV3 -** BTM_SCO_PKT_TYPES_MASK_EV4 -** BTM_SCO_PKT_TYPES_MASK_EV5 -** -** Returns packet types supported for the connection -** -*******************************************************************************/ -//extern -UINT16 BTM_ReadScoPacketTypes (UINT16 sco_inx); - - -/******************************************************************************* -** -** Function BTM_ReadDeviceScoPacketTypes -** -** Description This function is read the SCO packet types that -** the device supports. -** -** Returns packet types supported by the device. -** -*******************************************************************************/ -//extern -UINT16 BTM_ReadDeviceScoPacketTypes (void); - - -/******************************************************************************* -** -** Function BTM_ReadScoHandle -** -** Description This function is used to read the HCI handle used for a specific -** SCO connection, -** -** Returns handle for the connection, or 0xFFFF if invalid SCO index. -** -*******************************************************************************/ -//extern -UINT16 BTM_ReadScoHandle (UINT16 sco_inx); - - -/******************************************************************************* -** -** Function BTM_ReadScoBdAddr -** -** Description This function is read the remote BD Address for a specific -** SCO connection, -** -** Returns pointer to BD address or NULL if not known -** -*******************************************************************************/ -//extern -UINT8 *BTM_ReadScoBdAddr (UINT16 sco_inx); - - -/******************************************************************************* -** -** Function BTM_ReadScoDiscReason -** -** Description This function is returns the reason why an (e)SCO connection -** has been removed. It contains the value until read, or until -** another (e)SCO connection has disconnected. -** -** Returns HCI reason or BTM_INVALID_SCO_DISC_REASON if not set. -** -*******************************************************************************/ -//extern -UINT16 BTM_ReadScoDiscReason (void); - - -/******************************************************************************* -** -** Function BTM_SetEScoMode -** -** Description This function sets up the negotiated parameters for SCO or -** eSCO, and sets as the default mode used for calls to -** BTM_CreateSco. It can be called only when there are no -** active (e)SCO links. -** -** Returns BTM_SUCCESS if the successful. -** BTM_BUSY if there are one or more active (e)SCO links. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetEScoMode (tBTM_SCO_TYPE sco_mode, - tBTM_ESCO_PARAMS *p_parms); - -/******************************************************************************* -** -** Function BTM_SetWBSCodec -** -** Description This function sends command to the controller to setup -** WBS codec for the upcoming eSCO connection. -** -** Returns BTM_SUCCESS. -** -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetWBSCodec (tBTM_SCO_CODEC_TYPE codec_type); - -/******************************************************************************* -** -** Function BTM_RegForEScoEvts -** -** Description This function registers a SCO event callback with the -** specified instance. It should be used to received -** connection indication events and change of link parameter -** events. -** -** Returns BTM_SUCCESS if the successful. -** BTM_ILLEGAL_VALUE if there is an illegal sco_inx -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_RegForEScoEvts (UINT16 sco_inx, - tBTM_ESCO_CBACK *p_esco_cback); - -/******************************************************************************* -** -** Function BTM_ReadEScoLinkParms -** -** Description This function returns the current eSCO link parameters for -** the specified handle. This can be called anytime a connection -** is active, but is typically called after receiving the SCO -** opened callback. -** -** Note: If called over a 1.1 controller, only the packet types -** field has meaning. -** Note: If the upper layer doesn't know the current sco index, -** BTM_FIRST_ACTIVE_SCO_INDEX can be used as the first parameter to -** find the first active SCO index -** -** Returns BTM_SUCCESS if returned data is valid connection. -** BTM_ILLEGAL_VALUE if no connection for specified sco_inx. -** BTM_MODE_UNSUPPORTED if local controller does not support -** 1.2 specification. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadEScoLinkParms (UINT16 sco_inx, - tBTM_ESCO_DATA *p_parms); - -/******************************************************************************* -** -** Function BTM_ChangeEScoLinkParms -** -** Description This function requests renegotiation of the parameters on -** the current eSCO Link. If any of the changes are accepted -** by the controllers, the BTM_ESCO_CHG_EVT event is sent in -** the tBTM_ESCO_CBACK function with the current settings of -** the link. The callback is registered through the call to -** BTM_SetEScoMode. -** -** -** Returns BTM_CMD_STARTED if command is successfully initiated. -** BTM_ILLEGAL_VALUE if no connection for specified sco_inx. -** BTM_NO_RESOURCES - not enough resources to initiate command. -** BTM_MODE_UNSUPPORTED if local controller does not support -** 1.2 specification. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ChangeEScoLinkParms (UINT16 sco_inx, - tBTM_CHG_ESCO_PARAMS *p_parms); - -/******************************************************************************* -** -** Function BTM_EScoConnRsp -** -** Description This function is called upon receipt of an (e)SCO connection -** request event (BTM_ESCO_CONN_REQ_EVT) to accept or reject -** the request. Parameters used to negotiate eSCO links. -** If p_parms is NULL, then values set through BTM_SetEScoMode -** are used. -** If the link type of the incoming request is SCO, then only -** the tx_bw, max_latency, content format, and packet_types are -** valid. The hci_status parameter should be -** ([0x0] to accept, [0x0d..0x0f] to reject) -** -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_EScoConnRsp (UINT16 sco_inx, UINT8 hci_status, - tBTM_ESCO_PARAMS *p_parms); - -/******************************************************************************* -** -** Function BTM_GetNumScoLinks -** -** Description This function returns the number of active SCO links. -** -** Returns UINT8 -** -*******************************************************************************/ -//extern -UINT8 BTM_GetNumScoLinks (void); - -/***************************************************************************** -** SECURITY MANAGEMENT FUNCTIONS -*****************************************************************************/ -/******************************************************************************* -** -** Function BTM_SecRegister -** -** Description Application manager calls this function to register for -** security services. There can be one and only one application -** saving link keys. BTM allows only first registration. -** -** Returns TRUE if registered OK, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SecRegister (tBTM_APPL_INFO *p_cb_info); - -/******************************************************************************* -** -** Function BTM_SecRegisterLinkKeyNotificationCallback -** -** Description Profiles can register to be notified when a new Link Key -** is generated per connection. -** -** Returns TRUE if registered OK, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SecRegisterLinkKeyNotificationCallback( - tBTM_LINK_KEY_CALLBACK *p_callback); - -/******************************************************************************* -** -** Function BTM_SecAddRmtNameNotifyCallback -** -** Description Profiles can register to be notified when name of the -** remote device is resolved (up to BTM_SEC_MAX_RMT_NAME_CALLBACKS). -** -** Returns TRUE if registered OK, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SecAddRmtNameNotifyCallback (tBTM_RMT_NAME_CALLBACK *p_callback); - - -/******************************************************************************* -** -** Function BTM_SecDeleteRmtNameNotifyCallback -** -** Description A profile can deregister notification when a new Link Key -** is generated per connection. -** -** Returns TRUE if OK, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SecDeleteRmtNameNotifyCallback (tBTM_RMT_NAME_CALLBACK *p_callback); - -/******************************************************************************* -** -** Function BTM_GetSecurityFlags -** -** Description Get security flags for the device -** -** Returns BOOLEAN TRUE or FALSE is device found -** -*******************************************************************************/ -//extern -BOOLEAN BTM_GetSecurityFlags (BD_ADDR bd_addr, UINT8 *p_sec_flags); - -/******************************************************************************* -** -** Function BTM_GetSecurityFlagsByTransport -** -** Description Get security flags for the device on a particular transport -** -** Parameters bd_addr: BD address of remote device -** p_sec_flags : Out parameter to be filled with security flags for the connection -** transport : Physical transport of the connection (BR/EDR or LE) -** -** Returns BOOLEAN TRUE or FALSE is device found -** -*******************************************************************************/ -//extern -BOOLEAN BTM_GetSecurityFlagsByTransport (BD_ADDR bd_addr, - UINT8 *p_sec_flags, tBT_TRANSPORT transport); - -/******************************************************************************* -** -** Function BTM_ReadTrustedMask -** -** Description Get trusted mask for the device -** -** Returns NULL, if the device record is not found. -** otherwise, the trusted mask -** -*******************************************************************************/ -//extern -UINT32 *BTM_ReadTrustedMask (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTM_SetPinType -** -** Description Set PIN type for the device. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_SetPinType (UINT8 pin_type, PIN_CODE pin_code, UINT8 pin_code_len); - - -/******************************************************************************* -** -** Function BTM_SetPairableMode -** -** Description Enable or disable pairing -** -** Parameters allow_pairing - (TRUE or FALSE) whether or not the device -** allows pairing. -** connect_only_paired - (TRUE or FALSE) whether or not to -** only allow paired devices to connect. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_SetPairableMode (BOOLEAN allow_pairing, BOOLEAN connect_only_paired); - -/******************************************************************************* -** -** Function BTM_SetSecureConnectionsOnly -** -** Description Enable or disable default treatment for Mode 4 Level 0 services -** -** Parameter secure_connections_only_mode - (TRUE or FALSE) -** TRUE means that the device should treat Mode 4 Level 0 services as -** services of other levels. -** FALSE means that the device should provide default treatment for -** Mode 4 Level 0 services. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_SetSecureConnectionsOnly (BOOLEAN secure_connections_only_mode); - -/******************************************************************************* -** -** Function BTM_SetSecurityLevel -** -** Description Register service security level with Security Manager. Each -** service must register its requirements regardless of the -** security level that is used. This API is called once for originators -** nad again for acceptors of connections. -** -** Returns TRUE if registered OK, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SetSecurityLevel (BOOLEAN is_originator, char *p_name, - UINT8 service_id, UINT16 sec_level, - UINT16 psm, UINT32 mx_proto_id, - UINT32 mx_chan_id); - -/******************************************************************************* -** -** Function BTM_SetOutService -** -** Description This function is called to set the service for -** outgoing connection. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_SetOutService(BD_ADDR bd_addr, UINT8 service_id, UINT32 mx_chan_id); - -/******************************************************************************* -** -** Function BTM_SecClrService -** -** Description Removes specified service record(s) from the security database. -** All service records with the specified name are removed. -** Typically used only by devices with limited RAM so that it can -** reuse an old security service record. -** records (except SDP). -** -** Returns Number of records that were freed. -** -*******************************************************************************/ -//extern -UINT8 BTM_SecClrService (UINT8 service_id); - -/******************************************************************************* -** -** Function BTM_SecAddDevice -** -** Description Add/modify device. This function will be normally called -** during host startup to restore all required information -** stored in the NVRAM. -** dev_class, bd_name, link_key, and features are NULL if unknown -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SecAddDevice (BD_ADDR bd_addr, DEV_CLASS dev_class, - BD_NAME bd_name, UINT8 *features, - UINT32 trusted_mask[], LINK_KEY link_key, - UINT8 key_type, tBTM_IO_CAP io_cap, UINT8 pin_length); - - -/******************************************************************************* -** -** Function BTM_SecDeleteDevice -** -** Description Free resources associated with the device. -** -** Returns TRUE if rmoved OK, FALSE if not found -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SecDeleteDevice (BD_ADDR bd_addr); - - -/******************************************************************************* -** -** Function BTM_SecGetDeviceLinkKey -** -** Description This function is called to obtain link key for the device -** it returns BTM_SUCCESS if link key is available, or -** BTM_UNKNOWN_ADDR if Security Manager does not know about -** the device or device record does not contain link key info -** -** Returns BTM_SUCCESS if successful, otherwise error code -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SecGetDeviceLinkKey (BD_ADDR bd_addr, - LINK_KEY link_key); - - -/******************************************************************************* -** -** Function BTM_SecGetDeviceLinkKeyType -** -** Description This function is called to obtain link key type for the -** device. -** it returns BTM_SUCCESS if link key is available, or -** BTM_UNKNOWN_ADDR if Security Manager does not know about -** the device or device record does not contain link key info -** -** Returns BTM_LKEY_TYPE_IGNORE if link key is unknown, link type -** otherwise. -** -*******************************************************************************/ -//extern -tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType (BD_ADDR bd_addr); - - -/******************************************************************************* -** -** Function BTM_PINCodeReply -** -** Description This function is called after Security Manager submitted -** PIN code request to the UI. -** -** Parameters: bd_addr - Address of the device for which PIN was requested -** res - result of the operation BTM_SUCCESS if success -** pin_len - length in bytes of the PIN Code -** p_pin - pointer to array with the PIN Code -** trusted_mask - bitwise OR of trusted services (array of UINT32) -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len, - UINT8 *p_pin, UINT32 trusted_mask[]); - - -/******************************************************************************* -** -** Function BTM_SecBond -** -** Description This function is called to perform bonding with peer device. -** -** Parameters: bd_addr - Address of the device to bond -** pin_len - length in bytes of the PIN Code -** p_pin - pointer to array with the PIN Code -** trusted_mask - bitwise OR of trusted services (array of UINT32) - -** Returns BTM_CMD_STARTED if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SecBond (BD_ADDR bd_addr, - UINT8 pin_len, UINT8 *p_pin, - UINT32 trusted_mask[]); - -/******************************************************************************* -** -** Function BTM_SecBondByTransport -** -** Description This function is called to perform bonding by designated transport -** -** Parameters: bd_addr - Address of the device to bond -** pin_len - length in bytes of the PIN Code -** p_pin - pointer to array with the PIN Code -** trusted_mask - bitwise OR of trusted services (array of UINT32) -** transport : Physical transport to use for bonding (BR/EDR or LE) -** -** Returns BTM_CMD_STARTED if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SecBondByTransport (BD_ADDR bd_addr, - tBT_TRANSPORT transport, - UINT8 pin_len, UINT8 *p_pin, - UINT32 trusted_mask[]); - -/******************************************************************************* -** -** Function BTM_SecBondCancel -** -** Description This function is called to cancel ongoing bonding process -** with peer device. -** -** Returns BTM_CMD_STARTED if successfully initiated, otherwise error -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SecBondCancel (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTM_SetEncryption -** -** Description This function is called to ensure that connection is -** encrypted. Should be called only on an open connection. -** Typically only needed for connections that first want to -** bring up unencrypted links, then later encrypt them. -** -** Parameters: bd_addr - Address of the peer device -** p_callback - Pointer to callback function called if -** this function returns PENDING after required -** procedures are completed. Can be set to NULL -** if status is not desired. -** p_ref_data - pointer to any data the caller wishes to receive -** in the callback function upon completion. -* can be set to NULL if not used. -** -** Returns BTM_SUCCESS - already encrypted -** BTM_PENDING - command will be returned in the callback -** BTM_WRONG_MODE- connection not up. -** BTM_BUSY - security procedures are currently active -** BTM_MODE_UNSUPPORTED - if security manager not linked in. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetEncryption (BD_ADDR bd_addr, tBT_TRANSPORT transport, - tBTM_SEC_CBACK *p_callback, void *p_ref_data); - -/******************************************************************************* -** -** Function BTM_ConfirmReqReply -** -** Description This function is called to confirm the numeric value for -** Simple Pairing in response to BTM_SP_CFM_REQ_EVT -** -** Parameters: res - result of the operation BTM_SUCCESS if success -** bd_addr - Address of the peer device -** -*******************************************************************************/ -//extern -void BTM_ConfirmReqReply(tBTM_STATUS res, BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTM_PasskeyReqReply -** -** Description This function is called to provide the passkey for -** Simple Pairing in response to BTM_SP_KEY_REQ_EVT -** -** Parameters: res - result of the operation BTM_SUCCESS if success -** bd_addr - Address of the peer device -** passkey - numeric value in the range of 0 - 999999(0xF423F). -** -*******************************************************************************/ -//extern -void BTM_PasskeyReqReply(tBTM_STATUS res, BD_ADDR bd_addr, UINT32 passkey); - -/******************************************************************************* -** -** Function BTM_SendKeypressNotif -** -** Description This function is used during the passkey entry model -** by a device with KeyboardOnly IO capabilities -** (very likely to be a HID Device). -** It is called by a HID Device to inform the remote device when -** a key has been entered or erased. -** -** Parameters: bd_addr - Address of the peer device -** type - notification type -** -*******************************************************************************/ -//extern -void BTM_SendKeypressNotif(BD_ADDR bd_addr, tBTM_SP_KEY_TYPE type); - -/******************************************************************************* -** -** Function BTM_IoCapRsp -** -** Description This function is called in response to BTM_SP_IO_REQ_EVT -** When the event data io_req.oob_data is set to BTM_OOB_UNKNOWN -** by the tBTM_SP_CALLBACK implementation, this function is -** called to provide the actual response -** -** Parameters: bd_addr - Address of the peer device -** io_cap - The IO capability of local device. -** oob - BTM_OOB_NONE or BTM_OOB_PRESENT. -** auth_req- MITM protection required or not. -** -*******************************************************************************/ -//extern -void BTM_IoCapRsp(BD_ADDR bd_addr, tBTM_IO_CAP io_cap, - tBTM_OOB_DATA oob, tBTM_AUTH_REQ auth_req); - -/******************************************************************************* -** -** Function BTM_ReadLocalOobData -** -** Description This function is called to read the local OOB data from -** LM -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadLocalOobData(void); - -/******************************************************************************* -** -** Function BTM_RemoteOobDataReply -** -** Description This function is called to provide the remote OOB data for -** Simple Pairing in response to BTM_SP_RMT_OOB_EVT -** -** Parameters: bd_addr - Address of the peer device -** c - simple pairing Hash C. -** r - simple pairing Randomizer C. -** -*******************************************************************************/ -//extern -void BTM_RemoteOobDataReply(tBTM_STATUS res, BD_ADDR bd_addr, - BT_OCTET16 c, BT_OCTET16 r); - -/******************************************************************************* -** -** Function BTM_BuildOobData -** -** Description This function is called to build the OOB data payload to -** be sent over OOB (non-Bluetooth) link -** -** Parameters: p_data - the location for OOB data -** max_len - p_data size. -** c - simple pairing Hash C. -** r - simple pairing Randomizer C. -** name_len- 0, local device name would not be included. -** otherwise, the local device name is included for -** up to this specified length -** -** Returns Number of bytes in p_data. -** -*******************************************************************************/ -//extern -UINT16 BTM_BuildOobData(UINT8 *p_data, UINT16 max_len, BT_OCTET16 c, - BT_OCTET16 r, UINT8 name_len); - -/******************************************************************************* -** -** Function BTM_BothEndsSupportSecureConnections -** -** Description This function is called to check if both the local device and the peer device -** specified by bd_addr support BR/EDR Secure Connections. -** -** Parameters: bd_addr - address of the peer -** -** Returns TRUE if BR/EDR Secure Connections are supported by both local -** and the remote device. -** else FALSE. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BothEndsSupportSecureConnections(BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTM_PeerSupportsSecureConnections -** -** Description This function is called to check if the peer supports -** BR/EDR Secure Connections. -** -** Parameters: bd_addr - address of the peer -** -** Returns TRUE if BR/EDR Secure Connections are supported by the peer, -** else FALSE. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_PeerSupportsSecureConnections(BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTM_ReadOobData -** -** Description This function is called to parse the OOB data payload -** received over OOB (non-Bluetooth) link -** -** Parameters: p_data - the location for OOB data -** eir_tag - The associated EIR tag to read the data. -** *p_len(output) - the length of the data with the given tag. -** -** Returns the beginning of the data with the given tag. -** NULL, if the tag is not found. -** -*******************************************************************************/ -//extern -UINT8 *BTM_ReadOobData(UINT8 *p_data, UINT8 eir_tag, UINT8 *p_len); - -/******************************************************************************* -** -** Function BTM_SecReadDevName -** -** Description Looks for the device name in the security database for the -** specified BD address. -** -** Returns Pointer to the name or NULL -** -*******************************************************************************/ -//extern -char *BTM_SecReadDevName (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTM_SecClearSecurityFlags -** -** Description Reset the security flags (mark as not-paired) for a given -** remove device. -** -*******************************************************************************/ -extern void BTM_SecClearSecurityFlags (BD_ADDR bd_addr); - - - -/***************************************************************************** -** POWER MANAGEMENT FUNCTIONS -*****************************************************************************/ -/******************************************************************************* -** -** Function BTM_PmRegister -** -** Description register or deregister with power manager -** -** Returns BTM_SUCCESS if successful, -** BTM_NO_RESOURCES if no room to hold registration -** BTM_ILLEGAL_VALUE -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_PmRegister (UINT8 mask, UINT8 *p_pm_id, - tBTM_PM_STATUS_CBACK *p_cb); - - -/******************************************************************************* -** -** Function BTM_SetPowerMode -** -** Description store the mode in control block or -** alter ACL connection behavior. -** -** Returns BTM_SUCCESS if successful, -** BTM_UNKNOWN_ADDR if bd addr is not active or bad -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetPowerMode (UINT8 pm_id, BD_ADDR remote_bda, - tBTM_PM_PWR_MD *p_mode); - - -/******************************************************************************* -** -** Function BTM_ReadPowerMode -** -** Description This returns the current mode for a specific -** ACL connection. -** -** Input Param remote_bda - device address of desired ACL connection -** -** Output Param p_mode - address where the current mode is copied into. -** BTM_ACL_MODE_NORMAL -** BTM_ACL_MODE_HOLD -** BTM_ACL_MODE_SNIFF -** BTM_ACL_MODE_PARK -** (valid only if return code is BTM_SUCCESS) -** -** Returns BTM_SUCCESS if successful, -** BTM_UNKNOWN_ADDR if bd addr is not active or bad -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ReadPowerMode (BD_ADDR remote_bda, - tBTM_PM_MODE *p_mode); - -/******************************************************************************* -** -** Function BTM_SetSsrParams -** -** Description This sends the given SSR parameters for the given ACL -** connection if it is in ACTIVE mode. -** -** Input Param remote_bda - device address of desired ACL connection -** max_lat - maximum latency (in 0.625ms)(0-0xFFFE) -** min_rmt_to - minimum remote timeout -** min_loc_to - minimum local timeout -** -** -** Returns BTM_SUCCESS if the HCI command is issued successful, -** BTM_UNKNOWN_ADDR if bd addr is not active or bad -** BTM_CMD_STORED if the command is stored -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetSsrParams (BD_ADDR remote_bda, UINT16 max_lat, - UINT16 min_rmt_to, UINT16 min_loc_to); - -/******************************************************************************* -** -** Function BTM_GetHCIConnHandle -** -** Description This function is called to get the handle for an ACL connection -** to a specific remote BD Address. -** -** Returns the handle of the connection, or 0xFFFF if none. -** -*******************************************************************************/ -//extern -UINT16 BTM_GetHCIConnHandle (BD_ADDR remote_bda, tBT_TRANSPORT transport); - -/******************************************************************************* -** -** Function BTM_DeleteStoredLinkKey -** -** Description This function is called to delete link key for the specified -** device addresses from the NVRAM storage attached to the Bluetooth -** controller. -** -** Parameters: bd_addr - Addresses of the devices -** p_cb - Call back function to be called to return -** the results -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_DeleteStoredLinkKey(BD_ADDR bd_addr, tBTM_CMPL_CB *p_cb); - -/******************************************************************************* -** -** Function BTM_WriteEIR -** -** Description This function is called to write EIR data to controller. -** -** Parameters p_buff - allocated HCI command buffer including extended -** inquriry response -** -** Returns BTM_SUCCESS - if successful -** BTM_MODE_UNSUPPORTED - if local device cannot support it -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_WriteEIR( BT_HDR *p_buff ); - -/******************************************************************************* -** -** Function BTM_CheckEirData -** -** Description This function is called to get EIR data from significant part. -** -** Parameters p_eir - pointer of EIR significant part -** type - finding EIR data type -** p_length - return the length of EIR data -** -** Returns pointer of EIR data -** -*******************************************************************************/ -//extern -UINT8 *BTM_CheckEirData( UINT8 *p_eir, UINT8 type, UINT8 *p_length ); - -/******************************************************************************* -** -** Function BTM_HasEirService -** -** Description This function is called to know if UUID in bit map of UUID. -** -** Parameters p_eir_uuid - bit map of UUID list -** uuid16 - UUID 16-bit -** -** Returns TRUE - if found -** FALSE - if not found -** -*******************************************************************************/ -//extern -BOOLEAN BTM_HasEirService( UINT32 *p_eir_uuid, UINT16 uuid16 ); - -/******************************************************************************* -** -** Function BTM_HasInquiryEirService -** -** Description This function is called to know if UUID in bit map of UUID list. -** -** Parameters p_results - inquiry results -** uuid16 - UUID 16-bit -** -** Returns BTM_EIR_FOUND - if found -** BTM_EIR_NOT_FOUND - if not found and it is complete list -** BTM_EIR_UNKNOWN - if not found and it is not complete list -** -*******************************************************************************/ -//extern -tBTM_EIR_SEARCH_RESULT BTM_HasInquiryEirService( tBTM_INQ_RESULTS *p_results, - UINT16 uuid16 ); - -/******************************************************************************* -** -** Function BTM_AddEirService -** -** Description This function is called to add a service in bit map of UUID list. -** -** Parameters p_eir_uuid - bit mask of UUID list for EIR -** uuid16 - UUID 16-bit -** -** Returns None -** -*******************************************************************************/ -//extern -void BTM_AddEirService( UINT32 *p_eir_uuid, UINT16 uuid16 ); - -/******************************************************************************* -** -** Function BTM_RemoveEirService -** -** Description This function is called to remove a service in bit map of UUID list. -** -** Parameters p_eir_uuid - bit mask of UUID list for EIR -** uuid16 - UUID 16-bit -** -** Returns None -** -*******************************************************************************/ -//extern -void BTM_RemoveEirService( UINT32 *p_eir_uuid, UINT16 uuid16 ); - -/******************************************************************************* -** -** Function BTM_GetEirSupportedServices -** -** Description This function is called to get UUID list from bit map of UUID list. -** -** Parameters p_eir_uuid - bit mask of UUID list for EIR -** p - reference of current pointer of EIR -** max_num_uuid16 - max number of UUID can be written in EIR -** num_uuid16 - number of UUID have been written in EIR -** -** Returns BTM_EIR_MORE_16BITS_UUID_TYPE, if it has more than max -** BTM_EIR_COMPLETE_16BITS_UUID_TYPE, otherwise -** -*******************************************************************************/ -//extern -UINT8 BTM_GetEirSupportedServices( UINT32 *p_eir_uuid, UINT8 **p, - UINT8 max_num_uuid16, UINT8 *p_num_uuid16); - -/******************************************************************************* -** -** Function BTM_GetEirUuidList -** -** Description This function parses EIR and returns UUID list. -** -** Parameters p_eir - EIR -** uuid_size - LEN_UUID_16, LEN_UUID_32, LEN_UUID_128 -** p_num_uuid - return number of UUID in found list -** p_uuid_list - return UUID 16-bit list -** max_num_uuid - maximum number of UUID to be returned -** -** Returns 0 - if not found -** BTM_EIR_COMPLETE_16BITS_UUID_TYPE -** BTM_EIR_MORE_16BITS_UUID_TYPE -** BTM_EIR_COMPLETE_32BITS_UUID_TYPE -** BTM_EIR_MORE_32BITS_UUID_TYPE -** BTM_EIR_COMPLETE_128BITS_UUID_TYPE -** BTM_EIR_MORE_128BITS_UUID_TYPE -** -*******************************************************************************/ -//extern -UINT8 BTM_GetEirUuidList( UINT8 *p_eir, UINT8 uuid_size, UINT8 *p_num_uuid, - UINT8 *p_uuid_list, UINT8 max_num_uuid); - -/***************************************************************************** -** SCO OVER HCI -*****************************************************************************/ -/******************************************************************************* -** -** Function BTM_ConfigScoPath -** -** Description This function enable/disable SCO over HCI and registers SCO -** data callback if SCO over HCI is enabled. -** -** Parameter path: SCO or HCI -** p_sco_data_cb: callback function or SCO data if path is set -** to transport. -** p_pcm_param: pointer to the PCM interface parameter. If a NULL -** pointer is used, PCM parameter maintained in -** the control block will be used; otherwise update -** control block value. -** err_data_rpt: Lisbon feature to enable the erronous data report -** or not. -** -** Returns BTM_SUCCESS if the successful. -** BTM_NO_RESOURCES: no rsource to start the command. -** BTM_ILLEGAL_VALUE: invalid callback function pointer. -** BTM_CMD_STARTED :Command sent. Waiting for command cmpl event. -** -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_ConfigScoPath (tBTM_SCO_ROUTE_TYPE path, - tBTM_SCO_DATA_CB *p_sco_data_cb, - tBTM_SCO_PCM_PARAM *p_pcm_param, - BOOLEAN err_data_rpt); - -/******************************************************************************* -** -** Function BTM_WriteScoData -** -** Description This function write SCO data to a specified instance. The data -** to be written p_buf needs to carry an offset of -** HCI_SCO_PREAMBLE_SIZE bytes, and the data length can not -** exceed BTM_SCO_DATA_SIZE_MAX bytes, whose default value is set -** to 60 and is configurable. Data longer than the maximum bytes -** will be truncated. -** -** Returns BTM_SUCCESS: data write is successful -** BTM_ILLEGAL_VALUE: SCO data contains illegal offset value. -** BTM_SCO_BAD_LENGTH: SCO data length exceeds the max SCO packet -** size. -** BTM_NO_RESOURCES: no resources. -** BTM_UNKNOWN_ADDR: unknown SCO connection handle, or SCO is not -** routed via HCI. -** -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_WriteScoData (UINT16 sco_inx, BT_HDR *p_buf); - -/******************************************************************************* -** -** Function BTM_SetARCMode -** -** Description Send Audio Routing Control command. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_SetARCMode (UINT8 iface, UINT8 arc_mode, tBTM_VSC_CMPL_CB *p_arc_cb); - - -/******************************************************************************* -** -** Function BTM_PCM2Setup_Write -** -** Description Send PCM2_Setup write command. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_PCM2Setup_Write (BOOLEAN clk_master, tBTM_VSC_CMPL_CB *p_arc_cb); - - -/******************************************************************************* -** -** Function BTM_PM_ReadControllerState -** -** Description This function is called to obtain the controller state -** -** Returns Controller state (BTM_CONTRL_ACTIVE, BTM_CONTRL_SCAN, and BTM_CONTRL_IDLE) -** -*******************************************************************************/ -//extern -tBTM_CONTRL_STATE BTM_PM_ReadControllerState(void); -/* -#ifdef __cplusplus -} -#endif -*/ - -#endif /* BTM_API_H */ diff --git a/tools/sdk/include/bluedroid/btm_ble_api.h b/tools/sdk/include/bluedroid/btm_ble_api.h deleted file mode 100644 index 43de28b4fd4..00000000000 --- a/tools/sdk/include/bluedroid/btm_ble_api.h +++ /dev/null @@ -1,2019 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains the Bluetooth Manager (BTM) API function external - * definitions. - * - ******************************************************************************/ -#ifndef BTM_BLE_API_H -#define BTM_BLE_API_H - -#include "bt_defs.h" -#include "btm_api.h" -#include "bt_common_types.h" - -#define CHANNEL_MAP_LEN 5 -typedef UINT8 tBTM_BLE_CHNL_MAP[CHANNEL_MAP_LEN]; - -/* 0x00-0x04 only used for set advertising parameter command */ -#define BTM_BLE_CONNECT_EVT 0x00 /* 0x00-0x04 only used for set advertising - parameter command */ -#define BTM_BLE_CONNECT_DIR_EVT 0x01 /* Connectable directed advertising */ -#define BTM_BLE_DISCOVER_EVT 0x02 /* Scannable undirected advertising */ -#define BTM_BLE_NON_CONNECT_EVT 0x03 /* Non connectable undirected advertising */ -#define BTM_BLE_CONNECT_LO_DUTY_DIR_EVT 0x04 /* Connectable low duty - cycle directed advertising */ -/* 0x00 - 0x05 can be received on adv event type */ -#define BTM_BLE_SCAN_RSP_EVT 0x04 -#define BTM_BLE_SCAN_REQ_EVT 0x05 -#define BTM_BLE_UNKNOWN_EVT 0xff - -#define BTM_BLE_UNKNOWN_EVT 0xff - -typedef UINT8 tBTM_BLE_EVT; -typedef UINT8 tBTM_BLE_CONN_MODE; - -typedef UINT32 tBTM_BLE_REF_VALUE; - -#define BTM_BLE_SCAN_MODE_PASS 0 -#define BTM_BLE_SCAN_MODE_ACTI 1 -#define BTM_BLE_SCAN_MODE_NONE 0xff -typedef UINT8 tBLE_SCAN_MODE; - -#define BTM_BLE_BATCH_SCAN_MODE_DISABLE 0 -#define BTM_BLE_BATCH_SCAN_MODE_PASS 1 -#define BTM_BLE_BATCH_SCAN_MODE_ACTI 2 -#define BTM_BLE_BATCH_SCAN_MODE_PASS_ACTI 3 - -typedef UINT8 tBTM_BLE_BATCH_SCAN_MODE; - -/* advertising channel map */ -#define BTM_BLE_ADV_CHNL_37 (0x01 << 0) -#define BTM_BLE_ADV_CHNL_38 (0x01 << 1) -#define BTM_BLE_ADV_CHNL_39 (0x01 << 2) -typedef UINT8 tBTM_BLE_ADV_CHNL_MAP; - -/*d efault advertising channel map */ -#ifndef BTM_BLE_DEFAULT_ADV_CHNL_MAP -#define BTM_BLE_DEFAULT_ADV_CHNL_MAP (BTM_BLE_ADV_CHNL_37| BTM_BLE_ADV_CHNL_38| BTM_BLE_ADV_CHNL_39) -#endif - -/* advertising filter policy */ -#define AP_SCAN_CONN_ALL 0x00 /* default */ -#define AP_SCAN_WL_CONN_ALL 0x01 -#define AP_SCAN_ALL_CONN_WL 0x02 -#define AP_SCAN_CONN_WL 0x03 -#define AP_SCAN_CONN_POLICY_MAX 0x04 -typedef UINT8 tBTM_BLE_AFP; - -/* default advertising filter policy */ -#ifndef BTM_BLE_DEFAULT_AFP -#define BTM_BLE_DEFAULT_AFP AP_SCAN_CONN_ALL -#endif - -/* scanning filter policy */ -#define SP_ADV_ALL 0x00 /* 0: accept adv packet from all, directed adv pkt not directed */ -/* to local device is ignored */ -#define SP_ADV_WL 0x01 /* 1: accept adv packet from device in white list, directed adv */ -/* packet not directed to local device is ignored */ -#define SP_ADV_ALL_RPA_DIR_ADV 0x02 /* 2: accept adv packet from all, directed adv pkt */ -/* not directed to me is ignored except direct adv with RPA */ -#define SP_ADV_WL_RPA_DIR_ADV 0x03 /* 3: accept adv packet from device in white list, directed */ -/* adv pkt not directed to me is ignored except direct adv */ -/* with RPA */ -typedef UINT8 tBTM_BLE_SFP; - -#ifndef BTM_BLE_DEFAULT_SFP -#define BTM_BLE_DEFAULT_SFP SP_ADV_ALL -#endif - -/* adv parameter boundary values */ -#define BTM_BLE_ADV_INT_MIN 0x0020 -#define BTM_BLE_ADV_INT_MAX 0x4000 - -/* Full scan boundary values */ -#define BTM_BLE_ADV_SCAN_FULL_MIN 0x00 -#define BTM_BLE_ADV_SCAN_FULL_MAX 0x64 - -/* Partial scan boundary values */ -#define BTM_BLE_ADV_SCAN_TRUNC_MIN BTM_BLE_ADV_SCAN_FULL_MIN -#define BTM_BLE_ADV_SCAN_TRUNC_MAX BTM_BLE_ADV_SCAN_FULL_MAX - -/* Threshold values */ -#define BTM_BLE_ADV_SCAN_THR_MIN BTM_BLE_ADV_SCAN_FULL_MIN -#define BTM_BLE_ADV_SCAN_THR_MAX BTM_BLE_ADV_SCAN_FULL_MAX - -/* connection parameter boundary values */ -#define BTM_BLE_SCAN_INT_MIN 0x0004 -#define BTM_BLE_SCAN_INT_MAX 0x4000 -#define BTM_BLE_SCAN_WIN_MIN 0x0004 -#define BTM_BLE_SCAN_WIN_MAX 0x4000 -#define BTM_BLE_EXT_SCAN_INT_MAX 0x00FFFFFF -#define BTM_BLE_EXT_SCAN_WIN_MAX 0xFFFF -#define BTM_BLE_CONN_INT_MIN 0x0006 -#define BTM_BLE_CONN_INT_MAX 0x0C80 -#define BTM_BLE_CONN_LATENCY_MAX 500 -#define BTM_BLE_CONN_SUP_TOUT_MIN 0x000A -#define BTM_BLE_CONN_SUP_TOUT_MAX 0x0C80 -#define BTM_BLE_CONN_PARAM_UNDEF 0xffff /* use this value when a specific value not to be overwritten */ -#define BTM_BLE_SCAN_PARAM_UNDEF 0xffffffff - -/* default connection parameters if not configured, use GAP recommend value for auto/selective connection */ -/* default scan interval */ -#ifndef BTM_BLE_SCAN_FAST_INT -#define BTM_BLE_SCAN_FAST_INT 96 /* 30 ~ 60 ms (use 60) = 96 *0.625 */ -#endif -/* default scan window for background connection, applicable for auto connection or selective conenction */ -#ifndef BTM_BLE_SCAN_FAST_WIN -#define BTM_BLE_SCAN_FAST_WIN 48 /* 30 ms = 48 *0.625 */ -#endif - -/* default scan paramter used in reduced power cycle (background scanning) */ -#ifndef BTM_BLE_SCAN_SLOW_INT_1 -#define BTM_BLE_SCAN_SLOW_INT_1 2048 /* 1.28 s = 2048 *0.625 */ -#endif -#ifndef BTM_BLE_SCAN_SLOW_WIN_1 -#define BTM_BLE_SCAN_SLOW_WIN_1 48 /* 30 ms = 48 *0.625 */ -#endif - -/* default scan paramter used in reduced power cycle (background scanning) */ -#ifndef BTM_BLE_SCAN_SLOW_INT_2 -#define BTM_BLE_SCAN_SLOW_INT_2 4096 /* 2.56 s = 4096 *0.625 */ -#endif -#ifndef BTM_BLE_SCAN_SLOW_WIN_2 -#define BTM_BLE_SCAN_SLOW_WIN_2 36 /* 22.5 ms = 36 *0.625 */ -#endif - -/* default connection interval min */ -#ifndef BTM_BLE_CONN_INT_MIN_DEF -#define BTM_BLE_CONN_INT_MIN_DEF 10 /* recommended min: 12.5 ms = 10 * 1.25 */ -#endif - -/* default connection interval max */ -#ifndef BTM_BLE_CONN_INT_MAX_DEF -#define BTM_BLE_CONN_INT_MAX_DEF 12 /* recommended max: 15 ms = 12 * 1.25 */ -#endif - -/* default slave latency */ -#ifndef BTM_BLE_CONN_SLAVE_LATENCY_DEF -#define BTM_BLE_CONN_SLAVE_LATENCY_DEF 0 /* 0 */ -#endif - -/* default supervision timeout */ -#ifndef BTM_BLE_CONN_TIMEOUT_DEF -#define BTM_BLE_CONN_TIMEOUT_DEF 600 -#endif - -/* minimum acceptable connection interval */ -#ifndef BTM_BLE_CONN_INT_MIN_LIMIT -#define BTM_BLE_CONN_INT_MIN_LIMIT 0x0009 -#endif - -#define BTM_BLE_DIR_CONN_FALLBACK_UNDIR 1 -#define BTM_BLE_DIR_CONN_FALLBACK_NO_ADV 2 - -#ifndef BTM_BLE_DIR_CONN_FALLBACK -#define BTM_BLE_DIR_CONN_FALLBACK BTM_BLE_DIR_CONN_FALLBACK_UNDIR -#endif - -#define BTM_CMAC_TLEN_SIZE 8 /* 64 bits */ -#define BTM_BLE_AUTH_SIGN_LEN 12 /* BLE data signature length 8 Bytes + 4 bytes counter*/ -typedef UINT8 BLE_SIGNATURE[BTM_BLE_AUTH_SIGN_LEN]; /* Device address */ - -#ifndef BTM_BLE_HOST_SUPPORT -#define BTM_BLE_HOST_SUPPORT 0x01 -#endif - -#ifndef BTM_BLE_SIMULTANEOUS_HOST -#define BTM_BLE_SIMULTANEOUS_HOST 0x01 -#endif - -/* Appearance Values Reported with BTM_BLE_AD_TYPE_APPEARANCE */ -#define BTM_BLE_APPEARANCE_UKNOWN 0x0000 -#define BTM_BLE_APPEARANCE_GENERIC_PHONE 0x0040 -#define BTM_BLE_APPEARANCE_GENERIC_COMPUTER 0x0080 -#define BTM_BLE_APPEARANCE_GENERIC_WATCH 0x00C0 -#define BTM_BLE_APPEARANCE_SPORTS_WATCH 0x00C1 -#define BTM_BLE_APPEARANCE_GENERIC_CLOCK 0x0100 -#define BTM_BLE_APPEARANCE_GENERIC_DISPLAY 0x0140 -#define BTM_BLE_APPEARANCE_GENERIC_REMOTE 0x0180 -#define BTM_BLE_APPEARANCE_GENERIC_EYEGLASSES 0x01C0 -#define BTM_BLE_APPEARANCE_GENERIC_TAG 0x0200 -#define BTM_BLE_APPEARANCE_GENERIC_KEYRING 0x0240 -#define BTM_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER 0x0280 -#define BTM_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER 0x02C0 -#define BTM_BLE_APPEARANCE_GENERIC_THERMOMETER 0x0300 -#define BTM_BLE_APPEARANCE_THERMOMETER_EAR 0x0301 -#define BTM_BLE_APPEARANCE_GENERIC_HEART_RATE 0x0340 -#define BTM_BLE_APPEARANCE_HEART_RATE_BELT 0x0341 -#define BTM_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE 0x0380 -#define BTM_BLE_APPEARANCE_BLOOD_PRESSURE_ARM 0x0381 -#define BTM_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST 0x0382 -#define BTM_BLE_APPEARANCE_GENERIC_HID 0x03C0 -#define BTM_BLE_APPEARANCE_HID_KEYBOARD 0x03C1 -#define BTM_BLE_APPEARANCE_HID_MOUSE 0x03C2 -#define BTM_BLE_APPEARANCE_HID_JOYSTICK 0x03C3 -#define BTM_BLE_APPEARANCE_HID_GAMEPAD 0x03C4 -#define BTM_BLE_APPEARANCE_HID_DIGITIZER_TABLET 0x03C5 -#define BTM_BLE_APPEARANCE_HID_CARD_READER 0x03C6 -#define BTM_BLE_APPEARANCE_HID_DIGITAL_PEN 0x03C7 -#define BTM_BLE_APPEARANCE_HID_BARCODE_SCANNER 0x03C8 -#define BTM_BLE_APPEARANCE_GENERIC_GLUCOSE 0x0400 -#define BTM_BLE_APPEARANCE_GENERIC_WALKING 0x0440 -#define BTM_BLE_APPEARANCE_WALKING_IN_SHOE 0x0441 -#define BTM_BLE_APPEARANCE_WALKING_ON_SHOE 0x0442 -#define BTM_BLE_APPEARANCE_WALKING_ON_HIP 0x0443 -#define BTM_BLE_APPEARANCE_GENERIC_CYCLING 0x0480 -#define BTM_BLE_APPEARANCE_CYCLING_COMPUTER 0x0481 -#define BTM_BLE_APPEARANCE_CYCLING_SPEED 0x0482 -#define BTM_BLE_APPEARANCE_CYCLING_CADENCE 0x0483 -#define BTM_BLE_APPEARANCE_CYCLING_POWER 0x0484 -#define BTM_BLE_APPEARANCE_CYCLING_SPEED_CADENCE 0x0485 -#define BTM_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER 0x0C40 -#define BTM_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP 0x0C41 -#define BTM_BLE_APPEARANCE_PULSE_OXIMETER_WRIST 0x0C42 -#define BTM_BLE_APPEARANCE_GENERIC_WEIGHT 0x0C80 -#define BTM_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS 0x1440 -#define BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION 0x1441 -#define BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV 0x1442 -#define BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD 0x1443 -#define BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV 0x1444 - - -/* Structure returned with Rand/Encrypt complete callback */ -typedef struct { - UINT8 status; - UINT8 param_len; - UINT16 opcode; - UINT8 param_buf[BT_OCTET16_LEN]; -} tBTM_RAND_ENC; - -/* General callback function for notifying an application that a synchronous -** BTM function is complete. The pointer contains the address of any returned data. -*/ -typedef void (tBTM_RAND_ENC_CB) (tBTM_RAND_ENC *p1); - -#define BTM_BLE_FILTER_TARGET_SCANNER 0x01 -#define BTM_BLE_FILTER_TARGET_ADVR 0x00 - -#define BTM_BLE_POLICY_BLACK_ALL 0x00 /* relevant to both */ -#define BTM_BLE_POLICY_ALLOW_SCAN 0x01 /* relevant to advertiser */ -#define BTM_BLE_POLICY_ALLOW_CONN 0x02 /* relevant to advertiser */ -#define BTM_BLE_POLICY_WHITE_ALL 0x03 /* relevant to both */ - -/* ADV data flag bit definition used for BTM_BLE_AD_TYPE_FLAG */ -#define BTM_BLE_LIMIT_DISC_FLAG (0x01 << 0) -#define BTM_BLE_GEN_DISC_FLAG (0x01 << 1) -#define BTM_BLE_BREDR_NOT_SPT (0x01 << 2) -/* 4.1 spec adv flag for simultaneous BR/EDR+LE connection support */ -#define BTM_BLE_DMT_CONTROLLER_SPT (0x01 << 3) -#define BTM_BLE_DMT_HOST_SPT (0x01 << 4) -#define BTM_BLE_NON_LIMIT_DISC_FLAG (0x00 ) /* lowest bit unset */ -#define BTM_BLE_ADV_FLAG_MASK (BTM_BLE_LIMIT_DISC_FLAG | BTM_BLE_BREDR_NOT_SPT | BTM_BLE_GEN_DISC_FLAG) -#define BTM_BLE_LIMIT_DISC_MASK (BTM_BLE_LIMIT_DISC_FLAG ) - -#define BTM_BLE_AD_BIT_DEV_NAME (0x00000001 << 0) -#define BTM_BLE_AD_BIT_FLAGS (0x00000001 << 1) -#define BTM_BLE_AD_BIT_MANU (0x00000001 << 2) -#define BTM_BLE_AD_BIT_TX_PWR (0x00000001 << 3) -#define BTM_BLE_AD_BIT_INT_RANGE (0x00000001 << 5) -#define BTM_BLE_AD_BIT_SERVICE (0x00000001 << 6) -#define BTM_BLE_AD_BIT_SERVICE_SOL (0x00000001 << 7) -#define BTM_BLE_AD_BIT_SERVICE_DATA (0x00000001 << 8) -#define BTM_BLE_AD_BIT_SIGN_DATA (0x00000001 << 9) -#define BTM_BLE_AD_BIT_SERVICE_128SOL (0x00000001 << 10) -#define BTM_BLE_AD_BIT_APPEARANCE (0x00000001 << 11) -#define BTM_BLE_AD_BIT_PUBLIC_ADDR (0x00000001 << 12) -#define BTM_BLE_AD_BIT_RANDOM_ADDR (0x00000001 << 13) -#define BTM_BLE_AD_BIT_SERVICE_32 (0x00000001 << 4) -#define BTM_BLE_AD_BIT_SERVICE_32SOL (0x00000001 << 14) -#define BTM_BLE_AD_BIT_PROPRIETARY (0x00000001 << 15) -#define BTM_BLE_AD_BIT_SERVICE_128 (0x00000001 << 16) /*128-bit Service UUIDs*/ - -typedef UINT32 tBTM_BLE_AD_MASK; - -/* relate to ESP_BLE_AD_TYPE_xxx in esp_gap_ble_api.h */ -#define BTM_BLE_AD_TYPE_FLAG HCI_EIR_FLAGS_TYPE /* 0x01 */ -#define BTM_BLE_AD_TYPE_16SRV_PART HCI_EIR_MORE_16BITS_UUID_TYPE /* 0x02 */ -#define BTM_BLE_AD_TYPE_16SRV_CMPL HCI_EIR_COMPLETE_16BITS_UUID_TYPE /* 0x03 */ -#define BTM_BLE_AD_TYPE_32SRV_PART HCI_EIR_MORE_32BITS_UUID_TYPE /* 0x04 */ -#define BTM_BLE_AD_TYPE_32SRV_CMPL HCI_EIR_COMPLETE_32BITS_UUID_TYPE /* 0x05 */ -#define BTM_BLE_AD_TYPE_128SRV_PART HCI_EIR_MORE_128BITS_UUID_TYPE /* 0x06 */ -#define BTM_BLE_AD_TYPE_128SRV_CMPL HCI_EIR_COMPLETE_128BITS_UUID_TYPE /* 0x07 */ -#define BTM_BLE_AD_TYPE_NAME_SHORT HCI_EIR_SHORTENED_LOCAL_NAME_TYPE /* 0x08 */ -#define BTM_BLE_AD_TYPE_NAME_CMPL HCI_EIR_COMPLETE_LOCAL_NAME_TYPE /* 0x09 */ -#define BTM_BLE_AD_TYPE_TX_PWR HCI_EIR_TX_POWER_LEVEL_TYPE /* 0x0A */ -#define BTM_BLE_AD_TYPE_DEV_CLASS 0x0D -#define BTM_BLE_AD_TYPE_SM_TK 0x10 -#define BTM_BLE_AD_TYPE_SM_OOB_FLAG 0x11 -#define BTM_BLE_AD_TYPE_INT_RANGE 0x12 -#define BTM_BLE_AD_TYPE_SOL_SRV_UUID 0x14 -#define BTM_BLE_AD_TYPE_128SOL_SRV_UUID 0x15 -#define BTM_BLE_AD_TYPE_SERVICE_DATA 0x16 -#define BTM_BLE_AD_TYPE_PUBLIC_TARGET 0x17 -#define BTM_BLE_AD_TYPE_RANDOM_TARGET 0x18 -#define BTM_BLE_AD_TYPE_APPEARANCE 0x19 -#define BTM_BLE_AD_TYPE_ADV_INT 0x1a -#define BTM_BLE_AD_TYPE_LE_DEV_ADDR 0x1b -#define BTM_BLE_AD_TYPE_LE_ROLE 0x1c -#define BTM_BLE_AD_TYPE_SPAIR_C256 0x1d -#define BTM_BLE_AD_TYPE_SPAIR_R256 0x1e -#define BTM_BLE_AD_TYPE_32SOL_SRV_UUID 0x1f -#define BTM_BLE_AD_TYPE_32SERVICE_DATA 0x20 -#define BTM_BLE_AD_TYPE_128SERVICE_DATA 0x21 -#define BTM_BLE_AD_TYPE_LE_SECURE_CONFIRM 0x22 -#define BTM_BLE_AD_TYPE_LE_SECURE_RANDOM 0x23 -#define BTM_BLE_AD_TYPE_URI 0x24 -#define BTM_BLE_AD_TYPE_INDOOR_POSITION 0x25 -#define BTM_BLE_AD_TYPE_TRANS_DISC_DATA 0x26 -#define BTM_BLE_AD_TYPE_LE_SUPPORT_FEATURE 0x27 -#define BTM_BLE_AD_TYPE_CHAN_MAP_UPDATE 0x28 - -#define BTM_BLE_AD_TYPE_MANU HCI_EIR_MANUFACTURER_SPECIFIC_TYPE /* 0xff */ -typedef UINT8 tBTM_BLE_AD_TYPE; - -/* Security settings used with L2CAP LE COC */ -#define BTM_SEC_LE_LINK_ENCRYPTED 0x01 -#define BTM_SEC_LE_LINK_PAIRED_WITHOUT_MITM 0x02 -#define BTM_SEC_LE_LINK_PAIRED_WITH_MITM 0x04 - -/* Min/max Preferred number of payload octets that the local Controller - should include in a single Link Layer Data Channel PDU. */ -#define BTM_BLE_DATA_SIZE_MAX 0x00fb -#define BTM_BLE_DATA_SIZE_MIN 0x001b - -/* Preferred maximum number of microseconds that the local Controller - should use to transmit a single Link Layer Data Channel PDU. */ -#define BTM_BLE_DATA_TX_TIME_MIN 0x0148 -#define BTM_BLE_DATA_TX_TIME_MAX 0x0848 - -/* adv tx power level */ -#define BTM_BLE_ADV_TX_POWER_MIN 0 /* minimum tx power */ -#define BTM_BLE_ADV_TX_POWER_LOW 1 /* low tx power */ -#define BTM_BLE_ADV_TX_POWER_MID 2 /* middle tx power */ -#define BTM_BLE_ADV_TX_POWER_UPPER 3 /* upper tx power */ -#define BTM_BLE_ADV_TX_POWER_MAX 4 /* maximum tx power */ -typedef UINT8 tBTM_BLE_ADV_TX_POWER; - -/* adv tx power in dBm */ -typedef struct { - UINT8 adv_inst_max; /* max adv instance supported in controller */ - UINT8 rpa_offloading; - UINT16 tot_scan_results_strg; - UINT8 max_irk_list_sz; - UINT8 filter_support; - UINT8 max_filter; - UINT8 energy_support; - BOOLEAN values_read; - UINT16 version_supported; - UINT16 total_trackable_advertisers; - UINT8 extended_scan_support; - UINT8 debug_logging_supported; -} tBTM_BLE_VSC_CB; - -/* slave preferred connection interval range */ -typedef struct { - UINT16 low; - UINT16 hi; - -} tBTM_BLE_INT_RANGE; - -/* Service tag supported in the device */ -typedef struct { - UINT8 num_service; - BOOLEAN list_cmpl; - UINT16 *p_uuid; -} tBTM_BLE_SERVICE; - -/* 32 bits Service supported in the device */ -typedef struct { - UINT8 num_service; - BOOLEAN list_cmpl; - UINT32 *p_uuid; -} tBTM_BLE_32SERVICE; - -/* 128 bits Service supported in the device */ -typedef struct { - BOOLEAN list_cmpl; - UINT8 uuid128[MAX_UUID_SIZE]; -} tBTM_BLE_128SERVICE; - -typedef struct { - UINT8 len; - UINT8 *p_val; -} tBTM_BLE_MANU; - - -typedef struct { - tBT_UUID service_uuid; - UINT8 len; - UINT8 *p_val; -} tBTM_BLE_SERVICE_DATA; - -typedef struct { - UINT8 adv_type; - UINT8 len; - UINT8 *p_val; /* number of len byte */ -} tBTM_BLE_PROP_ELEM; - -typedef struct { - UINT8 num_elem; - tBTM_BLE_PROP_ELEM *p_elem; -} tBTM_BLE_PROPRIETARY; - -typedef struct { - tBTM_BLE_INT_RANGE int_range; /* slave prefered conn interval range */ - tBTM_BLE_MANU *p_manu; /* manufactuer data */ - tBTM_BLE_SERVICE *p_services; /* services */ - tBTM_BLE_128SERVICE *p_services_128b; /* 128 bits service */ - tBTM_BLE_32SERVICE *p_service_32b; /* 32 bits Service UUID */ - tBTM_BLE_SERVICE *p_sol_services; /* 16 bits services Solicitation UUIDs */ - tBTM_BLE_32SERVICE *p_sol_service_32b; /* List of 32 bit Service Solicitation UUIDs */ - tBTM_BLE_128SERVICE *p_sol_service_128b; /* List of 128 bit Service Solicitation UUIDs */ - tBTM_BLE_PROPRIETARY *p_proprietary; - tBTM_BLE_SERVICE_DATA *p_service_data; /* service data */ - UINT16 appearance; - UINT8 flag; - UINT8 tx_power; -} tBTM_BLE_ADV_DATA; - -#ifndef BTM_BLE_MULTI_ADV_MAX -#define BTM_BLE_MULTI_ADV_MAX 16 /* controller returned adv_inst_max should be less - than this number */ -#endif - -#define BTM_BLE_MULTI_ADV_INVALID 0 - -#define BTM_BLE_MULTI_ADV_ENB_EVT 1 -#define BTM_BLE_MULTI_ADV_DISABLE_EVT 2 -#define BTM_BLE_MULTI_ADV_PARAM_EVT 3 -#define BTM_BLE_MULTI_ADV_DATA_EVT 4 -typedef UINT8 tBTM_BLE_MULTI_ADV_EVT; - -#define BTM_BLE_MULTI_ADV_DEFAULT_STD 0 - -typedef struct { - UINT16 adv_int_min; - UINT16 adv_int_max; - UINT8 adv_type; - tBTM_BLE_ADV_CHNL_MAP channel_map; - tBTM_BLE_AFP adv_filter_policy; - tBTM_BLE_ADV_TX_POWER tx_power; -} tBTM_BLE_ADV_PARAMS; - -typedef struct { - UINT8 *p_sub_code; /* dynamic array to store sub code */ - UINT8 *p_inst_id; /* dynamic array to store instance id */ - UINT8 pending_idx; - UINT8 next_idx; -} tBTM_BLE_MULTI_ADV_OPQ; - -typedef void (tBTM_BLE_MULTI_ADV_CBACK)(tBTM_BLE_MULTI_ADV_EVT evt, UINT8 inst_id, - void *p_ref, tBTM_STATUS status); - -typedef struct { - UINT8 inst_id; - BOOLEAN in_use; - UINT8 adv_evt; - BD_ADDR rpa; - TIMER_LIST_ENT raddr_timer_ent; - tBTM_BLE_MULTI_ADV_CBACK *p_cback; - void *p_ref; - UINT8 index; -} tBTM_BLE_MULTI_ADV_INST; - -typedef struct { - UINT8 inst_index_queue[BTM_BLE_MULTI_ADV_MAX]; - int front; - int rear; -} tBTM_BLE_MULTI_ADV_INST_IDX_Q; - -typedef struct { - tBTM_BLE_MULTI_ADV_INST *p_adv_inst; /* dynamic array to store adv instance */ - tBTM_BLE_MULTI_ADV_OPQ op_q; -} tBTM_BLE_MULTI_ADV_CB; - -typedef UINT8 tGATT_IF; - -typedef void (tBTM_BLE_SCAN_THRESHOLD_CBACK)(tBTM_BLE_REF_VALUE ref_value); -typedef void (tBTM_BLE_SCAN_REP_CBACK)(tBTM_BLE_REF_VALUE ref_value, UINT8 report_format, - UINT8 num_records, UINT16 total_len, - UINT8 *p_rep_data, UINT8 status); -typedef void (tBTM_BLE_SCAN_SETUP_CBACK)(UINT8 evt, tBTM_BLE_REF_VALUE ref_value, UINT8 status); - -#ifndef BTM_BLE_BATCH_SCAN_MAX -#define BTM_BLE_BATCH_SCAN_MAX 5 -#endif - -#ifndef BTM_BLE_BATCH_REP_MAIN_Q_SIZE -#define BTM_BLE_BATCH_REP_MAIN_Q_SIZE 2 -#endif - -typedef enum { - BTM_BLE_SCAN_INVALID_STATE = 0, - BTM_BLE_SCAN_ENABLE_CALLED = 1, - BTM_BLE_SCAN_ENABLED_STATE = 2, - BTM_BLE_SCAN_DISABLE_CALLED = 3, - BTM_BLE_SCAN_DISABLED_STATE = 4 -} tBTM_BLE_BATCH_SCAN_STATE; - -enum { - BTM_BLE_DISCARD_OLD_ITEMS, - BTM_BLE_DISCARD_LOWER_RSSI_ITEMS -}; -typedef UINT8 tBTM_BLE_DISCARD_RULE; - -typedef struct { - UINT8 sub_code[BTM_BLE_BATCH_SCAN_MAX]; - tBTM_BLE_BATCH_SCAN_STATE cur_state[BTM_BLE_BATCH_SCAN_MAX]; - tBTM_BLE_REF_VALUE ref_value[BTM_BLE_BATCH_SCAN_MAX]; - UINT8 pending_idx; - UINT8 next_idx; -} tBTM_BLE_BATCH_SCAN_OPQ; - -typedef struct { - UINT8 rep_mode[BTM_BLE_BATCH_REP_MAIN_Q_SIZE]; - tBTM_BLE_REF_VALUE ref_value[BTM_BLE_BATCH_REP_MAIN_Q_SIZE]; - UINT8 num_records[BTM_BLE_BATCH_REP_MAIN_Q_SIZE]; - UINT16 data_len[BTM_BLE_BATCH_REP_MAIN_Q_SIZE]; - UINT8 *p_data[BTM_BLE_BATCH_REP_MAIN_Q_SIZE]; - UINT8 pending_idx; - UINT8 next_idx; -} tBTM_BLE_BATCH_SCAN_REP_Q; - -typedef struct { - tBTM_BLE_BATCH_SCAN_STATE cur_state; - tBTM_BLE_BATCH_SCAN_MODE scan_mode; - UINT32 scan_interval; - UINT32 scan_window; - tBLE_ADDR_TYPE addr_type; - tBTM_BLE_DISCARD_RULE discard_rule; - tBTM_BLE_BATCH_SCAN_OPQ op_q; - tBTM_BLE_BATCH_SCAN_REP_Q main_rep_q; - tBTM_BLE_SCAN_SETUP_CBACK *p_setup_cback; - tBTM_BLE_SCAN_THRESHOLD_CBACK *p_thres_cback; - tBTM_BLE_SCAN_REP_CBACK *p_scan_rep_cback; - tBTM_BLE_REF_VALUE ref_value; -} tBTM_BLE_BATCH_SCAN_CB; - -/* filter selection bit index */ -#define BTM_BLE_PF_ADDR_FILTER 0 -#define BTM_BLE_PF_SRVC_DATA 1 -#define BTM_BLE_PF_SRVC_UUID 2 -#define BTM_BLE_PF_SRVC_SOL_UUID 3 -#define BTM_BLE_PF_LOCAL_NAME 4 -#define BTM_BLE_PF_MANU_DATA 5 -#define BTM_BLE_PF_SRVC_DATA_PATTERN 6 -#define BTM_BLE_PF_TYPE_ALL 7 /* when passed in payload filter type all, only clear action is applicable */ -#define BTM_BLE_PF_TYPE_MAX 8 - -/* max number of filter spot for different filter type */ -#ifndef BTM_BLE_MAX_UUID_FILTER -#define BTM_BLE_MAX_UUID_FILTER 8 -#endif -#ifndef BTM_BLE_MAX_ADDR_FILTER -#define BTM_BLE_MAX_ADDR_FILTER 8 -#endif -#ifndef BTM_BLE_PF_STR_COND_MAX -#define BTM_BLE_PF_STR_COND_MAX 4 /* apply to manu data , or local name */ -#endif -#ifndef BTM_BLE_PF_STR_LEN_MAX -#define BTM_BLE_PF_STR_LEN_MAX 29 /* match for first 29 bytes */ -#endif - -typedef UINT8 tBTM_BLE_PF_COND_TYPE; - -#define BTM_BLE_PF_LOGIC_OR 0 -#define BTM_BLE_PF_LOGIC_AND 1 -typedef UINT8 tBTM_BLE_PF_LOGIC_TYPE; - -#define BTM_BLE_PF_ENABLE 1 -#define BTM_BLE_PF_CONFIG 2 -typedef UINT8 tBTM_BLE_PF_ACTION; - -typedef UINT8 tBTM_BLE_PF_FILT_INDEX; - -typedef UINT8 tBTM_BLE_PF_AVBL_SPACE; - -#define BTM_BLE_PF_BRDCAST_ADDR_FILT 1 -#define BTM_BLE_PF_SERV_DATA_CHG_FILT 2 -#define BTM_BLE_PF_SERV_UUID 4 -#define BTM_BLE_PF_SERV_SOLC_UUID 8 -#define BTM_BLE_PF_LOC_NAME_CHECK 16 -#define BTM_BLE_PF_MANUF_NAME_CHECK 32 -#define BTM_BLE_PF_SERV_DATA_CHECK 64 -typedef UINT16 tBTM_BLE_PF_FEAT_SEL; - -#define BTM_BLE_PF_LIST_LOGIC_OR 1 -#define BTM_BLE_PF_LIST_LOGIC_AND 2 -typedef UINT16 tBTM_BLE_PF_LIST_LOGIC_TYPE; - -#define BTM_BLE_PF_FILT_LOGIC_OR 0 -#define BTM_BLE_PF_FILT_LOGIC_AND 1 -typedef UINT16 tBTM_BLE_PF_FILT_LOGIC_TYPE; - -typedef UINT8 tBTM_BLE_PF_RSSI_THRESHOLD; -typedef UINT8 tBTM_BLE_PF_DELIVERY_MODE; -typedef UINT16 tBTM_BLE_PF_TIMEOUT; -typedef UINT8 tBTM_BLE_PF_TIMEOUT_CNT; -typedef UINT16 tBTM_BLE_PF_ADV_TRACK_ENTRIES; - -typedef struct { - tBTM_BLE_PF_FEAT_SEL feat_seln; - tBTM_BLE_PF_LIST_LOGIC_TYPE logic_type; - tBTM_BLE_PF_FILT_LOGIC_TYPE filt_logic_type; - tBTM_BLE_PF_RSSI_THRESHOLD rssi_high_thres; - tBTM_BLE_PF_RSSI_THRESHOLD rssi_low_thres; - tBTM_BLE_PF_DELIVERY_MODE dely_mode; - tBTM_BLE_PF_TIMEOUT found_timeout; - tBTM_BLE_PF_TIMEOUT lost_timeout; - tBTM_BLE_PF_TIMEOUT_CNT found_timeout_cnt; - tBTM_BLE_PF_ADV_TRACK_ENTRIES num_of_tracking_entries; -} tBTM_BLE_PF_FILT_PARAMS; - -enum { - BTM_BLE_SCAN_COND_ADD, - BTM_BLE_SCAN_COND_DELETE, - BTM_BLE_SCAN_COND_CLEAR = 2 -}; -typedef UINT8 tBTM_BLE_SCAN_COND_OP; - -enum { - BTM_BLE_FILT_ENABLE_DISABLE = 1, - BTM_BLE_FILT_CFG = 2, - BTM_BLE_FILT_ADV_PARAM = 3 -}; - -typedef UINT8 tBTM_BLE_FILT_CB_EVT; - -/* BLE adv payload filtering config complete callback */ -typedef void (tBTM_BLE_PF_CFG_CBACK)(tBTM_BLE_PF_ACTION action, tBTM_BLE_SCAN_COND_OP cfg_op, - tBTM_BLE_PF_AVBL_SPACE avbl_space, tBTM_STATUS status, - tBTM_BLE_REF_VALUE ref_value); - -typedef void (tBTM_BLE_PF_CMPL_CBACK) (tBTM_BLE_PF_CFG_CBACK); - -/* BLE adv payload filtering status setup complete callback */ -typedef void (tBTM_BLE_PF_STATUS_CBACK) (UINT8 action, tBTM_STATUS status, - tBTM_BLE_REF_VALUE ref_value); - -/* BLE adv payload filtering param setup complete callback */ -typedef void (tBTM_BLE_PF_PARAM_CBACK) (tBTM_BLE_PF_ACTION action_type, - tBTM_BLE_PF_AVBL_SPACE avbl_space, - tBTM_BLE_REF_VALUE ref_value, tBTM_STATUS status); - -typedef union { - UINT16 uuid16_mask; - UINT32 uuid32_mask; - UINT8 uuid128_mask[LEN_UUID_128]; -} tBTM_BLE_PF_COND_MASK; - -typedef struct { - tBLE_BD_ADDR *p_target_addr; /* target address, if NULL, generic UUID filter */ - tBT_UUID uuid; /* UUID condition */ - tBTM_BLE_PF_LOGIC_TYPE cond_logic; /* AND/OR */ - tBTM_BLE_PF_COND_MASK *p_uuid_mask; /* UUID mask */ -} tBTM_BLE_PF_UUID_COND; - -typedef struct { - UINT8 data_len; /* <= 20 bytes */ - UINT8 *p_data; -} tBTM_BLE_PF_LOCAL_NAME_COND; - -typedef struct { - UINT16 company_id; /* company ID */ - UINT8 data_len; /* <= 20 bytes */ - UINT8 *p_pattern; - UINT16 company_id_mask; /* UUID value mask */ - UINT8 *p_pattern_mask; /* Manufacturer data matching mask, - same length as data pattern, - set to all 0xff, match exact data */ -} tBTM_BLE_PF_MANU_COND; - -typedef struct { - UINT16 uuid; /* service ID */ - UINT8 data_len; /* <= 20 bytes */ - UINT8 *p_pattern; - UINT8 *p_pattern_mask; /* Service data matching mask, same length as data pattern, - set to all 0xff, match exact data */ -} tBTM_BLE_PF_SRVC_PATTERN_COND; - - -typedef union { - tBLE_BD_ADDR target_addr; - tBTM_BLE_PF_LOCAL_NAME_COND local_name; /* lcoal name filtering */ - tBTM_BLE_PF_MANU_COND manu_data; /* manufactuer data filtering */ - tBTM_BLE_PF_UUID_COND srvc_uuid; /* service UUID filtering */ - tBTM_BLE_PF_UUID_COND solicitate_uuid; /* solicitated service UUID filtering */ - tBTM_BLE_PF_SRVC_PATTERN_COND srvc_data; /* service data pattern */ -} tBTM_BLE_PF_COND_PARAM; - -typedef struct { - UINT8 action_ocf[BTM_BLE_PF_TYPE_MAX]; - tBTM_BLE_REF_VALUE ref_value[BTM_BLE_PF_TYPE_MAX]; - tBTM_BLE_PF_PARAM_CBACK *p_filt_param_cback[BTM_BLE_PF_TYPE_MAX]; - tBTM_BLE_PF_CFG_CBACK *p_scan_cfg_cback[BTM_BLE_PF_TYPE_MAX]; - UINT8 cb_evt[BTM_BLE_PF_TYPE_MAX]; - UINT8 pending_idx; - UINT8 next_idx; -} tBTM_BLE_ADV_FILTER_ADV_OPQ; - -#define BTM_BLE_MAX_FILTER_COUNTER (BTM_BLE_MAX_ADDR_FILTER + 1) /* per device filter + one generic filter indexed by 0 */ - -#ifndef BTM_CS_IRK_LIST_MAX -#define BTM_CS_IRK_LIST_MAX 0x20 -#endif - -typedef struct { - BOOLEAN in_use; - BD_ADDR bd_addr; - UINT8 pf_counter[BTM_BLE_PF_TYPE_MAX]; /* number of filter indexed by tBTM_BLE_PF_COND_TYPE */ -} tBTM_BLE_PF_COUNT; - -typedef struct { - BOOLEAN enable; - UINT8 op_type; - tBTM_BLE_PF_COUNT *p_addr_filter_count; /* per BDA filter array */ - tBLE_BD_ADDR cur_filter_target; - tBTM_BLE_PF_STATUS_CBACK *p_filt_stat_cback; - tBTM_BLE_ADV_FILTER_ADV_OPQ op_q; -} tBTM_BLE_ADV_FILTER_CB; - -/* Sub codes */ -#define BTM_BLE_META_PF_ENABLE 0x00 -#define BTM_BLE_META_PF_FEAT_SEL 0x01 -#define BTM_BLE_META_PF_ADDR 0x02 -#define BTM_BLE_META_PF_UUID 0x03 -#define BTM_BLE_META_PF_SOL_UUID 0x04 -#define BTM_BLE_META_PF_LOCAL_NAME 0x05 -#define BTM_BLE_META_PF_MANU_DATA 0x06 -#define BTM_BLE_META_PF_SRVC_DATA 0x07 -#define BTM_BLE_META_PF_ALL 0x08 - -typedef UINT8 BTM_BLE_ADV_STATE; -typedef UINT8 BTM_BLE_ADV_INFO_PRESENT; -typedef UINT8 BTM_BLE_RSSI_VALUE; -typedef UINT16 BTM_BLE_ADV_INFO_TIMESTAMP; - -/* These are the fields returned in each device adv packet. It -** is returned in the results callback if registered. -*/ -typedef struct { - UINT8 conn_mode; - tBTM_BLE_AD_MASK ad_mask; /* mask of the valid adv data field */ - UINT8 flag; - UINT8 tx_power_level; - UINT8 remote_name_len; - UINT8 *p_remote_name; - tBTM_BLE_SERVICE service; -} tBTM_BLE_INQ_DATA; - -enum { - BTM_BLE_CONN_NONE, - BTM_BLE_CONN_AUTO, - BTM_BLE_CONN_SELECTIVE -}; -typedef UINT8 tBTM_BLE_CONN_TYPE; - -#define ADV_INFO_PRESENT 0x00 -#define NO_ADV_INFO_PRESENT 0x01 - -typedef btgatt_track_adv_info_t tBTM_BLE_TRACK_ADV_DATA; - -typedef void (tBTM_BLE_TRACK_ADV_CBACK)(tBTM_BLE_TRACK_ADV_DATA *p_track_adv_data); - -typedef UINT8 tBTM_BLE_TRACK_ADV_EVT; - -typedef struct { - tBTM_BLE_REF_VALUE ref_value; - tBTM_BLE_TRACK_ADV_CBACK *p_track_cback; -} tBTM_BLE_ADV_TRACK_CB; - -enum { - BTM_BLE_TRACK_ADV_ADD, - BTM_BLE_TRACK_ADV_REMOVE -}; - -typedef UINT8 tBTM_BLE_TRACK_ADV_ACTION; - -#define BTM_BLE_MULTI_ADV_INVALID 0 - -#define BTM_BLE_BATCH_SCAN_ENABLE_EVT 1 -#define BTM_BLE_BATCH_SCAN_CFG_STRG_EVT 2 -#define BTM_BLE_BATCH_SCAN_READ_REPTS_EVT 3 -#define BTM_BLE_BATCH_SCAN_THR_EVT 4 -#define BTM_BLE_BATCH_SCAN_PARAM_EVT 5 -#define BTM_BLE_BATCH_SCAN_DISABLE_EVT 6 - -typedef UINT8 tBTM_BLE_BATCH_SCAN_EVT; - -typedef UINT32 tBTM_BLE_TX_TIME_MS; -typedef UINT32 tBTM_BLE_RX_TIME_MS; -typedef UINT32 tBTM_BLE_IDLE_TIME_MS; -typedef UINT32 tBTM_BLE_ENERGY_USED; - -typedef void (tBTM_BLE_ENERGY_INFO_CBACK)(tBTM_BLE_TX_TIME_MS tx_time, tBTM_BLE_RX_TIME_MS rx_time, - tBTM_BLE_IDLE_TIME_MS idle_time, - tBTM_BLE_ENERGY_USED energy_used, - tBTM_STATUS status); - -typedef struct { - tBTM_BLE_ENERGY_INFO_CBACK *p_ener_cback; -} tBTM_BLE_ENERGY_INFO_CB; - -typedef BOOLEAN (tBTM_BLE_SEL_CBACK)(BD_ADDR random_bda, UINT8 *p_remote_name); -typedef void (tBTM_BLE_CTRL_FEATURES_CBACK)(tBTM_STATUS status); - -/* callback function for SMP signing algorithm, signed data in little endian order with tlen bits long */ -typedef void (tBTM_BLE_SIGN_CBACK)(void *p_ref_data, UINT8 *p_signing_data); -typedef void (tBTM_BLE_VERIFY_CBACK)(void *p_ref_data, BOOLEAN match); -/* random address set complete callback */ -typedef void (tBTM_BLE_RANDOM_SET_CBACK) (BD_ADDR random_bda); - -typedef void (tBTM_BLE_SCAN_REQ_CBACK)(BD_ADDR remote_bda, tBLE_ADDR_TYPE addr_type, UINT8 adv_evt); -typedef void (*tBLE_SCAN_PARAM_SETUP_CBACK)(tGATT_IF client_if, tBTM_STATUS status); - -tBTM_BLE_SCAN_SETUP_CBACK bta_ble_scan_setup_cb; - -typedef void (tBTM_START_ADV_CMPL_CBACK) (UINT8 status); -typedef void (tBTM_START_STOP_ADV_CMPL_CBACK) (UINT8 status); - - - -/***************************************************************************** -** EXTERNAL FUNCTION DECLARATIONS -*****************************************************************************/ -/* -#ifdef __cplusplus -extern "C" { -#endif -*/ - -/******************************************************************************* -** -** Function BTM_BleRegiseterConnParamCallback -** -** Description register connection parameters update callback func -** -** Parameters: update_conn_param_cb -** -** Returns void -** -*******************************************************************************/ -void BTM_BleRegiseterConnParamCallback(tBTM_UPDATE_CONN_PARAM_CBACK *update_conn_param_cb); - -/******************************************************************************* -** -** Function BTM_SecAddBleDevice -** -** Description Add/modify device. This function will be normally called -** during host startup to restore all required information -** for a LE device stored in the NVRAM. -** -** Parameters: bd_addr - BD address of the peer -** bd_name - Name of the peer device. NULL if unknown. -** dev_type - Remote device's device type. -** addr_type - LE device address type. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SecAddBleDevice (BD_ADDR bd_addr, BD_NAME bd_name, - tBT_DEVICE_TYPE dev_type, tBLE_ADDR_TYPE addr_type); - -/******************************************************************************* -** -** Function BTM_SecAddBleKey -** -** Description Add/modify LE device information. This function will be -** normally called during host startup to restore all required -** information stored in the NVRAM. -** -** Parameters: bd_addr - BD address of the peer -** p_le_key - LE key values. -** key_type - LE SMP key type. -* -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_SecAddBleKey (BD_ADDR bd_addr, tBTM_LE_KEY_VALUE *p_le_key, - tBTM_LE_KEY_TYPE key_type); - -/******************************************************************************* -** -** Function BTM_BleSetAdvParams -** -** Description This function is called to set advertising parameters. -** -** Parameters: None. -** -** Returns void -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleSetAdvParams(UINT16 adv_int_min, UINT16 adv_int_max, - tBLE_BD_ADDR *p_dir_bda, tBTM_BLE_ADV_CHNL_MAP chnl_map); - - - -/******************************************************************************* -** -** Function BTM_BleSetAdvParamsStartAdv -** -** Description This function is called to set all of the advertising parameters. -** -** Parameters: None. -** -** Returns void -** -*******************************************************************************/ -tBTM_STATUS BTM_BleSetAdvParamsStartAdv(UINT16 adv_int_min, UINT16 adv_int_max, UINT8 adv_type, - tBLE_ADDR_TYPE own_bda_type, tBLE_BD_ADDR *p_dir_bda, - tBTM_BLE_ADV_CHNL_MAP chnl_map, tBTM_BLE_AFP afp, tBTM_START_ADV_CMPL_CBACK *adv_cb); - - -/******************************************************************************* -** -** Function BTM_BleWriteAdvData -** -** Description This function is called to write advertising data. -** -** Parameters: None. -** -** Returns void -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleWriteAdvData(tBTM_BLE_AD_MASK data_mask, - tBTM_BLE_ADV_DATA *p_data); - -/******************************************************************************* -** -** Function BTM_BleWriteAdvDataRaw -** -** Description This function is called to write raw advertising data. -** -** Parameters: p_raw_adv : point to raw advertising data -** raw_adv_len : raw advertising data -** -** Returns BTM_SUCCESS means success. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleWriteAdvDataRaw(UINT8 *p_raw_adv, UINT32 raw_adv_len); - - -tBTM_STATUS BTM_BleSetRandAddress(BD_ADDR rand_addr); - - -/******************************************************************************* -** -** Function BTM_BleSetAdvParams -** -** Description This function is called to set advertising parameters. -** -** Parameters adv_int_min: minimum advertising interval -** adv_int_max: maximum advertising interval -** p_dir_bda: connectable direct initiator's LE device address -** chnl_map: advertising channel map. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleReadAdvParams (UINT16 *adv_int_min, UINT16 *adv_int_max, - tBLE_BD_ADDR *p_dir_bda, tBTM_BLE_ADV_CHNL_MAP *p_chnl_map); - -/******************************************************************************* -** -** Function BTM_BleObtainVendorCapabilities -** -** Description This function is called to obatin vendor capabilties -** -** Parameters p_cmn_vsc_cb - Returns the vednor capabilities -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleObtainVendorCapabilities(tBTM_BLE_VSC_CB *p_cmn_vsc_cb); - -/******************************************************************************* -** -** Function BTM_BleSetScanParams -** -** Description This function is called to set Scan parameters. -** -** Parameters client_if - Client IF value -** scan_interval - Scan interval -** scan_window - Scan window -** scan_type - Scan type -** scan_setup_status_cback - Scan setup status callback -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleSetScanParams(tGATT_IF client_if, UINT32 scan_interval, - UINT32 scan_window, tBLE_SCAN_MODE scan_type, - tBLE_SCAN_PARAM_SETUP_CBACK scan_setup_status_cback); - - - -/******************************************************************************* -** -** Function BTM_BleSetScanFilterParams -** -** Description This function is called to set Scan Filter & parameters. -** -** Parameters client_if - Client IF value -** scan_interval - Scan interval -** scan_window - Scan window -** scan_type - Scan type -** addr_type_own - owner address type -** scan_filter_policy - scan filter policy -** scan_setup_status_cback - Scan setup status callback -** -** Returns void -** -*******************************************************************************/ -void BTM_BleSetScanFilterParams(tGATT_IF client_if, UINT32 scan_interval, UINT32 scan_window, - tBLE_SCAN_MODE scan_mode, UINT8 addr_type_own, tBTM_BLE_SFP scan_filter_policy, - tBLE_SCAN_PARAM_SETUP_CBACK scan_setup_status_cback); - - -/******************************************************************************* -** -** Function BTM_BleGetVendorCapabilities -** -** Description This function reads local LE features -** -** Parameters p_cmn_vsc_cb : Locala LE capability structure -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB *p_cmn_vsc_cb); -/******************************************************************************* -** -** Function BTM_BleSetStorageConfig -** -** Description This function is called to setup storage configuration and setup callbacks. -** -** Parameters UINT8 batch_scan_full_max -Batch scan full maximum - UINT8 batch_scan_trunc_max - Batch scan truncated value maximum - UINT8 batch_scan_notify_threshold - Threshold value - tBTM_BLE_SCAN_SETUP_CBACK *p_setup_cback - Setup callback - tBTM_BLE_SCAN_THRESHOLD_CBACK *p_thres_cback -Threshold callback - void *p_ref - Reference value -** -** Returns tBTM_STATUS -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleSetStorageConfig(UINT8 batch_scan_full_max, - UINT8 batch_scan_trunc_max, - UINT8 batch_scan_notify_threshold, - tBTM_BLE_SCAN_SETUP_CBACK *p_setup_cback, - tBTM_BLE_SCAN_THRESHOLD_CBACK *p_thres_cback, - tBTM_BLE_SCAN_REP_CBACK *p_cback, - tBTM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTM_BleEnableBatchScan -** -** Description This function is called to enable batch scan -** -** Parameters tBTM_BLE_BATCH_SCAN_MODE scan_mode - Batch scan mode - UINT32 scan_interval -Scan interval - UINT32 scan_window - Scan window value - tBLE_ADDR_TYPE addr_type - Address type - tBTM_BLE_DISCARD_RULE discard_rule - Data discard rules -** -** Returns tBTM_STATUS -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleEnableBatchScan(tBTM_BLE_BATCH_SCAN_MODE scan_mode, - UINT32 scan_interval, UINT32 scan_window, - tBTM_BLE_DISCARD_RULE discard_rule, - tBLE_ADDR_TYPE addr_type, - tBTM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTM_BleDisableBatchScan -** -** Description This function is called to disable batch scanning -** -** Parameters void -** -** Returns void -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleDisableBatchScan(tBTM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTM_BleReadScanReports -** -** Description This function is called to read batch scan reports -** -** Parameters tBLE_SCAN_MODE scan_mode - Scan mode report to be read out - tBTM_BLE_SCAN_REP_CBACK* p_cback - Reports callback -** -** Returns tBTM_STATUS -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleReadScanReports(tBLE_SCAN_MODE scan_mode, - tBTM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTM_BleTrackAdvertiser -** -** Description This function is called to read batch scan reports -** -** Parameters p_track_cback - Tracking callback -** ref_value - Reference value -** -** Returns tBTM_STATUS -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleTrackAdvertiser(tBTM_BLE_TRACK_ADV_CBACK *p_track_cback, - tBTM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTM_BleWriteScanRsp -** -** Description This function is called to write LE scan response. -** -** Parameters: p_scan_rsp: scan response. -** -** Returns status -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleWriteScanRsp(tBTM_BLE_AD_MASK data_mask, - tBTM_BLE_ADV_DATA *p_data); - -/******************************************************************************* -** -** Function BTM_BleWriteScanRspRaw -** -** Description This function is called to write raw scan response data -** -** Parameters: None. -** -** Returns void -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleWriteScanRspRaw(UINT8 *p_raw_scan_rsp, UINT32 raw_scan_rsp_len); - -/******************************************************************************* -** -** Function BTM_BleObserve -** -** Description This procedure keep the device listening for advertising -** events from a broadcast device. -** -** Parameters start: start or stop observe. -** -** Returns void -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleObserve(BOOLEAN start, UINT32 duration, - tBTM_INQ_RESULTS_CB *p_results_cb, tBTM_CMPL_CB *p_cmpl_cb); - -/******************************************************************************* -** -** Function BTM_BleScan -** -** Description This procedure keep the device listening for advertising -** events from a broadcast device. -** -** Parameters start: start or stop scan. -** -** Returns void -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleScan(BOOLEAN start, UINT32 duration, - tBTM_INQ_RESULTS_CB *p_results_cb, tBTM_CMPL_CB *p_cmpl_cb); - - -/******************************************************************************* -** -** Function BTM_GetDeviceIDRoot -** -** Description This function is called to read the local device identity -** root. -** -** Returns void -** the local device ER is copied into er -** -*******************************************************************************/ -//extern -void BTM_GetDeviceIDRoot (BT_OCTET16 ir); - -/******************************************************************************* -** -** Function BTM_GetDeviceEncRoot -** -** Description This function is called to read the local device encryption -** root. -** -** Returns void -** the local device ER is copied into er -** -*******************************************************************************/ -//extern -void BTM_GetDeviceEncRoot (BT_OCTET16 er); - -/******************************************************************************* -** -** Function BTM_GetDeviceDHK -** -** Description This function is called to read the local device DHK. -** -** Returns void -** the local device DHK is copied into dhk -** -*******************************************************************************/ -//extern -void BTM_GetDeviceDHK (BT_OCTET16 dhk); - -/******************************************************************************* -** -** Function BTM_SecurityGrant -** -** Description This function is called to grant security process. -** -** Parameters bd_addr - peer device bd address. -** res - result of the operation BTM_SUCCESS if success. -** Otherwise, BTM_REPEATED_ATTEMPTS is too many attempts. -** -** Returns None -** -*******************************************************************************/ -//extern -void BTM_SecurityGrant(BD_ADDR bd_addr, UINT8 res); - -/******************************************************************************* -** -** Function BTM_BlePasskeyReply -** -** Description This function is called after Security Manager submitted -** passkey request to the application. -** -** Parameters: bd_addr - Address of the device for which passkey was requested -** res - result of the operation SMP_SUCCESS if success -** passkey - numeric value in the range of -** BTM_MIN_PASSKEY_VAL(0) - BTM_MAX_PASSKEY_VAL(999999(0xF423F)). -** -*******************************************************************************/ -//extern -void BTM_BlePasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey); - -/******************************************************************************* -** -** Function BTM_BleConfirmReply -** -** Description This function is called after Security Manager submitted -** numeric comparison request to the application. -** -** Parameters: bd_addr - Address of the device with which numeric -** comparison was requested -** res - comparison result BTM_SUCCESS if success -** -*******************************************************************************/ -//extern -void BTM_BleConfirmReply (BD_ADDR bd_addr, UINT8 res); - -/******************************************************************************* -** -** Function BTM_LeOobDataReply -** -** Description This function is called to provide the OOB data for -** SMP in response to BTM_LE_OOB_REQ_EVT -** -** Parameters: bd_addr - Address of the peer device -** res - result of the operation SMP_SUCCESS if success -** p_data - simple pairing Randomizer C. -** -*******************************************************************************/ -//extern -void BTM_BleOobDataReply(BD_ADDR bd_addr, UINT8 res, UINT8 len, UINT8 *p_data); - - -/******************************************************************************* -** -** Function BTM_BleDataSignature -** -** Description This function is called to sign the data using AES128 CMAC -** algorith. -** -** Parameter bd_addr: target device the data to be signed for. -** p_text: singing data -** len: length of the signing data -** signature: output parameter where data signature is going to -** be stored. -** -** Returns TRUE if signing sucessul, otherwise FALSE. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BleDataSignature (BD_ADDR bd_addr, UINT8 *p_text, UINT16 len, - BLE_SIGNATURE signature); - -/******************************************************************************* -** -** Function BTM_BleVerifySignature -** -** Description This function is called to verify the data signature -** -** Parameter bd_addr: target device the data to be signed for. -** p_orig: original data before signature. -** len: length of the signing data -** counter: counter used when doing data signing -** p_comp: signature to be compared against. - -** Returns TRUE if signature verified correctly; otherwise FALSE. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BleVerifySignature (BD_ADDR bd_addr, UINT8 *p_orig, - UINT16 len, UINT32 counter, - UINT8 *p_comp); - -/******************************************************************************* -** -** Function BTM_ReadConnectionAddr -** -** Description This function is called to set the local device random address -** . -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_ReadConnectionAddr (BD_ADDR remote_bda, BD_ADDR local_conn_addr, - tBLE_ADDR_TYPE *p_addr_type); - - - -/******************************************************************************* -** -** Function BTM_ReadRemoteConnectionAddr -** -** Description This function is read the remote device address currently used -** . -** -** Returns void -** -*******************************************************************************/ -//extern -BOOLEAN BTM_ReadRemoteConnectionAddr(BD_ADDR pseudo_addr, - BD_ADDR conn_addr, - tBLE_ADDR_TYPE *p_addr_type); - -/******************************************************************************* -** -** Function BTM_BleLoadLocalKeys -** -** Description Local local identity key, encryption root or sign counter. -** -** Parameters: key_type: type of key, can be BTM_BLE_KEY_TYPE_ID, BTM_BLE_KEY_TYPE_ER -** or BTM_BLE_KEY_TYPE_COUNTER. -** p_key: pointer to the key. -* -** Returns non2. -** -*******************************************************************************/ -//extern -void BTM_BleLoadLocalKeys(UINT8 key_type, tBTM_BLE_LOCAL_KEYS *p_key); - - -/******************************************************************************* -** -** Function BTM_BleSetBgConnType -** -** Description This function is called to set BLE background connection -** procedure type. It can be auto connection, or selective connection. -** -** Parameters conn_type: it can be auto connection, or selective connection. -** p_select_cback: callback function when selective connection procedure -** is being used. -** -** Returns void -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BleSetBgConnType(tBTM_BLE_CONN_TYPE conn_type, - tBTM_BLE_SEL_CBACK *p_select_cback); - -/******************************************************************************* -** -** Function BTM_BleUpdateBgConnDev -** -** Description This function is called to add or remove a device into/from -** background connection procedure. The background connection -* procedure is decided by the background connection type, it can be -* auto connection, or selective connection. -** -** Parameters add_remove: TRUE to add; FALSE to remove. -** remote_bda: device address to add/remove. -** -** Returns void -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BleUpdateBgConnDev(BOOLEAN add_remove, BD_ADDR remote_bda); - -/******************************************************************************* -** -** Function BTM_BleClearBgConnDev -** -** Description This function is called to clear the whitelist, -** end any pending whitelist connections, -* and reset the local bg device list. -** -** Parameters void -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleClearBgConnDev(void); - -/******************************************************** -** -** Function BTM_BleSetPrefConnParams -** -** Description Set a peripheral's preferred connection parameters. When -** any of the value does not want to be updated while others -** do, use BTM_BLE_CONN_PARAM_UNDEF for the ones want to -** leave untouched. -** -** Parameters: bd_addr - BD address of the peripheral -** min_conn_int - minimum preferred connection interval -** max_conn_int - maximum preferred connection interval -** slave_latency - preferred slave latency -** supervision_tout - preferred supervision timeout -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleSetPrefConnParams (BD_ADDR bd_addr, - UINT16 min_conn_int, UINT16 max_conn_int, - UINT16 slave_latency, UINT16 supervision_tout); - -/****************************************************************************** -** -** Function BTM_BleSetConnScanParams -** -** Description Set scan parameters used in BLE connection request -** -** Parameters: scan_interval - scan interval -** scan_window - scan window -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleSetConnScanParams (UINT32 scan_interval, UINT32 scan_window); - -/****************************************************************************** -** -** Function BTM_BleReadControllerFeatures -** -** Description Reads BLE specific controller features -** -** Parameters: tBTM_BLE_CTRL_FEATURES_CBACK : Callback to notify when features are read -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK *p_vsc_cback); - -/******************************************************************************* -** -** Function BTM_CheckAdvData -** -** Description This function is called to get ADV data for a specific type. -** -** Parameters p_adv - pointer of ADV data -** type - finding ADV data type -** p_length - return the length of ADV data not including type -** -** Returns pointer of ADV data -** -*******************************************************************************/ -//extern -UINT8 *BTM_CheckAdvData( UINT8 *p_adv, UINT8 type, UINT8 *p_length); - -/******************************************************************************* -** -** Function BTM_BleGetCurrentAddress -** -** Description This function is called to get local used BLE address. -** -** Parameters: None. -** -** Returns success or fail -** -*******************************************************************************/ -BOOLEAN BTM_BleGetCurrentAddress(BD_ADDR addr, uint8_t *addr_type); - -/******************************************************************************* -** -** Function BTM__BLEReadDiscoverability -** -** Description This function is called to read the current LE discoverability -** mode of the device. -** -** Returns BTM_BLE_NON_DISCOVERABLE ,BTM_BLE_LIMITED_DISCOVERABLE or -** BTM_BLE_GENRAL_DISCOVERABLE -** -*******************************************************************************/ -UINT16 BTM_BleReadDiscoverability(); - -/******************************************************************************* -** -** Function BTM__BLEReadConnectability -** -** Description This function is called to read the current LE connectibility -** mode of the device. -** -** Returns BTM_BLE_NON_CONNECTABLE or BTM_BLE_CONNECTABLE -** -*******************************************************************************/ -//extern -UINT16 BTM_BleReadConnectability (); - -void BTM_Recovery_Pre_State(void); - -/******************************************************************************* -** -** Function BTM_ReadDevInfo -** -** Description This function is called to read the device/address type -** of BD address. -** -** Parameter remote_bda: remote device address -** p_dev_type: output parameter to read the device type. -** p_addr_type: output parameter to read the address type. -** -*******************************************************************************/ -//extern -void BTM_ReadDevInfo (BD_ADDR remote_bda, tBT_DEVICE_TYPE *p_dev_type, - tBLE_ADDR_TYPE *p_addr_type); - - -/******************************************************************************* -** -** Function BTM_ReadConnectedTransportAddress -** -** Description This function is called to read the paired device/address type of other device paired -** corresponding to the BD_address -** -** Parameter remote_bda: remote device address, carry out the transport address -** transport: active transport -** -** Return TRUE if an active link is identified; FALSE otherwise -** -*******************************************************************************/ -//extern -BOOLEAN BTM_ReadConnectedTransportAddress(BD_ADDR remote_bda, - tBT_TRANSPORT transport); - -/******************************************************************************* -** -** Function BTM_BleBroadcast -** -** Description This function is to start or stop broadcasting. -** -** Parameters start: start or stop broadcasting. -** -** Returns status. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleBroadcast(BOOLEAN start, tBTM_START_STOP_ADV_CMPL_CBACK *p_stop_adv_cback); - -/******************************************************************************* -** -** Function BTM_BleConfigPrivacy -** -** Description This function is called to enable or disable the privacy in -** the local device. -** -** Parameters enable: TRUE to enable it; FALSE to disable it. -** -** Returns BOOLEAN privacy mode set success; otherwise failed. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BleConfigPrivacy(BOOLEAN enable, tBTM_SET_LOCAL_PRIVACY_CBACK *set_local_privacy_cabck); - -/******************************************************************************* -** -** Function BTM_BleLocalPrivacyEnabled -** -** Description Checks if local device supports private address -** -** Returns Return TRUE if local privacy is enabled else FALSE -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BleLocalPrivacyEnabled(void); - -/******************************************************************************* -** -** Function BTM_BleEnableMixedPrivacyMode -** -** Description This function is called to enabled Mixed mode if privacy 1.2 -** is applicable in controller. -** -** Parameters mixed_on: mixed mode to be used or not. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleEnableMixedPrivacyMode(BOOLEAN mixed_on); - -/******************************************************************************* -** -** Function BTM_BleMaxMultiAdvInstanceCount -** -** Description Returns max number of multi adv instances supported by controller -** -** Returns Max multi adv instance count -** -*******************************************************************************/ -//extern -UINT8 BTM_BleMaxMultiAdvInstanceCount(); - -/******************************************************************************* -** -** Function BTM_BleSetConnectableMode -** -** Description This function is called to set BLE connectable mode for a -** peripheral device. -** -** Parameters connectable_mode: directed connectable mode, or non-directed.It can -** be BTM_BLE_CONNECT_EVT, BTM_BLE_CONNECT_DIR_EVT or -** BTM_BLE_CONNECT_LO_DUTY_DIR_EVT -** -** Returns BTM_ILLEGAL_VALUE if controller does not support BLE. -** BTM_SUCCESS is status set successfully; otherwise failure. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleSetConnectableMode(tBTM_BLE_CONN_MODE connectable_mode); - -/******************************************************************************* -** -** Function BTM_BleTurnOnPrivacyOnRemote -** -** Description This function is called to enable or disable the privacy on the -** remote device. -** -** Parameters bd_addr: remote device address. -** privacy_on: TRUE to enable it; FALSE to disable it. -** -** Returns void -** -*******************************************************************************/ -//extern -void BTM_BleTurnOnPrivacyOnRemote(BD_ADDR bd_addr, - BOOLEAN privacy_on); - -/******************************************************************************* -** -** Function BTM_BleUpdateAdvWhitelist -** -** Description Add or remove device from advertising white list -** -** Returns void -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BleUpdateAdvWhitelist(BOOLEAN add_remove, BD_ADDR emote_bda, tBTM_ADD_WHITELIST_CBACK *add_wl_cb); - -/******************************************************************************* -** -** Function BTM_BleUpdateAdvFilterPolicy -** -** Description This function update the filter policy of advertiser. -** -** Parameter adv_policy: advertising filter policy -** -** Return void -*******************************************************************************/ -//extern -void BTM_BleUpdateAdvFilterPolicy(tBTM_BLE_AFP adv_policy); - -/******************************************************************************* -** -** Function BTM_BleReceiverTest -** -** Description This function is called to start the LE Receiver test -** -** Parameter rx_freq - Frequency Range -** p_cmd_cmpl_cback - Command Complete callback -** -*******************************************************************************/ -void BTM_BleReceiverTest(UINT8 rx_freq, tBTM_CMPL_CB *p_cmd_cmpl_cback); - - -/******************************************************************************* -** -** Function BTM_BleTransmitterTest -** -** Description This function is called to start the LE Transmitter test -** -** Parameter tx_freq - Frequency Range -** test_data_len - Length in bytes of payload data in each packet -** packet_payload - Pattern to use in the payload -** p_cmd_cmpl_cback - Command Complete callback -** -*******************************************************************************/ -void BTM_BleTransmitterTest(UINT8 tx_freq, UINT8 test_data_len, - UINT8 packet_payload, tBTM_CMPL_CB *p_cmd_cmpl_cback); - -/******************************************************************************* -** -** Function BTM_BleTestEnd -** -** Description This function is called to stop the in-progress TX or RX test -** -** Parameter p_cmd_cmpl_cback - Command complete callback -** -*******************************************************************************/ -void BTM_BleTestEnd(tBTM_CMPL_CB *p_cmd_cmpl_cback); - -/******************************************************************************* -** -** Function BTM_UseLeLink -** -** Description This function is to select the underneath physical link to use. -** -** Returns TRUE to use LE, FALSE use BR/EDR. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_UseLeLink (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTM_BleStackEnable -** -** Description Enable/Disable BLE functionality on stack regarless controller -** capability. -** -** Parameters: enable: TRUE to enable, FALSE to disable. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleStackEnable (BOOLEAN enable); - -/******************************************************************************* -** -** Function BTM_GetLeSecurityState -** -** Description This function is called to get security mode 1 flags and -** encryption key size for LE peer. -** -** Returns BOOLEAN TRUE if LE device is found, FALSE otherwise. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_GetLeSecurityState (BD_ADDR bd_addr, - UINT8 *p_le_dev_sec_flags, - UINT8 *p_le_key_size); - -/******************************************************************************* -** -** Function BTM_BleSecurityProcedureIsRunning -** -** Description This function indicates if LE security procedure is -** currently running with the peer. -** -** Returns BOOLEAN TRUE if security procedure is running, FALSE otherwise. -** -*******************************************************************************/ -//extern -BOOLEAN BTM_BleSecurityProcedureIsRunning (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function BTM_BleGetSupportedKeySize -** -** Description This function gets the maximum encryption key size in bytes -** the local device can suport. -** record. -** -** Returns the key size or 0 if the size can't be retrieved. -** -*******************************************************************************/ -//extern -UINT8 BTM_BleGetSupportedKeySize (BD_ADDR bd_addr); - -/*******************************************************************************/ -/* Multi ADV API */ -/******************************************************************************* -** -** Function BTM_BleEnableAdvInstance -** -** Description This function enable a Multi-ADV instance with the specified -** adv parameters -** -** Parameters p_params: pointer to the adv parameter structure, set as default -** adv parameter when the instance is enabled. -** p_cback: callback function for the adv instance. -** p_ref: reference data attach to the adv instance to be enabled. -** -** Returns status -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleEnableAdvInstance (tBTM_BLE_ADV_PARAMS *p_params, - tBTM_BLE_MULTI_ADV_CBACK *p_cback, - void *p_ref); - -/******************************************************************************* -** -** Function BTM_BleUpdateAdvInstParam -** -** Description This function update a Multi-ADV instance with the specififed -** adv parameters. -** -** Parameters inst_id: adv instance ID -** p_params: pointer to the adv parameter structure. -** -** Returns status -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleUpdateAdvInstParam (UINT8 inst_id, tBTM_BLE_ADV_PARAMS *p_params); - -/******************************************************************************* -** -** Function BTM_BleCfgAdvInstData -** -** Description This function configure a Multi-ADV instance with the specified -** adv data or scan response data. -** -** Parameters inst_id: adv instance ID -** is_scan_rsp: is this scacn response, if no set as adv data. -** data_mask: adv data mask. -** p_data: pointer to the adv data structure. -** -** Returns status -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleCfgAdvInstData (UINT8 inst_id, BOOLEAN is_scan_rsp, - tBTM_BLE_AD_MASK data_mask, - tBTM_BLE_ADV_DATA *p_data); - -/******************************************************************************* -** -** Function BTM_BleDisableAdvInstance -** -** Description This function disable a Multi-ADV instance. -** -** Parameters inst_id: adv instance ID -** -** Returns status -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleDisableAdvInstance (UINT8 inst_id); - -/******************************************************************************* -** -** Function BTM_BleAdvFilterParamSetup -** -** Description This function is called to setup the adv data payload filter -** condition. -** -** Parameters p_target: enabble the filter condition on a target device; if NULL -** enable the generic scan condition. -** enable: enable or disable the filter condition -** -** Returns void -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleAdvFilterParamSetup(int action, - tBTM_BLE_PF_FILT_INDEX filt_index, - tBTM_BLE_PF_FILT_PARAMS *p_filt_params, - tBLE_BD_ADDR *p_target, tBTM_BLE_PF_PARAM_CBACK *p_cmpl_cback, - tBTM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTM_BleCfgFilterCondition -** -** Description This function is called to configure the adv data payload filter -** condition. -** -** Parameters action: to read/write/clear -** cond_type: filter condition type. -** p_cond: filter condition paramter -** -** Returns tBTM_STATUS -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleCfgFilterCondition(tBTM_BLE_SCAN_COND_OP action, - tBTM_BLE_PF_COND_TYPE cond_type, - tBTM_BLE_PF_FILT_INDEX filt_index, - tBTM_BLE_PF_COND_PARAM *p_cond, - tBTM_BLE_PF_CFG_CBACK *p_cmpl_cback, - tBTM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTM_BleEnableDisableFilterFeature -** -** Description This function is called to enable or disable the APCF feature -** -** Parameters enable - TRUE - enables the APCF, FALSE - disables the APCF -** ref_value - Ref value -** -** Returns tBTM_STATUS -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleEnableDisableFilterFeature(UINT8 enable, - tBTM_BLE_PF_STATUS_CBACK *p_stat_cback, - tBTM_BLE_REF_VALUE ref_value); - -/******************************************************************************* -** -** Function BTM_BleGetEnergyInfo -** -** Description This function obtains the energy info -** -** Parameters p_ener_cback - Callback pointer -** -** Returns status -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_BleGetEnergyInfo(tBTM_BLE_ENERGY_INFO_CBACK *p_ener_cback); - -/******************************************************************************* -** -** Function BTM_SetBleDataLength -** -** Description This function is called to set maximum BLE transmission packet size -** -** Returns BTM_SUCCESS if success; otherwise failed. -** -*******************************************************************************/ -//extern -tBTM_STATUS BTM_SetBleDataLength(BD_ADDR bd_addr, UINT16 tx_pdu_length); - -/* -#ifdef __cplusplus -} -#endif -*/ - -#endif diff --git a/tools/sdk/include/bluedroid/btm_ble_int.h b/tools/sdk/include/bluedroid/btm_ble_int.h deleted file mode 100644 index e1f8f400d3a..00000000000 --- a/tools/sdk/include/bluedroid/btm_ble_int.h +++ /dev/null @@ -1,497 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * this file contains the main Bluetooth Manager (BTM) internal - * definitions. - * - ******************************************************************************/ - -#ifndef BTM_BLE_INT_H -#define BTM_BLE_INT_H - -#include "bt_target.h" -#include "fixed_queue.h" -#include "hcidefs.h" -#include "btm_ble_api.h" -#include "btm_int.h" - -#if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE -#include "smp_api.h" -#endif - - -/* scanning enable status */ -#define BTM_BLE_SCAN_ENABLE 0x01 -#define BTM_BLE_SCAN_DISABLE 0x00 - -/* advertising enable status */ -#define BTM_BLE_ADV_ENABLE 0x01 -#define BTM_BLE_ADV_DISABLE 0x00 - -/* use the high 4 bits unused by inquiry mode */ -#define BTM_BLE_SELECT_SCAN 0x20 -#define BTM_BLE_NAME_REQUEST 0x40 -#define BTM_BLE_OBSERVE 0x80 - -#define BTM_BLE_MAX_WL_ENTRY 1 -#define BTM_BLE_AD_DATA_LEN 31 - -#define BTM_BLE_ENC_MASK 0x03 - -#define BTM_BLE_DUPLICATE_ENABLE 1 -#define BTM_BLE_DUPLICATE_DISABLE 0 - -#define BTM_BLE_GAP_DISC_SCAN_INT 18 /* Interval(scan_int) = 11.25 ms= 0x0010 * 0.625 ms */ -#define BTM_BLE_GAP_DISC_SCAN_WIN 18 /* scan_window = 11.25 ms= 0x0010 * 0.625 ms */ -#define BTM_BLE_GAP_ADV_INT 512 /* Tgap(gen_disc) = 1.28 s= 512 * 0.625 ms */ -#define BTM_BLE_GAP_LIM_TOUT 180 /* Tgap(lim_timeout) = 180s max */ -#define BTM_BLE_LOW_LATENCY_SCAN_INT 8000 /* Interval(scan_int) = 5s= 8000 * 0.625 ms */ -#define BTM_BLE_LOW_LATENCY_SCAN_WIN 8000 /* scan_window = 5s= 8000 * 0.625 ms */ - - -#define BTM_BLE_GAP_ADV_FAST_INT_1 48 /* TGAP(adv_fast_interval1) = 30(used) ~ 60 ms = 48 *0.625 */ -#define BTM_BLE_GAP_ADV_FAST_INT_2 160 /* TGAP(adv_fast_interval2) = 100(used) ~ 150 ms = 160 * 0.625 ms */ -#define BTM_BLE_GAP_ADV_SLOW_INT 2048 /* Tgap(adv_slow_interval) = 1.28 s= 512 * 0.625 ms */ -#define BTM_BLE_GAP_ADV_DIR_MAX_INT 800 /* Tgap(dir_conn_adv_int_max) = 500 ms = 800 * 0.625 ms */ -#define BTM_BLE_GAP_ADV_DIR_MIN_INT 400 /* Tgap(dir_conn_adv_int_min) = 250 ms = 400 * 0.625 ms */ - -#define BTM_BLE_GAP_FAST_ADV_TOUT 30 - -#define BTM_BLE_SEC_REQ_ACT_NONE 0 -#define BTM_BLE_SEC_REQ_ACT_ENCRYPT 1 /* encrypt the link using current key or key refresh */ -#define BTM_BLE_SEC_REQ_ACT_PAIR 2 -#define BTM_BLE_SEC_REQ_ACT_DISCARD 3 /* discard the sec request while encryption is started but not completed */ -typedef UINT8 tBTM_BLE_SEC_REQ_ACT; - -#define BLE_STATIC_PRIVATE_MSB_MASK 0x3f -#define BLE_RESOLVE_ADDR_MSB 0x40 /* most significant bit, bit7, bit6 is 01 to be resolvable random */ -#define BLE_RESOLVE_ADDR_MASK 0xc0 /* bit 6, and bit7 */ -#define BTM_BLE_IS_RESOLVE_BDA(x) ((x[0] & BLE_RESOLVE_ADDR_MASK) == BLE_RESOLVE_ADDR_MSB) - -/* LE scan activity bit mask, continue with LE inquiry bits */ -#define BTM_LE_SELECT_CONN_ACTIVE 0x0040 /* selection connection is in progress */ -#define BTM_LE_OBSERVE_ACTIVE 0x0080 /* observe is in progress */ -#define BTM_LE_DISCOVER_ACTIVE 0x0100 /* scan is in progress */ - -/* BLE scan activity mask checking */ -#define BTM_BLE_IS_SCAN_ACTIVE(x) ((x) & BTM_BLE_SCAN_ACTIVE_MASK) -#define BTM_BLE_IS_INQ_ACTIVE(x) ((x) & BTM_BLE_INQUIRY_MASK) -#define BTM_BLE_IS_OBS_ACTIVE(x) ((x) & BTM_LE_OBSERVE_ACTIVE) -#define BTM_BLE_IS_DISCO_ACTIVE(x) ((x) & BTM_LE_DISCOVER_ACTIVE) -#define BTM_BLE_IS_SEL_CONN_ACTIVE(x) ((x) & BTM_LE_SELECT_CONN_ACTIVE) - -/* BLE ADDR type ID bit */ -#define BLE_ADDR_TYPE_ID_BIT 0x02 - -#define BTM_VSC_CHIP_CAPABILITY_L_VERSION 55 -#define BTM_VSC_CHIP_CAPABILITY_M_VERSION 95 - -typedef enum { - BTM_BLE_IDLE, - BTM_BLE_SCANNING, - BTM_BLE_SCAN_PENDING, - BTM_BLE_STOP_SCAN, - BTM_BLE_ADVERTISING, - BTM_BLE_ADV_PENDING, - BTM_BLE_STOP_ADV, -}tBTM_BLE_GAP_STATE; - -typedef struct { - UINT16 data_mask; - UINT8 *p_flags; - UINT8 ad_data[BTM_BLE_AD_DATA_LEN]; - UINT8 *p_pad; -} tBTM_BLE_LOCAL_ADV_DATA; - -typedef struct { - UINT32 inq_count; /* Used for determining if a response has already been */ - /* received for the current inquiry operation. (We do not */ - /* want to flood the caller with multiple responses from */ - /* the same device. */ - BOOLEAN scan_rsp; - tBLE_BD_ADDR le_bda; -} tINQ_LE_BDADDR; - -#define BTM_BLE_ADV_DATA_LEN_MAX 31 -#define BTM_BLE_CACHE_ADV_DATA_MAX 62 - -#define BTM_BLE_ISVALID_PARAM(x, min, max) (((x) >= (min) && (x) <= (max)) || ((x) == BTM_BLE_CONN_PARAM_UNDEF)) - -#define BTM_BLE_PRIVATE_ADDR_INT 900 /* 15 minutes minimum for random address refreshing */ - -typedef struct { - UINT16 discoverable_mode; - UINT16 connectable_mode; - BOOLEAN scan_params_set; - UINT32 scan_window; - UINT32 scan_interval; - UINT8 scan_type; /* current scan type: active or passive */ - UINT8 scan_duplicate_filter; /* duplicate filter enabled for scan */ - UINT16 adv_interval_min; - UINT16 adv_interval_max; - tBTM_BLE_AFP afp; /* advertising filter policy */ - tBTM_BLE_SFP sfp; /* scanning filter policy */ - tBTM_START_ADV_CMPL_CBACK *p_adv_cb; - tBTM_START_STOP_ADV_CMPL_CBACK *p_stop_adv_cb; - tBLE_ADDR_TYPE adv_addr_type; - BOOLEAN adv_callback_twice; - UINT8 evt_type; - UINT8 adv_mode; - tBLE_BD_ADDR direct_bda; - tBTM_BLE_EVT directed_conn; - BOOLEAN fast_adv_on; - TIMER_LIST_ENT fast_adv_timer; - - UINT8 adv_len; - UINT8 adv_data_cache[BTM_BLE_CACHE_ADV_DATA_MAX]; - - /* inquiry BD addr database */ - UINT8 num_bd_entries; - UINT8 max_bd_entries; - tBTM_BLE_LOCAL_ADV_DATA adv_data; - tBTM_BLE_ADV_CHNL_MAP adv_chnl_map; - - TIMER_LIST_ENT inq_timer_ent; - BOOLEAN scan_rsp; - tBTM_BLE_GAP_STATE state; /* Current state that the inquiry process is in */ - INT8 tx_power; -} tBTM_BLE_INQ_CB; - - -/* random address resolving complete callback */ -typedef void (tBTM_BLE_RESOLVE_CBACK) (void *match_rec, void *p); - -typedef void (tBTM_BLE_ADDR_CBACK) (BD_ADDR_PTR static_random, void *p); - -/* random address management control block */ -typedef struct { - tBLE_ADDR_TYPE own_addr_type; /* local device LE address type */ - BD_ADDR private_addr; - BD_ADDR random_bda; - BOOLEAN busy; - UINT16 index; - tBTM_BLE_RESOLVE_CBACK *p_resolve_cback; - tBTM_BLE_ADDR_CBACK *p_generate_cback; - void *p; - TIMER_LIST_ENT raddr_timer_ent; - tBTM_SET_LOCAL_PRIVACY_CBACK *set_local_privacy_cback; -} tBTM_LE_RANDOM_CB; - -#define BTM_BLE_MAX_BG_CONN_DEV_NUM 10 - -typedef struct { - UINT16 min_conn_int; - UINT16 max_conn_int; - UINT16 slave_latency; - UINT16 supervision_tout; - -} tBTM_LE_CONN_PRAMS; - - -typedef struct { - BD_ADDR bd_addr; - UINT8 attr; - BOOLEAN is_connected; - BOOLEAN in_use; -} tBTM_LE_BG_CONN_DEV; - -/* white list using state as a bit mask */ -#define BTM_BLE_WL_IDLE 0 -#define BTM_BLE_WL_INIT 1 -#define BTM_BLE_WL_SCAN 2 -#define BTM_BLE_WL_ADV 4 -typedef UINT8 tBTM_BLE_WL_STATE; - -/* resolving list using state as a bit mask */ -#define BTM_BLE_RL_IDLE 0 -#define BTM_BLE_RL_INIT 1 -#define BTM_BLE_RL_SCAN 2 -#define BTM_BLE_RL_ADV 4 -typedef UINT8 tBTM_BLE_RL_STATE; - -/* BLE connection state */ -#define BLE_CONN_IDLE 0 -#define BLE_DIR_CONN 1 -#define BLE_BG_CONN 2 -#define BLE_CONN_CANCEL 3 -typedef UINT8 tBTM_BLE_CONN_ST; - -typedef struct { - void *p_param; -} tBTM_BLE_CONN_REQ; - -/* LE state request */ -#define BTM_BLE_STATE_INVALID 0 -#define BTM_BLE_STATE_CONN_ADV 1 -#define BTM_BLE_STATE_INIT 2 -#define BTM_BLE_STATE_MASTER 3 -#define BTM_BLE_STATE_SLAVE 4 -#define BTM_BLE_STATE_LO_DUTY_DIR_ADV 5 -#define BTM_BLE_STATE_HI_DUTY_DIR_ADV 6 -#define BTM_BLE_STATE_NON_CONN_ADV 7 -#define BTM_BLE_STATE_PASSIVE_SCAN 8 -#define BTM_BLE_STATE_ACTIVE_SCAN 9 -#define BTM_BLE_STATE_SCAN_ADV 10 -#define BTM_BLE_STATE_MAX 11 -typedef UINT8 tBTM_BLE_STATE; - -#define BTM_BLE_STATE_CONN_ADV_BIT 0x0001 -#define BTM_BLE_STATE_INIT_BIT 0x0002 -#define BTM_BLE_STATE_MASTER_BIT 0x0004 -#define BTM_BLE_STATE_SLAVE_BIT 0x0008 -#define BTM_BLE_STATE_LO_DUTY_DIR_ADV_BIT 0x0010 -#define BTM_BLE_STATE_HI_DUTY_DIR_ADV_BIT 0x0020 -#define BTM_BLE_STATE_NON_CONN_ADV_BIT 0x0040 -#define BTM_BLE_STATE_PASSIVE_SCAN_BIT 0x0080 -#define BTM_BLE_STATE_ACTIVE_SCAN_BIT 0x0100 -#define BTM_BLE_STATE_SCAN_ADV_BIT 0x0200 -typedef UINT16 tBTM_BLE_STATE_MASK; - -#define BTM_BLE_STATE_ALL_MASK 0x03ff -#define BTM_BLE_STATE_ALL_ADV_MASK (BTM_BLE_STATE_CONN_ADV_BIT|BTM_BLE_STATE_LO_DUTY_DIR_ADV_BIT|BTM_BLE_STATE_HI_DUTY_DIR_ADV_BIT|BTM_BLE_STATE_SCAN_ADV_BIT) -#define BTM_BLE_STATE_ALL_SCAN_MASK (BTM_BLE_STATE_PASSIVE_SCAN_BIT|BTM_BLE_STATE_ACTIVE_SCAN_BIT) -#define BTM_BLE_STATE_ALL_CONN_MASK (BTM_BLE_STATE_MASTER_BIT|BTM_BLE_STATE_SLAVE_BIT) - -#ifndef BTM_LE_RESOLVING_LIST_MAX -#define BTM_LE_RESOLVING_LIST_MAX 0x20 -#endif - -typedef struct { - BD_ADDR *resolve_q_random_pseudo; - UINT8 *resolve_q_action; - UINT8 q_next; - UINT8 q_pending; -} tBTM_BLE_RESOLVE_Q; - -typedef struct { - BOOLEAN in_use; - BOOLEAN to_add; - BD_ADDR bd_addr; - UINT8 attr; -} tBTM_BLE_WL_OP; - -/* BLE privacy mode */ -#define BTM_PRIVACY_NONE 0 /* BLE no privacy */ -#define BTM_PRIVACY_1_1 1 /* BLE privacy 1.1, do not support privacy 1.0 */ -#define BTM_PRIVACY_1_2 2 /* BLE privacy 1.2 */ -#define BTM_PRIVACY_MIXED 3 /* BLE privacy mixed mode, broadcom propietary mode */ -typedef UINT8 tBTM_PRIVACY_MODE; - -/* data length change event callback */ -typedef void (tBTM_DATA_LENGTH_CHANGE_CBACK) (UINT16 max_tx_length, UINT16 max_rx_length); - -/* Define BLE Device Management control structure -*/ -typedef struct { - UINT16 scan_activity; /* LE scan activity mask */ - - /***************************************************** - ** BLE Inquiry - *****************************************************/ - tBTM_BLE_INQ_CB inq_var; - - /* observer callback and timer */ - tBTM_INQ_RESULTS_CB *p_obs_results_cb; - tBTM_CMPL_CB *p_obs_cmpl_cb; - TIMER_LIST_ENT obs_timer_ent; - - /* scan callback and timer */ - tBTM_INQ_RESULTS_CB *p_scan_results_cb; - tBTM_CMPL_CB *p_scan_cmpl_cb; - TIMER_LIST_ENT scan_timer_ent; - - /* background connection procedure cb value */ - tBTM_BLE_CONN_TYPE bg_conn_type; - UINT32 scan_int; - UINT32 scan_win; - tBTM_BLE_SEL_CBACK *p_select_cback; - /* white list information */ - UINT8 white_list_avail_size; - tBTM_ADD_WHITELIST_CBACK *add_wl_cb; - tBTM_BLE_WL_STATE wl_state; - - fixed_queue_t *conn_pending_q; - tBTM_BLE_CONN_ST conn_state; - - /* random address management control block */ - tBTM_LE_RANDOM_CB addr_mgnt_cb; - - BOOLEAN enabled; - -#if BLE_PRIVACY_SPT == TRUE - BOOLEAN mixed_mode; /* privacy 1.2 mixed mode is on or not */ - tBTM_PRIVACY_MODE privacy_mode; /* privacy mode */ - UINT8 resolving_list_avail_size; /* resolving list available size */ - tBTM_BLE_RESOLVE_Q resolving_list_pend_q; /* Resolving list queue */ - tBTM_BLE_RL_STATE suspended_rl_state; /* Suspended resolving list state */ - UINT8 *irk_list_mask; /* IRK list availability mask, up to max entry bits */ - tBTM_BLE_RL_STATE rl_state; /* Resolving list state */ -#endif - - tBTM_BLE_WL_OP wl_op_q[BTM_BLE_MAX_BG_CONN_DEV_NUM]; - - /* current BLE link state */ - tBTM_BLE_STATE_MASK cur_states; /* bit mask of tBTM_BLE_STATE */ - UINT8 link_count[2]; /* total link count master and slave*/ -} tBTM_BLE_CB; - -#ifdef __cplusplus -extern "C" { -#endif - -void btm_ble_timeout(TIMER_LIST_ENT *p_tle); -void btm_ble_process_adv_pkt (UINT8 *p); -void btm_ble_proc_scan_rsp_rpt (UINT8 *p); -tBTM_STATUS btm_ble_read_remote_name(BD_ADDR remote_bda, tBTM_INQ_INFO *p_cur, tBTM_CMPL_CB *p_cb); -BOOLEAN btm_ble_cancel_remote_name(BD_ADDR remote_bda); - -tBTM_STATUS btm_ble_set_discoverability(UINT16 combined_mode); -tBTM_STATUS btm_ble_set_connectability(UINT16 combined_mode); -tBTM_STATUS btm_ble_start_inquiry (UINT8 mode, UINT8 duration); -void btm_ble_stop_scan(void); -void btm_clear_all_pending_le_entry(void); - -BOOLEAN btm_ble_send_extended_scan_params(UINT8 scan_type, UINT32 scan_int, - UINT32 scan_win, UINT8 addr_type_own, - UINT8 scan_filter_policy); -void btm_ble_stop_inquiry(void); -void btm_ble_init (void); -void btm_ble_free (void); -void btm_ble_connected (UINT8 *bda, UINT16 handle, UINT8 enc_mode, UINT8 role, tBLE_ADDR_TYPE addr_type, BOOLEAN addr_matched); -void btm_ble_read_remote_features_complete(UINT8 *p); -void btm_ble_write_adv_enable_complete(UINT8 *p); -void btm_ble_conn_complete(UINT8 *p, UINT16 evt_len, BOOLEAN enhanced); -void btm_read_ble_local_supported_states_complete(UINT8 *p, UINT16 evt_len); -tBTM_BLE_CONN_ST btm_ble_get_conn_st(void); -void btm_ble_set_conn_st(tBTM_BLE_CONN_ST new_st); -UINT8 *btm_ble_build_adv_data(tBTM_BLE_AD_MASK *p_data_mask, UINT8 **p_dst, - tBTM_BLE_ADV_DATA *p_data); -tBTM_STATUS btm_ble_start_adv(void); -tBTM_STATUS btm_ble_stop_adv(void); -tBTM_STATUS btm_ble_start_scan(void); -void btm_ble_create_ll_conn_complete (UINT8 status); - -/* LE security function from btm_sec.c */ -#if SMP_INCLUDED == TRUE -void btm_ble_link_sec_check(BD_ADDR bd_addr, tBTM_LE_AUTH_REQ auth_req, tBTM_BLE_SEC_REQ_ACT *p_sec_req_act); -void btm_ble_ltk_request_reply(BD_ADDR bda, BOOLEAN use_stk, BT_OCTET16 stk); -UINT8 btm_proc_smp_cback(tSMP_EVT event, BD_ADDR bd_addr, tSMP_EVT_DATA *p_data); -tBTM_STATUS btm_ble_set_encryption (BD_ADDR bd_addr, void *p_ref_data, UINT8 link_role); -void btm_ble_ltk_request(UINT16 handle, UINT8 rand[8], UINT16 ediv); -tBTM_STATUS btm_ble_start_encrypt(BD_ADDR bda, BOOLEAN use_stk, BT_OCTET16 stk); -void btm_ble_link_encrypted(BD_ADDR bd_addr, UINT8 encr_enable); -#endif - -/* LE device management functions */ -void btm_ble_reset_id( void ); - -/* security related functions */ -void btm_ble_increment_sign_ctr(BD_ADDR bd_addr, BOOLEAN is_local ); -BOOLEAN btm_get_local_div (BD_ADDR bd_addr, UINT16 *p_div); -BOOLEAN btm_ble_get_enc_key_type(BD_ADDR bd_addr, UINT8 *p_key_types); - -void btm_ble_test_command_complete(UINT8 *p); -void btm_ble_rand_enc_complete (UINT8 *p, UINT16 op_code, tBTM_RAND_ENC_CB *p_enc_cplt_cback); - -void btm_sec_save_le_key(BD_ADDR bd_addr, tBTM_LE_KEY_TYPE key_type, tBTM_LE_KEY_VALUE *p_keys, BOOLEAN pass_to_application); -void btm_ble_update_sec_key_size(BD_ADDR bd_addr, UINT8 enc_key_size); -UINT8 btm_ble_read_sec_key_size(BD_ADDR bd_addr); - -/* white list function */ -BOOLEAN btm_update_dev_to_white_list(BOOLEAN to_add, BD_ADDR bd_addr, tBTM_ADD_WHITELIST_CBACK *add_wl_cb); -void btm_update_scanner_filter_policy(tBTM_BLE_SFP scan_policy); -void btm_update_adv_filter_policy(tBTM_BLE_AFP adv_policy); -void btm_ble_clear_white_list (void); -void btm_read_white_list_size_complete(UINT8 *p, UINT16 evt_len); -void btm_ble_add_2_white_list_complete(UINT8 status); -void btm_ble_remove_from_white_list_complete(UINT8 *p, UINT16 evt_len); -void btm_ble_clear_white_list_complete(UINT8 *p, UINT16 evt_len); -void btm_ble_white_list_init(UINT8 white_list_size); - -/* background connection function */ -BOOLEAN btm_ble_suspend_bg_conn(void); -BOOLEAN btm_ble_resume_bg_conn(void); -void btm_ble_initiate_select_conn(BD_ADDR bda); -BOOLEAN btm_ble_start_auto_conn(BOOLEAN start); -BOOLEAN btm_ble_start_select_conn(BOOLEAN start, tBTM_BLE_SEL_CBACK *p_select_cback); -BOOLEAN btm_ble_renew_bg_conn_params(BOOLEAN add, BD_ADDR bd_addr); -void btm_write_dir_conn_wl(BD_ADDR target_addr); -void btm_ble_update_mode_operation(UINT8 link_role, BD_ADDR bda, UINT8 status); -BOOLEAN btm_execute_wl_dev_operation(void); -void btm_ble_update_link_topology_mask(UINT8 role, BOOLEAN increase); - -/* direct connection utility */ -BOOLEAN btm_send_pending_direct_conn(void); -void btm_ble_enqueue_direct_conn_req(void *p_param); - -/* BLE address management */ -void btm_gen_resolvable_private_addr (void *p_cmd_cplt_cback); -void btm_gen_non_resolvable_private_addr (tBTM_BLE_ADDR_CBACK *p_cback, void *p); -void btm_ble_resolve_random_addr(BD_ADDR random_bda, tBTM_BLE_RESOLVE_CBACK *p_cback, void *p); -void btm_gen_resolve_paddr_low(tBTM_RAND_ENC *p); - -/* privacy function */ -#if (defined BLE_PRIVACY_SPT && BLE_PRIVACY_SPT == TRUE) -/* BLE address mapping with CS feature */ -BOOLEAN btm_identity_addr_to_random_pseudo(BD_ADDR bd_addr, UINT8 *p_addr_type, BOOLEAN refresh); -BOOLEAN btm_random_pseudo_to_identity_addr(BD_ADDR random_pseudo, UINT8 *p_static_addr_type); -void btm_ble_refresh_peer_resolvable_private_addr(BD_ADDR pseudo_bda, BD_ADDR rra, UINT8 rra_type); -void btm_ble_refresh_local_resolvable_private_addr(BD_ADDR pseudo_addr, BD_ADDR local_rpa); -void btm_ble_read_resolving_list_entry_complete(UINT8 *p, UINT16 evt_len) ; -void btm_ble_remove_resolving_list_entry_complete(UINT8 *p, UINT16 evt_len); -void btm_ble_add_resolving_list_entry_complete(UINT8 *p, UINT16 evt_len); -void btm_ble_clear_resolving_list_complete(UINT8 *p, UINT16 evt_len); -void btm_read_ble_resolving_list_size_complete (UINT8 *p, UINT16 evt_len); -void btm_ble_enable_resolving_list(UINT8); -BOOLEAN btm_ble_disable_resolving_list(UINT8 rl_mask, BOOLEAN to_resume); -void btm_ble_enable_resolving_list_for_platform (UINT8 rl_mask); -void btm_ble_resolving_list_init(UINT8 max_irk_list_sz); -void btm_ble_resolving_list_cleanup(void); -#endif - -void btm_ble_multi_adv_configure_rpa (tBTM_BLE_MULTI_ADV_INST *p_inst); -void btm_ble_multi_adv_init(void); -void *btm_ble_multi_adv_get_ref(UINT8 inst_id); -void btm_ble_multi_adv_cleanup(void); -void btm_ble_multi_adv_reenable(UINT8 inst_id); -void btm_ble_multi_adv_enb_privacy(BOOLEAN enable); -char btm_ble_map_adv_tx_power(int tx_power_index); -void btm_ble_batchscan_init(void); -void btm_ble_batchscan_cleanup(void); -void btm_ble_adv_filter_init(void); -void btm_ble_adv_filter_cleanup(void); -BOOLEAN btm_ble_topology_check(tBTM_BLE_STATE_MASK request); -BOOLEAN btm_ble_clear_topology_mask(tBTM_BLE_STATE_MASK request_state); -BOOLEAN btm_ble_set_topology_mask(tBTM_BLE_STATE_MASK request_state); - -#if BTM_BLE_CONFORMANCE_TESTING == TRUE -void btm_ble_set_no_disc_if_pair_fail (BOOLEAN disble_disc); -void btm_ble_set_test_mac_value (BOOLEAN enable, UINT8 *p_test_mac_val); -void btm_ble_set_test_local_sign_cntr_value(BOOLEAN enable, UINT32 test_local_sign_cntr); -void btm_set_random_address(BD_ADDR random_bda); -void btm_ble_set_keep_rfu_in_auth_req(BOOLEAN keep_rfu); -#endif - -/* -#ifdef __cplusplus -} -#endif -*/ -#endif diff --git a/tools/sdk/include/bluedroid/btm_int.h b/tools/sdk/include/bluedroid/btm_int.h deleted file mode 100644 index 79a10cf7141..00000000000 --- a/tools/sdk/include/bluedroid/btm_int.h +++ /dev/null @@ -1,1136 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * this file contains the main Bluetooth Manager (BTM) internal - * definitions. - * - ******************************************************************************/ -#ifndef BTM_INT_H -#define BTM_INT_H - -#include "bt_defs.h" -#include "bt_target.h" -#include "hcidefs.h" - -#include "rfcdefs.h" - -#include "btm_api.h" - -#if (BLE_INCLUDED == TRUE) -#include "btm_ble_int.h" -#if (SMP_INCLUDED == TRUE) -#include "smp_api.h" -#endif -#endif - -#if BTM_MAX_LOC_BD_NAME_LEN > 0 -typedef char tBTM_LOC_BD_NAME[BTM_MAX_LOC_BD_NAME_LEN + 1]; -#endif - -#define BTM_ACL_IS_CONNECTED(bda) (btm_bda_to_acl (bda, BT_TRANSPORT_BR_EDR) != NULL) - -/* Definitions for Server Channel Number (SCN) management -*/ -#define BTM_MAX_SCN PORT_MAX_RFC_PORTS - -/* Define masks for supported and exception 2.0 ACL packet types -*/ -#define BTM_ACL_SUPPORTED_PKTS_MASK (HCI_PKT_TYPES_MASK_DM1 | \ - HCI_PKT_TYPES_MASK_DH1 | \ - HCI_PKT_TYPES_MASK_DM3 | \ - HCI_PKT_TYPES_MASK_DH3 | \ - HCI_PKT_TYPES_MASK_DM5 | \ - HCI_PKT_TYPES_MASK_DH5) - -#define BTM_ACL_EXCEPTION_PKTS_MASK (HCI_PKT_TYPES_MASK_NO_2_DH1 | \ - HCI_PKT_TYPES_MASK_NO_3_DH1 | \ - HCI_PKT_TYPES_MASK_NO_2_DH3 | \ - HCI_PKT_TYPES_MASK_NO_3_DH3 | \ - HCI_PKT_TYPES_MASK_NO_2_DH5 | \ - HCI_PKT_TYPES_MASK_NO_3_DH5) - -#define BTM_EPR_AVAILABLE(p) ((HCI_ATOMIC_ENCRYPT_SUPPORTED((p)->peer_lmp_features[HCI_EXT_FEATURES_PAGE_0]) && \ - HCI_ATOMIC_ENCRYPT_SUPPORTED(controller_get_interface()->get_features_classic(0)->as_array)) \ - ? TRUE : FALSE) - -#define BTM_IS_BRCM_CONTROLLER() (controller_get_interface()->get_bt_version()->manufacturer == LMP_COMPID_BROADCOM) - -/* Define the ACL Management control structure -*/ -typedef struct { -UINT16 hci_handle; -UINT16 pkt_types_mask; -UINT16 clock_offset; -BD_ADDR remote_addr; -DEV_CLASS remote_dc; -BD_NAME remote_name; - -UINT16 manufacturer; -UINT16 lmp_subversion; -UINT16 link_super_tout; -BD_FEATURES peer_lmp_features[HCI_EXT_FEATURES_PAGE_MAX + 1]; /* Peer LMP Extended features mask table for the device */ -UINT8 num_read_pages; -UINT8 lmp_version; - -BOOLEAN in_use; -UINT8 link_role; -BOOLEAN link_up_issued; /* True if busy_level link up has been issued */ - -#define BTM_ACL_SWKEY_STATE_IDLE 0 -#define BTM_ACL_SWKEY_STATE_MODE_CHANGE 1 -#define BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF 2 -#define BTM_ACL_SWKEY_STATE_SWITCHING 3 -#define BTM_ACL_SWKEY_STATE_ENCRYPTION_ON 4 -#define BTM_ACL_SWKEY_STATE_IN_PROGRESS 5 -UINT8 switch_role_state; - -#define BTM_ACL_ENCRYPT_STATE_IDLE 0 -#define BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF 1 /* encryption turning off */ -#define BTM_ACL_ENCRYPT_STATE_TEMP_FUNC 2 /* temporarily off for change link key or role switch */ -#define BTM_ACL_ENCRYPT_STATE_ENCRYPT_ON 3 /* encryption turning on */ -UINT8 encrypt_state; /* overall BTM encryption state */ - -#if BLE_INCLUDED == TRUE -tBT_TRANSPORT transport; -BD_ADDR conn_addr; /* local device address used for this connection */ -UINT8 conn_addr_type; /* local device address type for this connection */ -BD_ADDR active_remote_addr; /* remote address used on this connection */ -UINT8 active_remote_addr_type; /* local device address type for this connection */ -BD_FEATURES peer_le_features; /* Peer LE Used features mask for the device */ -tBTM_SET_PKT_DATA_LENGTH_CBACK *p_set_pkt_data_cback; -tBTM_LE_SET_PKT_DATA_LENGTH_PARAMS data_length_params; -#endif - -} tACL_CONN; - -/***************************************************** -** TIMER Definitions -******************************************************/ -#define TT_DEV_RESET 1 -#define TT_DEV_RLN 2 -#define TT_DEV_RLNKP 4 /* Read Link Policy Settings */ - -/* Define the Device Management control structure -*/ -typedef struct { -tBTM_DEV_STATUS_CB *p_dev_status_cb; /* Device status change callback */ -tBTM_VS_EVT_CB *p_vend_spec_cb[BTM_MAX_VSE_CALLBACKS]; /* Register for vendor specific events */ - -tBTM_CMPL_CB *p_stored_link_key_cmpl_cb; /* Read/Write/Delete stored link key */ - -TIMER_LIST_ENT reset_timer; -tBTM_CMPL_CB *p_reset_cmpl_cb; - -TIMER_LIST_ENT rln_timer; -tBTM_CMPL_CB *p_rln_cmpl_cb; /* Callback function to be called when */ -/* read local name function complete */ -TIMER_LIST_ENT rssi_timer; -tBTM_CMPL_CB *p_rssi_cmpl_cb; /* Callback function to be called when */ -/* read rssi function completes */ -TIMER_LIST_ENT lnk_quality_timer; -tBTM_CMPL_CB *p_lnk_qual_cmpl_cb;/* Callback function to be called when */ -/* read link quality function completes */ -TIMER_LIST_ENT txpwer_timer; -tBTM_CMPL_CB *p_txpwer_cmpl_cb; /* Callback function to be called when */ -/* read inq tx power function completes */ - -TIMER_LIST_ENT qossu_timer; -tBTM_CMPL_CB *p_qossu_cmpl_cb; /* Callback function to be called when */ -/* qos setup function completes */ - -tBTM_ROLE_SWITCH_CMPL switch_role_ref_data; -tBTM_CMPL_CB *p_switch_role_cb; /* Callback function to be called when */ -/* requested switch role is completed */ - -TIMER_LIST_ENT tx_power_timer; -tBTM_CMPL_CB *p_tx_power_cmpl_cb;/* Callback function to be called */ - -DEV_CLASS dev_class; /* Local device class */ - -#if BLE_INCLUDED == TRUE - -tBTM_CMPL_CB *p_le_test_cmd_cmpl_cb; /* Callback function to be called when - LE test mode command has been sent successfully */ - -BD_ADDR read_tx_pwr_addr; /* read TX power target address */ - -#define BTM_LE_SUPPORT_STATE_SIZE 8 -UINT8 le_supported_states[BTM_LE_SUPPORT_STATE_SIZE]; - -tBTM_BLE_LOCAL_ID_KEYS id_keys; /* local BLE ID keys */ -BT_OCTET16 ble_encryption_key_value; /* BLE encryption key */ - -#if BTM_BLE_CONFORMANCE_TESTING == TRUE -BOOLEAN no_disc_if_pair_fail; -BOOLEAN enable_test_mac_val; -BT_OCTET8 test_mac; -BOOLEAN enable_test_local_sign_cntr; -UINT32 test_local_sign_cntr; -#endif - -#endif /* BLE_INCLUDED */ - -tBTM_IO_CAP loc_io_caps; /* IO capability of the local device */ -tBTM_AUTH_REQ loc_auth_req; /* the auth_req flag */ -BOOLEAN secure_connections_only; /* Rejects service level 0 connections if */ -/* itself or peer device doesn't support */ -/* secure connections */ -} tBTM_DEVCB; - - -/* Define the structures and constants used for inquiry -*/ - -/* Definitions of limits for inquiries */ -#define BTM_PER_INQ_MIN_MAX_PERIOD HCI_PER_INQ_MIN_MAX_PERIOD -#define BTM_PER_INQ_MAX_MAX_PERIOD HCI_PER_INQ_MAX_MAX_PERIOD -#define BTM_PER_INQ_MIN_MIN_PERIOD HCI_PER_INQ_MIN_MIN_PERIOD -#define BTM_PER_INQ_MAX_MIN_PERIOD HCI_PER_INQ_MAX_MIN_PERIOD -#define BTM_MAX_INQUIRY_LENGTH HCI_MAX_INQUIRY_LENGTH -#define BTM_MIN_INQUIRY_LEN 0x01 - -#define BTM_MIN_INQ_TX_POWER -70 -#define BTM_MAX_INQ_TX_POWER 20 - -typedef struct { -UINT32 inq_count; /* Used for determining if a response has already been */ -/* received for the current inquiry operation. (We do not */ -/* want to flood the caller with multiple responses from */ -/* the same device. */ -BD_ADDR bd_addr; -} tINQ_BDADDR; - -typedef struct { -UINT32 time_of_resp; -UINT32 inq_count; /* "timestamps" the entry with a particular inquiry count */ -/* Used for determining if a response has already been */ -/* received for the current inquiry operation. (We do not */ -/* want to flood the caller with multiple responses from */ -/* the same device. */ -tBTM_INQ_INFO inq_info; -BOOLEAN in_use; - -#if (BLE_INCLUDED == TRUE) -BOOLEAN scan_rsp; -#endif -} tINQ_DB_ENT; - - -enum { -INQ_NONE, -INQ_LE_OBSERVE, -INQ_GENERAL -}; -typedef UINT8 tBTM_INQ_TYPE; - -typedef struct { - tBTM_CMPL_CB *p_remname_cmpl_cb; - -#define BTM_EXT_RMT_NAME_TIMEOUT 40 - - - TIMER_LIST_ENT rmt_name_timer_ent; - - UINT16 discoverable_mode; - UINT16 connectable_mode; - UINT16 page_scan_window; - UINT16 page_scan_period; - UINT16 inq_scan_window; - UINT16 inq_scan_period; - UINT16 inq_scan_type; - UINT16 page_scan_type; /* current page scan type */ - tBTM_INQ_TYPE scan_type; - - BD_ADDR remname_bda; /* Name of bd addr for active remote name request */ -#define BTM_RMT_NAME_INACTIVE 0 -#define BTM_RMT_NAME_EXT 0x1 /* Initiated through API */ -#define BTM_RMT_NAME_SEC 0x2 /* Initiated internally by security manager */ -#define BTM_RMT_NAME_INQ 0x4 /* Remote name initiated internally by inquiry */ - BOOLEAN remname_active; /* State of a remote name request by external API */ - - tBTM_CMPL_CB *p_inq_cmpl_cb; - tBTM_INQ_RESULTS_CB *p_inq_results_cb; - tBTM_CMPL_CB *p_inq_ble_cmpl_cb; /*completion callback exclusively for LE Observe*/ - tBTM_INQ_RESULTS_CB *p_inq_ble_results_cb;/*results callback exclusively for LE observe*/ - tBTM_CMPL_CB *p_inqfilter_cmpl_cb; /* Called (if not NULL) after inquiry filter completed */ - UINT32 inq_counter; /* Counter incremented each time an inquiry completes */ - /* Used for determining whether or not duplicate devices */ - /* have responded to the same inquiry */ - TIMER_LIST_ENT inq_timer_ent; - tINQ_BDADDR *p_bd_db; /* Pointer to memory that holds bdaddrs */ - UINT16 num_bd_entries; /* Number of entries in database */ - UINT16 max_bd_entries; /* Maximum number of entries that can be stored */ - tINQ_DB_ENT inq_db[BTM_INQ_DB_SIZE]; - tBTM_INQ_PARMS inqparms; /* Contains the parameters for the current inquiry */ - tBTM_INQUIRY_CMPL inq_cmpl_info; /* Status and number of responses from the last inquiry */ - - UINT16 per_min_delay; /* Current periodic minimum delay */ - UINT16 per_max_delay; /* Current periodic maximum delay */ - BOOLEAN inqfilt_active; - UINT8 pending_filt_complete_event; /* to take care of btm_event_filter_complete corresponding to */ - /* inquiry that has been cancelled*/ - UINT8 inqfilt_type; /* Contains the inquiry filter type (BD ADDR, COD, or Clear) */ - -#define BTM_INQ_INACTIVE_STATE 0 -#define BTM_INQ_CLR_FILT_STATE 1 /* Currently clearing the inquiry filter preceeding the inquiry request */ - /* (bypassed if filtering is not used) */ -#define BTM_INQ_SET_FILT_STATE 2 /* Sets the new filter (or turns off filtering) in this state */ -#define BTM_INQ_ACTIVE_STATE 3 /* Actual inquiry or periodic inquiry is in progress */ -#define BTM_INQ_REMNAME_STATE 4 /* Remote name requests are active */ - - UINT8 state; /* Current state that the inquiry process is in */ - UINT8 inq_active; /* Bit Mask indicating type of inquiry is active */ - BOOLEAN no_inc_ssp; /* TRUE, to stop inquiry on incoming SSP */ -#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE) - btm_inq_state next_state; /*interleaving state to determine next mode to be inquired*/ -#endif -} tBTM_INQUIRY_VAR_ST; - -/* The MSB of the clock offset field indicates that the offset is valid if TRUE */ -#define BTM_CLOCK_OFFSET_VALID 0x8000 - -/* Define the structures needed by security management -*/ - -#define BTM_SEC_INVALID_HANDLE 0xFFFF - -typedef UINT8 *BTM_BD_NAME_PTR; /* Pointer to Device name */ - -/* Security callback is called by this unit when security -** procedures are completed. Parameters are -** BD Address of remote -** Result of the operation -*/ -typedef tBTM_SEC_CBACK tBTM_SEC_CALLBACK; - -typedef void (tBTM_SCO_IND_CBACK) (UINT16 sco_inx) ; - -/* MACROs to convert from SCO packet types mask to ESCO and back */ -#define BTM_SCO_PKT_TYPE_MASK ( HCI_PKT_TYPES_MASK_HV1 \ - | HCI_PKT_TYPES_MASK_HV2 \ - | HCI_PKT_TYPES_MASK_HV3) - -/* Mask defining only the SCO types of an esco packet type */ -#define BTM_ESCO_PKT_TYPE_MASK ( HCI_ESCO_PKT_TYPES_MASK_HV1 \ - | HCI_ESCO_PKT_TYPES_MASK_HV2 \ - | HCI_ESCO_PKT_TYPES_MASK_HV3) - -#define BTM_SCO_2_ESCO(scotype) ((UINT16)(((scotype) & BTM_SCO_PKT_TYPE_MASK) >> 5)) -#define BTM_ESCO_2_SCO(escotype) ((UINT16)(((escotype) & BTM_ESCO_PKT_TYPE_MASK) << 5)) - -/* Define masks for supported and exception 2.0 SCO packet types -*/ -#define BTM_SCO_SUPPORTED_PKTS_MASK (HCI_ESCO_PKT_TYPES_MASK_HV1 | \ - HCI_ESCO_PKT_TYPES_MASK_HV2 | \ - HCI_ESCO_PKT_TYPES_MASK_HV3 | \ - HCI_ESCO_PKT_TYPES_MASK_EV3 | \ - HCI_ESCO_PKT_TYPES_MASK_EV4 | \ - HCI_ESCO_PKT_TYPES_MASK_EV5) - -#define BTM_SCO_EXCEPTION_PKTS_MASK (HCI_ESCO_PKT_TYPES_MASK_NO_2_EV3 | \ - HCI_ESCO_PKT_TYPES_MASK_NO_3_EV3 | \ - HCI_ESCO_PKT_TYPES_MASK_NO_2_EV5 | \ - HCI_ESCO_PKT_TYPES_MASK_NO_3_EV5) - - -#define BTM_SCO_ROUTE_UNKNOWN 0xff - -/* Define the structure that contains (e)SCO data */ -typedef struct { - tBTM_ESCO_CBACK *p_esco_cback; /* Callback for eSCO events */ - tBTM_ESCO_PARAMS setup; - tBTM_ESCO_DATA data; /* Connection complete information */ - UINT8 hci_status; -} tBTM_ESCO_INFO; - -/* Define the structure used for SCO Management -*/ -typedef struct { - tBTM_ESCO_INFO esco; /* Current settings */ -#if BTM_SCO_HCI_INCLUDED == TRUE - fixed_queue_t *xmit_data_q; /* SCO data transmitting queue */ -#endif - tBTM_SCO_CB *p_conn_cb; /* Callback for when connected */ - tBTM_SCO_CB *p_disc_cb; /* Callback for when disconnect */ - UINT16 state; /* The state of the SCO link */ - UINT16 hci_handle; /* HCI Handle */ - BOOLEAN is_orig; /* TRUE if the originator */ - BOOLEAN rem_bd_known; /* TRUE if remote BD addr known */ - -} tSCO_CONN; - -/* SCO Management control block */ -typedef struct { - tBTM_SCO_IND_CBACK *app_sco_ind_cb; -#if BTM_SCO_HCI_INCLUDED == TRUE - tBTM_SCO_DATA_CB *p_data_cb; /* Callback for SCO data over HCI */ - UINT32 xmit_window_size; /* Total SCO window in bytes */ -#endif - tSCO_CONN sco_db[BTM_MAX_SCO_LINKS]; - tBTM_ESCO_PARAMS def_esco_parms; - BD_ADDR xfer_addr; - UINT16 sco_disc_reason; - BOOLEAN esco_supported; /* TRUE if 1.2 cntlr AND supports eSCO links */ - tBTM_SCO_TYPE desired_sco_mode; - tBTM_SCO_TYPE xfer_sco_type; - tBTM_SCO_PCM_PARAM sco_pcm_param; - tBTM_SCO_CODEC_TYPE codec_in_use; /* None, CVSD, MSBC, etc. */ -#if BTM_SCO_HCI_INCLUDED == TRUE - tBTM_SCO_ROUTE_TYPE sco_path; -#endif - -} tSCO_CB; - - -#if BTM_SCO_INCLUDED == TRUE -void btm_set_sco_ind_cback( tBTM_SCO_IND_CBACK *sco_ind_cb ); -void btm_accept_sco_link(UINT16 sco_inx, tBTM_ESCO_PARAMS *p_setup, - tBTM_SCO_CB *p_conn_cb, tBTM_SCO_CB *p_disc_cb); -void btm_reject_sco_link(UINT16 sco_inx ); -void btm_sco_chk_pend_rolechange (UINT16 hci_handle); -#else -#define btm_accept_sco_link(sco_inx, p_setup, p_conn_cb, p_disc_cb) -#define btm_reject_sco_link(sco_inx) -#define btm_set_sco_ind_cback(sco_ind_cb) -#define btm_sco_chk_pend_rolechange(hci_handle) -#endif /* BTM_SCO_INCLUDED */ - -/* -** Define structure for Security Service Record. -** A record exists for each service registered with the Security Manager -*/ -#define BTM_SEC_OUT_FLAGS (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHORIZE) -#define BTM_SEC_IN_FLAGS (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHORIZE) - -#define BTM_SEC_OUT_LEVEL4_FLAGS (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT | \ - BTM_SEC_OUT_MITM | BTM_SEC_MODE4_LEVEL4) - -#define BTM_SEC_IN_LEVEL4_FLAGS (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | \ - BTM_SEC_IN_MITM | BTM_SEC_MODE4_LEVEL4) - -typedef struct { - UINT32 mx_proto_id; /* Service runs over this multiplexer protocol */ - UINT32 orig_mx_chan_id; /* Channel on the multiplexer protocol */ - UINT32 term_mx_chan_id; /* Channel on the multiplexer protocol */ - UINT16 psm; /* L2CAP PSM value */ - UINT16 security_flags; /* Bitmap of required security features */ - UINT8 service_id; /* Passed in authorization callback */ -#if (L2CAP_UCD_INCLUDED == TRUE) - UINT16 ucd_security_flags; /* Bitmap of required security features for UCD */ -#endif -#if BTM_SEC_SERVICE_NAME_LEN > 0 - UINT8 orig_service_name[BTM_SEC_SERVICE_NAME_LEN + 1]; - UINT8 term_service_name[BTM_SEC_SERVICE_NAME_LEN + 1]; -#endif -} tBTM_SEC_SERV_REC; - -#if BLE_INCLUDED == TRUE -/* LE Security information of device in Slave Role */ -typedef struct { - BT_OCTET16 irk; /* peer diverified identity root */ - BT_OCTET16 pltk; /* peer long term key */ - BT_OCTET16 pcsrk; /* peer SRK peer device used to secured sign local data */ - - BT_OCTET16 lltk; /* local long term key */ - BT_OCTET16 lcsrk; /* local SRK peer device used to secured sign local data */ - - BT_OCTET8 rand; /* random vector for LTK generation */ - UINT16 ediv; /* LTK diversifier of this slave device */ - UINT16 div; /* local DIV to generate local LTK=d1(ER,DIV,0) and CSRK=d1(ER,DIV,1) */ - UINT8 sec_level; /* local pairing security level */ - UINT8 key_size; /* key size of the LTK delivered to peer device */ - UINT8 srk_sec_level; /* security property of peer SRK for this device */ - UINT8 local_csrk_sec_level; /* security property of local CSRK for this device */ - - UINT32 counter; /* peer sign counter for verifying rcv signed cmd */ - UINT32 local_counter; /* local sign counter for sending signed write cmd*/ -} tBTM_SEC_BLE_KEYS; - -typedef struct { - BD_ADDR pseudo_addr; /* LE pseudo address of the device if different from device address */ - tBLE_ADDR_TYPE ble_addr_type; /* LE device type: public or random address */ - tBLE_ADDR_TYPE static_addr_type; /* static address type */ - BD_ADDR static_addr; /* static address */ - -#define BTM_WHITE_LIST_BIT 0x01 -#define BTM_RESOLVING_LIST_BIT 0x02 - UINT8 in_controller_list; /* in controller resolving list or not */ - UINT8 resolving_list_index; -#if BLE_PRIVACY_SPT == TRUE - BD_ADDR cur_rand_addr; /* current random address */ - -#define BTM_BLE_ADDR_PSEUDO 0 /* address index device record */ -#define BTM_BLE_ADDR_RRA 1 /* cur_rand_addr */ -#define BTM_BLE_ADDR_STATIC 2 /* static_addr */ - UINT8 active_addr_type; -#endif - -#if SMP_INCLUDED == TRUE - tBTM_LE_KEY_TYPE key_type; /* bit mask of valid key types in record */ - tBTM_SEC_BLE_KEYS keys; /* LE device security info in slave rode */ -#endif -#if (BLE_PRIVACY_SPT == TRUE) - tBLE_ADDR_TYPE current_addr_type; /* current adv addr type*/ - BD_ADDR current_addr; /* current adv addr*/ - bool current_addr_valid; /* current addr info is valid or not*/ -#endif -} tBTM_SEC_BLE; - - -#endif /* BLE_INCLUDED */ - -/* Peering bond type */ -enum { - BOND_TYPE_UNKNOWN, - BOND_TYPE_PERSISTENT, - BOND_TYPE_TEMPORARY -}; -typedef UINT8 tBTM_BOND_TYPE; - -/* -** Define structure for Security Device Record. -** A record exists for each device authenticated with this device -*/ -typedef struct { - tBTM_SEC_SERV_REC *p_cur_service; - tBTM_SEC_CALLBACK *p_callback; - void *p_ref_data; - UINT32 timestamp; /* Timestamp of the last connection */ - UINT32 trusted_mask[BTM_SEC_SERVICE_ARRAY_SIZE]; /* Bitwise OR of trusted services */ - UINT16 hci_handle; /* Handle to connection when exists */ - UINT16 clock_offset; /* Latest known clock offset */ - BD_ADDR bd_addr; /* BD_ADDR of the device */ - DEV_CLASS dev_class; /* DEV_CLASS of the device */ - LINK_KEY link_key; /* Device link key */ - UINT8 pin_code_length; /* Length of the pin_code used for paring */ - -#define BTM_SEC_AUTHORIZED BTM_SEC_FLAG_AUTHORIZED /* 0x01 */ -#define BTM_SEC_AUTHENTICATED BTM_SEC_FLAG_AUTHENTICATED /* 0x02 */ -#define BTM_SEC_ENCRYPTED BTM_SEC_FLAG_ENCRYPTED /* 0x04 */ -#define BTM_SEC_NAME_KNOWN 0x08 -#define BTM_SEC_LINK_KEY_KNOWN BTM_SEC_FLAG_LKEY_KNOWN /* 0x10 */ -#define BTM_SEC_LINK_KEY_AUTHED BTM_SEC_FLAG_LKEY_AUTHED /* 0x20 */ -#define BTM_SEC_ROLE_SWITCHED 0x40 -#define BTM_SEC_IN_USE 0x80 - /* LE link security flag */ -#define BTM_SEC_LE_AUTHENTICATED 0x0200 /* LE link is encrypted after pairing with MITM */ -#define BTM_SEC_LE_ENCRYPTED 0x0400 /* LE link is encrypted */ -#define BTM_SEC_LE_NAME_KNOWN 0x0800 /* not used */ -#define BTM_SEC_LE_LINK_KEY_KNOWN 0x1000 /* bonded with peer (peer LTK and/or SRK is saved) */ -#define BTM_SEC_LE_LINK_KEY_AUTHED 0x2000 /* pairing is done with MITM */ -#define BTM_SEC_16_DIGIT_PIN_AUTHED 0x4000 /* pairing is done with 16 digit pin */ - - UINT16 sec_flags; /* Current device security state */ - - tBTM_BD_NAME sec_bd_name; /* User friendly name of the device. (may be truncated to save space in dev_rec table) */ - BD_FEATURES features[HCI_EXT_FEATURES_PAGE_MAX + 1]; /* Features supported by the device */ - UINT8 num_read_pages; - -#define BTM_SEC_STATE_IDLE 0 -#define BTM_SEC_STATE_AUTHENTICATING 1 -#define BTM_SEC_STATE_ENCRYPTING 2 -#define BTM_SEC_STATE_GETTING_NAME 3 -#define BTM_SEC_STATE_AUTHORIZING 4 -#define BTM_SEC_STATE_SWITCHING_ROLE 5 -#define BTM_SEC_STATE_DISCONNECTING 6 /* disconnecting BR/EDR */ -#define BTM_SEC_STATE_DELAY_FOR_ENC 7 /* delay to check for encryption to work around */ - /* controller problems */ -#define BTM_SEC_STATE_DISCONNECTING_BLE 8 /* disconnecting BLE */ -#define BTM_SEC_STATE_DISCONNECTING_BOTH 9 /* disconnecting BR/EDR and BLE */ - - UINT8 sec_state; /* Operating state */ - BOOLEAN is_originator; /* TRUE if device is originating connection */ -#if (L2CAP_UCD_INCLUDED == TRUE) - BOOLEAN is_ucd; /* TRUE if device is sending or receiving UCD */ - /* if incoming security failed, received UCD will be discarded */ -#endif - BOOLEAN role_master; /* TRUE if current mode is master */ - UINT16 security_required; /* Security required for connection */ - BOOLEAN link_key_not_sent; /* link key notification has not been sent waiting for name */ - UINT8 link_key_type; /* Type of key used in pairing */ - BOOLEAN link_key_changed; /* Changed link key during current connection */ - -#define BTM_MAX_PRE_SM4_LKEY_TYPE BTM_LKEY_TYPE_REMOTE_UNIT /* the link key type used by legacy pairing */ - -#define BTM_SM4_UNKNOWN 0x00 -#define BTM_SM4_KNOWN 0x10 -#define BTM_SM4_TRUE 0x11 -#define BTM_SM4_REQ_PEND 0x08 /* set this bit when getting remote features */ -#define BTM_SM4_UPGRADE 0x04 /* set this bit when upgrading link key */ -#define BTM_SM4_RETRY 0x02 /* set this bit to retry on HCI_ERR_KEY_MISSING or HCI_ERR_LMP_ERR_TRANS_COLLISION */ -#define BTM_SM4_DD_ACP 0x20 /* set this bit to indicate peer initiated dedicated bonding */ -#define BTM_SM4_CONN_PEND 0x40 /* set this bit to indicate accepting acl conn; to be cleared on btm_acl_created */ - UINT8 sm4; /* BTM_SM4_TRUE, if the peer supports SM4 */ - tBTM_IO_CAP rmt_io_caps; /* IO capability of the peer device */ - tBTM_AUTH_REQ rmt_auth_req; /* the auth_req flag as in the IO caps rsp evt */ - BOOLEAN remote_supports_secure_connections; - BOOLEAN remote_features_needed; /* set to true if the local device is in */ - /* "Secure Connections Only" mode and it receives */ - /* HCI_IO_CAPABILITY_REQUEST_EVT from the peer before */ - /* it knows peer's support for Secure Connections */ - - UINT16 ble_hci_handle; /* use in DUMO connection */ - UINT8 enc_key_size; /* current link encryption key size */ - tBT_DEVICE_TYPE device_type; - BOOLEAN new_encryption_key_is_p256; /* Set to TRUE when the newly generated LK - ** is generated from P-256. - ** Link encrypted with such LK can be used - ** for SM over BR/EDR. - */ - BOOLEAN no_smp_on_br; /* if set to TRUE then SMP on BR/EDR doesn't */ - /* work, i.e. link keys crosspairing */ - /* SC BR/EDR->SC LE doesn't happen */ - tBTM_BOND_TYPE bond_type; /* peering bond type */ - -#if BLE_INCLUDED == TRUE - tBTM_SEC_BLE ble; - tBTM_LE_CONN_PRAMS conn_params; -#endif - -// btla-specific ++ -#if BTM_DISC_DURING_RS == TRUE -#define BTM_SEC_RS_NOT_PENDING 0 /* Role Switch not in progress */ -#define BTM_SEC_RS_PENDING 1 /* Role Switch in progress */ -#define BTM_SEC_DISC_PENDING 2 /* Disconnect is pending */ - UINT8 rs_disc_pending; -#endif -// btla-specific -- -#define BTM_SEC_NO_LAST_SERVICE_ID 0 - UINT8 last_author_service_id; /* ID of last serviced authorized: Reset after each l2cap connection */ - -} tBTM_SEC_DEV_REC; - -#define BTM_SEC_IS_SM4(sm) ((BOOLEAN)(BTM_SM4_TRUE == ((sm)&BTM_SM4_TRUE))) -#define BTM_SEC_IS_SM4_LEGACY(sm) ((BOOLEAN)(BTM_SM4_KNOWN == ((sm)&BTM_SM4_TRUE))) -#define BTM_SEC_IS_SM4_UNKNOWN(sm) ((BOOLEAN)(BTM_SM4_UNKNOWN == ((sm)&BTM_SM4_TRUE))) - -#define BTM_SEC_LE_MASK (BTM_SEC_LE_AUTHENTICATED|BTM_SEC_LE_ENCRYPTED|BTM_SEC_LE_LINK_KEY_KNOWN|BTM_SEC_LE_LINK_KEY_AUTHED) - -/* -** Define device configuration structure -*/ -typedef struct { -#if BTM_MAX_LOC_BD_NAME_LEN > 0 - tBTM_LOC_BD_NAME bd_name; /* local Bluetooth device name */ -#endif - BOOLEAN pin_type; /* TRUE if PIN type is fixed */ - UINT8 pin_code_len; /* Bonding information */ - PIN_CODE pin_code; /* PIN CODE if pin type is fixed */ - BOOLEAN connectable; /* If TRUE page scan should be enabled */ - UINT8 def_inq_scan_mode; /* ??? limited/general/none */ -} tBTM_CFG; - -enum { - BTM_PM_ST_ACTIVE = BTM_PM_STS_ACTIVE, - BTM_PM_ST_HOLD = BTM_PM_STS_HOLD, - BTM_PM_ST_SNIFF = BTM_PM_STS_SNIFF, - BTM_PM_ST_PARK = BTM_PM_STS_PARK, - BTM_PM_ST_PENDING = BTM_PM_STS_PENDING -}; -typedef UINT8 tBTM_PM_STATE; - -enum { - BTM_PM_SET_MODE_EVT, /* Set power mode API is called. */ - BTM_PM_UPDATE_EVT, - BTM_PM_RD_MODE_EVT /* Read power mode API is called. */ -}; -typedef UINT8 tBTM_PM_EVENT; - -typedef struct { - UINT16 event; - UINT16 len; - UINT8 link_ind; -} tBTM_PM_MSG_DATA; - -typedef struct { - UINT8 hci_status; - UINT8 mode; - UINT16 interval; -} tBTM_PM_MD_CHG_DATA; - -typedef struct { - UINT8 pm_id; /* the entity that calls SetPowerMode API */ - tBTM_PM_PWR_MD *p_pmd; -} tBTM_PM_SET_MD_DATA; - -typedef struct { - void *p_data; - UINT8 link_ind; -} tBTM_PM_SM_DATA; - -typedef struct { - tBTM_PM_PWR_MD req_mode[BTM_MAX_PM_RECORDS + 1]; /* the desired mode and parameters of the connection*/ - tBTM_PM_PWR_MD set_mode; /* the mode and parameters sent down to the host controller. */ - UINT16 interval; /* the interval from last mode change event. */ -#if (BTM_SSR_INCLUDED == TRUE) - UINT16 max_lat; /* stored SSR maximum latency */ - UINT16 min_rmt_to;/* stored SSR minimum remote timeout */ - UINT16 min_loc_to;/* stored SSR minimum local timeout */ -#endif - tBTM_PM_STATE state; /* contains the current mode of the connection */ - BOOLEAN chg_ind; /* a request change indication */ -} tBTM_PM_MCB; - -#define BTM_PM_REC_NOT_USED 0 -typedef struct { - tBTM_PM_STATUS_CBACK *cback;/* to notify the registered party of mode change event */ - UINT8 mask; /* registered request mask. 0, if this entry is not used */ -} tBTM_PM_RCB; - -enum { - BTM_BLI_ACL_UP_EVT, - BTM_BLI_ACL_DOWN_EVT, - BTM_BLI_PAGE_EVT, - BTM_BLI_PAGE_DONE_EVT, - BTM_BLI_INQ_EVT, - BTM_BLI_INQ_CANCEL_EVT, - BTM_BLI_INQ_DONE_EVT -}; -typedef UINT8 tBTM_BLI_EVENT; - -/* Pairing State */ -enum { - BTM_PAIR_STATE_IDLE, /* Idle */ - BTM_PAIR_STATE_GET_REM_NAME, /* Getting the remote name (to check for SM4) */ - BTM_PAIR_STATE_WAIT_PIN_REQ, /* Started authentication, waiting for PIN req (PIN is pre-fetched) */ - BTM_PAIR_STATE_WAIT_LOCAL_PIN, /* Waiting for local PIN code */ - BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM, /* Waiting user 'yes' to numeric confirmation */ - BTM_PAIR_STATE_KEY_ENTRY, /* Key entry state (we are a keyboard) */ - BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP, /* Waiting for local response to peer OOB data */ - BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS, /* Waiting for local IO capabilities and OOB data */ - BTM_PAIR_STATE_INCOMING_SSP, /* Incoming SSP (got peer IO caps when idle) */ - BTM_PAIR_STATE_WAIT_AUTH_COMPLETE, /* All done, waiting authentication cpmplete */ - BTM_PAIR_STATE_WAIT_DISCONNECT /* Waiting to disconnect the ACL */ -}; -typedef UINT8 tBTM_PAIRING_STATE; - -#define BTM_PAIR_FLAGS_WE_STARTED_DD 0x01 /* We want to do dedicated bonding */ -#define BTM_PAIR_FLAGS_PEER_STARTED_DD 0x02 /* Peer initiated dedicated bonding */ -#define BTM_PAIR_FLAGS_DISC_WHEN_DONE 0x04 /* Disconnect when done */ -#define BTM_PAIR_FLAGS_PIN_REQD 0x08 /* set this bit when pin_callback is called */ -#define BTM_PAIR_FLAGS_PRE_FETCH_PIN 0x10 /* set this bit when pre-fetch pin */ -#define BTM_PAIR_FLAGS_REJECTED_CONNECT 0x20 /* set this bit when rejected incoming connection */ -#define BTM_PAIR_FLAGS_WE_CANCEL_DD 0x40 /* set this bit when cancelling a bonding procedure */ -#define BTM_PAIR_FLAGS_LE_ACTIVE 0x80 /* use this bit when SMP pairing is active */ - - -typedef struct { - BOOLEAN is_mux; - BD_ADDR bd_addr; - UINT16 psm; - BOOLEAN is_orig; - tBTM_SEC_CALLBACK *p_callback; - void *p_ref_data; - UINT32 mx_proto_id; - UINT32 mx_chan_id; - tBT_TRANSPORT transport; -} tBTM_SEC_QUEUE_ENTRY; - -#if (L2CAP_UCD_INCLUDED == TRUE) - -#define CONN_ORIENT_TERM 0x00 /* incoming connection oriented */ -#define CONN_ORIENT_ORIG 0x01 /* outgoing connection oriented */ -#define CONNLESS_TERM 0x02 /* incoming connectionless */ -#define CONNLESS_ORIG 0x03 /* outgoing connectionless */ -#define CONNECTION_TYPE_ORIG_MASK 0x01 /* mask for direction */ -#define CONNECTION_TYPE_CONNLESS_MASK 0x02 /* mask for connectionless or not */ -typedef UINT8 CONNECTION_TYPE; - -#else - -#define CONN_ORIENT_TERM FALSE -#define CONN_ORIENT_ORIG TRUE -typedef BOOLEAN CONNECTION_TYPE; - -#endif /* (L2CAP_UCD_INCLUDED == TRUE) */ - -/* Define a structure to hold all the BTM data -*/ - -#define BTM_STATE_BUFFER_SIZE 5 /* size of state buffer */ - -typedef struct { - tBTM_CFG cfg; /* Device configuration */ - - /**************************************************** - ** ACL Management - ****************************************************/ - tACL_CONN acl_db[MAX_L2CAP_LINKS]; -#if (CLASSIC_BT_INCLUDED == TRUE) - UINT8 btm_scn[BTM_MAX_SCN]; /* current SCNs: TRUE if SCN is in use */ -#endif ///CLASSIC_BT_INCLUDED == TRUE - UINT16 btm_def_link_policy; - UINT16 btm_def_link_super_tout; - - tBTM_BL_EVENT_MASK bl_evt_mask; - tBTM_BL_CHANGE_CB *p_bl_changed_cb; /* Callback for when Busy Level changed */ - - /**************************************************** - ** Power Management - ****************************************************/ - tBTM_PM_MCB pm_mode_db[MAX_L2CAP_LINKS]; /* per ACL link */ - tBTM_PM_RCB pm_reg_db[BTM_MAX_PM_RECORDS + 1]; /* per application/module */ - UINT8 pm_pend_link; /* the index of acl_db, which has a pending PM cmd */ - UINT8 pm_pend_id; /* the id pf the module, which has a pending PM cmd */ - - /***************************************************** - ** Device control - *****************************************************/ - tBTM_DEVCB devcb; - - /***************************************************** - ** BLE Device controllers - *****************************************************/ -#if (BLE_INCLUDED == TRUE) - tBTM_BLE_CB ble_ctr_cb; - - UINT16 enc_handle; - BT_OCTET8 enc_rand; /* received rand value from LTK request*/ - UINT16 ediv; /* received ediv value from LTK request */ - UINT8 key_size; - tBTM_BLE_VSC_CB cmn_ble_vsc_cb; -#endif - - /* Packet types supported by the local device */ - UINT16 btm_acl_pkt_types_supported; - UINT16 btm_sco_pkt_types_supported; - - - /***************************************************** - ** Inquiry - *****************************************************/ - tBTM_INQUIRY_VAR_ST btm_inq_vars; - - /***************************************************** - ** SCO Management - *****************************************************/ -#if BTM_SCO_INCLUDED == TRUE - tSCO_CB sco_cb; -#endif - - /***************************************************** - ** Security Management - *****************************************************/ - tBTM_APPL_INFO api; - -#define BTM_SEC_MAX_RMT_NAME_CALLBACKS 2 - - tBTM_RMT_NAME_CALLBACK *p_rmt_name_callback[BTM_SEC_MAX_RMT_NAME_CALLBACKS]; -#if (SMP_INCLUDED == TRUE) - tBTM_SEC_DEV_REC *p_collided_dev_rec; -#endif ///SMP_INCLUDED == TRUE - TIMER_LIST_ENT sec_collision_tle; - UINT32 collision_start_time; - UINT32 max_collision_delay; - UINT32 dev_rec_count; /* Counter used for device record timestamp */ - UINT8 security_mode; - BOOLEAN pairing_disabled; - BOOLEAN connect_only_paired; - BOOLEAN security_mode_changed; /* mode changed during bonding */ - BOOLEAN pin_type_changed; /* pin type changed during bonding */ - BOOLEAN sec_req_pending; /* TRUE if a request is pending */ -#if (SMP_INCLUDED == TRUE) -// btla-specific ++ -#ifdef PORCHE_PAIRING_CONFLICT - UINT8 pin_code_len_saved; /* for legacy devices */ -#endif -// btla-specific -- - - UINT8 pin_code_len; /* for legacy devices */ - PIN_CODE pin_code; /* for legacy devices */ - tBTM_PAIRING_STATE pairing_state; /* The current pairing state */ - UINT8 pairing_flags; /* The current pairing flags */ - BD_ADDR pairing_bda; /* The device currently pairing */ - TIMER_LIST_ENT pairing_tle; /* Timer for pairing process */ - UINT16 disc_handle; /* for legacy devices */ - UINT8 disc_reason; /* for legacy devices */ -#endif ///SMP_INCLUDED == TRUE -#if SMP_INCLUDED == TRUE || CLASSIC_BT_INCLUDED == TRUE - tBTM_SEC_SERV_REC sec_serv_rec[BTM_SEC_MAX_SERVICE_RECORDS]; -#endif // SMP_INCLUDED == TRUE || CLASSIC_BT_ENABLED == TRUE - tBTM_SEC_DEV_REC sec_dev_rec[BTM_SEC_MAX_DEVICE_RECORDS]; - tBTM_SEC_SERV_REC *p_out_serv; - tBTM_MKEY_CALLBACK *mkey_cback; - - BD_ADDR connecting_bda; - DEV_CLASS connecting_dc; - - UINT8 acl_disc_reason; - UINT8 trace_level; - UINT8 busy_level; /* the current busy level */ - BOOLEAN is_paging; /* TRUE, if paging is in progess */ - BOOLEAN is_inquiry; /* TRUE, if inquiry is in progess */ - fixed_queue_t *page_queue; - BOOLEAN paging; - BOOLEAN discing; - fixed_queue_t *sec_pending_q; /* pending sequrity requests in tBTM_SEC_QUEUE_ENTRY format */ -#if (!defined(BT_TRACE_VERBOSE) || (BT_TRACE_VERBOSE == FALSE)) - char state_temp_buffer[BTM_STATE_BUFFER_SIZE]; -#endif -} tBTM_CB; - -typedef struct{ - //connection parameters update callback - tBTM_UPDATE_CONN_PARAM_CBACK *update_conn_param_cb; -}tBTM_CallbackFunc; - -extern tBTM_CallbackFunc conn_param_update_cb; -/* security action for L2CAP COC channels */ -#define BTM_SEC_OK 1 -#define BTM_SEC_ENCRYPT 2 /* encrypt the link with current key */ -#define BTM_SEC_ENCRYPT_NO_MITM 3 /* unauthenticated encryption or better */ -#define BTM_SEC_ENCRYPT_MITM 4 /* authenticated encryption */ -#define BTM_SEC_ENC_PENDING 5 /* wait for link encryption pending */ - -typedef UINT8 tBTM_SEC_ACTION; - -/* -#ifdef __cplusplus -extern "C" -{ -#endif -*/ - -#if BTM_DYNAMIC_MEMORY == FALSE -extern tBTM_CB btm_cb; -#else -extern tBTM_CB *btm_cb_ptr; -#define btm_cb (*btm_cb_ptr) -#endif - -/* Internal functions provided by btm_main.c -******************************************** -*/ -void btm_init (void); -void btm_free (void); - -/* Internal functions provided by btm_inq.c -******************************************* -*/ -tBTM_STATUS btm_initiate_rem_name (BD_ADDR remote_bda, - tBTM_INQ_INFO *p_cur, - UINT8 origin, UINT32 timeout, - tBTM_CMPL_CB *p_cb); - -void btm_process_remote_name (BD_ADDR bda, BD_NAME name, UINT16 evt_len, - UINT8 hci_status); -void btm_inq_rmt_name_failed(void); - -/* Inquiry related functions */ -void btm_clr_inq_db (BD_ADDR p_bda); -void btm_inq_db_init (void); -void btm_process_inq_results (UINT8 *p, UINT8 inq_res_mode); -void btm_process_inq_complete (UINT8 status, UINT8 mode); -void btm_process_cancel_complete(UINT8 status, UINT8 mode); -void btm_event_filter_complete (UINT8 *p); -void btm_inq_stop_on_ssp(void); -void btm_inq_clear_ssp(void); -tINQ_DB_ENT *btm_inq_db_find (BD_ADDR p_bda); -BOOLEAN btm_inq_find_bdaddr (BD_ADDR p_bda); - -BOOLEAN btm_lookup_eir(BD_ADDR_PTR p_rem_addr); - -/* Internal functions provided by btm_acl.c -******************************************** -*/ -void btm_acl_init (void); -void btm_acl_created (BD_ADDR bda, DEV_CLASS dc, BD_NAME bdn, - UINT16 hci_handle, UINT8 link_role, tBT_TRANSPORT transport); -void btm_acl_removed (BD_ADDR bda, tBT_TRANSPORT transport); -void btm_acl_device_down (void); -void btm_acl_update_busy_level (tBTM_BLI_EVENT event); - -void btm_cont_rswitch (tACL_CONN *p, - tBTM_SEC_DEV_REC *p_dev_rec, - UINT8 hci_status); - -UINT8 btm_handle_to_acl_index (UINT16 hci_handle); -tACL_CONN *btm_handle_to_acl (UINT16 hci_handle); -void btm_read_link_policy_complete (UINT8 *p); -void btm_read_rssi_complete (UINT8 *p); -void btm_read_tx_power_complete (UINT8 *p, BOOLEAN is_ble); -void btm_read_link_quality_complete (UINT8 *p); -tBTM_STATUS btm_set_packet_types (tACL_CONN *p, UINT16 pkt_types); -void btm_process_clk_off_comp_evt (UINT16 hci_handle, UINT16 clock_offset); -void btm_acl_role_changed (UINT8 hci_status, BD_ADDR bd_addr, UINT8 new_role); -void btm_acl_encrypt_change (UINT16 handle, UINT8 status, UINT8 encr_enable); -UINT16 btm_get_acl_disc_reason_code (void); -tBTM_STATUS btm_remove_acl (BD_ADDR bd_addr, tBT_TRANSPORT transport); -void btm_read_remote_features_complete (UINT8 *p); -void btm_read_remote_ext_features_complete (UINT8 *p); -void btm_read_remote_ext_features_failed (UINT8 status, UINT16 handle); -void btm_read_remote_version_complete (UINT8 *p); -void btm_establish_continue (tACL_CONN *p_acl_cb); - -// btla-specific ++ -void btm_acl_chk_peer_pkt_type_support (tACL_CONN *p, UINT16 *p_pkt_type); -// btla-specific -- -/* Read maximum data packet that can be sent over current connection */ -UINT16 btm_get_max_packet_size (BD_ADDR addr); -tACL_CONN *btm_bda_to_acl (BD_ADDR bda, tBT_TRANSPORT transport); -BOOLEAN btm_acl_notif_conn_collision (BD_ADDR bda); - -void btm_pm_reset(void); -void btm_pm_sm_alloc(UINT8 ind); -void btm_pm_proc_cmd_status(UINT8 status); -void btm_pm_proc_mode_change (UINT8 hci_status, UINT16 hci_handle, UINT8 mode, - UINT16 interval); -void btm_pm_proc_ssr_evt (UINT8 *p, UINT16 evt_len); -#if BTM_SCO_INCLUDED == TRUE -void btm_sco_chk_pend_unpark (UINT8 hci_status, UINT16 hci_handle); -#else -#define btm_sco_chk_pend_unpark(hci_status, hci_handle) -#endif /* BTM_SCO_INCLUDED */ -void btm_qos_setup_complete (UINT8 status, UINT16 handle, FLOW_SPEC *p_flow); - - -/* Internal functions provided by btm_sco.c -******************************************** -*/ -void btm_sco_init (void); -void btm_sco_connected (UINT8 hci_status, BD_ADDR bda, UINT16 hci_handle, - tBTM_ESCO_DATA *p_esco_data); -void btm_esco_proc_conn_chg (UINT8 status, UINT16 handle, UINT8 tx_interval, - UINT8 retrans_window, UINT16 rx_pkt_len, - UINT16 tx_pkt_len); -void btm_sco_conn_req (BD_ADDR bda, DEV_CLASS dev_class, UINT8 link_type); -void btm_sco_removed (UINT16 hci_handle, UINT8 reason); -void btm_sco_acl_removed (BD_ADDR bda); -void btm_route_sco_data (BT_HDR *p_msg); -BOOLEAN btm_is_sco_active (UINT16 handle); -void btm_remove_sco_links (BD_ADDR bda); -BOOLEAN btm_is_sco_active_by_bdaddr (BD_ADDR remote_bda); - -tBTM_SCO_TYPE btm_read_def_esco_mode (tBTM_ESCO_PARAMS *p_parms); -UINT16 btm_find_scb_by_handle (UINT16 handle); -void btm_sco_flush_sco_data(UINT16 sco_inx); - -/* Internal functions provided by btm_devctl.c -********************************************** -*/ -void btm_dev_init (void); -void btm_dev_timeout (TIMER_LIST_ENT *p_tle); -void btm_read_local_name_complete (UINT8 *p, UINT16 evt_len); - -#if (BLE_INCLUDED == TRUE) -void btm_ble_add_2_white_list_complete(UINT8 status); -void btm_ble_remove_from_white_list_complete(UINT8 *p, UINT16 evt_len); -void btm_ble_clear_white_list_complete(UINT8 *p, UINT16 evt_len); -BOOLEAN btm_ble_addr_resolvable(BD_ADDR rpa, tBTM_SEC_DEV_REC *p_dev_rec); -tBTM_STATUS btm_ble_read_resolving_list_entry(tBTM_SEC_DEV_REC *p_dev_rec); -BOOLEAN btm_ble_resolving_list_load_dev(tBTM_SEC_DEV_REC *p_dev_rec); -void btm_ble_resolving_list_remove_dev(tBTM_SEC_DEV_REC *p_dev_rec); -#endif /* BLE_INCLUDED */ - -/* Vendor Specific Command complete evt handler */ -void btm_vsc_complete (UINT8 *p, UINT16 cc_opcode, UINT16 evt_len, - tBTM_CMPL_CB *p_vsc_cplt_cback); -void btm_inq_db_reset (void); -void btm_vendor_specific_evt (UINT8 *p, UINT8 evt_len); -void btm_delete_stored_link_key_complete (UINT8 *p); -void btm_report_device_status (tBTM_DEV_STATUS status); - - -/* Internal functions provided by btm_dev.c -********************************************** -*/ -BOOLEAN btm_dev_support_switch (BD_ADDR bd_addr); - -tBTM_SEC_DEV_REC *btm_sec_alloc_dev (BD_ADDR bd_addr); -void btm_sec_free_dev (tBTM_SEC_DEV_REC *p_dev_rec); -tBTM_SEC_DEV_REC *btm_find_dev (BD_ADDR bd_addr); -tBTM_SEC_DEV_REC *btm_find_or_alloc_dev (BD_ADDR bd_addr); -tBTM_SEC_DEV_REC *btm_find_dev_by_handle (UINT16 handle); -tBTM_BOND_TYPE btm_get_bond_type_dev(BD_ADDR bd_addr); -BOOLEAN btm_set_bond_type_dev(BD_ADDR bd_addr, - tBTM_BOND_TYPE bond_type); - -/* Internal functions provided by btm_sec.c -********************************************** -*/ -BOOLEAN btm_dev_support_switch (BD_ADDR bd_addr); -tBTM_STATUS btm_sec_l2cap_access_req (BD_ADDR bd_addr, UINT16 psm, - UINT16 handle, CONNECTION_TYPE conn_type, - tBTM_SEC_CALLBACK *p_callback, void *p_ref_data); -tBTM_STATUS btm_sec_mx_access_request (BD_ADDR bd_addr, UINT16 psm, BOOLEAN is_originator, - UINT32 mx_proto_id, UINT32 mx_chan_id, - tBTM_SEC_CALLBACK *p_callback, void *p_ref_data); -void btm_sec_conn_req (UINT8 *bda, UINT8 *dc); -void btm_create_conn_cancel_complete (UINT8 *p); -void btm_read_linq_tx_power_complete (UINT8 *p); - -void btm_sec_init (UINT8 sec_mode); -void btm_sec_dev_reset (void); -void btm_sec_abort_access_req (BD_ADDR bd_addr); -void btm_sec_auth_complete (UINT16 handle, UINT8 status); -void btm_sec_encrypt_change (UINT16 handle, UINT8 status, UINT8 encr_enable); -void btm_sec_connected (UINT8 *bda, UINT16 handle, UINT8 status, UINT8 enc_mode); -tBTM_STATUS btm_sec_disconnect (UINT16 handle, UINT8 reason); -void btm_sec_disconnected (UINT16 handle, UINT8 reason); -void btm_sec_rmt_name_request_complete (UINT8 *bd_addr, UINT8 *bd_name, UINT8 status); -void btm_sec_rmt_host_support_feat_evt (UINT8 *p); -void btm_io_capabilities_req (UINT8 *p); -void btm_io_capabilities_rsp (UINT8 *p); -void btm_proc_sp_req_evt (tBTM_SP_EVT event, UINT8 *p); -void btm_keypress_notif_evt (UINT8 *p); -void btm_simple_pair_complete (UINT8 *p); -void btm_sec_link_key_notification (UINT8 *p_bda, UINT8 *p_link_key, UINT8 key_type); -void btm_sec_link_key_request (UINT8 *p_bda); -void btm_sec_pin_code_request (UINT8 *p_bda); -void btm_sec_update_clock_offset (UINT16 handle, UINT16 clock_offset); -void btm_sec_dev_rec_cback_event (tBTM_SEC_DEV_REC *p_dev_rec, UINT8 res, BOOLEAN is_le_trasnport); -void btm_sec_set_peer_sec_caps (tACL_CONN *p_acl_cb, tBTM_SEC_DEV_REC *p_dev_rec); - -#if BLE_INCLUDED == TRUE -void btm_sec_clear_ble_keys (tBTM_SEC_DEV_REC *p_dev_rec); -BOOLEAN btm_sec_find_bonded_dev (UINT8 start_idx, UINT8 *p_found_idx, tBTM_SEC_DEV_REC **p_rec); -BOOLEAN btm_sec_is_a_bonded_dev (BD_ADDR bda); -void btm_consolidate_dev(tBTM_SEC_DEV_REC *p_target_rec); -BOOLEAN btm_sec_is_le_capable_dev (BD_ADDR bda); -BOOLEAN btm_ble_init_pseudo_addr (tBTM_SEC_DEV_REC *p_dev_rec, BD_ADDR new_pseudo_addr); -extern BOOLEAN btm_ble_start_sec_check(BD_ADDR bd_addr, UINT16 psm, BOOLEAN is_originator, - tBTM_SEC_CALLBACK *p_callback, void *p_ref_data); -extern tBTM_SEC_SERV_REC *btm_sec_find_first_serv (CONNECTION_TYPE conn_type, UINT16 psm); - -#endif /* BLE_INCLUDED */ - -tINQ_DB_ENT *btm_inq_db_new (BD_ADDR p_bda); - -#if BTM_OOB_INCLUDED == TRUE -void btm_rem_oob_req (UINT8 *p); -void btm_read_local_oob_complete (UINT8 *p); -#else -#define btm_rem_oob_req(p) -#define btm_read_local_oob_complete(p) -#endif - -void btm_acl_resubmit_page (void); -void btm_acl_reset_paging (void); -void btm_acl_paging (BT_HDR *p, BD_ADDR dest); -UINT8 btm_sec_clr_service_by_psm (UINT16 psm); -void btm_sec_clr_temp_auth_service (BD_ADDR bda); - -/* -#ifdef __cplusplus -} -#endif -*/ - -#endif diff --git a/tools/sdk/include/bluedroid/btu.h b/tools/sdk/include/bluedroid/btu.h deleted file mode 100644 index c59fb7f56d5..00000000000 --- a/tools/sdk/include/bluedroid/btu.h +++ /dev/null @@ -1,285 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * this file contains the main Bluetooth Upper Layer definitions. The Broadcom - * implementations of L2CAP RFCOMM, SDP and the BTIf run as one GKI task. The - * btu_task switches between them. - * - ******************************************************************************/ - -#ifndef BTU_H -#define BTU_H - -#include "bt_target.h" -#include "bt_defs.h" - -// HACK(zachoverflow): temporary dark magic -#define BTU_POST_TO_TASK_NO_GOOD_HORRIBLE_HACK 0x1700 // didn't look used in bt_types...here goes nothing -typedef struct { - void (*callback)(BT_HDR *); -} post_to_task_hack_t; - -typedef struct { - void (*callback)(BT_HDR *); - BT_HDR *response; - void *context; -} command_complete_hack_t; - -typedef struct { - void (*callback)(BT_HDR *); - uint8_t status; - BT_HDR *command; - void *context; -} command_status_hack_t; - -/* callbacks -*/ -typedef void (*tBTU_TIMER_CALLBACK)(TIMER_LIST_ENT *p_tle); -typedef void (*tBTU_EVENT_CALLBACK)(BT_HDR *p_hdr); - - -/* Define the timer types maintained by BTU -*/ -#define BTU_TTYPE_BTM_DEV_CTL 1 -#define BTU_TTYPE_L2CAP_LINK 2 -#define BTU_TTYPE_L2CAP_CHNL 3 -#define BTU_TTYPE_L2CAP_HOLD 4 -#define BTU_TTYPE_SDP 5 -#define BTU_TTYPE_BTM_SCO 6 -#define BTU_TTYPE_BTM_ACL 9 -#define BTU_TTYPE_BTM_RMT_NAME 10 -#define BTU_TTYPE_RFCOMM_MFC 11 -#define BTU_TTYPE_RFCOMM_PORT 12 -#define BTU_TTYPE_TCS_L2CAP 13 -#define BTU_TTYPE_TCS_CALL 14 -#define BTU_TTYPE_TCS_WUG 15 -#define BTU_TTYPE_AUTO_SYNC 16 -#define BTU_TTYPE_CTP_RECON 17 -#define BTU_TTYPE_CTP_T100 18 -#define BTU_TTYPE_CTP_GUARD 19 -#define BTU_TTYPE_CTP_DETACH 20 - -#define BTU_TTYPE_SPP_CONN_RETRY 21 -#define BTU_TTYPE_USER_FUNC 22 - -#define BTU_TTYPE_FTP_DISC 25 -#define BTU_TTYPE_OPP_DISC 26 - -#define BTU_TTYPE_CTP_TL_DISCVY 28 -#define BTU_TTYPE_IPFRAG_TIMER 29 -#define BTU_TTYPE_HSP2_AT_CMD_TO 30 -#define BTU_TTYPE_HSP2_REPEAT_RING 31 - -#define BTU_TTYPE_CTP_GW_INIT 32 -#define BTU_TTYPE_CTP_GW_CONN 33 -#define BTU_TTYPE_CTP_GW_IDLE 35 - -#define BTU_TTYPE_ICP_L2CAP 36 -#define BTU_TTYPE_ICP_T100 37 - -#define BTU_TTYPE_HSP2_WAIT_OK 38 - -/* HCRP Timers */ -#define BTU_TTYPE_HCRP_NOTIF_REG 39 -#define BTU_TTYPE_HCRP_PROTO_RSP 40 -#define BTU_TTYPE_HCRP_CR_GRANT 41 -#define BTU_TTYPE_HCRP_CR_CHECK 42 -#define BTU_TTYPE_HCRP_W4_CLOSE 43 - -/* HCRPM Timers */ -#define BTU_TTYPE_HCRPM_NOTIF_REG 44 -#define BTU_TTYPE_HCRPM_NOTIF_KEEP 45 -#define BTU_TTYPE_HCRPM_API_RSP 46 -#define BTU_TTYPE_HCRPM_W4_OPEN 47 -#define BTU_TTYPE_HCRPM_W4_CLOSE 48 - -/* BNEP Timers */ -#define BTU_TTYPE_BNEP 50 - -#define BTU_TTYPE_HSP2_SDP_FAIL_TO 55 -#define BTU_TTYPE_HSP2_SDP_RTRY_TO 56 - -/* BTU internal */ -/* unused 60 */ - -#define BTU_TTYPE_AVDT_CCB_RET 61 -#define BTU_TTYPE_AVDT_CCB_RSP 62 -#define BTU_TTYPE_AVDT_CCB_IDLE 63 -#define BTU_TTYPE_AVDT_SCB_TC 64 - -#define BTU_TTYPE_HID_DEV_REPAGE_TO 65 -#define BTU_TTYPE_HID_HOST_REPAGE_TO 66 - -#define BTU_TTYPE_HSP2_DELAY_CKPD_RCV 67 - -#define BTU_TTYPE_SAP_TO 68 - -/* BPP Timer */ -#define BTU_TTYPE_BPP_REF_CHNL 72 - -/* LP HC idle Timer */ -#define BTU_TTYPE_LP_HC_IDLE_TO 74 - -/* Patch RAM Timer */ -#define BTU_TTYPE_PATCHRAM_TO 75 - -/* eL2CAP Info Request and other proto cmds timer */ -#define BTU_TTYPE_L2CAP_FCR_ACK 78 -#define BTU_TTYPE_L2CAP_INFO 79 -/* L2CAP update connection parameters timer */ -#define BTU_TTYPE_L2CAP_UPDA_CONN_PARAMS 80 - -#define BTU_TTYPE_MCA_CCB_RSP 98 - -/* BTU internal timer for BLE activity */ -#define BTU_TTYPE_BLE_INQUIRY 99 -#define BTU_TTYPE_BLE_GAP_LIM_DISC 100 -#define BTU_TTYPE_ATT_WAIT_FOR_RSP 101 -#define BTU_TTYPE_SMP_PAIRING_CMD 102 -#define BTU_TTYPE_BLE_RANDOM_ADDR 103 -#define BTU_TTYPE_ATT_WAIT_FOR_APP_RSP 104 -#define BTU_TTYPE_ATT_WAIT_FOR_IND_ACK 105 - -#define BTU_TTYPE_BLE_GAP_FAST_ADV 106 -#define BTU_TTYPE_BLE_OBSERVE 107 - -#define BTU_TTYPE_UCD_TO 108 -#define BTU_TTYPE_BLE_SCAN 109 - - -/* This is the inquiry response information held by BTU, and available -** to applications. -*/ -typedef struct { - BD_ADDR remote_bd_addr; - UINT8 page_scan_rep_mode; - UINT8 page_scan_per_mode; - UINT8 page_scan_mode; - DEV_CLASS dev_class; - UINT16 clock_offset; -} tBTU_INQ_INFO; - - - -#define BTU_MAX_REG_TIMER (2) /* max # timer callbacks which may register */ -#define BTU_MAX_REG_EVENT (6) /* max # event callbacks which may register */ -#define BTU_DEFAULT_DATA_SIZE (0x2a0) - -#if (BLE_INCLUDED == TRUE) -#define BTU_DEFAULT_BLE_DATA_SIZE (27) -#endif - -/* structure to hold registered timers */ -typedef struct { - TIMER_LIST_ENT *p_tle; /* timer entry */ - tBTU_TIMER_CALLBACK timer_cb; /* callback triggered when timer expires */ -} tBTU_TIMER_REG; - -/* structure to hold registered event callbacks */ -typedef struct { - UINT16 event_range; /* start of event range */ - tBTU_EVENT_CALLBACK event_cb; /* callback triggered when event is in range */ -} tBTU_EVENT_REG; - -#define NFC_MAX_LOCAL_CTRLS 0 - -/* the index to BTU command queue array */ -#define NFC_CONTROLLER_ID (1) -#define BTU_MAX_LOCAL_CTRLS (1 + NFC_MAX_LOCAL_CTRLS) /* only BR/EDR */ - -/* Define structure holding BTU variables -*/ -typedef struct { - tBTU_TIMER_REG timer_reg[BTU_MAX_REG_TIMER]; - tBTU_EVENT_REG event_reg[BTU_MAX_REG_EVENT]; - - BOOLEAN reset_complete; /* TRUE after first ack from device received */ - UINT8 trace_level; /* Trace level for HCI layer */ -} tBTU_CB; - -/* -#ifdef __cplusplus -extern "C" { -#endif -*/ -/* Global BTU data */ -#if BTU_DYNAMIC_MEMORY == FALSE -extern tBTU_CB btu_cb; -#else -extern tBTU_CB *btu_cb_ptr; -#define btu_cb (*btu_cb_ptr) -#endif - -extern const BD_ADDR BT_BD_ANY; - -/* Functions provided by btu_task.c -************************************ -*/ -void btu_start_timer (TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout); -void btu_stop_timer (TIMER_LIST_ENT *p_tle); -void btu_free_timer (TIMER_LIST_ENT *p_tle); -void btu_start_timer_oneshot(TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout); -void btu_stop_timer_oneshot(TIMER_LIST_ENT *p_tle); - -void btu_uipc_rx_cback(BT_HDR *p_msg); - -/* -** Quick Timer -*/ -#if defined(QUICK_TIMER_TICKS_PER_SEC) && (QUICK_TIMER_TICKS_PER_SEC > 0) -void btu_start_quick_timer (TIMER_LIST_ENT *p_tle, UINT16 type, UINT32 timeout); -void btu_stop_quick_timer (TIMER_LIST_ENT *p_tle); -void btu_free_quick_timer (TIMER_LIST_ENT *p_tle); -void btu_process_quick_timer_evt (void); -#endif - -#if (defined(HCILP_INCLUDED) && HCILP_INCLUDED == TRUE) -void btu_check_bt_sleep (void); -#endif - -/* Functions provided by btu_hcif.c -************************************ -*/ -void btu_hcif_process_event (UINT8 controller_id, BT_HDR *p_buf); -void btu_hcif_send_cmd (UINT8 controller_id, BT_HDR *p_msg); -void btu_hcif_send_host_rdy_for_data(void); -void btu_hcif_cmd_timeout (UINT8 controller_id); - -/* Functions provided by btu_core.c -************************************ -*/ -void btu_init_core(void); -void btu_free_core(void); - -void BTU_StartUp(void); -void BTU_ShutDown(void); - -void btu_task_start_up(void); -void btu_task_shut_down(void); - -UINT16 BTU_BleAclPktSize(void); - -/* -#ifdef __cplusplus -} -#endif -*/ - -#endif diff --git a/tools/sdk/include/bluedroid/buffer.h b/tools/sdk/include/bluedroid/buffer.h deleted file mode 100644 index fd1b2fa3732..00000000000 --- a/tools/sdk/include/bluedroid/buffer.h +++ /dev/null @@ -1,59 +0,0 @@ -/****************************************************************************** - * - * 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/include/bluedroid/buffer_allocator.h b/tools/sdk/include/bluedroid/buffer_allocator.h deleted file mode 100644 index 9dd7ba7c453..00000000000 --- a/tools/sdk/include/bluedroid/buffer_allocator.h +++ /dev/null @@ -1,25 +0,0 @@ -/****************************************************************************** - * - * 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_ALLOCATOR_H_ - -#include "allocator.h" - -const allocator_t *buffer_allocator_get_interface(); - -#endif /*_BUFFER_ALLOCATOR_H_*/ diff --git a/tools/sdk/include/bluedroid/button_pro.h b/tools/sdk/include/bluedroid/button_pro.h deleted file mode 100644 index cbc2d68d51c..00000000000 --- a/tools/sdk/include/bluedroid/button_pro.h +++ /dev/null @@ -1,120 +0,0 @@ -#include "prf_defs.h" -// 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. - - -#if (BUT_PROFILE_CFG) -#include "bt_target.h" -#include "gatt_api.h" -#include "gattdefs.h" -#include "esp_gatt_api.h" - -#define KEY_SUCCESS GATT_SUCCESS -#define KEY_ILLEGAL_PARAM GATT_ILLEGAL_PARAMETER -#define KEY_NO_RESOURCES GATT_NO_RESOURCES - -//define the key serivce uuid -#define ATT_SVC_BUTTON 0xFFFF -//define the key Char uuid -#define ATT_CHAR_BUTTON_WIT 0xFF01 -#define ATT_CHAR_BUTTON_NTF 0xFF02 - -#define BUTTON_PRESS_NTF_CFG 0x01 - -#define BUTTON_VAL_MAX_LEN (10) - -#define BUTT_MAX_APPS GATT_CL_MAX_LCB - -#define BUT_MAX_STRING_DATA 7 - -typedef void (*but_prf_cb_t)(uint8_t app_id, uint8_t event, uint16_t len, uint8_t *value); - -#ifndef BUT_MAX_INT_NUM -#define BUT_MAX_INT_NUM 4 -#endif - -enum { - RECEIVE_NET_PASSWD_EVT, - RECEIVE_NET_SSD_EVT, - RECEIVE_EVT_MAX -}; - -/// button Service Attributes Indexes -enum { - KEY_IDX_SVC, - KEY_IDX_BUTTON_WIT_CHAR, - KEY_IDX_BUTTON_WIT_VAL, - KEY_IDX_BUTTON_NTF_CHAR, - KEY_IDX_BUTTON_NTF_VAL, - KEY_IDX_BUTTON_NTF_CFG, - - KEY_IDX_NB, -}; - -typedef struct { - BD_ADDR remote_bda; - BOOLEAN need_rsp; - uint16_t clt_cfg; -} but_write_data_t; - -typedef struct { - BOOLEAN in_use; - BOOLEAN congest; - uint16_t conn_id; - BOOLEAN connected; - BD_ADDR remote_bda; - uint32_t trans_id; - uint8_t cur_srvc_id; - -} but_clcb_t; - - -typedef struct { - uint8_t app_id; - uint16_t but_wirt_hdl; - uint16_t but_ntf_hdl; - uint16_t but_cfg_hdl; - - but_prf_cb_t p_cback; - -} but_inst_t; - - -/* service engine control block */ -typedef struct { - but_clcb_t clcb; /* connection link*/ - esp_gatt_if_t gatt_if; - BOOLEAN enabled; - BOOLEAN is_primery; - but_inst_t button_inst; - uint8_t inst_id; -} button_env_cb_t; - -void Button_CreateService(void); - -but_clcb_t *button_env_clcb_alloc(uint16_t conn_id, BD_ADDR bda); - -uint16_t button_env_find_conn_id_by_bd_adddr(BD_ADDR bda); - -BOOLEAN button_env_clcb_dealloc(uint16_t conn_id); - -esp_gatt_status_t button_init(but_prf_cb_t call_back); - -void button_disable(uint16_t connid); - -void button_msg_notify(uint16_t len, uint8_t *button_msg); - -extern button_env_cb_t button_cb_env; - -#endif ///BUT_PROFILE_CFG diff --git a/tools/sdk/include/bluedroid/config.h b/tools/sdk/include/bluedroid/config.h deleted file mode 100644 index 41f5ddb18a0..00000000000 --- a/tools/sdk/include/bluedroid/config.h +++ /dev/null @@ -1,148 +0,0 @@ -// 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, 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/include/bluedroid/controller.h b/tools/sdk/include/bluedroid/controller.h deleted file mode 100644 index bffa714f433..00000000000 --- a/tools/sdk/include/bluedroid/controller.h +++ /dev/null @@ -1,86 +0,0 @@ -/****************************************************************************** - * - * 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 _CONTROLLER_H_ -#define _CONTROLLER_H_ - -#include -#include - -#include "bt_target.h" -#include "bdaddr.h" -#include "device_features.h" -#include "hci_layer.h" -#include "hci_packet_factory.h" -#include "hci_packet_parser.h" - -typedef struct controller_t { - void (*start_up)(void); - void (*shut_down)(void); - bool (*get_is_ready)(void); - - const bt_bdaddr_t *(*get_address)(void); - const bt_version_t *(*get_bt_version)(void); - - const bt_device_features_t *(*get_features_classic)(int index); - - uint8_t (*get_last_features_classic_index)(void); - - const bt_device_features_t *(*get_features_ble)(void); - const uint8_t *(*get_ble_supported_states)(void); - - bool (*supports_simple_pairing)(void); - bool (*supports_secure_connections)(void); - bool (*supports_simultaneous_le_bredr)(void); - bool (*supports_reading_remote_extended_features)(void); - bool (*supports_interlaced_inquiry_scan)(void); - bool (*supports_rssi_with_inquiry_results)(void); - bool (*supports_extended_inquiry_response)(void); - bool (*supports_master_slave_role_switch)(void); - - bool (*supports_ble)(void); - bool (*supports_ble_packet_extension)(void); - bool (*supports_ble_connection_parameters_request)(void); - bool (*supports_ble_privacy)(void); - - // Get the cached acl data sizes for the controller. - uint16_t (*get_acl_data_size_classic)(void); - uint16_t (*get_acl_data_size_ble)(void); - - // Get the cached acl packet sizes for the controller. - // This is a convenience function for the respective - // acl data size + size of the acl header. - uint16_t (*get_acl_packet_size_classic)(void); - uint16_t (*get_acl_packet_size_ble)(void); - - uint16_t (*get_ble_default_data_packet_length)(void); - uint16_t (*get_ble_default_data_packet_txtime)(void); - - // Get the number of acl packets the controller can buffer. - uint16_t (*get_acl_buffer_count_classic)(void); - uint8_t (*get_acl_buffer_count_ble)(void); - - uint8_t (*get_ble_white_list_size)(void); - - uint8_t (*get_ble_resolving_list_max_size)(void); - void (*set_ble_resolving_list_max_size)(int resolving_list_max_size); -} controller_t; - -const controller_t *controller_get_interface(); - -#endif /*_CONTROLLER_H_*/ diff --git a/tools/sdk/include/bluedroid/device_features.h b/tools/sdk/include/bluedroid/device_features.h deleted file mode 100644 index 360d3768d60..00000000000 --- a/tools/sdk/include/bluedroid/device_features.h +++ /dev/null @@ -1,29 +0,0 @@ -/****************************************************************************** - * - * 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 _DEVICE_FEATURES_H_ -#define _DEVICE_FEATURES_H_ - -#include - -// Represents a page of device feature enabled/disabled bits returned -// by the local controller. See the bluetooth spec for bit indexes. -typedef struct { - uint8_t as_array[8]; -} bt_device_features_t; - -#endif /*_DEVICE_FEATURES_H_*/ diff --git a/tools/sdk/include/bluedroid/dis_api.h b/tools/sdk/include/bluedroid/dis_api.h deleted file mode 100644 index 5b8cfc5f78e..00000000000 --- a/tools/sdk/include/bluedroid/dis_api.h +++ /dev/null @@ -1,338 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2013 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/******************************************************************************* -** -** Header file for profile folder. -** -********************************************************************************/ - -#ifndef SRVC_DIS_API_H -#define SRVC_DIS_API_H - -#include "bt_target.h" -#include "gatt_api.h" -#include "gattdefs.h" -#include "esp_gatts_api.h" - -#define DIS_SUCCESS GATT_SUCCESS -#define DIS_ILLEGAL_PARAM GATT_ILLEGAL_PARAMETER -#define DIS_NO_RESOURCES GATT_NO_RESOURCES -typedef UINT8 tDIS_STATUS; - - -/***************************************************************************** -** Data structure for DIS -*****************************************************************************/ - -#define DIS_ATTR_SYS_ID_BIT 0x0001 -#define DIS_ATTR_MODEL_NUM_BIT 0x0002 -#define DIS_ATTR_SERIAL_NUM_BIT 0x0004 -#define DIS_ATTR_FW_NUM_BIT 0x0008 -#define DIS_ATTR_HW_NUM_BIT 0x0010 -#define DIS_ATTR_SW_NUM_BIT 0x0020 -#define DIS_ATTR_MANU_NAME_BIT 0x0040 -#define DIS_ATTR_IEEE_DATA_BIT 0x0080 -#define DIS_ATTR_PNP_ID_BIT 0x0100 -typedef UINT16 tDIS_ATTR_MASK; - -#define DIS_ATTR_ALL_MASK 0xffff - -typedef tDIS_ATTR_MASK tDIS_ATTR_BIT ; - -#define DIS_MAX_NUM_INC_SVR 0 -#define DIS_MAX_CHAR_NUM 9 -#define DIS_MAX_ATTR_NUM (DIS_MAX_CHAR_NUM * 2 + DIS_MAX_NUM_INC_SVR + 1) - -#ifndef DIS_ATTR_DB_SIZE -#define DIS_ATTR_DB_SIZE GATT_DB_MEM_SIZE(DIS_MAX_NUM_INC_SVR, DIS_MAX_CHAR_NUM, 0) -#endif - -#define DIS_SYSTEM_ID_SIZE 8 -#define DIS_PNP_ID_SIZE 7 - - -typedef struct { - UINT16 uuid; - UINT16 handle; -} tDIS_DB_ENTRY; - -typedef struct { - UINT16 len; - UINT8 *p_data; -} tDIS_STRING; - -typedef struct { - UINT16 vendor_id; - UINT16 product_id; - UINT16 product_version; - UINT8 vendor_id_src; - -} tDIS_PNP_ID; - -typedef union { - UINT64 system_id; - tDIS_PNP_ID pnp_id; - tDIS_STRING data_str; -} tDIS_ATTR; - -#define DIS_MAX_STRING_DATA 7 - -typedef struct { - UINT16 attr_mask; - UINT64 system_id; - tDIS_PNP_ID pnp_id; - UINT8 *data_string[DIS_MAX_STRING_DATA]; -} tDIS_VALUE; - -//typedef void (tDIS_READ_CBACK)(BD_ADDR addr, tDIS_VALUE *p_dis_value); - -typedef struct { - tDIS_DB_ENTRY dis_attr[DIS_MAX_CHAR_NUM]; - tDIS_VALUE dis_value; - -// tDIS_READ_CBACK *p_read_dis_cback; - - UINT16 service_handle; - UINT16 max_handle; - - bool enabled; - - // UINT8 dis_read_uuid_idx; - // tDIS_ATTR_MASK request_mask; -} tDIS_CB; - -/***************************************************************************** -** Data structure used by Battery Service -*****************************************************************************/ - -#ifndef BA_MAX_INT_NUM -#define BA_MAX_INT_NUM 4 -#endif - -#define BATTERY_LEVEL_SIZE 1 - -typedef struct { - BD_ADDR remote_bda; - BOOLEAN need_rsp; - UINT16 clt_cfg; -} tBA_WRITE_DATA; - -#define BA_READ_CLT_CFG_REQ 1 -#define BA_READ_PRE_FMT_REQ 2 -#define BA_READ_RPT_REF_REQ 3 -#define BA_READ_LEVEL_REQ 4 -#define BA_WRITE_CLT_CFG_REQ 5 - -typedef void (tBA_CBACK)(UINT32 trans_id, UINT16 conn_id, UINT8 app_id, UINT8 event, tBA_WRITE_DATA *p_data); - -#define BA_LEVEL_NOTIFY 0x01 -#define BA_LEVEL_PRE_FMT 0x02 -#define BA_LEVEL_RPT_REF 0x04 -typedef UINT8 tBA_LEVEL_DESCR; - -typedef struct { - BOOLEAN is_pri; - tBA_LEVEL_DESCR ba_level_descr; - tGATT_TRANSPORT transport; - tBA_CBACK *p_cback; - -} tBA_REG_INFO; - -typedef union { - UINT8 ba_level; - UINT16 clt_cfg; - tGATT_CHAR_RPT_REF rpt_ref; - tGATT_CHAR_PRES pres_fmt; -} tBA_RSP_DATA; - -typedef struct { - UINT8 app_id; - UINT16 ba_level_hdl; - UINT16 clt_cfg_hdl; - UINT16 rpt_ref_hdl; - UINT16 pres_fmt_hdl; - - tBA_CBACK *p_cback; - - UINT16 pending_handle; - //UINT8 pending_clcb_idx; - UINT8 pending_evt; -} tBA_INST; - -typedef struct { - tBA_INST battery_inst[BA_MAX_INT_NUM]; - UINT8 inst_id; - bool enabled; -} tBATTERY_CB; -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif -/***************************************************************************** -** Service Engine API -*****************************************************************************/ -/******************************************************************************* -** -** Function srvc_eng_init -** -** Description Initializa the GATT Service engine, register a GATT application -** as for a central service management. -** -*******************************************************************************/ -//extern tGATT_STATUS srvc_eng_init (void); - - -/***************************************************************************** -** DIS Server Function -*****************************************************************************/ - -extern bool dis_valid_handle_range(UINT16 handle); -/******************************************************************************* -** -** Function DIS_Init -** -** Description Initializa the Device Information Service Server. -** -*******************************************************************************/ -extern void DIS_Init (tBTA_GATTS_IF gatt_if, tDIS_ATTR_MASK dis_attr_mask); -/******************************************************************************* -** -** Function DIS_SrUpdate -** -** Description Update the DIS server attribute values -** -*******************************************************************************/ -extern tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT dis_attr_bit, tDIS_ATTR *p_info); -/******************************************************************************* -** -** Function dis_AddChar -** -** Description add characteristic for dis -** -*******************************************************************************/ -extern void dis_AddChar(UINT16 service_id); -/******************************************************************************* -** dis_s_read_attr_value -** -** Process read DIS attribute request. -*******************************************************************************/ - -extern void dis_s_read_attr_value (tGATTS_DATA *p_data, tGATT_VALUE *p_value, - UINT32 trans_id, UINT16 conn_id); -/***************************************************************************** -** DIS Client Function -*****************************************************************************/ -/******************************************************************************* -** -** Function DIS_ReadDISInfo -** -** Description Read remote device DIS information. -** -** Returns void -** -*******************************************************************************/ -//extern BOOLEAN DIS_ReadDISInfo(BD_ADDR peer_bda, tDIS_READ_CBACK *p_cback, -// tDIS_ATTR_MASK mask); - -/******************************************************************************* -** BATTERY SERVICE API -*******************************************************************************/ -/*************************************************************** -** -** Function bas_register -** -** Description register app for battery service -** -****************************************************************/ -extern void bas_register(void); -/*************************************************************** -** -** Function bas_init -** -** Description register battery service -** -****************************************************************/ -extern void bas_init(tBTA_GATTS_IF gatt_if, UINT16 app_id); - -/*************************************************************** -** -** Function bas_AddChar -** -** Description add characteristic for battery service -** -****************************************************************/ -extern void bas_AddChar(UINT16 service_id, tBT_UUID *char_uuid); -/*************************************************************** -** -** Function bas_AddCharDescr -** -** Description add descriptor for battery service if needed -** -****************************************************************/ -extern void bas_AddCharDescr(UINT16 service_id, UINT16 attr_id); -/*************************************************************** -** -** Function bas_service_cmpl -** -** Description create battery service complete -** -****************************************************************/ -extern void bas_service_cmpl(UINT16 service_id, tBTA_GATT_STATUS status); -/******************************************************************************* -** -** Function Battery_Rsp -** -** Description Respond to a battery service request -** -*******************************************************************************/ -extern void Battery_Rsp (UINT32 trans_id, UINT16 conn_id, UINT8 app_id, - tGATT_STATUS st, UINT8 event, tBA_RSP_DATA *p_rsp); -/******************************************************************************* -** -** Function Battery_Notify -** -** Description Send battery level notification -** -*******************************************************************************/ -extern void Battery_Notify (UINT16 conn_id, UINT8 app_id, BD_ADDR remote_bda, UINT8 battery_level); - -/***************************************************************************** -** Function bas_s_read_attr_value -** -** Description it will be called when client send a read request -******************************************************************************/ -extern void bas_s_read_attr_value(tGATTS_DATA *p_data, UINT32 trans_id, UINT16 conn_id); -/***************************************************************************** -** Function bas_s_write_attr_value -** -** Description it will be called when client send a write request -******************************************************************************/ -extern void bas_s_write_attr_value(tGATTS_DATA *p_data, UINT32 trans_id, - UINT16 conn_id, BD_ADDR bd_addr); - -extern void gatts_server_test(void); -#ifdef __cplusplus - -} -#endif - -#endif diff --git a/tools/sdk/include/bluedroid/dyn_mem.h b/tools/sdk/include/bluedroid/dyn_mem.h deleted file mode 100644 index 223ae9f9010..00000000000 --- a/tools/sdk/include/bluedroid/dyn_mem.h +++ /dev/null @@ -1,217 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 DYN_MEM_H -#define DYN_MEM_H - -#include "sdkconfig.h" -#if CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY -#define BTU_DYNAMIC_MEMORY TRUE -#define BTM_DYNAMIC_MEMORY TRUE -#define L2C_DYNAMIC_MEMORY TRUE -#define GATT_DYNAMIC_MEMORY TRUE -#define SMP_DYNAMIC_MEMORY TRUE -#define BTA_DYNAMIC_MEMORY TRUE -#define SDP_DYNAMIC_MEMORY TRUE -#define RFC_DYNAMIC_MEMORY TRUE -#define TCS_DYNAMIC_MEMORY TRUE -#define BNEP_DYNAMIC_MEMORY TRUE -#define AVDT_DYNAMIC_MEMORY TRUE -#define AVCT_DYNAMIC_MEMORY TRUE -#define MCA_DYNAMIC_MEMORY TRUE -#define A2D_DYNAMIC_MEMORY TRUE -#define VDP_DYNAMIC_MEMORY TRUE -#define AVRC_DYNAMIC_MEMORY TRUE -#define BIP_DYNAMIC_MEMORY TRUE -#define BPP_DYNAMIC_MEMORY TRUE -#define CTP_DYNAMIC_MEMORY TRUE -#define FTP_DYNAMIC_MEMORY TRUE -#define HCRP_DYNAMIC_MEMORY TRUE -#define HFP_DYNAMIC_MEMORY TRUE -#define HID_DYNAMIC_MEMORY TRUE -#define HSP2_DYNAMIC_MEMORY TRUE -#define ICP_DYNAMIC_MEMORY TRUE -#define OPP_DYNAMIC_MEMORY TRUE -#define PAN_DYNAMIC_MEMORY TRUE -#define SPP_DYNAMIC_MEMORY TRUE -#define SLIP_DYNAMIC_MEMORY TRUE -#define LLCP_DYNAMIC_MEMORY TRUE -#define BTC_SBC_DEC_DYNAMIC_MEMORY TRUE - -#else /* #if CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY */ - -#define SDP_DYNAMIC_MEMORY FALSE -#define RFC_DYNAMIC_MEMORY FALSE -#define TCS_DYNAMIC_MEMORY FALSE -#define BNEP_DYNAMIC_MEMORY FALSE -#define AVDT_DYNAMIC_MEMORY FALSE -#define AVCT_DYNAMIC_MEMORY FALSE -#define MCA_DYNAMIC_MEMORY FALSE -#define A2D_DYNAMIC_MEMORY FALSE -#define VDP_DYNAMIC_MEMORY FALSE -#define AVRC_DYNAMIC_MEMORY FALSE -#define BIP_DYNAMIC_MEMORY FALSE -#define BPP_DYNAMIC_MEMORY FALSE -#define CTP_DYNAMIC_MEMORY FALSE -#define FTP_DYNAMIC_MEMORY FALSE -#define HCRP_DYNAMIC_MEMORY FALSE -#define HFP_DYNAMIC_MEMORY FALSE -#define HID_DYNAMIC_MEMORY FALSE -#define HSP2_DYNAMIC_MEMORY FALSE -#define ICP_DYNAMIC_MEMORY FALSE -#define OPP_DYNAMIC_MEMORY FALSE -#define PAN_DYNAMIC_MEMORY FALSE -#define SPP_DYNAMIC_MEMORY FALSE -#define SLIP_DYNAMIC_MEMORY FALSE -#define LLCP_DYNAMIC_MEMORY FALSE -#define BTC_SBC_DEC_DYNAMIC_MEMORY FALSE - -#endif /* #if CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY */ -/**************************************************************************** -** Define memory usage for each CORE component (if not defined in bdroid_buildcfg.h) -** The default for each component is to use static memory allocations. -*/ -#ifndef BTU_DYNAMIC_MEMORY -#define BTU_DYNAMIC_MEMORY FALSE -#endif - -#ifndef BTM_DYNAMIC_MEMORY -#define BTM_DYNAMIC_MEMORY FALSE -#endif - -#ifndef SDP_DYNAMIC_MEMORY -#define SDP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef L2C_DYNAMIC_MEMORY -#define L2C_DYNAMIC_MEMORY FALSE -#endif - -#ifndef RFC_DYNAMIC_MEMORY -#define RFC_DYNAMIC_MEMORY FALSE -#endif - -#ifndef TCS_DYNAMIC_MEMORY -#define TCS_DYNAMIC_MEMORY FALSE -#endif - -#ifndef BNEP_DYNAMIC_MEMORY -#define BNEP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef AVDT_DYNAMIC_MEMORY -#define AVDT_DYNAMIC_MEMORY FALSE -#endif - -#ifndef AVCT_DYNAMIC_MEMORY -#define AVCT_DYNAMIC_MEMORY FALSE -#endif - -#ifndef MCA_DYNAMIC_MEMORY -#define MCA_DYNAMIC_MEMORY FALSE -#endif - -#ifndef GATT_DYNAMIC_MEMORY -#define GATT_DYNAMIC_MEMORY FALSE -#endif - -#ifndef SMP_DYNAMIC_MEMORY -#define SMP_DYNAMIC_MEMORY FALSE -#endif - -/**************************************************************************** -** Define memory usage for each PROFILE component (if not defined in bdroid_buildcfg.h) -** The default for each component is to use static memory allocations. -*/ -#ifndef A2D_DYNAMIC_MEMORY -#define A2D_DYNAMIC_MEMORY FALSE -#endif - -#ifndef VDP_DYNAMIC_MEMORY -#define VDP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef AVRC_DYNAMIC_MEMORY -#define AVRC_DYNAMIC_MEMORY FALSE -#endif - -#ifndef BIP_DYNAMIC_MEMORY -#define BIP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef BPP_DYNAMIC_MEMORY -#define BPP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef CTP_DYNAMIC_MEMORY -#define CTP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef FTP_DYNAMIC_MEMORY -#define FTP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef HCRP_DYNAMIC_MEMORY -#define HCRP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef HFP_DYNAMIC_MEMORY -#define HFP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef HID_DYNAMIC_MEMORY -#define HID_DYNAMIC_MEMORY FALSE -#endif - -#ifndef HSP2_DYNAMIC_MEMORY -#define HSP2_DYNAMIC_MEMORY FALSE -#endif - -#ifndef ICP_DYNAMIC_MEMORY -#define ICP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef OPP_DYNAMIC_MEMORY -#define OPP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef PAN_DYNAMIC_MEMORY -#define PAN_DYNAMIC_MEMORY FALSE -#endif - -#ifndef SPP_DYNAMIC_MEMORY -#define SPP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef SLIP_DYNAMIC_MEMORY -#define SLIP_DYNAMIC_MEMORY FALSE -#endif - -#ifndef LLCP_DYNAMIC_MEMORY -#define LLCP_DYNAMIC_MEMORY FALSE -#endif - -/**************************************************************************** -** Define memory usage for BTA (if not defined in bdroid_buildcfg.h) -** The default for each component is to use static memory allocations. -*/ -#ifndef BTA_DYNAMIC_MEMORY -#define BTA_DYNAMIC_MEMORY FALSE -#endif - -#endif /* #ifdef DYN_MEM_H */ - diff --git a/tools/sdk/include/bluedroid/esp_gap_ble_api.h b/tools/sdk/include/bluedroid/esp_gap_ble_api.h deleted file mode 100644 index 6aa07f24df9..00000000000 --- a/tools/sdk/include/bluedroid/esp_gap_ble_api.h +++ /dev/null @@ -1,1029 +0,0 @@ -// 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 btm_api.h */ -#define ESP_LE_KEY_NONE 0 /* relate to BTM_LE_KEY_NONE in btm_api.h */ -#define ESP_LE_KEY_PENC (1 << 0) /*!< encryption key, encryption information of peer device */ /* relate to BTM_LE_KEY_PENC in btm_api.h */ -#define ESP_LE_KEY_PID (1 << 1) /*!< identity key of the peer device */ /* relate to BTM_LE_KEY_PID in btm_api.h */ -#define ESP_LE_KEY_PCSRK (1 << 2) /*!< peer SRK */ /* relate to BTM_LE_KEY_PCSRK in btm_api.h */ -#define ESP_LE_KEY_PLK (1 << 3) /*!< Link key*/ /* relate to BTM_LE_KEY_PLK in btm_api.h */ -#define ESP_LE_KEY_LLK (ESP_LE_KEY_PLK << 4) /* relate to BTM_LE_KEY_LLK in 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 btm_api.h */ -#define ESP_LE_KEY_LID (ESP_LE_KEY_PID << 4) /*!< master device ID key */ /* relate to BTM_LE_KEY_LID in 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 btm_api.h */ -typedef uint8_t esp_ble_key_type_t; - -/* relate to BTM_LE_AUTH_xxx in btm_api.h */ -#define ESP_LE_AUTH_NO_BOND 0x00 /*!< 0*/ /* relate to BTM_LE_AUTH_NO_BOND in btm_api.h */ -#define ESP_LE_AUTH_BOND 0x01 /*!< 1 << 0 */ /* relate to BTM_LE_AUTH_BOND in btm_api.h */ -#define ESP_LE_AUTH_REQ_MITM (1 << 2) /*!< 1 << 2 */ /* relate to BTM_LE_AUTH_REQ_MITM in btm_api.h */ -#define ESP_LE_AUTH_REQ_SC_ONLY (1 << 3) /*!< 1 << 3 */ /* relate to BTM_LE_AUTH_REQ_SC_ONLY in 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 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 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 btm_api.h */ -typedef uint8_t esp_ble_auth_req_t; /*!< combination of the above bit pattern */ - -/* relate to BTM_IO_CAP_xxx in btm_api.h */ -#define ESP_IO_CAP_OUT 0 /*!< DisplayOnly */ /* relate to BTM_IO_CAP_OUT in btm_api.h */ -#define ESP_IO_CAP_IO 1 /*!< DisplayYesNo */ /* relate to BTM_IO_CAP_IO in btm_api.h */ -#define ESP_IO_CAP_IN 2 /*!< KeyboardOnly */ /* relate to BTM_IO_CAP_IN in btm_api.h */ -#define ESP_IO_CAP_NONE 3 /*!< NoInputNoOutput */ /* relate to BTM_IO_CAP_NONE in btm_api.h */ -#define ESP_IO_CAP_KBDISP 4 /*!< Keyboard display */ /* relate to BTM_IO_CAP_KBDISP in btm_api.h */ -typedef uint8_t esp_ble_io_cap_t; /*!< combination of the io capability */ - -/// GAP BLE callback event type -typedef enum { - 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 */ - ESP_GAP_BLE_AUTH_CMPL_EVT, /* 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 */ - 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 */ - ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT, /*!< 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 lenght 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 */ - ESP_GAP_BLE_EVT_MAX, -} esp_gap_ble_cb_event_t; -/// 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 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 btm_ble_api.h */ - ESP_BLE_AD_TYPE_16SRV_PART = 0x02, /* relate to BTM_BLE_AD_TYPE_16SRV_PART in btm_ble_api.h */ - ESP_BLE_AD_TYPE_16SRV_CMPL = 0x03, /* relate to BTM_BLE_AD_TYPE_16SRV_CMPL in btm_ble_api.h */ - ESP_BLE_AD_TYPE_32SRV_PART = 0x04, /* relate to BTM_BLE_AD_TYPE_32SRV_PART in btm_ble_api.h */ - ESP_BLE_AD_TYPE_32SRV_CMPL = 0x05, /* relate to BTM_BLE_AD_TYPE_32SRV_CMPL in btm_ble_api.h */ - ESP_BLE_AD_TYPE_128SRV_PART = 0x06, /* relate to BTM_BLE_AD_TYPE_128SRV_PART in btm_ble_api.h */ - ESP_BLE_AD_TYPE_128SRV_CMPL = 0x07, /* relate to BTM_BLE_AD_TYPE_128SRV_CMPL in btm_ble_api.h */ - ESP_BLE_AD_TYPE_NAME_SHORT = 0x08, /* relate to BTM_BLE_AD_TYPE_NAME_SHORT in btm_ble_api.h */ - ESP_BLE_AD_TYPE_NAME_CMPL = 0x09, /* relate to BTM_BLE_AD_TYPE_NAME_CMPL in btm_ble_api.h */ - ESP_BLE_AD_TYPE_TX_PWR = 0x0A, /* relate to BTM_BLE_AD_TYPE_TX_PWR in btm_ble_api.h */ - ESP_BLE_AD_TYPE_DEV_CLASS = 0x0D, /* relate to BTM_BLE_AD_TYPE_DEV_CLASS in btm_ble_api.h */ - ESP_BLE_AD_TYPE_SM_TK = 0x10, /* relate to BTM_BLE_AD_TYPE_SM_TK in btm_ble_api.h */ - ESP_BLE_AD_TYPE_SM_OOB_FLAG = 0x11, /* relate to BTM_BLE_AD_TYPE_SM_OOB_FLAG in btm_ble_api.h */ - ESP_BLE_AD_TYPE_INT_RANGE = 0x12, /* relate to BTM_BLE_AD_TYPE_INT_RANGE in btm_ble_api.h */ - ESP_BLE_AD_TYPE_SOL_SRV_UUID = 0x14, /* relate to BTM_BLE_AD_TYPE_SOL_SRV_UUID in btm_ble_api.h */ - ESP_BLE_AD_TYPE_128SOL_SRV_UUID = 0x15, /* relate to BTM_BLE_AD_TYPE_128SOL_SRV_UUID in btm_ble_api.h */ - ESP_BLE_AD_TYPE_SERVICE_DATA = 0x16, /* relate to BTM_BLE_AD_TYPE_SERVICE_DATA in btm_ble_api.h */ - ESP_BLE_AD_TYPE_PUBLIC_TARGET = 0x17, /* relate to BTM_BLE_AD_TYPE_PUBLIC_TARGET in btm_ble_api.h */ - ESP_BLE_AD_TYPE_RANDOM_TARGET = 0x18, /* relate to BTM_BLE_AD_TYPE_RANDOM_TARGET in btm_ble_api.h */ - ESP_BLE_AD_TYPE_APPEARANCE = 0x19, /* relate to BTM_BLE_AD_TYPE_APPEARANCE in btm_ble_api.h */ - ESP_BLE_AD_TYPE_ADV_INT = 0x1A, /* relate to BTM_BLE_AD_TYPE_ADV_INT in btm_ble_api.h */ - ESP_BLE_AD_TYPE_LE_DEV_ADDR = 0x1b, /* relate to BTM_BLE_AD_TYPE_LE_DEV_ADDR in btm_ble_api.h */ - ESP_BLE_AD_TYPE_LE_ROLE = 0x1c, /* relate to BTM_BLE_AD_TYPE_LE_ROLE in btm_ble_api.h */ - ESP_BLE_AD_TYPE_SPAIR_C256 = 0x1d, /* relate to BTM_BLE_AD_TYPE_SPAIR_C256 in btm_ble_api.h */ - ESP_BLE_AD_TYPE_SPAIR_R256 = 0x1e, /* relate to BTM_BLE_AD_TYPE_SPAIR_R256 in btm_ble_api.h */ - ESP_BLE_AD_TYPE_32SOL_SRV_UUID = 0x1f, /* relate to BTM_BLE_AD_TYPE_32SOL_SRV_UUID in btm_ble_api.h */ - ESP_BLE_AD_TYPE_32SERVICE_DATA = 0x20, /* relate to BTM_BLE_AD_TYPE_32SERVICE_DATA in btm_ble_api.h */ - ESP_BLE_AD_TYPE_128SERVICE_DATA = 0x21, /* relate to BTM_BLE_AD_TYPE_128SERVICE_DATA in btm_ble_api.h */ - ESP_BLE_AD_TYPE_LE_SECURE_CONFIRM = 0x22, /* relate to BTM_BLE_AD_TYPE_LE_SECURE_CONFIRM in btm_ble_api.h */ - ESP_BLE_AD_TYPE_LE_SECURE_RANDOM = 0x23, /* relate to BTM_BLE_AD_TYPE_LE_SECURE_RANDOM in btm_ble_api.h */ - ESP_BLE_AD_TYPE_URI = 0x24, /* relate to BTM_BLE_AD_TYPE_URI in btm_ble_api.h */ - ESP_BLE_AD_TYPE_INDOOR_POSITION = 0x25, /* relate to BTM_BLE_AD_TYPE_INDOOR_POSITION in btm_ble_api.h */ - ESP_BLE_AD_TYPE_TRANS_DISC_DATA = 0x26, /* relate to BTM_BLE_AD_TYPE_TRANS_DISC_DATA in btm_ble_api.h */ - ESP_BLE_AD_TYPE_LE_SUPPORT_FEATURE = 0x27, /* relate to BTM_BLE_AD_TYPE_LE_SUPPORT_FEATURE in btm_ble_api.h */ - ESP_BLE_AD_TYPE_CHAN_MAP_UPDATE = 0x28, /* relate to BTM_BLE_AD_TYPE_CHAN_MAP_UPDATE in btm_ble_api.h */ - ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE = 0xFF, /* relate to BTM_BLE_AD_MANUFACTURER_SPECIFIC_TYPE in 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_api.h */ -typedef enum { - ESP_BLE_SEC_ENCRYPT = 1, /* relate to BTA_DM_BLE_SEC_ENCRYPT in 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_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_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, - ESP_BLE_SM_AUTHEN_REQ_MODE, - ESP_BLE_SM_IOCAP_MODE, - ESP_BLE_SM_SET_INIT_KEY, - ESP_BLE_SM_SET_RSP_KEY, - ESP_BLE_SM_MAX_KEY_SIZE, -} esp_ble_sm_param_t; - -/// 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 */ - 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 advertising min interval */ - int max_interval; /*!< Advertising data show advertising max interval */ - 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; - -/// 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_PRA_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 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_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 informatuon 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_cmpl_t; /*!< The ble authentication complite 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 secutity type */ - -/// 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_evt_t; - -/** - * @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; -/** - * @brief Gap callback parameters union - */ -typedef union { - /** - * @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 */ - } 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 */ - - esp_ble_sec_t ble_security; /*!< ble gap security union type */ - /** - * @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 */ - /** - * @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 */ -} 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); - - -/** - * @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); - - - -/** - * @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 set the random 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 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 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. -* @return -* - ESP_OK : success -* - other : failed -* -*/ -esp_err_t esp_ble_gap_update_whitelist(bool add_remove, esp_bd_addr_t remote_bda); - -/** -* @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); - -/** -* @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); - -/** - * @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 - ESP_OK : success - * - other : failed - * - */ -uint8_t *esp_ble_resolve_adv_data(uint8_t *adv_data, uint8_t type, uint8_t *length); - -/** - * @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); - -/** - * @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 (SMP_INCLUDED == TRUE) -/** -* @brief Set a GAP security parameter value. Overrides the default value. -* -* @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 lagecy connection stage. -* -* @param[in] bd_addr : BD address of the peer -* @param[in] accept : passkey entry sucessful 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 comfirm value to the peer device in the lagecy 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. -* - < 0 : 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); - -#endif /* #if (SMP_INCLUDED == TRUE) */ - -/** -* @brief This function is to disconnect the physical connection of the peer device -* gattc maybe have multiple virtual GATT server connections when multiple app_id registed. -* 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); - -#ifdef __cplusplus -} -#endif - -#endif /* __ESP_GAP_BLE_API_H__ */ diff --git a/tools/sdk/include/bluedroid/esp_gap_bt_api.h b/tools/sdk/include/bluedroid/esp_gap_bt_api.h deleted file mode 100644 index d61e3ce9673..00000000000 --- a/tools/sdk/include/bluedroid/esp_gap_bt_api.h +++ /dev/null @@ -1,333 +0,0 @@ -// 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 - - -/// Discoverability and Connectability mode -typedef enum { - ESP_BT_SCAN_MODE_NONE = 0, /*!< Neither discoverable nor connectable */ - ESP_BT_SCAN_MODE_CONNECTABLE, /*!< Connectable but not discoverable */ - ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE /*!< both discoverable and connectable */ -} esp_bt_scan_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; /*!< devlice prpoerty value */ -} esp_bt_gap_dev_prop_t; - -/// Extended Inquiry Response data type -typedef enum { - ESP_BT_EIR_TYPE_FLAGS = 0x01, /*!< Flag with information such as BR/EDR and LE support */ - ESP_BT_EIR_TYPE_INCMPL_16BITS_UUID = 0x02, /*!< Incomplete list of 16-bit service UUIDs */ - ESP_BT_EIR_TYPE_CMPL_16BITS_UUID = 0x03, /*!< Complete list of 16-bit service UUIDs */ - ESP_BT_EIR_TYPE_INCMPL_32BITS_UUID = 0x04, /*!< Incomplete list of 32-bit service UUIDs */ - ESP_BT_EIR_TYPE_CMPL_32BITS_UUID = 0x05, /*!< Complete list of 32-bit service UUIDs */ - ESP_BT_EIR_TYPE_INCMPL_128BITS_UUID = 0x06, /*!< Incomplete list of 128-bit service UUIDs */ - ESP_BT_EIR_TYPE_CMPL_128BITS_UUID = 0x07, /*!< Complete list of 128-bit service UUIDs */ - ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME = 0x08, /*!< Shortened Local Name */ - ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME = 0x09, /*!< Complete Local Name */ - ESP_BT_EIR_TYPE_TX_POWER_LEVEL = 0x0a, /*!< Tx power level, value is 1 octet ranging from -127 to 127, unit is dBm*/ - ESP_BT_EIR_TYPE_MANU_SPECIFIC = 0xff, /*!< Manufacturer specific data */ -} esp_bt_eir_type_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, Headerset 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; - -/// 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_cb_event_t; - -/** Inquiry Mode */ -typedef enum { - ESP_BT_INQ_MODE_GENERAL_INQUIRY, /*!< General inquiry mode */ - ESP_BT_INQ_MODE_LIMITED_INQIURY, /*!< 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 paramter 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 */ -} 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 - */ -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 - */ -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 - */ -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 - */ -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 - */ -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] mode : one of the enums of bt_scan_mode_t - * - * @return - * - ESP_OK : Succeed - * - ESP_ERR_INVALID_ARG: if argument invalid - * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled - * - ESP_FAIL: others - */ -esp_err_t esp_bt_gap_set_scan_mode(esp_bt_scan_mode_t mode); - -/** - * @brief Start device discovery. This function should be called after esp_bluedroid_enable() completes successfully. - * esp_bt_gap_cb_t will is called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT if discovery is started or halted. - * esp_bt_gap_cb_t will is called with ESP_BT_GAP_DISC_RES_EVT if discovery result is got. - * - * @param[in] mode - inquiry mode - * @param[in] inq_len - inquiry duration in 1.28 sec units, ranging from 0x01 to 0x30 - * @param[in] num_rsps - number of inquiry responses that can be received, value 0 indicates an unlimited number of responses - * - * @return - * - ESP_OK : Succeed - * - ESP_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 device discovery. This function should be called after esp_bluedroid_enable() completes successfully - * esp_bt_gap_cb_t will is called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT if discovery is stopped. - * - * @return - * - ESP_OK : Succeed - * - ESP_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 is called with ESP_BT_GAP_RMT_SRVCS_EVT after service discovery ends - * - * @return - * - ESP_OK : Succeed - * - ESP_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 is called with ESP_BT_GAP_RMT_SRVC_REC_EVT after service discovery ends - * @return - * - ESP_OK : Succeed - * - ESP_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); - -#ifdef __cplusplus -} -#endif - -#endif /* __ESP_GAP_BT_API_H__ */ diff --git a/tools/sdk/include/bluedroid/esp_sec_api.h b/tools/sdk/include/bluedroid/esp_sec_api.h deleted file mode 100644 index f9b0f9ec141..00000000000 --- a/tools/sdk/include/bluedroid/esp_sec_api.h +++ /dev/null @@ -1,79 +0,0 @@ -// 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_SEC_API_H__ -#define __ESP_SEC_API_H__ - -#include "bt_types.h" - -#define APP_SEC_IRK_FLAG (0) -#define RAND_NB_LEN 0x08 -#define SEC_KEY_LEN 0x10 - -/* - * STRUCTURES DEFINITIONS - **************************************************************************************** - */ - - -/// Generic Security key structure -typedef struct { - /// Key value MSB -> LSB - UINT8 key[SEC_KEY_LEN]; -} smp_sec_key; - -///Random number structure -typedef struct { - ///8-byte array for random number - UINT8 nb[RAND_NB_LEN]; -} rand_nb; - -typedef struct { - // LTK - smp_sec_key ltk; - // Random Number - rand_nb rand_nb; - // EDIV - UINT16 ediv; - // LTK key size - UINT8 key_size; - - // Last paired peer address type - UINT8 peer_addr_type; - // Last paired peer address - BD_ADDR peer_addr; - - // authentication level - UINT8 auth; - -} tAPP_SEC_ENV; - -extern tAPP_SEC_ENV app_sec_env; - -/* -* GLOBAL FUNCTIONS DECLARATIONS -**************************************************************************************** -*/ - -void app_ble_sec_init(void); - -void app_ble_sec_pairing_cmp_evt_send(UINT8); - -UINT32 app_ble_sec_gen_tk(void); - -void app_ble_sec_gen_ltk(UINT8 key_size); - -void app_ble_security_start(void); - -#endif /* __ESP_SEC_API_H__ */ diff --git a/tools/sdk/include/bluedroid/event_mask.h b/tools/sdk/include/bluedroid/event_mask.h deleted file mode 100644 index d4d036d5681..00000000000 --- a/tools/sdk/include/bluedroid/event_mask.h +++ /dev/null @@ -1,30 +0,0 @@ -/****************************************************************************** - * - * 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 _EVENT_MASK_H_ -#define _EVENT_MASK_H_ - -#include - -// Represents a mask which can be used to tell the controller which -// HCI events the stack wishes to be informed about. See the bluetooth -// spec for more information on what each bit means. -typedef struct { - uint8_t as_array[8]; -} bt_event_mask_t; - -#endif /*_EVENT_MASK_H_*/ diff --git a/tools/sdk/include/bluedroid/fixed_queue.h b/tools/sdk/include/bluedroid/fixed_queue.h deleted file mode 100644 index becafea1988..00000000000 --- a/tools/sdk/include/bluedroid/fixed_queue.h +++ /dev/null @@ -1,131 +0,0 @@ -/****************************************************************************** - * - * 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 "list.h" - -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 -// if nore more space is available in the queue. Neither |queue| nor |data| -// may be NULL. -void fixed_queue_enqueue(fixed_queue_t *queue, void *data); - -// Dequeues the next element from |queue|. If the queue is currently empty, -// this function will block the caller until an item is enqueued. This -// function will never return NULL. |queue| may not be NULL. -void *fixed_queue_dequeue(fixed_queue_t *queue); - -// Tries to enqueue |data| into the |queue|. This function will never block -// the caller. If the queue capacity would be exceeded by adding one more -// element, this function returns false immediately. Otherwise, this function -// returns true. Neither |queue| nor |data| may be NULL. -bool fixed_queue_try_enqueue(fixed_queue_t *queue, void *data); - -// Tries to dequeue an element from |queue|. This function will never block -// the caller. If the queue is empty, this function returns NULL immediately. -// Otherwise, the next element in the queue is returned. |queue| may not be -// NULL. -void *fixed_queue_try_dequeue(fixed_queue_t *queue); - -// 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/include/bluedroid/future.h b/tools/sdk/include/bluedroid/future.h deleted file mode 100644 index f001f1f1337..00000000000 --- a/tools/sdk/include/bluedroid/future.h +++ /dev/null @@ -1,53 +0,0 @@ -/****************************************************************************** - * - * 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 "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/include/bluedroid/gap_api.h b/tools/sdk/include/bluedroid/gap_api.h deleted file mode 100644 index 1f22db008da..00000000000 --- a/tools/sdk/include/bluedroid/gap_api.h +++ /dev/null @@ -1,391 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2009-2013 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 GAP_API_H -#define GAP_API_H - -#include "sdpdefs.h" -#include "profiles_api.h" -#include "btm_api.h" -#include "l2c_api.h" - -/***************************************************************************** -** Constants -*****************************************************************************/ -/*** GAP Error and Status Codes ***/ -#define GAP_UNSUPPORTED (GAP_ERR_GRP + 0x01) /* Unsupported call */ -#define GAP_EOINQDB (GAP_ERR_GRP + 0x02) /* End of inquiry database marker */ -#define GAP_ERR_BUSY (GAP_ERR_GRP + 0x03) /* The requested function was busy */ -#define GAP_ERR_NO_CTRL_BLK (GAP_ERR_GRP + 0x04) /* No control blocks available */ -#define GAP_ERR_STARTING_CMD (GAP_ERR_GRP + 0x05) /* Error occurred while initiating the command */ -#define GAP_NO_BDADDR_REC (GAP_ERR_GRP + 0x06) /* No Inquiry DB record for BD_ADDR */ -#define GAP_ERR_ILL_MODE (GAP_ERR_GRP + 0x07) /* An illegal mode parameter was detected */ -#define GAP_ERR_ILL_INQ_TIME (GAP_ERR_GRP + 0x08) /* An illegal time parameter was detected */ -#define GAP_ERR_ILL_PARM (GAP_ERR_GRP + 0x09) /* An illegal parameter was detected */ -#define GAP_ERR_REM_NAME (GAP_ERR_GRP + 0x0a) /* Error starting the remote device name request */ -#define GAP_CMD_INITIATED (GAP_ERR_GRP + 0x0b) /* The GAP command was started (result pending) */ -#define GAP_DEVICE_NOT_UP (GAP_ERR_GRP + 0x0c) /* The device was not up; the request was not executed */ -#define GAP_BAD_BD_ADDR (GAP_ERR_GRP + 0x0d) /* The bd addr passed in was not found or invalid */ - -#define GAP_ERR_BAD_HANDLE (GAP_ERR_GRP + 0x0e) /* Bad GAP handle */ -#define GAP_ERR_BUF_OFFSET (GAP_ERR_GRP + 0x0f) /* Buffer offset invalid */ -#define GAP_ERR_BAD_STATE (GAP_ERR_GRP + 0x10) /* Connection is in invalid state */ -#define GAP_NO_DATA_AVAIL (GAP_ERR_GRP + 0x11) /* No data available */ -#define GAP_ERR_CONGESTED (GAP_ERR_GRP + 0x12) /* BT stack is congested */ -#define GAP_ERR_SECURITY (GAP_ERR_GRP + 0x13) /* Security failed */ - -#define GAP_ERR_PROCESSING (GAP_ERR_GRP + 0x14) /* General error processing BTM request */ -#define GAP_ERR_TIMEOUT (GAP_ERR_GRP + 0x15) /* Timeout occurred while processing cmd */ -#define GAP_EVT_CONN_OPENED 0x0100 -#define GAP_EVT_CONN_CLOSED 0x0101 -#define GAP_EVT_CONN_DATA_AVAIL 0x0102 -#define GAP_EVT_CONN_CONGESTED 0x0103 -#define GAP_EVT_CONN_UNCONGESTED 0x0104 -/* Values for 'chan_mode_mask' field */ -/* GAP_ConnOpen() - optional channels to negotiate */ -#define GAP_FCR_CHAN_OPT_BASIC L2CAP_FCR_CHAN_OPT_BASIC -#define GAP_FCR_CHAN_OPT_ERTM L2CAP_FCR_CHAN_OPT_ERTM -#define GAP_FCR_CHAN_OPT_STREAM L2CAP_FCR_CHAN_OPT_STREAM -/*** used in connection variables and functions ***/ -#define GAP_INVALID_HANDLE 0xFFFF - -/* This is used to change the criteria for AMP */ -#define GAP_PROTOCOL_ID (UUID_PROTOCOL_UDP) - - -#ifndef GAP_PREFER_CONN_INT_MAX -#define GAP_PREFER_CONN_INT_MAX BTM_BLE_CONN_INT_MIN -#endif - -#ifndef GAP_PREFER_CONN_INT_MIN -#define GAP_PREFER_CONN_INT_MIN BTM_BLE_CONN_INT_MIN -#endif - -#ifndef GAP_PREFER_CONN_LATENCY -#define GAP_PREFER_CONN_LATENCY 0 -#endif - -#ifndef GAP_PREFER_CONN_SP_TOUT -#define GAP_PREFER_CONN_SP_TOUT 2000 -#endif - -/***************************************************************************** -** Type Definitions -*****************************************************************************/ -/* -** Callback function for connection services -*/ -typedef void (tGAP_CONN_CALLBACK) (UINT16 gap_handle, UINT16 event); - -/* -** Define the callback function prototypes. Parameters are specific -** to each event and are described below -*/ -typedef void (tGAP_CALLBACK) (UINT16 event, void *p_data); - - -/* Definition of the GAP_FindAddrByName results structure */ -typedef struct { - UINT16 status; - BD_ADDR bd_addr; - tBTM_BD_NAME devname; -} tGAP_FINDADDR_RESULTS; - -typedef struct { - UINT16 int_min; - UINT16 int_max; - UINT16 latency; - UINT16 sp_tout; -} tGAP_BLE_PREF_PARAM; - -typedef union { - tGAP_BLE_PREF_PARAM conn_param; - BD_ADDR reconn_bda; - UINT16 icon; - UINT8 *p_dev_name; - UINT8 addr_resolution; - -} tGAP_BLE_ATTR_VALUE; - -typedef void (tGAP_BLE_CMPL_CBACK)(BOOLEAN status, BD_ADDR addr, UINT16 length, char *p_name); - - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ - -/*** Functions for L2CAP connection interface ***/ - -/******************************************************************************* -** -** Function GAP_ConnOpen -** -** Description This function is called to open a generic L2CAP connection. -** -** Returns handle of the connection if successful, else GAP_INVALID_HANDLE -** -*******************************************************************************/ -extern UINT16 GAP_ConnOpen (char *p_serv_name, UINT8 service_id, BOOLEAN is_server, - BD_ADDR p_rem_bda, UINT16 psm, tL2CAP_CFG_INFO *p_cfg, - tL2CAP_ERTM_INFO *ertm_info, - UINT16 security, UINT8 chan_mode_mask, tGAP_CONN_CALLBACK *p_cb); - -/******************************************************************************* -** -** Function GAP_ConnClose -** -** Description This function is called to close a connection. -** -** Returns BT_PASS - closed OK -** GAP_ERR_BAD_HANDLE - invalid handle -** -*******************************************************************************/ -extern UINT16 GAP_ConnClose (UINT16 gap_handle); - -/******************************************************************************* -** -** Function GAP_ConnReadData -** -** Description GKI buffer unaware application will call this function -** after receiving GAP_EVT_RXDATA event. A data copy is made -** into the receive buffer parameter. -** -** Returns BT_PASS - data read -** GAP_ERR_BAD_HANDLE - invalid handle -** GAP_NO_DATA_AVAIL - no data available -** -*******************************************************************************/ -extern UINT16 GAP_ConnReadData (UINT16 gap_handle, UINT8 *p_data, - UINT16 max_len, UINT16 *p_len); - -/******************************************************************************* -** -** Function GAP_GetRxQueueCnt -** -** Description This function return number of bytes on the rx queue. -** -** Parameters: handle - Handle returned in the GAP_ConnOpen -** p_rx_queue_count - Pointer to return queue count in. -** -** -*******************************************************************************/ -extern int GAP_GetRxQueueCnt (UINT16 handle, UINT32 *p_rx_queue_count); - -/******************************************************************************* -** -** Function GAP_ConnBTRead -** -** Description GKI buffer aware applications will call this function after -** receiving an GAP_EVT_RXDATA event to process the incoming -** data buffer. -** -** Returns BT_PASS - data read -** GAP_ERR_BAD_HANDLE - invalid handle -** GAP_NO_DATA_AVAIL - no data available -** -*******************************************************************************/ -extern UINT16 GAP_ConnBTRead (UINT16 gap_handle, BT_HDR **pp_buf); - -/******************************************************************************* -** -** Function GAP_ConnBTWrite -** -** Description GKI buffer aware applications can call this function to write data -** by passing a pointer to the GKI buffer of data. -** -** Returns BT_PASS - data read -** GAP_ERR_BAD_HANDLE - invalid handle -** GAP_ERR_BAD_STATE - connection not established -** GAP_INVALID_BUF_OFFSET - buffer offset is invalid -*******************************************************************************/ -extern UINT16 GAP_ConnBTWrite (UINT16 gap_handle, BT_HDR *p_buf); - -/******************************************************************************* -** -** Function GAP_ConnWriteData -** -** Description GKI buffer unaware application will call this function -** to send data to the connection. A data copy is made into a GKI -** buffer. -** -** Returns BT_PASS - data read -** GAP_ERR_BAD_HANDLE - invalid handle -** GAP_ERR_BAD_STATE - connection not established -** GAP_CONGESTION - system is congested -** -*******************************************************************************/ -extern UINT16 GAP_ConnWriteData (UINT16 gap_handle, UINT8 *p_data, - UINT16 max_len, UINT16 *p_len); - -/******************************************************************************* -** -** Function GAP_ConnReconfig -** -** Description Applications can call this function to reconfigure the connection. -** -** Returns BT_PASS - config process started -** GAP_ERR_BAD_HANDLE - invalid handle -** -*******************************************************************************/ -extern UINT16 GAP_ConnReconfig (UINT16 gap_handle, tL2CAP_CFG_INFO *p_cfg); - -/******************************************************************************* -** -** Function GAP_ConnSetIdleTimeout -** -** Description Higher layers call this function to set the idle timeout for -** a connection, or for all future connections. The "idle timeout" -** is the amount of time that a connection can remain up with -** no L2CAP channels on it. A timeout of zero means that the -** connection will be torn down immediately when the last channel -** is removed. A timeout of 0xFFFF means no timeout. Values are -** in seconds. -** -** Returns BT_PASS - config process started -** GAP_ERR_BAD_HANDLE - invalid handle -** -*******************************************************************************/ -extern UINT16 GAP_ConnSetIdleTimeout (UINT16 gap_handle, UINT16 timeout); - -/******************************************************************************* -** -** Function GAP_ConnGetRemoteAddr -** -** Description This function is called to get the remote BD address -** of a connection. -** -** Returns BT_PASS - closed OK -** GAP_ERR_BAD_HANDLE - invalid handle -** -*******************************************************************************/ -extern UINT8 *GAP_ConnGetRemoteAddr (UINT16 gap_handle); - -/******************************************************************************* -** -** Function GAP_ConnGetRemMtuSize -** -** Description Returns the remote device's MTU size. -** -** Returns UINT16 - maximum size buffer that can be transmitted to the peer -** -*******************************************************************************/ -extern UINT16 GAP_ConnGetRemMtuSize (UINT16 gap_handle); - -/******************************************************************************* -** -** Function GAP_ConnGetL2CAPCid -** -** Description Returns the L2CAP channel id -** -** Parameters: handle - Handle of the connection -** -** Returns UINT16 - The L2CAP channel id -** 0, if error -** -*******************************************************************************/ -extern UINT16 GAP_ConnGetL2CAPCid (UINT16 gap_handle); - -/******************************************************************************* -** -** Function GAP_SetTraceLevel -** -** Description This function sets the trace level for GAP. If called with -** a value of 0xFF, it simply returns the current trace level. -** -** Returns The new or current trace level -** -*******************************************************************************/ -extern UINT8 GAP_SetTraceLevel (UINT8 new_level); - -/******************************************************************************* -** -** Function GAP_Init -** -** Description Initializes the control blocks used by GAP. -** This routine should not be called except once per -** stack invocation. -** -** Returns Nothing -** -*******************************************************************************/ -extern void GAP_Init(void); - -#if (BLE_INCLUDED == TRUE) -/******************************************************************************* -** -** Function GAP_BleAttrDBUpdate -** -** Description update GAP local BLE attribute database. -** -** Returns Nothing -** -*******************************************************************************/ -extern void GAP_BleAttrDBUpdate(UINT16 attr_uuid, tGAP_BLE_ATTR_VALUE *p_value); - - -/******************************************************************************* -** -** Function GAP_BleReadPeerPrefConnParams -** -** Description Start a process to read a connected peripheral's preferred -** connection parameters -** -** Returns TRUE if read started, else FALSE if GAP is busy -** -*******************************************************************************/ -extern BOOLEAN GAP_BleReadPeerPrefConnParams (BD_ADDR peer_bda); - -/******************************************************************************* -** -** Function GAP_BleReadPeerDevName -** -** Description Start a process to read a connected peripheral's device name. -** -** Returns TRUE if request accepted -** -*******************************************************************************/ -extern BOOLEAN GAP_BleReadPeerDevName (BD_ADDR peer_bda, tGAP_BLE_CMPL_CBACK *p_cback); - - -/******************************************************************************* -** -** Function GAP_BleReadPeerAddressResolutionCap -** -** Description Start a process to read peer address resolution capability -** -** Returns TRUE if request accepted -** -*******************************************************************************/ -extern BOOLEAN GAP_BleReadPeerAddressResolutionCap (BD_ADDR peer_bda, - tGAP_BLE_CMPL_CBACK *p_cback); - -/******************************************************************************* -** -** Function GAP_BleCancelReadPeerDevName -** -** Description Cancel reading a peripheral's device name. -** -** Returns TRUE if request accepted -** -*******************************************************************************/ -extern BOOLEAN GAP_BleCancelReadPeerDevName (BD_ADDR peer_bda); - - -#endif - -#endif /* GAP_API_H */ diff --git a/tools/sdk/include/bluedroid/gap_int.h b/tools/sdk/include/bluedroid/gap_int.h deleted file mode 100644 index e9317a04b4b..00000000000 --- a/tools/sdk/include/bluedroid/gap_int.h +++ /dev/null @@ -1,154 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2009-2013 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 GAP_INT_H -#define GAP_INT_H - -#include "bt_target.h" -#include "fixed_queue.h" -#include "gap_api.h" -#include "gatt_api.h" -#define GAP_MAX_BLOCKS 2 /* Concurrent GAP commands pending at a time*/ -/* Define the Generic Access Profile control structure */ -typedef struct { - void *p_data; /* Pointer to any data returned in callback */ - tGAP_CALLBACK *gap_cback; /* Pointer to users callback function */ - tGAP_CALLBACK *gap_inq_rslt_cback; /* Used for inquiry results */ - UINT16 event; /* Passed back in the callback */ - UINT8 index; /* Index of this control block and callback */ - BOOLEAN in_use; /* True when structure is allocated */ -} tGAP_INFO; - -/* Define the control block for the FindAddrByName operation (Only 1 active at a time) */ -typedef struct { - tGAP_CALLBACK *p_cback; - tBTM_INQ_INFO *p_cur_inq; /* Pointer to the current inquiry database entry */ - tGAP_FINDADDR_RESULTS results; - BOOLEAN in_use; -} tGAP_FINDADDR_CB; - -/* Define the GAP Connection Control Block. -*/ -typedef struct { -#define GAP_CCB_STATE_IDLE 0 -#define GAP_CCB_STATE_LISTENING 1 -#define GAP_CCB_STATE_CONN_SETUP 2 -#define GAP_CCB_STATE_CFG_SETUP 3 -#define GAP_CCB_STATE_WAIT_SEC 4 -#define GAP_CCB_STATE_CONNECTED 5 - UINT8 con_state; - -#define GAP_CCB_FLAGS_IS_ORIG 0x01 -#define GAP_CCB_FLAGS_HIS_CFG_DONE 0x02 -#define GAP_CCB_FLAGS_MY_CFG_DONE 0x04 -#define GAP_CCB_FLAGS_SEC_DONE 0x08 -#define GAP_CCB_FLAGS_CONN_DONE 0x0E - UINT8 con_flags; - - UINT8 service_id; /* Used by BTM */ - UINT16 gap_handle; /* GAP handle */ - UINT16 connection_id; /* L2CAP CID */ - BOOLEAN rem_addr_specified; - UINT8 chan_mode_mask; /* Supported channel modes (FCR) */ - BD_ADDR rem_dev_address; - UINT16 psm; - UINT16 rem_mtu_size; - - BOOLEAN is_congested; - fixed_queue_t *tx_queue; /* Queue of buffers waiting to be sent */ - fixed_queue_t *rx_queue; /* Queue of buffers waiting to be read */ - - UINT32 rx_queue_size; /* Total data count in rx_queue */ - - tGAP_CONN_CALLBACK *p_callback; /* Users callback function */ - - tL2CAP_CFG_INFO cfg; /* Configuration */ - tL2CAP_ERTM_INFO ertm_info; /* Pools and modes for ertm */ -} tGAP_CCB; - -typedef struct { -#if ((defined AMP_INCLUDED) && (AMP_INCLUDED == TRUE)) - tAMP_APPL_INFO reg_info; -#else - tL2CAP_APPL_INFO reg_info; /* L2CAP Registration info */ -#endif - tGAP_CCB ccb_pool[GAP_MAX_CONNECTIONS]; -} tGAP_CONN; - - -#if BLE_INCLUDED == TRUE -#define GAP_MAX_CHAR_NUM 4 - -typedef struct { - UINT16 handle; - UINT16 uuid; - tGAP_BLE_ATTR_VALUE attr_value; -} tGAP_ATTR; -#endif -/********************************************************************** -** M A I N C O N T R O L B L O C K -***********************************************************************/ - -#define GAP_MAX_CL GATT_CL_MAX_LCB - -typedef struct { - UINT16 uuid; - tGAP_BLE_CMPL_CBACK *p_cback; -} tGAP_BLE_REQ; - -typedef struct { - BD_ADDR bda; - tGAP_BLE_CMPL_CBACK *p_cback; - UINT16 conn_id; - UINT16 cl_op_uuid; - BOOLEAN in_use; - BOOLEAN connected; - fixed_queue_t *pending_req_q; - -} tGAP_CLCB; - -typedef struct { - tGAP_INFO blk[GAP_MAX_BLOCKS]; - tBTM_CMPL_CB *btm_cback[GAP_MAX_BLOCKS]; - UINT8 trace_level; - //tGAP_FINDADDR_CB findaddr_cb; /* Contains the control block for finding a device addr */ - //tBTM_INQ_INFO *cur_inqptr; - -#if GAP_CONN_INCLUDED == TRUE - tGAP_CONN conn; -#endif - - /* LE GAP attribute database */ -#if BLE_INCLUDED == TRUE && GATTS_INCLUDED == TRUE - tGAP_ATTR gatt_attr[GAP_MAX_CHAR_NUM]; - tGAP_CLCB clcb[GAP_MAX_CL]; /* connection link*/ - tGATT_IF gatt_if; -#endif -} tGAP_CB; - - -extern tGAP_CB gap_cb; -#if (GAP_CONN_INCLUDED == TRUE) -extern void gap_conn_init(void); -#endif -#if (BLE_INCLUDED == TRUE && GATTS_INCLUDED == TRUE) -extern void gap_attr_db_init(void); -#endif - -#endif diff --git a/tools/sdk/include/bluedroid/gatt_api.h b/tools/sdk/include/bluedroid/gatt_api.h deleted file mode 100644 index 7307f53c826..00000000000 --- a/tools/sdk/include/bluedroid/gatt_api.h +++ /dev/null @@ -1,1217 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 GATT_API_H -#define GATT_API_H - -#include "bt_target.h" -#include "gattdefs.h" -#include "btm_ble_api.h" - -/***************************************************************************** -** Constants -*****************************************************************************/ -/* Success code and error codes */ -#define GATT_SUCCESS 0x00 -#define GATT_INVALID_HANDLE 0x01 -#define GATT_READ_NOT_PERMIT 0x02 -#define GATT_WRITE_NOT_PERMIT 0x03 -#define GATT_INVALID_PDU 0x04 -#define GATT_INSUF_AUTHENTICATION 0x05 -#define GATT_REQ_NOT_SUPPORTED 0x06 -#define GATT_INVALID_OFFSET 0x07 -#define GATT_INSUF_AUTHORIZATION 0x08 -#define GATT_PREPARE_Q_FULL 0x09 -#define GATT_NOT_FOUND 0x0a -#define GATT_NOT_LONG 0x0b -#define GATT_INSUF_KEY_SIZE 0x0c -#define GATT_INVALID_ATTR_LEN 0x0d -#define GATT_ERR_UNLIKELY 0x0e -#define GATT_INSUF_ENCRYPTION 0x0f -#define GATT_UNSUPPORT_GRP_TYPE 0x10 -#define GATT_INSUF_RESOURCE 0x11 - - -#define GATT_NO_RESOURCES 0x80 -#define GATT_INTERNAL_ERROR 0x81 -#define GATT_WRONG_STATE 0x82 -#define GATT_DB_FULL 0x83 -#define GATT_BUSY 0x84 -#define GATT_ERROR 0x85 -#define GATT_CMD_STARTED 0x86 -#define GATT_ILLEGAL_PARAMETER 0x87 -#define GATT_PENDING 0x88 -#define GATT_AUTH_FAIL 0x89 -#define GATT_MORE 0x8a -#define GATT_INVALID_CFG 0x8b -#define GATT_SERVICE_STARTED 0x8c -#define GATT_ENCRYPED_MITM GATT_SUCCESS -#define GATT_ENCRYPED_NO_MITM 0x8d -#define GATT_NOT_ENCRYPTED 0x8e -#define GATT_CONGESTED 0x8f - -#define GATT_DUP_REG 0x90 -#define GATT_ALREADY_OPEN 0x91 -#define GATT_CANCEL 0x92 - -/* 0xE0 ~ 0xFC reserved for future use */ -#define GATT_STACK_RSP 0xE0 -#define GATT_APP_RSP 0xE1 -//Error caused by customer application or stack bug -#define GATT_UNKNOWN_ERROR 0XEF - -#define GATT_CCC_CFG_ERR 0xFD /* Client Characteristic Configuration Descriptor Improperly Configured */ -#define GATT_PRC_IN_PROGRESS 0xFE /* Procedure Already in progress */ -#define GATT_OUT_OF_RANGE 0xFF /* Attribute value out of range */ - -typedef UINT8 tGATT_STATUS; - - -#define GATT_RSP_ERROR 0x01 -#define GATT_REQ_MTU 0x02 -#define GATT_RSP_MTU 0x03 -#define GATT_REQ_FIND_INFO 0x04 -#define GATT_RSP_FIND_INFO 0x05 -#define GATT_REQ_FIND_TYPE_VALUE 0x06 -#define GATT_RSP_FIND_TYPE_VALUE 0x07 -#define GATT_REQ_READ_BY_TYPE 0x08 -#define GATT_RSP_READ_BY_TYPE 0x09 -#define GATT_REQ_READ 0x0A -#define GATT_RSP_READ 0x0B -#define GATT_REQ_READ_BLOB 0x0C -#define GATT_RSP_READ_BLOB 0x0D -#define GATT_REQ_READ_MULTI 0x0E -#define GATT_RSP_READ_MULTI 0x0F -#define GATT_REQ_READ_BY_GRP_TYPE 0x10 -#define GATT_RSP_READ_BY_GRP_TYPE 0x11 -#define GATT_REQ_WRITE 0x12 /* 0001-0010 (write)*/ -#define GATT_RSP_WRITE 0x13 -#define GATT_CMD_WRITE 0x52 /* changed in V4.0 01001-0010(write cmd)*/ -#define GATT_REQ_PREPARE_WRITE 0x16 -#define GATT_RSP_PREPARE_WRITE 0x17 -#define GATT_REQ_EXEC_WRITE 0x18 -#define GATT_RSP_EXEC_WRITE 0x19 -#define GATT_HANDLE_VALUE_NOTIF 0x1B -#define GATT_HANDLE_VALUE_IND 0x1D -#define GATT_HANDLE_VALUE_CONF 0x1E -#define GATT_SIGN_CMD_WRITE 0xD2 /* changed in V4.0 1101-0010 (signed write) see write cmd above*/ -#define GATT_OP_CODE_MAX GATT_HANDLE_VALUE_CONF + 1 /* 0x1E = 30 + 1 = 31*/ - - -#define GATT_HANDLE_IS_VALID(x) ((x) != 0) - -#define GATT_CONN_UNKNOWN 0 -#define GATT_CONN_L2C_FAILURE 1 /* general L2cap failure */ -#define GATT_CONN_TIMEOUT HCI_ERR_CONNECTION_TOUT /* 0x08 connection timeout */ -#define GATT_CONN_TERMINATE_PEER_USER HCI_ERR_PEER_USER /* 0x13 connection terminate by peer user */ -#define GATT_CONN_TERMINATE_LOCAL_HOST HCI_ERR_CONN_CAUSE_LOCAL_HOST /* 0x16 connectionterminated by local host */ -#define GATT_CONN_FAIL_ESTABLISH HCI_ERR_CONN_FAILED_ESTABLISHMENT/* 0x03E connection fail to establish */ -#define GATT_CONN_LMP_TIMEOUT HCI_ERR_LMP_RESPONSE_TIMEOUT /* 0x22 connection fail for LMP response tout */ -#define GATT_CONN_CANCEL L2CAP_CONN_CANCEL /* 0x0100 L2CAP connection cancelled */ -typedef UINT16 tGATT_DISCONN_REASON; - -/* MAX GATT MTU size -*/ -#ifndef GATT_MAX_MTU_SIZE -#define GATT_MAX_MTU_SIZE 517 -#endif - -/* max legth of an attribute value -*/ -#ifndef GATT_MAX_ATTR_LEN -#define GATT_MAX_ATTR_LEN 600 -#endif - -/* default GATT MTU size over LE link -*/ -#define GATT_DEF_BLE_MTU_SIZE 23 - -/* invalid connection ID -*/ -#define GATT_INVALID_CONN_ID 0xFFFF - -#ifndef GATT_CL_MAX_LCB -#define GATT_CL_MAX_LCB 12 // 22 -#endif - -#ifndef GATT_MAX_SCCB -#define GATT_MAX_SCCB 10 -#endif - - -/* GATT notification caching timer, default to be three seconds -*/ -#ifndef GATTC_NOTIF_TIMEOUT -#define GATTC_NOTIF_TIMEOUT 3 -#endif - -/***************************************************************************** -** GATT Structure Definition -*****************************************************************************/ - -/* Attribute permissions -*/ -#define GATT_PERM_READ (1 << 0) /* bit 0 */ -#define GATT_PERM_READ_ENCRYPTED (1 << 1) /* bit 1 */ -#define GATT_PERM_READ_ENC_MITM (1 << 2) /* bit 2 */ -#define GATT_PERM_WRITE (1 << 4) /* bit 4 */ -#define GATT_PERM_WRITE_ENCRYPTED (1 << 5) /* bit 5 */ -#define GATT_PERM_WRITE_ENC_MITM (1 << 6) /* bit 6 */ -#define GATT_PERM_WRITE_SIGNED (1 << 7) /* bit 7 */ -#define GATT_PERM_WRITE_SIGNED_MITM (1 << 8) /* bit 8 */ -typedef UINT16 tGATT_PERM; - -#define GATT_ENCRYPT_KEY_SIZE_MASK (0xF000) /* the MS nibble of tGATT_PERM; key size 7=0; size 16=9 */ - -#define GATT_READ_ALLOWED (GATT_PERM_READ | GATT_PERM_READ_ENCRYPTED | GATT_PERM_READ_ENC_MITM) -#define GATT_READ_AUTH_REQUIRED (GATT_PERM_READ_ENCRYPTED) -#define GATT_READ_MITM_REQUIRED (GATT_PERM_READ_ENC_MITM) -#define GATT_READ_ENCRYPTED_REQUIRED (GATT_PERM_READ_ENCRYPTED | GATT_PERM_READ_ENC_MITM) - - -#define GATT_WRITE_ALLOWED (GATT_PERM_WRITE | GATT_PERM_WRITE_ENCRYPTED | GATT_PERM_WRITE_ENC_MITM | \ - GATT_PERM_WRITE_SIGNED | GATT_PERM_WRITE_SIGNED_MITM) - -#define GATT_WRITE_AUTH_REQUIRED (GATT_PERM_WRITE_ENCRYPTED | GATT_PERM_WRITE_SIGNED) - -#define GATT_WRITE_MITM_REQUIRED (GATT_PERM_WRITE_ENC_MITM | GATT_PERM_WRITE_SIGNED_MITM) - -#define GATT_WRITE_ENCRYPTED_PERM (GATT_PERM_WRITE_ENCRYPTED | GATT_PERM_WRITE_ENC_MITM) - -#define GATT_WRITE_SIGNED_PERM (GATT_PERM_WRITE_SIGNED | GATT_PERM_WRITE_SIGNED_MITM) - - -/* Characteristic properties -*/ -#define GATT_CHAR_PROP_BIT_BROADCAST (1 << 0) -#define GATT_CHAR_PROP_BIT_READ (1 << 1) -#define GATT_CHAR_PROP_BIT_WRITE_NR (1 << 2) -#define GATT_CHAR_PROP_BIT_WRITE (1 << 3) -#define GATT_CHAR_PROP_BIT_NOTIFY (1 << 4) -#define GATT_CHAR_PROP_BIT_INDICATE (1 << 5) -#define GATT_CHAR_PROP_BIT_AUTH (1 << 6) -#define GATT_CHAR_PROP_BIT_EXT_PROP (1 << 7) -typedef UINT8 tGATT_CHAR_PROP; - - -/* Format of the value of a characteristic. enumeration type -*/ -enum { - GATT_FORMAT_RES, /* rfu */ - GATT_FORMAT_BOOL, /* 0x01 boolean */ - GATT_FORMAT_2BITS, /* 0x02 2 bit */ - GATT_FORMAT_NIBBLE, /* 0x03 nibble */ - GATT_FORMAT_UINT8, /* 0x04 uint8 */ - GATT_FORMAT_UINT12, /* 0x05 uint12 */ - GATT_FORMAT_UINT16, /* 0x06 uint16 */ - GATT_FORMAT_UINT24, /* 0x07 uint24 */ - GATT_FORMAT_UINT32, /* 0x08 uint32 */ - GATT_FORMAT_UINT48, /* 0x09 uint48 */ - GATT_FORMAT_UINT64, /* 0x0a uint64 */ - GATT_FORMAT_UINT128, /* 0x0B uint128 */ - GATT_FORMAT_SINT8, /* 0x0C signed 8 bit integer */ - GATT_FORMAT_SINT12, /* 0x0D signed 12 bit integer */ - GATT_FORMAT_SINT16, /* 0x0E signed 16 bit integer */ - GATT_FORMAT_SINT24, /* 0x0F signed 24 bit integer */ - GATT_FORMAT_SINT32, /* 0x10 signed 32 bit integer */ - GATT_FORMAT_SINT48, /* 0x11 signed 48 bit integer */ - GATT_FORMAT_SINT64, /* 0x12 signed 64 bit integer */ - GATT_FORMAT_SINT128, /* 0x13 signed 128 bit integer */ - GATT_FORMAT_FLOAT32, /* 0x14 float 32 */ - GATT_FORMAT_FLOAT64, /* 0x15 float 64*/ - GATT_FORMAT_SFLOAT, /* 0x16 IEEE-11073 16 bit SFLOAT */ - GATT_FORMAT_FLOAT, /* 0x17 IEEE-11073 32 bit SFLOAT */ - GATT_FORMAT_DUINT16, /* 0x18 IEEE-20601 format */ - GATT_FORMAT_UTF8S, /* 0x19 UTF-8 string */ - GATT_FORMAT_UTF16S, /* 0x1a UTF-16 string */ - GATT_FORMAT_STRUCT, /* 0x1b Opaque structure*/ - GATT_FORMAT_MAX /* 0x1c or above reserved */ -}; -typedef UINT8 tGATT_FORMAT; - -/* Characteristic Presentation Format Descriptor value -*/ -typedef struct { - UINT16 unit; /* as UUIUD defined by SIG */ - UINT16 descr; /* as UUID as defined by SIG */ - tGATT_FORMAT format; - INT8 exp; - UINT8 name_spc; /* The name space of the description */ -} tGATT_CHAR_PRES; - -/* Characteristic Report reference Descriptor format -*/ -typedef struct { - UINT8 rpt_id; /* report ID */ - UINT8 rpt_type; /* report type */ -} tGATT_CHAR_RPT_REF; - - -#define GATT_VALID_RANGE_MAX_SIZE 16 -typedef struct { - UINT8 format; - UINT16 len; - UINT8 lower_range[GATT_VALID_RANGE_MAX_SIZE]; /* in little endian format */ - UINT8 upper_range[GATT_VALID_RANGE_MAX_SIZE]; -} tGATT_VALID_RANGE; - -/* Characteristic Aggregate Format attribute value -*/ -#define GATT_AGGR_HANDLE_NUM_MAX 10 -typedef struct { - UINT8 num_handle; - UINT16 handle_list[GATT_AGGR_HANDLE_NUM_MAX]; -} tGATT_CHAR_AGGRE; - -/* Characteristic descriptor: Extended Properties value -*/ -#define GATT_CHAR_BIT_REL_WRITE 0x0001 /* permits reliable writes of the Characteristic Value */ -#define GATT_CHAR_BIT_WRITE_AUX 0x0002 /* permits writes to the characteristic descriptor */ - - -/* characteristic descriptor: client configuration value -*/ -#define GATT_CLT_CONFIG_NONE 0x0000 -#define GATT_CLT_CONFIG_NOTIFICATION 0x0001 -#define GATT_CLT_CONFIG_INDICATION 0x0002 -typedef UINT16 tGATT_CLT_CHAR_CONFIG; - - -/* characteristic descriptor: server configuration value -*/ -#define GATT_SVR_CONFIG_NONE 0x0000 -#define GATT_SVR_CONFIG_BROADCAST 0x0001 -typedef UINT16 tGATT_SVR_CHAR_CONFIG; - -/* Characteristic descriptor: Extended Properties value -*/ -#define GATT_CHAR_BIT_REL_WRITE 0x0001 /* permits reliable writes of the Characteristic Value */ -#define GATT_CHAR_BIT_WRITE_AUX 0x0002 /* permits writes to the characteristic descriptor */ - -/* authentication requirement -*/ -#define GATT_AUTH_REQ_NONE 0 -#define GATT_AUTH_REQ_NO_MITM 1 /* unauthenticated encryption */ -#define GATT_AUTH_REQ_MITM 2 /* authenticated encryption */ -#define GATT_AUTH_REQ_SIGNED_NO_MITM 3 -#define GATT_AUTH_REQ_SIGNED_MITM 4 -typedef UINT8 tGATT_AUTH_REQ; - -/* Attribute Value structure -*/ -typedef struct { - UINT16 conn_id; - UINT16 handle; /* attribute handle */ - UINT16 offset; /* attribute value offset, if no offfset is needed for the command, ignore it */ - UINT16 len; /* length of attribute value */ - tGATT_AUTH_REQ auth_req; /* authentication request */ - UINT8 value[GATT_MAX_ATTR_LEN]; /* the actual attribute value */ -} tGATT_VALUE; - -typedef struct{ - UINT16 attr_max_len; - UINT16 attr_len; - UINT8 *attr_val; -}tGATT_ATTR_VAL; - -typedef struct{ - uint8_t auto_rsp; -}tGATTS_ATTR_CONTROL; - -/* Mask for gatt server attribute */ -#define GATT_ATTR_VALUE_ALLOCATED 0x01 -typedef UINT8 tGATT_ATTR_MASK; - -/* Union of the event data which is used in the server respond API to carry the server response information -*/ -typedef union { - /* data type member event */ - tGATT_VALUE attr_value; /* READ, HANDLE_VALUE_IND, PREPARE_WRITE */ - /* READ_BLOB, READ_BY_TYPE */ - UINT16 handle; /* WRITE, WRITE_BLOB */ - -} tGATTS_RSP; - -/* Transports for the primary service */ -#define GATT_TRANSPORT_LE BT_TRANSPORT_LE -#define GATT_TRANSPORT_BR_EDR BT_TRANSPORT_BR_EDR -#define GATT_TRANSPORT_LE_BR_EDR (BT_TRANSPORT_LE|BT_TRANSPORT_BR_EDR) -typedef UINT8 tGATT_TRANSPORT; - -#define GATT_PREP_WRITE_CANCEL 0x00 -#define GATT_PREP_WRITE_EXEC 0x01 -typedef UINT8 tGATT_EXEC_FLAG; - -/* read request always based on UUID */ -typedef struct { - UINT16 handle; - UINT16 offset; - BOOLEAN is_long; - BOOLEAN need_rsp; -} tGATT_READ_REQ; - -/* write request data */ -typedef struct { - UINT16 handle; /* attribute handle */ - UINT16 offset; /* attribute value offset, if no offfset is needed for the command, ignore it */ - UINT16 len; /* length of attribute value */ - UINT8 value[GATT_MAX_ATTR_LEN]; /* the actual attribute value */ - BOOLEAN need_rsp; /* need write response */ - BOOLEAN is_prep; /* is prepare write */ -} tGATT_WRITE_REQ; - -/* callback data for server access request from client */ -typedef union { - tGATT_READ_REQ read_req; /* read request, read by Type, read blob */ - - tGATT_WRITE_REQ write_req; /* write */ - /* prepare write */ - /* write blob */ - UINT16 handle; /* handle value confirmation */ - UINT16 mtu; /* MTU exchange request */ - tGATT_EXEC_FLAG exec_write; /* execute write */ -} tGATTS_DATA; - -typedef UINT8 tGATT_SERV_IF; /* GATT Service Interface */ - -enum { - GATTS_REQ_TYPE_READ = 1, /* Attribute read request */ - GATTS_REQ_TYPE_WRITE, /* Attribute write request */ - GATTS_REQ_TYPE_WRITE_EXEC, /* Execute write */ - GATTS_REQ_TYPE_MTU, /* MTU exchange information */ - GATTS_REQ_TYPE_CONF /* handle value confirmation */ -}; -typedef UINT8 tGATTS_REQ_TYPE; - - - -/* Client Used Data Structure -*/ -/* definition of different discovery types */ -enum { - GATT_DISC_SRVC_ALL = 1, /* discover all services */ - GATT_DISC_SRVC_BY_UUID, /* discover service of a special type */ - GATT_DISC_INC_SRVC, /* discover the included service within a service */ - GATT_DISC_CHAR, /* discover characteristics of a service with/without type requirement */ - GATT_DISC_CHAR_DSCPT, /* discover characteristic descriptors of a character */ - GATT_DISC_MAX /* maximnun discover type */ -}; -typedef UINT8 tGATT_DISC_TYPE; - -/* Discover parameters of different discovery types -*/ -typedef struct { - tBT_UUID service; - UINT16 s_handle; - UINT16 e_handle; -} tGATT_DISC_PARAM; - -/* GATT read type enumeration -*/ -enum { - GATT_READ_BY_TYPE = 1, - GATT_READ_BY_HANDLE, - GATT_READ_MULTIPLE, - GATT_READ_CHAR_VALUE, - GATT_READ_PARTIAL, - GATT_READ_MAX -}; -typedef UINT8 tGATT_READ_TYPE; - -/* Read By Type Request (GATT_READ_BY_TYPE) Data -*/ -typedef struct { - tGATT_AUTH_REQ auth_req; - UINT16 s_handle; - UINT16 e_handle; - tBT_UUID uuid; -} tGATT_READ_BY_TYPE; - -/* GATT_READ_MULTIPLE request data -*/ -#define GATT_MAX_READ_MULTI_HANDLES 10 /* Max attributes to read in one request */ -typedef struct { - tGATT_AUTH_REQ auth_req; - UINT16 num_handles; /* number of handles to read */ - UINT16 handles[GATT_MAX_READ_MULTI_HANDLES]; /* handles list to be read */ -} tGATT_READ_MULTI; - -/* Read By Handle Request (GATT_READ_BY_HANDLE) data */ -typedef struct { - tGATT_AUTH_REQ auth_req; - UINT16 handle; -} tGATT_READ_BY_HANDLE; - -/* READ_BT_HANDLE_Request data */ -typedef struct { - tGATT_AUTH_REQ auth_req; - UINT16 handle; - UINT16 offset; -} tGATT_READ_PARTIAL; - -/* Read Request Data -*/ -typedef union { - tGATT_READ_BY_TYPE service; - tGATT_READ_BY_TYPE char_type; /* characterisitc type */ - tGATT_READ_MULTI read_multiple; - tGATT_READ_BY_HANDLE by_handle; - tGATT_READ_PARTIAL partial; -} tGATT_READ_PARAM; - -/* GATT write type enumeration */ -enum { - GATT_WRITE_NO_RSP = 1, - GATT_WRITE , - GATT_WRITE_PREPARE -}; -typedef UINT8 tGATT_WRITE_TYPE; - -/* Client Operation Complete Callback Data -*/ -typedef union { - tGATT_VALUE att_value; - UINT16 mtu; - UINT16 handle; -} tGATT_CL_COMPLETE; - -/* GATT client operation type, used in client callback function -*/ -#define GATTC_OPTYPE_NONE 0 -#define GATTC_OPTYPE_DISCOVERY 1 -#define GATTC_OPTYPE_READ 2 -#define GATTC_OPTYPE_WRITE 3 -#define GATTC_OPTYPE_EXE_WRITE 4 -#define GATTC_OPTYPE_CONFIG 5 -#define GATTC_OPTYPE_NOTIFICATION 6 -#define GATTC_OPTYPE_INDICATION 7 -typedef UINT8 tGATTC_OPTYPE; - -/* characteristic declaration -*/ -typedef struct { - tGATT_CHAR_PROP char_prop; /* characterisitc properties */ - UINT16 val_handle; /* characteristic value attribute handle */ - tBT_UUID char_uuid; /* characteristic UUID type */ -} tGATT_CHAR_DCLR_VAL; - -/* primary service group data -*/ -typedef struct { - UINT16 e_handle; /* ending handle of the group */ - tBT_UUID service_type; /* group type */ -} tGATT_GROUP_VALUE; - - -/* included service attribute value -*/ -typedef struct { - tBT_UUID service_type; /* included service UUID */ - UINT16 s_handle; /* starting handle */ - UINT16 e_handle; /* ending handle */ -} tGATT_INCL_SRVC; - -typedef union { - tGATT_INCL_SRVC incl_service; /* include service value */ - tGATT_GROUP_VALUE group_value; /* Service UUID type. - This field is used with GATT_DISC_SRVC_ALL - or GATT_DISC_SRVC_BY_UUID - type of discovery result callback. */ - - UINT16 handle; /* When used with GATT_DISC_INC_SRVC type discovery result, - it is the included service starting handle.*/ - - tGATT_CHAR_DCLR_VAL dclr_value; /* Characteristic declaration value. - This field is used with GATT_DISC_CHAR type discovery.*/ -} tGATT_DISC_VALUE; - -/* discover result record -*/ -typedef struct { - tBT_UUID type; - UINT16 handle; - tGATT_DISC_VALUE value; -} tGATT_DISC_RES; - - -#define GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP 0 /* start a idle timer for this duration - when no application need to use the link */ - -#define GATT_LINK_NO_IDLE_TIMEOUT 0xFFFF - -#define GATT_INVALID_ACL_HANDLE 0xFFFF -/* discover result callback function */ -typedef void (tGATT_DISC_RES_CB) (UINT16 conn_id, tGATT_DISC_TYPE disc_type, - tGATT_DISC_RES *p_data); - -/* discover complete callback function */ -typedef void (tGATT_DISC_CMPL_CB) (UINT16 conn_id, tGATT_DISC_TYPE disc_type, tGATT_STATUS status); - -/* Define a callback function for when read/write/disc/config operation is completed. */ -typedef void (tGATT_CMPL_CBACK) (UINT16 conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, - tGATT_CL_COMPLETE *p_data); - -/* Define a callback function when an initialized connection is established. */ -typedef void (tGATT_CONN_CBACK) (tGATT_IF gatt_if, BD_ADDR bda, UINT16 conn_id, BOOLEAN connected, - tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport); - -/* attribute request callback for ATT server */ -typedef void (tGATT_REQ_CBACK )(UINT16 conn_id, UINT32 trans_id, tGATTS_REQ_TYPE type, - tGATTS_DATA *p_data); - -/* channel congestion/uncongestion callback */ -typedef void (tGATT_CONGESTION_CBACK )(UINT16 conn_id, BOOLEAN congested); - -/* Define a callback function when encryption is established. */ -typedef void (tGATT_ENC_CMPL_CB)(tGATT_IF gatt_if, BD_ADDR bda); - - -/* Define the structure that applications use to register with -** GATT. This structure includes callback functions. All functions -** MUST be provided. -*/ -typedef struct { - tGATT_CONN_CBACK *p_conn_cb; - tGATT_CMPL_CBACK *p_cmpl_cb; - tGATT_DISC_RES_CB *p_disc_res_cb; - tGATT_DISC_CMPL_CB *p_disc_cmpl_cb; - tGATT_REQ_CBACK *p_req_cb; - tGATT_ENC_CMPL_CB *p_enc_cmpl_cb; - tGATT_CONGESTION_CBACK *p_congestion_cb; -} tGATT_CBACK; - -/*********************** Start Handle Management Definitions ********************** -*/ - - -typedef struct { - tBT_UUID app_uuid128; - tBT_UUID svc_uuid; - UINT16 svc_inst; - UINT16 s_handle; - UINT16 e_handle; - BOOLEAN is_primary; /* primary service or secondary */ -} tGATTS_HNDL_RANGE; - - - -#define GATTS_SRV_CHG_CMD_ADD_CLIENT 1 -#define GATTS_SRV_CHG_CMD_UPDATE_CLIENT 2 -#define GATTS_SRV_CHG_CMD_REMOVE_CLIENT 3 -#define GATTS_SRV_CHG_CMD_READ_NUM_CLENTS 4 -#define GATTS_SRV_CHG_CMD_READ_CLENT 5 -typedef UINT8 tGATTS_SRV_CHG_CMD; - -typedef struct { - BD_ADDR bda; - BOOLEAN srv_changed; -} tGATTS_SRV_CHG; - - -typedef union { - tGATTS_SRV_CHG srv_chg; - UINT8 client_read_index; /* only used for sequential reading client srv chg info */ -} tGATTS_SRV_CHG_REQ; - -typedef union { - tGATTS_SRV_CHG srv_chg; - UINT8 num_clients; -} tGATTS_SRV_CHG_RSP; - - - -typedef struct { - tGATTS_HNDL_RANGE *p_new_srv_start; -} tGATTS_PENDING_NEW_SRV_START; - -/* Attibute server handle ranges NV storage callback functions -*/ -typedef void (tGATTS_NV_SAVE_CBACK)(BOOLEAN is_saved, tGATTS_HNDL_RANGE *p_hndl_range); -typedef BOOLEAN (tGATTS_NV_SRV_CHG_CBACK)(tGATTS_SRV_CHG_CMD cmd, tGATTS_SRV_CHG_REQ *p_req, - tGATTS_SRV_CHG_RSP *p_rsp); - -typedef struct { - tGATTS_NV_SAVE_CBACK *p_nv_save_callback; - tGATTS_NV_SRV_CHG_CBACK *p_srv_chg_callback; -} tGATT_APPL_INFO; - -/* -*********************** End Handle Management Definitions **********************/ - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function GATT_SetTraceLevel -** -** Description This function sets the trace level. If called with -** a value of 0xFF, it simply returns the current trace level. -** -** Returns The new or current trace level -** -*******************************************************************************/ -extern UINT8 GATT_SetTraceLevel (UINT8 new_level); - - -/*******************************************************************************/ -/* GATT Profile API Functions */ -/*******************************************************************************/ -/* GATT Profile Server Functions */ -/*******************************************************************************/ -/******************************************************************************* -** -** Function GATTS_AddHandleRange -** -** Description This function add the allocated handles range for the specifed -** application UUID, service UUID and service instance -** -** Parameter p_hndl_range: pointer to allocated handles information -** -** Returns TRUE if handle range is added sucessfully; otherwise FALSE. -** -*******************************************************************************/ - -extern BOOLEAN GATTS_AddHandleRange(tGATTS_HNDL_RANGE *p_hndl_range); - -/******************************************************************************* -** -** Function GATTS_NVRegister -** -** Description Application manager calls this function to register for -** NV save callback function. There can be one and only one -** NV save callback function. -** -** Parameter p_cb_info : callback informaiton -** -** Returns TRUE if registered OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN GATTS_NVRegister (tGATT_APPL_INFO *p_cb_info); - - -/******************************************************************************* -** -** Function GATTS_CreateService -** -** Description This function is called to reserve a block of handles for a service. -** -** *** It should be called only once per service instance *** -** -** Parameter gatt_if : application if -** p_svc_uuid : service UUID -** svc_inst : instance of the service inside the application -** num_handles : number of handles needed by the service. -** is_pri : is a primary service or not. -** -** Returns service handle if sucessful, otherwise 0. -** -*******************************************************************************/ -extern UINT16 GATTS_CreateService (tGATT_IF gatt_if, tBT_UUID *p_svc_uuid, - UINT16 svc_inst, UINT16 num_handles, BOOLEAN is_pri); - - -/******************************************************************************* -** -** Function GATTS_AddIncludeService -** -** Description This function is called to add an included service. -** -** Parameter service_handle : To which service this included service is added to. -** include_svc_handle : included service handle. -** -** Returns included service attribute handle. If 0, add included service -** fail. -** -*******************************************************************************/ -extern UINT16 GATTS_AddIncludeService (UINT16 service_handle, - UINT16 include_svc_handle); - - -/******************************************************************************* -** -** Function GATTS_AddCharacteristic -** -** Description This function is called to add a characteristic into a service. -** It will add a characteristic declaration and characteristic -** value declaration into the service database identified by the -** service handle. -** -** Parameter service_handle : To which service this included service is added to. -** char_uuid : Characteristic UUID. -** perm : Characteristic value declaration attribute permission. -** property : Characteristic Properties -** -** Returns Characteristic value declaration attribute handle. 0 if add -** characteristic failed. -** -*******************************************************************************/ -extern UINT16 GATTS_AddCharacteristic (UINT16 service_handle, tBT_UUID *p_char_uuid, - tGATT_PERM perm, tGATT_CHAR_PROP property, - tGATT_ATTR_VAL *attr_val, tGATTS_ATTR_CONTROL *control); - -/******************************************************************************* -** -** Function GATTS_AddCharDescriptor -** -** Description This function is called to add a characteristic descriptor -** into a service database. Add descriptor should follow add char -** to which it belongs, and next add char should be done only -** after all add descriptors for the previous char. -** -** Parameter service_handle : To which service this characteristic descriptor -** is added to. -** perm : Characteristic value declaration attribute -** permission. -** p_descr_uuid : Characteristic descriptor UUID. -** -** Returns Characteristic descriptor attribute handle. 0 if add -** characteristic descriptor failed. -** -*******************************************************************************/ -extern UINT16 GATTS_AddCharDescriptor (UINT16 service_handle, tGATT_PERM perm, - tBT_UUID *p_descr_uuid, tGATT_ATTR_VAL *attr_val, - tGATTS_ATTR_CONTROL *control); - -/******************************************************************************* -** -** Function GATTS_DeleteService -** -** Description This function is called to delete a service. -** -** Parameter gatt_if : application interface -** p_svc_uuid : service UUID -** svc_inst : instance of the service inside the application -** -** Returns TRUE if operation succeed, FALSE if handle block was not found. -** -*******************************************************************************/ -extern BOOLEAN GATTS_DeleteService (tGATT_IF gatt_if, tBT_UUID *p_svc_uuid, - UINT16 svc_inst); - -/******************************************************************************* -** -** Function GATTS_StartService -** -** Description This function is called to start a service with GATT -** -** Parameter gatt_if : service handle. -** p_cback : application service callback functions. -** sup_transport : supported transport(s) for this primary service -** -** return GATT_SUCCESS if sucessfully started; otherwise error code. -** -*******************************************************************************/ -extern tGATT_STATUS GATTS_StartService (tGATT_IF gatt_if, UINT16 service_handle, - tGATT_TRANSPORT sup_transport); - - -/******************************************************************************* -** -** Function GATTS_StopService -** -** Description This function is called to stop a service -** -** Parameter service_handle : this is the start handle of a service -** -** Returns None. -** -*******************************************************************************/ -extern void GATTS_StopService (UINT16 service_handle); - - -/******************************************************************************* -** -** Function GATTs_HandleValueIndication -** -** Description This function sends a handle value indication to a client. -** -** Parameter conn_id: connection identifier. -** attr_handle: Attribute handle of this handle value indication. -** val_len: Length of the indicated attribute value. -** p_val: Pointer to the indicated attribute value data. -** -** Returns GATT_SUCCESS if sucessfully sent or queued; otherwise error code. -** -*******************************************************************************/ -extern tGATT_STATUS GATTS_HandleValueIndication (UINT16 conn_id, - UINT16 attr_handle, - UINT16 val_len, UINT8 *p_val); - -/******************************************************************************* -** -** Function GATTS_HandleValueNotification -** -** Description This function sends a handle value notification to a client. -** -** Parameter conn_id: connection identifier. -** attr_handle: Attribute handle of this handle value indication. -** val_len: Length of the indicated attribute value. -** p_val: Pointer to the indicated attribute value data. -** -** Returns GATT_SUCCESS if sucessfully sent; otherwise error code. -** -*******************************************************************************/ -extern tGATT_STATUS GATTS_HandleValueNotification (UINT16 conn_id, UINT16 attr_handle, - UINT16 val_len, UINT8 *p_val); - - -/******************************************************************************* -** -** Function GATTS_SendRsp -** -** Description This function sends the server response to client. -** -** Parameter conn_id: connection identifier. -** trans_id: transaction id -** status: response status -** p_msg: pointer to message parameters structure. -** -** Returns GATT_SUCCESS if sucessfully sent; otherwise error code. -** -*******************************************************************************/ -extern tGATT_STATUS GATTS_SendRsp (UINT16 conn_id, UINT32 trans_id, - tGATT_STATUS status, tGATTS_RSP *p_msg); - - -/******************************************************************************* -** -** Function GATTS_SetAttributeValue -** -** Description This function sends to set the attribute value . -** -** Parameter attr_handle:the attribute handle -** length: the attribute length -** value: the value to be set to the attribute in the database -** -** Returns GATT_SUCCESS if sucessfully sent; otherwise error code. -** -*******************************************************************************/ -tGATT_STATUS GATTS_SetAttributeValue(UINT16 attr_handle, UINT16 length, UINT8 *value); - - -/******************************************************************************* -** -** Function GATTS_GetAttributeValue -** -** Description This function sends to set the attribute value . -** -** Parameter attr_handle: the attribute handle -** length:the attribute value length in the database -** value: the attribute value out put -** -** Returns GATT_SUCCESS if sucessfully sent; otherwise error code. -** -*******************************************************************************/ -tGATT_STATUS GATTS_GetAttributeValue(UINT16 attr_handle, UINT16 *length, UINT8 **value); - - - -/*******************************************************************************/ -/* GATT Profile Client Functions */ -/*******************************************************************************/ - -/******************************************************************************* -** -** Function GATTC_ConfigureMTU -** -** Description This function is called to configure the ATT MTU size for -** a connection on an LE transport. -** -** Parameters conn_id: connection identifier. -** mtu - attribute MTU size.. -** -** Returns GATT_SUCCESS if command started successfully. -** -*******************************************************************************/ -extern tGATT_STATUS GATTC_ConfigureMTU (UINT16 conn_id); - -/******************************************************************************* -** -** Function GATTC_Discover -** -** Description This function is called to do a discovery procedure on ATT server. -** -** Parameters conn_id: connection identifier. -** disc_type:discovery type. -** p_param: parameters of discovery requirement. -** -** Returns GATT_SUCCESS if command received/sent successfully. -** -*******************************************************************************/ -extern tGATT_STATUS GATTC_Discover (UINT16 conn_id, - tGATT_DISC_TYPE disc_type, - tGATT_DISC_PARAM *p_param ); -/******************************************************************************* -** -** Function GATTC_Read -** -** Description This function is called to read the value of an attribute from -** the server. -** -** Parameters conn_id: connection identifier. -** type - attribute read type. -** p_read - read operation parameters. -** -** Returns GATT_SUCCESS if command started successfully. -** -*******************************************************************************/ -extern tGATT_STATUS GATTC_Read (UINT16 conn_id, tGATT_READ_TYPE type, - tGATT_READ_PARAM *p_read); - -/******************************************************************************* -** -** Function GATTC_Write -** -** Description This function is called to read the value of an attribute from -** the server. -** -** Parameters conn_id: connection identifier. -** type - attribute write type. -** p_write - write operation parameters. -** -** Returns GATT_SUCCESS if command started successfully. -** -*******************************************************************************/ -extern tGATT_STATUS GATTC_Write (UINT16 conn_id, tGATT_WRITE_TYPE type, - tGATT_VALUE *p_write); - - -/******************************************************************************* -** -** Function GATTC_ExecuteWrite -** -** Description This function is called to send an Execute write request to -** the server. -** -** Parameters conn_id: connection identifier. -** is_execute - to execute or cancel the prepare write requet(s) -** -** Returns GATT_SUCCESS if command started successfully. -** -*******************************************************************************/ -extern tGATT_STATUS GATTC_ExecuteWrite (UINT16 conn_id, BOOLEAN is_execute); - -/******************************************************************************* -** -** Function GATTC_SendHandleValueConfirm -** -** Description This function is called to send a handle value confirmation -** as response to a handle value notification from server. -** -** Parameters conn_id: connection identifier. -** handle: the handle of the attribute confirmation. -** -** Returns GATT_SUCCESS if command started successfully. -** -*******************************************************************************/ -extern tGATT_STATUS GATTC_SendHandleValueConfirm (UINT16 conn_id, UINT16 handle); - - -/******************************************************************************* -** -** Function GATT_SetIdleTimeout -** -** Description This function (common to both client and server) sets the idle -** timeout for a tansport connection -** -** Parameter bd_addr: target device bd address. -** idle_tout: timeout value in seconds. -** transport: trasnport option. -** -** Returns void -** -*******************************************************************************/ -extern void GATT_SetIdleTimeout (BD_ADDR bd_addr, UINT16 idle_tout, - tGATT_TRANSPORT transport); - - -/******************************************************************************* -** -** Function GATT_Register -** -** Description This function is called to register an application -** with GATT -** -** Parameter p_app_uuid128: Application UUID -** p_cb_info: callback functions. -** -** Returns 0 for error, otherwise the index of the client registered with GATT -** -*******************************************************************************/ -extern tGATT_IF GATT_Register (tBT_UUID *p_app_uuid128, tGATT_CBACK *p_cb_info); - -/******************************************************************************* -** -** Function GATT_Deregister -** -** Description This function deregistered the application from GATT. -** -** Parameters gatt_if: applicaiton interface. -** -** Returns None. -** -*******************************************************************************/ -extern void GATT_Deregister (tGATT_IF gatt_if); - -/******************************************************************************* -** -** Function GATT_StartIf -** -** Description This function is called after registration to start receiving -** callbacks for registered interface. Function may call back -** with connection status and queued notifications -** -** Parameter gatt_if: applicaiton interface. -** -** Returns None -** -*******************************************************************************/ -extern void GATT_StartIf (tGATT_IF gatt_if); - -/******************************************************************************* -** -** Function GATT_Connect -** -** Description This function initiate a connecttion to a remote device on GATT -** channel. -** -** Parameters gatt_if: applicaiton interface -** bd_addr: peer device address. -** bd_addr_type: peer device address type. -** is_direct: is a direct conenection or a background auto connection -** transport : Physical transport for GATT connection (BR/EDR or LE) -** -** Returns TRUE if connection started; FALSE if connection start failure. -** -*******************************************************************************/ -extern BOOLEAN GATT_Connect (tGATT_IF gatt_if, BD_ADDR bd_addr, tBLE_ADDR_TYPE bd_addr_type, - BOOLEAN is_direct, tBT_TRANSPORT transport); - - -/******************************************************************************* -** -** Function GATT_CancelConnect -** -** Description This function terminate the connection initaition to a remote -** device on GATT channel. -** -** Parameters gatt_if: client interface. If 0 used as unconditionally disconnect, -** typically used for direct connection cancellation. -** bd_addr: peer device address. -** is_direct: is a direct conenection or a background auto connection -** -** Returns TRUE if connection started; FALSE if connection start failure. -** -*******************************************************************************/ -extern BOOLEAN GATT_CancelConnect (tGATT_IF gatt_if, BD_ADDR bd_addr, - BOOLEAN is_direct); - -/******************************************************************************* -** -** Function GATT_Disconnect -** -** Description This function disconnect the GATT channel for this registered -** application. -** -** Parameters conn_id: connection identifier. -** -** Returns GATT_SUCCESS if disconnected. -** -*******************************************************************************/ -extern tGATT_STATUS GATT_Disconnect (UINT16 conn_id); - - - -/******************************************************************************* -** -** Function GATT_GetConnectionInfor -** -** Description This function use conn_id to find its associated BD address and applciation -** interface -** -** Parameters conn_id: connection id (input) -** p_gatt_if: applicaiton interface (output) -** bd_addr: peer device address. (output) -** transport : physical transport of the GATT connection (BR/EDR or LE) -** -** Returns TRUE the ligical link information is found for conn_id -** -*******************************************************************************/ -extern BOOLEAN GATT_GetConnectionInfor(UINT16 conn_id, tGATT_IF *p_gatt_if, - BD_ADDR bd_addr, tBT_TRANSPORT *p_transport); - - -/******************************************************************************* -** -** Function GATT_GetConnIdIfConnected -** -** Description This function find the conn_id if the logical link for BD address -** and applciation interface is connected -** -** Parameters gatt_if: applicaiton interface (input) -** bd_addr: peer device address. (input) -** p_conn_id: connection id (output) -** transport : physical transport of the GATT connection (BR/EDR or LE) -** -** Returns TRUE the ligical link is connected -** -*******************************************************************************/ -extern BOOLEAN GATT_GetConnIdIfConnected(tGATT_IF gatt_if, BD_ADDR bd_addr, - UINT16 *p_conn_id, tBT_TRANSPORT transport); - - -/******************************************************************************* -** -** Function GATT_Listen -** -** Description This function start or stop LE advertisement and listen for -** connection. -** -** Parameters gatt_if: applicaiton interface -** p_bd_addr: listen for specific address connection, or NULL for -** listen to all device connection. -** start: is a direct conenection or a background auto connection -** -** Returns TRUE if advertisement is started; FALSE if adv start failure. -** -*******************************************************************************/ -extern BOOLEAN GATT_Listen (tGATT_IF gatt_if, BOOLEAN start, BD_ADDR_PTR bd_addr); - -/******************************************************************************* -** -** Function GATT_ConfigServiceChangeCCC -** -** Description Configure service change indication on remote device -** -** Returns None. -** -*******************************************************************************/ -extern void GATT_ConfigServiceChangeCCC (BD_ADDR remote_bda, BOOLEAN enable, - tBT_TRANSPORT transport); - -#ifdef __cplusplus - -} -#endif - -#endif /* GATT_API_H */ diff --git a/tools/sdk/include/bluedroid/gatt_int.h b/tools/sdk/include/bluedroid/gatt_int.h deleted file mode 100644 index 6aaa42aa0a2..00000000000 --- a/tools/sdk/include/bluedroid/gatt_int.h +++ /dev/null @@ -1,753 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 GATT_INT_H -#define GATT_INT_H - -#include "bt_target.h" -#include "bt_trace.h" -#include "gatt_api.h" -#include "btm_ble_api.h" -#include "btu.h" -#include "fixed_queue.h" - -#include - - -#define GATT_CREATE_CONN_ID(tcb_idx, gatt_if) ((UINT16) ((((UINT8)(tcb_idx) ) << 8) | ((UINT8) (gatt_if)))) -#define GATT_GET_TCB_IDX(conn_id) ((UINT8) (((UINT16) (conn_id)) >> 8)) -#define GATT_GET_GATT_IF(conn_id) ((tGATT_IF)((UINT8) (conn_id))) - -#define GATT_GET_SR_REG_PTR(index) (&gatt_cb.sr_reg[(UINT8) (index)]); -#define GATT_TRANS_ID_MAX 0x0fffffff /* 4 MSB is reserved */ -#define GATT_RSP_BY_APP 0x00 -#define GATT_RSP_BY_STACK 0x01 -#define GATT_RSP_DEFAULT GATT_RSP_BY_APP //need to rsp by the app. - -/* security action for GATT write and read request */ -#define GATT_SEC_NONE 0 -#define GATT_SEC_OK 1 -#define GATT_SEC_SIGN_DATA 2 /* compute the signature for the write cmd */ -#define GATT_SEC_ENCRYPT 3 /* encrypt the link with current key */ -#define GATT_SEC_ENCRYPT_NO_MITM 4 /* unauthenticated encryption or better */ -#define GATT_SEC_ENCRYPT_MITM 5 /* authenticated encryption */ -#define GATT_SEC_ENC_PENDING 6 /* wait for link encryption pending */ -typedef UINT8 tGATT_SEC_ACTION; - - -#define GATT_ATTR_OP_SPT_MTU (0x00000001 << 0) -#define GATT_ATTR_OP_SPT_FIND_INFO (0x00000001 << 1) -#define GATT_ATTR_OP_SPT_FIND_BY_TYPE (0x00000001 << 2) -#define GATT_ATTR_OP_SPT_READ_BY_TYPE (0x00000001 << 3) -#define GATT_ATTR_OP_SPT_READ (0x00000001 << 4) -#define GATT_ATTR_OP_SPT_MULT_READ (0x00000001 << 5) -#define GATT_ATTR_OP_SPT_READ_BLOB (0x00000001 << 6) -#define GATT_ATTR_OP_SPT_READ_BY_GRP_TYPE (0x00000001 << 7) -#define GATT_ATTR_OP_SPT_WRITE (0x00000001 << 8) -#define GATT_ATTR_OP_SPT_WRITE_CMD (0x00000001 << 9) -#define GATT_ATTR_OP_SPT_PREP_WRITE (0x00000001 << 10) -#define GATT_ATTR_OP_SPT_EXE_WRITE (0x00000001 << 11) -#define GATT_ATTR_OP_SPT_HDL_VALUE_CONF (0x00000001 << 12) -#define GATT_ATTR_OP_SP_SIGN_WRITE (0x00000001 << 13) - -#define GATT_INDEX_INVALID 0xff - -#define GATT_PENDING_REQ_NONE 0 - - -#define GATT_WRITE_CMD_MASK 0xc0 /*0x1100-0000*/ -#define GATT_AUTH_SIGN_MASK 0x80 /*0x1000-0000*/ -#define GATT_AUTH_SIGN_LEN 12 - -#define GATT_HDR_SIZE 3 /* 1B opcode + 2B handle */ - -/* wait for ATT cmd response timeout value */ -#define GATT_WAIT_FOR_RSP_TOUT 30 -#define GATT_WAIT_FOR_DISC_RSP_TOUT 5 -#define GATT_REQ_RETRY_LIMIT 2 -#define GATT_WAIT_FOR_IND_ACK_TOUT 5 - -/* characteristic descriptor type */ -#define GATT_DESCR_EXT_DSCPTOR 1 /* Characteristic Extended Properties */ -#define GATT_DESCR_USER_DSCPTOR 2 /* Characteristic User Description */ -#define GATT_DESCR_CLT_CONFIG 3 /* Client Characteristic Configuration */ -#define GATT_DESCR_SVR_CONFIG 4 /* Server Characteristic Configuration */ -#define GATT_DESCR_PRES_FORMAT 5 /* Characteristic Presentation Format */ -#define GATT_DESCR_AGGR_FORMAT 6 /* Characteristic Aggregate Format */ -#define GATT_DESCR_VALID_RANGE 7 /* Characteristic Valid Range */ -#define GATT_DESCR_UNKNOWN 0xff - -#define GATT_SEC_FLAG_LKEY_UNAUTHED BTM_SEC_FLAG_LKEY_KNOWN -#define GATT_SEC_FLAG_LKEY_AUTHED BTM_SEC_FLAG_LKEY_AUTHED -#define GATT_SEC_FLAG_ENCRYPTED BTM_SEC_FLAG_ENCRYPTED -typedef UINT8 tGATT_SEC_FLAG; - -/* Find Information Response Type -*/ -#define GATT_INFO_TYPE_PAIR_16 0x01 -#define GATT_INFO_TYPE_PAIR_128 0x02 - -/* GATT client FIND_TYPE_VALUE_Request data */ -typedef struct { - tBT_UUID uuid; /* type of attribute to be found */ - UINT16 s_handle; /* starting handle */ - UINT16 e_handle; /* ending handle */ - UINT16 value_len; /* length of the attribute value */ - UINT8 value[GATT_MAX_MTU_SIZE]; /* pointer to the attribute value to be found */ -} tGATT_FIND_TYPE_VALUE; - -/* client request message to ATT protocol -*/ -typedef union { - tGATT_READ_BY_TYPE browse; /* read by type request */ - tGATT_FIND_TYPE_VALUE find_type_value;/* find by type value */ - tGATT_READ_MULTI read_multi; /* read multiple request */ - tGATT_READ_PARTIAL read_blob; /* read blob */ - tGATT_VALUE attr_value; /* write request */ - /* prepare write */ - /* write blob */ - UINT16 handle; /* read, handle value confirmation */ - UINT16 mtu; - tGATT_EXEC_FLAG exec_write; /* execute write */ -} tGATT_CL_MSG; - -/* error response strucutre */ -typedef struct { - UINT16 handle; - UINT8 cmd_code; - UINT8 reason; -} tGATT_ERROR; - -/* Execute write response structure */ -typedef struct { - UINT8 op_code; -}__attribute__((packed)) tGATT_EXEC_WRITE_RSP; - -/* Write request response structure */ -typedef struct { - UINT8 op_code; -}__attribute__((packed)) tGATT_WRITE_REQ_RSP; - -/* server response message to ATT protocol -*/ -typedef union { - /* data type member event */ - tGATT_VALUE attr_value; /* READ, HANDLE_VALUE_IND, PREPARE_WRITE */ - /* READ_BLOB, READ_BY_TYPE */ - tGATT_ERROR error; /* ERROR_RSP */ - UINT16 handle; /* WRITE, WRITE_BLOB */ - UINT16 mtu; /* exchange MTU request */ -} tGATT_SR_MSG; - -/* Characteristic declaration attribute value -*/ -typedef struct { - tGATT_CHAR_PROP property; - UINT16 char_val_handle; -} tGATT_CHAR_DECL; - -/* attribute value maintained in the server database -*/ -typedef union { - tBT_UUID uuid; /* service declaration */ - tGATT_CHAR_DECL char_decl; /* characteristic declaration */ - tGATT_INCL_SRVC incl_handle; /* included service */ - tGATT_ATTR_VAL attr_val; -} tGATT_ATTR_VALUE; - -/* Attribute UUID type -*/ -#define GATT_ATTR_UUID_TYPE_16 0 -#define GATT_ATTR_UUID_TYPE_128 1 -#define GATT_ATTR_UUID_TYPE_32 2 -typedef UINT8 tGATT_ATTR_UUID_TYPE; - -/* 16 bits UUID Attribute in server database -*/ -typedef struct { - void *p_next; /* pointer to the next attribute, either tGATT_ATTR16 or tGATT_ATTR128 */ - tGATT_ATTR_VALUE *p_value; - tGATT_ATTR_UUID_TYPE uuid_type; - tGATT_PERM permission; - tGATTS_ATTR_CONTROL control; - tGATT_ATTR_MASK mask; - UINT16 handle; - UINT16 uuid; -} tGATT_ATTR16; - -/* 32 bits UUID Attribute in server database -*/ -typedef struct { - void *p_next; /* pointer to the next attribute, either tGATT_ATTR16, tGATT_ATTR32 or tGATT_ATTR128 */ - tGATT_ATTR_VALUE *p_value; - tGATT_ATTR_UUID_TYPE uuid_type; - tGATT_PERM permission; - tGATTS_ATTR_CONTROL control; - tGATT_ATTR_MASK mask; - UINT16 handle; - UINT32 uuid; -} tGATT_ATTR32; - - -/* 128 bits UUID Attribute in server database -*/ -typedef struct { - void *p_next; /* pointer to the next attribute, either tGATT_ATTR16 or tGATT_ATTR128 */ - tGATT_ATTR_VALUE *p_value; - tGATT_ATTR_UUID_TYPE uuid_type; - tGATT_PERM permission; - tGATTS_ATTR_CONTROL control; - tGATT_ATTR_MASK mask; - UINT16 handle; - UINT8 uuid[LEN_UUID_128]; -} tGATT_ATTR128; - -/* Service Database definition -*/ -typedef struct { - void *p_attr_list; /* pointer to the first attribute, either tGATT_ATTR16 or tGATT_ATTR128 */ - UINT8 *p_free_mem; /* Pointer to free memory */ - fixed_queue_t *svc_buffer; /* buffer queue used for service database */ - UINT32 mem_free; /* Memory still available */ - UINT16 end_handle; /* Last handle number */ - UINT16 next_handle; /* Next usable handle value */ -} tGATT_SVC_DB; - -/* Data Structure used for GATT server */ -/* A GATT registration record consists of a handle, and 1 or more attributes */ -/* A service registration information record consists of beginning and ending */ -/* attribute handle, service UUID and a set of GATT server callback. */ -typedef struct { - tGATT_SVC_DB *p_db; /* pointer to the service database */ - tBT_UUID app_uuid; /* applicatino UUID */ - UINT32 sdp_handle; /* primamry service SDP handle */ - UINT16 service_instance; /* service instance number */ - UINT16 type; /* service type UUID, primary or secondary */ - UINT16 s_hdl; /* service starting handle */ - UINT16 e_hdl; /* service ending handle */ - tGATT_IF gatt_if; /* this service is belong to which application */ - BOOLEAN in_use; -} tGATT_SR_REG; - -#define GATT_LISTEN_TO_ALL 0xff -#define GATT_LISTEN_TO_NONE 0 - -/* Data Structure used for GATT server */ -/* An GATT registration record consists of a handle, and 1 or more attributes */ -/* A service registration information record consists of beginning and ending */ -/* attribute handle, service UUID and a set of GATT server callback. */ - -typedef struct { - tBT_UUID app_uuid128; - tGATT_CBACK app_cb; - tGATT_IF gatt_if; /* one based */ - BOOLEAN in_use; - UINT8 listening; /* if adv for all has been enabled */ -} tGATT_REG; - - - - -/* command queue for each connection */ -typedef struct { - BT_HDR *p_cmd; - UINT16 clcb_idx; - UINT8 op_code; - BOOLEAN to_send; -} tGATT_CMD_Q; - - -#if GATT_MAX_SR_PROFILES <= 8 -typedef UINT8 tGATT_APP_MASK; -#elif GATT_MAX_SR_PROFILES <= 16 -typedef UINT16 tGATT_APP_MASK; -#elif GATT_MAX_SR_PROFILES <= 32 -typedef UINT32 tGATT_APP_MASK; -#endif - -/* command details for each connection */ -typedef struct { - BT_HDR *p_rsp_msg; - UINT32 trans_id; - tGATT_READ_MULTI multi_req; - fixed_queue_t *multi_rsp_q; - UINT16 handle; - UINT8 op_code; - UINT8 status; - UINT8 cback_cnt[GATT_MAX_APPS]; -} tGATT_SR_CMD; - -#define GATT_CH_CLOSE 0 -#define GATT_CH_CLOSING 1 -#define GATT_CH_CONN 2 -#define GATT_CH_CFG 3 -#define GATT_CH_OPEN 4 - -typedef UINT8 tGATT_CH_STATE; - -#define GATT_GATT_START_HANDLE 1 -#define GATT_GAP_START_HANDLE 20 -#define GATT_APP_START_HANDLE 40 - -typedef struct hdl_cfg { - UINT16 gatt_start_hdl; - UINT16 gap_start_hdl; - UINT16 app_start_hdl; -} tGATT_HDL_CFG; - -typedef struct hdl_list_elem { - struct hdl_list_elem *p_next; - struct hdl_list_elem *p_prev; - tGATTS_HNDL_RANGE asgn_range; /* assigned handle range */ - tGATT_SVC_DB svc_db; - BOOLEAN in_use; -} tGATT_HDL_LIST_ELEM; - -typedef struct { - tGATT_HDL_LIST_ELEM *p_first; - tGATT_HDL_LIST_ELEM *p_last; - UINT16 count; -} tGATT_HDL_LIST_INFO; - - -typedef struct srv_list_elem { - struct srv_list_elem *p_next; - struct srv_list_elem *p_prev; - UINT16 s_hdl; - UINT8 i_sreg; - BOOLEAN in_use; - BOOLEAN is_primary; -} tGATT_SRV_LIST_ELEM; - - -typedef struct { - tGATT_SRV_LIST_ELEM *p_last_primary; - tGATT_SRV_LIST_ELEM *p_first; - tGATT_SRV_LIST_ELEM *p_last; - UINT16 count; -} tGATT_SRV_LIST_INFO; - -/* prepare write queue data */ -typedef struct{ - //len: length of value - tGATT_ATTR16 *p_attr; - UINT16 len; - UINT8 op_code; - UINT16 handle; - UINT16 offset; - UINT8 value[2]; -}__attribute__((packed)) tGATT_PREPARE_WRITE_QUEUE_DATA; - -/* structure to store prepare write packts information */ -typedef struct{ - //only store prepare write packets which need - //to be responded by stack (not by application) - fixed_queue_t *queue; - - //store the total number of prepare write packets - //including that should be responded by stack or by application - UINT16 total_num; - - //store application error code for prepare write, - //invalid offset && invalid length - UINT8 error_code_app; -}tGATT_PREPARE_WRITE_RECORD; - -typedef struct { - fixed_queue_t *pending_enc_clcb; /* pending encryption channel q */ - tGATT_SEC_ACTION sec_act; - BD_ADDR peer_bda; - tBT_TRANSPORT transport; - UINT32 trans_id; - - UINT16 att_lcid; /* L2CAP channel ID for ATT */ - UINT16 payload_size; - - tGATT_CH_STATE ch_state; - UINT8 ch_flags; - - tGATT_IF app_hold_link[GATT_MAX_APPS]; - - /* server needs */ - /* server response data */ -#if (GATTS_INCLUDED == TRUE) - tGATT_SR_CMD sr_cmd; -#endif ///GATTS_INCLUDED == TRUE - UINT16 indicate_handle; - fixed_queue_t *pending_ind_q; - - TIMER_LIST_ENT conf_timer_ent; /* peer confirm to indication timer */ - - UINT8 prep_cnt[GATT_MAX_APPS]; - UINT8 ind_count; - - tGATT_CMD_Q cl_cmd_q[GATT_CL_MAX_LCB]; - TIMER_LIST_ENT ind_ack_timer_ent; /* local app confirm to indication timer */ - UINT8 pending_cl_req; - UINT8 next_slot_inq; /* index of next available slot in queue */ - - BOOLEAN in_use; - UINT8 tcb_idx; - tGATT_PREPARE_WRITE_RECORD prepare_write_record; /* prepare write packets record */ -} tGATT_TCB; - - -/* logic channel */ -typedef struct { - UINT16 next_disc_start_hdl; /* starting handle for the next inc srvv discovery */ - tGATT_DISC_RES result; - BOOLEAN wait_for_read_rsp; -} tGATT_READ_INC_UUID128; -typedef struct { - tGATT_TCB *p_tcb; /* associated TCB of this CLCB */ - tGATT_REG *p_reg; /* owner of this CLCB */ - UINT8 sccb_idx; - UINT8 *p_attr_buf; /* attribute buffer for read multiple, prepare write */ - tBT_UUID uuid; - UINT16 conn_id; /* connection handle */ - UINT16 clcb_idx; - UINT16 s_handle; /* starting handle of the active request */ - UINT16 e_handle; /* ending handle of the active request */ - UINT16 counter; /* used as offset, attribute length, num of prepare write */ - UINT16 start_offset; - tGATT_AUTH_REQ auth_req; /* authentication requirement */ - UINT8 operation; /* one logic channel can have one operation active */ - UINT8 op_subtype; /* operation subtype */ - UINT8 status; /* operation status */ - BOOLEAN first_read_blob_after_read; - tGATT_READ_INC_UUID128 read_uuid128; - BOOLEAN in_use; - TIMER_LIST_ENT rsp_timer_ent; /* peer response timer */ - UINT8 retry_count; - -} tGATT_CLCB; - -typedef struct { - tGATT_CLCB *p_clcb; -} tGATT_PENDING_ENC_CLCB; - - -#define GATT_SIGN_WRITE 1 -#define GATT_VERIFY_SIGN_DATA 2 - -typedef struct { - BT_HDR hdr; - tGATT_CLCB *p_clcb; -} tGATT_SIGN_WRITE_OP; - -typedef struct { - BT_HDR hdr; - tGATT_TCB *p_tcb; - BT_HDR *p_data; - -} tGATT_VERIFY_SIGN_OP; - - -typedef struct { - UINT16 clcb_idx; - BOOLEAN in_use; -} tGATT_SCCB; - -typedef struct { - UINT16 handle; - UINT16 uuid; - UINT32 service_change; -} tGATT_SVC_CHG; - -typedef struct { - tGATT_IF gatt_if[GATT_MAX_APPS]; - tGATT_IF listen_gif[GATT_MAX_APPS]; - BD_ADDR remote_bda; - BOOLEAN in_use; -} tGATT_BG_CONN_DEV; - -#define GATT_SVC_CHANGED_CONNECTING 1 /* wait for connection */ -#define GATT_SVC_CHANGED_SERVICE 2 /* GATT service discovery */ -#define GATT_SVC_CHANGED_CHARACTERISTIC 3 /* service change char discovery */ -#define GATT_SVC_CHANGED_DESCRIPTOR 4 /* service change CCC discoery */ -#define GATT_SVC_CHANGED_CONFIGURE_CCCD 5 /* config CCC */ - -typedef struct { - UINT16 conn_id; - BOOLEAN in_use; - BOOLEAN connected; - BD_ADDR bda; - tBT_TRANSPORT transport; - - /* GATT service change CCC related variables */ - UINT8 ccc_stage; - UINT8 ccc_result; - UINT16 s_handle; - UINT16 e_handle; -} tGATT_PROFILE_CLCB; - -typedef struct { - tGATT_TCB tcb[GATT_MAX_PHY_CHANNEL]; - fixed_queue_t *sign_op_queue; - - tGATT_SR_REG sr_reg[GATT_MAX_SR_PROFILES]; - UINT16 next_handle; /* next available handle */ - tGATT_SVC_CHG gattp_attr; /* GATT profile attribute service change */ - tGATT_IF gatt_if; -#if (GATTS_INCLUDED == TRUE) - tGATT_HDL_LIST_INFO hdl_list_info; - tGATT_HDL_LIST_ELEM hdl_list[GATT_MAX_SR_PROFILES]; - tGATT_SRV_LIST_INFO srv_list_info; - tGATT_SRV_LIST_ELEM srv_list[GATT_MAX_SR_PROFILES]; -#endif ///GATTS_INCLUDED == TRUE - fixed_queue_t *srv_chg_clt_q; /* service change clients queue */ - fixed_queue_t *pending_new_srv_start_q; /* pending new service start queue */ - tGATT_REG cl_rcb[GATT_MAX_APPS]; - tGATT_CLCB clcb[GATT_CL_MAX_LCB]; /* connection link control block*/ - tGATT_SCCB sccb[GATT_MAX_SCCB]; /* sign complete callback function GATT_MAX_SCCB <= GATT_CL_MAX_LCB */ - UINT8 trace_level; - UINT16 def_mtu_size; - -#if GATT_CONFORMANCE_TESTING == TRUE - BOOLEAN enable_err_rsp; - UINT8 req_op_code; - UINT8 err_status; - UINT16 handle; -#endif -#if (GATTS_INCLUDED == TRUE) - tGATT_PROFILE_CLCB profile_clcb[GATT_MAX_APPS]; -#endif ///GATTS_INCLUDED == TRUE - UINT16 handle_of_h_r; /* Handle of the handles reused characteristic value */ - - tGATT_APPL_INFO cb_info; - - - - tGATT_HDL_CFG hdl_cfg; - tGATT_BG_CONN_DEV bgconn_dev[GATT_MAX_BG_CONN_DEV]; - -} tGATT_CB; - -typedef struct{ - UINT16 local_mtu; -} tGATT_DEFAULT; - -#define GATT_SIZE_OF_SRV_CHG_HNDL_RANGE 4 - -#ifdef __cplusplus -extern "C" { -#endif - -extern tGATT_DEFAULT gatt_default; - -/* Global GATT data */ -#if GATT_DYNAMIC_MEMORY == FALSE -extern tGATT_CB gatt_cb; -#else -extern tGATT_CB *gatt_cb_ptr; -#define gatt_cb (*gatt_cb_ptr) -#endif - -#if GATT_CONFORMANCE_TESTING == TRUE -extern void gatt_set_err_rsp(BOOLEAN enable, UINT8 req_op_code, UINT8 err_status); -#endif - -#ifdef __cplusplus -} -#endif - -/* internal functions */ -extern void gatt_init (void); -extern void gatt_free(void); - -/* from gatt_main.c */ -extern BOOLEAN gatt_disconnect (tGATT_TCB *p_tcb); -extern BOOLEAN gatt_act_connect (tGATT_REG *p_reg, BD_ADDR bd_addr, tBLE_ADDR_TYPE bd_addr_type, tBT_TRANSPORT transport); -extern BOOLEAN gatt_connect (BD_ADDR rem_bda, tBLE_ADDR_TYPE bd_addr_type, tGATT_TCB *p_tcb, tBT_TRANSPORT transport); -extern void gatt_data_process (tGATT_TCB *p_tcb, BT_HDR *p_buf); -extern void gatt_update_app_use_link_flag ( tGATT_IF gatt_if, tGATT_TCB *p_tcb, BOOLEAN is_add, BOOLEAN check_acl_link); - -extern void gatt_profile_db_init(void); -extern void gatt_set_ch_state(tGATT_TCB *p_tcb, tGATT_CH_STATE ch_state); -extern tGATT_CH_STATE gatt_get_ch_state(tGATT_TCB *p_tcb); -extern void gatt_init_srv_chg(void); -extern void gatt_proc_srv_chg (void); -extern void gatt_send_srv_chg_ind (BD_ADDR peer_bda); -extern void gatt_chk_srv_chg(tGATTS_SRV_CHG *p_srv_chg_clt); -extern void gatt_add_a_bonded_dev_for_srv_chg (BD_ADDR bda); - -/* from gatt_attr.c */ -extern UINT16 gatt_profile_find_conn_id_by_bd_addr(BD_ADDR bda); - - -/* Functions provided by att_protocol.c */ -extern tGATT_STATUS attp_send_cl_msg (tGATT_TCB *p_tcb, UINT16 clcb_idx, UINT8 op_code, tGATT_CL_MSG *p_msg); -extern BT_HDR *attp_build_sr_msg(tGATT_TCB *p_tcb, UINT8 op_code, tGATT_SR_MSG *p_msg); -extern tGATT_STATUS attp_send_sr_msg (tGATT_TCB *p_tcb, BT_HDR *p_msg); -extern tGATT_STATUS attp_send_msg_to_l2cap(tGATT_TCB *p_tcb, BT_HDR *p_toL2CAP); - -/* utility functions */ -extern UINT8 *gatt_dbg_op_name(UINT8 op_code); -#if (SDP_INCLUDED == TRUE) -extern UINT32 gatt_add_sdp_record (tBT_UUID *p_uuid, UINT16 start_hdl, UINT16 end_hdl); -#endif ///SDP_INCLUDED == TRUE -extern BOOLEAN gatt_parse_uuid_from_cmd(tBT_UUID *p_uuid, UINT16 len, UINT8 **p_data); -extern UINT8 gatt_build_uuid_to_stream(UINT8 **p_dst, tBT_UUID uuid); -extern BOOLEAN gatt_uuid_compare(tBT_UUID src, tBT_UUID tar); -extern void gatt_convert_uuid32_to_uuid128(UINT8 uuid_128[LEN_UUID_128], UINT32 uuid_32); -extern void gatt_sr_get_sec_info(BD_ADDR rem_bda, tBT_TRANSPORT transport, UINT8 *p_sec_flag, UINT8 *p_key_size); -extern void gatt_start_rsp_timer(UINT16 clcb_idx); -extern void gatt_start_conf_timer(tGATT_TCB *p_tcb); -extern void gatt_rsp_timeout(TIMER_LIST_ENT *p_tle); -extern void gatt_ind_ack_timeout(TIMER_LIST_ENT *p_tle); -extern void gatt_start_ind_ack_timer(tGATT_TCB *p_tcb); -extern tGATT_STATUS gatt_send_error_rsp(tGATT_TCB *p_tcb, UINT8 err_code, UINT8 op_code, UINT16 handle, BOOLEAN deq); -extern void gatt_dbg_display_uuid(tBT_UUID bt_uuid); -extern tGATT_PENDING_ENC_CLCB *gatt_add_pending_enc_channel_clcb(tGATT_TCB *p_tcb, tGATT_CLCB *p_clcb ); - -extern tGATTS_PENDING_NEW_SRV_START *gatt_sr_is_new_srv_chg(tBT_UUID *p_app_uuid128, tBT_UUID *p_svc_uuid, UINT16 svc_inst); - -extern BOOLEAN gatt_is_srv_chg_ind_pending (tGATT_TCB *p_tcb); -extern tGATTS_SRV_CHG *gatt_is_bda_in_the_srv_chg_clt_list (BD_ADDR bda); - -extern BOOLEAN gatt_find_the_connected_bda(UINT8 start_idx, BD_ADDR bda, UINT8 *p_found_idx, tBT_TRANSPORT *p_transport); -extern void gatt_set_srv_chg(void); -extern void gatt_delete_dev_from_srv_chg_clt_list(BD_ADDR bd_addr); -extern tGATT_VALUE *gatt_add_pending_ind(tGATT_TCB *p_tcb, tGATT_VALUE *p_ind); -extern tGATTS_PENDING_NEW_SRV_START *gatt_add_pending_new_srv_start( tGATTS_HNDL_RANGE *p_new_srv_start); -extern void gatt_free_srvc_db_buffer_app_id(tBT_UUID *p_app_id); -extern BOOLEAN gatt_update_listen_mode(void); -extern BOOLEAN gatt_cl_send_next_cmd_inq(tGATT_TCB *p_tcb); - -/* reserved handle list */ -extern tGATT_HDL_LIST_ELEM *gatt_find_hdl_buffer_by_app_id (tBT_UUID *p_app_uuid128, tBT_UUID *p_svc_uuid, UINT16 svc_inst); -extern tGATT_HDL_LIST_ELEM *gatt_find_hdl_buffer_by_handle(UINT16 handle); -extern tGATT_HDL_LIST_ELEM *gatt_find_hdl_buffer_by_attr_handle(UINT16 attr_handle); -extern tGATT_HDL_LIST_ELEM *gatt_alloc_hdl_buffer(void); -extern void gatt_free_hdl_buffer(tGATT_HDL_LIST_ELEM *p); -extern void gatt_free_attr_value_buffer(tGATT_HDL_LIST_ELEM *p); -extern BOOLEAN gatt_is_last_attribute(tGATT_SRV_LIST_INFO *p_list, tGATT_SRV_LIST_ELEM *p_start, tBT_UUID value); -extern void gatt_update_last_pri_srv_info(tGATT_SRV_LIST_INFO *p_list); -extern BOOLEAN gatt_add_a_srv_to_list(tGATT_SRV_LIST_INFO *p_list, tGATT_SRV_LIST_ELEM *p_new); -extern BOOLEAN gatt_remove_a_srv_from_list(tGATT_SRV_LIST_INFO *p_list, tGATT_SRV_LIST_ELEM *p_remove); -extern BOOLEAN gatt_add_an_item_to_list(tGATT_HDL_LIST_INFO *p_list, tGATT_HDL_LIST_ELEM *p_new); -extern BOOLEAN gatt_remove_an_item_from_list(tGATT_HDL_LIST_INFO *p_list, tGATT_HDL_LIST_ELEM *p_remove); -extern tGATTS_SRV_CHG *gatt_add_srv_chg_clt(tGATTS_SRV_CHG *p_srv_chg); - -/* for background connection */ -extern BOOLEAN gatt_update_auto_connect_dev (tGATT_IF gatt_if, BOOLEAN add, BD_ADDR bd_addr, BOOLEAN is_initiator); -extern BOOLEAN gatt_is_bg_dev_for_app(tGATT_BG_CONN_DEV *p_dev, tGATT_IF gatt_if); -extern BOOLEAN gatt_remove_bg_dev_for_app(tGATT_IF gatt_if, BD_ADDR bd_addr); -extern UINT8 gatt_get_num_apps_for_bg_dev(BD_ADDR bd_addr); -extern BOOLEAN gatt_find_app_for_bg_dev(BD_ADDR bd_addr, tGATT_IF *p_gatt_if); -extern tGATT_BG_CONN_DEV *gatt_find_bg_dev(BD_ADDR remote_bda); -extern void gatt_deregister_bgdev_list(tGATT_IF gatt_if); -extern void gatt_reset_bgdev_list(void); - -/* server function */ -extern UINT8 gatt_sr_find_i_rcb_by_handle(UINT16 handle); -extern UINT8 gatt_sr_find_i_rcb_by_app_id(tBT_UUID *p_app_uuid128, tBT_UUID *p_svc_uuid, UINT16 svc_inst); -extern UINT8 gatt_sr_alloc_rcb(tGATT_HDL_LIST_ELEM *p_list); -extern tGATT_STATUS gatt_sr_process_app_rsp (tGATT_TCB *p_tcb, tGATT_IF gatt_if, UINT32 trans_id, UINT8 op_code, tGATT_STATUS status, tGATTS_RSP *p_msg); -extern void gatt_server_handle_client_req (tGATT_TCB *p_tcb, UINT8 op_code, - UINT16 len, UINT8 *p_data); -extern void gatt_sr_send_req_callback(UINT16 conn_id, UINT32 trans_id, - UINT8 op_code, tGATTS_DATA *p_req_data); -extern UINT32 gatt_sr_enqueue_cmd (tGATT_TCB *p_tcb, UINT8 op_code, UINT16 handle); -extern BOOLEAN gatt_cancel_open(tGATT_IF gatt_if, BD_ADDR bda); - -/* */ - -extern tGATT_REG *gatt_get_regcb (tGATT_IF gatt_if); -extern BOOLEAN gatt_is_clcb_allocated (UINT16 conn_id); -extern tGATT_CLCB *gatt_clcb_alloc (UINT16 conn_id); -extern void gatt_clcb_dealloc (tGATT_CLCB *p_clcb); - -extern void gatt_sr_copy_prep_cnt_to_cback_cnt(tGATT_TCB *p_tcb ); -extern BOOLEAN gatt_sr_is_cback_cnt_zero(tGATT_TCB *p_tcb ); -extern BOOLEAN gatt_sr_is_prep_cnt_zero(tGATT_TCB *p_tcb ); -extern void gatt_sr_reset_cback_cnt(tGATT_TCB *p_tcb ); -extern void gatt_sr_reset_prep_cnt(tGATT_TCB *p_tcb ); -extern void gatt_sr_update_cback_cnt(tGATT_TCB *p_tcb, tGATT_IF gatt_if, BOOLEAN is_inc, BOOLEAN is_reset_first); -extern void gatt_sr_update_prep_cnt(tGATT_TCB *p_tcb, tGATT_IF gatt_if, BOOLEAN is_inc, BOOLEAN is_reset_first); - -extern BOOLEAN gatt_find_app_hold_link(tGATT_TCB *p_tcb, UINT8 start_idx, UINT8 *p_found_idx, tGATT_IF *p_gatt_if); -extern BOOLEAN gatt_find_specific_app_in_hold_link(tGATT_TCB *p_tcb, tGATT_IF p_gatt_if); -extern UINT8 gatt_num_apps_hold_link(tGATT_TCB *p_tcb); -extern UINT8 gatt_num_clcb_by_bd_addr(BD_ADDR bda); -extern tGATT_TCB *gatt_find_tcb_by_cid(UINT16 lcid); -extern tGATT_TCB *gatt_allocate_tcb_by_bdaddr(BD_ADDR bda, tBT_TRANSPORT transport); -extern tGATT_TCB *gatt_get_tcb_by_idx(UINT8 tcb_idx); -extern tGATT_TCB *gatt_find_tcb_by_addr(BD_ADDR bda, tBT_TRANSPORT transport); -extern BOOLEAN gatt_send_ble_burst_data (BD_ADDR remote_bda, BT_HDR *p_buf); - -/* GATT client functions */ -extern void gatt_dequeue_sr_cmd (tGATT_TCB *p_tcb); -extern UINT8 gatt_send_write_msg(tGATT_TCB *p_tcb, UINT16 clcb_idx, UINT8 op_code, UINT16 handle, - UINT16 len, UINT16 offset, UINT8 *p_data); -extern void gatt_cleanup_upon_disc(BD_ADDR bda, UINT16 reason, tBT_TRANSPORT transport); -extern void gatt_end_operation(tGATT_CLCB *p_clcb, tGATT_STATUS status, void *p_data); - -extern void gatt_act_discovery(tGATT_CLCB *p_clcb); -extern void gatt_act_read(tGATT_CLCB *p_clcb, UINT16 offset); -extern void gatt_act_write(tGATT_CLCB *p_clcb, UINT8 sec_act); -extern UINT8 gatt_act_send_browse(tGATT_TCB *p_tcb, UINT16 index, UINT8 op, UINT16 s_handle, UINT16 e_handle, - tBT_UUID uuid); -extern tGATT_CLCB *gatt_cmd_dequeue(tGATT_TCB *p_tcb, UINT8 *p_opcode); -extern BOOLEAN gatt_cmd_enq(tGATT_TCB *p_tcb, UINT16 clcb_idx, BOOLEAN to_send, UINT8 op_code, BT_HDR *p_buf); -extern void gatt_client_handle_server_rsp (tGATT_TCB *p_tcb, UINT8 op_code, - UINT16 len, UINT8 *p_data); -extern void gatt_send_queue_write_cancel (tGATT_TCB *p_tcb, tGATT_CLCB *p_clcb, tGATT_EXEC_FLAG flag); - -/* gatt_auth.c */ -extern BOOLEAN gatt_security_check_start(tGATT_CLCB *p_clcb); -extern void gatt_verify_signature(tGATT_TCB *p_tcb, BT_HDR *p_buf); -extern tGATT_SEC_ACTION gatt_determine_sec_act(tGATT_CLCB *p_clcb ); -extern tGATT_STATUS gatt_get_link_encrypt_status(tGATT_TCB *p_tcb); -extern tGATT_SEC_ACTION gatt_get_sec_act(tGATT_TCB *p_tcb); -extern void gatt_set_sec_act(tGATT_TCB *p_tcb, tGATT_SEC_ACTION sec_act); - -/* gatt_db.c */ -extern BOOLEAN gatts_init_service_db (tGATT_SVC_DB *p_db, tBT_UUID *p_service, BOOLEAN is_pri, UINT16 s_hdl, UINT16 num_handle); -extern UINT16 gatts_add_included_service (tGATT_SVC_DB *p_db, UINT16 s_handle, UINT16 e_handle, tBT_UUID service); -extern UINT16 gatts_add_characteristic (tGATT_SVC_DB *p_db, tGATT_PERM perm, - tGATT_CHAR_PROP property, - tBT_UUID *p_char_uuid, tGATT_ATTR_VAL *attr_val, - tGATTS_ATTR_CONTROL *control); -extern UINT16 gatts_add_char_descr (tGATT_SVC_DB *p_db, tGATT_PERM perm, - tBT_UUID *p_dscp_uuid, tGATT_ATTR_VAL *attr_val, - tGATTS_ATTR_CONTROL *control); - -extern tGATT_STATUS gatts_set_attribute_value(tGATT_SVC_DB *p_db, UINT16 attr_handle, - UINT16 length, UINT8 *value); - -extern tGATT_STATUS gatts_get_attribute_value(tGATT_SVC_DB *p_db, UINT16 attr_handle, - UINT16 *length, UINT8 **value); -extern BOOLEAN gatts_is_auto_response(UINT16 attr_handle); -extern tGATT_STATUS gatts_db_read_attr_value_by_type (tGATT_TCB *p_tcb, tGATT_SVC_DB *p_db, UINT8 op_code, BT_HDR *p_rsp, UINT16 s_handle, - UINT16 e_handle, tBT_UUID type, UINT16 *p_len, tGATT_SEC_FLAG sec_flag, UINT8 key_size, UINT32 trans_id, UINT16 *p_cur_handle); -extern tGATT_STATUS gatts_read_attr_value_by_handle(tGATT_TCB *p_tcb, tGATT_SVC_DB *p_db, UINT8 op_code, UINT16 handle, UINT16 offset, - UINT8 *p_value, UINT16 *p_len, UINT16 mtu, tGATT_SEC_FLAG sec_flag, UINT8 key_size, UINT32 trans_id); -extern tGATT_STATUS gatts_write_attr_value_by_handle(tGATT_SVC_DB *p_db, - UINT16 handle, UINT16 offset, - UINT8 *p_value, UINT16 len); -extern tGATT_STATUS gatts_write_attr_perm_check (tGATT_SVC_DB *p_db, UINT8 op_code, UINT16 handle, UINT16 offset, UINT8 *p_data, - UINT16 len, tGATT_SEC_FLAG sec_flag, UINT8 key_size); -extern tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB *p_db, BOOLEAN is_long, UINT16 handle, tGATT_SEC_FLAG sec_flag, UINT8 key_size); -extern void gatts_update_srv_list_elem(UINT8 i_sreg, UINT16 handle, BOOLEAN is_primary); -extern tBT_UUID *gatts_get_service_uuid (tGATT_SVC_DB *p_db); - -extern void gatt_reset_bgdev_list(void); -extern uint16_t gatt_get_local_mtu(void); -extern void gatt_set_local_mtu(uint16_t mtu); -#endif diff --git a/tools/sdk/include/bluedroid/gattdefs.h b/tools/sdk/include/bluedroid/gattdefs.h deleted file mode 100644 index 9380e2e9c69..00000000000 --- a/tools/sdk/include/bluedroid/gattdefs.h +++ /dev/null @@ -1,124 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains internally used ATT definitions - * - ******************************************************************************/ - -#ifndef _GATTDEFS_H -#define _GATTDEFS_H - -#define GATT_ILLEGAL_UUID 0 - -/* GATT attribute types -*/ -#define GATT_UUID_PRI_SERVICE 0x2800 -#define GATT_UUID_SEC_SERVICE 0x2801 -#define GATT_UUID_INCLUDE_SERVICE 0x2802 -#define GATT_UUID_CHAR_DECLARE 0x2803 /* Characteristic Declaration*/ - -#define GATT_UUID_CHAR_EXT_PROP 0x2900 /* Characteristic Extended Properties */ -#define GATT_UUID_CHAR_DESCRIPTION 0x2901 /* Characteristic User Description*/ -#define GATT_UUID_CHAR_CLIENT_CONFIG 0x2902 /* Client Characteristic Configuration */ -#define GATT_UUID_CHAR_SRVR_CONFIG 0x2903 /* Server Characteristic Configuration */ -#define GATT_UUID_CHAR_PRESENT_FORMAT 0x2904 /* Characteristic Presentation Format*/ -#define GATT_UUID_CHAR_AGG_FORMAT 0x2905 /* Characteristic Aggregate Format*/ -#define GATT_UUID_CHAR_VALID_RANGE 0x2906 /* Characteristic Valid Range */ -#define GATT_UUID_EXT_RPT_REF_DESCR 0x2907 -#define GATT_UUID_RPT_REF_DESCR 0x2908 - - -/* GAP Profile Attributes -*/ -#define GATT_UUID_GAP_DEVICE_NAME 0x2A00 -#define GATT_UUID_GAP_ICON 0x2A01 -#define GATT_UUID_GAP_PREF_CONN_PARAM 0x2A04 -#define GATT_UUID_GAP_CENTRAL_ADDR_RESOL 0x2AA6 - -/* Attribute Profile Attribute UUID */ -#define GATT_UUID_GATT_SRV_CHGD 0x2A05 -/* Attribute Protocol Test */ - -/* Link Loss Service */ -#define GATT_UUID_ALERT_LEVEL 0x2A06 /* Alert Level */ -#define GATT_UUID_TX_POWER_LEVEL 0x2A07 /* TX power level */ - -/* Time Profile */ -/* Current Time Service */ -#define GATT_UUID_CURRENT_TIME 0x2A2B /* Current Time */ -#define GATT_UUID_LOCAL_TIME_INFO 0x2A0F /* Local time info */ -#define GATT_UUID_REF_TIME_INFO 0x2A14 /* reference time information */ - -/* NwA Profile */ -#define GATT_UUID_NW_STATUS 0x2A18 /* network availability status */ -#define GATT_UUID_NW_TRIGGER 0x2A1A /* Network availability trigger */ - -/* phone alert */ -#define GATT_UUID_ALERT_STATUS 0x2A3F /* alert status */ -#define GATT_UUID_RINGER_CP 0x2A40 /* ringer control point */ -#define GATT_UUID_RINGER_SETTING 0x2A41 /* ringer setting */ - -/* Glucose Service */ -#define GATT_UUID_GM_MEASUREMENT 0x2A18 -#define GATT_UUID_GM_CONTEXT 0x2A34 -#define GATT_UUID_GM_CONTROL_POINT 0x2A52 -#define GATT_UUID_GM_FEATURE 0x2A51 - -/* device infor characteristic */ -#define GATT_UUID_SYSTEM_ID 0x2A23 -#define GATT_UUID_MODEL_NUMBER_STR 0x2A24 -#define GATT_UUID_SERIAL_NUMBER_STR 0x2A25 -#define GATT_UUID_FW_VERSION_STR 0x2A26 -#define GATT_UUID_HW_VERSION_STR 0x2A27 -#define GATT_UUID_SW_VERSION_STR 0x2A28 -#define GATT_UUID_MANU_NAME 0x2A29 -#define GATT_UUID_IEEE_DATA 0x2A2A -#define GATT_UUID_PNP_ID 0x2A50 - -/* HID characteristics */ -#define GATT_UUID_HID_INFORMATION 0x2A4A -#define GATT_UUID_HID_REPORT_MAP 0x2A4B -#define GATT_UUID_HID_CONTROL_POINT 0x2A4C -#define GATT_UUID_HID_REPORT 0x2A4D -#define GATT_UUID_HID_PROTO_MODE 0x2A4E -#define GATT_UUID_HID_BT_KB_INPUT 0x2A22 -#define GATT_UUID_HID_BT_KB_OUTPUT 0x2A32 -#define GATT_UUID_HID_BT_MOUSE_INPUT 0x2A33 - -/* Battery Service char */ -#define GATT_UUID_BATTERY_LEVEL 0x2A19 - -#define GATT_UUID_SC_CONTROL_POINT 0x2A55 -#define GATT_UUID_SENSOR_LOCATION 0x2A5D - -/* RUNNERS SPEED AND CADENCE SERVICE */ -#define GATT_UUID_RSC_MEASUREMENT 0x2A53 -#define GATT_UUID_RSC_FEATURE 0x2A54 - -/* CYCLING SPEED AND CADENCE SERVICE */ -#define GATT_UUID_CSC_MEASUREMENT 0x2A5B -#define GATT_UUID_CSC_FEATURE 0x2A5C - - -/* Scan Parameter charatceristics */ -#define GATT_UUID_SCAN_INT_WINDOW 0x2A4F -#define GATT_UUID_SCAN_REFRESH 0x2A31 - -#endif diff --git a/tools/sdk/include/bluedroid/hash_functions.h b/tools/sdk/include/bluedroid/hash_functions.h deleted file mode 100644 index 2edbeb8b74a..00000000000 --- a/tools/sdk/include/bluedroid/hash_functions.h +++ /dev/null @@ -1,33 +0,0 @@ -/****************************************************************************** - * - * 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 "hash_map.h" - -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); - -#endif /* _HASH_FUNCTIONS_H_ */ diff --git a/tools/sdk/include/bluedroid/hash_map.h b/tools/sdk/include/bluedroid/hash_map.h deleted file mode 100644 index fea1e0212c5..00000000000 --- a/tools/sdk/include/bluedroid/hash_map.h +++ /dev/null @@ -1,110 +0,0 @@ -/****************************************************************************** - * - * 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/include/bluedroid/hci_hal.h b/tools/sdk/include/bluedroid/hci_hal.h deleted file mode 100644 index 9853211df46..00000000000 --- a/tools/sdk/include/bluedroid/hci_hal.h +++ /dev/null @@ -1,85 +0,0 @@ -/****************************************************************************** - * - * 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 _HCI_HAL_H_ -#define _HCI_HAL_H_ - -#include -#include - -#include "bt_types.h" - -typedef enum { - DATA_TYPE_COMMAND = 1, - DATA_TYPE_ACL = 2, - DATA_TYPE_SCO = 3, - DATA_TYPE_EVENT = 4 -} serial_data_type_t; - -typedef void (*packet_ready_cb)(BT_HDR *packet); - -typedef struct { - // Called when the HAL detects inbound data. - // Data |type| may be ACL, SCO, or EVENT. - // Executes in the context of the thread supplied to |init|. - packet_ready_cb packet_ready; - - /* - // Called when the HAL detects inbound astronauts named Dave. - // HAL will deny all requests to open the pod bay doors after this. - dave_ready_cb dave_ready; - */ -} hci_hal_callbacks_t; - -typedef struct hci_hal_t { - // Initialize the HAL, with |upper_callbacks| and |upper_thread| to run in the context of. - //bool (*init)(const hci_hal_callbacks_t *upper_callbacks); - - // Connect to the underlying hardware, and let data start flowing. - bool (*open)(const hci_hal_callbacks_t *upper_callbacks); - // Disconnect from the underlying hardware, and close the HAL. - // "Daisy, Daisy..." - void (*close)(void); - - // Retrieve up to |max_size| bytes for ACL, SCO, or EVENT data packets into - // |buffer|, blocking until max_size bytes read if |block| is true. - // Only guaranteed to be correct in the context of a data_ready callback - // of the corresponding type. - //size_t (*read_data)(serial_data_type_t type, uint8_t *buffer, size_t max_size); - // The upper layer must call this to notify the HAL that it has finished - // reading a packet of the specified |type|. Underlying implementations that - // use shared channels for multiple data types depend on this to know when - // to reinterpret the data stream. - //void (*packet_finished)(serial_data_type_t type); - // Transmit COMMAND, ACL, or SCO data packets. - // |data| may not be NULL. |length| must be greater than zero. - // - // IMPORTANT NOTE: - // Depending on the underlying implementation, the byte right - // before the beginning of |data| may be borrowed during this call - // and then restored to its original value. - // This is safe in the bluetooth context, because there is always a buffer - // header that prefixes data you're sending. - uint16_t (*transmit_data)(serial_data_type_t type, uint8_t *data, uint16_t length); -} hci_hal_t; - - -// Gets the correct hal implementation, as compiled for. -const hci_hal_t *hci_hal_h4_get_interface(void); - -#endif /* _HCI_HAL_H */ diff --git a/tools/sdk/include/bluedroid/hci_internals.h b/tools/sdk/include/bluedroid/hci_internals.h deleted file mode 100644 index 41c792cf3cb..00000000000 --- a/tools/sdk/include/bluedroid/hci_internals.h +++ /dev/null @@ -1,31 +0,0 @@ -/****************************************************************************** - * - * 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 _HCI_INTERNALS_H_ -#define _HCI_INTERNALS_H_ - -// 2 bytes for opcode, 1 byte for parameter length (Volume 2, Part E, 5.4.1) -#define HCI_COMMAND_PREAMBLE_SIZE 3 -// 2 bytes for handle, 2 bytes for data length (Volume 2, Part E, 5.4.2) -#define HCI_ACL_PREAMBLE_SIZE 4 -// 2 bytes for handle, 1 byte for data length (Volume 2, Part E, 5.4.3) -#define HCI_SCO_PREAMBLE_SIZE 3 -// 1 byte for event code, 1 byte for parameter length (Volume 2, Part E, 5.4.4) -#define HCI_EVENT_PREAMBLE_SIZE 2 - -#endif /* _HCI_INTERNALS_H_ */ diff --git a/tools/sdk/include/bluedroid/hci_layer.h b/tools/sdk/include/bluedroid/hci_layer.h deleted file mode 100644 index 5e9b8c695b5..00000000000 --- a/tools/sdk/include/bluedroid/hci_layer.h +++ /dev/null @@ -1,99 +0,0 @@ -/****************************************************************************** - * - * 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 _HCI_LAYER_H_ -#define _HCI_LAYER_H_ - -#include "bt_types.h" -#include "allocator.h" -#include "osi.h" -#include "future.h" -///// LEGACY DEFINITIONS ///// - -/* Message event mask across Host/Controller lib and stack */ -#define MSG_EVT_MASK 0xFF00 /* eq. BT_EVT_MASK */ -#define MSG_SUB_EVT_MASK 0x00FF /* eq. BT_SUB_EVT_MASK */ - -/* Message event ID passed from Host/Controller lib to stack */ -#define MSG_HC_TO_STACK_HCI_ERR 0x1300 /* eq. BT_EVT_TO_BTU_HCIT_ERR */ -#define MSG_HC_TO_STACK_HCI_ACL 0x1100 /* eq. BT_EVT_TO_BTU_HCI_ACL */ -#define MSG_HC_TO_STACK_HCI_SCO 0x1200 /* eq. BT_EVT_TO_BTU_HCI_SCO */ -#define MSG_HC_TO_STACK_HCI_EVT 0x1000 /* eq. BT_EVT_TO_BTU_HCI_EVT */ -#define MSG_HC_TO_STACK_L2C_SEG_XMIT 0x1900 /* eq. BT_EVT_TO_BTU_L2C_SEG_XMIT */ - -/* Message event ID passed from stack to vendor lib */ -#define MSG_STACK_TO_HC_HCI_ACL 0x2100 /* eq. BT_EVT_TO_LM_HCI_ACL */ -#define MSG_STACK_TO_HC_HCI_SCO 0x2200 /* eq. BT_EVT_TO_LM_HCI_SCO */ -#define MSG_STACK_TO_HC_HCI_CMD 0x2000 /* eq. BT_EVT_TO_LM_HCI_CMD */ - -/* Local Bluetooth Controller ID for BR/EDR */ -#define LOCAL_BR_EDR_CONTROLLER_ID 0 - -///// END LEGACY DEFINITIONS ///// - -typedef struct hci_hal_t hci_hal_t; -//typedef struct btsnoop_t btsnoop_t; -typedef struct controller_t controller_t; -//typedef struct hci_inject_t hci_inject_t; -typedef struct packet_fragmenter_t packet_fragmenter_t; -//typedef struct vendor_t vendor_t; -//typedef struct low_power_manager_t low_power_manager_t; - -//typedef unsigned char * bdaddr_t; -typedef uint16_t command_opcode_t; - -/* -typedef enum { - LPM_DISABLE, - LPM_ENABLE, - LPM_WAKE_ASSERT, - LPM_WAKE_DEASSERT -} low_power_command_t; -*/ - -typedef void (*command_complete_cb)(BT_HDR *response, void *context); -typedef void (*command_status_cb)(uint8_t status, BT_HDR *command, void *context); - -typedef struct hci_t { - // Send a low power command, if supported and the low power manager is enabled. - //void (*send_low_power_command)(low_power_command_t command); - - // Do the postload sequence (call after the rest of the BT stack initializes). - void (*do_postload)(void); - - // Send a command through the HCI layer - void (*transmit_command)( - BT_HDR *command, - command_complete_cb complete_callback, - command_status_cb status_cb, - void *context - ); - - future_t *(*transmit_command_futured)(BT_HDR *command); - - // Send some data downward through the HCI layer - void (*transmit_downward)(uint16_t type, void *data); -} hci_t; - -const hci_t *hci_layer_get_interface(); - -int hci_start_up(void); -void hci_shut_down(void); - - -#endif /* _HCI_LAYER_H_ */ diff --git a/tools/sdk/include/bluedroid/hci_packet_factory.h b/tools/sdk/include/bluedroid/hci_packet_factory.h deleted file mode 100644 index 11f0053a583..00000000000 --- a/tools/sdk/include/bluedroid/hci_packet_factory.h +++ /dev/null @@ -1,49 +0,0 @@ -/****************************************************************************** - * - * 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 _HCI_PACKET_FACTORY_H_ -#define _HCI_PACKET_FACTORY_H_ - -#include "bt_types.h" -#include "event_mask.h" - -typedef struct { - BT_HDR *(*make_reset)(void); - BT_HDR *(*make_read_buffer_size)(void); - BT_HDR *(*make_host_buffer_size)(uint16_t acl_size, uint8_t sco_size, uint16_t acl_count, uint16_t sco_count); - BT_HDR *(*make_read_local_version_info)(void); - BT_HDR *(*make_read_bd_addr)(void); - BT_HDR *(*make_read_local_supported_commands)(void); - BT_HDR *(*make_read_local_extended_features)(uint8_t page_number); - BT_HDR *(*make_write_simple_pairing_mode)(uint8_t mode); - BT_HDR *(*make_write_secure_connections_host_support)(uint8_t mode); - BT_HDR *(*make_set_event_mask)(const bt_event_mask_t *event_mask); - BT_HDR *(*make_ble_write_host_support)(uint8_t supported_host, uint8_t simultaneous_host); - BT_HDR *(*make_ble_read_white_list_size)(void); - BT_HDR *(*make_ble_read_buffer_size)(void); - BT_HDR *(*make_ble_read_supported_states)(void); - BT_HDR *(*make_ble_read_local_supported_features)(void); - BT_HDR *(*make_ble_read_resolving_list_size)(void); - BT_HDR *(*make_ble_read_suggested_default_data_length)(void); - BT_HDR *(*make_ble_write_suggested_default_data_length)(uint16_t SuggestedMaxTxOctets, uint16_t SuggestedMaxTxTime); - BT_HDR *(*make_ble_set_event_mask)(const bt_event_mask_t *event_mask); -} hci_packet_factory_t; - -const hci_packet_factory_t *hci_packet_factory_get_interface(); - -#endif /*_HCI_PACKET_FACTORY_H_*/ diff --git a/tools/sdk/include/bluedroid/hci_packet_parser.h b/tools/sdk/include/bluedroid/hci_packet_parser.h deleted file mode 100644 index 7090708f0d0..00000000000 --- a/tools/sdk/include/bluedroid/hci_packet_parser.h +++ /dev/null @@ -1,100 +0,0 @@ -/****************************************************************************** - * - * 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 _HCI_PACKET_PARSER_H_ -#define _HCI_PACKET_PARSER_H_ - -#include - -#include "allocator.h" -#include "bdaddr.h" -#include "bt_types.h" -#include "device_features.h" -//#include "features.h" -#include "version.h" - -typedef struct { - void (*parse_generic_command_complete)(BT_HDR *response); - - void (*parse_read_buffer_size_response)( - BT_HDR *response, - uint16_t *data_size_ptr, - uint16_t *acl_buffer_count_ptr - ); - - void (*parse_read_local_version_info_response)( - BT_HDR *response, - bt_version_t *bt_version_ptr - ); - - void (*parse_read_bd_addr_response)( - BT_HDR *response, - bt_bdaddr_t *address_ptr - ); - - void (*parse_read_local_supported_commands_response)( - BT_HDR *response, - uint8_t *supported_commands_ptr, - size_t supported_commands_length - ); - - void (*parse_read_local_extended_features_response)( - BT_HDR *response, - uint8_t *page_number_ptr, - uint8_t *max_page_number_ptr, - bt_device_features_t *feature_pages, - size_t feature_pages_count - ); - - void (*parse_ble_read_white_list_size_response)( - BT_HDR *response, - uint8_t *white_list_size_ptr - ); - - void (*parse_ble_read_buffer_size_response)( - BT_HDR *response, - uint16_t *data_size_ptr, - uint8_t *acl_buffer_count_ptr - ); - - void (*parse_ble_read_supported_states_response)( - BT_HDR *response, - uint8_t *supported_states, - size_t supported_states_size - ); - - void (*parse_ble_read_local_supported_features_response)( - BT_HDR *response, - bt_device_features_t *supported_features - ); - - void (*parse_ble_read_resolving_list_size_response) ( - BT_HDR *response, - uint8_t *resolving_list_size_ptr - ); - - void (*parse_ble_read_suggested_default_data_length_response)( - BT_HDR *response, - uint16_t *ble_default_packet_length_ptr, - uint16_t *ble_default_packet_txtime_ptr - ); -} hci_packet_parser_t; - -const hci_packet_parser_t *hci_packet_parser_get_interface(); - -#endif /*_HCI_PACKET_PARSER_H_*/ diff --git a/tools/sdk/include/bluedroid/hcidefs.h b/tools/sdk/include/bluedroid/hcidefs.h deleted file mode 100644 index 44fff2e5213..00000000000 --- a/tools/sdk/include/bluedroid/hcidefs.h +++ /dev/null @@ -1,2609 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2014 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 HCIDEFS_H -#define HCIDEFS_H - -#include "bt_target.h" - -#include "bt_types.h" - -#define HCI_PROTO_VERSION 0x01 /* Version for BT spec 1.1 */ -#define HCI_PROTO_VERSION_1_2 0x02 /* Version for BT spec 1.2 */ -#define HCI_PROTO_VERSION_2_0 0x03 /* Version for BT spec 2.0 */ -#define HCI_PROTO_VERSION_2_1 0x04 /* Version for BT spec 2.1 [Lisbon] */ -#define HCI_PROTO_VERSION_3_0 0x05 /* Version for BT spec 3.0 */ -#define HCI_PROTO_VERSION_4_0 0x06 /* Version for BT spec 4.0 */ -#define HCI_PROTO_VERSION_4_1 0x07 /* Version for BT spec 4.1 */ -#define HCI_PROTO_VERSION_4_2 0x08 /* Version for BT spec 4.2 */ -#define HCI_PROTO_REVISION 0x000C /* Current implementation version */ -/* -** Definitions for HCI groups -*/ -#define HCI_GRP_LINK_CONTROL_CMDS (0x01 << 10) /* 0x0400 */ -#define HCI_GRP_LINK_POLICY_CMDS (0x02 << 10) /* 0x0800 */ -#define HCI_GRP_HOST_CONT_BASEBAND_CMDS (0x03 << 10) /* 0x0C00 */ -#define HCI_GRP_INFORMATIONAL_PARAMS (0x04 << 10) /* 0x1000 */ -#define HCI_GRP_STATUS_PARAMS (0x05 << 10) /* 0x1400 */ -#define HCI_GRP_TESTING_CMDS (0x06 << 10) /* 0x1800 */ - -#define HCI_GRP_VENDOR_SPECIFIC (0x3F << 10) /* 0xFC00 */ - -/* Group occupies high 6 bits of the HCI command rest is opcode itself */ -#define HCI_OGF(p) (UINT8)((0xFC00 & (p)) >> 10) -#define HCI_OCF(p) ( 0x3FF & (p)) - -/* -** Definitions for Link Control Commands -*/ -/* Following opcode is used only in command complete event for flow control */ -#define HCI_COMMAND_NONE 0x0000 - -/* Commands of HCI_GRP_LINK_CONTROL_CMDS group */ -#define HCI_INQUIRY (0x0001 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_INQUIRY_CANCEL (0x0002 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_PERIODIC_INQUIRY_MODE (0x0003 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_EXIT_PERIODIC_INQUIRY_MODE (0x0004 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_CREATE_CONNECTION (0x0005 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_DISCONNECT (0x0006 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_ADD_SCO_CONNECTION (0x0007 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_CREATE_CONNECTION_CANCEL (0x0008 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_ACCEPT_CONNECTION_REQUEST (0x0009 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_REJECT_CONNECTION_REQUEST (0x000A | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_LINK_KEY_REQUEST_REPLY (0x000B | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_LINK_KEY_REQUEST_NEG_REPLY (0x000C | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_PIN_CODE_REQUEST_REPLY (0x000D | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_PIN_CODE_REQUEST_NEG_REPLY (0x000E | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_CHANGE_CONN_PACKET_TYPE (0x000F | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_AUTHENTICATION_REQUESTED (0x0011 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_SET_CONN_ENCRYPTION (0x0013 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_CHANGE_CONN_LINK_KEY (0x0015 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_MASTER_LINK_KEY (0x0017 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_RMT_NAME_REQUEST (0x0019 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_RMT_NAME_REQUEST_CANCEL (0x001A | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_READ_RMT_FEATURES (0x001B | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_READ_RMT_EXT_FEATURES (0x001C | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_READ_RMT_VERSION_INFO (0x001D | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_READ_RMT_CLOCK_OFFSET (0x001F | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_READ_LMP_HANDLE (0x0020 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_SETUP_ESCO_CONNECTION (0x0028 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_ACCEPT_ESCO_CONNECTION (0x0029 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_REJECT_ESCO_CONNECTION (0x002A | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_IO_CAPABILITY_REQUEST_REPLY (0x002B | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_USER_CONF_REQUEST_REPLY (0x002C | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_USER_CONF_VALUE_NEG_REPLY (0x002D | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_USER_PASSKEY_REQ_REPLY (0x002E | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_USER_PASSKEY_REQ_NEG_REPLY (0x002F | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_REM_OOB_DATA_REQ_REPLY (0x0030 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_REM_OOB_DATA_REQ_NEG_REPLY (0x0033 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_IO_CAP_REQ_NEG_REPLY (0x0034 | HCI_GRP_LINK_CONTROL_CMDS) - -/* AMP HCI */ -#define HCI_CREATE_PHYSICAL_LINK (0x0035 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_ACCEPT_PHYSICAL_LINK (0x0036 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_DISCONNECT_PHYSICAL_LINK (0x0037 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_CREATE_LOGICAL_LINK (0x0038 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_ACCEPT_LOGICAL_LINK (0x0039 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_DISCONNECT_LOGICAL_LINK (0x003A | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_LOGICAL_LINK_CANCEL (0x003B | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_FLOW_SPEC_MODIFY (0x003C | HCI_GRP_LINK_CONTROL_CMDS) - -#define HCI_ENH_SETUP_ESCO_CONNECTION (0x003D | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_ENH_ACCEPT_ESCO_CONNECTION (0x003E | HCI_GRP_LINK_CONTROL_CMDS) - -/* ConnectionLess Broadcast */ -#define HCI_TRUNCATED_PAGE (0x003F | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_TRUNCATED_PAGE_CANCEL (0x0040 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_SET_CLB (0x0041 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_RECEIVE_CLB (0x0042 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_START_SYNC_TRAIN (0x0043 | HCI_GRP_LINK_CONTROL_CMDS) -#define HCI_RECEIVE_SYNC_TRAIN (0x0044 | HCI_GRP_LINK_CONTROL_CMDS) - -#define HCI_LINK_CTRL_CMDS_FIRST HCI_INQUIRY -#define HCI_LINK_CTRL_CMDS_LAST HCI_RECEIVE_SYNC_TRAIN - -/* Commands of HCI_GRP_LINK_POLICY_CMDS */ -#define HCI_HOLD_MODE (0x0001 | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_SNIFF_MODE (0x0003 | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_EXIT_SNIFF_MODE (0x0004 | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_PARK_MODE (0x0005 | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_EXIT_PARK_MODE (0x0006 | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_QOS_SETUP (0x0007 | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_ROLE_DISCOVERY (0x0009 | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_SWITCH_ROLE (0x000B | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_READ_POLICY_SETTINGS (0x000C | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_WRITE_POLICY_SETTINGS (0x000D | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_READ_DEF_POLICY_SETTINGS (0x000E | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_WRITE_DEF_POLICY_SETTINGS (0x000F | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_FLOW_SPECIFICATION (0x0010 | HCI_GRP_LINK_POLICY_CMDS) -#define HCI_SNIFF_SUB_RATE (0x0011 | HCI_GRP_LINK_POLICY_CMDS) - -#define HCI_LINK_POLICY_CMDS_FIRST HCI_HOLD_MODE -#define HCI_LINK_POLICY_CMDS_LAST HCI_SNIFF_SUB_RATE - - -/* Commands of HCI_GRP_HOST_CONT_BASEBAND_CMDS */ -#define HCI_SET_EVENT_MASK (0x0001 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_RESET (0x0003 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_EVENT_FILTER (0x0005 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_FLUSH (0x0008 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_PIN_TYPE (0x0009 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_PIN_TYPE (0x000A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_CREATE_NEW_UNIT_KEY (0x000B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_GET_MWS_TRANS_LAYER_CFG (0x000C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_STORED_LINK_KEY (0x000D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_STORED_LINK_KEY (0x0011 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_DELETE_STORED_LINK_KEY (0x0012 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_CHANGE_LOCAL_NAME (0x0013 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_LOCAL_NAME (0x0014 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_CONN_ACCEPT_TOUT (0x0015 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_CONN_ACCEPT_TOUT (0x0016 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_PAGE_TOUT (0x0017 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_PAGE_TOUT (0x0018 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_SCAN_ENABLE (0x0019 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_SCAN_ENABLE (0x001A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_PAGESCAN_CFG (0x001B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_PAGESCAN_CFG (0x001C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_INQUIRYSCAN_CFG (0x001D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_INQUIRYSCAN_CFG (0x001E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_AUTHENTICATION_ENABLE (0x001F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_AUTHENTICATION_ENABLE (0x0020 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_ENCRYPTION_MODE (0x0021 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_ENCRYPTION_MODE (0x0022 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_CLASS_OF_DEVICE (0x0023 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_CLASS_OF_DEVICE (0x0024 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_VOICE_SETTINGS (0x0025 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_VOICE_SETTINGS (0x0026 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_AUTO_FLUSH_TOUT (0x0027 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_AUTO_FLUSH_TOUT (0x0028 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_NUM_BCAST_REXMITS (0x0029 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_NUM_BCAST_REXMITS (0x002A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_HOLD_MODE_ACTIVITY (0x002B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_HOLD_MODE_ACTIVITY (0x002C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_TRANSMIT_POWER_LEVEL (0x002D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_SCO_FLOW_CTRL_ENABLE (0x002E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_SCO_FLOW_CTRL_ENABLE (0x002F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_HC_TO_HOST_FLOW_CTRL (0x0031 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_HOST_BUFFER_SIZE (0x0033 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_HOST_NUM_PACKETS_DONE (0x0035 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_LINK_SUPER_TOUT (0x0036 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_LINK_SUPER_TOUT (0x0037 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_NUM_SUPPORTED_IAC (0x0038 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_CURRENT_IAC_LAP (0x0039 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_CURRENT_IAC_LAP (0x003A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_PAGESCAN_PERIOD_MODE (0x003B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_PAGESCAN_PERIOD_MODE (0x003C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_PAGESCAN_MODE (0x003D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_PAGESCAN_MODE (0x003E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_AFH_CHANNELS (0x003F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) - -#define HCI_READ_INQSCAN_TYPE (0x0042 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_INQSCAN_TYPE (0x0043 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_INQUIRY_MODE (0x0044 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_INQUIRY_MODE (0x0045 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_PAGESCAN_TYPE (0x0046 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_PAGESCAN_TYPE (0x0047 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_AFH_ASSESSMENT_MODE (0x0048 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_AFH_ASSESSMENT_MODE (0x0049 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_EXT_INQ_RESPONSE (0x0051 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_EXT_INQ_RESPONSE (0x0052 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_REFRESH_ENCRYPTION_KEY (0x0053 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_SIMPLE_PAIRING_MODE (0x0055 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_SIMPLE_PAIRING_MODE (0x0056 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_LOCAL_OOB_DATA (0x0057 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_INQ_TX_POWER_LEVEL (0x0058 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_INQ_TX_POWER_LEVEL (0x0059 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_ERRONEOUS_DATA_RPT (0x005A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_ERRONEOUS_DATA_RPT (0x005B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_ENHANCED_FLUSH (0x005F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SEND_KEYPRESS_NOTIF (0x0060 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) - - -/* AMP HCI */ -#define HCI_READ_LOGICAL_LINK_ACCEPT_TIMEOUT (0x0061 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT (0x0062 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_EVENT_MASK_PAGE_2 (0x0063 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_LOCATION_DATA (0x0064 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_LOCATION_DATA (0x0065 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_FLOW_CONTROL_MODE (0x0066 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_FLOW_CONTROL_MODE (0x0067 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_BE_FLUSH_TOUT (0x0069 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_BE_FLUSH_TOUT (0x006A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SHORT_RANGE_MODE (0x006B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) /* 802.11 only */ -#define HCI_READ_LE_HOST_SUPPORT (0x006C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_LE_HOST_SUPPORT (0x006D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) - - -/* MWS coexistence */ -#define HCI_SET_MWS_CHANNEL_PARAMETERS (0x006E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_EXTERNAL_FRAME_CONFIGURATION (0x006F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_MWS_SIGNALING (0x0070 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_MWS_TRANSPORT_LAYER (0x0071 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_MWS_SCAN_FREQUENCY_TABLE (0x0072 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_MWS_PATTERN_CONFIGURATION (0x0073 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) - -/* Connectionless Broadcast */ -#define HCI_SET_RESERVED_LT_ADDR (0x0074 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_DELETE_RESERVED_LT_ADDR (0x0075 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_CLB_DATA (0x0076 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_SYNC_TRAIN_PARAM (0x0077 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_SYNC_TRAIN_PARAM (0x0078 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) - -#define HCI_READ_SECURE_CONNS_SUPPORT (0x0079 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_SECURE_CONNS_SUPPORT (0x007A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_CONT_BASEBAND_CMDS_FIRST HCI_SET_EVENT_MASK -#define HCI_CONT_BASEBAND_CMDS_LAST HCI_READ_SYNC_TRAIN_PARAM - - -/* Commands of HCI_GRP_INFORMATIONAL_PARAMS group */ -#define HCI_READ_LOCAL_VERSION_INFO (0x0001 | HCI_GRP_INFORMATIONAL_PARAMS) -#define HCI_READ_LOCAL_SUPPORTED_CMDS (0x0002 | HCI_GRP_INFORMATIONAL_PARAMS) -#define HCI_READ_LOCAL_FEATURES (0x0003 | HCI_GRP_INFORMATIONAL_PARAMS) -#define HCI_READ_LOCAL_EXT_FEATURES (0x0004 | HCI_GRP_INFORMATIONAL_PARAMS) -#define HCI_READ_BUFFER_SIZE (0x0005 | HCI_GRP_INFORMATIONAL_PARAMS) -#define HCI_READ_COUNTRY_CODE (0x0007 | HCI_GRP_INFORMATIONAL_PARAMS) -#define HCI_READ_BD_ADDR (0x0009 | HCI_GRP_INFORMATIONAL_PARAMS) -#define HCI_READ_DATA_BLOCK_SIZE (0x000A | HCI_GRP_INFORMATIONAL_PARAMS) -#define HCI_READ_LOCAL_SUPPORTED_CODECS (0x000B | HCI_GRP_INFORMATIONAL_PARAMS) - -#define HCI_INFORMATIONAL_CMDS_FIRST HCI_READ_LOCAL_VERSION_INFO -#define HCI_INFORMATIONAL_CMDS_LAST HCI_READ_LOCAL_SUPPORTED_CODECS - - -/* Commands of HCI_GRP_STATUS_PARAMS group */ -#define HCI_READ_FAILED_CONTACT_COUNT (0x0001 | HCI_GRP_STATUS_PARAMS) -#define HCI_RESET_FAILED_CONTACT_COUNT (0x0002 | HCI_GRP_STATUS_PARAMS) -#define HCI_GET_LINK_QUALITY (0x0003 | HCI_GRP_STATUS_PARAMS) -#define HCI_READ_RSSI (0x0005 | HCI_GRP_STATUS_PARAMS) -#define HCI_READ_AFH_CH_MAP (0x0006 | HCI_GRP_STATUS_PARAMS) -#define HCI_READ_CLOCK (0x0007 | HCI_GRP_STATUS_PARAMS) -#define HCI_READ_ENCR_KEY_SIZE (0x0008 | HCI_GRP_STATUS_PARAMS) - -/* AMP HCI */ -#define HCI_READ_LOCAL_AMP_INFO (0x0009 | HCI_GRP_STATUS_PARAMS) -#define HCI_READ_LOCAL_AMP_ASSOC (0x000A | HCI_GRP_STATUS_PARAMS) -#define HCI_WRITE_REMOTE_AMP_ASSOC (0x000B | HCI_GRP_STATUS_PARAMS) - -#define HCI_STATUS_PARAMS_CMDS_FIRST HCI_READ_FAILED_CONTACT_COUNT -#define HCI_STATUS_PARAMS_CMDS_LAST HCI_WRITE_REMOTE_AMP_ASSOC - -/* Commands of HCI_GRP_TESTING_CMDS group */ -#define HCI_READ_LOOPBACK_MODE (0x0001 | HCI_GRP_TESTING_CMDS) -#define HCI_WRITE_LOOPBACK_MODE (0x0002 | HCI_GRP_TESTING_CMDS) -#define HCI_ENABLE_DEV_UNDER_TEST_MODE (0x0003 | HCI_GRP_TESTING_CMDS) -#define HCI_WRITE_SIMP_PAIR_DEBUG_MODE (0x0004 | HCI_GRP_TESTING_CMDS) - -/* AMP HCI */ -#define HCI_ENABLE_AMP_RCVR_REPORTS (0x0007 | HCI_GRP_TESTING_CMDS) -#define HCI_AMP_TEST_END (0x0008 | HCI_GRP_TESTING_CMDS) -#define HCI_AMP_TEST (0x0009 | HCI_GRP_TESTING_CMDS) - -#define HCI_TESTING_CMDS_FIRST HCI_READ_LOOPBACK_MODE -#define HCI_TESTING_CMDS_LAST HCI_AMP_TEST - -#define HCI_VENDOR_CMDS_FIRST 0x0001 -#define HCI_VENDOR_CMDS_LAST 0xFFFF -#define HCI_VSC_MULTI_AV_HANDLE 0x0AAA -#define HCI_VSC_BURST_MODE_HANDLE 0x0BBB - -/* BLE HCI */ -#define HCI_GRP_BLE_CMDS (0x08 << 10) -/* Commands of BLE Controller setup and configuration */ -#define HCI_BLE_SET_EVENT_MASK (0x0001 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_BUFFER_SIZE (0x0002 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_LOCAL_SPT_FEAT (0x0003 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_LOCAL_SPT_FEAT (0x0004 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_RANDOM_ADDR (0x0005 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_ADV_PARAMS (0x0006 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_ADV_CHNL_TX_POWER (0x0007 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_ADV_DATA (0x0008 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_SCAN_RSP_DATA (0x0009 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_ADV_ENABLE (0x000A | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_SCAN_PARAMS (0x000B | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_SCAN_ENABLE (0x000C | HCI_GRP_BLE_CMDS) -#define HCI_BLE_CREATE_LL_CONN (0x000D | HCI_GRP_BLE_CMDS) -#define HCI_BLE_CREATE_CONN_CANCEL (0x000E | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_WHITE_LIST_SIZE (0x000F | HCI_GRP_BLE_CMDS) -#define HCI_BLE_CLEAR_WHITE_LIST (0x0010 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_ADD_WHITE_LIST (0x0011 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_REMOVE_WHITE_LIST (0x0012 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_UPD_LL_CONN_PARAMS (0x0013 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_SET_HOST_CHNL_CLASS (0x0014 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_CHNL_MAP (0x0015 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_REMOTE_FEAT (0x0016 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_ENCRYPT (0x0017 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_RAND (0x0018 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_START_ENC (0x0019 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_LTK_REQ_REPLY (0x001A | HCI_GRP_BLE_CMDS) -#define HCI_BLE_LTK_REQ_NEG_REPLY (0x001B | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_SUPPORTED_STATES (0x001C | HCI_GRP_BLE_CMDS) -/*0x001D, 0x001E and 0x001F are reserved*/ -#define HCI_BLE_RECEIVER_TEST (0x001D | HCI_GRP_BLE_CMDS) -#define HCI_BLE_TRANSMITTER_TEST (0x001E | HCI_GRP_BLE_CMDS) -/* BLE TEST COMMANDS */ -#define HCI_BLE_TEST_END (0x001F | HCI_GRP_BLE_CMDS) -#define HCI_BLE_RC_PARAM_REQ_REPLY (0x0020 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_RC_PARAM_REQ_NEG_REPLY (0x0021 | HCI_GRP_BLE_CMDS) - -#define HCI_BLE_SET_DATA_LENGTH (0x0022 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_DEFAULT_DATA_LENGTH (0x0023 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_WRITE_DEFAULT_DATA_LENGTH (0x0024 | HCI_GRP_BLE_CMDS) - -#define HCI_BLE_ADD_DEV_RESOLVING_LIST (0x0027 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_RM_DEV_RESOLVING_LIST (0x0028 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_CLEAR_RESOLVING_LIST (0x0029 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_RESOLVING_LIST_SIZE (0x002A | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_RESOLVABLE_ADDR_PEER (0x002B | HCI_GRP_BLE_CMDS) -#define HCI_BLE_READ_RESOLVABLE_ADDR_LOCAL (0x002C | HCI_GRP_BLE_CMDS) -#define HCI_BLE_SET_ADDR_RESOLUTION_ENABLE (0x002D | HCI_GRP_BLE_CMDS) -#define HCI_BLE_SET_RAND_PRIV_ADDR_TIMOUT (0x002E | HCI_GRP_BLE_CMDS) - -/* LE Get Vendor Capabilities Command OCF */ -#define HCI_BLE_VENDOR_CAP_OCF (0x0153 | HCI_GRP_VENDOR_SPECIFIC) - -/* Multi adv OCF */ -#define HCI_BLE_MULTI_ADV_OCF (0x0154 | HCI_GRP_VENDOR_SPECIFIC) - -/* Batch scan OCF */ -#define HCI_BLE_BATCH_SCAN_OCF (0x0156 | HCI_GRP_VENDOR_SPECIFIC) - -/* ADV filter OCF */ -#define HCI_BLE_ADV_FILTER_OCF (0x0157 | HCI_GRP_VENDOR_SPECIFIC) - -/* Tracking OCF */ -#define HCI_BLE_TRACK_ADV_OCF (0x0158 | HCI_GRP_VENDOR_SPECIFIC) - -/* Energy info OCF */ -#define HCI_BLE_ENERGY_INFO_OCF (0x0159 | HCI_GRP_VENDOR_SPECIFIC) - -/* Extended BLE Scan parameters OCF */ -#define HCI_BLE_EXTENDED_SCAN_PARAMS_OCF (0x0160 | HCI_GRP_VENDOR_SPECIFIC) - -/* subcode for multi adv feature */ -#define BTM_BLE_MULTI_ADV_SET_PARAM 0x01 -#define BTM_BLE_MULTI_ADV_WRITE_ADV_DATA 0x02 -#define BTM_BLE_MULTI_ADV_WRITE_SCAN_RSP_DATA 0x03 -#define BTM_BLE_MULTI_ADV_SET_RANDOM_ADDR 0x04 -#define BTM_BLE_MULTI_ADV_ENB 0x05 - -/* multi adv VSE subcode */ -#define HCI_VSE_SUBCODE_BLE_MULTI_ADV_ST_CHG 0x55 /* multi adv instance state change */ - -/* subcode for batch scan feature */ -#define BTM_BLE_BATCH_SCAN_ENB_DISAB_CUST_FEATURE 0x01 -#define BTM_BLE_BATCH_SCAN_SET_STORAGE_PARAM 0x02 -#define BTM_BLE_BATCH_SCAN_SET_PARAMS 0x03 -#define BTM_BLE_BATCH_SCAN_READ_RESULTS 0x04 - -/* batch scan VSE subcode */ -#define HCI_VSE_SUBCODE_BLE_THRESHOLD_SUB_EVT 0x54 /* Threshold event */ - -/* tracking sub event */ -#define HCI_VSE_SUBCODE_BLE_TRACKING_SUB_EVT 0x56 /* Tracking event */ - -/* LE supported states definition */ -#define HCI_LE_ADV_STATE 0x00000001 -#define HCI_LE_SCAN_STATE 0x00000002 -#define HCI_LE_INIT_STATE 0x00000004 -#define HCI_LE_CONN_SL_STATE 0x00000008 -#define HCI_LE_ADV_SCAN_STATE 0x00000010 -#define HCI_LE_ADV_INIT_STATE 0x00000020 -#define HCI_LE_ADV_MA_STATE 0x00000040 -#define HCI_LE_ADV_SL_STATE 0x00000080 -#define HCI_LE_SCAN_INIT_STATE 0x00000100 -#define HCI_LE_SCAN_MA_STATE 0x00000200 -#define HCI_LE_SCAN_SL_STATE 0x00000400 -#define HCI_LE_INIT_MA_STATE 0x00000800 - -/* LE Supported States */ -/* Non Connectable Adv state is supported. 0x0000000000000001 */ -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_MASK 0x01 -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_OFF 0 -#define HCI_LE_STATES_NON_CONN_ADV_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_NON_CONN_ADV_OFF] & HCI_SUPP_LE_STATES_NON_CONN_ADV_MASK) - -/*Scanneable Connectable Adv state is supported. 0x0000000000000002 */ -#define HCI_SUPP_LE_STATES_SCAN_ADV_MASK 0x02 -#define HCI_SUPP_LE_STATESSCAN_ADV_OFF 0 -#define HCI_LE_STATES_SCAN_ADV_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATESSCAN_ADV_OFF] & HCI_SUPP_LE_STATES_SCAN_ADV_MASK) - -/* Connectable Adv state is supported. 0x0000000000000004 */ -#define HCI_SUPP_LE_STATES_CONN_ADV_MASK 0x04 -#define HCI_SUPP_LE_STATES_CONN_ADV_OFF 0 -#define HCI_LE_STATES_CONN_ADV_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_CONN_ADV_OFF] & HCI_SUPP_LE_STATES_CONN_ADV_MASK) - -/* Hi duty Cycle Directed Adv state is supported. 0x0000000000000008 */ -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_MASK 0x08 -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_OFF 0 -#define HCI_LE_STATES_HI_DUTY_DIR_ADV_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_OFF] & HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_MASK) - -/* Passive Scan state is supported. 0x0000000000000010 */ -#define HCI_SUPP_LE_STATES_PASS_SCAN_MASK 0x10 -#define HCI_SUPP_LE_STATES_PASS_SCAN_OFF 0 -#define HCI_LE_STATES_PASS_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_PASS_SCAN_OFF] & HCI_SUPP_LE_STATES_PASS_SCAN_MASK) - -/* Active Scan state is supported. 0x0000000000000020 */ -#define HCI_SUPP_LE_STATES_ACTIVE_SCAN_MASK 0x20 -#define HCI_SUPP_LE_STATES_ACTIVE_SCAN_OFF 0 -#define HCI_LE_STATES_ACTIVE_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_ACTIVE_SCAN_OFF] & HCI_SUPP_LE_STATES_ACTIVE_SCAN_MASK) - -/* Initiating state is supported. 0x0000000000000040 (or connection state in master role is also supported) */ -#define HCI_SUPP_LE_STATES_INIT_MASK 0x40 -#define HCI_SUPP_LE_STATES_INIT_OFF 0 -#define HCI_LE_STATES_INIT_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_INIT_OFF] & HCI_SUPP_LE_STATES_INIT_MASK) - -/*connection state in slave role is also supported. 0x0000000000000080 */ -#define HCI_SUPP_LE_STATES_SLAVE_MASK 0x80 -#define HCI_SUPP_LE_STATES_SLAVE_OFF 0 -#define HCI_LE_STATES_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_SLAVE_OFF] & HCI_SUPP_LE_STATES_SLAVE_MASK) - -/* Non Connectable Adv state and Passive Scanning State combination is supported. 0x0000000000000100 */ -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_PASS_SCAN_MASK 0x01 -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_PASS_SCAN_OFF 1 -#define HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_NON_CONN_ADV_PASS_SCAN_OFF] & HCI_SUPP_LE_STATES_NON_CONN_ADV_PASS_SCAN_MASK) - -/*Scannable Adv state and Passive Scanning State combination is supported. 0x0000000000000200 */ -#define HCI_SUPP_LE_STATES_SCAN_ADV_PASS_SCAN_MASK 0x02 -#define HCI_SUPP_LE_STATES_SCAN_ADV_PASS_SCAN_OFF 1 -#define HCI_LE_STATES_SCAN_ADV_PASS_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_SCAN_ADV_PASS_SCAN_OFF] & HCI_SUPP_LE_STATES_SCAN_ADV_PASS_SCAN_MASK) - -/*Connectable Adv state and Passive Scanning State combination is supported. 0x0000000000000400 */ -#define HCI_SUPP_LE_STATES_CONN_ADV_PASS_SCAN_MASK 0x04 -#define HCI_SUPP_LE_STATES_CONN_ADV_PASS_SCAN_OFF 1 -#define HCI_LE_STATES_CONN_ADV_PASS_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_CONN_ADV_PASS_SCAN_OFF] & HCI_SUPP_LE_STATES_CONN_ADV_PASS_SCAN_MASK) - -/*High Duty Cycl Directed ADv and Passive Scanning State combination is supported. 0x0000000000000800 */ -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_MASK 0x08 -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_OFF 1 -#define HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_MASK] & HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_OFF) - -/*Non Connectable Adv state and Passive Scanning State combination is supported. 0x0000000000001000 */ -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_MASK 0x10 -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_OFF 1 -#define HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_OFF] & HCI_SUPP_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_MASK) - -/*Scannable Adv state and Active Scanning State combination is supported. 0x0000000000002000 */ -#define HCI_SUPP_LE_STATES_SCAN_ADV_ACTIVE_SCAN_MASK 0x20 -#define HCI_SUPP_LE_STATES_SCAN_ADV_ACTIVE_SCAN_OFF 1 -#define HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_SCAN_ADV_ACTIVE_SCAN_OFF] & HCI_SUPP_LE_STATES_SCAN_ADV_ACTIVE_SCAN_MASK) - -/*Connectable Adv state and Active Scanning State combination is supported. 0x0000000000004000 */ -#define HCI_SUPP_LE_STATES_CONN_ADV_ACTIVE_SCAN_MASK 0x40 -#define HCI_SUPP_LE_STATES_CONN_ADV_ACTIVE_SCAN_OFF 1 -#define HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_CONN_ADV_ACTIVE_SCAN_OFF] & HCI_SUPP_LE_STATES_CONN_ADV_ACTIVE_SCAN_MASK) - -/*High Duty Cycl Directed ADv and ACtive Scanning State combination is supported. 0x0000000000008000 */ -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_MASK 0x80 -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_OFF 1 -#define HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_MASK] & HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_OFF) - -/*Non-Connectable Adv state and Initiating State combination is supported. 0x0000000000010000 */ -#define HCI_SUPP_LE_STATES_NON_CONN_INIT_MASK 0x01 -#define HCI_SUPP_LE_STATES_NON_CONN_INIT_OFF 2 -#define HCI_LE_STATES_NON_CONN_INIT_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_NON_CONN_INIT_OFF] & HCI_SUPP_LE_STATES_NON_CONN_INIT_MASK) - -/* Scannable Adv state and Initiating State combination is supported. 0x0000000000020000 */ -#define HCI_SUPP_LE_STATES_SCAN_ADV_INIT_MASK 0x02 -#define HCI_SUPP_LE_STATES_SCAN_ADV_INIT_OFF 2 -#define HCI_LE_STATES_SCAN_ADV_INIT_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_SCAN_ADV_INIT_OFF] & HCI_SUPP_LE_STATES_SCAN_ADV_INIT_MASK) - -/* Non-Connectable Adv state and Master Role combination is supported. 0x0000000000040000 */ -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_MASTER_MASK 0x04 -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_MASTER_OFF 2 -#define HCI_LE_STATES_NON_CONN_ADV_MASTER_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_NON_CONN_ADV_MASTER_OFF] & HCI_SUPP_LE_STATES_NON_CONN_ADV_MASTER_MASK) - -/*Scannable Adv state and Master Role combination is supported. 0x0000000000040000 */ -#define HCI_SUPP_LE_STATES_SCAN_ADV_MASTER_MASK 0x08 -#define HCI_SUPP_LE_STATES_SCAN_ADV_MASTER_OFF 2 -#define HCI_LE_STATES_SCAN_ADV_MASTER_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_SCAN_ADV_MASTER_OFF] & HCI_SUPP_LE_STATES_SCAN_ADV_MASTER_MASK) - -/* Non-Connectable Adv and Slave Role combination is supported. 0x000000000100000 */ -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_SLAVE_MASK 0x10 -#define HCI_SUPP_LE_STATES_NON_CONN_ADV_SLAVE_OFF 2 -#define HCI_LE_STATES_NON_CONN_ADV_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_NON_CONN_ADV_SLAVE_OFF] & HCI_SUPP_LE_STATES_NON_CONN_ADV_SLAVE_MASK) - -/*Scannable Adv and Slave Role combination is supported. 0x000000000200000 */ -#define HCI_SUPP_LE_STATES_SCAN_ADV_SLAVE_MASK 0x20 -#define HCI_SUPP_LE_STATES_SCAN_ADV_SLAVE_OFF 2 -#define HCI_LE_STATES_SCAN_ADV_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_SCAN_ADV_SLAVE_OFF] & HCI_SUPP_LE_STATES_SCAN_ADV_SLAVE_MASK) - -/*Passive Scan and Initiating State combination is supported. 0x000000000400000 */ -#define HCI_SUPP_LE_STATES_PASS_SCAN_INIT_MASK 0x40 -#define HCI_SUPP_LE_STATES_PASS_SCAN_INIT_OFF 2 -#define HCI_LE_STATES_PASS_SCAN_INIT_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_PASS_SCAN_INIT_OFF] & HCI_SUPP_LE_STATES_PASS_SCAN_INIT_MASK) - -/*Active Scan and Initiating State combination is supported. 0x000000000800000 */ -#define HCI_SUPP_LE_STATES_ACTIVE_SCAN_INIT_MASK 0x80 -#define HCI_SUPP_LE_STATES_ACTIVE_SCAN_INIT_OFF 2 -#define HCI_LE_STATES_ACTIVE_SCAN_INIT_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_ACTIVE_SCAN_INIT_OFF] & HCI_SUPP_LE_STATES_ACTIVE_SCAN_INIT_MASK) - -/*Passive Scan and Master Role combination is supported. 0x000000001000000 */ -#define HCI_SUPP_LE_STATES_PASS_SCAN_MASTER_MASK 0x01 -#define HCI_SUPP_LE_STATES_PASS_SCAN_MASTER_OFF 3 -#define HCI_LE_STATES_PASS_SCAN_MASTER_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_PASS_SCAN_MASTER_OFF] & HCI_SUPP_LE_STATES_PASS_SCAN_MASTER_MASK) - -/*Active Scan and Master Role combination is supported. 0x000000002000000 */ -#define HCI_SUPP_LE_STATES_ACTIVE_SCAN_MASTER_MASK 0x02 -#define HCI_SUPP_LE_STATES_ACTIVE_SCAN_MASTER_OFF 3 -#define HCI_LE_STATES_ACTIVE_SCAN_MASTER_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_ACTIVE_SCAN_MASTER_OFF] & HCI_SUPP_LE_STATES_ACTIVE_SCAN_MASTER_MASK) - -/*Passive Scan and Slave Role combination is supported. 0x000000004000000 */ -#define HCI_SUPP_LE_STATES_PASS_SCAN_SLAVE_MASK 0x04 -#define HCI_SUPP_LE_STATES_PASS_SCAN_SLAVE_OFF 3 -#define HCI_LE_STATES_PASS_SCAN_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_PASS_SCAN_SLAVE_OFF] & HCI_SUPP_LE_STATES_PASS_SCAN_SLAVE_MASK) - -/*Active Scan and Slave Role combination is supported. 0x000000008000000 */ -#define HCI_SUPP_LE_STATES_ACTIVE_SCAN_SLAVE_MASK 0x08 -#define HCI_SUPP_LE_STATES_ACTIVE_SCAN_SLAVE_OFF 3 -#define HCI_LE_STATES_ACTIVE_SCAN_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_ACTIVE_SCAN_SLAVE_OFF] & HCI_SUPP_LE_STATES_ACTIVE_SCAN_SLAVE_MASK) - -/*Link Layer Topology Added States Combo */ -/*Initiating State and Master Role combination supported. - Master Role and Master Role combination is also supported. 0x0000000010000000 */ -#define HCI_SUPP_LE_STATES_INIT_MASTER_MASK 0x10 -#define HCI_SUPP_LE_STATES_INIT_MASTER_OFF 3 -#define HCI_LE_STATES_INIT_MASTER_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_INIT_MASTER_OFF] & HCI_SUPP_LE_STATES_INIT_MASTER_MASK) - -/*Low Duty Cycle Directed Advertising State . 0x0000000020000000 */ -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_MASK 0x20 -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_OFF 3 -#define HCI_LE_STATES_LOW_DUTY_DIR_ADV_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_LOW_DUTY_DIR_ADV_OFF] & HCI_SUPP_LE_STATES_LOW_DUTY_DIR_ADV_MASK) - -/*Low Duty Cycle Directed Advertising State and Passive scan combination. 0x0000000040000000 */ -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_PASS_SCAN_MASK 0x40 -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_PASS_SCAN_OFF 3 -#define HCI_LE_STATES_LO_DUTY_DIR_ADV_PASS_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_PASS_SCAN_OFF] & HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_PASS_SCAN_MASK) - -/*Low Duty Cycle Directed Advertising State and Active scan combination . 0x0000000080000000 */ -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_ACTIVE_SCAN_MASK 0x80 -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_ACTIVE_SCAN_OFF 3 -#define HCI_LE_STATES_LO_DUTY_DIR_ADV_ACTIVE_SCAN_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_ACTIVE_SCAN_OFF] & HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_ACTIVE_SCAN_MASK) - -/* Connectable Advertising State and Initiating State combination supported. 0x0000000100000000 */ -#define HCI_SUPP_LE_STATES_CONN_ADV_INIT_MASK 0x01 -#define HCI_SUPP_LE_STATES_CONN_ADV_INIT_OFF 4 -#define HCI_LE_STATES_CONN_ADV_INIT_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_CONN_ADV_INIT_OFF] & HCI_SUPP_LE_STATES_CONN_ADV_INIT_MASK) - -/* High Duty Cycle Directed Advertising State and Initiating State combination supported. */ -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_INIT_MASK 0x02 -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_INIT_OFF 4 -#define HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_INIT_OFF] & HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_INIT_MASK) - -/* Low Duty Cycle Directed Advertising State and Initiating State combination supported.*/ -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_INIT_MASK 0x04 -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_INIT_OFF 4 -#define HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_INIT_OFF] & HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_INIT_MASK) - -/* Connectable Advertising State and Master Role combination supported.*/ -#define HCI_SUPP_LE_STATES_CONN_ADV_MASTER_MASK 0x08 -#define HCI_SUPP_LE_STATES_CONN_ADV_MASTER_OFF 4 -#define HCI_LE_STATES_CONN_ADV_MASTER_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_CONN_ADV_MASTER_OFF] & HCI_SUPP_LE_STATES_CONN_ADV_MASTER_MASK) - -/* High Duty Cycle Directed Advertising State and Master Role combination supported.*/ -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_MASTER_MASK 0x10 -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_MASTER_OFF 4 -#define HCI_LE_STATES_HI_DUTY_DIR_ADV_MASTER_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_MASTER_OFF] & HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_MASTER_MASK) - -/* Low Duty Cycle Directed Advertising State and Master Role combination supported.*/ -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_MASTER_MASK 0x20 -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_MASTER_OFF 4 -#define HCI_LE_STATES_LO_DUTY_DIR_ADV_MASTER_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_MASTER_OFF] & HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_MASTER_MASK) - -/* Connectable Advertising State and Slave Role combination supported. */ -#define HCI_SUPP_LE_STATES_CONN_ADV_SLAVE_MASK 0x40 -#define HCI_SUPP_LE_STATES_CONN_ADV_SLAVE_OFF 4 -#define HCI_LE_STATES_CONN_ADV_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_CONN_ADV_SLAVE_OFF] & HCI_SUPP_LE_STATES_CONN_ADV_SLAVE_MASK) - -/* High Duty Cycle Directed Advertising State and slave Role combination supported.*/ -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_SLAVE_MASK 0x80 -#define HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_SLAVE_OFF 4 -#define HCI_LE_STATES_HI_DUTY_DIR_ADV_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_SLAVE_OFF] & HCI_SUPP_LE_STATES_HI_DUTY_DIR_ADV_SLAVE_MASK) - -/* Low Duty Cycle Directed Advertising State and slave Role combination supported.*/ -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_SLAVE_MASK 0x01 -#define HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_SLAVE_OFF 5 -#define HCI_LE_STATES_LO_DUTY_DIR_ADV_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_SLAVE_OFF] & HCI_SUPP_LE_STATES_LO_DUTY_DIR_ADV_SLAVE_MASK) - -/* Initiating State and Slave Role combination supported. - Master Role and Slave Role combination also supported. - */ -#define HCI_SUPP_LE_STATES_INIT_MASTER_SLAVE_MASK 0x02 -#define HCI_SUPP_LE_STATES_INIT_MASTER_SLAVE_OFF 5 -#define HCI_LE_STATES_INIT_MASTER_SLAVE_SUPPORTED(x) ((x)[HCI_SUPP_LE_STATES_INIT_MASTER_SLAVE_OFF] & HCI_SUPP_LE_STATES_INIT_MASTER_SLAVE_MASK) - -/* -** Definitions for HCI Events -*/ -#define HCI_INQUIRY_COMP_EVT 0x01 -#define HCI_INQUIRY_RESULT_EVT 0x02 -#define HCI_CONNECTION_COMP_EVT 0x03 -#define HCI_CONNECTION_REQUEST_EVT 0x04 -#define HCI_DISCONNECTION_COMP_EVT 0x05 -#define HCI_AUTHENTICATION_COMP_EVT 0x06 -#define HCI_RMT_NAME_REQUEST_COMP_EVT 0x07 -#define HCI_ENCRYPTION_CHANGE_EVT 0x08 -#define HCI_CHANGE_CONN_LINK_KEY_EVT 0x09 -#define HCI_MASTER_LINK_KEY_COMP_EVT 0x0A -#define HCI_READ_RMT_FEATURES_COMP_EVT 0x0B -#define HCI_READ_RMT_VERSION_COMP_EVT 0x0C -#define HCI_QOS_SETUP_COMP_EVT 0x0D -#define HCI_COMMAND_COMPLETE_EVT 0x0E -#define HCI_COMMAND_STATUS_EVT 0x0F -#define HCI_HARDWARE_ERROR_EVT 0x10 -#define HCI_FLUSH_OCCURED_EVT 0x11 -#define HCI_ROLE_CHANGE_EVT 0x12 -#define HCI_NUM_COMPL_DATA_PKTS_EVT 0x13 -#define HCI_MODE_CHANGE_EVT 0x14 -#define HCI_RETURN_LINK_KEYS_EVT 0x15 -#define HCI_PIN_CODE_REQUEST_EVT 0x16 -#define HCI_LINK_KEY_REQUEST_EVT 0x17 -#define HCI_LINK_KEY_NOTIFICATION_EVT 0x18 -#define HCI_LOOPBACK_COMMAND_EVT 0x19 -#define HCI_DATA_BUF_OVERFLOW_EVT 0x1A -#define HCI_MAX_SLOTS_CHANGED_EVT 0x1B -#define HCI_READ_CLOCK_OFF_COMP_EVT 0x1C -#define HCI_CONN_PKT_TYPE_CHANGE_EVT 0x1D -#define HCI_QOS_VIOLATION_EVT 0x1E -#define HCI_PAGE_SCAN_MODE_CHANGE_EVT 0x1F -#define HCI_PAGE_SCAN_REP_MODE_CHNG_EVT 0x20 -#define HCI_FLOW_SPECIFICATION_COMP_EVT 0x21 -#define HCI_INQUIRY_RSSI_RESULT_EVT 0x22 -#define HCI_READ_RMT_EXT_FEATURES_COMP_EVT 0x23 -#define HCI_ESCO_CONNECTION_COMP_EVT 0x2C -#define HCI_ESCO_CONNECTION_CHANGED_EVT 0x2D -#define HCI_SNIFF_SUB_RATE_EVT 0x2E -#define HCI_EXTENDED_INQUIRY_RESULT_EVT 0x2F -#define HCI_ENCRYPTION_KEY_REFRESH_COMP_EVT 0x30 -#define HCI_IO_CAPABILITY_REQUEST_EVT 0x31 -#define HCI_IO_CAPABILITY_RESPONSE_EVT 0x32 -#define HCI_USER_CONFIRMATION_REQUEST_EVT 0x33 -#define HCI_USER_PASSKEY_REQUEST_EVT 0x34 -#define HCI_REMOTE_OOB_DATA_REQUEST_EVT 0x35 -#define HCI_SIMPLE_PAIRING_COMPLETE_EVT 0x36 -#define HCI_LINK_SUPER_TOUT_CHANGED_EVT 0x38 -#define HCI_ENHANCED_FLUSH_COMPLETE_EVT 0x39 -#define HCI_USER_PASSKEY_NOTIFY_EVT 0x3B -#define HCI_KEYPRESS_NOTIFY_EVT 0x3C -#define HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT 0x3D - -/*#define HCI_GENERIC_AMP_LINK_KEY_NOTIF_EVT 0x3E Removed from spec */ -#define HCI_PHYSICAL_LINK_COMP_EVT 0x40 -#define HCI_CHANNEL_SELECTED_EVT 0x41 -#define HCI_DISC_PHYSICAL_LINK_COMP_EVT 0x42 -#define HCI_PHY_LINK_LOSS_EARLY_WARNING_EVT 0x43 -#define HCI_PHY_LINK_RECOVERY_EVT 0x44 -#define HCI_LOGICAL_LINK_COMP_EVT 0x45 -#define HCI_DISC_LOGICAL_LINK_COMP_EVT 0x46 -#define HCI_FLOW_SPEC_MODIFY_COMP_EVT 0x47 -#define HCI_NUM_COMPL_DATA_BLOCKS_EVT 0x48 -#define HCI_SHORT_RANGE_MODE_COMPLETE_EVT 0x4C -#define HCI_AMP_STATUS_CHANGE_EVT 0x4D -#define HCI_SET_TRIGGERED_CLOCK_CAPTURE_EVT 0x4E - -/* ULP HCI Event */ -#define HCI_BLE_EVENT 0x3e -/* ULP Event sub code */ -#define HCI_BLE_CONN_COMPLETE_EVT 0x01 -#define HCI_BLE_ADV_PKT_RPT_EVT 0x02 -#define HCI_BLE_LL_CONN_PARAM_UPD_EVT 0x03 -#define HCI_BLE_READ_REMOTE_FEAT_CMPL_EVT 0x04 -#define HCI_BLE_LTK_REQ_EVT 0x05 -#define HCI_BLE_RC_PARAM_REQ_EVT 0x06 -#define HCI_BLE_DATA_LENGTH_CHANGE_EVT 0x07 -#define HCI_BLE_ENHANCED_CONN_COMPLETE_EVT 0x0a -#define HCI_BLE_DIRECT_ADV_EVT 0x0b - -/* Definitions for LE Channel Map */ -#define HCI_BLE_CHNL_MAP_SIZE 5 - -#define HCI_VENDOR_SPECIFIC_EVT 0xFF /* Vendor specific events */ -#define HCI_NAP_TRACE_EVT 0xFF /* was define 0xFE, 0xFD, change to 0xFF - because conflict w/ TCI_EVT and per - specification compliant */ - -/* -** Defentions for HCI Error Codes that are past in the events -*/ -#define HCI_SUCCESS 0x00 -#define HCI_PENDING 0x00 -#define HCI_ERR_ILLEGAL_COMMAND 0x01 -#define HCI_ERR_NO_CONNECTION 0x02 -#define HCI_ERR_HW_FAILURE 0x03 -#define HCI_ERR_PAGE_TIMEOUT 0x04 -#define HCI_ERR_AUTH_FAILURE 0x05 -#define HCI_ERR_KEY_MISSING 0x06 -#define HCI_ERR_MEMORY_FULL 0x07 -#define HCI_ERR_CONNECTION_TOUT 0x08 -#define HCI_ERR_MAX_NUM_OF_CONNECTIONS 0x09 -#define HCI_ERR_MAX_NUM_OF_SCOS 0x0A -#define HCI_ERR_CONNECTION_EXISTS 0x0B -#define HCI_ERR_COMMAND_DISALLOWED 0x0C -#define HCI_ERR_HOST_REJECT_RESOURCES 0x0D -#define HCI_ERR_HOST_REJECT_SECURITY 0x0E -#define HCI_ERR_HOST_REJECT_DEVICE 0x0F -#define HCI_ERR_HOST_TIMEOUT 0x10 -#define HCI_ERR_UNSUPPORTED_VALUE 0x11 -#define HCI_ERR_ILLEGAL_PARAMETER_FMT 0x12 -#define HCI_ERR_PEER_USER 0x13 -#define HCI_ERR_PEER_LOW_RESOURCES 0x14 -#define HCI_ERR_PEER_POWER_OFF 0x15 -#define HCI_ERR_CONN_CAUSE_LOCAL_HOST 0x16 -#define HCI_ERR_REPEATED_ATTEMPTS 0x17 -#define HCI_ERR_PAIRING_NOT_ALLOWED 0x18 -#define HCI_ERR_UNKNOWN_LMP_PDU 0x19 -#define HCI_ERR_UNSUPPORTED_REM_FEATURE 0x1A -#define HCI_ERR_SCO_OFFSET_REJECTED 0x1B -#define HCI_ERR_SCO_INTERVAL_REJECTED 0x1C -#define HCI_ERR_SCO_AIR_MODE 0x1D -#define HCI_ERR_INVALID_LMP_PARAM 0x1E -#define HCI_ERR_UNSPECIFIED 0x1F -#define HCI_ERR_UNSUPPORTED_LMP_FEATURE 0x20 -#define HCI_ERR_ROLE_CHANGE_NOT_ALLOWED 0x21 -#define HCI_ERR_LMP_RESPONSE_TIMEOUT 0x22 -#define HCI_ERR_LMP_ERR_TRANS_COLLISION 0x23 -#define HCI_ERR_LMP_PDU_NOT_ALLOWED 0x24 -#define HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE 0x25 -#define HCI_ERR_UNIT_KEY_USED 0x26 -#define HCI_ERR_QOS_NOT_SUPPORTED 0x27 -#define HCI_ERR_INSTANT_PASSED 0x28 -#define HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED 0x29 -#define HCI_ERR_DIFF_TRANSACTION_COLLISION 0x2A -#define HCI_ERR_UNDEFINED_0x2B 0x2B -#define HCI_ERR_QOS_UNACCEPTABLE_PARAM 0x2C -#define HCI_ERR_QOS_REJECTED 0x2D -#define HCI_ERR_CHAN_CLASSIF_NOT_SUPPORTED 0x2E -#define HCI_ERR_INSUFFCIENT_SECURITY 0x2F -#define HCI_ERR_PARAM_OUT_OF_RANGE 0x30 -#define HCI_ERR_UNDEFINED_0x31 0x31 -#define HCI_ERR_ROLE_SWITCH_PENDING 0x32 -#define HCI_ERR_UNDEFINED_0x33 0x33 -#define HCI_ERR_RESERVED_SLOT_VIOLATION 0x34 -#define HCI_ERR_ROLE_SWITCH_FAILED 0x35 -#define HCI_ERR_INQ_RSP_DATA_TOO_LARGE 0x36 -#define HCI_ERR_SIMPLE_PAIRING_NOT_SUPPORTED 0x37 -#define HCI_ERR_HOST_BUSY_PAIRING 0x38 -#define HCI_ERR_REJ_NO_SUITABLE_CHANNEL 0x39 -#define HCI_ERR_CONTROLLER_BUSY 0x3A -#define HCI_ERR_UNACCEPT_CONN_INTERVAL 0x3B -#define HCI_ERR_DIRECTED_ADVERTISING_TIMEOUT 0x3C -#define HCI_ERR_CONN_TOUT_DUE_TO_MIC_FAILURE 0x3D -#define HCI_ERR_CONN_FAILED_ESTABLISHMENT 0x3E -#define HCI_ERR_MAC_CONNECTION_FAILED 0x3F - -/* ConnectionLess Broadcast errors */ -#define HCI_ERR_LT_ADDR_ALREADY_IN_USE 0x40 -#define HCI_ERR_LT_ADDR_NOT_ALLOCATED 0x41 -#define HCI_ERR_CLB_NOT_ENABLED 0x42 -#define HCI_ERR_CLB_DATA_TOO_BIG 0x43 - -#define HCI_ERR_MAX_ERR 0x43 - -//ESP vendor error code -#define HCI_ERR_ESP_VENDOR_FAIL 0xE0 - -#define HCI_HINT_TO_RECREATE_AMP_PHYS_LINK 0xFF - -/* -** Definitions for HCI enable event -*/ -#define HCI_INQUIRY_COMPLETE_EV(p) (*((UINT32 *)(p)) & 0x00000001) -#define HCI_INQUIRY_RESULT_EV(p) (*((UINT32 *)(p)) & 0x00000002) -#define HCI_CONNECTION_COMPLETE_EV(p) (*((UINT32 *)(p)) & 0x00000004) -#define HCI_CONNECTION_REQUEST_EV(p) (*((UINT32 *)(p)) & 0x00000008) -#define HCI_DISCONNECTION_COMPLETE_EV(p) (*((UINT32 *)(p)) & 0x00000010) -#define HCI_AUTHENTICATION_COMPLETE_EV(p) (*((UINT32 *)(p)) & 0x00000020) -#define HCI_RMT_NAME_REQUEST_COMPL_EV(p) (*((UINT32 *)(p)) & 0x00000040) -#define HCI_CHANGE_CONN_ENCRPT_ENABLE_EV(p) (*((UINT32 *)(p)) & 0x00000080) -#define HCI_CHANGE_CONN_LINK_KEY_EV(p) (*((UINT32 *)(p)) & 0x00000100) -#define HCI_MASTER_LINK_KEY_COMPLETE_EV(p) (*((UINT32 *)(p)) & 0x00000200) -#define HCI_READ_RMT_FEATURES_COMPL_EV(p) (*((UINT32 *)(p)) & 0x00000400) -#define HCI_READ_RMT_VERSION_COMPL_EV(p) (*((UINT32 *)(p)) & 0x00000800) -#define HCI_QOS_SETUP_COMPLETE_EV(p) (*((UINT32 *)(p)) & 0x00001000) -#define HCI_COMMAND_COMPLETE_EV(p) (*((UINT32 *)(p)) & 0x00002000) -#define HCI_COMMAND_STATUS_EV(p) (*((UINT32 *)(p)) & 0x00004000) -#define HCI_HARDWARE_ERROR_EV(p) (*((UINT32 *)(p)) & 0x00008000) -#define HCI_FLASH_OCCURED_EV(p) (*((UINT32 *)(p)) & 0x00010000) -#define HCI_ROLE_CHANGE_EV(p) (*((UINT32 *)(p)) & 0x00020000) -#define HCI_NUM_COMPLETED_PKTS_EV(p) (*((UINT32 *)(p)) & 0x00040000) -#define HCI_MODE_CHANGE_EV(p) (*((UINT32 *)(p)) & 0x00080000) -#define HCI_RETURN_LINK_KEYS_EV(p) (*((UINT32 *)(p)) & 0x00100000) -#define HCI_PIN_CODE_REQUEST_EV(p) (*((UINT32 *)(p)) & 0x00200000) -#define HCI_LINK_KEY_REQUEST_EV(p) (*((UINT32 *)(p)) & 0x00400000) -#define HCI_LINK_KEY_NOTIFICATION_EV(p) (*((UINT32 *)(p)) & 0x00800000) -#define HCI_LOOPBACK_COMMAND_EV(p) (*((UINT32 *)(p)) & 0x01000000) -#define HCI_DATA_BUF_OVERFLOW_EV(p) (*((UINT32 *)(p)) & 0x02000000) -#define HCI_MAX_SLOTS_CHANGE_EV(p) (*((UINT32 *)(p)) & 0x04000000) -#define HCI_READ_CLOCK_OFFSET_COMP_EV(p) (*((UINT32 *)(p)) & 0x08000000) -#define HCI_CONN_PKT_TYPE_CHANGED_EV(p) (*((UINT32 *)(p)) & 0x10000000) -#define HCI_QOS_VIOLATION_EV(p) (*((UINT32 *)(p)) & 0x20000000) -#define HCI_PAGE_SCAN_MODE_CHANGED_EV(p) (*((UINT32 *)(p)) & 0x40000000) -#define HCI_PAGE_SCAN_REP_MODE_CHNG_EV(p) (*((UINT32 *)(p)) & 0x80000000) - -/* the default event mask for 2.1+EDR (Lisbon) does not include Lisbon events */ -#define HCI_DEFAULT_EVENT_MASK_0 0xFFFFFFFF -#define HCI_DEFAULT_EVENT_MASK_1 0x00001FFF - -/* the event mask for 2.0 + EDR and later (includes Lisbon events) */ -#define HCI_LISBON_EVENT_MASK_0 0xFFFFFFFF -#define HCI_LISBON_EVENT_MASK_1 0x1DBFFFFF -#define HCI_LISBON_EVENT_MASK "\x0D\xBF\xFF\xFF\xFF\xFF\xFF\xFF" -#define HCI_LISBON_EVENT_MASK_EXT "\x1D\xBF\xFF\xFF\xFF\xFF\xFF\xFF" -#define HCI_DUMO_EVENT_MASK_EXT "\x3D\xBF\xFF\xFF\xFF\xFF\xFF\xFF" -/* 0x00001FFF FFFFFFFF Default - no Lisbon events - 0x00000800 00000000 Synchronous Connection Complete Event - 0x00001000 00000000 Synchronous Connection Changed Event - 0x00002000 00000000 Sniff Subrate Event - 0x00004000 00000000 Extended Inquiry Result Event - 0x00008000 00000000 Encryption Key Refresh Complete Event - 0x00010000 00000000 IO Capability Request Event - 0x00020000 00000000 IO Capability Response Event - 0x00040000 00000000 User Confirmation Request Event - 0x00080000 00000000 User Passkey Request Event - 0x00100000 00000000 Remote OOB Data Request Event - 0x00200000 00000000 Simple Pairing Complete Event - 0x00400000 00000000 Generic AMP Link Key Notification Event - 0x00800000 00000000 Link Supervision Timeout Changed Event - 0x01000000 00000000 Enhanced Flush Complete Event - 0x04000000 00000000 User Passkey Notification Event - 0x08000000 00000000 Keypress Notification Event - 0x10000000 00000000 Remote Host Supported Features Notification Event - 0x20000000 00000000 LE Meta Event - */ - - -/* the event mask for AMP controllers */ -#define HCI_AMP_EVENT_MASK_3_0 "\x00\x00\x00\x00\x00\x00\x3F\xFF" - -/* 0x0000000000000000 No events specified (default) - 0x0000000000000001 Physical Link Complete Event - 0x0000000000000002 Channel Selected Event - 0x0000000000000004 Disconnection Physical Link Event - 0x0000000000000008 Physical Link Loss Early Warning Event - 0x0000000000000010 Physical Link Recovery Event - 0x0000000000000020 Logical Link Complete Event - 0x0000000000000040 Disconnection Logical Link Complete Event - 0x0000000000000080 Flow Spec Modify Complete Event - 0x0000000000000100 Number of Completed Data Blocks Event - 0x0000000000000200 AMP Start Test Event - 0x0000000000000400 AMP Test End Event - 0x0000000000000800 AMP Receiver Report Event - 0x0000000000001000 Short Range Mode Change Complete Event - 0x0000000000002000 AMP Status Change Event -*/ - -/* the event mask page 2 (CLB + CSA4) for BR/EDR controller */ -#define HCI_PAGE_2_EVENT_MASK "\x00\x00\x00\x00\x00\x7F\xC0\x00" -/* 0x0000000000004000 Triggered Clock Capture Event - 0x0000000000008000 Sync Train Complete Event - 0x0000000000010000 Sync Train Received Event - 0x0000000000020000 Connectionless Broadcast Receive Event - 0x0000000000040000 Connectionless Broadcast Timeout Event - 0x0000000000080000 Truncated Page Complete Event - 0x0000000000100000 Salve Page Response Timeout Event - 0x0000000000200000 Connectionless Broadcast Channel Map Change Event - 0x0000000000400000 Inquiry Response Notification Event -*/ -#if BLE_PRIVACY_SPT == TRUE -/* BLE event mask */ -#define HCI_BLE_EVENT_MASK_DEF "\x00\x00\x00\x00\x00\x00\x07\xff" -#else -#define HCI_BLE_EVENT_MASK_DEF "\x00\x00\x00\x00\x00\x00\x00\x7f" -#endif -/* -** Definitions for packet type masks (BT1.2 and BT2.0 definitions) -*/ -#define HCI_PKT_TYPES_MASK_NO_2_DH1 0x0002 -#define HCI_PKT_TYPES_MASK_NO_3_DH1 0x0004 -#define HCI_PKT_TYPES_MASK_DM1 0x0008 -#define HCI_PKT_TYPES_MASK_DH1 0x0010 -#define HCI_PKT_TYPES_MASK_HV1 0x0020 -#define HCI_PKT_TYPES_MASK_HV2 0x0040 -#define HCI_PKT_TYPES_MASK_HV3 0x0080 -#define HCI_PKT_TYPES_MASK_NO_2_DH3 0x0100 -#define HCI_PKT_TYPES_MASK_NO_3_DH3 0x0200 -#define HCI_PKT_TYPES_MASK_DM3 0x0400 -#define HCI_PKT_TYPES_MASK_DH3 0x0800 -#define HCI_PKT_TYPES_MASK_NO_2_DH5 0x1000 -#define HCI_PKT_TYPES_MASK_NO_3_DH5 0x2000 -#define HCI_PKT_TYPES_MASK_DM5 0x4000 -#define HCI_PKT_TYPES_MASK_DH5 0x8000 - -/* Packet type should be one of valid but at least one should be specified */ -#define HCI_VALID_SCO_PKT_TYPE(t) (((((t) & ~(HCI_PKT_TYPES_MASK_HV1 \ - | HCI_PKT_TYPES_MASK_HV2 \ - | HCI_PKT_TYPES_MASK_HV3)) == 0)) \ - && ((t) != 0)) - - - - - -/* Packet type should not be invalid and at least one should be specified */ -#define HCI_VALID_ACL_PKT_TYPE(t) (((((t) & ~(HCI_PKT_TYPES_MASK_DM1 \ - | HCI_PKT_TYPES_MASK_DH1 \ - | HCI_PKT_TYPES_MASK_DM3 \ - | HCI_PKT_TYPES_MASK_DH3 \ - | HCI_PKT_TYPES_MASK_DM5 \ - | HCI_PKT_TYPES_MASK_DH5 \ - | HCI_PKT_TYPES_MASK_NO_2_DH1 \ - | HCI_PKT_TYPES_MASK_NO_3_DH1 \ - | HCI_PKT_TYPES_MASK_NO_2_DH3 \ - | HCI_PKT_TYPES_MASK_NO_3_DH3 \ - | HCI_PKT_TYPES_MASK_NO_2_DH5 \ - | HCI_PKT_TYPES_MASK_NO_3_DH5 )) == 0)) \ - && (((t) & (HCI_PKT_TYPES_MASK_DM1 \ - | HCI_PKT_TYPES_MASK_DH1 \ - | HCI_PKT_TYPES_MASK_DM3 \ - | HCI_PKT_TYPES_MASK_DH3 \ - | HCI_PKT_TYPES_MASK_DM5 \ - | HCI_PKT_TYPES_MASK_DH5)) != 0)) - -/* -** Definitions for eSCO packet type masks (BT1.2 and BT2.0 definitions) -*/ -#define HCI_ESCO_PKT_TYPES_MASK_HV1 0x0001 -#define HCI_ESCO_PKT_TYPES_MASK_HV2 0x0002 -#define HCI_ESCO_PKT_TYPES_MASK_HV3 0x0004 -#define HCI_ESCO_PKT_TYPES_MASK_EV3 0x0008 -#define HCI_ESCO_PKT_TYPES_MASK_EV4 0x0010 -#define HCI_ESCO_PKT_TYPES_MASK_EV5 0x0020 -#define HCI_ESCO_PKT_TYPES_MASK_NO_2_EV3 0x0040 -#define HCI_ESCO_PKT_TYPES_MASK_NO_3_EV3 0x0080 -#define HCI_ESCO_PKT_TYPES_MASK_NO_2_EV5 0x0100 -#define HCI_ESCO_PKT_TYPES_MASK_NO_3_EV5 0x0200 - -/* Packet type should be one of valid but at least one should be specified for 1.2 */ -#define HCI_VALID_ESCO_PKT_TYPE(t) (((((t) & ~(HCI_ESCO_PKT_TYPES_MASK_EV3 \ - | HCI_ESCO_PKT_TYPES_MASK_EV4 \ - | HCI_ESCO_PKT_TYPES_MASK_EV5)) == 0)) \ - && ((t) != 0))/* Packet type should be one of valid but at least one should be specified */ - -#define HCI_VALID_ESCO_SCOPKT_TYPE(t) (((((t) & ~(HCI_ESCO_PKT_TYPES_MASK_HV1 \ - | HCI_ESCO_PKT_TYPES_MASK_HV2 \ - | HCI_ESCO_PKT_TYPES_MASK_HV3)) == 0)) \ - && ((t) != 0)) - -#define HCI_VALID_SCO_ALL_PKT_TYPE(t) (((((t) & ~(HCI_ESCO_PKT_TYPES_MASK_HV1 \ - | HCI_ESCO_PKT_TYPES_MASK_HV2 \ - | HCI_ESCO_PKT_TYPES_MASK_HV3 \ - | HCI_ESCO_PKT_TYPES_MASK_EV3 \ - | HCI_ESCO_PKT_TYPES_MASK_EV4 \ - | HCI_ESCO_PKT_TYPES_MASK_EV5)) == 0)) \ - && ((t) != 0)) - -/* -** Define parameters to allow role switch during create connection -*/ -#define HCI_CR_CONN_NOT_ALLOW_SWITCH 0x00 -#define HCI_CR_CONN_ALLOW_SWITCH 0x01 - -/* -** Hold Mode command destination -*/ -#define HOLD_MODE_DEST_LOCAL_DEVICE 0x00 -#define HOLD_MODE_DEST_RMT_DEVICE 0x01 - -/* -** Definitions for different HCI parameters -*/ -#define HCI_PER_INQ_MIN_MAX_PERIOD 0x0003 -#define HCI_PER_INQ_MAX_MAX_PERIOD 0xFFFF -#define HCI_PER_INQ_MIN_MIN_PERIOD 0x0002 -#define HCI_PER_INQ_MAX_MIN_PERIOD 0xFFFE - -#define HCI_MAX_INQUIRY_LENGTH 0x30 - -#define HCI_MIN_INQ_LAP 0x9E8B00 -#define HCI_MAX_INQ_LAP 0x9E8B3F - -/* HCI role defenitions */ -#define HCI_ROLE_MASTER 0x00 -#define HCI_ROLE_SLAVE 0x01 -#define HCI_ROLE_UNKNOWN 0xff - -/* HCI mode defenitions */ -#define HCI_MODE_ACTIVE 0x00 -#define HCI_MODE_HOLD 0x01 -#define HCI_MODE_SNIFF 0x02 -#define HCI_MODE_PARK 0x03 - -/* HCI Flow Control Mode defenitions */ -#define HCI_PACKET_BASED_FC_MODE 0x00 -#define HCI_BLOCK_BASED_FC_MODE 0x01 - -/* Define Packet types as requested by the Host */ -#define HCI_ACL_PKT_TYPE_NONE 0x0000 -#define HCI_ACL_PKT_TYPE_DM1 0x0008 -#define HCI_ACL_PKT_TYPE_DH1 0x0010 -#define HCI_ACL_PKT_TYPE_AUX1 0x0200 -#define HCI_ACL_PKT_TYPE_DM3 0x0400 -#define HCI_ACL_PKT_TYPE_DH3 0x0800 -#define HCI_ACL_PKT_TYPE_DM5 0x4000 -#define HCI_ACL_PKT_TYPE_DH5 0x8000 - -/* Define key type in the Master Link Key command */ -#define HCI_USE_SEMI_PERMANENT_KEY 0x00 -#define HCI_USE_TEMPORARY_KEY 0x01 - -/* Page scan period modes */ -#define HCI_PAGE_SCAN_REP_MODE_R0 0x00 -#define HCI_PAGE_SCAN_REP_MODE_R1 0x01 -#define HCI_PAGE_SCAN_REP_MODE_R2 0x02 - -/* Define limits for page scan repetition modes */ -#define HCI_PAGE_SCAN_R1_LIMIT 0x0800 -#define HCI_PAGE_SCAN_R2_LIMIT 0x1000 - -/* Page scan period modes */ -#define HCI_PAGE_SCAN_PER_MODE_P0 0x00 -#define HCI_PAGE_SCAN_PER_MODE_P1 0x01 -#define HCI_PAGE_SCAN_PER_MODE_P2 0x02 - -/* Page scan modes */ -#define HCI_MANDATARY_PAGE_SCAN_MODE 0x00 -#define HCI_OPTIONAL_PAGE_SCAN_MODE1 0x01 -#define HCI_OPTIONAL_PAGE_SCAN_MODE2 0x02 -#define HCI_OPTIONAL_PAGE_SCAN_MODE3 0x03 - -/* Page and inquiry scan types */ -#define HCI_SCAN_TYPE_STANDARD 0x00 -#define HCI_SCAN_TYPE_INTERLACED 0x01 /* 1.2 devices or later */ -#define HCI_DEF_SCAN_TYPE HCI_SCAN_TYPE_STANDARD - -/* Definitions for quality of service service types */ -#define HCI_SERVICE_NO_TRAFFIC 0x00 -#define HCI_SERVICE_BEST_EFFORT 0x01 -#define HCI_SERVICE_GUARANTEED 0x02 - -#define HCI_QOS_LATENCY_DO_NOT_CARE 0xFFFFFFFF -#define HCI_QOS_DELAY_DO_NOT_CARE 0xFFFFFFFF - -/* Definitions for Flow Specification */ -#define HCI_FLOW_SPEC_LATENCY_DO_NOT_CARE 0xFFFFFFFF - -/* Definitions for AFH Channel Map */ -#define HCI_AFH_CHANNEL_MAP_LEN 10 - -/* Definitions for Extended Inquiry Response */ -#define HCI_EXT_INQ_RESPONSE_LEN 240 -#define HCI_EIR_FLAGS_TYPE BT_EIR_FLAGS_TYPE -#define HCI_EIR_MORE_16BITS_UUID_TYPE BT_EIR_MORE_16BITS_UUID_TYPE -#define HCI_EIR_COMPLETE_16BITS_UUID_TYPE BT_EIR_COMPLETE_16BITS_UUID_TYPE -#define HCI_EIR_MORE_32BITS_UUID_TYPE BT_EIR_MORE_32BITS_UUID_TYPE -#define HCI_EIR_COMPLETE_32BITS_UUID_TYPE BT_EIR_COMPLETE_32BITS_UUID_TYPE -#define HCI_EIR_MORE_128BITS_UUID_TYPE BT_EIR_MORE_128BITS_UUID_TYPE -#define HCI_EIR_COMPLETE_128BITS_UUID_TYPE BT_EIR_COMPLETE_128BITS_UUID_TYPE -#define HCI_EIR_SHORTENED_LOCAL_NAME_TYPE BT_EIR_SHORTENED_LOCAL_NAME_TYPE -#define HCI_EIR_COMPLETE_LOCAL_NAME_TYPE BT_EIR_COMPLETE_LOCAL_NAME_TYPE -#define HCI_EIR_TX_POWER_LEVEL_TYPE BT_EIR_TX_POWER_LEVEL_TYPE -#define HCI_EIR_MANUFACTURER_SPECIFIC_TYPE BT_EIR_MANUFACTURER_SPECIFIC_TYPE -#define HCI_EIR_OOB_BD_ADDR_TYPE BT_EIR_OOB_BD_ADDR_TYPE -#define HCI_EIR_OOB_COD_TYPE BT_EIR_OOB_COD_TYPE -#define HCI_EIR_OOB_SSP_HASH_C_TYPE BT_EIR_OOB_SSP_HASH_C_TYPE -#define HCI_EIR_OOB_SSP_RAND_R_TYPE BT_EIR_OOB_SSP_RAND_R_TYPE - -/* Definitions for Write Simple Pairing Mode */ -#define HCI_SP_MODE_UNDEFINED 0x00 -#define HCI_SP_MODE_ENABLED 0x01 - -/* Definitions for Write Simple Pairing Debug Mode */ -#define HCI_SPD_MODE_DISABLED 0x00 -#define HCI_SPD_MODE_ENABLED 0x01 - -/* Definitions for Write Secure Connections Host Support */ -#define HCI_SC_MODE_DISABLED 0x00 -#define HCI_SC_MODE_ENABLED 0x01 - -/* Definitions for IO Capability Response/Command */ -#define HCI_IO_CAP_DISPLAY_ONLY 0x00 -#define HCI_IO_CAP_DISPLAY_YESNO 0x01 -#define HCI_IO_CAP_KEYBOARD_ONLY 0x02 -#define HCI_IO_CAP_NO_IO 0x03 - -#define HCI_OOB_AUTH_DATA_NOT_PRESENT 0x00 -#define HCI_OOB_REM_AUTH_DATA_PRESENT 0x01 - -#define HCI_MITM_PROTECT_NOT_REQUIRED 0x00 -#define HCI_MITM_PROTECT_REQUIRED 0x01 - - -/* Policy settings status */ -#define HCI_DISABLE_ALL_LM_MODES 0x0000 -#define HCI_ENABLE_MASTER_SLAVE_SWITCH 0x0001 -#define HCI_ENABLE_HOLD_MODE 0x0002 -#define HCI_ENABLE_SNIFF_MODE 0x0004 -#define HCI_ENABLE_PARK_MODE 0x0008 - -/* By default allow switch, because host can not allow that */ -/* that until he created the connection */ -#define HCI_DEFAULT_POLICY_SETTINGS HCI_DISABLE_ALL_LM_MODES - -/* Filters that are sent in set filter command */ -#define HCI_FILTER_TYPE_CLEAR_ALL 0x00 -#define HCI_FILTER_INQUIRY_RESULT 0x01 -#define HCI_FILTER_CONNECTION_SETUP 0x02 - -#define HCI_FILTER_COND_NEW_DEVICE 0x00 -#define HCI_FILTER_COND_DEVICE_CLASS 0x01 -#define HCI_FILTER_COND_BD_ADDR 0x02 - -#define HCI_DO_NOT_AUTO_ACCEPT_CONNECT 1 -#define HCI_DO_AUTO_ACCEPT_CONNECT 2 /* role switch disabled */ -#define HCI_DO_AUTO_ACCEPT_CONNECT_RS 3 /* role switch enabled (1.1 errata 1115) */ - -/* Auto accept flags */ -#define HCI_AUTO_ACCEPT_OFF 0x00 -#define HCI_AUTO_ACCEPT_ACL_CONNECTIONS 0x01 -#define HCI_AUTO_ACCEPT_SCO_CONNECTIONS 0x02 - -/* PIN type */ -#define HCI_PIN_TYPE_VARIABLE 0 -#define HCI_PIN_TYPE_FIXED 1 - -/* Loopback Modes */ -#define HCI_LOOPBACK_MODE_DISABLED 0 -#define HCI_LOOPBACK_MODE_LOCAL 1 -#define HCI_LOOPBACK_MODE_REMOTE 2 - -#define SLOTS_PER_10MS 16 /* 0.625 ms slots in a 10 ms tick */ - -/* Maximum connection accept timeout in 0.625msec */ -#define HCI_MAX_CONN_ACCEPT_TOUT 0xB540 /* 29 sec */ -#define HCI_DEF_CONN_ACCEPT_TOUT 0x1F40 /* 5 sec */ - -/* Page timeout is used in LC only and LC is counting down slots not using OS */ -#define HCI_DEFAULT_PAGE_TOUT 0x2000 /* 5.12 sec (in slots) */ - -/* Scan enable flags */ -#define HCI_NO_SCAN_ENABLED 0x00 -#define HCI_INQUIRY_SCAN_ENABLED 0x01 -#define HCI_PAGE_SCAN_ENABLED 0x02 - -/* Pagescan timer definitions in 0.625 ms */ -#define HCI_MIN_PAGESCAN_INTERVAL 0x12 /* 11.25 ms */ -#define HCI_MAX_PAGESCAN_INTERVAL 0x1000 /* 2.56 sec */ -#define HCI_DEF_PAGESCAN_INTERVAL 0x0800 /* 1.28 sec */ - -/* Parameter for pagescan window is passed to LC and is kept in slots */ -#define HCI_MIN_PAGESCAN_WINDOW 0x11 /* 10.625 ms */ -#define HCI_MAX_PAGESCAN_WINDOW 0x1000 /* 2.56 sec */ -#define HCI_DEF_PAGESCAN_WINDOW 0x12 /* 11.25 ms */ - -/* Inquiryscan timer definitions in 0.625 ms */ -#define HCI_MIN_INQUIRYSCAN_INTERVAL 0x12 /* 11.25 ms */ -#define HCI_MAX_INQUIRYSCAN_INTERVAL 0x1000 /* 2.56 sec */ -#define HCI_DEF_INQUIRYSCAN_INTERVAL 0x1000 /* 2.56 sec */ - -/* Parameter for inquiryscan window is passed to LC and is kept in slots */ -#define HCI_MIN_INQUIRYSCAN_WINDOW 0x11 /* 10.625 ms */ -#define HCI_MAX_INQUIRYSCAN_WINDOW 0x1000 /* 2.56 sec */ -#define HCI_DEF_INQUIRYSCAN_WINDOW 0x12 /* 11.25 ms */ - -/* Encryption modes */ -#define HCI_ENCRYPT_MODE_DISABLED 0x00 -#define HCI_ENCRYPT_MODE_POINT_TO_POINT 0x01 -#define HCI_ENCRYPT_MODE_ALL 0x02 - -/* Voice settings */ -#define HCI_INP_CODING_LINEAR 0x0000 /* 0000000000 */ -#define HCI_INP_CODING_U_LAW 0x0100 /* 0100000000 */ -#define HCI_INP_CODING_A_LAW 0x0200 /* 1000000000 */ -#define HCI_INP_CODING_MASK 0x0300 /* 1100000000 */ - -#define HCI_INP_DATA_FMT_1S_COMPLEMENT 0x0000 /* 0000000000 */ -#define HCI_INP_DATA_FMT_2S_COMPLEMENT 0x0040 /* 0001000000 */ -#define HCI_INP_DATA_FMT_SIGN_MAGNITUDE 0x0080 /* 0010000000 */ -#define HCI_INP_DATA_FMT_UNSIGNED 0x00c0 /* 0011000000 */ -#define HCI_INP_DATA_FMT_MASK 0x00c0 /* 0011000000 */ - -#define HCI_INP_SAMPLE_SIZE_8BIT 0x0000 /* 0000000000 */ -#define HCI_INP_SAMPLE_SIZE_16BIT 0x0020 /* 0000100000 */ -#define HCI_INP_SAMPLE_SIZE_MASK 0x0020 /* 0000100000 */ - -#define HCI_INP_LINEAR_PCM_BIT_POS_MASK 0x001c /* 0000011100 */ -#define HCI_INP_LINEAR_PCM_BIT_POS_OFFS 2 - -#define HCI_AIR_CODING_FORMAT_CVSD 0x0000 /* 0000000000 */ -#define HCI_AIR_CODING_FORMAT_U_LAW 0x0001 /* 0000000001 */ -#define HCI_AIR_CODING_FORMAT_A_LAW 0x0002 /* 0000000010 */ -#define HCI_AIR_CODING_FORMAT_TRANSPNT 0x0003 /* 0000000011 */ -#define HCI_AIR_CODING_FORMAT_MASK 0x0003 /* 0000000011 */ - -/* default 0001100000 */ -#define HCI_DEFAULT_VOICE_SETTINGS (HCI_INP_CODING_LINEAR \ - | HCI_INP_DATA_FMT_2S_COMPLEMENT \ - | HCI_INP_SAMPLE_SIZE_16BIT \ - | HCI_AIR_CODING_FORMAT_CVSD) - -#define HCI_CVSD_SUPPORTED(x) (((x) & HCI_AIR_CODING_FORMAT_MASK) == HCI_AIR_CODING_FORMAT_CVSD) -#define HCI_U_LAW_SUPPORTED(x) (((x) & HCI_AIR_CODING_FORMAT_MASK) == HCI_AIR_CODING_FORMAT_U_LAW) -#define HCI_A_LAW_SUPPORTED(x) (((x) & HCI_AIR_CODING_FORMAT_MASK) == HCI_AIR_CODING_FORMAT_A_LAW) -#define HCI_TRANSPNT_SUPPORTED(x) (((x) & HCI_AIR_CODING_FORMAT_MASK) == HCI_AIR_CODING_FORMAT_TRANSPNT) - -/* Retransmit timer definitions in 0.625 */ -#define HCI_MAX_AUTO_FLUSH_TOUT 0x07FF -#define HCI_DEFAULT_AUTO_FLUSH_TOUT 0 /* No auto flush */ - -/* Broadcast retransmitions */ -#define HCI_DEFAULT_NUM_BCAST_RETRAN 1 - -/* Define broadcast data types as passed in the hci data packet */ -#define HCI_DATA_POINT_TO_POINT 0x00 -#define HCI_DATA_ACTIVE_BCAST 0x01 -#define HCI_DATA_PICONET_BCAST 0x02 - -/* Hold mode activity */ -#define HCI_MAINTAIN_CUR_POWER_STATE 0x00 -#define HCI_SUSPEND_PAGE_SCAN 0x01 -#define HCI_SUSPEND_INQUIRY_SCAN 0x02 -#define HCI_SUSPEND_PERIODIC_INQUIRIES 0x04 - -/* Default Link Supervision timeoout */ -#define HCI_DEFAULT_INACT_TOUT 0x7D00 /* BR/EDR (20 seconds) */ -#define HCI_DEFAULT_AMP_INACT_TOUT 0x3E80 /* AMP (10 seconds) */ - -/* Read transmit power level parameter */ -#define HCI_READ_CURRENT 0x00 -#define HCI_READ_MAXIMUM 0x01 - -/* Link types for connection complete event */ -#define HCI_LINK_TYPE_SCO 0x00 -#define HCI_LINK_TYPE_ACL 0x01 -#define HCI_LINK_TYPE_ESCO 0x02 - -/* Link Key Notification Event (Key Type) definitions */ -#define HCI_LKEY_TYPE_COMBINATION 0x00 -#define HCI_LKEY_TYPE_LOCAL_UNIT 0x01 -#define HCI_LKEY_TYPE_REMOTE_UNIT 0x02 -#define HCI_LKEY_TYPE_DEBUG_COMB 0x03 -#define HCI_LKEY_TYPE_UNAUTH_COMB 0x04 -#define HCI_LKEY_TYPE_AUTH_COMB 0x05 -#define HCI_LKEY_TYPE_CHANGED_COMB 0x06 -#define HCI_LKEY_TYPE_UNAUTH_COMB_P_256 0x07 -#define HCI_LKEY_TYPE_AUTH_COMB_P_256 0x08 - -/* Internal definitions - not used over HCI */ -#define HCI_LKEY_TYPE_AMP_WIFI 0x80 -#define HCI_LKEY_TYPE_AMP_UWB 0x81 -#define HCI_LKEY_TYPE_UNKNOWN 0xff - -/* Read Local Version HCI Version return values (Command Complete Event) */ -#define HCI_VERSION_1_0B 0x00 -#define HCI_VERSION_1_1 0x01 - -/* Define an invalid value for a handle */ -#define HCI_INVALID_HANDLE 0xFFFF - -/* Define max ammount of data in the HCI command */ -#define HCI_COMMAND_SIZE 255 - -/* Define the preamble length for all HCI Commands. -** This is 2-bytes for opcode and 1 byte for length -*/ -#define HCIC_PREAMBLE_SIZE 3 - -/* Define the preamble length for all HCI Events -** This is 1-byte for opcode and 1 byte for length -*/ -#define HCIE_PREAMBLE_SIZE 2 -#define HCI_SCO_PREAMBLE_SIZE 3 -#define HCI_DATA_PREAMBLE_SIZE 4 - -/* local Bluetooth controller id for AMP HCI */ -#define LOCAL_BR_EDR_CONTROLLER_ID 0 - -/* controller id types for AMP HCI */ -#define HCI_CONTROLLER_TYPE_BR_EDR 0 -#define HCI_CONTROLLER_TYPE_802_11 1 -#define HCI_CONTROLLER_TYPE_ECMA 2 -#define HCI_MAX_CONTROLLER_TYPES 3 - -/* ConnectionLess Broadcast */ -#define HCI_CLB_DISABLE 0x00 -#define HCI_CLB_ENABLE 0x01 - -/* ConnectionLess Broadcast Data fragment */ -#define HCI_CLB_FRAGMENT_CONT 0x00 -#define HCI_CLB_FRAGMENT_START 0x01 -#define HCI_CLB_FRAGMENT_END 0x02 -#define HCI_CLB_FRAGMENT_SINGLE 0x03 - -/* AMP Controller Status codes -*/ -#define HCI_AMP_CTRLR_PHYSICALLY_DOWN 0 -#define HCI_AMP_CTRLR_USABLE_BY_BT 1 -#define HCI_AMP_CTRLR_UNUSABLE_FOR_BT 2 -#define HCI_AMP_CTRLR_LOW_CAP_FOR_BT 3 -#define HCI_AMP_CTRLR_MED_CAP_FOR_BT 4 -#define HCI_AMP_CTRLR_HIGH_CAP_FOR_BT 5 -#define HCI_AMP_CTRLR_FULL_CAP_FOR_BT 6 - -#define HCI_MAX_AMP_STATUS_TYPES 7 - - -/* Define the extended flow specification fields used by AMP */ -typedef struct { - UINT8 id; - UINT8 stype; - UINT16 max_sdu_size; - UINT32 sdu_inter_time; - UINT32 access_latency; - UINT32 flush_timeout; -} tHCI_EXT_FLOW_SPEC; - - -/* HCI message type definitions (for H4 messages) */ -#define HCIT_TYPE_COMMAND 1 -#define HCIT_TYPE_ACL_DATA 2 -#define HCIT_TYPE_SCO_DATA 3 -#define HCIT_TYPE_EVENT 4 -#define HCIT_TYPE_LM_DIAG 7 -#define HCIT_TYPE_NFC 16 - -#define HCIT_LM_DIAG_LENGTH 63 - -/* Parameter information for HCI_BRCM_SET_ACL_PRIORITY */ -#define HCI_BRCM_ACL_PRIORITY_PARAM_SIZE 3 -#define HCI_BRCM_ACL_PRIORITY_LOW 0x00 -#define HCI_BRCM_ACL_PRIORITY_HIGH 0xFF -#define HCI_BRCM_SET_ACL_PRIORITY (0x0057 | HCI_GRP_VENDOR_SPECIFIC) - -/* Define values for LMP Test Control parameters -** Test Scenario, Hopping Mode, Power Control Mode -*/ -#define LMP_TESTCTL_TESTSC_PAUSE 0 -#define LMP_TESTCTL_TESTSC_TXTEST_0 1 -#define LMP_TESTCTL_TESTSC_TXTEST_1 2 -#define LMP_TESTCTL_TESTSC_TXTEST_1010 3 -#define LMP_TESTCTL_TESTSC_PSRND_BITSEQ 4 -#define LMP_TESTCTL_TESTSC_CLOSEDLB_ACL 5 -#define LMP_TESTCTL_TESTSC_CLOSEDLB_SCO 6 -#define LMP_TESTCTL_TESTSC_ACL_NOWHIT 7 -#define LMP_TESTCTL_TESTSC_SCO_NOWHIT 8 -#define LMP_TESTCTL_TESTSC_TXTEST_11110000 9 -#define LMP_TESTCTL_TESTSC_EXITTESTMODE 255 - -#define LMP_TESTCTL_HOPMOD_RXTX1FREQ 0 -#define LMP_TESTCTL_HOPMOD_HOP_EURUSA 1 -#define LMP_TESTCTL_HOPMOD_HOP_JAPAN 2 -#define LMP_TESTCTL_HOPMOD_HOP_FRANCE 3 -#define LMP_TESTCTL_HOPMOD_HOP_SPAIN 4 -#define LMP_TESTCTL_HOPMOD_REDUCED_HOP 5 - -#define LMP_TESTCTL_POWCTL_FIXEDTX_OP 0 -#define LMP_TESTCTL_POWCTL_ADAPTIVE 1 - -// TODO(zachoverflow): remove this once broadcom specific hacks are removed -#define LMP_COMPID_BROADCOM 15 - -/* -** Define the packet types in the packet header, and a couple extra -*/ -#define PKT_TYPE_NULL 0x00 -#define PKT_TYPE_POLL 0x01 -#define PKT_TYPE_FHS 0x02 -#define PKT_TYPE_DM1 0x03 - -#define PKT_TYPE_DH1 0x04 -#define PKT_TYPE_HV1 0x05 -#define PKT_TYPE_HV2 0x06 -#define PKT_TYPE_HV3 0x07 -#define PKT_TYPE_DV 0x08 -#define PKT_TYPE_AUX1 0x09 - -#define PKT_TYPE_DM3 0x0a -#define PKT_TYPE_DH3 0x0b - -#define PKT_TYPE_DM5 0x0e -#define PKT_TYPE_DH5 0x0f - - -#define PKT_TYPE_ID 0x10 /* Internally used packet types */ -#define PKT_TYPE_BAD 0x11 -#define PKT_TYPE_NONE 0x12 - -/* -** Define packet size -*/ -#define HCI_DM1_PACKET_SIZE 17 -#define HCI_DH1_PACKET_SIZE 27 -#define HCI_DM3_PACKET_SIZE 121 -#define HCI_DH3_PACKET_SIZE 183 -#define HCI_DM5_PACKET_SIZE 224 -#define HCI_DH5_PACKET_SIZE 339 -#define HCI_AUX1_PACKET_SIZE 29 -#define HCI_HV1_PACKET_SIZE 10 -#define HCI_HV2_PACKET_SIZE 20 -#define HCI_HV3_PACKET_SIZE 30 -#define HCI_DV_PACKET_SIZE 9 -#define HCI_EDR2_DH1_PACKET_SIZE 54 -#define HCI_EDR2_DH3_PACKET_SIZE 367 -#define HCI_EDR2_DH5_PACKET_SIZE 679 -#define HCI_EDR3_DH1_PACKET_SIZE 83 -#define HCI_EDR3_DH3_PACKET_SIZE 552 -#define HCI_EDR3_DH5_PACKET_SIZE 1021 - -/* Feature Pages */ -#define HCI_EXT_FEATURES_PAGE_0 0 /* Extended Feature Page 0 (regular features) */ -#define HCI_EXT_FEATURES_PAGE_1 1 /* Extended Feature Page 1 */ -#define HCI_EXT_FEATURES_PAGE_2 2 /* Extended Feature Page 2 */ -#define HCI_EXT_FEATURES_PAGE_MAX HCI_EXT_FEATURES_PAGE_2 - -#define HCI_FEATURE_BYTES_PER_PAGE 8 - -#define HCI_FEATURES_KNOWN(x) ((x[0] | x[1] | x[2] | x[3] | x[4] | x[5] | x[6] | x[7]) != 0) - -/* -** LMP features encoding - page 0 -*/ -#define HCI_FEATURE_3_SLOT_PACKETS_MASK 0x01 -#define HCI_FEATURE_3_SLOT_PACKETS_OFF 0 -#define HCI_3_SLOT_PACKETS_SUPPORTED(x) ((x)[HCI_FEATURE_3_SLOT_PACKETS_OFF] & HCI_FEATURE_3_SLOT_PACKETS_MASK) - -#define HCI_FEATURE_5_SLOT_PACKETS_MASK 0x02 -#define HCI_FEATURE_5_SLOT_PACKETS_OFF 0 -#define HCI_5_SLOT_PACKETS_SUPPORTED(x) ((x)[HCI_FEATURE_5_SLOT_PACKETS_OFF] & HCI_FEATURE_5_SLOT_PACKETS_MASK) - -#define HCI_FEATURE_ENCRYPTION_MASK 0x04 -#define HCI_FEATURE_ENCRYPTION_OFF 0 -#define HCI_ENCRYPTION_SUPPORTED(x) ((x)[HCI_FEATURE_ENCRYPTION_OFF] & HCI_FEATURE_ENCRYPTION_MASK) - -#define HCI_FEATURE_SLOT_OFFSET_MASK 0x08 -#define HCI_FEATURE_SLOT_OFFSET_OFF 0 -#define HCI_SLOT_OFFSET_SUPPORTED(x) ((x)[HCI_FEATURE_SLOT_OFFSET_OFF] & HCI_FEATURE_SLOT_OFFSET_MASK) - -#define HCI_FEATURE_TIMING_ACC_MASK 0x10 -#define HCI_FEATURE_TIMING_ACC_OFF 0 -#define HCI_TIMING_ACC_SUPPORTED(x) ((x)[HCI_FEATURE_TIMING_ACC_OFF] & HCI_FEATURE_TIMING_ACC_MASK) - -#define HCI_FEATURE_SWITCH_MASK 0x20 -#define HCI_FEATURE_SWITCH_OFF 0 -// temporarily disable ROLE_SWITCH since there is an issue to be fixed -#define HCI_SWITCH_SUPPORTED(x) (0 & ((x)[HCI_FEATURE_SWITCH_OFF] & HCI_FEATURE_SWITCH_MASK)) - -#define HCI_FEATURE_HOLD_MODE_MASK 0x40 -#define HCI_FEATURE_HOLD_MODE_OFF 0 -#define HCI_HOLD_MODE_SUPPORTED(x) ((x)[HCI_FEATURE_HOLD_MODE_OFF] & HCI_FEATURE_HOLD_MODE_MASK) - -#define HCI_FEATURE_SNIFF_MODE_MASK 0x80 -#define HCI_FEATURE_SNIFF_MODE_OFF 0 -#define HCI_SNIFF_MODE_SUPPORTED(x) ((x)[HCI_FEATURE_SNIFF_MODE_OFF] & HCI_FEATURE_SNIFF_MODE_MASK) - -#define HCI_FEATURE_PARK_MODE_MASK 0x01 -#define HCI_FEATURE_PARK_MODE_OFF 1 -#define HCI_PARK_MODE_SUPPORTED(x) ((x)[HCI_FEATURE_PARK_MODE_OFF] & HCI_FEATURE_PARK_MODE_MASK) - -#define HCI_FEATURE_RSSI_MASK 0x02 -#define HCI_FEATURE_RSSI_OFF 1 -#define HCI_RSSI_SUPPORTED(x) ((x)[HCI_FEATURE_RSSI_OFF] & HCI_FEATURE_RSSI_MASK) - -#define HCI_FEATURE_CQM_DATA_RATE_MASK 0x04 -#define HCI_FEATURE_CQM_DATA_RATE_OFF 1 -#define HCI_CQM_DATA_RATE_SUPPORTED(x) ((x)[HCI_FEATURE_CQM_DATA_RATE_OFF] & HCI_FEATURE_CQM_DATA_RATE_MASK) - -#define HCI_FEATURE_SCO_LINK_MASK 0x08 -#define HCI_FEATURE_SCO_LINK_OFF 1 -#define HCI_SCO_LINK_SUPPORTED(x) ((x)[HCI_FEATURE_SCO_LINK_OFF] & HCI_FEATURE_SCO_LINK_MASK) - -#define HCI_FEATURE_HV2_PACKETS_MASK 0x10 -#define HCI_FEATURE_HV2_PACKETS_OFF 1 -#define HCI_HV2_PACKETS_SUPPORTED(x) ((x)[HCI_FEATURE_HV2_PACKETS_OFF] & HCI_FEATURE_HV2_PACKETS_MASK) - -#define HCI_FEATURE_HV3_PACKETS_MASK 0x20 -#define HCI_FEATURE_HV3_PACKETS_OFF 1 -#define HCI_HV3_PACKETS_SUPPORTED(x) ((x)[HCI_FEATURE_HV3_PACKETS_OFF] & HCI_FEATURE_HV3_PACKETS_MASK) - -#define HCI_FEATURE_U_LAW_MASK 0x40 -#define HCI_FEATURE_U_LAW_OFF 1 -#define HCI_LMP_U_LAW_SUPPORTED(x) ((x)[HCI_FEATURE_U_LAW_OFF] & HCI_FEATURE_U_LAW_MASK) - -#define HCI_FEATURE_A_LAW_MASK 0x80 -#define HCI_FEATURE_A_LAW_OFF 1 -#define HCI_LMP_A_LAW_SUPPORTED(x) ((x)[HCI_FEATURE_A_LAW_OFF] & HCI_FEATURE_A_LAW_MASK) - -#define HCI_FEATURE_CVSD_MASK 0x01 -#define HCI_FEATURE_CVSD_OFF 2 -#define HCI_LMP_CVSD_SUPPORTED(x) ((x)[HCI_FEATURE_CVSD_OFF] & HCI_FEATURE_CVSD_MASK) - -#define HCI_FEATURE_PAGING_SCHEME_MASK 0x02 -#define HCI_FEATURE_PAGING_SCHEME_OFF 2 -#define HCI_PAGING_SCHEME_SUPPORTED(x) ((x)[HCI_FEATURE_PAGING_SCHEME_OFF] & HCI_FEATURE_PAGING_SCHEME_MASK) - -#define HCI_FEATURE_POWER_CTRL_MASK 0x04 -#define HCI_FEATURE_POWER_CTRL_OFF 2 -#define HCI_POWER_CTRL_SUPPORTED(x) ((x)[HCI_FEATURE_POWER_CTRL_OFF] & HCI_FEATURE_POWER_CTRL_MASK) - -#define HCI_FEATURE_TRANSPNT_MASK 0x08 -#define HCI_FEATURE_TRANSPNT_OFF 2 -#define HCI_LMP_TRANSPNT_SUPPORTED(x) ((x)[HCI_FEATURE_TRANSPNT_OFF] & HCI_FEATURE_TRANSPNT_MASK) - -#define HCI_FEATURE_FLOW_CTRL_LAG_MASK 0x70 -#define HCI_FEATURE_FLOW_CTRL_LAG_OFF 2 -#define HCI_FLOW_CTRL_LAG_VALUE(x) (((x)[HCI_FEATURE_FLOW_CTRL_LAG_OFF] & HCI_FEATURE_FLOW_CTRL_LAG_MASK) >> 4) - -#define HCI_FEATURE_BROADCAST_ENC_MASK 0x80 -#define HCI_FEATURE_BROADCAST_ENC_OFF 2 -#define HCI_LMP_BCAST_ENC_SUPPORTED(x) ((x)[HCI_FEATURE_BROADCAST_ENC_OFF] & HCI_FEATURE_BROADCAST_ENC_MASK) - -#define HCI_FEATURE_SCATTER_MODE_MASK 0x01 -#define HCI_FEATURE_SCATTER_MODE_OFF 3 -#define HCI_LMP_SCATTER_MODE_SUPPORTED(x) ((x)[HCI_FEATURE_SCATTER_MODE_OFF] & HCI_FEATURE_SCATTER_MODE_MASK) - -#define HCI_FEATURE_EDR_ACL_2MPS_MASK 0x02 -#define HCI_FEATURE_EDR_ACL_2MPS_OFF 3 -#define HCI_EDR_ACL_2MPS_SUPPORTED(x) ((x)[HCI_FEATURE_EDR_ACL_2MPS_OFF] & HCI_FEATURE_EDR_ACL_2MPS_MASK) - -#define HCI_FEATURE_EDR_ACL_3MPS_MASK 0x04 -#define HCI_FEATURE_EDR_ACL_3MPS_OFF 3 -#define HCI_EDR_ACL_3MPS_SUPPORTED(x) ((x)[HCI_FEATURE_EDR_ACL_3MPS_OFF] & HCI_FEATURE_EDR_ACL_3MPS_MASK) - -#define HCI_FEATURE_ENHANCED_INQ_MASK 0x08 -#define HCI_FEATURE_ENHANCED_INQ_OFF 3 -#define HCI_ENHANCED_INQ_SUPPORTED(x) ((x)[HCI_FEATURE_ENHANCED_INQ_OFF] & HCI_FEATURE_ENHANCED_INQ_MASK) - -#define HCI_FEATURE_INTERLACED_INQ_SCAN_MASK 0x10 -#define HCI_FEATURE_INTERLACED_INQ_SCAN_OFF 3 -#define HCI_LMP_INTERLACED_INQ_SCAN_SUPPORTED(x) ((x)[HCI_FEATURE_INTERLACED_INQ_SCAN_OFF] & HCI_FEATURE_INTERLACED_INQ_SCAN_MASK) - -#define HCI_FEATURE_INTERLACED_PAGE_SCAN_MASK 0x20 -#define HCI_FEATURE_INTERLACED_PAGE_SCAN_OFF 3 -#define HCI_LMP_INTERLACED_PAGE_SCAN_SUPPORTED(x) ((x)[HCI_FEATURE_INTERLACED_PAGE_SCAN_OFF] & HCI_FEATURE_INTERLACED_PAGE_SCAN_MASK) - -#define HCI_FEATURE_INQ_RSSI_MASK 0x40 -#define HCI_FEATURE_INQ_RSSI_OFF 3 -#define HCI_LMP_INQ_RSSI_SUPPORTED(x) ((x)[HCI_FEATURE_INQ_RSSI_OFF] & HCI_FEATURE_INQ_RSSI_MASK) - -#define HCI_FEATURE_ESCO_EV3_MASK 0x80 -#define HCI_FEATURE_ESCO_EV3_OFF 3 -#define HCI_ESCO_EV3_SUPPORTED(x) ((x)[HCI_FEATURE_ESCO_EV3_OFF] & HCI_FEATURE_ESCO_EV3_MASK) - -#define HCI_FEATURE_ESCO_EV4_MASK 0x01 -#define HCI_FEATURE_ESCO_EV4_OFF 4 -#define HCI_ESCO_EV4_SUPPORTED(x) ((x)[HCI_FEATURE_ESCO_EV4_OFF] & HCI_FEATURE_ESCO_EV4_MASK) - -#define HCI_FEATURE_ESCO_EV5_MASK 0x02 -#define HCI_FEATURE_ESCO_EV5_OFF 4 -#define HCI_ESCO_EV5_SUPPORTED(x) ((x)[HCI_FEATURE_ESCO_EV5_OFF] & HCI_FEATURE_ESCO_EV5_MASK) - -#define HCI_FEATURE_ABSENCE_MASKS_MASK 0x04 -#define HCI_FEATURE_ABSENCE_MASKS_OFF 4 -#define HCI_LMP_ABSENCE_MASKS_SUPPORTED(x) ((x)[HCI_FEATURE_ABSENCE_MASKS_OFF] & HCI_FEATURE_ABSENCE_MASKS_MASK) - -#define HCI_FEATURE_AFH_CAP_SLAVE_MASK 0x08 -#define HCI_FEATURE_AFH_CAP_SLAVE_OFF 4 -#define HCI_LMP_AFH_CAP_SLAVE_SUPPORTED(x) ((x)[HCI_FEATURE_AFH_CAP_SLAVE_OFF] & HCI_FEATURE_AFH_CAP_SLAVE_MASK) - -#define HCI_FEATURE_AFH_CLASS_SLAVE_MASK 0x10 -#define HCI_FEATURE_AFH_CLASS_SLAVE_OFF 4 -#define HCI_LMP_AFH_CLASS_SLAVE_SUPPORTED(x) ((x)[HCI_FEATURE_AFH_CLASS_SLAVE_OFF] & HCI_FEATURE_AFH_CLASS_SLAVE_MASK) - -#if 1 -#define HCI_FEATURE_BREDR_NOT_SPT_MASK 0x20 -#define HCI_FEATURE_BREDR_NOT_SPT_OFF 4 -#define HCI_BREDR_NOT_SPT_SUPPORTED(x) ((x)[HCI_FEATURE_BREDR_NOT_SPT_OFF] & HCI_FEATURE_BREDR_NOT_SPT_MASK) - -#define HCI_FEATURE_LE_SPT_MASK 0x40 -#define HCI_FEATURE_LE_SPT_OFF 4 -#define HCI_LE_SPT_SUPPORTED(x) ((x)[HCI_FEATURE_LE_SPT_OFF] & HCI_FEATURE_LE_SPT_MASK) -#else - -#define HCI_FEATURE_ALIAS_AUTH_MASK 0x20 -#define HCI_FEATURE_ALIAS_AUTH_OFF 4 -#define HCI_LMP_ALIAS_AUTH_SUPPORTED(x) ((x)[HCI_FEATURE_ALIAS_AUTH_OFF] & HCI_FEATURE_ALIAS_AUTH_MASK) - -#define HCI_FEATURE_ANON_MODE_MASK 0x40 -#define HCI_FEATURE_ANON_MODE_OFF 4 -#define HCI_LMP_ANON_MODE_SUPPORTED(x) ((x)[HCI_FEATURE_ANON_MODE_OFF] & HCI_FEATURE_ANON_MODE_MASK) -#endif - -#define HCI_FEATURE_3_SLOT_EDR_ACL_MASK 0x80 -#define HCI_FEATURE_3_SLOT_EDR_ACL_OFF 4 -#define HCI_3_SLOT_EDR_ACL_SUPPORTED(x) ((x)[HCI_FEATURE_3_SLOT_EDR_ACL_OFF] & HCI_FEATURE_3_SLOT_EDR_ACL_MASK) - -#define HCI_FEATURE_5_SLOT_EDR_ACL_MASK 0x01 -#define HCI_FEATURE_5_SLOT_EDR_ACL_OFF 5 -#define HCI_5_SLOT_EDR_ACL_SUPPORTED(x) ((x)[HCI_FEATURE_5_SLOT_EDR_ACL_OFF] & HCI_FEATURE_5_SLOT_EDR_ACL_MASK) - -#define HCI_FEATURE_SNIFF_SUB_RATE_MASK 0x02 -#define HCI_FEATURE_SNIFF_SUB_RATE_OFF 5 -#define HCI_SNIFF_SUB_RATE_SUPPORTED(x) ((x)[HCI_FEATURE_SNIFF_SUB_RATE_OFF] & HCI_FEATURE_SNIFF_SUB_RATE_MASK) - -#define HCI_FEATURE_ATOMIC_ENCRYPT_MASK 0x04 -#define HCI_FEATURE_ATOMIC_ENCRYPT_OFF 5 -#define HCI_ATOMIC_ENCRYPT_SUPPORTED(x) ((x)[HCI_FEATURE_ATOMIC_ENCRYPT_OFF] & HCI_FEATURE_ATOMIC_ENCRYPT_MASK) - -#define HCI_FEATURE_AFH_CAP_MASTR_MASK 0x08 -#define HCI_FEATURE_AFH_CAP_MASTR_OFF 5 -#define HCI_LMP_AFH_CAP_MASTR_SUPPORTED(x) ((x)[HCI_FEATURE_AFH_CAP_MASTR_OFF] & HCI_FEATURE_AFH_CAP_MASTR_MASK) - -#define HCI_FEATURE_AFH_CLASS_MASTR_MASK 0x10 -#define HCI_FEATURE_AFH_CLASS_MASTR_OFF 5 -#define HCI_LMP_AFH_CLASS_MASTR_SUPPORTED(x) ((x)[HCI_FEATURE_AFH_CLASS_MASTR_OFF] & HCI_FEATURE_AFH_CLASS_MASTR_MASK) - -#define HCI_FEATURE_EDR_ESCO_2MPS_MASK 0x20 -#define HCI_FEATURE_EDR_ESCO_2MPS_OFF 5 -#define HCI_EDR_ESCO_2MPS_SUPPORTED(x) ((x)[HCI_FEATURE_EDR_ESCO_2MPS_OFF] & HCI_FEATURE_EDR_ESCO_2MPS_MASK) - -#define HCI_FEATURE_EDR_ESCO_3MPS_MASK 0x40 -#define HCI_FEATURE_EDR_ESCO_3MPS_OFF 5 -#define HCI_EDR_ESCO_3MPS_SUPPORTED(x) ((x)[HCI_FEATURE_EDR_ESCO_3MPS_OFF] & HCI_FEATURE_EDR_ESCO_3MPS_MASK) - -#define HCI_FEATURE_3_SLOT_EDR_ESCO_MASK 0x80 -#define HCI_FEATURE_3_SLOT_EDR_ESCO_OFF 5 -#define HCI_3_SLOT_EDR_ESCO_SUPPORTED(x) ((x)[HCI_FEATURE_3_SLOT_EDR_ESCO_OFF] & HCI_FEATURE_3_SLOT_EDR_ESCO_MASK) - -#define HCI_FEATURE_EXT_INQ_RSP_MASK 0x01 -#define HCI_FEATURE_EXT_INQ_RSP_OFF 6 -#define HCI_EXT_INQ_RSP_SUPPORTED(x) ((x)[HCI_FEATURE_EXT_INQ_RSP_OFF] & HCI_FEATURE_EXT_INQ_RSP_MASK) - -#if 1 /* TOKYO spec definition */ -#define HCI_FEATURE_SIMUL_LE_BREDR_MASK 0x02 -#define HCI_FEATURE_SIMUL_LE_BREDR_OFF 6 -#define HCI_SIMUL_LE_BREDR_SUPPORTED(x) ((x)[HCI_FEATURE_SIMUL_LE_BREDR_OFF] & HCI_FEATURE_SIMUL_LE_BREDR_MASK) - -#else -#define HCI_FEATURE_ANUM_PIN_AWARE_MASK 0x02 -#define HCI_FEATURE_ANUM_PIN_AWARE_OFF 6 -#define HCI_ANUM_PIN_AWARE_SUPPORTED(x) ((x)[HCI_FEATURE_ANUM_PIN_AWARE_OFF] & HCI_FEATURE_ANUM_PIN_AWARE_MASK) -#endif - -#define HCI_FEATURE_ANUM_PIN_CAP_MASK 0x04 -#define HCI_FEATURE_ANUM_PIN_CAP_OFF 6 -#define HCI_ANUM_PIN_CAP_SUPPORTED(x) ((x)[HCI_FEATURE_ANUM_PIN_CAP_OFF] & HCI_FEATURE_ANUM_PIN_CAP_MASK) - -#define HCI_FEATURE_SIMPLE_PAIRING_MASK 0x08 -#define HCI_FEATURE_SIMPLE_PAIRING_OFF 6 -#define HCI_SIMPLE_PAIRING_SUPPORTED(x) ((x)[HCI_FEATURE_SIMPLE_PAIRING_OFF] & HCI_FEATURE_SIMPLE_PAIRING_MASK) - -#define HCI_FEATURE_ENCAP_PDU_MASK 0x10 -#define HCI_FEATURE_ENCAP_PDU_OFF 6 -#define HCI_ENCAP_PDU_SUPPORTED(x) ((x)[HCI_FEATURE_ENCAP_PDU_OFF] & HCI_FEATURE_ENCAP_PDU_MASK) - -#define HCI_FEATURE_ERROR_DATA_MASK 0x20 -#define HCI_FEATURE_ERROR_DATA_OFF 6 -#define HCI_ERROR_DATA_SUPPORTED(x) ((x)[HCI_FEATURE_ERROR_DATA_OFF] & HCI_FEATURE_ERROR_DATA_MASK) - -#define HCI_FEATURE_NON_FLUSHABLE_PB_MASK 0x40 -#define HCI_FEATURE_NON_FLUSHABLE_PB_OFF 6 - -/* This feature is causing frequent link drops when doing call switch with certain av/hfp headsets */ -#define HCI_NON_FLUSHABLE_PB_SUPPORTED(x) (0)//((x)[HCI_FEATURE_NON_FLUSHABLE_PB_OFF] & HCI_FEATURE_NON_FLUSHABLE_PB_MASK) - -#define HCI_FEATURE_LINK_SUP_TO_EVT_MASK 0x01 -#define HCI_FEATURE_LINK_SUP_TO_EVT_OFF 7 -#define HCI_LINK_SUP_TO_EVT_SUPPORTED(x) ((x)[HCI_FEATURE_LINK_SUP_TO_EVT_OFF] & HCI_FEATURE_LINK_SUP_TO_EVT_MASK) - -#define HCI_FEATURE_INQ_RESP_TX_MASK 0x02 -#define HCI_FEATURE_INQ_RESP_TX_OFF 7 -#define HCI_INQ_RESP_TX_SUPPORTED(x) ((x)[HCI_FEATURE_INQ_RESP_TX_OFF] & HCI_FEATURE_INQ_RESP_TX_MASK) - -#define HCI_FEATURE_EXTENDED_MASK 0x80 -#define HCI_FEATURE_EXTENDED_OFF 7 -#define HCI_LMP_EXTENDED_SUPPORTED(x) ((x)[HCI_FEATURE_EXTENDED_OFF] & HCI_FEATURE_EXTENDED_MASK) - -/* -** LMP features encoding - page 1 -*/ -#define HCI_EXT_FEATURE_SSP_HOST_MASK 0x01 -#define HCI_EXT_FEATURE_SSP_HOST_OFF 0 -#define HCI_SSP_HOST_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_SSP_HOST_OFF] & HCI_EXT_FEATURE_SSP_HOST_MASK) - -#define HCI_EXT_FEATURE_LE_HOST_MASK 0x02 -#define HCI_EXT_FEATURE_LE_HOST_OFF 0 -#define HCI_LE_HOST_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_LE_HOST_OFF] & HCI_EXT_FEATURE_LE_HOST_MASK) - -#define HCI_EXT_FEATURE_SIMUL_DUMO_HOST_MASK 0x04 -#define HCI_EXT_FEATURE_SIMUL_DUMO_HOST_OFF 0 -#define HCI_SIMUL_DUMO_HOST_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_SIMUL_DUMO_HOST_OFF] & HCI_EXT_FEATURE_SIMUL_DUMO_HOST_MASK) - -#define HCI_EXT_FEATURE_SC_HOST_MASK 0x08 -#define HCI_EXT_FEATURE_SC_HOST_OFF 0 -#define HCI_SC_HOST_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_SC_HOST_OFF] & HCI_EXT_FEATURE_SC_HOST_MASK) - -/* -** LMP features encoding - page 2 -*/ -#define HCI_EXT_FEATURE_CSB_MASTER_MASK 0x01 -#define HCI_EXT_FEATURE_CSB_MASTER_OFF 0 -#define HCI_CSB_MASTER_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_CSB_MASTER_OFF] & HCI_EXT_FEATURE_CSB_MASTER_MASK) - -#define HCI_EXT_FEATURE_CSB_SLAVE_MASK 0x02 -#define HCI_EXT_FEATURE_CSB_SLAVE_OFF 0 -#define HCI_CSB_SLAVE_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_CSB_SLAVE_OFF] & HCI_EXT_FEATURE_CSB_SLAVE_MASK) - -#define HCI_EXT_FEATURE_SYNC_TRAIN_MASTER_MASK 0x04 -#define HCI_EXT_FEATURE_SYNC_TRAIN_MASTER_OFF 0 -#define HCI_SYNC_TRAIN_MASTER_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_SYNC_TRAIN_MASTER_OFF] & HCI_EXT_FEATURE_SYNC_TRAIN_MASTER_MASK) - -#define HCI_EXT_FEATURE_SYNC_SCAN_SLAVE_MASK 0x08 -#define HCI_EXT_FEATURE_SYNC_SCAN_SLAVE_OFF 0 -#define HCI_SYNC_SCAN_SLAVE_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_SYNC_SCAN_SLAVE_OFF] & HCI_EXT_FEATURE_SYNC_SCAN_SLAVE_MASK) - -#define HCI_EXT_FEATURE_INQ_RESP_NOTIF_MASK 0x10 -#define HCI_EXT_FEATURE_INQ_RESP_NOTIF_OFF 0 -#define HCI_INQ_RESP_NOTIF_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_INQ_RESP_NOTIF_OFF] & HCI_EXT_FEATURE_INQ_RESP_NOTIF_MASK) - -#define HCI_EXT_FEATURE_SC_CTRLR_MASK 0x01 -#define HCI_EXT_FEATURE_SC_CTRLR_OFF 1 -#define HCI_SC_CTRLR_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_SC_CTRLR_OFF] & HCI_EXT_FEATURE_SC_CTRLR_MASK) - -#define HCI_EXT_FEATURE_PING_MASK 0x02 -#define HCI_EXT_FEATURE_PING_OFF 1 -#define HCI_PING_SUPPORTED(x) ((x)[HCI_EXT_FEATURE_PING_OFF] & HCI_EXT_FEATURE_PING_MASK) - -/* -** LE features encoding - page 0 (the only page for now) -*/ -/* LE Encryption */ -#define HCI_LE_FEATURE_LE_ENCRYPTION_MASK 0x01 -#define HCI_LE_FEATURE_LE_ENCRYPTION_OFF 0 -#define HCI_LE_ENCRYPTION_SUPPORTED(x) ((x)[HCI_LE_FEATURE_LE_ENCRYPTION_OFF] & HCI_LE_FEATURE_LE_ENCRYPTION_MASK) - -/* Connection Parameters Request Procedure */ -#define HCI_LE_FEATURE_CONN_PARAM_REQ_MASK 0x02 -#define HCI_LE_FEATURE_CONN_PARAM_REQ_OFF 0 -#define HCI_LE_CONN_PARAM_REQ_SUPPORTED(x) ((x)[HCI_LE_FEATURE_CONN_PARAM_REQ_OFF] & HCI_LE_FEATURE_CONN_PARAM_REQ_MASK) - -/* Extended Reject Indication */ -#define HCI_LE_FEATURE_EXT_REJ_IND_MASK 0x04 -#define HCI_LE_FEATURE_EXT_REJ_IND_OFF 0 -#define HCI_LE_EXT_REJ_IND_SUPPORTED(x) ((x)[HCI_LE_FEATURE_EXT_REJ_IND_OFF] & HCI_LE_FEATURE_EXT_REJ_IND_MASK) - -/* Slave-initiated Features Exchange */ -#define HCI_LE_FEATURE_SLAVE_INIT_FEAT_EXC_MASK 0x08 -#define HCI_LE_FEATURE_SLAVE_INIT_FEAT_EXC_OFF 0 -#define HCI_LE_SLAVE_INIT_FEAT_EXC_SUPPORTED(x) ((x)[HCI_LE_FEATURE_SLAVE_INIT_FEAT_EXC_OFF] & HCI_LE_FEATURE_SLAVE_INIT_FEAT_EXC_MASK) - -/* Enhanced privacy Feature: bit 6 */ -#define HCI_LE_FEATURE_ENHANCED_PRIVACY_MASK 0x40 -#define HCI_LE_FEATURE_ENHANCED_PRIVACY_OFF 0 -#define HCI_LE_ENHANCED_PRIVACY_SUPPORTED(x) ((x)[HCI_LE_FEATURE_ENHANCED_PRIVACY_OFF] & HCI_LE_FEATURE_ENHANCED_PRIVACY_MASK) - -/* Extended scanner filter policy : 7 */ -#define HCI_LE_FEATURE_EXT_SCAN_FILTER_POLICY_MASK 0x80 -#define HCI_LE_FEATURE_EXT_SCAN_FILTER_POLICY_OFF 0 -#define HCI_LE_EXT_SCAN_FILTER_POLICY_SUPPORTED(x) ((x)[HCI_LE_FEATURE_EXT_SCAN_FILTER_POLICY_OFF] & HCI_LE_FEATURE_EXT_SCAN_FILTER_POLICY_MASK) - -/* Slave-initiated Features Exchange */ -#define HCI_LE_FEATURE_DATA_LEN_EXT_MASK 0x20 -#define HCI_LE_FEATURE_DATA_LEN_EXT_OFF 0 -#define HCI_LE_DATA_LEN_EXT_SUPPORTED(x) ((x)[HCI_LE_FEATURE_DATA_LEN_EXT_OFF] & HCI_LE_FEATURE_DATA_LEN_EXT_MASK) - -/* -** Local Supported Commands encoding -*/ -#define HCI_NUM_SUPP_COMMANDS_BYTES 64 - -/* Supported Commands Byte 0 */ -#define HCI_SUPP_COMMANDS_INQUIRY_MASK 0x01 -#define HCI_SUPP_COMMANDS_INQUIRY_OFF 0 -#define HCI_INQUIRY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_INQUIRY_OFF] & HCI_SUPP_COMMANDS_INQUIRY_MASK) - -#define HCI_SUPP_COMMANDS_INQUIRY_CANCEL_MASK 0x02 -#define HCI_SUPP_COMMANDS_INQUIRY_CANCEL_OFF 0 -#define HCI_INQUIRY_CANCEL_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_INQUIRY_CANCEL_OFF] & HCI_SUPP_COMMANDS_INQUIRY_CANCEL_MASK) - -#define HCI_SUPP_COMMANDS_PERIODIC_INQUIRY_MASK 0x04 -#define HCI_SUPP_COMMANDS_PERIODIC_INQUIRY_OFF 0 -#define HCI_PERIODIC_INQUIRY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_PERIODIC_INQUIRY_OFF] & HCI_SUPP_COMMANDS_PERIODIC_INQUIRY_MASK) - -#define HCI_SUPP_COMMANDS_EXIT_PERIODIC_INQUIRY_MASK 0x08 -#define HCI_SUPP_COMMANDS_EXIT_PERIODIC_INQUIRY_OFF 0 -#define HCI_EXIT_PERIODIC_INQUIRY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_EXIT_PERIODIC_INQUIRY_OFF] & HCI_SUPP_COMMANDS_EXIT_PERIODIC_INQUIRY_MASK) - -#define HCI_SUPP_COMMANDS_CREATE_CONN_MASK 0x10 -#define HCI_SUPP_COMMANDS_CREATE_CONN_OFF 0 -#define HCI_CREATE_CONN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_CREATE_CONN_OFF] & HCI_SUPP_COMMANDS_CREATE_CONN_MASK) - -#define HCI_SUPP_COMMANDS_DISCONNECT_MASK 0x20 -#define HCI_SUPP_COMMANDS_DISCONNECT_OFF 0 -#define HCI_DISCONNECT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_DISCONNECT_OFF] & HCI_SUPP_COMMANDS_DISCONNECT_MASK) - -#define HCI_SUPP_COMMANDS_ADD_SCO_CONN_MASK 0x40 -#define HCI_SUPP_COMMANDS_ADD_SCO_CONN_OFF 0 -#define HCI_ADD_SCO_CONN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ADD_SCO_CONN_OFF] & HCI_SUPP_COMMANDS_ADD_SCO_CONN_MASK) - -#define HCI_SUPP_COMMANDS_CANCEL_CREATE_CONN_MASK 0x80 -#define HCI_SUPP_COMMANDS_CANCEL_CREATE_CONN_OFF 0 -#define HCI_CANCEL_CREATE_CONN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_CANCEL_CREATE_CONN_OFF] & HCI_SUPP_COMMANDS_CANCEL_CREATE_CONN_MASK) - -#define HCI_SUPP_COMMANDS_ACCEPT_CONN_REQUEST_MASK 0x01 -#define HCI_SUPP_COMMANDS_ACCEPT_CONN_REQUEST_OFF 1 -#define HCI_ACCEPT_CONN_REQUEST_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ACCEPT_CONN_REQUEST_OFF] & HCI_SUPP_COMMANDS_ACCEPT_CONN_REQUEST_MASK) - -#define HCI_SUPP_COMMANDS_REJECT_CONN_REQUEST_MASK 0x02 -#define HCI_SUPP_COMMANDS_REJECT_CONN_REQUEST_OFF 1 -#define HCI_REJECT_CONN_REQUEST_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_REJECT_CONN_REQUEST_OFF] & HCI_SUPP_COMMANDS_REJECT_CONN_REQUEST_MASK) - -#define HCI_SUPP_COMMANDS_LINK_KEY_REQUEST_REPLY_MASK 0x04 -#define HCI_SUPP_COMMANDS_LINK_KEY_REQUEST_REPLY_OFF 1 -#define HCI_LINK_KEY_REQUEST_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_LINK_KEY_REQUEST_REPLY_OFF] & HCI_SUPP_COMMANDS_LINK_KEY_REQUEST_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_LINK_KEY_REQUEST_NEG_REPLY_MASK 0x08 -#define HCI_SUPP_COMMANDS_LINK_KEY_REQUEST_NEG_REPLY_OFF 1 -#define HCI_LINK_KEY_REQUEST_NEG_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_LINK_KEY_REQUEST_NEG_REPLY_OFF] & HCI_SUPP_COMMANDS_LINK_KEY_REQUEST_NEG_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_PIN_CODE_REQUEST_REPLY_MASK 0x10 -#define HCI_SUPP_COMMANDS_PIN_CODE_REQUEST_REPLY_OFF 1 -#define HCI_PIN_CODE_REQUEST_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_PIN_CODE_REQUEST_REPLY_OFF] & HCI_SUPP_COMMANDS_PIN_CODE_REQUEST_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_PIN_CODE_REQUEST_NEG_REPLY_MASK 0x20 -#define HCI_SUPP_COMMANDS_PIN_CODE_REQUEST_NEG_REPLY_OFF 1 -#define HCI_PIN_CODE_REQUEST_NEG_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_PIN_CODE_REQUEST_NEG_REPLY_OFF] & HCI_SUPP_COMMANDS_PIN_CODE_REQUEST_NEG_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_CHANGE_CONN_PKT_TYPE_MASK 0x40 -#define HCI_SUPP_COMMANDS_CHANGE_CONN_PKT_TYPE_OFF 1 -#define HCI_CHANGE_CONN_PKT_TYPE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_CHANGE_CONN_PKT_TYPE_OFF] & HCI_SUPP_COMMANDS_CHANGE_CONN_PKT_TYPE_MASK) - -#define HCI_SUPP_COMMANDS_AUTH_REQUEST_MASK 0x80 -#define HCI_SUPP_COMMANDS_AUTH_REQUEST_OFF 1 -#define HCI_AUTH_REQUEST_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_AUTH_REQUEST_OFF] & HCI_SUPP_COMMANDS_AUTH_REQUEST_MASK) - -#define HCI_SUPP_COMMANDS_SET_CONN_ENCRYPTION_MASK 0x01 -#define HCI_SUPP_COMMANDS_SET_CONN_ENCRYPTION_OFF 2 -#define HCI_SET_CONN_ENCRYPTION_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_CONN_ENCRYPTION_OFF] & HCI_SUPP_COMMANDS_SET_CONN_ENCRYPTION_MASK) - -#define HCI_SUPP_COMMANDS_CHANGE_CONN_LINK_KEY_MASK 0x02 -#define HCI_SUPP_COMMANDS_CHANGE_CONN_LINK_KEY_OFF 2 -#define HCI_CHANGE_CONN_LINK_KEY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_CHANGE_CONN_LINK_KEY_OFF] & HCI_SUPP_COMMANDS_CHANGE_CONN_LINK_KEY_MASK) - -#define HCI_SUPP_COMMANDS_MASTER_LINK_KEY_MASK 0x04 -#define HCI_SUPP_COMMANDS_MASTER_LINK_KEY_OFF 2 -#define HCI_MASTER_LINK_KEY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_MASTER_LINK_KEY_OFF] & HCI_SUPP_COMMANDS_MASTER_LINK_KEY_MASK) - -#define HCI_SUPP_COMMANDS_REMOTE_NAME_REQUEST_MASK 0x08 -#define HCI_SUPP_COMMANDS_REMOTE_NAME_REQUEST_OFF 2 -#define HCI_REMOTE_NAME_REQUEST_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_REMOTE_NAME_REQUEST_OFF] & HCI_SUPP_COMMANDS_REMOTE_NAME_REQUEST_MASK) - -#define HCI_SUPP_COMMANDS_CANCEL_REMOTE_NAME_REQUEST_MASK 0x10 -#define HCI_SUPP_COMMANDS_CANCEL_REMOTE_NAME_REQUEST_OFF 2 -#define HCI_CANCEL_REMOTE_NAME_REQUEST_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_CANCEL_REMOTE_NAME_REQUEST_OFF] & HCI_SUPP_COMMANDS_CANCEL_REMOTE_NAME_REQUEST_MASK) - -#define HCI_SUPP_COMMANDS_READ_REMOTE_SUPP_FEATURES_MASK 0x20 -#define HCI_SUPP_COMMANDS_READ_REMOTE_SUPP_FEATURES_OFF 2 -#define HCI_READ_REMOTE_SUPP_FEATURES_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_REMOTE_SUPP_FEATURES_OFF] & HCI_SUPP_COMMANDS_READ_REMOTE_SUPP_FEATURES_MASK) - -#define HCI_SUPP_COMMANDS_READ_REMOTE_EXT_FEATURES_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_REMOTE_EXT_FEATURES_OFF 2 -#define HCI_READ_REMOTE_EXT_FEATURES_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_REMOTE_EXT_FEATURES_OFF] & HCI_SUPP_COMMANDS_READ_REMOTE_EXT_FEATURES_MASK) - -#define HCI_SUPP_COMMANDS_READ_REMOTE_VER_INFO_MASK 0x80 -#define HCI_SUPP_COMMANDS_READ_REMOTE_VER_INFO_OFF 2 -#define HCI_READ_REMOTE_VER_INFO_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_REMOTE_VER_INFO_OFF] & HCI_SUPP_COMMANDS_READ_REMOTE_VER_INFO_MASK) - -#define HCI_SUPP_COMMANDS_READ_CLOCK_OFFSET_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_CLOCK_OFFSET_OFF 3 -#define HCI_READ_CLOCK_OFFSET_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_CLOCK_OFFSET_OFF] & HCI_SUPP_COMMANDS_READ_CLOCK_OFFSET_MASK) - -#define HCI_SUPP_COMMANDS_READ_LMP_HANDLE_MASK 0x02 -#define HCI_SUPP_COMMANDS_READ_LMP_HANDLE_OFF 3 -#define HCI_READ_LMP_HANDLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LMP_HANDLE_OFF] & HCI_SUPP_COMMANDS_READ_LMP_HANDLE_MASK) - -#define HCI_SUPP_COMMANDS_HOLD_MODE_CMD_MASK 0x02 -#define HCI_SUPP_COMMANDS_HOLD_MODE_CMD_OFF 4 -#define HCI_HOLD_MODE_CMD_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_HOLD_MODE_CMD_OFF] & HCI_SUPP_COMMANDS_HOLD_MODE_CMD_MASK) - -#define HCI_SUPP_COMMANDS_SNIFF_MODE_CMD_MASK 0x04 -#define HCI_SUPP_COMMANDS_SNIFF_MODE_CMD_OFF 4 -#define HCI_SNIFF_MODE_CMD_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SNIFF_MODE_CMD_OFF] & HCI_SUPP_COMMANDS_SNIFF_MODE_CMD_MASK) - -#define HCI_SUPP_COMMANDS_EXIT_SNIFF_MODE_MASK 0x08 -#define HCI_SUPP_COMMANDS_EXIT_SNIFF_MODE_OFF 4 -#define HCI_EXIT_SNIFF_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_EXIT_SNIFF_MODE_OFF] & HCI_SUPP_COMMANDS_EXIT_SNIFF_MODE_MASK) - -#define HCI_SUPP_COMMANDS_PARK_STATE_MASK 0x10 -#define HCI_SUPP_COMMANDS_PARK_STATE_OFF 4 -#define HCI_PARK_STATE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_PARK_STATE_OFF] & HCI_SUPP_COMMANDS_PARK_STATE_MASK) - -#define HCI_SUPP_COMMANDS_EXIT_PARK_STATE_MASK 0x20 -#define HCI_SUPP_COMMANDS_EXIT_PARK_STATE_OFF 4 -#define HCI_EXIT_PARK_STATE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_EXIT_PARK_STATE_OFF] & HCI_SUPP_COMMANDS_EXIT_PARK_STATE_MASK) - -#define HCI_SUPP_COMMANDS_QOS_SETUP_MASK 0x40 -#define HCI_SUPP_COMMANDS_QOS_SETUP_OFF 4 -#define HCI_QOS_SETUP_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_QOS_SETUP_OFF] & HCI_SUPP_COMMANDS_QOS_SETUP_MASK) - -#define HCI_SUPP_COMMANDS_ROLE_DISCOVERY_MASK 0x80 -#define HCI_SUPP_COMMANDS_ROLE_DISCOVERY_OFF 4 -#define HCI_ROLE_DISCOVERY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ROLE_DISCOVERY_OFF] & HCI_SUPP_COMMANDS_ROLE_DISCOVERY_MASK) - -#define HCI_SUPP_COMMANDS_SWITCH_ROLE_MASK 0x01 -#define HCI_SUPP_COMMANDS_SWITCH_ROLE_OFF 5 -#define HCI_SWITCH_ROLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SWITCH_ROLE_OFF] & HCI_SUPP_COMMANDS_SWITCH_ROLE_MASK) - -#define HCI_SUPP_COMMANDS_READ_LINK_POLICY_SET_MASK 0x02 -#define HCI_SUPP_COMMANDS_READ_LINK_POLICY_SET_OFF 5 -#define HCI_READ_LINK_POLICY_SET_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LINK_POLICY_SET_OFF] & HCI_SUPP_COMMANDS_READ_LINK_POLICY_SET_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_LINK_POLICY_SET_MASK 0x04 -#define HCI_SUPP_COMMANDS_WRITE_LINK_POLICY_SET_OFF 5 -#define HCI_WRITE_LINK_POLICY_SET_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_LINK_POLICY_SET_OFF] & HCI_SUPP_COMMANDS_WRITE_LINK_POLICY_SET_MASK) - -#define HCI_SUPP_COMMANDS_READ_DEF_LINK_POLICY_SET_MASK 0x08 -#define HCI_SUPP_COMMANDS_READ_DEF_LINK_POLICY_SET_OFF 5 -#define HCI_READ_DEF_LINK_POLICY_SET_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_DEF_LINK_POLICY_SET_OFF] & HCI_SUPP_COMMANDS_READ_DEF_LINK_POLICY_SET_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_DEF_LINK_POLICY_SET_MASK 0x10 -#define HCI_SUPP_COMMANDS_WRITE_DEF_LINK_POLICY_SET_OFF 5 -#define HCI_WRITE_DEF_LINK_POLICY_SET_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_DEF_LINK_POLICY_SET_OFF] & HCI_SUPP_COMMANDS_WRITE_DEF_LINK_POLICY_SET_MASK) - -#define HCI_SUPP_COMMANDS_FLOW_SPECIFICATION_MASK 0x20 -#define HCI_SUPP_COMMANDS_FLOW_SPECIFICATION_OFF 5 -#define HCI_FLOW_SPECIFICATION_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_FLOW_SPECIFICATION_OFF] & HCI_SUPP_COMMANDS_FLOW_SPECIFICATION_MASK) - -#define HCI_SUPP_COMMANDS_SET_EVENT_MASK_MASK 0x40 -#define HCI_SUPP_COMMANDS_SET_EVENT_MASK_OFF 5 -#define HCI_SET_EVENT_MASK_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_EVENT_MASK_OFF] & HCI_SUPP_COMMANDS_SET_EVENT_MASK_MASK) - -#define HCI_SUPP_COMMANDS_RESET_MASK 0x80 -#define HCI_SUPP_COMMANDS_RESET_OFF 5 -#define HCI_RESET_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_RESET_OFF] & HCI_SUPP_COMMANDS_RESET_MASK) - -#define HCI_SUPP_COMMANDS_SET_EVENT_FILTER_MASK 0x01 -#define HCI_SUPP_COMMANDS_SET_EVENT_FILTER_OFF 6 -#define HCI_SET_EVENT_FILTER_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_EVENT_FILTER_OFF] & HCI_SUPP_COMMANDS_SET_EVENT_FILTER_MASK) - -#define HCI_SUPP_COMMANDS_FLUSH_MASK 0x02 -#define HCI_SUPP_COMMANDS_FLUSH_OFF 6 -#define HCI_FLUSH_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_FLUSH_OFF] & HCI_SUPP_COMMANDS_FLUSH_MASK) - -#define HCI_SUPP_COMMANDS_READ_PIN_TYPE_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_PIN_TYPE_OFF 6 -#define HCI_READ_PIN_TYPE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_PIN_TYPE_OFF] & HCI_SUPP_COMMANDS_READ_PIN_TYPE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_PIN_TYPE_MASK 0x08 -#define HCI_SUPP_COMMANDS_WRITE_PIN_TYPE_OFF 6 -#define HCI_WRITE_PIN_TYPE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_PIN_TYPE_OFF] & HCI_SUPP_COMMANDS_WRITE_PIN_TYPE_MASK) - -#define HCI_SUPP_COMMANDS_CREATE_NEW_UNIT_KEY_MASK 0x10 -#define HCI_SUPP_COMMANDS_CREATE_NEW_UNIT_KEY_OFF 6 -#define HCI_CREATE_NEW_UNIT_KEY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_CREATE_NEW_UNIT_KEY_OFF] & HCI_SUPP_COMMANDS_CREATE_NEW_UNIT_KEY_MASK) - -#define HCI_SUPP_COMMANDS_READ_STORED_LINK_KEY_MASK 0x20 -#define HCI_SUPP_COMMANDS_READ_STORED_LINK_KEY_OFF 6 -#define HCI_READ_STORED_LINK_KEY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_STORED_LINK_KEY_OFF] & HCI_SUPP_COMMANDS_READ_STORED_LINK_KEY_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_STORED_LINK_KEY_MASK 0x40 -#define HCI_SUPP_COMMANDS_WRITE_STORED_LINK_KEY_OFF 6 -#define HCI_WRITE_STORED_LINK_KEY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_STORED_LINK_KEY_OFF] & HCI_SUPP_COMMANDS_WRITE_STORED_LINK_KEY_MASK) - -#define HCI_SUPP_COMMANDS_DELETE_STORED_LINK_KEY_MASK 0x80 -#define HCI_SUPP_COMMANDS_DELETE_STORED_LINK_KEY_OFF 6 -#define HCI_DELETE_STORED_LINK_KEY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_DELETE_STORED_LINK_KEY_OFF] & HCI_SUPP_COMMANDS_DELETE_STORED_LINK_KEY_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_LOCAL_NAME_MASK 0x01 -#define HCI_SUPP_COMMANDS_WRITE_LOCAL_NAME_OFF 7 -#define HCI_WRITE_LOCAL_NAME_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_LOCAL_NAME_OFF] & HCI_SUPP_COMMANDS_WRITE_LOCAL_NAME_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_NAME_MASK 0x02 -#define HCI_SUPP_COMMANDS_READ_LOCAL_NAME_OFF 7 -#define HCI_READ_LOCAL_NAME_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_NAME_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_NAME_MASK) - -#define HCI_SUPP_COMMANDS_READ_CONN_ACCEPT_TOUT_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_CONN_ACCEPT_TOUT_OFF 7 -#define HCI_READ_CONN_ACCEPT_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_CONN_ACCEPT_TOUT_OFF] & HCI_SUPP_COMMANDS_READ_CONN_ACCEPT_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_CONN_ACCEPT_TOUT_MASK 0x08 -#define HCI_SUPP_COMMANDS_WRITE_CONN_ACCEPT_TOUT_OFF 7 -#define HCI_WRITE_CONN_ACCEPT_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_CONN_ACCEPT_TOUT_OFF] & HCI_SUPP_COMMANDS_WRITE_CONN_ACCEPT_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_READ_PAGE_TOUT_MASK 0x10 -#define HCI_SUPP_COMMANDS_READ_PAGE_TOUT_OFF 7 -#define HCI_READ_PAGE_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_PAGE_TOUT_OFF] & HCI_SUPP_COMMANDS_READ_PAGE_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_PAGE_TOUT_MASK 0x20 -#define HCI_SUPP_COMMANDS_WRITE_PAGE_TOUT_OFF 7 -#define HCI_WRITE_PAGE_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_PAGE_TOUT_OFF] & HCI_SUPP_COMMANDS_WRITE_PAGE_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_READ_SCAN_ENABLE_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_SCAN_ENABLE_OFF 7 -#define HCI_READ_SCAN_ENABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_SCAN_ENABLE_OFF] & HCI_SUPP_COMMANDS_READ_SCAN_ENABLE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_SCAN_ENABLE_MASK 0x80 -#define HCI_SUPP_COMMANDS_WRITE_SCAN_ENABLE_OFF 7 -#define HCI_WRITE_SCAN_ENABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_SCAN_ENABLE_OFF] & HCI_SUPP_COMMANDS_WRITE_SCAN_ENABLE_MASK) - -#define HCI_SUPP_COMMANDS_READ_PAGE_SCAN_ACTIVITY_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_PAGE_SCAN_ACTIVITY_OFF 8 -#define HCI_READ_PAGE_SCAN_ACTIVITY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_PAGE_SCAN_ACTIVITY_OFF] & HCI_SUPP_COMMANDS_READ_PAGE_SCAN_ACTIVITY_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_ACTIVITY_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_ACTIVITY_OFF 8 -#define HCI_WRITE_PAGE_SCAN_ACTIVITY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_ACTIVITY_OFF] & HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_ACTIVITY_MASK) - -#define HCI_SUPP_COMMANDS_READ_INQURIY_SCAN_ACTIVITY_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_INQURIY_SCAN_ACTIVITY_OFF 8 -#define HCI_READ_INQURIY_SCAN_ACTIVITY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_INQURIY_SCAN_ACTIVITY_OFF] & HCI_SUPP_COMMANDS_READ_INQURIY_SCAN_ACTIVITY_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_INQURIY_SCAN_ACTIVITY_MASK 0x08 -#define HCI_SUPP_COMMANDS_WRITE_INQURIY_SCAN_ACTIVITY_OFF 8 -#define HCI_WRITE_INQURIY_SCAN_ACTIVITY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_INQURIY_SCAN_ACTIVITY_OFF] & HCI_SUPP_COMMANDS_WRITE_INQURIY_SCAN_ACTIVITY_MASK) - -#define HCI_SUPP_COMMANDS_READ_AUTH_ENABLE_MASK 0x10 -#define HCI_SUPP_COMMANDS_READ_AUTH_ENABLE_OFF 8 -#define HCI_READ_AUTH_ENABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_AUTH_ENABLE_OFF] & HCI_SUPP_COMMANDS_READ_AUTH_ENABLE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_AUTH_ENABLE_MASK 0x20 -#define HCI_SUPP_COMMANDS_WRITE_AUTH_ENABLE_OFF 8 -#define HCI_WRITE_AUTH_ENABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_AUTH_ENABLE_OFF] & HCI_SUPP_COMMANDS_WRITE_AUTH_ENABLE_MASK) - -#define HCI_SUPP_COMMANDS_READ_ENCRYPT_ENABLE_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_ENCRYPT_ENABLE_OFF 8 -#define HCI_READ_ENCRYPT_ENABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_ENCRYPT_ENABLE_OFF] & HCI_SUPP_COMMANDS_READ_ENCRYPT_ENABLE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_ENCRYPT_ENABLE_MASK 0x80 -#define HCI_SUPP_COMMANDS_WRITE_ENCRYPT_ENABLE_OFF 8 -#define HCI_WRITE_ENCRYPT_ENABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_ENCRYPT_ENABLE_OFF] & HCI_SUPP_COMMANDS_WRITE_ENCRYPT_ENABLE_MASK) - -#define HCI_SUPP_COMMANDS_READ_CLASS_DEVICE_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_CLASS_DEVICE_OFF 9 -#define HCI_READ_CLASS_DEVICE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_CLASS_DEVICE_OFF] & HCI_SUPP_COMMANDS_READ_CLASS_DEVICE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_CLASS_DEVICE_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_CLASS_DEVICE_OFF 9 -#define HCI_WRITE_CLASS_DEVICE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_CLASS_DEVICE_OFF] & HCI_SUPP_COMMANDS_WRITE_CLASS_DEVICE_MASK) - -#define HCI_SUPP_COMMANDS_READ_VOICE_SETTING_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_VOICE_SETTING_OFF 9 -#define HCI_READ_VOICE_SETTING_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_VOICE_SETTING_OFF] & HCI_SUPP_COMMANDS_READ_VOICE_SETTING_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_VOICE_SETTING_MASK 0x08 -#define HCI_SUPP_COMMANDS_WRITE_VOICE_SETTING_OFF 9 -#define HCI_WRITE_VOICE_SETTING_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_VOICE_SETTING_OFF] & HCI_SUPP_COMMANDS_WRITE_VOICE_SETTING_MASK) - -#define HCI_SUPP_COMMANDS_READ_AUTO_FLUSH_TOUT_MASK 0x10 -#define HCI_SUPP_COMMANDS_READ_AUTO_FLUSH_TOUT_OFF 9 -#define HCI_READ_AUTO_FLUSH_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_AUTO_FLUSH_TOUT_OFF] & HCI_SUPP_COMMANDS_READ_AUTO_FLUSH_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_AUTO_FLUSH_TOUT_MASK 0x20 -#define HCI_SUPP_COMMANDS_WRITE_AUTO_FLUSH_TOUT_OFF 9 -#define HCI_WRITE_AUTO_FLUSH_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_AUTO_FLUSH_TOUT_OFF] & HCI_SUPP_COMMANDS_WRITE_AUTO_FLUSH_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_READ_NUM_BROAD_RETRANS_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_NUM_BROAD_RETRANS_OFF 9 -#define HCI_READ_NUM_BROAD_RETRANS_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_NUM_BROAD_RETRANS_OFF] & HCI_SUPP_COMMANDS_READ_NUM_BROAD_RETRANS_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_NUM_BROAD_RETRANS_MASK 0x80 -#define HCI_SUPP_COMMANDS_WRITE_NUM_BROAD_RETRANS_OFF 9 -#define HCI_WRITE_NUM_BROAD_RETRANS_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_NUM_BROAD_RETRANS_OFF] & HCI_SUPP_COMMANDS_WRITE_NUM_BROAD_RETRANS_MASK) - -#define HCI_SUPP_COMMANDS_READ_HOLD_MODE_ACTIVITY_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_HOLD_MODE_ACTIVITY_OFF 10 -#define HCI_READ_HOLD_MODE_ACTIVITY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_HOLD_MODE_ACTIVITY_OFF] & HCI_SUPP_COMMANDS_READ_HOLD_MODE_ACTIVITY_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_HOLD_MODE_ACTIVITY_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_HOLD_MODE_ACTIVITY_OFF 10 -#define HCI_WRITE_HOLD_MODE_ACTIVITY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_HOLD_MODE_ACTIVITY_OFF] & HCI_SUPP_COMMANDS_WRITE_HOLD_MODE_ACTIVITY_MASK) - -#define HCI_SUPP_COMMANDS_READ_TRANS_PWR_LEVEL_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_TRANS_PWR_LEVEL_OFF 10 -#define HCI_READ_TRANS_PWR_LEVEL_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_TRANS_PWR_LEVEL_OFF] & HCI_SUPP_COMMANDS_READ_TRANS_PWR_LEVEL_MASK) - -#define HCI_SUPP_COMMANDS_READ_SYNCH_FLOW_CTRL_ENABLE_MASK 0x08 -#define HCI_SUPP_COMMANDS_READ_SYNCH_FLOW_CTRL_ENABLE_OFF 10 -#define HCI_READ_SYNCH_FLOW_CTRL_ENABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_SYNCH_FLOW_CTRL_ENABLE_OFF] & HCI_SUPP_COMMANDS_READ_SYNCH_FLOW_CTRL_ENABLE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_SYNCH_FLOW_CTRL_ENABLE_MASK 0x10 -#define HCI_SUPP_COMMANDS_WRITE_SYNCH_FLOW_CTRL_ENABLE_OFF 10 -#define HCI_WRITE_SYNCH_FLOW_CTRL_ENABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_SYNCH_FLOW_CTRL_ENABLE_OFF] & HCI_SUPP_COMMANDS_WRITE_SYNCH_FLOW_CTRL_ENABLE_MASK) - -#define HCI_SUPP_COMMANDS_SET_HOST_CTRLR_TO_HOST_FC_MASK 0x20 -#define HCI_SUPP_COMMANDS_SET_HOST_CTRLR_TO_HOST_FC_OFF 10 -#define HCI_SET_HOST_CTRLR_TO_HOST_FC_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_HOST_CTRLR_TO_HOST_FC_OFF] & HCI_SUPP_COMMANDS_SET_HOST_CTRLR_TO_HOST_FC_MASK) - -#define HCI_SUPP_COMMANDS_HOST_BUFFER_SIZE_MASK 0x40 -#define HCI_SUPP_COMMANDS_HOST_BUFFER_SIZE_OFF 10 -#define HCI_HOST_BUFFER_SIZE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_HOST_BUFFER_SIZE_OFF] & HCI_SUPP_COMMANDS_HOST_BUFFER_SIZE_MASK) - -#define HCI_SUPP_COMMANDS_HOST_NUM_COMPLETED_PKTS_MASK 0x80 -#define HCI_SUPP_COMMANDS_HOST_NUM_COMPLETED_PKTS_OFF 10 -#define HCI_HOST_NUM_COMPLETED_PKTS_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_HOST_NUM_COMPLETED_PKTS_OFF] & HCI_SUPP_COMMANDS_HOST_NUM_COMPLETED_PKTS_MASK) - -#define HCI_SUPP_COMMANDS_READ_LINK_SUP_TOUT_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_LINK_SUP_TOUT_OFF 11 -#define HCI_READ_LINK_SUP_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LINK_SUP_TOUT_OFF] & HCI_SUPP_COMMANDS_READ_LINK_SUP_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_LINK_SUP_TOUT_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_LINK_SUP_TOUT_OFF 11 -#define HCI_WRITE_LINK_SUP_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_LINK_SUP_TOUT_OFF] & HCI_SUPP_COMMANDS_WRITE_LINK_SUP_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_READ_NUM_SUPP_IAC_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_NUM_SUPP_IAC_OFF 11 -#define HCI_READ_NUM_SUPP_IAC_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_NUM_SUPP_IAC_OFF] & HCI_SUPP_COMMANDS_READ_NUM_SUPP_IAC_MASK) - -#define HCI_SUPP_COMMANDS_READ_CURRENT_IAC_LAP_MASK 0x08 -#define HCI_SUPP_COMMANDS_READ_CURRENT_IAC_LAP_OFF 11 -#define HCI_READ_CURRENT_IAC_LAP_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_CURRENT_IAC_LAP_OFF] & HCI_SUPP_COMMANDS_READ_CURRENT_IAC_LAP_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_CURRENT_IAC_LAP_MASK 0x10 -#define HCI_SUPP_COMMANDS_WRITE_CURRENT_IAC_LAP_OFF 11 -#define HCI_WRITE_CURRENT_IAC_LAP_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_CURRENT_IAC_LAP_OFF] & HCI_SUPP_COMMANDS_WRITE_CURRENT_IAC_LAP_MASK) - -#define HCI_SUPP_COMMANDS_READ_PAGE_SCAN_PER_MODE_MASK 0x20 -#define HCI_SUPP_COMMANDS_READ_PAGE_SCAN_PER_MODE_OFF 11 -#define HCI_READ_PAGE_SCAN_PER_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_PAGE_SCAN_PER_MODE_OFF] & HCI_SUPP_COMMANDS_READ_PAGE_SCAN_PER_MODE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_PER_MODE_MASK 0x40 -#define HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_PER_MODE_OFF 11 -#define HCI_WRITE_PAGE_SCAN_PER_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_PER_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_PER_MODE_MASK) - -#define HCI_SUPP_COMMANDS_READ_PAGE_SCAN_MODE_MASK 0x80 -#define HCI_SUPP_COMMANDS_READ_PAGE_SCAN_MODE_OFF 11 -#define HCI_READ_PAGE_SCAN_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_PAGE_SCAN_MODE_OFF] & HCI_SUPP_COMMANDS_READ_PAGE_SCAN_MODE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_MODE_MASK 0x01 -#define HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_MODE_OFF 12 -#define HCI_WRITE_PAGE_SCAN_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_MODE_MASK) - -#define HCI_SUPP_COMMANDS_SET_AFH_CHNL_CLASS_MASK 0x02 -#define HCI_SUPP_COMMANDS_SET_AFH_CHNL_CLASS_OFF 12 -#define HCI_SET_AFH_CHNL_CLASS_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_AFH_CHNL_CLASS_OFF] & HCI_SUPP_COMMANDS_SET_AFH_CHNL_CLASS_MASK) - -#define HCI_SUPP_COMMANDS_READ_INQUIRY_SCAN_TYPE_MASK 0x10 -#define HCI_SUPP_COMMANDS_READ_INQUIRY_SCAN_TYPE_OFF 12 -#define HCI_READ_INQUIRY_SCAN_TYPE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_INQUIRY_SCAN_TYPE_OFF] & HCI_SUPP_COMMANDS_READ_INQUIRY_SCAN_TYPE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_INQUIRY_SCAN_TYPE_MASK 0x20 -#define HCI_SUPP_COMMANDS_WRITE_INQUIRY_SCAN_TYPE_OFF 12 -#define HCI_WRITE_INQUIRY_SCAN_TYPE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_INQUIRY_SCAN_TYPE_OFF] & HCI_SUPP_COMMANDS_WRITE_INQUIRY_SCAN_TYPE_MASK) - -#define HCI_SUPP_COMMANDS_READ_INQUIRY_MODE_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_INQUIRY_MODE_OFF 12 -#define HCI_READ_INQUIRY_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_INQUIRY_MODE_OFF] & HCI_SUPP_COMMANDS_READ_INQUIRY_MODE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_INQUIRY_MODE_MASK 0x80 -#define HCI_SUPP_COMMANDS_WRITE_INQUIRY_MODE_OFF 12 -#define HCI_WRITE_INQUIRY_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_INQUIRY_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_INQUIRY_MODE_MASK) - -#define HCI_SUPP_COMMANDS_READ_PAGE_SCAN_TYPE_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_PAGE_SCAN_TYPE_OFF 13 -#define HCI_READ_PAGE_SCAN_TYPE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_PAGE_SCAN_TYPE_OFF] & HCI_SUPP_COMMANDS_READ_PAGE_SCAN_TYPE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_TYPE_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_TYPE_OFF 13 -#define HCI_WRITE_PAGE_SCAN_TYPE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_TYPE_OFF] & HCI_SUPP_COMMANDS_WRITE_PAGE_SCAN_TYPE_MASK) - -#define HCI_SUPP_COMMANDS_READ_AFH_CHNL_ASSESS_MODE_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_AFH_CHNL_ASSESS_MODE_OFF 13 -#define HCI_READ_AFH_CHNL_ASSESS_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_AFH_CHNL_ASSESS_MODE_OFF] & HCI_SUPP_COMMANDS_READ_AFH_CHNL_ASSESS_MODE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_AFH_CHNL_ASSESS_MODE_MASK 0x08 -#define HCI_SUPP_COMMANDS_WRITE_AFH_CHNL_ASSESS_MODE_OFF 13 -#define HCI_WRITE_AFH_CHNL_ASSESS_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_AFH_CHNL_ASSESS_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_AFH_CHNL_ASSESS_MODE_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_VER_INFO_MASK 0x08 -#define HCI_SUPP_COMMANDS_READ_LOCAL_VER_INFO_OFF 14 -#define HCI_READ_LOCAL_VER_INFO_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_VER_INFO_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_VER_INFO_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_SUP_CMDS_MASK 0x10 -#define HCI_SUPP_COMMANDS_READ_LOCAL_SUP_CMDS_OFF 14 -#define HCI_READ_LOCAL_SUP_CMDS_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_SUP_CMDS_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_SUP_CMDS_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_SUPP_FEATURES_MASK 0x20 -#define HCI_SUPP_COMMANDS_READ_LOCAL_SUPP_FEATURES_OFF 14 -#define HCI_READ_LOCAL_SUPP_FEATURES_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_SUPP_FEATURES_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_SUPP_FEATURES_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_EXT_FEATURES_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_LOCAL_EXT_FEATURES_OFF 14 -#define HCI_READ_LOCAL_EXT_FEATURES_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_EXT_FEATURES_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_EXT_FEATURES_MASK) - -#define HCI_SUPP_COMMANDS_READ_BUFFER_SIZE_MASK 0x80 -#define HCI_SUPP_COMMANDS_READ_BUFFER_SIZE_OFF 14 -#define HCI_READ_BUFFER_SIZE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_BUFFER_SIZE_OFF] & HCI_SUPP_COMMANDS_READ_BUFFER_SIZE_MASK) - -#define HCI_SUPP_COMMANDS_READ_COUNTRY_CODE_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_COUNTRY_CODE_OFF 15 -#define HCI_READ_COUNTRY_CODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_COUNTRY_CODE_OFF] & HCI_SUPP_COMMANDS_READ_COUNTRY_CODE_MASK) - -#define HCI_SUPP_COMMANDS_READ_BD_ADDR_MASK 0x02 -#define HCI_SUPP_COMMANDS_READ_BD_ADDR_OFF 15 -#define HCI_READ_BD_ADDR_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_BD_ADDR_OFF] & HCI_SUPP_COMMANDS_READ_BD_ADDR_MASK) - -#define HCI_SUPP_COMMANDS_READ_FAIL_CONTACT_CNTR_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_FAIL_CONTACT_CNTR_OFF 15 -#define HCI_READ_FAIL_CONTACT_CNTR_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_FAIL_CONTACT_CNTR_OFF] & HCI_SUPP_COMMANDS_READ_FAIL_CONTACT_CNTR_MASK) - -#define HCI_SUPP_COMMANDS_RESET_FAIL_CONTACT_CNTR_MASK 0x08 -#define HCI_SUPP_COMMANDS_RESET_FAIL_CONTACT_CNTR_OFF 15 -#define HCI_RESET_FAIL_CONTACT_CNTR_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_RESET_FAIL_CONTACT_CNTR_OFF] & HCI_SUPP_COMMANDS_RESET_FAIL_CONTACT_CNTR_MASK) - -#define HCI_SUPP_COMMANDS_GET_LINK_QUALITY_MASK 0x10 -#define HCI_SUPP_COMMANDS_GET_LINK_QUALITY_OFF 15 -#define HCI_GET_LINK_QUALITY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_GET_LINK_QUALITY_OFF] & HCI_SUPP_COMMANDS_GET_LINK_QUALITY_MASK) - -#define HCI_SUPP_COMMANDS_READ_RSSI_MASK 0x20 -#define HCI_SUPP_COMMANDS_READ_RSSI_OFF 15 -#define HCI_READ_RSSI_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_RSSI_OFF] & HCI_SUPP_COMMANDS_READ_RSSI_MASK) - -#define HCI_SUPP_COMMANDS_READ_AFH_CH_MAP_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_AFH_CH_MAP_OFF 15 -#define HCI_READ_AFH_CH_MAP_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_AFH_CH_MAP_OFF] & HCI_SUPP_COMMANDS_READ_AFH_CH_MAP_MASK) - -#define HCI_SUPP_COMMANDS_READ_BD_CLOCK_MASK 0x80 -#define HCI_SUPP_COMMANDS_READ_BD_CLOCK_OFF 15 -#define HCI_READ_BD_CLOCK_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_BD_CLOCK_OFF] & HCI_SUPP_COMMANDS_READ_BD_CLOCK_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOOPBACK_MODE_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_LOOPBACK_MODE_OFF 16 -#define HCI_READ_LOOPBACK_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOOPBACK_MODE_OFF] & HCI_SUPP_COMMANDS_READ_LOOPBACK_MODE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_LOOPBACK_MODE_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_LOOPBACK_MODE_OFF 16 -#define HCI_WRITE_LOOPBACK_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_LOOPBACK_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_LOOPBACK_MODE_MASK) - -#define HCI_SUPP_COMMANDS_ENABLE_DEV_UNDER_TEST_MASK 0x04 -#define HCI_SUPP_COMMANDS_ENABLE_DEV_UNDER_TEST_OFF 16 -#define HCI_ENABLE_DEV_UNDER_TEST_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ENABLE_DEV_UNDER_TEST_OFF] & HCI_SUPP_COMMANDS_ENABLE_DEV_UNDER_TEST_MASK) - -#define HCI_SUPP_COMMANDS_SETUP_SYNCH_CONN_MASK 0x08 -#define HCI_SUPP_COMMANDS_SETUP_SYNCH_CONN_OFF 16 -#define HCI_SETUP_SYNCH_CONN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SETUP_SYNCH_CONN_OFF] & HCI_SUPP_COMMANDS_SETUP_SYNCH_CONN_MASK) - -#define HCI_SUPP_COMMANDS_ACCEPT_SYNCH_CONN_MASK 0x10 -#define HCI_SUPP_COMMANDS_ACCEPT_SYNCH_CONN_OFF 16 -#define HCI_ACCEPT_SYNCH_CONN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ACCEPT_SYNCH_CONN_OFF] & HCI_SUPP_COMMANDS_ACCEPT_SYNCH_CONN_MASK) - -#define HCI_SUPP_COMMANDS_REJECT_SYNCH_CONN_MASK 0x20 -#define HCI_SUPP_COMMANDS_REJECT_SYNCH_CONN_OFF 16 -#define HCI_REJECT_SYNCH_CONN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_REJECT_SYNCH_CONN_OFF] & HCI_SUPP_COMMANDS_REJECT_SYNCH_CONN_MASK) - -#define HCI_SUPP_COMMANDS_READ_EXT_INQUIRY_RESP_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_EXT_INQUIRY_RESP_OFF 17 -#define HCI_READ_EXT_INQUIRY_RESP_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_EXT_INQUIRY_RESP_OFF] & HCI_SUPP_COMMANDS_READ_EXT_INQUIRY_RESP_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_EXT_INQUIRY_RESP_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_EXT_INQUIRY_RESP_OFF 17 -#define HCI_WRITE_EXT_INQUIRY_RESP_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_EXT_INQUIRY_RESP_OFF] & HCI_SUPP_COMMANDS_WRITE_EXT_INQUIRY_RESP_MASK) - -#define HCI_SUPP_COMMANDS_REFRESH_ENCRYPTION_KEY_MASK 0x04 -#define HCI_SUPP_COMMANDS_REFRESH_ENCRYPTION_KEY_OFF 17 -#define HCI_REFRESH_ENCRYPTION_KEY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_REFRESH_ENCRYPTION_KEY_OFF] & HCI_SUPP_COMMANDS_REFRESH_ENCRYPTION_KEY_MASK) - -/* Octet 17, bit 3 is reserved */ - -#define HCI_SUPP_COMMANDS_SNIFF_SUB_RATE_MASK 0x10 -#define HCI_SUPP_COMMANDS_SNIFF_SUB_RATE_OFF 17 -#define HCI_SNIFF_SUB_RATE_CMD_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SNIFF_SUB_RATE_OFF] & HCI_SUPP_COMMANDS_SNIFF_SUB_RATE_MASK) - -#define HCI_SUPP_COMMANDS_READ_SIMPLE_PAIRING_MODE_MASK 0x20 -#define HCI_SUPP_COMMANDS_READ_SIMPLE_PAIRING_MODE_OFF 17 -#define HCI_READ_SIMPLE_PAIRING_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_SIMPLE_PAIRING_MODE_OFF] & HCI_SUPP_COMMANDS_READ_SIMPLE_PAIRING_MODE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_SIMPLE_PAIRING_MODE_MASK 0x40 -#define HCI_SUPP_COMMANDS_WRITE_SIMPLE_PAIRING_MODE_OFF 17 -#define HCI_WRITE_SIMPLE_PAIRING_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_SIMPLE_PAIRING_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_SIMPLE_PAIRING_MODE_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_OOB_DATA_MASK 0x80 -#define HCI_SUPP_COMMANDS_READ_LOCAL_OOB_DATA_OFF 17 -#define HCI_READ_LOCAL_OOB_DATA_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_OOB_DATA_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_OOB_DATA_MASK) - -#define HCI_SUPP_COMMANDS_READ_INQUIRY_RESPONSE_TX_POWER_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_INQUIRY_RESPONSE_TX_POWER_OFF 18 -#define HCI_READ_INQUIRY_RESPONSE_TX_POWER_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_INQUIRY_RESPONSE_TX_POWER_OFF] & HCI_SUPP_COMMANDS_READ_INQUIRY_RESPONSE_TX_POWER_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_INQUIRY_RESPONSE_TX_POWER_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_INQUIRY_RESPONSE_TX_POWER_OFF 18 -#define HCI_WRITE_INQUIRY_RESPONSE_TX_POWER_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_INQUIRY_RESPONSE_TX_POWER_OFF] & HCI_SUPP_COMMANDS_WRITE_INQUIRY_RESPONSE_TX_POWER_MASK) - -#define HCI_SUPP_COMMANDS_READ_DEFAULT_ERRONEOUS_DATA_REPORTING_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_DEFAULT_ERRONEOUS_DATA_REPORTING_OFF 18 -#define HCI_READ_DEFAULT_ERRONEOUS_DATA_REPORTING_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_DEFAULT_ERRONEOUS_DATA_REPORTING_OFF] & HCI_SUPP_COMMANDS_READ_DEFAULT_ERRONEOUS_DATA_REPORTING_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING_MASK 0x08 -#define HCI_SUPP_COMMANDS_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING_OFF 18 -#define HCI_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING_OFF] & HCI_SUPP_COMMANDS_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING_MASK) - -#define HCI_SUPP_COMMANDS_IO_CAPABILITY_REQUEST_REPLY_MASK 0x80 -#define HCI_SUPP_COMMANDS_IO_CAPABILITY_REQUEST_REPLY_OFF 18 -#define HCI_IO_CAPABILITY_REQUEST_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_IO_CAPABILITY_REQUEST_REPLY_OFF] & HCI_SUPP_COMMANDS_IO_CAPABILITY_REQUEST_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_USER_CONFIRMATION_REQUEST_REPLY_MASK 0x01 -#define HCI_SUPP_COMMANDS_USER_CONFIRMATION_REQUEST_REPLY_OFF 19 -#define HCI_USER_CONFIRMATION_REQUEST_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_USER_CONFIRMATION_REQUEST_REPLY_OFF] & HCI_SUPP_COMMANDS_USER_CONFIRMATION_REQUEST_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_USER_CONFIRMATION_REQUEST_NEG_REPLY_MASK 0x02 -#define HCI_SUPP_COMMANDS_USER_CONFIRMATION_REQUEST_NEG_REPLY_OFF 19 -#define HCI_USER_CONFIRMATION_REQUEST_NEG_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_USER_CONFIRMATION_REQUEST_NEG_REPLY_OFF] & HCI_SUPP_COMMANDS_USER_CONFIRMATION_REQUEST_NEG_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_USER_PASSKEY_REQUEST_REPLY_MASK 0x04 -#define HCI_SUPP_COMMANDS_USER_PASSKEY_REQUEST_REPLY_OFF 19 -#define HCI_USER_PASSKEY_REQUEST_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_USER_PASSKEY_REQUEST_REPLY_OFF] & HCI_SUPP_COMMANDS_USER_PASSKEY_REQUEST_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_USER_PASSKEY_REQUEST_NEG_REPLY_MASK 0x08 -#define HCI_SUPP_COMMANDS_USER_PASSKEY_REQUEST_NEG_REPLY_OFF 19 -#define HCI_USER_PASSKEY_REQUEST_NEG_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_USER_PASSKEY_REQUEST_NEG_REPLY_OFF] & HCI_SUPP_COMMANDS_USER_PASSKEY_REQUEST_NEG_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_REMOTE_OOB_DATA_REQUEST_REPLY_MASK 0x10 -#define HCI_SUPP_COMMANDS_REMOTE_OOB_DATA_REQUEST_REPLY_OFF 19 -#define HCI_REMOTE_OOB_DATA_REQUEST_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_REMOTE_OOB_DATA_REQUEST_REPLY_OFF] & HCI_SUPP_COMMANDS_REMOTE_OOB_DATA_REQUEST_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_SIMPLE_PAIRING_DBG_MODE_MASK 0x20 -#define HCI_SUPP_COMMANDS_WRITE_SIMPLE_PAIRING_DBG_MODE_OFF 19 -#define HCI_WRITE_SIMPLE_PAIRING_DBG_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_SIMPLE_PAIRING_DBG_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_SIMPLE_PAIRING_DBG_MODE_MASK) - -#define HCI_SUPP_COMMANDS_ENHANCED_FLUSH_MASK 0x40 -#define HCI_SUPP_COMMANDS_ENHANCED_FLUSH_OFF 19 -#define HCI_ENHANCED_FLUSH_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ENHANCED_FLUSH_OFF] & HCI_SUPP_COMMANDS_ENHANCED_FLUSH_MASK) - -#define HCI_SUPP_COMMANDS_REMOTE_OOB_DATA_REQUEST_NEG_REPLY_MASK 0x80 -#define HCI_SUPP_COMMANDS_REMOTE_OOB_DATA_REQUEST_NEG_REPLY_OFF 19 -#define HCI_REMOTE_OOB_DATA_REQUEST_NEG_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_REMOTE_OOB_DATA_REQUEST_NEG_REPLY_OFF] & HCI_SUPP_COMMANDS_REMOTE_OOB_DATA_REQUEST_NEG_REPLY_MASK) - -/* Supported Commands (Byte 20) */ -#define HCI_SUPP_COMMANDS_SEND_KEYPRESS_NOTIF_MASK 0x04 -#define HCI_SUPP_COMMANDS_SEND_KEYPRESS_NOTIF_OFF 20 -#define HCI_SEND_NOTIF_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SEND_KEYPRESS_NOTIF_OFF] & HCI_SUPP_COMMANDS_SEND_KEYPRESS_NOTIF_MASK) - -#define HCI_SUPP_COMMANDS_IO_CAP_REQ_NEG_REPLY_MASK 0x08 -#define HCI_SUPP_COMMANDS_IO_CAP_REQ_NEG_REPLY_OFF 20 -#define HCI_IO_CAP_REQ_NEG_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_IO_CAP_REQ_NEG_REPLY_OFF] & HCI_SUPP_COMMANDS_IO_CAP_REQ_NEG_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_READ_ENCR_KEY_SIZE_MASK 0x10 -#define HCI_SUPP_COMMANDS_READ_ENCR_KEY_SIZE_OFF 20 -#define HCI_READ_ENCR_KEY_SIZE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_ENCR_KEY_SIZE_OFF] & HCI_SUPP_COMMANDS_READ_ENCR_KEY_SIZE_MASK) - -/* Supported Commands (Byte 21) */ -#define HCI_SUPP_COMMANDS_CREATE_PHYSICAL_LINK_MASK 0x01 -#define HCI_SUPP_COMMANDS_CREATE_PHYSICAL_LINK_OFF 21 -#define HCI_CREATE_PHYSICAL_LINK_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_CREATE_PHYSICAL_LINK_OFF] & HCI_SUPP_COMMANDS_CREATE_PHYSICAL_LINK_MASK) - -#define HCI_SUPP_COMMANDS_ACCEPT_PHYSICAL_LINK_MASK 0x02 -#define HCI_SUPP_COMMANDS_ACCEPT_PHYSICAL_LINK_OFF 21 -#define HCI_ACCEPT_PHYSICAL_LINK_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ACCEPT_PHYSICAL_LINK_OFF] & HCI_SUPP_COMMANDS_ACCEPT_PHYSICAL_LINK_MASK) - -#define HCI_SUPP_COMMANDS_DISCONNECT_PHYSICAL_LINK_MASK 0x04 -#define HCI_SUPP_COMMANDS_DISCONNECT_PHYSICAL_LINK_OFF 21 -#define HCI_DISCONNECT_PHYSICAL_LINK_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_DISCONNECT_PHYSICAL_LINK_OFF] & HCI_SUPP_COMMANDS_DISCONNECT_PHYSICAL_LINK_MASK) - -#define HCI_SUPP_COMMANDS_CREATE_LOGICAL_LINK_MASK 0x08 -#define HCI_SUPP_COMMANDS_CREATE_LOGICAL_LINK_OFF 21 -#define HCI_CREATE_LOGICAL_LINK_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_CREATE_LOGICAL_LINK_OFF] & HCI_SUPP_COMMANDS_CREATE_LOGICAL_LINK_MASK) - -#define HCI_SUPP_COMMANDS_ACCEPT_LOGICAL_LINK_MASK 0x10 -#define HCI_SUPP_COMMANDS_ACCEPT_LOGICAL_LINK_OFF 21 -#define HCI_ACCEPT_LOGICAL_LINK_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ACCEPT_LOGICAL_LINK_OFF] & HCI_SUPP_COMMANDS_ACCEPT_LOGICAL_LINK_MASK) - -#define HCI_SUPP_COMMANDS_DISCONNECT_LOGICAL_LINK_MASK 0x20 -#define HCI_SUPP_COMMANDS_DISCONNECT_LOGICAL_LINK_OFF 21 -#define HCI_DISCONNECT_LOGICAL_LINK_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_DISCONNECT_LOGICAL_LINK_OFF] & HCI_SUPP_COMMANDS_DISCONNECT_LOGICAL_LINK_MASK) - -#define HCI_SUPP_COMMANDS_LOGICAL_LINK_CANCEL_MASK 0x40 -#define HCI_SUPP_COMMANDS_LOGICAL_LINK_CANCEL_OFF 21 -#define HCI_LOGICAL_LINK_CANCEL_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_LOGICAL_LINK_CANCEL_OFF] & HCI_SUPP_COMMANDS_LOGICAL_LINK_CANCEL_MASK) - -#define HCI_SUPP_COMMANDS_FLOW_SPEC_MODIFY_MASK 0x80 -#define HCI_SUPP_COMMANDS_FLOW_SPEC_MODIFY_OFF 21 -#define HCI_FLOW_SPEC_MODIFY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_FLOW_SPEC_MODIFY_OFF] & HCI_SUPP_COMMANDS_FLOW_SPEC_MODIFY_MASK) - -/* Supported Commands (Byte 22) */ -#define HCI_SUPP_COMMANDS_READ_LOGICAL_LINK_ACCEPT_TIMEOUT_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_LOGICAL_LINK_ACCEPT_TIMEOUT_OFF 22 -#define HCI_READ_LOGICAL_LINK_ACCEPT_TIMEOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOGICAL_LINK_ACCEPT_TIMEOUT_OFF] & HCI_SUPP_COMMANDS_READ_LOGICAL_LINK_ACCEPT_TIMEOUT_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT_OFF 22 -#define HCI_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT_OFF] & HCI_SUPP_COMMANDS_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT_MASK) - -#define HCI_SUPP_COMMANDS_SET_EVENT_MASK_PAGE_2_MASK 0x04 -#define HCI_SUPP_COMMANDS_SET_EVENT_MASK_PAGE_2_OFF 22 -#define HCI_SET_EVENT_MASK_PAGE_2_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_EVENT_MASK_PAGE_2_OFF] & HCI_SUPP_COMMANDS_SET_EVENT_MASK_PAGE_2_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCATION_DATA_MASK 0x08 -#define HCI_SUPP_COMMANDS_READ_LOCATION_DATA_OFF 22 -#define HCI_READ_LOCATION_DATA_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCATION_DATA_OFF] & HCI_SUPP_COMMANDS_READ_LOCATION_DATA_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_LOCATION_DATA_MASK 0x10 -#define HCI_SUPP_COMMANDS_WRITE_LOCATION_DATA_OFF 22 -#define HCI_WRITE_LOCATION_DATA_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_LOCATION_DATA_OFF] & HCI_SUPP_COMMANDS_WRITE_LOCATION_DATA_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_AMP_INFO_MASK 0x20 -#define HCI_SUPP_COMMANDS_READ_LOCAL_AMP_INFO_OFF 22 -#define HCI_READ_LOCAL_AMP_INFO_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_AMP_INFO_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_AMP_INFO_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_AMP_ASSOC_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_LOCAL_AMP_ASSOC_OFF 22 -#define HCI_READ_LOCAL_AMP_ASSOC_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_AMP_ASSOC_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_AMP_ASSOC_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_REMOTE_AMP_ASSOC_MASK 0x80 -#define HCI_SUPP_COMMANDS_WRITE_REMOTE_AMP_ASSOC_OFF 22 -#define HCI_WRITE_REMOTE_AMP_ASSOC_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_REMOTE_AMP_ASSOC_OFF] & HCI_SUPP_COMMANDS_WRITE_REMOTE_AMP_ASSOC_MASK) - -/* Supported Commands (Byte 23) */ -#define HCI_SUPP_COMMANDS_READ_FLOW_CONTROL_MODE_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_FLOW_CONTROL_MODE_OFF 23 -#define HCI_READ_FLOW_CONTROL_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_FLOW_CONTROL_MODE_OFF] & HCI_SUPP_COMMANDS_READ_FLOW_CONTROL_MODE_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_FLOW_CONTROL_MODE_MASK 0x02 -#define HCI_SUPP_COMMANDS_WRITE_FLOW_CONTROL_MODE_OFF 23 -#define HCI_WRITE_FLOW_CONTROL_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_FLOW_CONTROL_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_FLOW_CONTROL_MODE_MASK) - -#define HCI_SUPP_COMMANDS_READ_DATA_BLOCK_SIZE_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_DATA_BLOCK_SIZE_OFF 23 -#define HCI_READ_DATA_BLOCK_SIZE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_DATA_BLOCK_SIZE_OFF] & HCI_SUPP_COMMANDS_READ_DATA_BLOCK_SIZE_MASK) - -#define HCI_SUPP_COMMANDS_ENABLE_AMP_RCVR_REPORTS_MASK 0x20 -#define HCI_SUPP_COMMANDS_ENABLE_AMP_RCVR_REPORTS_OFF 23 -#define HCI_ENABLE_AMP_RCVR_REPORTS_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ENABLE_AMP_RCVR_REPORTS_OFF] & HCI_SUPP_COMMANDS_ENABLE_AMP_RCVR_REPORTS_MASK) - -#define HCI_SUPP_COMMANDS_AMP_TEST_END_MASK 0x40 -#define HCI_SUPP_COMMANDS_AMP_TEST_END_OFF 23 -#define HCI_AMP_TEST_END_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_AMP_TEST_END_OFF] & HCI_SUPP_COMMANDS_AMP_TEST_END_MASK) - -#define HCI_SUPP_COMMANDS_AMP_TEST_MASK 0x80 -#define HCI_SUPP_COMMANDS_AMP_TEST_OFF 23 -#define HCI_AMP_TEST_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_AMP_TEST_OFF] & HCI_SUPP_COMMANDS_AMP_TEST_MASK) - -/* Supported Commands (Byte 24) */ -#define HCI_SUPP_COMMANDS_READ_TRANSMIT_POWER_LEVEL_MASK 0x01 -#define HCI_SUPP_COMMANDS_READ_TRANSMIT_POWER_LEVEL_OFF 24 -#define HCI_READ_TRANSMIT_POWER_LEVEL_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_TRANSMIT_POWER_LEVEL_OFF] & HCI_SUPP_COMMANDS_READ_TRANSMIT_POWER_LEVEL_MASK) - -#define HCI_SUPP_COMMANDS_READ_BE_FLUSH_TOUT_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_BE_FLUSH_TOUT_OFF 24 -#define HCI_READ_BE_FLUSH_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_BE_FLUSH_TOUT_OFF] & HCI_SUPP_COMMANDS_READ_BE_FLUSH_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_BE_FLUSH_TOUT_MASK 0x08 -#define HCI_SUPP_COMMANDS_WRITE_BE_FLUSH_TOUT_OFF 24 -#define HCI_WRITE_BE_FLUSH_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_BE_FLUSH_TOUT_OFF] & HCI_SUPP_COMMANDS_WRITE_BE_FLUSH_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_SHORT_RANGE_MODE_MASK 0x10 -#define HCI_SUPP_COMMANDS_SHORT_RANGE_MODE_OFF 24 -#define HCI_SHORT_RANGE_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SHORT_RANGE_MODE_OFF] & HCI_SUPP_COMMANDS_SHORT_RANGE_MODE_MASK) - -/* LE commands TBD -** Supported Commands (Byte 24 continued) -** Supported Commands (Byte 25) -** Supported Commands (Byte 26) -** Supported Commands (Byte 27) -** Supported Commands (Byte 28) -*/ - -/* Supported Commands (Byte 29) */ -#define HCI_SUPP_COMMANDS_ENH_SETUP_SYNCH_CONN_MASK 0x08 -#define HCI_SUPP_COMMANDS_ENH_SETUP_SYNCH_CONN_OFF 29 -#define HCI_READ_ENH_SETUP_SYNCH_CONN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ENH_SETUP_SYNCH_CONN_OFF] & HCI_SUPP_COMMANDS_ENH_SETUP_SYNCH_CONN_MASK) - -#define HCI_SUPP_COMMANDS_ENH_ACCEPT_SYNCH_CONN_MASK 0x10 -#define HCI_SUPP_COMMANDS_ENH_ACCEPT_SYNCH_CONN_OFF 29 -#define HCI_READ_ENH_ACCEPT_SYNCH_CONN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_ENH_ACCEPT_SYNCH_CONN_OFF] & HCI_SUPP_COMMANDS_ENH_ACCEPT_SYNCH_CONN_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_CODECS_MASK 0x20 -#define HCI_SUPP_COMMANDS_READ_LOCAL_CODECS_OFF 29 -#define HCI_READ_LOCAL_CODECS_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_CODECS_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_CODECS_MASK) - -#define HCI_SUPP_COMMANDS_SET_MWS_CHANN_PARAM_MASK 0x40 -#define HCI_SUPP_COMMANDS_SET_MWS_CHANN_PARAM_OFF 29 -#define HCI_SET_MWS_CHANNEL_PARAMETERS_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_MWS_CHANN_PARAM_OFF] & HCI_SUPP_COMMANDS_SET_MWS_CHANN_PARAM_MASK) - -#define HCI_SUPP_COMMANDS_SET_EXT_FRAME_CONF_MASK 0x80 -#define HCI_SUPP_COMMANDS_SET_EXT_FRAME_CONF_OFF 29 -#define HCI_SET_EXTERNAL_FRAME_CONFIGURATION_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_EXT_FRAME_CONF_OFF] & HCI_SUPP_COMMANDS_SET_EXT_FRAME_CONF_MASK) - - -/* Supported Commands (Byte 30) */ -#define HCI_SUPP_COMMANDS_SET_MWS_SIGNALING_MASK 0x01 -#define HCI_SUPP_COMMANDS_SET_MWS_SIGNALING_OFF 30 -#define HCI_SET_MWS_SIGNALING_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_MWS_SIGNALING_OFF] & HCI_SUPP_COMMANDS_SET_MWS_SIGNALING_MASK) - -#define HCI_SUPP_COMMANDS_SET_MWS_TRANS_LAYER_MASK 0x02 -#define HCI_SUPP_COMMANDS_SET_MWS_TRANS_LAYER_OFF 30 -#define HCI_SET_MWS_TRANSPORT_LAYER_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_MWS_TRANS_LAYER_OFF] & HCI_SUPP_COMMANDS_SET_MWS_TRANS_LAYER_MASK) - -#define HCI_SUPP_COMMANDS_SET_MWS_SCAN_FREQ_TABLE_MASK 0x04 -#define HCI_SUPP_COMMANDS_SET_MWS_SCAN_FREQ_TABLE_OFF 30 -#define HCI_SET_MWS_SCAN_FREQUENCY_TABLE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_MWS_SCAN_FREQ_TABLE_OFF] & HCI_SUPP_COMMANDS_SET_MWS_SCAN_FREQ_TABLE_MASK) - -#define HCI_SUPP_COMMANDS_GET_TRANS_LAYER_CONF_MASK 0x08 -#define HCI_SUPP_COMMANDS_GET_TRANS_LAYER_CONF_OFF 30 -#define HCI_GET_MWS_TRANS_LAYER_CFG_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_GET_TRANS_LAYER_CONF_OFF] & HCI_SUPP_COMMANDS_GET_TRANS_LAYER_CONF_MASK) - -#define HCI_SUPP_COMMANDS_SET_MWS_PATTERN_CONF_MASK 0x10 -#define HCI_SUPP_COMMANDS_SET_MWS_PATTERN_CONF_OFF 30 -#define HCI_SET_MWS_PATTERN_CONFIGURATION_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_MWS_PATTERN_CONF_OFF] & HCI_SUPP_COMMANDS_SET_MWS_PATTERN_CONF_MASK) - -/* Supported Commands (Byte 30 bit 5) */ -#define HCI_SUPP_COMMANDS_SET_TRIG_CLK_CAP_MASK 0x20 -#define HCI_SUPP_COMMANDS_SET_TRIG_CLK_CAP_OFF 30 -#define HCI_SET_TRIG_CLK_CAP_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_TRIG_CLK_CAP_OFF] & HCI_SUPP_COMMANDS_SET_TRIG_CLK_CAP_MASK) - - -/* Supported Commands (Byte 30 bit 6-7) */ -#define HCI_SUPP_COMMANDS_TRUNCATED_PAGE 0x06 -#define HCI_SUPP_COMMANDS_TRUNCATED_PAGE_OFF 30 -#define HCI_TRUNCATED_PAGE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_TRUNCATED_PAGE_OFF] & HCI_SUPP_COMMANDS_TRUNCATED_PAGE) - -#define HCI_SUPP_COMMANDS_TRUNCATED_PAGE_CANCEL 0x07 -#define HCI_SUPP_COMMANDS_TRUNCATED_PAGE_CANCEL_OFF 30 -#define HCI_TRUNCATED_PAGE_CANCEL_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_TRUNCATED_PAGE_CANCEL_OFF] & HCI_SUPP_COMMANDS_TRUNCATED_PAGE_CANCEL) - -/* Supported Commands (Byte 31 bit 6-7) */ -#define HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST 0x00 -#define HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_OFF 31 -#define HCI_SET_CONLESS_SLAVE_BRCST_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_OFF] & HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST) - -#define HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_RECEIVE 0x01 -#define HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_RECEIVE_OFF 31 -#define HCI_SET_CONLESS_SLAVE_BRCST_RECEIVE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_RECEIVE_OFF] & HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_RECEIVE) - -#define HCI_SUPP_COMMANDS_START_SYNC_TRAIN 0x02 -#define HCI_SUPP_COMMANDS_START_SYNC_TRAIN_OFF 31 -#define HCI_START_SYNC_TRAIN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_START_SYNC_TRAIN_OFF] & HCI_SUPP_COMMANDS_START_SYNC_TRAIN) - -#define HCI_SUPP_COMMANDS_RECEIVE_SYNC_TRAIN 0x03 -#define HCI_SUPP_COMMANDS_RECEIVE_SYNC_TRAIN_OFF 31 -#define HCI_RECEIVE_SYNC_TRAIN_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_RECEIVE_SYNC_TRAIN_OFF] & HCI_SUPP_COMMANDS_RECEIVE_SYNC_TRAIN) - -#define HCI_SUPP_COMMANDS_SET_RESERVED_LT_ADDR 0x04 -#define HCI_SUPP_COMMANDS_SET_RESERVED_LT_ADDR_OFF 31 -#define HCI_SET_RESERVED_LT_ADDR_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_RESERVED_LT_ADDR_OFF] & HCI_SUPP_COMMANDS_SET_RESERVED_LT_ADDR) - -#define HCI_SUPP_COMMANDS_DELETE_RESERVED_LT_ADDR 0x05 -#define HCI_SUPP_COMMANDS_DELETE_RESERVED_LT_ADDR_OFF 31 -#define HCI_DELETE_RESERVED_LT_ADDR_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_DELETE_RESERVED_LT_ADDR_OFF] & HCI_SUPP_COMMANDS_DELETE_RESERVED_LT_ADDR) - -#define HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_DATA 0x06 -#define HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_DATA_OFF 31 -#define HCI_SET_CONLESS_SLAVE_BRCST_DATA_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_DATA_OFF] & HCI_SUPP_COMMANDS_SET_CONLESS_SLAVE_BRCST_DATA) - -#define HCI_SUPP_COMMANDS_READ_SYNC_TRAIN_PARAM 0x07 -#define HCI_SUPP_COMMANDS_READ_SYNC_TRAIN_PARAM_OFF 31 -#define HCI_READ_SYNC_TRAIN_PARAM_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_SYNC_TRAIN_PARAM_OFF] & HCI_SUPP_COMMANDS_READ_SYNC_TRAIN_PARAM) - -/* Supported Commands (Byte 32 bit 0) */ -#define HCI_SUPP_COMMANDS_WRITE_SYNC_TRAIN_PARAM 0x00 -#define HCI_SUPP_COMMANDS_WRITE_SYNC_TRAIN_PARAM_OFF 32 -#define HCI_WRITE_SYNC_TRAIN_PARAM_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_SYNC_TRAIN_PARAM_OFF] & HCI_SUPP_COMMANDS_WRITE_SYNC_TRAIN_PARAM) - -#define HCI_SUPP_COMMANDS_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY_MASK 0x02 -#define HCI_SUPP_COMMANDS_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY_OFF 32 -#define HCI_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY_OFF] & HCI_SUPP_COMMANDS_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY_MASK) - -#define HCI_SUPP_COMMANDS_READ_SECURE_CONNS_SUPPORT_MASK 0x04 -#define HCI_SUPP_COMMANDS_READ_SECURE_CONNS_SUPPORT_OFF 32 -#define HCI_READ_SECURE_CONNS_SUPPORT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_SECURE_CONNS_SUPPORT_OFF] & HCI_SUPP_COMMANDS_READ_SECURE_CONNS_SUPPORT_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_SECURE_CONNS_SUPPORT_MASK 0x08 -#define HCI_SUPP_COMMANDS_WRITE_SECURE_CONNS_SUPPORT_OFF 32 -#define HCI_WRITE_SECURE_CONNS_SUPPORT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_SECURE_CONNS_SUPPORT_OFF] & HCI_SUPP_COMMANDS_WRITE_SECURE_CONNS_SUPPORT_MASK) - -#define HCI_SUPP_COMMANDS_READ_AUTHENT_PAYLOAD_TOUT_MASK 0x10 -#define HCI_SUPP_COMMANDS_READ_AUTHENT_PAYLOAD_TOUT_OFF 32 -#define HCI_READ_AUTHENT_PAYLOAD_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_AUTHENT_PAYLOAD_TOUT_OFF] & HCI_SUPP_COMMANDS_READ_AUTHENT_PAYLOAD_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_AUTHENT_PAYLOAD_TOUT_MASK 0x20 -#define HCI_SUPP_COMMANDS_WRITE_AUTHENT_PAYLOAD_TOUT_OFF 32 -#define HCI_WRITE_AUTHENT_PAYLOAD_TOUT_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_AUTHENT_PAYLOAD_TOUT_OFF] & HCI_SUPP_COMMANDS_WRITE_AUTHENT_PAYLOAD_TOUT_MASK) - -#define HCI_SUPP_COMMANDS_READ_LOCAL_OOB_EXTENDED_DATA_MASK 0x40 -#define HCI_SUPP_COMMANDS_READ_LOCAL_OOB_EXTENDED_DATA_OFF 32 -#define HCI_READ_LOCAL_OOB_EXTENDED_DATA_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_READ_LOCAL_OOB_EXTENDED_DATA_OFF] & HCI_SUPP_COMMANDS_READ_LOCAL_OOB_EXTENDED_DATA_MASK) - -#define HCI_SUPP_COMMANDS_WRITE_SECURE_CONNECTIONS_TEST_MODE_MASK 0x80 -#define HCI_SUPP_COMMANDS_WRITE_SECURE_CONNECTIONS_TEST_MODE_OFF 32 -#define HCI_WRITE_SECURE_CONNECTIONS_TEST_MODE_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_WRITE_SECURE_CONNECTIONS_TEST_MODE_OFF] & HCI_SUPP_COMMANDS_WRITE_SECURE_CONNECTIONS_TEST_MODE_MASK) - -/* supported LE remote control connection parameter request reply */ -#define HCI_SUPP_COMMANDS_LE_RC_CONN_PARAM_UPD_RPY_MASK 0x10 -#define HCI_SUPP_COMMANDS_LE_RC_CONN_PARAM_UPD_RPY_OFF 33 -#define HCI_LE_RC_CONN_PARAM_UPD_RPY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_LE_RC_CONN_PARAM_UPD_RPY_OFF] & HCI_SUPP_COMMANDS_LE_RC_CONN_PARAM_UPD_RPY_MASK) - -#define HCI_SUPP_COMMANDS_RLE_RC_CONN_PARAM_UPD_NEG_RPY_MASK 0x20 -#define HCI_SUPP_COMMANDS_LE_RC_CONN_PARAM_UPD_NEG_RPY_OFF 33 -#define HCI_LE_RC_CONN_PARAM_UPD_NEG_RPY_SUPPORTED(x) ((x)[HCI_SUPP_COMMANDS_LE_RC_CONN_PARAM_UPD_NEG_RPY_OFF] & HCI_SUPP_COMMANDS_RLE_RC_CONN_PARAM_UPD_NEG_RPY_MASK) - -#endif - diff --git a/tools/sdk/include/bluedroid/hcimsgs.h b/tools/sdk/include/bluedroid/hcimsgs.h deleted file mode 100644 index d360a9a121d..00000000000 --- a/tools/sdk/include/bluedroid/hcimsgs.h +++ /dev/null @@ -1,811 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 HCIMSGS_H -#define HCIMSGS_H - -#include "bt_target.h" -#include "hcidefs.h" -#include "bt_types.h" - -void bte_main_hci_send(BT_HDR *p_msg, UINT16 event); -void bte_main_lpm_allow_bt_device_sleep(void); - -/* Message by message.... */ - -BOOLEAN btsnd_hcic_inquiry(const LAP inq_lap, UINT8 duration, - UINT8 response_cnt); - -#define HCIC_PARAM_SIZE_INQUIRY 5 - - -#define HCIC_INQ_INQ_LAP_OFF 0 -#define HCIC_INQ_DUR_OFF 3 -#define HCIC_INQ_RSP_CNT_OFF 4 -/* Inquiry */ - -/* Inquiry Cancel */ -BOOLEAN btsnd_hcic_inq_cancel(void); - -#define HCIC_PARAM_SIZE_INQ_CANCEL 0 - -/* Periodic Inquiry Mode */ -BOOLEAN btsnd_hcic_per_inq_mode(UINT16 max_period, UINT16 min_period, - const LAP inq_lap, UINT8 duration, - UINT8 response_cnt); - -#define HCIC_PARAM_SIZE_PER_INQ_MODE 9 - -#define HCI_PER_INQ_MAX_INTRVL_OFF 0 -#define HCI_PER_INQ_MIN_INTRVL_OFF 2 -#define HCI_PER_INQ_INQ_LAP_OFF 4 -#define HCI_PER_INQ_DURATION_OFF 7 -#define HCI_PER_INQ_RSP_CNT_OFF 8 -/* Periodic Inquiry Mode */ - -/* Exit Periodic Inquiry Mode */ -BOOLEAN btsnd_hcic_exit_per_inq(void); - -#define HCIC_PARAM_SIZE_EXIT_PER_INQ 0 -/* Create Connection */ -BOOLEAN btsnd_hcic_create_conn(BD_ADDR dest, UINT16 packet_types, - UINT8 page_scan_rep_mode, - UINT8 page_scan_mode, - UINT16 clock_offset, - UINT8 allow_switch); - -#define HCIC_PARAM_SIZE_CREATE_CONN 13 - -#define HCIC_CR_CONN_BD_ADDR_OFF 0 -#define HCIC_CR_CONN_PKT_TYPES_OFF 6 -#define HCIC_CR_CONN_REP_MODE_OFF 8 -#define HCIC_CR_CONN_PAGE_SCAN_MODE_OFF 9 -#define HCIC_CR_CONN_CLK_OFF_OFF 10 -#define HCIC_CR_CONN_ALLOW_SWITCH_OFF 12 -/* Create Connection */ - -/* Disconnect */ -BOOLEAN btsnd_hcic_disconnect(UINT16 handle, UINT8 reason); - -#define HCIC_PARAM_SIZE_DISCONNECT 3 - -#define HCI_DISC_HANDLE_OFF 0 -#define HCI_DISC_REASON_OFF 2 -/* Disconnect */ - -#if BTM_SCO_INCLUDED == TRUE -/* Add SCO Connection */ -BOOLEAN btsnd_hcic_add_SCO_conn (UINT16 handle, UINT16 packet_types); -#endif /* BTM_SCO_INCLUDED */ - -#define HCIC_PARAM_SIZE_ADD_SCO_CONN 4 - -#define HCI_ADD_SCO_HANDLE_OFF 0 -#define HCI_ADD_SCO_PACKET_TYPES_OFF 2 -/* Add SCO Connection */ - -/* Create Connection Cancel */ -BOOLEAN btsnd_hcic_create_conn_cancel(BD_ADDR dest); - -#define HCIC_PARAM_SIZE_CREATE_CONN_CANCEL 6 - -#define HCIC_CR_CONN_CANCEL_BD_ADDR_OFF 0 -/* Create Connection Cancel */ - -/* Accept Connection Request */ -BOOLEAN btsnd_hcic_accept_conn (BD_ADDR bd_addr, UINT8 role); - -#define HCIC_PARAM_SIZE_ACCEPT_CONN 7 - -#define HCI_ACC_CONN_BD_ADDR_OFF 0 -#define HCI_ACC_CONN_ROLE_OFF 6 -/* Accept Connection Request */ - -/* Reject Connection Request */ -BOOLEAN btsnd_hcic_reject_conn (BD_ADDR bd_addr, UINT8 reason); - -#define HCIC_PARAM_SIZE_REJECT_CONN 7 - -#define HCI_REJ_CONN_BD_ADDR_OFF 0 -#define HCI_REJ_CONN_REASON_OFF 6 -/* Reject Connection Request */ - -/* Link Key Request Reply */ -BOOLEAN btsnd_hcic_link_key_req_reply (BD_ADDR bd_addr, - LINK_KEY link_key); - -#define HCIC_PARAM_SIZE_LINK_KEY_REQ_REPLY 22 - -#define HCI_LINK_KEY_REPLY_BD_ADDR_OFF 0 -#define HCI_LINK_KEY_REPLY_LINK_KEY_OFF 6 -/* Link Key Request Reply */ - -/* Link Key Request Neg Reply */ -BOOLEAN btsnd_hcic_link_key_neg_reply (BD_ADDR bd_addr); - -#define HCIC_PARAM_SIZE_LINK_KEY_NEG_REPLY 6 - -#define HCI_LINK_KEY_NEG_REP_BD_ADR_OFF 0 -/* Link Key Request Neg Reply */ - -/* PIN Code Request Reply */ -BOOLEAN btsnd_hcic_pin_code_req_reply (BD_ADDR bd_addr, - UINT8 pin_code_len, - PIN_CODE pin_code); - -#define HCIC_PARAM_SIZE_PIN_CODE_REQ_REPLY 23 - -#define HCI_PIN_CODE_REPLY_BD_ADDR_OFF 0 -#define HCI_PIN_CODE_REPLY_PIN_LEN_OFF 6 -#define HCI_PIN_CODE_REPLY_PIN_CODE_OFF 7 -/* PIN Code Request Reply */ - -/* Link Key Request Neg Reply */ -BOOLEAN btsnd_hcic_pin_code_neg_reply (BD_ADDR bd_addr); - -#define HCIC_PARAM_SIZE_PIN_CODE_NEG_REPLY 6 - -#define HCI_PIN_CODE_NEG_REP_BD_ADR_OFF 0 -/* Link Key Request Neg Reply */ - -/* Change Connection Type */ -BOOLEAN btsnd_hcic_change_conn_type (UINT16 handle, UINT16 packet_types); - -#define HCIC_PARAM_SIZE_CHANGE_CONN_TYPE 4 - -#define HCI_CHNG_PKT_TYPE_HANDLE_OFF 0 -#define HCI_CHNG_PKT_TYPE_PKT_TYPE_OFF 2 -/* Change Connection Type */ - -#define HCIC_PARAM_SIZE_CMD_HANDLE 2 - -#define HCI_CMD_HANDLE_HANDLE_OFF 0 - -BOOLEAN btsnd_hcic_auth_request (UINT16 handle); /* Authentication Request */ - -/* Set Connection Encryption */ -BOOLEAN btsnd_hcic_set_conn_encrypt (UINT16 handle, BOOLEAN enable); -#define HCIC_PARAM_SIZE_SET_CONN_ENCRYPT 3 - - -#define HCI_SET_ENCRYPT_HANDLE_OFF 0 -#define HCI_SET_ENCRYPT_ENABLE_OFF 2 -/* Set Connection Encryption */ - -/* Remote Name Request */ -BOOLEAN btsnd_hcic_rmt_name_req (BD_ADDR bd_addr, - UINT8 page_scan_rep_mode, - UINT8 page_scan_mode, - UINT16 clock_offset); - -#define HCIC_PARAM_SIZE_RMT_NAME_REQ 10 - -#define HCI_RMT_NAME_BD_ADDR_OFF 0 -#define HCI_RMT_NAME_REP_MODE_OFF 6 -#define HCI_RMT_NAME_PAGE_SCAN_MODE_OFF 7 -#define HCI_RMT_NAME_CLK_OFF_OFF 8 -/* Remote Name Request */ - -/* Remote Name Request Cancel */ -BOOLEAN btsnd_hcic_rmt_name_req_cancel(BD_ADDR bd_addr); - -#define HCIC_PARAM_SIZE_RMT_NAME_REQ_CANCEL 6 - -#define HCI_RMT_NAME_CANCEL_BD_ADDR_OFF 0 -/* Remote Name Request Cancel */ - -BOOLEAN btsnd_hcic_rmt_features_req(UINT16 handle); /* Remote Features Request */ - -/* Remote Extended Features */ -BOOLEAN btsnd_hcic_rmt_ext_features(UINT16 handle, UINT8 page_num); - -#define HCIC_PARAM_SIZE_RMT_EXT_FEATURES 3 - -#define HCI_RMT_EXT_FEATURES_HANDLE_OFF 0 -#define HCI_RMT_EXT_FEATURES_PAGE_NUM_OFF 2 -/* Remote Extended Features */ - - -BOOLEAN btsnd_hcic_rmt_ver_req(UINT16 handle); /* Remote Version Info Request */ -BOOLEAN btsnd_hcic_read_rmt_clk_offset(UINT16 handle); /* Remote Clock Offset */ -BOOLEAN btsnd_hcic_read_lmp_handle(UINT16 handle); /* Remote LMP Handle */ - -BOOLEAN btsnd_hcic_setup_esco_conn (UINT16 handle, - UINT32 tx_bw, UINT32 rx_bw, - UINT16 max_latency, UINT16 voice, - UINT8 retrans_effort, - UINT16 packet_types); -#define HCIC_PARAM_SIZE_SETUP_ESCO 17 - -#define HCI_SETUP_ESCO_HANDLE_OFF 0 -#define HCI_SETUP_ESCO_TX_BW_OFF 2 -#define HCI_SETUP_ESCO_RX_BW_OFF 6 -#define HCI_SETUP_ESCO_MAX_LAT_OFF 10 -#define HCI_SETUP_ESCO_VOICE_OFF 12 -#define HCI_SETUP_ESCO_RETRAN_EFF_OFF 14 -#define HCI_SETUP_ESCO_PKT_TYPES_OFF 15 - - -BOOLEAN btsnd_hcic_accept_esco_conn (BD_ADDR bd_addr, - UINT32 tx_bw, UINT32 rx_bw, - UINT16 max_latency, - UINT16 content_fmt, - UINT8 retrans_effort, - UINT16 packet_types); -#define HCIC_PARAM_SIZE_ACCEPT_ESCO 21 - -#define HCI_ACCEPT_ESCO_BDADDR_OFF 0 -#define HCI_ACCEPT_ESCO_TX_BW_OFF 6 -#define HCI_ACCEPT_ESCO_RX_BW_OFF 10 -#define HCI_ACCEPT_ESCO_MAX_LAT_OFF 14 -#define HCI_ACCEPT_ESCO_VOICE_OFF 16 -#define HCI_ACCEPT_ESCO_RETRAN_EFF_OFF 18 -#define HCI_ACCEPT_ESCO_PKT_TYPES_OFF 19 - - -BOOLEAN btsnd_hcic_reject_esco_conn (BD_ADDR bd_addr, UINT8 reason); -#define HCIC_PARAM_SIZE_REJECT_ESCO 7 - -#define HCI_REJECT_ESCO_BDADDR_OFF 0 -#define HCI_REJECT_ESCO_REASON_OFF 6 - -/* Hold Mode */ -BOOLEAN btsnd_hcic_hold_mode(UINT16 handle, UINT16 max_hold_period, - UINT16 min_hold_period); - -#define HCIC_PARAM_SIZE_HOLD_MODE 6 - -#define HCI_HOLD_MODE_HANDLE_OFF 0 -#define HCI_HOLD_MODE_MAX_PER_OFF 2 -#define HCI_HOLD_MODE_MIN_PER_OFF 4 -/* Hold Mode */ - -/* Sniff Mode */ -BOOLEAN btsnd_hcic_sniff_mode(UINT16 handle, - UINT16 max_sniff_period, - UINT16 min_sniff_period, - UINT16 sniff_attempt, - UINT16 sniff_timeout); - -#define HCIC_PARAM_SIZE_SNIFF_MODE 10 - - -#define HCI_SNIFF_MODE_HANDLE_OFF 0 -#define HCI_SNIFF_MODE_MAX_PER_OFF 2 -#define HCI_SNIFF_MODE_MIN_PER_OFF 4 -#define HCI_SNIFF_MODE_ATTEMPT_OFF 6 -#define HCI_SNIFF_MODE_TIMEOUT_OFF 8 -/* Sniff Mode */ - -BOOLEAN btsnd_hcic_exit_sniff_mode(UINT16 handle); /* Exit Sniff Mode */ - -/* Park Mode */ -BOOLEAN btsnd_hcic_park_mode (UINT16 handle, - UINT16 beacon_max_interval, - UINT16 beacon_min_interval); - -#define HCIC_PARAM_SIZE_PARK_MODE 6 - -#define HCI_PARK_MODE_HANDLE_OFF 0 -#define HCI_PARK_MODE_MAX_PER_OFF 2 -#define HCI_PARK_MODE_MIN_PER_OFF 4 -/* Park Mode */ - -BOOLEAN btsnd_hcic_exit_park_mode(UINT16 handle); /* Exit Park Mode */ - -/* QoS Setup */ -BOOLEAN btsnd_hcic_qos_setup (UINT16 handle, UINT8 flags, - UINT8 service_type, - UINT32 token_rate, UINT32 peak, - UINT32 latency, UINT32 delay_var); - -#define HCIC_PARAM_SIZE_QOS_SETUP 20 - -#define HCI_QOS_HANDLE_OFF 0 -#define HCI_QOS_FLAGS_OFF 2 -#define HCI_QOS_SERVICE_TYPE_OFF 3 -#define HCI_QOS_TOKEN_RATE_OFF 4 -#define HCI_QOS_PEAK_BANDWIDTH_OFF 8 -#define HCI_QOS_LATENCY_OFF 12 -#define HCI_QOS_DELAY_VAR_OFF 16 -/* QoS Setup */ - -/* Switch Role Request */ -BOOLEAN btsnd_hcic_switch_role (BD_ADDR bd_addr, UINT8 role); - -#define HCIC_PARAM_SIZE_SWITCH_ROLE 7 - -#define HCI_SWITCH_BD_ADDR_OFF 0 -#define HCI_SWITCH_ROLE_OFF 6 -/* Switch Role Request */ - -/* Write Policy Settings */ -BOOLEAN btsnd_hcic_write_policy_set(UINT16 handle, UINT16 settings); - -#define HCIC_PARAM_SIZE_WRITE_POLICY_SET 4 - -#define HCI_WRITE_POLICY_HANDLE_OFF 0 -#define HCI_WRITE_POLICY_SETTINGS_OFF 2 -/* Write Policy Settings */ - -/* Write Default Policy Settings */ -BOOLEAN btsnd_hcic_write_def_policy_set(UINT16 settings); - -#define HCIC_PARAM_SIZE_WRITE_DEF_POLICY_SET 2 - -#define HCI_WRITE_DEF_POLICY_SETTINGS_OFF 0 -/* Write Default Policy Settings */ - -/****************************************** -** Lisbon Features -*******************************************/ -#if BTM_SSR_INCLUDED == TRUE -/* Sniff Subrating */ -BOOLEAN btsnd_hcic_sniff_sub_rate(UINT16 handle, UINT16 max_lat, - UINT16 min_remote_lat, - UINT16 min_local_lat); - -#define HCIC_PARAM_SIZE_SNIFF_SUB_RATE 8 - -#define HCI_SNIFF_SUB_RATE_HANDLE_OFF 0 -#define HCI_SNIFF_SUB_RATE_MAX_LAT_OFF 2 -#define HCI_SNIFF_SUB_RATE_MIN_REM_LAT_OFF 4 -#define HCI_SNIFF_SUB_RATE_MIN_LOC_LAT_OFF 6 -/* Sniff Subrating */ - -#else /* BTM_SSR_INCLUDED == FALSE */ - -#define btsnd_hcic_sniff_sub_rate(handle, max_lat, min_remote_lat, min_local_lat) FALSE - -#endif /* BTM_SSR_INCLUDED */ - -/* Extended Inquiry Response */ -void btsnd_hcic_write_ext_inquiry_response(void *buffer, UINT8 fec_req); - -#define HCIC_PARAM_SIZE_EXT_INQ_RESP 241 - -#define HCIC_EXT_INQ_RESP_FEC_OFF 0 -#define HCIC_EXT_INQ_RESP_RESPONSE 1 -/* IO Capabilities Response */ -BOOLEAN btsnd_hcic_io_cap_req_reply (BD_ADDR bd_addr, UINT8 capability, - UINT8 oob_present, UINT8 auth_req); - -#define HCIC_PARAM_SIZE_IO_CAP_RESP 9 - -#define HCI_IO_CAP_BD_ADDR_OFF 0 -#define HCI_IO_CAPABILITY_OFF 6 -#define HCI_IO_CAP_OOB_DATA_OFF 7 -#define HCI_IO_CAP_AUTH_REQ_OFF 8 - -/* IO Capabilities Req Neg Reply */ -BOOLEAN btsnd_hcic_io_cap_req_neg_reply (BD_ADDR bd_addr, UINT8 err_code); - -#define HCIC_PARAM_SIZE_IO_CAP_NEG_REPLY 7 - -#define HCI_IO_CAP_NR_BD_ADDR_OFF 0 -#define HCI_IO_CAP_NR_ERR_CODE 6 - -/* Read Local OOB Data */ -BOOLEAN btsnd_hcic_read_local_oob_data (void); - -#define HCIC_PARAM_SIZE_R_LOCAL_OOB 0 - - -BOOLEAN btsnd_hcic_user_conf_reply (BD_ADDR bd_addr, BOOLEAN is_yes); - -#define HCIC_PARAM_SIZE_UCONF_REPLY 6 - -#define HCI_USER_CONF_BD_ADDR_OFF 0 - - -BOOLEAN btsnd_hcic_user_passkey_reply (BD_ADDR bd_addr, UINT32 value); - -#define HCIC_PARAM_SIZE_U_PKEY_REPLY 10 - -#define HCI_USER_PASSKEY_BD_ADDR_OFF 0 -#define HCI_USER_PASSKEY_VALUE_OFF 6 - - -BOOLEAN btsnd_hcic_user_passkey_neg_reply (BD_ADDR bd_addr); - -#define HCIC_PARAM_SIZE_U_PKEY_NEG_REPLY 6 - -#define HCI_USER_PASSKEY_NEG_BD_ADDR_OFF 0 - -/* Remote OOB Data Request Reply */ -BOOLEAN btsnd_hcic_rem_oob_reply (BD_ADDR bd_addr, UINT8 *p_c, - UINT8 *p_r); - -#define HCIC_PARAM_SIZE_REM_OOB_REPLY 38 - -#define HCI_REM_OOB_DATA_BD_ADDR_OFF 0 -#define HCI_REM_OOB_DATA_C_OFF 6 -#define HCI_REM_OOB_DATA_R_OFF 22 - -/* Remote OOB Data Request Negative Reply */ -BOOLEAN btsnd_hcic_rem_oob_neg_reply (BD_ADDR bd_addr); - -#define HCIC_PARAM_SIZE_REM_OOB_NEG_REPLY 6 - -#define HCI_REM_OOB_DATA_NEG_BD_ADDR_OFF 0 - -/* Read Tx Power Level */ -BOOLEAN btsnd_hcic_read_inq_tx_power (void); - -#define HCIC_PARAM_SIZE_R_TX_POWER 0 - -/* Read Default Erroneous Data Reporting */ -BOOLEAN btsnd_hcic_read_default_erroneous_data_rpt (void); - -#define HCIC_PARAM_SIZE_R_ERR_DATA_RPT 0 - -#if L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE -BOOLEAN btsnd_hcic_enhanced_flush (UINT16 handle, UINT8 packet_type); - -#define HCIC_PARAM_SIZE_ENHANCED_FLUSH 3 -#endif - - -BOOLEAN btsnd_hcic_send_keypress_notif (BD_ADDR bd_addr, UINT8 notif); - -#define HCIC_PARAM_SIZE_SEND_KEYPRESS_NOTIF 7 - -#define HCI_SEND_KEYPRESS_NOTIF_BD_ADDR_OFF 0 -#define HCI_SEND_KEYPRESS_NOTIF_NOTIF_OFF 6 - -/**** end of Simple Pairing Commands ****/ - -/* Store Current Settings */ -#define MAX_FILT_COND (sizeof (BD_ADDR) + 1) - -BOOLEAN btsnd_hcic_set_event_filter(UINT8 filt_type, - UINT8 filt_cond_type, - UINT8 *filt_cond, - UINT8 filt_cond_len); - -#define HCIC_PARAM_SIZE_SET_EVT_FILTER 9 - -#define HCI_FILT_COND_FILT_TYPE_OFF 0 -#define HCI_FILT_COND_COND_TYPE_OFF 1 -#define HCI_FILT_COND_FILT_OFF 2 -/* Set Event Filter */ - -/* Delete Stored Key */ -BOOLEAN btsnd_hcic_delete_stored_key (BD_ADDR bd_addr, BOOLEAN delete_all_flag); - -#define HCIC_PARAM_SIZE_DELETE_STORED_KEY 7 - -#define HCI_DELETE_KEY_BD_ADDR_OFF 0 -#define HCI_DELETE_KEY_ALL_FLAG_OFF 6 -/* Delete Stored Key */ - -/* Change Local Name */ -BOOLEAN btsnd_hcic_change_name(BD_NAME name); - -#define HCIC_PARAM_SIZE_CHANGE_NAME BD_NAME_LEN - -#define HCI_CHANGE_NAME_NAME_OFF 0 -/* Change Local Name */ - - -#define HCIC_PARAM_SIZE_READ_CMD 0 - -#define HCIC_PARAM_SIZE_WRITE_PARAM1 1 - -#define HCIC_WRITE_PARAM1_PARAM_OFF 0 - -#define HCIC_PARAM_SIZE_WRITE_PARAM2 2 - -#define HCIC_WRITE_PARAM2_PARAM_OFF 0 - -#define HCIC_PARAM_SIZE_WRITE_PARAM3 3 - -#define HCIC_WRITE_PARAM3_PARAM_OFF 0 - -#define HCIC_PARAM_SIZE_SET_AFH_CHANNELS 10 - -BOOLEAN btsnd_hcic_write_pin_type(UINT8 type); /* Write PIN Type */ -BOOLEAN btsnd_hcic_write_auto_accept(UINT8 flag); /* Write Auto Accept */ -BOOLEAN btsnd_hcic_read_name (void); /* Read Local Name */ -BOOLEAN btsnd_hcic_write_page_tout(UINT16 timeout); /* Write Page Timout */ -BOOLEAN btsnd_hcic_write_scan_enable(UINT8 flag); /* Write Scan Enable */ -BOOLEAN btsnd_hcic_write_pagescan_cfg(UINT16 interval, - UINT16 window); /* Write Page Scan Activity */ - -#define HCIC_PARAM_SIZE_WRITE_PAGESCAN_CFG 4 - -#define HCI_SCAN_CFG_INTERVAL_OFF 0 -#define HCI_SCAN_CFG_WINDOW_OFF 2 -/* Write Page Scan Activity */ - -/* Write Inquiry Scan Activity */ -BOOLEAN btsnd_hcic_write_inqscan_cfg(UINT16 interval, UINT16 window); - -#define HCIC_PARAM_SIZE_WRITE_INQSCAN_CFG 4 - -#define HCI_SCAN_CFG_INTERVAL_OFF 0 -#define HCI_SCAN_CFG_WINDOW_OFF 2 -/* Write Inquiry Scan Activity */ - -BOOLEAN btsnd_hcic_write_auth_enable(UINT8 flag); /* Write Authentication Enable */ -BOOLEAN btsnd_hcic_write_dev_class(DEV_CLASS dev); /* Write Class of Device */ -BOOLEAN btsnd_hcic_write_voice_settings(UINT16 flags); /* Write Voice Settings */ - -/* Host Controller to Host flow control */ -#define HCI_HOST_FLOW_CTRL_OFF 0 -#define HCI_HOST_FLOW_CTRL_ACL_ON 1 -#define HCI_HOST_FLOW_CTRL_SCO_ON 2 -#define HCI_HOST_FLOW_CTRL_BOTH_ON 3 - -BOOLEAN btsnd_hcic_write_auto_flush_tout(UINT16 handle, - UINT16 timeout); /* Write Retransmit Timout */ - -#define HCIC_PARAM_SIZE_WRITE_AUTO_FLUSH_TOUT 4 - -#define HCI_FLUSH_TOUT_HANDLE_OFF 0 -#define HCI_FLUSH_TOUT_TOUT_OFF 2 - -BOOLEAN btsnd_hcic_read_tx_power(UINT16 handle, UINT8 type); /* Read Tx Power */ - -#define HCIC_PARAM_SIZE_READ_TX_POWER 3 - -#define HCI_READ_TX_POWER_HANDLE_OFF 0 -#define HCI_READ_TX_POWER_TYPE_OFF 2 - -/* Read transmit power level parameter */ -#define HCI_READ_CURRENT 0x00 -#define HCI_READ_MAXIMUM 0x01 - -BOOLEAN btsnd_hcic_host_num_xmitted_pkts (UINT8 num_handles, - UINT16 *handle, - UINT16 *num_pkts); /* Set Host Buffer Size */ - -#define HCIC_PARAM_SIZE_NUM_PKTS_DONE_SIZE sizeof(btmsg_hcic_num_pkts_done_t) - -#define MAX_DATA_HANDLES 10 - -#define HCI_PKTS_DONE_NUM_HANDLES_OFF 0 -#define HCI_PKTS_DONE_HANDLE_OFF 1 -#define HCI_PKTS_DONE_NUM_PKTS_OFF 3 - -/* Write Link Supervision Timeout */ -BOOLEAN btsnd_hcic_write_link_super_tout(UINT8 local_controller_id, UINT16 handle, UINT16 timeout); - -#define HCIC_PARAM_SIZE_WRITE_LINK_SUPER_TOUT 4 - -#define HCI_LINK_SUPER_TOUT_HANDLE_OFF 0 -#define HCI_LINK_SUPER_TOUT_TOUT_OFF 2 -/* Write Link Supervision Timeout */ - -BOOLEAN btsnd_hcic_write_cur_iac_lap (UINT8 num_cur_iac, - LAP *const iac_lap); /* Write Current IAC LAP */ - -#define MAX_IAC_LAPS 0x40 - -#define HCI_WRITE_IAC_LAP_NUM_OFF 0 -#define HCI_WRITE_IAC_LAP_LAP_OFF 1 -/* Write Current IAC LAP */ - -BOOLEAN btsnd_hcic_get_link_quality (UINT16 handle); /* Get Link Quality */ -BOOLEAN btsnd_hcic_read_rssi (UINT16 handle); /* Read RSSI */ -BOOLEAN btsnd_hcic_enable_test_mode (void); /* Enable Device Under Test Mode */ -BOOLEAN btsnd_hcic_write_pagescan_type(UINT8 type); /* Write Page Scan Type */ -BOOLEAN btsnd_hcic_write_inqscan_type(UINT8 type); /* Write Inquiry Scan Type */ -BOOLEAN btsnd_hcic_write_inquiry_mode(UINT8 type); /* Write Inquiry Mode */ - -#define HCI_DATA_HANDLE_MASK 0x0FFF - -#define HCID_GET_HANDLE_EVENT(p) (UINT16)((*((UINT8 *)((p) + 1) + p->offset) + \ - (*((UINT8 *)((p) + 1) + p->offset + 1) << 8))) - -#define HCID_GET_HANDLE(u16) (UINT16)((u16) & HCI_DATA_HANDLE_MASK) - -#define HCI_DATA_EVENT_MASK 3 -#define HCI_DATA_EVENT_OFFSET 12 -#define HCID_GET_EVENT(u16) (UINT8)(((u16) >> HCI_DATA_EVENT_OFFSET) & HCI_DATA_EVENT_MASK) - -#define HCI_DATA_BCAST_MASK 3 -#define HCI_DATA_BCAST_OFFSET 10 -#define HCID_GET_BCAST(u16) (UINT8)(((u16) >> HCI_DATA_BCAST_OFFSET) & HCI_DATA_BCAST_MASK) - -#define HCID_GET_ACL_LEN(p) (UINT16)((*((UINT8 *)((p) + 1) + p->offset + 2) + \ - (*((UINT8 *)((p) + 1) + p->offset + 3) << 8))) - -#define HCID_HEADER_SIZE 4 - -#define HCID_GET_SCO_LEN(p) (*((UINT8 *)((p) + 1) + p->offset + 2)) - -void btsnd_hcic_vendor_spec_cmd (void *buffer, UINT16 opcode, - UINT8 len, UINT8 *p_data, - void *p_cmd_cplt_cback); - -#if (BLE_INCLUDED == TRUE) -/******************************************************************************** -** BLE Commands -** Note: "local_controller_id" is for transport, not counted in HCI message size -*********************************************************************************/ -#define HCIC_BLE_RAND_DI_SIZE 8 -#define HCIC_BLE_ENCRYT_KEY_SIZE 16 -#define HCIC_BLE_IRK_SIZE 16 - -#define HCIC_PARAM_SIZE_SET_USED_FEAT_CMD 8 -#define HCIC_PARAM_SIZE_WRITE_RANDOM_ADDR_CMD 6 -#define HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS 15 -#define HCIC_PARAM_SIZE_BLE_WRITE_SCAN_RSP 31 -#define HCIC_PARAM_SIZE_WRITE_ADV_ENABLE 1 -#define HCIC_PARAM_SIZE_BLE_WRITE_SCAN_PARAM 7 -#define HCIC_PARAM_SIZE_BLE_WRITE_SCAN_ENABLE 2 -#define HCIC_PARAM_SIZE_BLE_CREATE_LL_CONN 25 -#define HCIC_PARAM_SIZE_BLE_CREATE_CONN_CANCEL 0 -#define HCIC_PARAM_SIZE_CLEAR_WHITE_LIST 0 -#define HCIC_PARAM_SIZE_ADD_WHITE_LIST 7 -#define HCIC_PARAM_SIZE_REMOVE_WHITE_LIST 7 -#define HCIC_PARAM_SIZE_BLE_UPD_LL_CONN_PARAMS 14 -#define HCIC_PARAM_SIZE_SET_HOST_CHNL_CLASS 5 -#define HCIC_PARAM_SIZE_READ_CHNL_MAP 2 -#define HCIC_PARAM_SIZE_BLE_READ_REMOTE_FEAT 2 -#define HCIC_PARAM_SIZE_BLE_ENCRYPT 32 -#define HCIC_PARAM_SIZE_BLE_RAND 0 -#define HCIC_PARAM_SIZE_WRITE_LE_HOST_SUPPORTED 2 - -#define HCIC_BLE_RAND_DI_SIZE 8 -#define HCIC_BLE_ENCRYT_KEY_SIZE 16 -#define HCIC_PARAM_SIZE_BLE_START_ENC (4 + HCIC_BLE_RAND_DI_SIZE + HCIC_BLE_ENCRYT_KEY_SIZE) -#define HCIC_PARAM_SIZE_LTK_REQ_REPLY (2 + HCIC_BLE_ENCRYT_KEY_SIZE) -#define HCIC_PARAM_SIZE_LTK_REQ_NEG_REPLY 2 -#define HCIC_BLE_CHNL_MAP_SIZE 5 -#define HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA 31 - -#define HCIC_PARAM_SIZE_BLE_ADD_DEV_RESOLVING_LIST (7 + HCIC_BLE_IRK_SIZE * 2) -#define HCIC_PARAM_SIZE_BLE_RM_DEV_RESOLVING_LIST 7 -#define HCIC_PARAM_SIZE_BLE_CLEAR_RESOLVING_LIST 0 -#define HCIC_PARAM_SIZE_BLE_READ_RESOLVING_LIST_SIZE 0 -#define HCIC_PARAM_SIZE_BLE_READ_RESOLVABLE_ADDR_PEER 7 -#define HCIC_PARAM_SIZE_BLE_READ_RESOLVABLE_ADDR_LOCAL 7 -#define HCIC_PARAM_SIZE_BLE_SET_ADDR_RESOLUTION_ENABLE 1 -#define HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMOUT 2 -#define HCIC_PARAM_SIZE_BLE_SET_DATA_LENGTH 6 -#define HCIC_PARAM_SIZE_BLE_WRITE_EXTENDED_SCAN_PARAM 11 - -/* ULP HCI command */ -BOOLEAN btsnd_hcic_ble_set_evt_mask (BT_EVENT_MASK event_mask); - -BOOLEAN btsnd_hcic_ble_read_buffer_size (void); - -BOOLEAN btsnd_hcic_ble_read_local_spt_feat (void); - -BOOLEAN btsnd_hcic_ble_set_local_used_feat (UINT8 feat_set[8]); - -BOOLEAN btsnd_hcic_ble_set_random_addr (BD_ADDR random_addr); - -BOOLEAN btsnd_hcic_ble_write_adv_params (UINT16 adv_int_min, UINT16 adv_int_max, - UINT8 adv_type, UINT8 addr_type_own, - UINT8 addr_type_dir, BD_ADDR direct_bda, - UINT8 channel_map, UINT8 adv_filter_policy); - -BOOLEAN btsnd_hcic_ble_read_adv_chnl_tx_power (void); - -BOOLEAN btsnd_hcic_ble_set_adv_data (UINT8 data_len, UINT8 *p_data); - -BOOLEAN btsnd_hcic_ble_set_scan_rsp_data (UINT8 data_len, UINT8 *p_scan_rsp); - -BOOLEAN btsnd_hcic_ble_set_adv_enable (UINT8 adv_enable); - -BOOLEAN btsnd_hcic_ble_set_scan_params (UINT8 scan_type, - UINT16 scan_int, UINT16 scan_win, - UINT8 addr_type, UINT8 scan_filter_policy); - -BOOLEAN btsnd_hcic_ble_set_scan_enable (UINT8 scan_enable, UINT8 duplicate); - -BOOLEAN btsnd_hcic_ble_create_ll_conn (UINT16 scan_int, UINT16 scan_win, - UINT8 init_filter_policy, UINT8 addr_type_peer, BD_ADDR bda_peer, UINT8 addr_type_own, - UINT16 conn_int_min, UINT16 conn_int_max, UINT16 conn_latency, UINT16 conn_timeout, - UINT16 min_ce_len, UINT16 max_ce_len); - -BOOLEAN btsnd_hcic_ble_create_conn_cancel (void); - -BOOLEAN btsnd_hcic_ble_read_white_list_size (void); - -BOOLEAN btsnd_hcic_ble_clear_white_list (void); - -BOOLEAN btsnd_hcic_ble_add_white_list (UINT8 addr_type, BD_ADDR bda); - -BOOLEAN btsnd_hcic_ble_remove_from_white_list (UINT8 addr_type, BD_ADDR bda); - -BOOLEAN btsnd_hcic_ble_upd_ll_conn_params (UINT16 handle, UINT16 conn_int_min, UINT16 conn_int_max, - UINT16 conn_latency, UINT16 conn_timeout, UINT16 min_len, UINT16 max_len); - -BOOLEAN btsnd_hcic_ble_set_host_chnl_class (UINT8 chnl_map[HCIC_BLE_CHNL_MAP_SIZE]); - -BOOLEAN btsnd_hcic_ble_read_chnl_map (UINT16 handle); - -BOOLEAN btsnd_hcic_ble_read_remote_feat ( UINT16 handle); - -BOOLEAN btsnd_hcic_ble_encrypt (UINT8 *key, UINT8 key_len, UINT8 *plain_text, UINT8 pt_len, void *p_cmd_cplt_cback); - -BOOLEAN btsnd_hcic_ble_rand (void *p_cmd_cplt_cback); - -BOOLEAN btsnd_hcic_ble_start_enc ( UINT16 handle, - UINT8 rand[HCIC_BLE_RAND_DI_SIZE], - UINT16 ediv, UINT8 ltk[HCIC_BLE_ENCRYT_KEY_SIZE]); - -BOOLEAN btsnd_hcic_ble_ltk_req_reply (UINT16 handle, UINT8 ltk[HCIC_BLE_ENCRYT_KEY_SIZE]); - -BOOLEAN btsnd_hcic_ble_ltk_req_neg_reply (UINT16 handle); - -BOOLEAN btsnd_hcic_ble_read_supported_states (void); - -BOOLEAN btsnd_hcic_ble_write_host_supported (UINT8 le_host_spt, UINT8 simul_le_host_spt); - -BOOLEAN btsnd_hcic_ble_read_host_supported (void); - -BOOLEAN btsnd_hcic_ble_receiver_test(UINT8 rx_freq); - -BOOLEAN btsnd_hcic_ble_transmitter_test(UINT8 tx_freq, UINT8 test_data_len, - UINT8 payload); -BOOLEAN btsnd_hcic_ble_test_end(void); - -#if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE) - -#define HCIC_PARAM_SIZE_BLE_RC_PARAM_REQ_REPLY 14 -BOOLEAN btsnd_hcic_ble_rc_param_req_reply(UINT16 handle, - UINT16 conn_int_min, UINT16 conn_int_max, - UINT16 conn_latency, UINT16 conn_timeout, - UINT16 min_ce_len, UINT16 max_ce_len); - -#define HCIC_PARAM_SIZE_BLE_RC_PARAM_REQ_NEG_REPLY 3 -BOOLEAN btsnd_hcic_ble_rc_param_req_neg_reply(UINT16 handle, UINT8 reason); - -#endif /* BLE_LLT_INCLUDED */ - -BOOLEAN btsnd_hcic_ble_set_data_length(UINT16 conn_handle, UINT16 tx_octets, - UINT16 tx_time); - -BOOLEAN btsnd_hcic_ble_add_device_resolving_list (UINT8 addr_type_peer, - BD_ADDR bda_peer, - UINT8 irk_peer[HCIC_BLE_IRK_SIZE], - UINT8 irk_local[HCIC_BLE_IRK_SIZE]); - -BOOLEAN btsnd_hcic_ble_rm_device_resolving_list (UINT8 addr_type_peer, - BD_ADDR bda_peer); - -BOOLEAN btsnd_hcic_ble_clear_resolving_list (void); - -BOOLEAN btsnd_hcic_ble_read_resolvable_addr_peer (UINT8 addr_type_peer, - BD_ADDR bda_peer); - -BOOLEAN btsnd_hcic_ble_read_resolvable_addr_local (UINT8 addr_type_peer, - BD_ADDR bda_peer); - -BOOLEAN btsnd_hcic_ble_set_addr_resolution_enable (UINT8 addr_resolution_enable); - -BOOLEAN btsnd_hcic_ble_set_rand_priv_addr_timeout (UINT16 rpa_timout); - -#endif /* BLE_INCLUDED */ - -BOOLEAN btsnd_hcic_read_authenticated_payload_tout(UINT16 handle); - -BOOLEAN btsnd_hcic_write_authenticated_payload_tout(UINT16 handle, - UINT16 timeout); - -#define HCIC_PARAM_SIZE_WRITE_AUTHENT_PAYLOAD_TOUT 4 - -#define HCI__WRITE_AUTHENT_PAYLOAD_TOUT_HANDLE_OFF 0 -#define HCI__WRITE_AUTHENT_PAYLOAD_TOUT_TOUT_OFF 2 - -#endif diff --git a/tools/sdk/include/bluedroid/hid_conn.h b/tools/sdk/include/bluedroid/hid_conn.h deleted file mode 100644 index 320b78fa321..00000000000 --- a/tools/sdk/include/bluedroid/hid_conn.h +++ /dev/null @@ -1,69 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains HID connection internal definitions - * - ******************************************************************************/ - -#ifndef HID_CONN_H -#define HID_CONN_H - -#if (HID_HOST_INCLUDED == TRUE) -/* Define the HID Connection Block -*/ -typedef struct hid_conn { -#define HID_CONN_STATE_UNUSED (0) -#define HID_CONN_STATE_CONNECTING_CTRL (1) -#define HID_CONN_STATE_CONNECTING_INTR (2) -#define HID_CONN_STATE_CONFIG (3) -#define HID_CONN_STATE_CONNECTED (4) -#define HID_CONN_STATE_DISCONNECTING (5) -#define HID_CONN_STATE_SECURITY (6) - - UINT8 conn_state; - -#define HID_CONN_FLAGS_IS_ORIG (0x01) -#define HID_CONN_FLAGS_HIS_CTRL_CFG_DONE (0x02) -#define HID_CONN_FLAGS_MY_CTRL_CFG_DONE (0x04) -#define HID_CONN_FLAGS_HIS_INTR_CFG_DONE (0x08) -#define HID_CONN_FLAGS_MY_INTR_CFG_DONE (0x10) -#define HID_CONN_FLAGS_ALL_CONFIGURED (0x1E) /* All the config done */ -#define HID_CONN_FLAGS_CONGESTED (0x20) -#define HID_CONN_FLAGS_INACTIVE (0x40) - - UINT8 conn_flags; - - UINT8 ctrl_id; - UINT16 ctrl_cid; - UINT16 intr_cid; - UINT16 rem_mtu_size; - UINT16 disc_reason; /* Reason for disconnecting (for HID_HDEV_EVT_CLOSE) */ - TIMER_LIST_ENT timer_entry; - -} tHID_CONN; - -#define HID_SEC_CHN 1 -#define HID_NOSEC_CHN 2 - -#define HIDD_SEC_CHN 3 -#define HIDD_NOSEC_CHN 4 - -#endif ///HID_HOST_INCLUDED == TRUE -#endif diff --git a/tools/sdk/include/bluedroid/hid_le_prf.h b/tools/sdk/include/bluedroid/hid_le_prf.h deleted file mode 100644 index 6436573f810..00000000000 --- a/tools/sdk/include/bluedroid/hid_le_prf.h +++ /dev/null @@ -1,265 +0,0 @@ -// 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. - -#include "prf_defs.h" - -#if (HIDD_LE_PROFILE_CFG) -#include "bta_gatts_int.h" -#include "bt_types.h" -#include "bta_api.h" -#include "gatt_api.h" -#include "bt_app_api.h" - -/// Maximal number of HIDS that can be added in the DB -#ifndef USE_ONE_HIDS_INSTANCE -#define HIDD_LE_NB_HIDS_INST_MAX (2) -#else -#define HIDD_LE_NB_HIDS_INST_MAX (1) -#endif - -// Number of HID reports defined in the service -#define HID_NUM_REPORTS 9 - - -#define ATT_SVC_HID 0x1812 - -/// Maximal number of Report Char. that can be added in the DB for one HIDS - Up to 11 -#define HIDD_LE_NB_REPORT_INST_MAX (5) - -/// Maximal length of Report Char. Value -#define HIDD_LE_REPORT_MAX_LEN (45) -/// Maximal length of Report Map Char. Value -#define HIDD_LE_REPORT_MAP_MAX_LEN (512) - -/// Length of Boot Report Char. Value Maximal Length -#define HIDD_LE_BOOT_REPORT_MAX_LEN (8) - -/// Boot KB Input Report Notification Configuration Bit Mask -#define HIDD_LE_BOOT_KB_IN_NTF_CFG_MASK (0x40) -/// Boot KB Input Report Notification Configuration Bit Mask -#define HIDD_LE_BOOT_MOUSE_IN_NTF_CFG_MASK (0x80) -/// Boot Report Notification Configuration Bit Mask -#define HIDD_LE_REPORT_NTF_CFG_MASK (0x20) - - -/* HID information flags */ -#define HID_FLAGS_REMOTE_WAKE 0x01 // RemoteWake -#define HID_FLAGS_NORMALLY_CONNECTABLE 0x02 // NormallyConnectable - -/* Control point commands */ -#define HID_CMD_SUSPEND 0x00 // Suspend -#define HID_CMD_EXIT_SUSPEND 0x01 // Exit Suspend - -/* HID protocol mode values */ -#define HID_PROTOCOL_MODE_BOOT 0x00 // Boot Protocol Mode -#define HID_PROTOCOL_MODE_REPORT 0x01 // Report Protocol Mode - -/* Attribute value lengths */ -#define HID_PROTOCOL_MODE_LEN 1 // HID Protocol Mode -#define HID_INFORMATION_LEN 4 // HID Information -#define HID_REPORT_REF_LEN 2 // HID Report Reference Descriptor -#define HID_EXT_REPORT_REF_LEN 2 // External Report Reference Descriptor - -// HID feature flags -#define HID_KBD_FLAGS HID_FLAGS_REMOTE_WAKE - - -/// HID Service Attributes Indexes -enum { - HIDD_LE_IDX_SVC, - - // Included Service - HIDD_LE_IDX_INCL_SVC, - - // HID Information - HIDD_LE_IDX_HID_INFO_CHAR, - HIDD_LE_IDX_HID_INFO_VAL, - - // HID Control Point - HIDD_LE_IDX_HID_CTNL_PT_CHAR, - HIDD_LE_IDX_HID_CTNL_PT_VAL, - - // Report Map - HIDD_LE_IDX_REPORT_MAP_CHAR, - HIDD_LE_IDX_REPORT_MAP_VAL, - HIDD_LE_IDX_REPORT_MAP_EXT_REP_REF, - - // Protocol Mode - HIDD_LE_IDX_PROTO_MODE_CHAR, - HIDD_LE_IDX_PROTO_MODE_VAL, - - // Boot Keyboard Input Report - HIDD_LE_IDX_BOOT_KB_IN_REPORT_CHAR, - HIDD_LE_IDX_BOOT_KB_IN_REPORT_VAL, - HIDD_LE_IDX_BOOT_KB_IN_REPORT_NTF_CFG, - - // Boot Keyboard Output Report - HIDD_LE_IDX_BOOT_KB_OUT_REPORT_CHAR, - HIDD_LE_IDX_BOOT_KB_OUT_REPORT_VAL, - - // Boot Mouse Input Report - HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_CHAR, - HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_VAL, - HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_NTF_CFG, - - // Report - HIDD_LE_IDX_REPORT_CHAR, - HIDD_LE_IDX_REPORT_VAL, - HIDD_LE_IDX_REPORT_REP_REF, - HIDD_LE_IDX_REPORT_NTF_CFG, - - HIDD_LE_IDX_NB, -}; - - -/// Attribute Table Indexes -enum { - HIDD_LE_INFO_CHAR, - HIDD_LE_CTNL_PT_CHAR, - HIDD_LE_REPORT_MAP_CHAR, - HIDD_LE_REPORT_CHAR, - HIDD_LE_PROTO_MODE_CHAR, - HIDD_LE_BOOT_KB_IN_REPORT_CHAR, - HIDD_LE_BOOT_KB_OUT_REPORT_CHAR, - HIDD_LE_BOOT_MOUSE_IN_REPORT_CHAR, - HIDD_LE_CHAR_MAX //= HIDD_LE_REPORT_CHAR + HIDD_LE_NB_REPORT_INST_MAX, -}; - -///att read event table Indexs -enum { - HIDD_LE_READ_INFO_EVT, - HIDD_LE_READ_CTNL_PT_EVT, - HIDD_LE_READ_REPORT_MAP_EVT, - HIDD_LE_READ_REPORT_EVT, - HIDD_LE_READ_PROTO_MODE_EVT, - HIDD_LE_BOOT_KB_IN_REPORT_EVT, - HIDD_LE_BOOT_KB_OUT_REPORT_EVT, - HIDD_LE_BOOT_MOUSE_IN_REPORT_EVT, - - HID_LE_EVT_MAX -}; - -/// Client Characteristic Configuration Codes -enum { - HIDD_LE_DESC_MASK = 0x10, - - HIDD_LE_BOOT_KB_IN_REPORT_CFG = HIDD_LE_BOOT_KB_IN_REPORT_CHAR | HIDD_LE_DESC_MASK, - HIDD_LE_BOOT_MOUSE_IN_REPORT_CFG = HIDD_LE_BOOT_MOUSE_IN_REPORT_CHAR | HIDD_LE_DESC_MASK, - HIDD_LE_REPORT_CFG = HIDD_LE_REPORT_CHAR | HIDD_LE_DESC_MASK, -}; - -/// Features Flag Values -enum { - HIDD_LE_CFG_KEYBOARD = 0x01, - HIDD_LE_CFG_MOUSE = 0x02, - HIDD_LE_CFG_PROTO_MODE = 0x04, - HIDD_LE_CFG_MAP_EXT_REF = 0x08, - HIDD_LE_CFG_BOOT_KB_WR = 0x10, - HIDD_LE_CFG_BOOT_MOUSE_WR = 0x20, -}; - -/// Report Char. Configuration Flag Values -enum { - HIDD_LE_CFG_REPORT_IN = 0x01, - HIDD_LE_CFG_REPORT_OUT = 0x02, - //HOGPD_CFG_REPORT_FEAT can be used as a mask to check Report type - HIDD_LE_CFG_REPORT_FEAT = 0x03, - HIDD_LE_CFG_REPORT_WR = 0x10, -}; - -/// Pointer to the connection clean-up function -#define HIDD_LE_CLEANUP_FNCT (NULL) - -/* - * TYPE DEFINITIONS - **************************************************************************************** - */ - -/// HIDD Features structure -typedef struct { - /// Service Features - uint8_t svc_features; - /// Number of Report Char. instances to add in the database - uint8_t report_nb; - /// Report Char. Configuration - uint8_t report_char_cfg[HIDD_LE_NB_REPORT_INST_MAX]; -} hidd_feature_t; - - -typedef struct { - BOOLEAN in_use; - BOOLEAN congest; - uint16_t conn_id; - BOOLEAN connected; - BD_ADDR remote_bda; - uint32_t trans_id; - uint8_t cur_srvc_id; - -} hidd_clcb_t; - -// HID report mapping table -typedef struct { - uint16_t handle; // Handle of report characteristic - uint16_t cccdHandle; // Handle of CCCD for report characteristic - uint8_t id; // Report ID - uint8_t type; // Report type - uint8_t mode; // Protocol mode (report or boot) -} hidRptMap_t; - - -typedef struct { - /// hidd profile id - uint8_t app_id; - /// Notified handle - uint16_t ntf_handle; - ///Attribute handle Table - uint16_t att_tbl[HIDD_LE_CHAR_MAX]; - /// Supported Features - hidd_feature_t hidd_feature[HIDD_LE_NB_HIDS_INST_MAX]; - /// Current Protocol Mode - uint8_t proto_mode[HIDD_LE_NB_HIDS_INST_MAX]; - /// Number of HIDS added in the database - uint8_t hids_nb; - uint8_t pending_evt; - uint16_t pending_hal; -} hidd_inst_t; - - -/* service engine control block */ -typedef struct { - hidd_clcb_t hidd_clcb; /* connection link*/ - esp_gatt_if_t gatt_if; - BOOLEAN enabled; - BOOLEAN is_primery; - hidd_inst_t hidd_inst; - uint8_t inst_id; -} hidd_le_env_t; - -extern hidd_le_env_t hidd_le_env; - - -void hidd_le_create_service(BOOLEAN is_primary); - -void hidd_rsp (uint32_t trans_id, uint16_t conn_id, uint8_t app_id, - esp_gatt_status_t status, uint8_t event, tGATTS_DATA *p_rsp); - -void hidd_read_attr_value(tGATTS_DATA *p_data, uint32_t trans_id); - - -tGATT_STATUS hidd_le_init (void); - - -#endif ///HIDD_LE_PROFILE_CFG - - diff --git a/tools/sdk/include/bluedroid/hiddefs.h b/tools/sdk/include/bluedroid/hiddefs.h deleted file mode 100644 index 23777f3adf4..00000000000 --- a/tools/sdk/include/bluedroid/hiddefs.h +++ /dev/null @@ -1,163 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains HID protocol definitions - * - ******************************************************************************/ - -#ifndef HIDDEFS_H -#define HIDDEFS_H -#include "bt_target.h" -#if (HID_HOST_INCLUDED == TRUE) - -#if (SDP_INCLUDED == TRUE) -#include "sdp_api.h" -#endif ///SDP_INCLUDED == TRUE -/* -** tHID_STATUS: HID result codes, returned by HID and device and host functions. -*/ -enum { - HID_SUCCESS, - HID_ERR_NOT_REGISTERED, - HID_ERR_ALREADY_REGISTERED, - HID_ERR_NO_RESOURCES, - HID_ERR_NO_CONNECTION, - HID_ERR_INVALID_PARAM, - HID_ERR_UNSUPPORTED, - HID_ERR_UNKNOWN_COMMAND, - HID_ERR_CONGESTED, - HID_ERR_CONN_IN_PROCESS, - HID_ERR_ALREADY_CONN, - HID_ERR_DISCONNECTING, - HID_ERR_SET_CONNABLE_FAIL, - /* Device specific error codes */ - HID_ERR_HOST_UNKNOWN, - HID_ERR_L2CAP_FAILED, - HID_ERR_AUTH_FAILED, - HID_ERR_SDP_BUSY, - HID_ERR_GATT, - - HID_ERR_INVALID = 0xFF -}; - -typedef UINT8 tHID_STATUS; - -#define HID_L2CAP_CONN_FAIL (0x0100) /* Connection Attempt was made but failed */ -#define HID_L2CAP_REQ_FAIL (0x0200) /* L2CAP_ConnectReq API failed */ -#define HID_L2CAP_CFG_FAIL (0x0400) /* L2CAP Configuration was rejected by peer */ - - - -/* Define the HID transaction types -*/ -#define HID_TRANS_HANDSHAKE (0) -#define HID_TRANS_CONTROL (1) -#define HID_TRANS_GET_REPORT (4) -#define HID_TRANS_SET_REPORT (5) -#define HID_TRANS_GET_PROTOCOL (6) -#define HID_TRANS_SET_PROTOCOL (7) -#define HID_TRANS_GET_IDLE (8) -#define HID_TRANS_SET_IDLE (9) -#define HID_TRANS_DATA (10) -#define HID_TRANS_DATAC (11) - -#define HID_GET_TRANS_FROM_HDR(x) ((x >> 4) & 0x0f) -#define HID_GET_PARAM_FROM_HDR(x) (x & 0x0f) -#define HID_BUILD_HDR(t,p) (UINT8)((t << 4) | (p & 0x0f)) - - -/* Parameters for Handshake -*/ -#define HID_PAR_HANDSHAKE_RSP_SUCCESS (0) -#define HID_PAR_HANDSHAKE_RSP_NOT_READY (1) -#define HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID (2) -#define HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ (3) -#define HID_PAR_HANDSHAKE_RSP_ERR_INVALID_PARAM (4) -#define HID_PAR_HANDSHAKE_RSP_ERR_UNKNOWN (14) -#define HID_PAR_HANDSHAKE_RSP_ERR_FATAL (15) - - -/* Parameters for Control -*/ -#define HID_PAR_CONTROL_NOP (0) -#define HID_PAR_CONTROL_HARD_RESET (1) -#define HID_PAR_CONTROL_SOFT_RESET (2) -#define HID_PAR_CONTROL_SUSPEND (3) -#define HID_PAR_CONTROL_EXIT_SUSPEND (4) -#define HID_PAR_CONTROL_VIRTUAL_CABLE_UNPLUG (5) - - -/* Different report types in get, set, data -*/ -#define HID_PAR_REP_TYPE_MASK (0x03) -#define HID_PAR_REP_TYPE_OTHER (0x00) -#define HID_PAR_REP_TYPE_INPUT (0x01) -#define HID_PAR_REP_TYPE_OUTPUT (0x02) -#define HID_PAR_REP_TYPE_FEATURE (0x03) - -/* Parameters for Get Report -*/ - -/* Buffer size in two bytes after Report ID */ -#define HID_PAR_GET_REP_BUFSIZE_FOLLOWS (0x08) - - -/* Parameters for Protocol Type -*/ -#define HID_PAR_PROTOCOL_MASK (0x01) -#define HID_PAR_PROTOCOL_REPORT (0x01) -#define HID_PAR_PROTOCOL_BOOT_MODE (0x00) - -#define HID_PAR_REP_TYPE_MASK (0x03) - -/* Descriptor types in the SDP record -*/ -#define HID_SDP_DESCRIPTOR_REPORT (0x22) -#define HID_SDP_DESCRIPTOR_PHYSICAL (0x23) - -typedef struct desc_info { - UINT16 dl_len; - UINT8 *dsc_list; -} tHID_DEV_DSCP_INFO; - -#define HID_SSR_PARAM_INVALID 0xffff - -typedef struct sdp_info { - char svc_name[HID_MAX_SVC_NAME_LEN]; /*Service Name */ - char svc_descr[HID_MAX_SVC_DESCR_LEN]; /*Service Description*/ - char prov_name[HID_MAX_PROV_NAME_LEN]; /*Provider Name.*/ - UINT16 rel_num; /*Release Number */ - UINT16 hpars_ver; /*HID Parser Version.*/ - UINT16 ssr_max_latency; /* HIDSSRHostMaxLatency value, if HID_SSR_PARAM_INVALID not used*/ - UINT16 ssr_min_tout; /* HIDSSRHostMinTimeout value, if HID_SSR_PARAM_INVALID not used* */ - UINT8 sub_class; /*Device Subclass.*/ - UINT8 ctry_code; /*Country Code.*/ - UINT16 sup_timeout;/* Supervisory Timeout */ - - tHID_DEV_DSCP_INFO dscp_info; /* Descriptor list and Report list to be set in the SDP record. - This parameter is used if HID_DEV_USE_GLB_SDP_REC is set to FALSE.*/ -#if(SDP_INCLUDED == TRUE) - tSDP_DISC_REC *p_sdp_layer_rec; -#endif ///SDP_INCLUDED == TRUE -} tHID_DEV_SDP_INFO; - -#endif ///HID_HOST_INCLUDED == TRUE -#endif - diff --git a/tools/sdk/include/bluedroid/hidh_api.h b/tools/sdk/include/bluedroid/hidh_api.h deleted file mode 100644 index 29344df905c..00000000000 --- a/tools/sdk/include/bluedroid/hidh_api.h +++ /dev/null @@ -1,238 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 HIDH_API_H -#define HIDH_API_H - -#include "hiddefs.h" -#include "sdp_api.h" - -#if (HID_HOST_INCLUDED == TRUE) -/***************************************************************************** -** Constants -*****************************************************************************/ - -enum { - HID_SDP_NO_SERV_UUID = (SDP_ILLEGAL_PARAMETER + 1), - HID_SDP_MANDATORY_MISSING -}; - -/* Attributes mask values to be used in HID_HostAddDev API */ -#define HID_VIRTUAL_CABLE 0x0001 -#define HID_NORMALLY_CONNECTABLE 0x0002 -#define HID_RECONN_INIT 0x0004 -#define HID_SDP_DISABLE 0x0008 -#define HID_BATTERY_POWER 0x0010 -#define HID_REMOTE_WAKE 0x0020 -#define HID_SUP_TOUT_AVLBL 0x0040 -#define HID_SSR_MAX_LATENCY 0x0080 -#define HID_SSR_MIN_TOUT 0x0100 - -#define HID_SEC_REQUIRED 0x8000 -#define HID_ATTR_MASK_IGNORE 0 - - -/***************************************************************************** -** Type Definitions -*****************************************************************************/ - -typedef void (tHID_HOST_SDP_CALLBACK) (UINT16 result, UINT16 attr_mask, - tHID_DEV_SDP_INFO *sdp_rec ); - -/* HID-HOST returns the events in the following table to the application via tHID_HOST_DEV_CALLBACK -HID_HDEV_EVT_OPEN Connected to device with Interrupt and Control Channels in OPEN state. - Data = NA -HID_HDEV_EVT_CLOSE Connection with device is closed. Data=reason code. -HID_HDEV_EVT_RETRYING Lost connection is being re-connected. - Data=Retrial number -HID_HDEV_EVT_IN_REPORT Device sent an input report Data=Report Type pdata= pointer to BT_HDR - (GKI buffer having report data.) -HID_HDEV_EVT_HANDSHAKE Device sent SET_REPORT Data=Result-code pdata=NA. -HID_HDEV_EVT_VC_UNPLUG Device sent Virtual Unplug Data=NA. pdata=NA. -*/ - -enum { - HID_HDEV_EVT_OPEN, - HID_HDEV_EVT_CLOSE, - HID_HDEV_EVT_RETRYING, - HID_HDEV_EVT_INTR_DATA, - HID_HDEV_EVT_INTR_DATC, - HID_HDEV_EVT_CTRL_DATA, - HID_HDEV_EVT_CTRL_DATC, - HID_HDEV_EVT_HANDSHAKE, - HID_HDEV_EVT_VC_UNPLUG -}; -typedef void (tHID_HOST_DEV_CALLBACK) (UINT8 dev_handle, - BD_ADDR addr, - UINT8 event, /* Event from HID-DEVICE. */ - UINT32 data, /* Integer data corresponding to the event.*/ - BT_HDR *p_buf ); /* Pointer data corresponding to the event. */ - - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function HID_HostGetSDPRecord -** -** Description This function reads the device SDP record. -** -** Returns tHID_STATUS -** -*******************************************************************************/ -extern tHID_STATUS HID_HostGetSDPRecord (BD_ADDR addr, - tSDP_DISCOVERY_DB *p_db, - UINT32 db_len, - tHID_HOST_SDP_CALLBACK *sdp_cback ); - -/******************************************************************************* -** -** Function HID_HostRegister -** -** Description This function registers HID-Host with lower layers. -** -** Returns tHID_STATUS -** -*******************************************************************************/ -extern tHID_STATUS HID_HostRegister (tHID_HOST_DEV_CALLBACK *dev_cback); - -/******************************************************************************* -** -** Function HID_HostDeregister -** -** Description This function is called when the host is about power down. -** -** Returns tHID_STATUS -** -*******************************************************************************/ -extern tHID_STATUS HID_HostDeregister(void); - -/******************************************************************************* -** -** Function HID_HostAddDev -** -** Description This is called so HID-host may manage this device. -** -** Returns tHID_STATUS -** -*******************************************************************************/ -extern tHID_STATUS HID_HostAddDev (BD_ADDR addr, UINT16 attr_mask, - UINT8 *handle ); - -/******************************************************************************* -** -** Function HID_HostRemoveDev -** -** Description This removes the device from list devices that host has to manage. -** -** Returns tHID_STATUS -** -*******************************************************************************/ -extern tHID_STATUS HID_HostRemoveDev (UINT8 dev_handle ); - -/******************************************************************************* -** -** Function HID_HostOpenDev -** -** Description This function is called when the user wants to initiate a -** connection attempt to a device. -** -** Returns void -** -*******************************************************************************/ -extern tHID_STATUS HID_HostOpenDev (UINT8 dev_handle ); - -/******************************************************************************* -** -** Function HID_HostWriteDev -** -** Description This function is called when the host has a report to send. -** -** Returns void -** -*******************************************************************************/ -extern tHID_STATUS HID_HostWriteDev(UINT8 dev_handle, UINT8 t_type, - UINT8 param, UINT16 data, - UINT8 report_id, BT_HDR *pbuf); - -/******************************************************************************* -** -** Function HID_HostCloseDev -** -** Description This function disconnects the device. -** -** Returns void -** -*******************************************************************************/ -extern tHID_STATUS HID_HostCloseDev(UINT8 dev_handle ); - -/******************************************************************************* -** Function HID_HostInit -** -** Description This function initializes the control block and trace variable -** -** Returns void -*******************************************************************************/ -extern void HID_HostInit(void); - -/******************************************************************************* -** Function HID_HostSetSecurityLevel -** -** Description This function sets the security level for the devices which -** are marked by application as requiring security -** -** Returns tHID_STATUS -*******************************************************************************/ -extern tHID_STATUS HID_HostSetSecurityLevel( char serv_name[], UINT8 sec_lvl ); - -/******************************************************************************* -** -** Function hid_known_hid_device -** -** Description This function checks if this device is of type HID Device -** -** Returns TRUE if device exists else FALSE -** -*******************************************************************************/ -BOOLEAN hid_known_hid_device (BD_ADDR bd_addr); - - -/******************************************************************************* -** -** Function HID_HostSetTraceLevel -** -** Description This function sets the trace level for HID Host. If called with -** a value of 0xFF, it simply reads the current trace level. -** -** Returns the new (current) trace level -** -*******************************************************************************/ -extern UINT8 HID_HostSetTraceLevel (UINT8 new_level); - -#ifdef __cplusplus -} -#endif - -#endif ///HID_HOST_INCLUDED == TRUE - -#endif /* HIDH_API_H */ diff --git a/tools/sdk/include/bluedroid/hidh_int.h b/tools/sdk/include/bluedroid/hidh_int.h deleted file mode 100644 index a1d40781d70..00000000000 --- a/tools/sdk/include/bluedroid/hidh_int.h +++ /dev/null @@ -1,95 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2002-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains HID HOST internal definitions - * - ******************************************************************************/ - -#ifndef HIDH_INT_H -#define HIDH_INT_H - -#include "hidh_api.h" -#include "hid_conn.h" -#include "l2c_api.h" - -#if (HID_HOST_INCLUDED == TRUE) - -enum { - HID_DEV_NO_CONN, - HID_DEV_CONNECTED -}; - -typedef struct per_device_ctb { - BOOLEAN in_use; - BD_ADDR addr; /* BD-Addr of the host device */ - UINT16 attr_mask; /* 0x01- virtual_cable; 0x02- normally_connectable; 0x03- reconn_initiate; - 0x04- sdp_disable; */ - UINT8 state; /* Device state if in HOST-KNOWN mode */ - UINT8 conn_substate; - UINT8 conn_tries; /* Remembers to the number of connection attempts while CONNECTING */ - - tHID_CONN conn; /* L2CAP channel info */ -} tHID_HOST_DEV_CTB; - -typedef struct host_ctb { - tHID_HOST_DEV_CTB devices[HID_HOST_MAX_DEVICES]; - tHID_HOST_DEV_CALLBACK *callback; /* Application callbacks */ - tL2CAP_CFG_INFO l2cap_cfg; - -#define MAX_SERVICE_DB_SIZE 4000 - - BOOLEAN sdp_busy; - tHID_HOST_SDP_CALLBACK *sdp_cback; - tSDP_DISCOVERY_DB *p_sdp_db; - tHID_DEV_SDP_INFO sdp_rec; - BOOLEAN reg_flag; - UINT8 trace_level; -} tHID_HOST_CTB; - -extern tHID_STATUS hidh_conn_snd_data(UINT8 dhandle, UINT8 trans_type, UINT8 param, \ - UINT16 data, UINT8 rpt_id, BT_HDR *buf); -extern tHID_STATUS hidh_conn_reg (void); -extern void hidh_conn_dereg( void ); -extern tHID_STATUS hidh_conn_disconnect (UINT8 dhandle); -extern tHID_STATUS hidh_conn_initiate (UINT8 dhandle); -extern void hidh_proc_repage_timeout (TIMER_LIST_ENT *p_tle); - -#ifdef __cplusplus -extern "C" -{ -#endif - -/****************************************************************************** -** Main Control Block -*******************************************************************************/ -#if HID_DYNAMIC_MEMORY == FALSE -extern tHID_HOST_CTB hh_cb; -#else -extern tHID_HOST_CTB *hidh_cb_ptr; -#define hh_cb (*hidh_cb_ptr) -#endif - -#ifdef __cplusplus -} -#endif - -#endif ///HID_HOST_INCLUDED == TRUE - -#endif diff --git a/tools/sdk/include/bluedroid/interop.h b/tools/sdk/include/bluedroid/interop.h deleted file mode 100644 index a90c44ad292..00000000000 --- a/tools/sdk/include/bluedroid/interop.h +++ /dev/null @@ -1,45 +0,0 @@ -/****************************************************************************** - * - * 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 _INTEROP_H_ -#define _INTEROP_H_ - -#include -#include "bt_defs.h" -#include "bt_target.h" - -typedef enum { - // Disable secure connections - // This is for pre BT 4.1/2 devices that do not handle secure mode - // very well. - INTEROP_DISABLE_LE_SECURE_CONNECTIONS, - - // Some devices have proven problematic during the pairing process, often - // requiring multiple retries to complete pairing. To avoid degrading the user - // experience for those devices, automatically re-try pairing if page - // timeouts are received during pairing. - INTEROP_AUTO_RETRY_PAIRING -} interop_feature_t; - -// Check if a given |addr| matches a known interoperability workaround as identified -// by the |interop_feature_t| enum. This API is used for simple address based lookups -// where more information is not available. No look-ups or random address resolution -// is performed on |addr|. -bool interop_match(const interop_feature_t feature, const bt_bdaddr_t *addr); - -#endif /*_INTEROP_H_*/ diff --git a/tools/sdk/include/bluedroid/interop_database.h b/tools/sdk/include/bluedroid/interop_database.h deleted file mode 100644 index 5b9bc934a72..00000000000 --- a/tools/sdk/include/bluedroid/interop_database.h +++ /dev/null @@ -1,50 +0,0 @@ -/****************************************************************************** - * - * 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 _INTEROP_DATABASE_H_ -#define _INTEROP_DATABASE_H_ - -#include "interop.h" - -typedef struct { - bt_bdaddr_t addr; - uint8_t len; - interop_feature_t feature; -} interop_entry_t; - -static const interop_entry_t interop_database[] = { - // Nexus Remote (Spike) - // Note: May affect other Asus brand devices - {{{0x08, 0x62, 0x66, 0, 0, 0}}, 3, INTEROP_DISABLE_LE_SECURE_CONNECTIONS}, - {{{0x38, 0x2c, 0x4a, 0xc9, 0, 0}}, 4, INTEROP_DISABLE_LE_SECURE_CONNECTIONS}, - {{{0x38, 0x2c, 0x4a, 0xe6, 0, 0}}, 4, INTEROP_DISABLE_LE_SECURE_CONNECTIONS}, - {{{0x54, 0xa0, 0x50, 0xd9, 0, 0}}, 4, INTEROP_DISABLE_LE_SECURE_CONNECTIONS}, - {{{0xac, 0x9e, 0x17, 0, 0, 0}}, 3, INTEROP_DISABLE_LE_SECURE_CONNECTIONS}, - {{{0xf0, 0x79, 0x59, 0, 0, 0}}, 3, INTEROP_DISABLE_LE_SECURE_CONNECTIONS}, - - // Motorola Key Link - {{{0x1c, 0x96, 0x5a, 0, 0, 0}}, 3, INTEROP_DISABLE_LE_SECURE_CONNECTIONS}, - - // Flic smart button - {{{0x80, 0xe4, 0xda, 0x70, 0, 0}}, 4, INTEROP_DISABLE_LE_SECURE_CONNECTIONS}, - - // BMW car kits (Harman/Becker) - {{{0x9c, 0xdf, 0x03, 0, 0, 0}}, 3, INTEROP_AUTO_RETRY_PAIRING} -}; - -#endif /*_INTEROP_DATABASE_H_*/ diff --git a/tools/sdk/include/bluedroid/l2c_api.h b/tools/sdk/include/bluedroid/l2c_api.h deleted file mode 100644 index 71e1f481681..00000000000 --- a/tools/sdk/include/bluedroid/l2c_api.h +++ /dev/null @@ -1,1234 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * this file contains the L2CAP API definitions - * - ******************************************************************************/ -#ifndef L2C_API_H -#define L2C_API_H - -#include - -#include "bt_target.h" -#include "l2cdefs.h" -#include "hcidefs.h" - -/***************************************************************************** -** Constants -*****************************************************************************/ - -/* Define the minimum offset that L2CAP needs in a buffer. This is made up of -** HCI type(1), len(2), handle(2), L2CAP len(2) and CID(2) => 9 -*/ -#define L2CAP_MIN_OFFSET 13 /* plus control(2), SDU length(2) */ - -/* Minimum offset for broadcast needs another two bytes for the PSM */ -#define L2CAP_BCST_MIN_OFFSET 11 - -/* ping result codes */ -#define L2CAP_PING_RESULT_OK 0 /* Ping reply received OK */ -#define L2CAP_PING_RESULT_NO_LINK 1 /* Link could not be setup */ -#define L2CAP_PING_RESULT_NO_RESP 2 /* Remote L2CAP did not reply */ - -/* result code for L2CA_DataWrite() */ -#define L2CAP_DW_FAILED FALSE -#define L2CAP_DW_SUCCESS TRUE -#define L2CAP_DW_CONGESTED 2 - -/* Values for priority parameter to L2CA_SetAclPriority */ -#define L2CAP_PRIORITY_NORMAL 0 -#define L2CAP_PRIORITY_HIGH 1 - -/* Values for priority parameter to L2CA_SetTxPriority */ -#define L2CAP_CHNL_PRIORITY_HIGH 0 -#define L2CAP_CHNL_PRIORITY_MEDIUM 1 -#define L2CAP_CHNL_PRIORITY_LOW 2 - -typedef UINT8 tL2CAP_CHNL_PRIORITY; - -/* Values for Tx/Rx data rate parameter to L2CA_SetChnlDataRate */ -#define L2CAP_CHNL_DATA_RATE_HIGH 3 -#define L2CAP_CHNL_DATA_RATE_MEDIUM 2 -#define L2CAP_CHNL_DATA_RATE_LOW 1 -#define L2CAP_CHNL_DATA_RATE_NO_TRAFFIC 0 - -typedef UINT8 tL2CAP_CHNL_DATA_RATE; - -/* Data Packet Flags (bits 2-15 are reserved) */ -/* layer specific 14-15 bits are used for FCR SAR */ -#define L2CAP_FLUSHABLE_MASK 0x0003 -#define L2CAP_FLUSHABLE_CH_BASED 0x0000 -#define L2CAP_FLUSHABLE_PKT 0x0001 -#define L2CAP_NON_FLUSHABLE_PKT 0x0002 - - -/* L2CA_FlushChannel num_to_flush definitions */ -#define L2CAP_FLUSH_CHANS_ALL 0xffff -#define L2CAP_FLUSH_CHANS_GET 0x0000 - - -/* special CID for Multi-AV for reporting congestion */ -#define L2CAP_MULTI_AV_CID 0 - -/* length of the HCI header block */ -/* HCI header(4) + SNK count(1) + FCR bits(1) + AV data length(2) */ -#define L2CAP_MULTI_AV_HCI_HDR_LEN 8 - -/* length of padding for 4 bytes align */ -#define L2CAP_MULTI_AV_PADDING_LEN 2 - -/* length of the HCI header block with padding for FCR */ -/* HCI header(4) + SNK count(1) + FCR bits(1) + AV data length(2) + padding(2) */ -#define L2CAP_MULTI_AV_HCI_HDR_LEN_WITH_PADDING 10 - -/* length of the L2CAP header block */ -/* HCI header(4) + L2CAP header(4) + padding(4) or control word(2) + FCS(2) */ -#define L2CAP_MULTI_AV_L2C_HDR_LEN 12 - -/* definition used for L2CA_SetDesireRole */ -#define L2CAP_ROLE_SLAVE HCI_ROLE_SLAVE -#define L2CAP_ROLE_MASTER HCI_ROLE_MASTER -#define L2CAP_ROLE_ALLOW_SWITCH 0x80 /* set this bit to allow switch at create conn */ -#define L2CAP_ROLE_DISALLOW_SWITCH 0x40 /* set this bit to disallow switch at create conn */ -#define L2CAP_ROLE_CHECK_SWITCH 0xC0 - - -/* Values for 'allowed_modes' field passed in structure tL2CAP_ERTM_INFO -*/ -#define L2CAP_FCR_CHAN_OPT_BASIC (1 << L2CAP_FCR_BASIC_MODE) -#define L2CAP_FCR_CHAN_OPT_ERTM (1 << L2CAP_FCR_ERTM_MODE) -#define L2CAP_FCR_CHAN_OPT_STREAM (1 << L2CAP_FCR_STREAM_MODE) - -#define L2CAP_FCR_CHAN_OPT_ALL_MASK (L2CAP_FCR_CHAN_OPT_BASIC | L2CAP_FCR_CHAN_OPT_ERTM | L2CAP_FCR_CHAN_OPT_STREAM) - -/* Validity check for PSM. PSM values must be odd. Also, all PSM values must -** be assigned such that the least significant bit of the most sigificant -** octet equals zero. -*/ -#define L2C_INVALID_PSM(psm) (((psm) & 0x0101) != 0x0001) -#define L2C_IS_VALID_PSM(psm) (((psm) & 0x0101) == 0x0001) -#define L2C_IS_VALID_LE_PSM(psm) (((psm) > 0x0000) && ((psm) < 0x0100)) - - -/***************************************************************************** -** Type Definitions -*****************************************************************************/ - -typedef struct { -#define L2CAP_FCR_BASIC_MODE 0x00 -#define L2CAP_FCR_ERTM_MODE 0x03 -#define L2CAP_FCR_STREAM_MODE 0x04 - - UINT8 mode; - - UINT8 tx_win_sz; - UINT8 max_transmit; - UINT16 rtrans_tout; - UINT16 mon_tout; - UINT16 mps; -} tL2CAP_FCR_OPTS; - -/* Define a structure to hold the configuration parameters. Since the -** parameters are optional, for each parameter there is a boolean to -** use to signify its presence or absence. -*/ -typedef struct { - UINT16 result; /* Only used in confirm messages */ - BOOLEAN mtu_present; - UINT16 mtu; - BOOLEAN qos_present; - FLOW_SPEC qos; - BOOLEAN flush_to_present; - UINT16 flush_to; - BOOLEAN fcr_present; - tL2CAP_FCR_OPTS fcr; - BOOLEAN fcs_present; /* Optionally bypasses FCS checks */ - UINT8 fcs; /* '0' if desire is to bypass FCS, otherwise '1' */ - BOOLEAN ext_flow_spec_present; - tHCI_EXT_FLOW_SPEC ext_flow_spec; - UINT16 flags; /* bit 0: 0-no continuation, 1-continuation */ -} tL2CAP_CFG_INFO; - -/* Define a structure to hold the configuration parameter for LE L2CAP connection -** oriented channels. -*/ -typedef struct -{ - UINT16 mtu; - UINT16 mps; - UINT16 credits; -} tL2CAP_LE_CFG_INFO; - - -/* L2CAP channel configured field bitmap */ -#define L2CAP_CH_CFG_MASK_MTU 0x0001 -#define L2CAP_CH_CFG_MASK_QOS 0x0002 -#define L2CAP_CH_CFG_MASK_FLUSH_TO 0x0004 -#define L2CAP_CH_CFG_MASK_FCR 0x0008 -#define L2CAP_CH_CFG_MASK_FCS 0x0010 -#define L2CAP_CH_CFG_MASK_EXT_FLOW_SPEC 0x0020 - -typedef UINT16 tL2CAP_CH_CFG_BITS; - -/********************************* -** Callback Functions Prototypes -**********************************/ - -/* Connection indication callback prototype. Parameters are -** BD Address of remote -** Local CID assigned to the connection -** PSM that the remote wants to connect to -** Identifier that the remote sent -*/ -typedef void (tL2CA_CONNECT_IND_CB) (BD_ADDR, UINT16, UINT16, UINT8); - - -/* Connection confirmation callback prototype. Parameters are -** Local CID -** Result - 0 = connected, non-zero means failure reason -*/ -typedef void (tL2CA_CONNECT_CFM_CB) (UINT16, UINT16); - - -/* Connection pending callback prototype. Parameters are -** Local CID -*/ -typedef void (tL2CA_CONNECT_PND_CB) (UINT16); - - -/* Configuration indication callback prototype. Parameters are -** Local CID assigned to the connection -** Pointer to configuration info -*/ -typedef void (tL2CA_CONFIG_IND_CB) (UINT16, tL2CAP_CFG_INFO *); - - -/* Configuration confirm callback prototype. Parameters are -** Local CID assigned to the connection -** Pointer to configuration info -*/ -typedef void (tL2CA_CONFIG_CFM_CB) (UINT16, tL2CAP_CFG_INFO *); - - -/* Disconnect indication callback prototype. Parameters are -** Local CID -** Boolean whether upper layer should ack this -*/ -typedef void (tL2CA_DISCONNECT_IND_CB) (UINT16, BOOLEAN); - - -/* Disconnect confirm callback prototype. Parameters are -** Local CID -** Result -*/ -typedef void (tL2CA_DISCONNECT_CFM_CB) (UINT16, UINT16); - - -/* QOS Violation indication callback prototype. Parameters are -** BD Address of violating device -*/ -typedef void (tL2CA_QOS_VIOLATION_IND_CB) (BD_ADDR); - - -/* Data received indication callback prototype. Parameters are -** Local CID -** Address of buffer -*/ -typedef void (tL2CA_DATA_IND_CB) (UINT16, BT_HDR *); - - -/* Echo response callback prototype. Note that this is not included in the -** registration information, but is passed to L2CAP as part of the API to -** actually send an echo request. Parameters are -** Result -*/ -typedef void (tL2CA_ECHO_RSP_CB) (UINT16); - - -/* Callback function prototype to pass broadcom specific echo response */ -/* to the upper layer */ -typedef void (tL2CA_ECHO_DATA_CB) (BD_ADDR, UINT16, UINT8 *); - - -/* Congestion status callback protype. This callback is optional. If -** an application tries to send data when the transmit queue is full, -** the data will anyways be dropped. The parameter is: -** Local CID -** TRUE if congested, FALSE if uncongested -*/ -typedef void (tL2CA_CONGESTION_STATUS_CB) (UINT16, BOOLEAN); - -/* Callback prototype for number of packets completed events. -** This callback notifies the application when Number of Completed Packets -** event has been received. -** This callback is originally designed for 3DG devices. -** The parameter is: -** peer BD_ADDR -*/ -typedef void (tL2CA_NOCP_CB) (BD_ADDR); - -/* Transmit complete callback protype. This callback is optional. If -** set, L2CAP will call it when packets are sent or flushed. If the -** count is 0xFFFF, it means all packets are sent for that CID (eRTM -** mode only). The parameters are: -** Local CID -** Number of SDUs sent or dropped -*/ -typedef void (tL2CA_TX_COMPLETE_CB) (UINT16, UINT16); - -/* Define the structure that applications use to register with -** L2CAP. This structure includes callback functions. All functions -** MUST be provided, with the exception of the "connect pending" -** callback and "congestion status" callback. -*/ -typedef struct { - tL2CA_CONNECT_IND_CB *pL2CA_ConnectInd_Cb; - tL2CA_CONNECT_CFM_CB *pL2CA_ConnectCfm_Cb; - tL2CA_CONNECT_PND_CB *pL2CA_ConnectPnd_Cb; - tL2CA_CONFIG_IND_CB *pL2CA_ConfigInd_Cb; - tL2CA_CONFIG_CFM_CB *pL2CA_ConfigCfm_Cb; - tL2CA_DISCONNECT_IND_CB *pL2CA_DisconnectInd_Cb; - tL2CA_DISCONNECT_CFM_CB *pL2CA_DisconnectCfm_Cb; - tL2CA_QOS_VIOLATION_IND_CB *pL2CA_QoSViolationInd_Cb; - tL2CA_DATA_IND_CB *pL2CA_DataInd_Cb; - tL2CA_CONGESTION_STATUS_CB *pL2CA_CongestionStatus_Cb; - tL2CA_TX_COMPLETE_CB *pL2CA_TxComplete_Cb; - -} tL2CAP_APPL_INFO; - -/* Define the structure that applications use to create or accept -** connections with enhanced retransmission mode. -*/ -typedef struct { - UINT8 preferred_mode; - UINT8 allowed_modes; - UINT16 user_rx_buf_size; - UINT16 user_tx_buf_size; - UINT16 fcr_rx_buf_size; - UINT16 fcr_tx_buf_size; - -} tL2CAP_ERTM_INFO; - -#define L2CA_REGISTER(a,b,c) L2CA_Register(a,(tL2CAP_APPL_INFO *)b) -#define L2CA_DEREGISTER(a) L2CA_Deregister(a) -#define L2CA_CONNECT_REQ(a,b,c,d) L2CA_ErtmConnectReq(a,b,c) -#define L2CA_CONNECT_RSP(a,b,c,d,e,f,g) L2CA_ErtmConnectRsp(a,b,c,d,e,f) -#define L2CA_CONFIG_REQ(a,b) L2CA_ConfigReq(a,b) -#define L2CA_CONFIG_RSP(a,b) L2CA_ConfigRsp(a,b) -#define L2CA_DISCONNECT_REQ(a) L2CA_DisconnectReq(a) -#define L2CA_DISCONNECT_RSP(a) L2CA_DisconnectRsp(a) -#define L2CA_DATA_WRITE(a, b) L2CA_DataWrite(a, b) - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -#if (CLASSIC_BT_INCLUDED == TRUE) -/******************************************************************************* -** -** Function L2CA_Register -** -** Description Other layers call this function to register for L2CAP -** services. -** -** Returns PSM to use or zero if error. Typically, the PSM returned -** is the same as was passed in, but for an outgoing-only -** connection to a dynamic PSM, a "virtual" PSM is returned -** and should be used in the calls to L2CA_ConnectReq() and -** BTM_SetSecurityLevel(). -** -*******************************************************************************/ -extern UINT16 L2CA_Register (UINT16 psm, tL2CAP_APPL_INFO *p_cb_info); - -/******************************************************************************* -** -** Function L2CA_Deregister -** -** Description Other layers call this function to deregister for L2CAP -** services. -** -** Returns void -** -*******************************************************************************/ -extern void L2CA_Deregister (UINT16 psm); - -/******************************************************************************* -** -** Function L2CA_AllocatePSM -** -** Description Other layers call this function to find an unused PSM for L2CAP -** services. -** -** Returns PSM to use. -** -*******************************************************************************/ -extern UINT16 L2CA_AllocatePSM(void); - -/******************************************************************************* -** -** Function L2CA_ConnectReq -** -** Description Higher layers call this function to create an L2CAP connection. -** Note that the connection is not established at this time, but -** connection establishment gets started. The callback function -** will be invoked when connection establishes or fails. -** -** Returns the CID of the connection, or 0 if it failed to start -** -*******************************************************************************/ -extern UINT16 L2CA_ConnectReq (UINT16 psm, BD_ADDR p_bd_addr); - -/******************************************************************************* -** -** Function L2CA_ConnectRsp -** -** Description Higher layers call this function to accept an incoming -** L2CAP connection, for which they had gotten an connect -** indication callback. -** -** Returns TRUE for success, FALSE for failure -** -*******************************************************************************/ -extern BOOLEAN L2CA_ConnectRsp (BD_ADDR p_bd_addr, UINT8 id, UINT16 lcid, - UINT16 result, UINT16 status); - -/******************************************************************************* -** -** Function L2CA_ErtmConnectReq -** -** Description Higher layers call this function to create an L2CAP connection -** that needs to use Enhanced Retransmission Mode. -** Note that the connection is not established at this time, but -** connection establishment gets started. The callback function -** will be invoked when connection establishes or fails. -** -** Returns the CID of the connection, or 0 if it failed to start -** -*******************************************************************************/ -extern UINT16 L2CA_ErtmConnectReq (UINT16 psm, BD_ADDR p_bd_addr, - tL2CAP_ERTM_INFO *p_ertm_info); - -// This function sets the callback routines for the L2CAP connection referred to by -// |local_cid|. The callback routines can only be modified for outgoing connections -// established by |L2CA_ConnectReq| or accepted incoming connections. |callbacks| -// must not be NULL. This function returns true if the callbacks could be updated, -// false if not (e.g. |local_cid| was not found). -bool L2CA_SetConnectionCallbacks(uint16_t local_cid, const tL2CAP_APPL_INFO *callbacks); - -/******************************************************************************* -** -** Function L2CA_ErtmConnectRsp -** -** Description Higher layers call this function to accept an incoming -** L2CAP connection, for which they had gotten an connect -** indication callback, and for which the higher layer wants -** to use Enhanced Retransmission Mode. -** -** Returns TRUE for success, FALSE for failure -** -*******************************************************************************/ -extern BOOLEAN L2CA_ErtmConnectRsp (BD_ADDR p_bd_addr, UINT8 id, UINT16 lcid, - UINT16 result, UINT16 status, - tL2CAP_ERTM_INFO *p_ertm_info); - -/******************************************************************************* -** -** Function L2CA_ConfigReq -** -** Description Higher layers call this function to send configuration. -** -** Returns TRUE if configuration sent, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_ConfigReq (UINT16 cid, tL2CAP_CFG_INFO *p_cfg); - -/******************************************************************************* -** -** Function L2CA_ConfigRsp -** -** Description Higher layers call this function to send a configuration -** response. -** -** Returns TRUE if configuration response sent, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_ConfigRsp (UINT16 cid, tL2CAP_CFG_INFO *p_cfg); - -/******************************************************************************* -** -** Function L2CA_DisconnectReq -** -** Description Higher layers call this function to disconnect a channel. -** -** Returns TRUE if disconnect sent, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_DisconnectReq (UINT16 cid); - -/******************************************************************************* -** -** Function L2CA_DisconnectRsp -** -** Description Higher layers call this function to acknowledge the -** disconnection of a channel. -** -** Returns void -** -*******************************************************************************/ -extern BOOLEAN L2CA_DisconnectRsp (UINT16 cid); -#endif ///CLASSIC_BT_INCLUDED == TRUE - -/******************************************************************************* -** -** Function L2CA_RegisterLECoc -** -** Description Other layers call this function to register for L2CAP -** Connection Oriented Channel. -** -** Returns PSM to use or zero if error. Typically, the PSM returned -** is the same as was passed in, but for an outgoing-only -** connection to a dynamic PSM, a "virtual" PSM is returned -** and should be used in the calls to L2CA_ConnectLECocReq() -** and BTM_SetSecurityLevel(). -** -*******************************************************************************/ -extern UINT16 L2CA_RegisterLECoc (UINT16 psm, tL2CAP_APPL_INFO *p_cb_info); - -/******************************************************************************* -** -** Function L2CA_DeregisterLECoc -** -** Description Other layers call this function to deregister for L2CAP -** Connection Oriented Channel. -** -** Returns void -** -*******************************************************************************/ -extern void L2CA_DeregisterLECoc (UINT16 psm); - -/******************************************************************************* -** -** Function L2CA_ConnectLECocReq -** -** Description Higher layers call this function to create an L2CAP LE COC. -** Note that the connection is not established at this time, but -** connection establishment gets started. The callback function -** will be invoked when connection establishes or fails. -** -** Returns the CID of the connection, or 0 if it failed to start -** -*******************************************************************************/ -extern UINT16 L2CA_ConnectLECocReq (UINT16 psm, BD_ADDR p_bd_addr, tL2CAP_LE_CFG_INFO *p_cfg); - -/******************************************************************************* -** -** Function L2CA_ConnectLECocRsp -** -** Description Higher layers call this function to accept an incoming -** L2CAP LE COC connection, for which they had gotten an connect -** indication callback. -** -** Returns TRUE for success, FALSE for failure -** -*******************************************************************************/ -extern BOOLEAN L2CA_ConnectLECocRsp (BD_ADDR p_bd_addr, UINT8 id, UINT16 lcid, UINT16 result, - UINT16 status, tL2CAP_LE_CFG_INFO *p_cfg); - -/******************************************************************************* -** -** Function L2CA_GetPeerLECocConfig -** -** Description Get peers configuration for LE Connection Oriented Channel. -** -** Return value: TRUE if peer is connected -** -*******************************************************************************/ -extern BOOLEAN L2CA_GetPeerLECocConfig (UINT16 lcid, tL2CAP_LE_CFG_INFO* peer_cfg); - -/******************************************************************************* -** -** Function L2CA_DataWrite -** -** Description Higher layers call this function to write data. -** -** Returns L2CAP_DW_SUCCESS, if data accepted, else FALSE -** L2CAP_DW_CONGESTED, if data accepted and the channel is congested -** L2CAP_DW_FAILED, if error -** -*******************************************************************************/ -extern UINT8 L2CA_DataWrite (UINT16 cid, BT_HDR *p_data); - -#if (CLASSIC_BT_INCLUDED == TRUE) - -/******************************************************************************* -** -** Function L2CA_Ping -** -** Description Higher layers call this function to send an echo request. -** -** Returns TRUE if echo request sent, else FALSE. -** -*******************************************************************************/ -extern BOOLEAN L2CA_Ping (BD_ADDR p_bd_addr, tL2CA_ECHO_RSP_CB *p_cb); - -/******************************************************************************* -** -** Function L2CA_Echo -** -** Description Higher layers call this function to send an echo request -** with application-specific data. -** -** Returns TRUE if echo request sent, else FALSE. -** -*******************************************************************************/ -extern BOOLEAN L2CA_Echo (BD_ADDR p_bd_addr, BT_HDR *p_data, tL2CA_ECHO_DATA_CB *p_callback); -#endif ///CLASSIC_BT_INCLUDED == TRUE - - -// Given a local channel identifier, |lcid|, this function returns the bound remote -// channel identifier, |rcid|, and the ACL link handle, |handle|. If |lcid| is not -// known or is invalid, this function returns false and does not modify the values -// pointed at by |rcid| and |handle|. |rcid| and |handle| may be NULL. -bool L2CA_GetIdentifiers(uint16_t lcid, uint16_t *rcid, uint16_t *handle); - -/******************************************************************************* -** -** Function L2CA_SetIdleTimeout -** -** Description Higher layers call this function to set the idle timeout for -** a connection, or for all future connections. The "idle timeout" -** is the amount of time that a connection can remain up with -** no L2CAP channels on it. A timeout of zero means that the -** connection will be torn down immediately when the last channel -** is removed. A timeout of 0xFFFF means no timeout. Values are -** in seconds. -** -** Returns TRUE if command succeeded, FALSE if failed -** -*******************************************************************************/ -extern BOOLEAN L2CA_SetIdleTimeout (UINT16 cid, UINT16 timeout, - BOOLEAN is_global); - - -/******************************************************************************* -** -** Function L2CA_SetIdleTimeoutByBdAddr -** -** Description Higher layers call this function to set the idle timeout for -** a connection. The "idle timeout" is the amount of time that -** a connection can remain up with no L2CAP channels on it. -** A timeout of zero means that the connection will be torn -** down immediately when the last channel is removed. -** A timeout of 0xFFFF means no timeout. Values are in seconds. -** A bd_addr is the remote BD address. If bd_addr = BT_BD_ANY, -** then the idle timeouts for all active l2cap links will be -** changed. -** -** Returns TRUE if command succeeded, FALSE if failed -** -** NOTE This timeout applies to all logical channels active on the -** ACL link. -*******************************************************************************/ -extern BOOLEAN L2CA_SetIdleTimeoutByBdAddr(BD_ADDR bd_addr, UINT16 timeout, - tBT_TRANSPORT transport); - - -/******************************************************************************* -** -** Function L2CA_SetTraceLevel -** -** Description This function sets the trace level for L2CAP. If called with -** a value of 0xFF, it simply reads the current trace level. -** -** Returns the new (current) trace level -** -*******************************************************************************/ -extern UINT8 L2CA_SetTraceLevel (UINT8 trace_level); - - -/******************************************************************************* -** -** Function L2CA_SetDesireRole -** -** Description This function sets the desire role for L2CAP. -** If the new role is L2CAP_ROLE_ALLOW_SWITCH, allow switch on -** HciCreateConnection. -** If the new role is L2CAP_ROLE_DISALLOW_SWITCH, do not allow switch on -** HciCreateConnection. -** -** If the new role is a valid role (HCI_ROLE_MASTER or HCI_ROLE_SLAVE), -** the desire role is set to the new value. Otherwise, it is not changed. -** -** Returns the new (current) role -** -*******************************************************************************/ -extern UINT8 L2CA_SetDesireRole (UINT8 new_role); -#if (CLASSIC_BT_INCLUDED == TRUE) -/******************************************************************************* -** -** Function L2CA_LocalLoopbackReq -** -** Description This function sets up a CID for local loopback -** -** Returns CID of 0 if none. -** -*******************************************************************************/ -extern UINT16 L2CA_LocalLoopbackReq (UINT16 psm, UINT16 handle, BD_ADDR p_bd_addr); - -/******************************************************************************* -** -** Function L2CA_FlushChannel -** -** Description This function flushes none, some or all buffers queued up -** for xmission for a particular CID. If called with -** L2CAP_FLUSH_CHANS_GET (0), it simply returns the number -** of buffers queued for that CID L2CAP_FLUSH_CHANS_ALL (0xffff) -** flushes all buffers. All other values specifies the maximum -** buffers to flush. -** -** Returns Number of buffers left queued for that CID -** -*******************************************************************************/ -extern UINT16 L2CA_FlushChannel (UINT16 lcid, UINT16 num_to_flush); - - -/******************************************************************************* -** -** Function L2CA_SetAclPriority -** -** Description Sets the transmission priority for an ACL channel. -** (For initial implementation only two values are valid. -** L2CAP_PRIORITY_NORMAL and L2CAP_PRIORITY_HIGH). -** -** Returns TRUE if a valid channel, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_SetAclPriority (BD_ADDR bd_addr, UINT8 priority); - -/******************************************************************************* -** -** Function L2CA_FlowControl -** -** Description Higher layers call this function to flow control a channel. -** -** data_enabled - TRUE data flows, FALSE data is stopped -** -** Returns TRUE if valid channel, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_FlowControl (UINT16 cid, BOOLEAN data_enabled); - -/******************************************************************************* -** -** Function L2CA_SendTestSFrame -** -** Description Higher layers call this function to send a test S-frame. -** -** Returns TRUE if valid Channel, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_SendTestSFrame (UINT16 cid, UINT8 sup_type, - UINT8 back_track); - -/******************************************************************************* -** -** Function L2CA_SetTxPriority -** -** Description Sets the transmission priority for a channel. (FCR Mode) -** -** Returns TRUE if a valid channel, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_SetTxPriority (UINT16 cid, tL2CAP_CHNL_PRIORITY priority); - -/******************************************************************************* -** -** Function L2CA_RegForNoCPEvt -** -** Description Register callback for Number of Completed Packets event. -** -** Input Param p_cb - callback for Number of completed packets event -** p_bda - BT address of remote device -** -** Returns -** -*******************************************************************************/ -extern BOOLEAN L2CA_RegForNoCPEvt(tL2CA_NOCP_CB *p_cb, BD_ADDR p_bda); - -/******************************************************************************* -** -** Function L2CA_SetChnlDataRate -** -** Description Sets the tx/rx data rate for a channel. -** -** Returns TRUE if a valid channel, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_SetChnlDataRate (UINT16 cid, tL2CAP_CHNL_DATA_RATE tx, tL2CAP_CHNL_DATA_RATE rx); - -typedef void (tL2CA_RESERVE_CMPL_CBACK) (void); - -/******************************************************************************* -** -** Function L2CA_SetFlushTimeout -** -** Description This function set the automatic flush time out in Baseband -** for ACL-U packets. -** BdAddr : the remote BD address of ACL link. If it is BT_DB_ANY -** then the flush time out will be applied to all ACL link. -** FlushTimeout: flush time out in ms -** 0x0000 : No automatic flush -** L2CAP_NO_RETRANSMISSION : No retransmission -** 0x0002 - 0xFFFE : flush time out, if (flush_tout*8)+3/5) -** <= HCI_MAX_AUTO_FLUSH_TOUT (in 625us slot). -** Otherwise, return FALSE. -** L2CAP_NO_AUTOMATIC_FLUSH : No automatic flush -** -** Returns TRUE if command succeeded, FALSE if failed -** -** NOTE This flush timeout applies to all logical channels active on the -** ACL link. -*******************************************************************************/ -extern BOOLEAN L2CA_SetFlushTimeout (BD_ADDR bd_addr, UINT16 flush_tout); -#endif ///CLASSIC_BT_INCLUDED == TRUE - -/******************************************************************************* -** -** Function L2CA_DataWriteEx -** -** Description Higher layers call this function to write data with extended -** flags. -** flags : L2CAP_FLUSHABLE_CH_BASED -** L2CAP_FLUSHABLE_PKT -** L2CAP_NON_FLUSHABLE_PKT -** -** Returns L2CAP_DW_SUCCESS, if data accepted, else FALSE -** L2CAP_DW_CONGESTED, if data accepted and the channel is congested -** L2CAP_DW_FAILED, if error -** -*******************************************************************************/ -extern UINT8 L2CA_DataWriteEx (UINT16 cid, BT_HDR *p_data, UINT16 flags); - -/******************************************************************************* -** -** Function L2CA_SetChnlFlushability -** -** Description Higher layers call this function to set a channels -** flushability flags -** -** Returns TRUE if CID found, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_SetChnlFlushability (UINT16 cid, BOOLEAN is_flushable); - -/******************************************************************************* -** -** Function L2CA_GetPeerFeatures -** -** Description Get a peers features and fixed channel map -** -** Parameters: BD address of the peer -** Pointers to features and channel mask storage area -** -** Return value: TRUE if peer is connected -** -*******************************************************************************/ -extern BOOLEAN L2CA_GetPeerFeatures (BD_ADDR bd_addr, UINT32 *p_ext_feat, UINT8 *p_chnl_mask); - -/******************************************************************************* -** -** Function L2CA_GetBDAddrbyHandle -** -** Description Get BD address for the given HCI handle -** -** Parameters: HCI handle -** BD address of the peer -** -** Return value: TRUE if found lcb for the given handle, FALSE otherwise -** -*******************************************************************************/ -extern BOOLEAN L2CA_GetBDAddrbyHandle (UINT16 handle, BD_ADDR bd_addr); - -#if (CLASSIC_BT_INCLUDED == TRUE) - -/******************************************************************************* -** -** Function L2CA_GetChnlFcrMode -** -** Description Get the channel FCR mode -** -** Parameters: Local CID -** -** Return value: Channel mode -** -*******************************************************************************/ -extern UINT8 L2CA_GetChnlFcrMode (UINT16 lcid); -#endif ///CLASSIC_BT_INCLUDED == TRUE - - -/******************************************************************************* -** -** UCD callback prototypes -** -*******************************************************************************/ - -/* UCD discovery. Parameters are -** BD Address of remote -** Data Type -** Data -*/ -#define L2CAP_UCD_INFO_TYPE_RECEPTION 0x01 -#define L2CAP_UCD_INFO_TYPE_MTU 0x02 - -typedef void (tL2CA_UCD_DISCOVER_CB) (BD_ADDR, UINT8, UINT32); - -/* UCD data received. Parameters are -** BD Address of remote -** Pointer to buffer with data -*/ -typedef void (tL2CA_UCD_DATA_CB) (BD_ADDR, BT_HDR *); - -/* Congestion status callback protype. This callback is optional. If -** an application tries to send data when the transmit queue is full, -** the data will anyways be dropped. The parameter is: -** remote BD_ADDR -** TRUE if congested, FALSE if uncongested -*/ -typedef void (tL2CA_UCD_CONGESTION_STATUS_CB) (BD_ADDR, BOOLEAN); - -/* UCD registration info (the callback addresses and PSM) -*/ -typedef struct { - tL2CA_UCD_DISCOVER_CB *pL2CA_UCD_Discover_Cb; - tL2CA_UCD_DATA_CB *pL2CA_UCD_Data_Cb; - tL2CA_UCD_CONGESTION_STATUS_CB *pL2CA_UCD_Congestion_Status_Cb; -} tL2CAP_UCD_CB_INFO; - -/******************************************************************************* -** -** Function L2CA_UcdRegister -** -** Description Register PSM on UCD. -** -** Parameters: tL2CAP_UCD_CB_INFO -** -** Return value: TRUE if successs -** -*******************************************************************************/ -extern BOOLEAN L2CA_UcdRegister ( UINT16 psm, tL2CAP_UCD_CB_INFO *p_cb_info ); - -/******************************************************************************* -** -** Function L2CA_UcdDeregister -** -** Description Deregister PSM on UCD. -** -** Parameters: PSM -** -** Return value: TRUE if successs -** -*******************************************************************************/ -extern BOOLEAN L2CA_UcdDeregister ( UINT16 psm ); - -/******************************************************************************* -** -** Function L2CA_UcdDiscover -** -** Description Discover UCD of remote device. -** -** Parameters: PSM -** BD_ADDR of remote device -** info_type : L2CAP_UCD_INFO_TYPE_RECEPTION -** L2CAP_UCD_INFO_TYPE_MTU -** -** -** Return value: TRUE if successs -** -*******************************************************************************/ -extern BOOLEAN L2CA_UcdDiscover ( UINT16 psm, BD_ADDR rem_bda, UINT8 info_type ); - -/******************************************************************************* -** -** Function L2CA_UcdDataWrite -** -** Description Send UCD to remote device -** -** Parameters: PSM -** BD Address of remote -** Pointer to buffer of type BT_HDR -** flags : L2CAP_FLUSHABLE_CH_BASED -** L2CAP_FLUSHABLE_PKT -** L2CAP_NON_FLUSHABLE_PKT -** -** Return value L2CAP_DW_SUCCESS, if data accepted -** L2CAP_DW_FAILED, if error -** -*******************************************************************************/ -extern UINT16 L2CA_UcdDataWrite (UINT16 psm, BD_ADDR rem_bda, BT_HDR *p_buf, UINT16 flags); - -/******************************************************************************* -** -** Function L2CA_UcdSetIdleTimeout -** -** Description Set UCD Idle timeout. -** -** Parameters: BD Addr -** Timeout in second -** -** Return value: TRUE if successs -** -*******************************************************************************/ -extern BOOLEAN L2CA_UcdSetIdleTimeout ( BD_ADDR rem_bda, UINT16 timeout ); - -/******************************************************************************* -** -** Function L2CA_UCDSetTxPriority -** -** Description Sets the transmission priority for a connectionless channel. -** -** Returns TRUE if a valid channel, else FALSE -** -*******************************************************************************/ -extern BOOLEAN L2CA_UCDSetTxPriority ( BD_ADDR rem_bda, tL2CAP_CHNL_PRIORITY priority ); - - -/******************************************************************************* -** -** Fixed Channel callback prototypes -** -*******************************************************************************/ - -/* Fixed channel connected and disconnected. Parameters are -** channel -** BD Address of remote -** TRUE if channel is connected, FALSE if disconnected -** Reason for connection failure -** transport : physical transport, BR/EDR or LE -*/ -typedef void (tL2CA_FIXED_CHNL_CB) (UINT16, BD_ADDR, BOOLEAN, UINT16, tBT_TRANSPORT); - -/* Signalling data received. Parameters are -** channel -** BD Address of remote -** Pointer to buffer with data -*/ -typedef void (tL2CA_FIXED_DATA_CB) (UINT16, BD_ADDR, BT_HDR *); - -/* Congestion status callback protype. This callback is optional. If -** an application tries to send data when the transmit queue is full, -** the data will anyways be dropped. The parameter is: -** remote BD_ADDR -** TRUE if congested, FALSE if uncongested -*/ -typedef void (tL2CA_FIXED_CONGESTION_STATUS_CB) (BD_ADDR, BOOLEAN); - -/* Fixed channel registration info (the callback addresses and channel config) -*/ -typedef struct { - tL2CA_FIXED_CHNL_CB *pL2CA_FixedConn_Cb; - tL2CA_FIXED_DATA_CB *pL2CA_FixedData_Cb; - tL2CA_FIXED_CONGESTION_STATUS_CB *pL2CA_FixedCong_Cb; - tL2CAP_FCR_OPTS fixed_chnl_opts; - - UINT16 default_idle_tout; - tL2CA_TX_COMPLETE_CB *pL2CA_FixedTxComplete_Cb; /* fixed channel tx complete callback */ -} tL2CAP_FIXED_CHNL_REG; - - -#if (L2CAP_NUM_FIXED_CHNLS > 0) -/******************************************************************************* -** -** Function L2CA_RegisterFixedChannel -** -** Description Register a fixed channel. -** -** Parameters: Fixed Channel # -** Channel Callbacks and config -** -** Return value: TRUE if registered OK -** -*******************************************************************************/ -extern BOOLEAN L2CA_RegisterFixedChannel (UINT16 fixed_cid, tL2CAP_FIXED_CHNL_REG *p_freg); - -/******************************************************************************* -** -** Function L2CA_ConnectFixedChnl -** -** Description Connect an fixed signalling channel to a remote device. -** -** Parameters: Fixed CID -** BD Address of remote -** BD Address type -** -** Return value: TRUE if connection started -** -*******************************************************************************/ -extern BOOLEAN L2CA_ConnectFixedChnl (UINT16 fixed_cid, BD_ADDR bd_addr, tBLE_ADDR_TYPE bd_addr_type); - -/******************************************************************************* -** -** Function L2CA_SendFixedChnlData -** -** Description Write data on a fixed signalling channel. -** -** Parameters: Fixed CID -** BD Address of remote -** Pointer to buffer of type BT_HDR -** -** Return value L2CAP_DW_SUCCESS, if data accepted -** L2CAP_DW_FAILED, if error -** -*******************************************************************************/ -extern UINT16 L2CA_SendFixedChnlData (UINT16 fixed_cid, BD_ADDR rem_bda, BT_HDR *p_buf); - -/******************************************************************************* -** -** Function L2CA_RemoveFixedChnl -** -** Description Remove a fixed channel to a remote device. -** -** Parameters: Fixed CID -** BD Address of remote -** Idle timeout to use (or 0xFFFF if don't care) -** -** Return value: TRUE if channel removed -** -*******************************************************************************/ -extern BOOLEAN L2CA_RemoveFixedChnl (UINT16 fixed_cid, BD_ADDR rem_bda); - -/******************************************************************************* -** -** Function L2CA_SetFixedChannelTout -** -** Description Higher layers call this function to set the idle timeout for -** a fixed channel. The "idle timeout" is the amount of time that -** a connection can remain up with no L2CAP channels on it. -** A timeout of zero means that the connection will be torn -** down immediately when the last channel is removed. -** A timeout of 0xFFFF means no timeout. Values are in seconds. -** A bd_addr is the remote BD address. If bd_addr = BT_BD_ANY, -** then the idle timeouts for all active l2cap links will be -** changed. -** -** Returns TRUE if command succeeded, FALSE if failed -** -*******************************************************************************/ -extern BOOLEAN L2CA_SetFixedChannelTout (BD_ADDR rem_bda, UINT16 fixed_cid, UINT16 idle_tout); - -#endif /* (L2CAP_NUM_FIXED_CHNLS > 0) */ - -#if (CLASSIC_BT_INCLUDED == TRUE) -/******************************************************************************* -** -** Function L2CA_GetCurrentConfig -** -** Description This function returns configurations of L2CAP channel -** pp_our_cfg : pointer of our saved configuration options -** p_our_cfg_bits : valid config in bitmap -** pp_peer_cfg: pointer of peer's saved configuration options -** p_peer_cfg_bits : valid config in bitmap -** -** Returns TRUE if successful -** -*******************************************************************************/ -extern BOOLEAN L2CA_GetCurrentConfig (UINT16 lcid, - tL2CAP_CFG_INFO **pp_our_cfg, tL2CAP_CH_CFG_BITS *p_our_cfg_bits, - tL2CAP_CFG_INFO **pp_peer_cfg, tL2CAP_CH_CFG_BITS *p_peer_cfg_bits); -#endif ///CLASSIC_BT_INCLUDED == TRUE - - -#if (BLE_INCLUDED == TRUE) -/******************************************************************************* -** -** Function L2CA_CancelBleConnectReq -** -** Description Cancel a pending connection attempt to a BLE device. -** -** Parameters: BD Address of remote -** -** Return value: TRUE if connection was cancelled -** -*******************************************************************************/ -extern BOOLEAN L2CA_CancelBleConnectReq (BD_ADDR rem_bda); - -/******************************************************************************* -** -** Function L2CA_UpdateBleConnParams -** -** Description Update BLE connection parameters. -** -** Parameters: BD Address of remote -** -** Return value: TRUE if update started -** -*******************************************************************************/ -extern BOOLEAN L2CA_UpdateBleConnParams (BD_ADDR rem_bdRa, UINT16 min_int, - UINT16 max_int, UINT16 latency, UINT16 timeout); - -/******************************************************************************* -** -** Function L2CA_EnableUpdateBleConnParams -** -** Description Update BLE connection parameters. -** -** Parameters: BD Address of remote -** enable flag -** -** Return value: TRUE if update started -** -*******************************************************************************/ -extern BOOLEAN L2CA_EnableUpdateBleConnParams (BD_ADDR rem_bda, BOOLEAN enable); - -/******************************************************************************* -** -** Function L2CA_GetBleConnRole -** -** Description This function returns the connection role. -** -** Returns link role. -** -*******************************************************************************/ -extern UINT8 L2CA_GetBleConnRole (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function L2CA_GetDisconnectReason -** -** Description This function returns the disconnect reason code. -** -** Parameters: BD Address of remote -** Physical transport for the L2CAP connection (BR/EDR or LE) -** -** Returns disconnect reason -** -*******************************************************************************/ -extern UINT16 L2CA_GetDisconnectReason (BD_ADDR remote_bda, tBT_TRANSPORT transport); - -#endif /* (BLE_INCLUDED == TRUE) */ - -#ifdef __cplusplus -} -#endif - -#endif /* L2C_API_H */ diff --git a/tools/sdk/include/bluedroid/l2c_int.h b/tools/sdk/include/bluedroid/l2c_int.h deleted file mode 100644 index 2728261f30c..00000000000 --- a/tools/sdk/include/bluedroid/l2c_int.h +++ /dev/null @@ -1,814 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains L2CAP internal definitions - * - ******************************************************************************/ -#ifndef L2C_INT_H -#define L2C_INT_H - -#include - -#include "btm_api.h" -#include "l2c_api.h" -#include "l2cdefs.h" -#include "list.h" -#include "fixed_queue.h" - -#define L2CAP_MIN_MTU 48 /* Minimum acceptable MTU is 48 bytes */ - -/* LE credit based L2CAP connection parameters */ -#define L2CAP_LE_MIN_MTU 23 -#define L2CAP_LE_MIN_MPS 23 -#define L2CAP_LE_MAX_MPS 65533 -#define L2CAP_LE_MIN_CREDIT 0 -#define L2CAP_LE_MAX_CREDIT 65535 -#define L2CAP_LE_DEFAULT_MTU 512 -#define L2CAP_LE_DEFAULT_MPS 23 -#define L2CAP_LE_DEFAULT_CREDIT 1 - - -/* Timeouts. Since L2CAP works off a 1-second list, all are in seconds. -*/ -#define L2CAP_LINK_ROLE_SWITCH_TOUT 10 /* 10 seconds */ -#define L2CAP_LINK_CONNECT_TOUT 60 /* 30 seconds */ -#define L2CAP_LINK_CONNECT_TOUT_EXT 120 /* 120 seconds */ -#define L2CAP_ECHO_RSP_TOUT 30 /* 30 seconds */ -#define L2CAP_LINK_FLOW_CONTROL_TOUT 2 /* 2 seconds */ -#define L2CAP_LINK_DISCONNECT_TOUT 30 /* 30 seconds */ - -#ifndef L2CAP_CHNL_CONNECT_TOUT /* BTIF needs to override for internal project needs */ -#define L2CAP_CHNL_CONNECT_TOUT 60 /* 60 seconds */ -#endif - -#define L2CAP_CHNL_CONNECT_TOUT_EXT 120 /* 120 seconds */ -#define L2CAP_CHNL_CFG_TIMEOUT 30 /* 30 seconds */ -#define L2CAP_CHNL_DISCONNECT_TOUT 10 /* 10 seconds */ -#define L2CAP_DELAY_CHECK_SM4 2 /* 2 seconds */ -#define L2CAP_WAIT_INFO_RSP_TOUT 3 /* 3 seconds */ -#define L2CAP_WAIT_UNPARK_TOUT 2 /* 2 seconds */ -#define L2CAP_LINK_INFO_RESP_TOUT 2 /* 2 seconds */ -#define L2CAP_UPDATE_CONN_PARAM_TOUT 6 /* 6 seconds */ -#define L2CAP_BLE_LINK_CONNECT_TOUT 30 /* 30 seconds */ -#define L2CAP_BLE_CONN_PARAM_UPD_TOUT 30 /* 30 seconds */ - -/* quick timer uses millisecond unit */ -#define L2CAP_DEFAULT_RETRANS_TOUT 2000 /* 2000 milliseconds */ -#define L2CAP_DEFAULT_MONITOR_TOUT 12000 /* 12000 milliseconds */ -#define L2CAP_FCR_ACK_TOUT 200 /* 200 milliseconds */ - -/* Define the possible L2CAP channel states. The names of -** the states may seem a bit strange, but they are taken from -** the Bluetooth specification. -*/ -typedef enum { - CST_CLOSED, /* Channel is in clodes state */ - CST_ORIG_W4_SEC_COMP, /* Originator waits security clearence */ - CST_TERM_W4_SEC_COMP, /* Acceptor waits security clearence */ - CST_W4_L2CAP_CONNECT_RSP, /* Waiting for peer conenct response */ - CST_W4_L2CA_CONNECT_RSP, /* Waiting for upper layer connect rsp */ - CST_CONFIG, /* Negotiating configuration */ - CST_OPEN, /* Data transfer state */ - CST_W4_L2CAP_DISCONNECT_RSP, /* Waiting for peer disconnect rsp */ - CST_W4_L2CA_DISCONNECT_RSP /* Waiting for upper layer disc rsp */ -} tL2C_CHNL_STATE; - -/* Define the possible L2CAP link states -*/ -typedef enum { - LST_DISCONNECTED, - LST_CONNECT_HOLDING, - LST_CONNECTING_WAIT_SWITCH, - LST_CONNECTING, - LST_CONNECTED, - LST_DISCONNECTING -} tL2C_LINK_STATE; - - - -/* Define input events to the L2CAP link and channel state machines. The names -** of the events may seem a bit strange, but they are taken from -** the Bluetooth specification. -*/ -#define L2CEVT_LP_CONNECT_CFM 0 /* Lower layer connect confirm */ -#define L2CEVT_LP_CONNECT_CFM_NEG 1 /* Lower layer connect confirm (failed) */ -#define L2CEVT_LP_CONNECT_IND 2 /* Lower layer connect indication */ -#define L2CEVT_LP_DISCONNECT_IND 3 /* Lower layer disconnect indication */ -#define L2CEVT_LP_QOS_CFM 4 /* Lower layer QOS confirmation */ -#define L2CEVT_LP_QOS_CFM_NEG 5 /* Lower layer QOS confirmation (failed)*/ -#define L2CEVT_LP_QOS_VIOLATION_IND 6 /* Lower layer QOS violation indication */ - -#define L2CEVT_SEC_COMP 7 /* Security cleared successfully */ -#define L2CEVT_SEC_COMP_NEG 8 /* Security procedure failed */ - -#define L2CEVT_L2CAP_CONNECT_REQ 10 /* Peer connection request */ -#define L2CEVT_L2CAP_CONNECT_RSP 11 /* Peer connection response */ -#define L2CEVT_L2CAP_CONNECT_RSP_PND 12 /* Peer connection response pending */ -#define L2CEVT_L2CAP_CONNECT_RSP_NEG 13 /* Peer connection response (failed) */ -#define L2CEVT_L2CAP_CONFIG_REQ 14 /* Peer configuration request */ -#define L2CEVT_L2CAP_CONFIG_RSP 15 /* Peer configuration response */ -#define L2CEVT_L2CAP_CONFIG_RSP_NEG 16 /* Peer configuration response (failed) */ -#define L2CEVT_L2CAP_DISCONNECT_REQ 17 /* Peer disconnect request */ -#define L2CEVT_L2CAP_DISCONNECT_RSP 18 /* Peer disconnect response */ -#define L2CEVT_L2CAP_INFO_RSP 19 /* Peer information response */ -#define L2CEVT_L2CAP_DATA 20 /* Peer data */ - -#define L2CEVT_L2CA_CONNECT_REQ 21 /* Upper layer connect request */ -#define L2CEVT_L2CA_CONNECT_RSP 22 /* Upper layer connect response */ -#define L2CEVT_L2CA_CONNECT_RSP_NEG 23 /* Upper layer connect response (failed)*/ -#define L2CEVT_L2CA_CONFIG_REQ 24 /* Upper layer config request */ -#define L2CEVT_L2CA_CONFIG_RSP 25 /* Upper layer config response */ -#define L2CEVT_L2CA_CONFIG_RSP_NEG 26 /* Upper layer config response (failed) */ -#define L2CEVT_L2CA_DISCONNECT_REQ 27 /* Upper layer disconnect request */ -#define L2CEVT_L2CA_DISCONNECT_RSP 28 /* Upper layer disconnect response */ -#define L2CEVT_L2CA_DATA_READ 29 /* Upper layer data read */ -#define L2CEVT_L2CA_DATA_WRITE 30 /* Upper layer data write */ -#define L2CEVT_L2CA_FLUSH_REQ 31 /* Upper layer flush */ - -#define L2CEVT_TIMEOUT 32 /* Timeout */ -#define L2CEVT_SEC_RE_SEND_CMD 33 /* btm_sec has enough info to proceed */ - -#define L2CEVT_ACK_TIMEOUT 34 /* RR delay timeout */ - - -/* Bitmask to skip over Broadcom feature reserved (ID) to avoid sending two - successive ID values, '0' id only or both */ -#define L2CAP_ADJ_BRCM_ID 0x1 -#define L2CAP_ADJ_ZERO_ID 0x2 -#define L2CAP_ADJ_ID 0x3 - -/* Return values for l2cu_process_peer_cfg_req() */ -#define L2CAP_PEER_CFG_UNACCEPTABLE 0 -#define L2CAP_PEER_CFG_OK 1 -#define L2CAP_PEER_CFG_DISCONNECT 2 - -/* eL2CAP option constants */ -#define L2CAP_MIN_RETRANS_TOUT 2000 /* Min retransmission timeout if no flush timeout or PBF */ -#define L2CAP_MIN_MONITOR_TOUT 12000 /* Min monitor timeout if no flush timeout or PBF */ - -#define L2CAP_MAX_FCR_CFG_TRIES 2 /* Config attempts before disconnecting */ - -typedef uint8_t tL2C_BLE_FIXED_CHNLS_MASK; - -typedef struct { - UINT8 next_tx_seq; /* Next sequence number to be Tx'ed */ - UINT8 last_rx_ack; /* Last sequence number ack'ed by the peer */ - UINT8 next_seq_expected; /* Next peer sequence number expected */ - UINT8 last_ack_sent; /* Last peer sequence number ack'ed */ - UINT8 num_tries; /* Number of retries to send a packet */ - UINT8 max_held_acks; /* Max acks we can hold before sending */ - - BOOLEAN remote_busy; /* TRUE if peer has flowed us off */ - BOOLEAN local_busy; /* TRUE if we have flowed off the peer */ - - BOOLEAN rej_sent; /* Reject was sent */ - BOOLEAN srej_sent; /* Selective Reject was sent */ - BOOLEAN wait_ack; /* Transmitter is waiting ack (poll sent) */ - BOOLEAN rej_after_srej; /* Send a REJ when SREJ clears */ - - BOOLEAN send_f_rsp; /* We need to send an F-bit response */ - - UINT16 rx_sdu_len; /* Length of the SDU being received */ - BT_HDR *p_rx_sdu; /* Buffer holding the SDU being received */ - fixed_queue_t *waiting_for_ack_q; /* Buffers sent and waiting for peer to ack */ - fixed_queue_t *srej_rcv_hold_q; /* Buffers rcvd but held pending SREJ rsp */ - fixed_queue_t *retrans_q; /* Buffers being retransmitted */ - - TIMER_LIST_ENT ack_timer; /* Timer delaying RR */ - TIMER_LIST_ENT mon_retrans_timer; /* Timer Monitor or Retransmission */ - -#if (L2CAP_ERTM_STATS == TRUE) - UINT32 connect_tick_count; /* Time channel was established */ - UINT32 ertm_pkt_counts[2]; /* Packets sent and received */ - UINT32 ertm_byte_counts[2]; /* Bytes sent and received */ - UINT32 s_frames_sent[4]; /* S-frames sent (RR, REJ, RNR, SREJ) */ - UINT32 s_frames_rcvd[4]; /* S-frames rcvd (RR, REJ, RNR, SREJ) */ - UINT32 xmit_window_closed; /* # of times the xmit window was closed */ - UINT32 controller_idle; /* # of times less than 2 packets in controller */ - /* when the xmit window was closed */ - UINT32 pkts_retransmitted; /* # of packets that were retransmitted */ - UINT32 retrans_touts; /* # of retransmission timouts */ - UINT32 xmit_ack_touts; /* # of xmit ack timouts */ - -#define L2CAP_ERTM_STATS_NUM_AVG 10 -#define L2CAP_ERTM_STATS_AVG_NUM_SAMPLES 100 - UINT32 ack_delay_avg_count; - UINT32 ack_delay_avg_index; - UINT32 throughput_start; - UINT32 throughput[L2CAP_ERTM_STATS_NUM_AVG]; - UINT32 ack_delay_avg[L2CAP_ERTM_STATS_NUM_AVG]; - UINT32 ack_delay_min[L2CAP_ERTM_STATS_NUM_AVG]; - UINT32 ack_delay_max[L2CAP_ERTM_STATS_NUM_AVG]; - UINT32 ack_q_count_avg[L2CAP_ERTM_STATS_NUM_AVG]; - UINT32 ack_q_count_min[L2CAP_ERTM_STATS_NUM_AVG]; - UINT32 ack_q_count_max[L2CAP_ERTM_STATS_NUM_AVG]; -#endif -} tL2C_FCRB; - - -/* Define a registration control block. Every application (e.g. RFCOMM, SDP, -** TCS etc) that registers with L2CAP is assigned one of these. -*/ -#if (L2CAP_UCD_INCLUDED == TRUE) -#define L2C_UCD_RCB_ID 0x00 -#define L2C_UCD_STATE_UNUSED 0x00 -#define L2C_UCD_STATE_W4_DATA 0x01 -#define L2C_UCD_STATE_W4_RECEPTION 0x02 -#define L2C_UCD_STATE_W4_MTU 0x04 - -typedef struct { - UINT8 state; - tL2CAP_UCD_CB_INFO cb_info; -} tL2C_UCD_REG; -#endif - -typedef struct { - BOOLEAN in_use; - UINT16 psm; - UINT16 real_psm; /* This may be a dummy RCB for an o/b connection but */ - /* this is the real PSM that we need to connect to */ -#if (L2CAP_UCD_INCLUDED == TRUE) - tL2C_UCD_REG ucd; -#endif - - tL2CAP_APPL_INFO api; -} tL2C_RCB; - -typedef void (tL2CAP_SEC_CBACK) (BD_ADDR bd_addr, tBT_TRANSPORT trasnport, - void *p_ref_data, tBTM_STATUS result); - -typedef struct -{ - UINT16 psm; - tBT_TRANSPORT transport; - BOOLEAN is_originator; - tL2CAP_SEC_CBACK *p_callback; - void *p_ref_data; -}tL2CAP_SEC_DATA; - -#ifndef L2CAP_CBB_DEFAULT_DATA_RATE_BUFF_QUOTA -#define L2CAP_CBB_DEFAULT_DATA_RATE_BUFF_QUOTA 100 -#endif -/* Define a channel control block (CCB). There may be many channel control blocks -** between the same two Bluetooth devices (i.e. on the same link). -** Each CCB has unique local and remote CIDs. All channel control blocks on -** the same physical link and are chained together. -*/ -typedef struct t_l2c_ccb { - BOOLEAN in_use; /* TRUE when in use, FALSE when not */ - tL2C_CHNL_STATE chnl_state; /* Channel state */ - tL2CAP_LE_CFG_INFO local_conn_cfg; /* Our config for ble conn oriented channel */ - tL2CAP_LE_CFG_INFO peer_conn_cfg; /* Peer device config ble conn oriented channel */ - - struct t_l2c_ccb *p_next_ccb; /* Next CCB in the chain */ - struct t_l2c_ccb *p_prev_ccb; /* Previous CCB in the chain */ - struct t_l2c_linkcb *p_lcb; /* Link this CCB is assigned to */ - - UINT16 local_cid; /* Local CID */ - UINT16 remote_cid; /* Remote CID */ - - TIMER_LIST_ENT timer_entry; /* CCB Timer List Entry */ - - tL2C_RCB *p_rcb; /* Registration CB for this Channel */ - bool should_free_rcb; /* True if RCB was allocated on the heap */ - -#define IB_CFG_DONE 0x01 -#define OB_CFG_DONE 0x02 -#define RECONFIG_FLAG 0x04 /* True after initial configuration */ -#define CFG_DONE_MASK (IB_CFG_DONE | OB_CFG_DONE) - - UINT8 config_done; /* Configuration flag word */ - UINT8 local_id; /* Transaction ID for local trans */ - UINT8 remote_id; /* Transaction ID for local */ - -#define CCB_FLAG_NO_RETRY 0x01 /* no more retry */ -#define CCB_FLAG_SENT_PENDING 0x02 /* already sent pending response */ - UINT8 flags; - - tL2CAP_CFG_INFO our_cfg; /* Our saved configuration options */ - tL2CAP_CH_CFG_BITS peer_cfg_bits; /* Store what peer wants to configure */ - tL2CAP_CFG_INFO peer_cfg; /* Peer's saved configuration options */ - - fixed_queue_t *xmit_hold_q; /* Transmit data hold queue */ - BOOLEAN cong_sent; /* Set when congested status sent */ - UINT16 buff_quota; /* Buffer quota before sending congestion */ - - tL2CAP_CHNL_PRIORITY ccb_priority; /* Channel priority */ - tL2CAP_CHNL_DATA_RATE tx_data_rate; /* Channel Tx data rate */ - tL2CAP_CHNL_DATA_RATE rx_data_rate; /* Channel Rx data rate */ - - /* Fields used for eL2CAP */ - tL2CAP_ERTM_INFO ertm_info; - tL2C_FCRB fcrb; - UINT16 tx_mps; /* TX MPS adjusted based on current controller */ - UINT16 max_rx_mtu; - UINT8 fcr_cfg_tries; /* Max number of negotiation attempts */ - BOOLEAN peer_cfg_already_rejected; /* If mode rejected once, set to TRUE */ - BOOLEAN out_cfg_fcr_present; /* TRUE if cfg response shoulkd include fcr options */ - -#define L2CAP_CFG_FCS_OUR 0x01 /* Our desired config FCS option */ -#define L2CAP_CFG_FCS_PEER 0x02 /* Peer's desired config FCS option */ -#define L2CAP_BYPASS_FCS (L2CAP_CFG_FCS_OUR | L2CAP_CFG_FCS_PEER) - UINT8 bypass_fcs; - -#if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) - BOOLEAN is_flushable; /* TRUE if channel is flushable */ -#endif - -#if (L2CAP_NUM_FIXED_CHNLS > 0) || (L2CAP_UCD_INCLUDED == TRUE) - UINT16 fixed_chnl_idle_tout; /* Idle timeout to use for the fixed channel */ -#endif - UINT16 tx_data_len; -} tL2C_CCB; - -/*********************************************************************** -** Define a queue of linked CCBs. -*/ -typedef struct { - tL2C_CCB *p_first_ccb; /* The first channel in this queue */ - tL2C_CCB *p_last_ccb; /* The last channel in this queue */ -} tL2C_CCB_Q; - -#if (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) - -/* Round-Robin service for the same priority channels */ -#define L2CAP_NUM_CHNL_PRIORITY 3 /* Total number of priority group (high, medium, low)*/ -#define L2CAP_CHNL_PRIORITY_WEIGHT 5 /* weight per priority for burst transmission quota */ -#define L2CAP_GET_PRIORITY_QUOTA(pri) ((L2CAP_NUM_CHNL_PRIORITY - (pri)) * L2CAP_CHNL_PRIORITY_WEIGHT) - -/* CCBs within the same LCB are served in round robin with priority */ -/* It will make sure that low priority channel (for example, HF signaling on RFCOMM) */ -/* can be sent to headset even if higher priority channel (for example, AV media channel) */ -/* is congested. */ - -typedef struct { - tL2C_CCB *p_serve_ccb; /* current serving ccb within priority group */ - tL2C_CCB *p_first_ccb; /* first ccb of priority group */ - UINT8 num_ccb; /* number of channels in priority group */ - UINT8 quota; /* burst transmission quota */ -} tL2C_RR_SERV; - -#endif /* (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) */ - -/* Define a link control block. There is one link control block between -** this device and any other device (i.e. BD ADDR). -*/ -typedef struct t_l2c_linkcb { - BOOLEAN in_use; /* TRUE when in use, FALSE when not */ - tL2C_LINK_STATE link_state; - - TIMER_LIST_ENT timer_entry; /* Timer list entry for timeout evt */ - UINT16 handle; /* The handle used with LM */ - - tL2C_CCB_Q ccb_queue; /* Queue of CCBs on this LCB */ - - tL2C_CCB *p_pending_ccb; /* ccb of waiting channel during link disconnect */ - TIMER_LIST_ENT info_timer_entry; /* Timer entry for info resp timeout evt */ - TIMER_LIST_ENT upda_con_timer; /* Timer entry for update connection parametr */ - BD_ADDR remote_bd_addr; /* The BD address of the remote */ - - UINT8 link_role; /* Master or slave */ - UINT8 id; - UINT8 cur_echo_id; /* Current id value for echo request */ - tL2CA_ECHO_RSP_CB *p_echo_rsp_cb; /* Echo response callback */ - UINT16 idle_timeout; /* Idle timeout */ - BOOLEAN is_bonding; /* True - link active only for bonding */ - - UINT16 link_flush_tout; /* Flush timeout used */ - - UINT16 link_xmit_quota; /* Num outstanding pkts allowed */ - UINT16 sent_not_acked; /* Num packets sent but not acked */ - - BOOLEAN partial_segment_being_sent; /* Set TRUE when a partial segment */ - /* is being sent. */ - BOOLEAN w4_info_rsp; /* TRUE when info request is active */ - UINT8 info_rx_bits; /* set 1 if received info type */ - UINT32 peer_ext_fea; /* Peer's extended features mask */ - list_t *link_xmit_data_q; /* Link transmit data buffer queue */ - - UINT8 peer_chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE]; -#if (L2CAP_UCD_INCLUDED == TRUE) - UINT16 ucd_mtu; /* peer MTU on UCD */ - fixed_queue_t *ucd_out_sec_pending_q; /* Security pending outgoing UCD packet */ - fixed_queue_t *ucd_in_sec_pending_q; /* Security pending incoming UCD packet */ -#endif - - BT_HDR *p_hcit_rcv_acl; /* Current HCIT ACL buf being rcvd */ - UINT16 idle_timeout_sv; /* Save current Idle timeout */ - UINT8 acl_priority; /* L2C_PRIORITY_NORMAL or L2C_PRIORITY_HIGH */ - tL2CA_NOCP_CB *p_nocp_cb; /* Num Cmpl pkts callback */ - -#if (L2CAP_NUM_FIXED_CHNLS > 0) - tL2C_CCB *p_fixed_ccbs[L2CAP_NUM_FIXED_CHNLS]; - UINT16 disc_reason; -#endif - - tBT_TRANSPORT transport; -#if (BLE_INCLUDED == TRUE) - tBLE_ADDR_TYPE open_addr_type; /* be set by open API */ - tBLE_ADDR_TYPE ble_addr_type; - UINT16 tx_data_len; /* tx data length used in data length extension */ - fixed_queue_t *le_sec_pending_q; /* LE coc channels waiting for security check completion */ - UINT8 sec_act; -#define L2C_BLE_CONN_UPDATE_DISABLE 0x1 /* disable update connection parameters */ -#define L2C_BLE_NEW_CONN_PARAM 0x2 /* new connection parameter to be set */ -#define L2C_BLE_UPDATE_PENDING 0x4 /* waiting for connection update finished */ -#define L2C_BLE_NOT_DEFAULT_PARAM 0x8 /* not using default connection parameters */ -#define L2C_BLE_UPDATE_PARAM_FULL 0x10 /* update connection parameters full, can not update */ - UINT8 conn_update_mask; - /* cache connection parameters that wait to update */ - UINT16 waiting_update_conn_min_interval; - UINT16 waiting_update_conn_max_interval; - UINT16 waiting_update_conn_latency; - UINT16 waiting_update_conn_timeout; - /* cache parameters that is being updated */ - UINT16 updating_conn_min_interval; - UINT16 updating_conn_max_interval; - bool updating_param_flag; - /* current connection parameters that current connection is using */ - UINT16 current_used_conn_interval; - UINT16 current_used_conn_latency; - UINT16 current_used_conn_timeout; - /* connection parameters update order: - waiting_update_conn_xx -> updating_conn_xx -> current_used_conn_xx - */ -#endif - -#if (L2CAP_ROUND_ROBIN_CHANNEL_SERVICE == TRUE) - /* each priority group is limited burst transmission */ - /* round robin service for the same priority channels */ - tL2C_RR_SERV rr_serv[L2CAP_NUM_CHNL_PRIORITY]; - UINT8 rr_pri; /* current serving priority group */ -#endif - -} tL2C_LCB; - -/* Define the L2CAP control structure -*/ -typedef struct { - UINT8 l2cap_trace_level; - UINT16 controller_xmit_window; /* Total ACL window for all links */ - - UINT16 round_robin_quota; /* Round-robin link quota */ - UINT16 round_robin_unacked; /* Round-robin unacked */ - BOOLEAN check_round_robin; /* Do a round robin check */ - - BOOLEAN is_cong_cback_context; - - tL2C_LCB lcb_pool[MAX_L2CAP_LINKS]; /* Link Control Block pool */ - tL2C_CCB ccb_pool[MAX_L2CAP_CHANNELS]; /* Channel Control Block pool */ - tL2C_RCB rcb_pool[MAX_L2CAP_CLIENTS]; /* Registration info pool */ - - tL2C_CCB *p_free_ccb_first; /* Pointer to first free CCB */ - tL2C_CCB *p_free_ccb_last; /* Pointer to last free CCB */ - - UINT8 desire_role; /* desire to be master/slave when accepting a connection */ - BOOLEAN disallow_switch; /* FALSE, to allow switch at create conn */ - UINT16 num_lm_acl_bufs; /* # of ACL buffers on controller */ - UINT16 idle_timeout; /* Idle timeout */ - - list_t *rcv_pending_q; /* Recv pending queue */ - TIMER_LIST_ENT rcv_hold_tle; /* Timer list entry for rcv hold */ - - tL2C_LCB *p_cur_hcit_lcb; /* Current HCI Transport buffer */ - UINT16 num_links_active; /* Number of links active */ - -#if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) - UINT16 non_flushable_pbf; /* L2CAP_PKT_START_NON_FLUSHABLE if controller supports */ - /* Otherwise, L2CAP_PKT_START */ - BOOLEAN is_flush_active; /* TRUE if an HCI_Enhanced_Flush has been sent */ -#endif - -#if L2CAP_CONFORMANCE_TESTING == TRUE - UINT32 test_info_resp; /* Conformance testing needs a dynamic response */ -#endif - -#if (L2CAP_NUM_FIXED_CHNLS > 0) - tL2CAP_FIXED_CHNL_REG fixed_reg[L2CAP_NUM_FIXED_CHNLS]; /* Reg info for fixed channels */ -#endif - -#if (BLE_INCLUDED == TRUE) - UINT16 num_ble_links_active; /* Number of LE links active */ - BOOLEAN is_ble_connecting; - BD_ADDR ble_connecting_bda; - UINT16 controller_le_xmit_window; /* Total ACL window for all links */ - tL2C_BLE_FIXED_CHNLS_MASK l2c_ble_fixed_chnls_mask; // LE fixed channels mask - UINT16 num_lm_ble_bufs; /* # of ACL buffers on controller */ - UINT16 ble_round_robin_quota; /* Round-robin link quota */ - UINT16 ble_round_robin_unacked; /* Round-robin unacked */ - BOOLEAN ble_check_round_robin; /* Do a round robin check */ - tL2C_RCB ble_rcb_pool[BLE_MAX_L2CAP_CLIENTS]; /* Registration info pool */ -#endif - - tL2CA_ECHO_DATA_CB *p_echo_data_cb; /* Echo data callback */ - -#if (defined(L2CAP_HIGH_PRI_CHAN_QUOTA_IS_CONFIGURABLE) && (L2CAP_HIGH_PRI_CHAN_QUOTA_IS_CONFIGURABLE == TRUE)) - UINT16 high_pri_min_xmit_quota; /* Minimum number of ACL credit for high priority link */ -#endif /* (L2CAP_HIGH_PRI_CHAN_QUOTA_IS_CONFIGURABLE == TRUE) */ - - UINT16 dyn_psm; -} tL2C_CB; - - - -/* Define a structure that contains the information about a connection. -** This structure is used to pass between functions, and not all the -** fields will always be filled in. -*/ -typedef struct { - BD_ADDR bd_addr; /* Remote BD address */ - UINT8 status; /* Connection status */ - UINT16 psm; /* PSM of the connection */ - UINT16 l2cap_result; /* L2CAP result */ - UINT16 l2cap_status; /* L2CAP status */ - UINT16 remote_cid; /* Remote CID */ -} tL2C_CONN_INFO; - - -typedef void (tL2C_FCR_MGMT_EVT_HDLR) (UINT8, tL2C_CCB *); - -/* The offset in a buffer that L2CAP will use when building commands. -*/ -#define L2CAP_SEND_CMD_OFFSET 0 - - -/* Number of ACL buffers to use for high priority channel -*/ -#if (!defined(L2CAP_HIGH_PRI_CHAN_QUOTA_IS_CONFIGURABLE) || (L2CAP_HIGH_PRI_CHAN_QUOTA_IS_CONFIGURABLE == FALSE)) -#define L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A (L2CAP_HIGH_PRI_MIN_XMIT_QUOTA) -#else -#define L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A (l2cb.high_pri_min_xmit_quota) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -/* L2CAP global data -************************************ -*/ -#if (!defined L2C_DYNAMIC_MEMORY) || (L2C_DYNAMIC_MEMORY == FALSE) -extern tL2C_CB l2cb; -#else -extern tL2C_CB *l2c_cb_ptr; -#define l2cb (*l2c_cb_ptr) -#endif - - -/* Functions provided by l2c_main.c -************************************ -*/ -void l2c_init(void); -void l2c_free(void); - -extern void l2c_process_timeout (TIMER_LIST_ENT *p_tle); -extern UINT8 l2c_data_write (UINT16 cid, BT_HDR *p_data, UINT16 flag); -extern void l2c_rcv_acl_data (BT_HDR *p_msg); -extern void l2c_process_held_packets (BOOLEAN timed_out); - -/* Functions provided by l2c_utils.c -************************************ -*/ -extern tL2C_LCB *l2cu_allocate_lcb (BD_ADDR p_bd_addr, BOOLEAN is_bonding, tBT_TRANSPORT transport); -extern BOOLEAN l2cu_start_post_bond_timer (UINT16 handle); -extern void l2cu_release_lcb (tL2C_LCB *p_lcb); -extern tL2C_LCB *l2cu_find_lcb_by_bd_addr (BD_ADDR p_bd_addr, tBT_TRANSPORT transport); -extern tL2C_LCB *l2cu_find_lcb_by_handle (UINT16 handle); -extern void l2cu_update_lcb_4_bonding (BD_ADDR p_bd_addr, BOOLEAN is_bonding); - -extern UINT8 l2cu_get_conn_role (tL2C_LCB *p_this_lcb); -extern BOOLEAN l2cu_set_acl_priority (BD_ADDR bd_addr, UINT8 priority, BOOLEAN reset_after_rs); - -extern void l2cu_enqueue_ccb (tL2C_CCB *p_ccb); -extern void l2cu_dequeue_ccb (tL2C_CCB *p_ccb); -extern void l2cu_change_pri_ccb (tL2C_CCB *p_ccb, tL2CAP_CHNL_PRIORITY priority); - -extern tL2C_CCB *l2cu_allocate_ccb (tL2C_LCB *p_lcb, UINT16 cid); -extern void l2cu_release_ccb (tL2C_CCB *p_ccb); -extern tL2C_CCB *l2cu_find_ccb_by_cid (tL2C_LCB *p_lcb, UINT16 local_cid); -extern tL2C_CCB *l2cu_find_ccb_by_remote_cid (tL2C_LCB *p_lcb, UINT16 remote_cid); -extern void l2cu_adj_id (tL2C_LCB *p_lcb, UINT8 adj_mask); -extern BOOLEAN l2c_is_cmd_rejected (UINT8 cmd_code, UINT8 id, tL2C_LCB *p_lcb); - -extern void l2cu_send_peer_cmd_reject (tL2C_LCB *p_lcb, UINT16 reason, - UINT8 rem_id, UINT16 p1, UINT16 p2); -extern void l2cu_send_peer_connect_req (tL2C_CCB *p_ccb); -extern void l2cu_send_peer_connect_rsp (tL2C_CCB *p_ccb, UINT16 result, UINT16 status); -extern void l2cu_send_peer_config_req (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); -extern void l2cu_send_peer_config_rsp (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); -extern void l2cu_send_peer_config_rej (tL2C_CCB *p_ccb, UINT8 *p_data, UINT16 data_len, UINT16 rej_len); -extern void l2cu_send_peer_disc_req (tL2C_CCB *p_ccb); -extern void l2cu_send_peer_disc_rsp (tL2C_LCB *p_lcb, UINT8 remote_id, UINT16 local_cid, UINT16 remote_cid); -extern void l2cu_send_peer_echo_req (tL2C_LCB *p_lcb, UINT8 *p_data, UINT16 data_len); -extern void l2cu_send_peer_echo_rsp (tL2C_LCB *p_lcb, UINT8 id, UINT8 *p_data, UINT16 data_len); -extern void l2cu_send_peer_info_rsp (tL2C_LCB *p_lcb, UINT8 id, UINT16 info_type); -extern void l2cu_reject_connection (tL2C_LCB *p_lcb, UINT16 remote_cid, UINT8 rem_id, UINT16 result); -extern void l2cu_send_peer_info_req (tL2C_LCB *p_lcb, UINT16 info_type); -extern void l2cu_set_acl_hci_header (BT_HDR *p_buf, tL2C_CCB *p_ccb); -extern void l2cu_check_channel_congestion (tL2C_CCB *p_ccb); -extern void l2cu_disconnect_chnl (tL2C_CCB *p_ccb); - -#if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) -extern void l2cu_set_non_flushable_pbf(BOOLEAN); -#endif - -#if (BLE_INCLUDED == TRUE) -extern void l2cu_send_peer_ble_par_req (tL2C_LCB *p_lcb, UINT16 min_int, UINT16 max_int, UINT16 latency, UINT16 timeout); -extern void l2cu_send_peer_ble_par_rsp (tL2C_LCB *p_lcb, UINT16 reason, UINT8 rem_id); -#endif - -extern BOOLEAN l2cu_initialize_fixed_ccb (tL2C_LCB *p_lcb, UINT16 fixed_cid, tL2CAP_FCR_OPTS *p_fcr); -extern void l2cu_no_dynamic_ccbs (tL2C_LCB *p_lcb); -extern void l2cu_process_fixed_chnl_resp (tL2C_LCB *p_lcb); - -/* Functions provided by l2c_ucd.c -************************************ -*/ -#if (L2CAP_UCD_INCLUDED == TRUE) -void l2c_ucd_delete_sec_pending_q(tL2C_LCB *p_lcb); -void l2c_ucd_enqueue_pending_out_sec_q(tL2C_CCB *p_ccb, void *p_data); -BOOLEAN l2c_ucd_check_pending_info_req(tL2C_CCB *p_ccb); -BOOLEAN l2c_ucd_check_pending_out_sec_q(tL2C_CCB *p_ccb); -void l2c_ucd_send_pending_out_sec_q(tL2C_CCB *p_ccb); -void l2c_ucd_discard_pending_out_sec_q(tL2C_CCB *p_ccb); -BOOLEAN l2c_ucd_check_pending_in_sec_q(tL2C_CCB *p_ccb); -void l2c_ucd_send_pending_in_sec_q(tL2C_CCB *p_ccb); -void l2c_ucd_discard_pending_in_sec_q(tL2C_CCB *p_ccb); -BOOLEAN l2c_ucd_check_rx_pkts(tL2C_LCB *p_lcb, BT_HDR *p_msg); -BOOLEAN l2c_ucd_process_event(tL2C_CCB *p_ccb, UINT16 event, void *p_data); -#endif - -#if (BLE_INCLUDED == TRUE) -extern void l2cu_send_peer_ble_par_req (tL2C_LCB *p_lcb, UINT16 min_int, UINT16 max_int, UINT16 latency, UINT16 timeout); -extern void l2cu_send_peer_ble_par_rsp (tL2C_LCB *p_lcb, UINT16 reason, UINT8 rem_id); -extern void l2cu_reject_ble_connection (tL2C_LCB *p_lcb, UINT8 rem_id, UINT16 result); -extern void l2cu_send_peer_ble_credit_based_conn_res (tL2C_CCB *p_ccb, UINT16 result); -extern void l2cu_send_peer_ble_credit_based_conn_req (tL2C_CCB *p_ccb); -extern void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB *p_ccb, UINT16 credit_value); -extern void l2cu_send_peer_ble_credit_based_disconn_req(tL2C_CCB *p_ccb); - -#endif - -extern BOOLEAN l2cu_initialize_fixed_ccb (tL2C_LCB *p_lcb, UINT16 fixed_cid, tL2CAP_FCR_OPTS *p_fcr); -extern void l2cu_no_dynamic_ccbs (tL2C_LCB *p_lcb); -extern void l2cu_process_fixed_chnl_resp (tL2C_LCB *p_lcb); - - -/* Functions provided for Broadcom Aware -**************************************** -*/ -extern BOOLEAN l2cu_check_feature_req (tL2C_LCB *p_lcb, UINT8 id, UINT8 *p_data, UINT16 data_len); -extern void l2cu_check_feature_rsp (tL2C_LCB *p_lcb, UINT8 id, UINT8 *p_data, UINT16 data_len); -extern void l2cu_send_feature_req (tL2C_CCB *p_ccb); - -extern tL2C_RCB *l2cu_allocate_rcb (UINT16 psm); -extern tL2C_RCB *l2cu_find_rcb_by_psm (UINT16 psm); -extern void l2cu_release_rcb (tL2C_RCB *p_rcb); -extern tL2C_RCB *l2cu_allocate_ble_rcb (UINT16 psm); -extern tL2C_RCB *l2cu_find_ble_rcb_by_psm (UINT16 psm); - - -extern UINT8 l2cu_process_peer_cfg_req (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); -extern void l2cu_process_peer_cfg_rsp (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); -extern void l2cu_process_our_cfg_req (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); -extern void l2cu_process_our_cfg_rsp (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); - -extern void l2cu_device_reset (void); -extern tL2C_LCB *l2cu_find_lcb_by_state (tL2C_LINK_STATE state); -extern BOOLEAN l2cu_lcb_disconnecting (void); - -extern BOOLEAN l2cu_create_conn (tL2C_LCB *p_lcb, tBT_TRANSPORT transport); -extern BOOLEAN l2cu_create_conn_after_switch (tL2C_LCB *p_lcb); -extern BT_HDR *l2cu_get_next_buffer_to_send (tL2C_LCB *p_lcb); -extern void l2cu_resubmit_pending_sec_req (BD_ADDR p_bda); -extern void l2cu_initialize_amp_ccb (tL2C_LCB *p_lcb); -extern void l2cu_adjust_out_mps (tL2C_CCB *p_ccb); - -/* Functions provided by l2c_link.c -************************************ -*/ -extern BOOLEAN l2c_link_hci_conn_req (BD_ADDR bd_addr); -extern BOOLEAN l2c_link_hci_conn_comp (UINT8 status, UINT16 handle, BD_ADDR p_bda); -extern BOOLEAN l2c_link_hci_disc_comp (UINT16 handle, UINT8 reason); -extern BOOLEAN l2c_link_hci_qos_violation (UINT16 handle); -extern void l2c_link_timeout (tL2C_LCB *p_lcb); -extern void l2c_info_timeout (tL2C_LCB *p_lcb); -extern void l2c_link_check_send_pkts (tL2C_LCB *p_lcb, tL2C_CCB *p_ccb, BT_HDR *p_buf); -extern void l2c_link_adjust_allocation (void); -extern void l2c_link_process_num_completed_pkts (UINT8 *p); -extern void l2c_link_process_num_completed_blocks (UINT8 controller_id, UINT8 *p, UINT16 evt_len); -extern void l2c_link_processs_num_bufs (UINT16 num_lm_acl_bufs); -extern UINT8 l2c_link_pkts_rcvd (UINT16 *num_pkts, UINT16 *handles); -extern void l2c_link_role_changed (BD_ADDR bd_addr, UINT8 new_role, UINT8 hci_status); -extern void l2c_link_sec_comp (BD_ADDR p_bda, tBT_TRANSPORT trasnport, void *p_ref_data, UINT8 status); -extern void l2c_link_segments_xmitted (BT_HDR *p_msg); -extern void l2c_pin_code_request (BD_ADDR bd_addr); -extern void l2c_link_adjust_chnl_allocation (void); - -#if (BLE_INCLUDED == TRUE) -extern void l2c_link_processs_ble_num_bufs (UINT16 num_lm_acl_bufs); -#endif - -#if L2CAP_WAKE_PARKED_LINK == TRUE -extern BOOLEAN l2c_link_check_power_mode ( tL2C_LCB *p_lcb ); -#define L2C_LINK_CHECK_POWER_MODE(x) l2c_link_check_power_mode ((x)) -#else // L2CAP_WAKE_PARKED_LINK -#define L2C_LINK_CHECK_POWER_MODE(x) (FALSE) -#endif // L2CAP_WAKE_PARKED_LINK - -#if L2CAP_CONFORMANCE_TESTING == TRUE -/* Used only for conformance testing */ -extern void l2cu_set_info_rsp_mask (UINT32 mask); -#endif - -/* Functions provided by l2c_csm.c -************************************ -*/ -extern void l2c_csm_execute (tL2C_CCB *p_ccb, UINT16 event, void *p_data); - -extern void l2c_enqueue_peer_data (tL2C_CCB *p_ccb, BT_HDR *p_buf); - - -/* Functions provided by l2c_fcr.c -************************************ -*/ -extern void l2c_fcr_cleanup (tL2C_CCB *p_ccb); -extern void l2c_fcr_proc_pdu (tL2C_CCB *p_ccb, BT_HDR *p_buf); -extern void l2c_fcr_proc_tout (tL2C_CCB *p_ccb); -extern void l2c_fcr_proc_ack_tout (tL2C_CCB *p_ccb); -extern void l2c_fcr_send_S_frame (tL2C_CCB *p_ccb, UINT16 function_code, UINT16 pf_bit); -extern BT_HDR *l2c_fcr_clone_buf (BT_HDR *p_buf, UINT16 new_offset, UINT16 no_of_bytes); -extern BOOLEAN l2c_fcr_is_flow_controlled (tL2C_CCB *p_ccb); -extern BT_HDR *l2c_fcr_get_next_xmit_sdu_seg (tL2C_CCB *p_ccb, UINT16 max_packet_length); -extern void l2c_fcr_start_timer (tL2C_CCB *p_ccb); - -/* Configuration negotiation */ -extern UINT8 l2c_fcr_chk_chan_modes (tL2C_CCB *p_ccb); -extern BOOLEAN l2c_fcr_adj_our_req_options (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); -extern void l2c_fcr_adj_our_rsp_options (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_peer_cfg); -extern BOOLEAN l2c_fcr_renegotiate_chan(tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); -extern UINT8 l2c_fcr_process_peer_cfg_req(tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg); -extern void l2c_fcr_adj_monitor_retran_timeout (tL2C_CCB *p_ccb); -extern void l2c_fcr_stop_timer (tL2C_CCB *p_ccb); -extern void l2c_fcr_free_timer (tL2C_CCB *p_ccb); -/* Functions provided by l2c_ble.c -************************************ -*/ -#if (BLE_INCLUDED == TRUE) -extern BOOLEAN l2cble_create_conn (tL2C_LCB *p_lcb); -extern void l2cble_process_sig_cmd (tL2C_LCB *p_lcb, UINT8 *p, UINT16 pkt_len); -extern void l2cble_conn_comp (UINT16 handle, UINT8 role, BD_ADDR bda, tBLE_ADDR_TYPE type, - UINT16 conn_interval, UINT16 conn_latency, UINT16 conn_timeout); -extern BOOLEAN l2cble_init_direct_conn (tL2C_LCB *p_lcb); -extern void l2cble_notify_le_connection (BD_ADDR bda); -extern void l2c_ble_link_adjust_allocation (void); -extern void l2cble_process_conn_update_evt (UINT16 handle, UINT8 status, UINT16 conn_interval, - UINT16 conn_latency, UINT16 conn_timeout); -extern void l2cble_get_conn_param_format_err_from_contoller(UINT8 status, UINT16 handle); - -extern void l2cble_credit_based_conn_req (tL2C_CCB *p_ccb); -extern void l2cble_credit_based_conn_res (tL2C_CCB *p_ccb, UINT16 result); -extern void l2cble_send_peer_disc_req(tL2C_CCB *p_ccb); -extern void l2cble_send_flow_control_credit(tL2C_CCB *p_ccb, UINT16 credit_value); -extern BOOLEAN l2ble_sec_access_req(BD_ADDR bd_addr, UINT16 psm, BOOLEAN is_originator, tL2CAP_SEC_CBACK *p_callback, void *p_ref_data); - - -#if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE) -extern void l2cble_process_rc_param_request_evt(UINT16 handle, UINT16 int_min, UINT16 int_max, - UINT16 latency, UINT16 timeout); -#endif - -extern void l2cble_update_data_length(tL2C_LCB *p_lcb); -extern void l2cble_set_fixed_channel_tx_data_length(BD_ADDR remote_bda, UINT16 fix_cid, - UINT16 tx_mtu); -extern void l2c_send_update_conn_params_cb(tL2C_LCB *p_lcb, UINT8 status); -extern void l2cble_process_data_length_change_event(UINT16 handle, UINT16 tx_data_len, - UINT16 rx_data_len); -extern UINT32 CalConnectParamTimeout(tL2C_LCB *p_lcb); - -#endif -extern void l2cu_process_fixed_disc_cback (tL2C_LCB *p_lcb); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/bluedroid/l2cap_client.h b/tools/sdk/include/bluedroid/l2cap_client.h deleted file mode 100644 index d18be32c4ca..00000000000 --- a/tools/sdk/include/bluedroid/l2cap_client.h +++ /dev/null @@ -1,80 +0,0 @@ -/****************************************************************************** - * - * 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 _L2CAP_CLIENT_H_ -#define _L2CAP_CLIENT_H_ -#if (defined(L2CAP_CLIENT_INCLUDED) && L2CAP_CLIENT_INCLUDED == TRUE) - -//#include -#include -#include - -typedef struct buffer_t buffer_t; -typedef struct l2cap_client_t l2cap_client_t; - -typedef struct { - void (*connected)(l2cap_client_t *client, void *context); - void (*disconnected)(l2cap_client_t *client, void *context); - void (*read_ready)(l2cap_client_t *client, buffer_t *packet, void *context); - void (*write_ready)(l2cap_client_t *client, void *context); -} l2cap_client_callbacks_t; - -// Returns a new buffer with enough space for |size| bytes of L2CAP payload. -// |size| must be greater than zero. This function returns NULL if the buffer -// could not be allocated. The returned buffer must be freed with |buffer_free| -// when it is no longer needed. -buffer_t *l2cap_buffer_new(size_t size); - -// Creates and returns a new L2CAP client object. |callbacks| must not be NULL and -// must specify a set of functions that should be called back when events occur -// on the L2CAP connection. |context| may be NULL and will be passed as the argument -// to all callbacks in |l2cap_client_callbacks_t|. The returned object must be freed -// with |l2cap_client_free|. -l2cap_client_t *l2cap_client_new(const l2cap_client_callbacks_t *callbacks, void *context); - -// Frees the L2CAP client object allocated with |l2cap_client_new|. |client| may be NULL. -void l2cap_client_free(l2cap_client_t *client); - -// Attempts to connect the |client| to a peer device specified by |remote_bdaddr| -// using the |psm| protocol specifier. This function returns true if the connect -// operation could be started and will indicate completion with either a 'connected' -// callback (success) or a 'disconnected' callback (failure). -// -// This function must not be called while a connect operation is in progress or -// while |l2cap_client_is_connected|. |client| and |remote_bdaddr| must not be NULL. -// |psm| must be greater than zero. -bool l2cap_client_connect(l2cap_client_t *client, const bt_bdaddr_t *remote_bdaddr, uint16_t psm); - -// Disconnects a connected |client|. This function is asynchronous and idempotent. It -// will indicate completion with a 'disconnected' callback. |client| must not be NULL. -void l2cap_client_disconnect(l2cap_client_t *client); - -// Returns true if |client| is connected and is ready to accept data written to it. -// |client| must not be NULL. -bool l2cap_client_is_connected(const l2cap_client_t *client); - -// Writes data contained in |packet| to a connected |client|. This function returns -// true if the packet was successfully queued for delivery, false if the client cannot -// accept more data at this time. If this function returns false, the caller must wait -// for the 'write_ready' callback to write additional data to the client. Neither -// |client| nor |packet| may be NULL. -bool l2cap_client_write(l2cap_client_t *client, buffer_t *packet); - -#endif ///(defined(L2CAP_CLIENT_INCLUDED) && L2CAP_CLIENT_INCLUDED == TRUE) - -#endif /*_L2CAP_CLIENT_H_*/ diff --git a/tools/sdk/include/bluedroid/l2cdefs.h b/tools/sdk/include/bluedroid/l2cdefs.h deleted file mode 100644 index 56ddfb0df1c..00000000000 --- a/tools/sdk/include/bluedroid/l2cdefs.h +++ /dev/null @@ -1,329 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 L2CDEFS_H -#define L2CDEFS_H - -/* L2CAP command codes -*/ -#define L2CAP_CMD_REJECT 0x01 -#define L2CAP_CMD_CONN_REQ 0x02 -#define L2CAP_CMD_CONN_RSP 0x03 -#define L2CAP_CMD_CONFIG_REQ 0x04 -#define L2CAP_CMD_CONFIG_RSP 0x05 -#define L2CAP_CMD_DISC_REQ 0x06 -#define L2CAP_CMD_DISC_RSP 0x07 -#define L2CAP_CMD_ECHO_REQ 0x08 -#define L2CAP_CMD_ECHO_RSP 0x09 -#define L2CAP_CMD_INFO_REQ 0x0A -#define L2CAP_CMD_INFO_RSP 0x0B -#define L2CAP_CMD_AMP_CONN_REQ 0x0C -#define L2CAP_CMD_AMP_CONN_RSP 0x0D -#define L2CAP_CMD_AMP_MOVE_REQ 0x0E -#define L2CAP_CMD_AMP_MOVE_RSP 0x0F -#define L2CAP_CMD_AMP_MOVE_CFM 0x10 -#define L2CAP_CMD_AMP_MOVE_CFM_RSP 0x11 - -#define L2CAP_CMD_BLE_UPDATE_REQ 0x12 -#define L2CAP_CMD_BLE_UPDATE_RSP 0x13 -#define L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ 0x14 -#define L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES 0x15 -#define L2CAP_CMD_BLE_FLOW_CTRL_CREDIT 0x16 - - - -/* Define some packet and header lengths -*/ -#define L2CAP_PKT_OVERHEAD 4 /* Length and CID */ -#define L2CAP_CMD_OVERHEAD 4 /* Cmd code, Id and length */ -#define L2CAP_CMD_REJECT_LEN 2 /* Reason (data is optional) */ -#define L2CAP_CONN_REQ_LEN 4 /* PSM and source CID */ -#define L2CAP_CONN_RSP_LEN 8 /* Dest CID, source CID, reason, status */ -#define L2CAP_CONFIG_REQ_LEN 4 /* Dest CID, flags (data is optional) */ -#define L2CAP_CONFIG_RSP_LEN 6 /* Dest CID, flags, result,data optional*/ -#define L2CAP_DISC_REQ_LEN 4 /* Dest CID, source CID */ -#define L2CAP_DISC_RSP_LEN 4 /* Dest CID, source CID */ -#define L2CAP_ECHO_REQ_LEN 0 /* Data is optional */ -#define L2CAP_ECHO_RSP_LEN 0 /* Data is optional */ -#define L2CAP_INFO_REQ_LEN 2 /* Info type */ -#define L2CAP_INFO_RSP_LEN 4 /* Info type, result (data is optional) */ -#define L2CAP_BCST_OVERHEAD 2 /* Additional broadcast packet overhead */ -#define L2CAP_UCD_OVERHEAD 2 /* Additional connectionless packet overhead */ - -#define L2CAP_AMP_CONN_REQ_LEN 5 /* PSM, CID, and remote controller ID */ -#define L2CAP_AMP_MOVE_REQ_LEN 3 /* CID and remote controller ID */ -#define L2CAP_AMP_MOVE_RSP_LEN 4 /* CID and result */ -#define L2CAP_AMP_MOVE_CFM_LEN 4 /* CID and result */ -#define L2CAP_AMP_MOVE_CFM_RSP_LEN 2 /* CID */ - -#define L2CAP_CMD_BLE_UPD_REQ_LEN 8 /* Min and max interval, latency, tout */ -#define L2CAP_CMD_BLE_UPD_RSP_LEN 2 /* Result */ - -#define L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ_LEN 10 /* LE_PSM, SCID, MTU, MPS, Init Credit */ -#define L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES_LEN 10 /* DCID, MTU, MPS, Init credit, Result */ -#define L2CAP_CMD_BLE_FLOW_CTRL_CREDIT_LEN 4 /* CID, Credit */ - - - -/* Define the packet boundary flags -*/ -#if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE) -#define L2CAP_PKT_START_FLUSHABLE 2 -#define L2CAP_PKT_START_NON_FLUSHABLE 0 -#endif -#define L2CAP_COMPLETE_AMP_PKT 3 /* complete L2CAP packet on AMP HCI */ -#define L2CAP_PKT_START 2 -#define L2CAP_PKT_CONTINUE 1 -#define L2CAP_MASK_FLAG 0x0FFF -#define L2CAP_PKT_TYPE_SHIFT 12 -#define L2CAP_PKT_TYPE_MASK 3 - - -/* Define the L2CAP connection result codes -*/ -#define L2CAP_CONN_OK 0 -#define L2CAP_CONN_PENDING 1 -#define L2CAP_CONN_NO_PSM 2 -#define L2CAP_CONN_SECURITY_BLOCK 3 -#define L2CAP_CONN_NO_RESOURCES 4 -#define L2CAP_CONN_BAD_CTLR_ID 5 /* AMP related */ -#define L2CAP_CONN_TIMEOUT 0xEEEE -#define L2CAP_CONN_AMP_FAILED 254 -#define L2CAP_CONN_NO_LINK 255 /* Add a couple of our own for internal use */ -#define L2CAP_CONN_CANCEL 256 /* L2CAP connection cancelled */ - - -/* Define L2CAP Move Channel Response result codes -*/ -#define L2CAP_MOVE_OK 0 -#define L2CAP_MOVE_PENDING 1 -#define L2CAP_MOVE_CTRL_ID_NOT_SUPPORT 2 -#define L2CAP_MOVE_SAME_CTRLR_ID 3 -#define L2CAP_MOVE_CONFIG_NOT_SUPPORTED 4 -#define L2CAP_MOVE_CHAN_COLLISION 5 -#define L2CAP_MOVE_NOT_ALLOWED 6 - - -/* Define L2CAP Move Channel Confirmation result codes -*/ -#define L2CAP_MOVE_CFM_OK 0 -#define L2CAP_MOVE_CFM_REFUSED 1 - - -/* Define the L2CAP command reject reason codes -*/ -#define L2CAP_CMD_REJ_NOT_UNDERSTOOD 0 -#define L2CAP_CMD_REJ_MTU_EXCEEDED 1 -#define L2CAP_CMD_REJ_INVALID_CID 2 - - -/* L2CAP Predefined CIDs -*/ -#define L2CAP_SIGNALLING_CID 1 -#define L2CAP_CONNECTIONLESS_CID 2 -#define L2CAP_AMP_CID 3 -#define L2CAP_ATT_CID 4 -#define L2CAP_BLE_SIGNALLING_CID 5 -#define L2CAP_SMP_CID 6 -#define L2CAP_SMP_BR_CID 7 -#define L2CAP_AMP_TEST_CID 0x003F -#define L2CAP_BASE_APPL_CID 0x0040 -#define L2CAP_BLE_CONN_MAX_CID 0x007F - -/* Fixed Channels mask bits */ - -/* Signal channel supported (Mandatory) */ -#define L2CAP_FIXED_CHNL_SIG_BIT (1 << L2CAP_SIGNALLING_CID) - -/* Connectionless reception */ -#define L2CAP_FIXED_CHNL_CNCTLESS_BIT (1 << L2CAP_CONNECTIONLESS_CID) - -/* AMP Manager supported */ -#define L2CAP_FIXED_CHNL_AMP_BIT (1 << L2CAP_AMP_CID) - -/* Attribute protocol supported */ -#define L2CAP_FIXED_CHNL_ATT_BIT (1 << L2CAP_ATT_CID) - -/* BLE Signalling supported */ -#define L2CAP_FIXED_CHNL_BLE_SIG_BIT (1 << L2CAP_BLE_SIGNALLING_CID) - -/* BLE Security Mgr supported */ -#define L2CAP_FIXED_CHNL_SMP_BIT (1 << L2CAP_SMP_CID) - -/* Security Mgr over BR supported */ -#define L2CAP_FIXED_CHNL_SMP_BR_BIT (1 << L2CAP_SMP_BR_CID) - - - -/* Define the L2CAP configuration result codes -*/ -#define L2CAP_CFG_OK 0 -#define L2CAP_CFG_UNACCEPTABLE_PARAMS 1 -#define L2CAP_CFG_FAILED_NO_REASON 2 -#define L2CAP_CFG_UNKNOWN_OPTIONS 3 -#define L2CAP_CFG_PENDING 4 -#define L2CAP_CFG_FLOW_SPEC_REJECTED 5 - - -/* Define the L2CAP configuration option types -*/ -#define L2CAP_CFG_TYPE_MTU 0x01 -#define L2CAP_CFG_TYPE_FLUSH_TOUT 0x02 -#define L2CAP_CFG_TYPE_QOS 0x03 -#define L2CAP_CFG_TYPE_FCR 0x04 -#define L2CAP_CFG_TYPE_FCS 0x05 -#define L2CAP_CFG_TYPE_EXT_FLOW 0x06 -#define L2CAP_CFG_TYPE_EXT_WIN_SIZE 0x07 - -#define L2CAP_CFG_MTU_OPTION_LEN 2 /* MTU option length */ -#define L2CAP_CFG_FLUSH_OPTION_LEN 2 /* Flush option len */ -#define L2CAP_CFG_QOS_OPTION_LEN 22 /* QOS option length */ -#define L2CAP_CFG_FCR_OPTION_LEN 9 /* FCR option length */ -#define L2CAP_CFG_FCS_OPTION_LEN 1 /* FCR option length */ -#define L2CAP_CFG_EXT_FLOW_OPTION_LEN 16 /* Extended Flow Spec */ -#define L2CAP_CFG_EXT_WIN_SIZE_LEN 2 /* Ext window size length */ -#define L2CAP_CFG_OPTION_OVERHEAD 2 /* Type and length */ - -/* Configuration Cmd/Rsp Flags mask -*/ -#define L2CAP_CFG_FLAGS_MASK_CONT 0x0001 /* Flags mask: Continuation */ - -/* FCS Check Option values -*/ -#define L2CAP_CFG_FCS_BYPASS 0 /* Bypass the FCS in streaming or ERTM modes */ -#define L2CAP_CFG_FCS_USE 1 /* Use the FCS in streaming or ERTM modes [default] */ - -/* Default values for configuration -*/ -#define L2CAP_NO_AUTOMATIC_FLUSH 0xFFFF -#define L2CAP_NO_RETRANSMISSION 0x0001 - -#define L2CAP_DEFAULT_MTU (672) -#define L2CAP_DEFAULT_FLUSH_TO L2CAP_NO_AUTOMATIC_FLUSH -#define L2CAP_DEFAULT_SERV_TYPE 1 -#define L2CAP_DEFAULT_TOKEN_RATE 0 -#define L2CAP_DEFAULT_BUCKET_SIZE 0 -#define L2CAP_DEFAULT_PEAK_BANDWIDTH 0 -#define L2CAP_DEFAULT_LATENCY 0xFFFFFFFF -#define L2CAP_DEFAULT_DELAY 0xFFFFFFFF -#define L2CAP_DEFAULT_FCS L2CAP_CFG_FCS_USE - - -/* Define the L2CAP disconnect result codes -*/ -#define L2CAP_DISC_OK 0 -#define L2CAP_DISC_TIMEOUT 0xEEEE - -/* Define the L2CAP info resp result codes -*/ -#define L2CAP_INFO_RESP_RESULT_SUCCESS 0 -#define L2CAP_INFO_RESP_RESULT_NOT_SUPPORTED 1 - -/* Define the info-type fields of information request & response -*/ -#define L2CAP_CONNLESS_MTU_INFO_TYPE 0x0001 -#define L2CAP_EXTENDED_FEATURES_INFO_TYPE 0x0002 /* Used in Information Req/Response */ -#define L2CAP_FIXED_CHANNELS_INFO_TYPE 0x0003 /* Used in AMP */ - -#define L2CAP_CONNLESS_MTU_INFO_SIZE 2 /* Connectionless MTU size */ -#define L2CAP_EXTENDED_FEATURES_ARRAY_SIZE 4 /* Extended features array size */ -#define L2CAP_FIXED_CHNL_ARRAY_SIZE 8 /* Fixed channel array size */ - -/* Extended features mask bits -*/ -#define L2CAP_EXTFEA_RTRANS 0x00000001 /* Retransmission Mode (Not Supported) */ -#define L2CAP_EXTFEA_FC 0x00000002 /* Flow Control Mode (Not Supported) */ -#define L2CAP_EXTFEA_QOS 0x00000004 -#define L2CAP_EXTFEA_ENH_RETRANS 0x00000008 /* Enhanced retransmission mode */ -#define L2CAP_EXTFEA_STREAM_MODE 0x00000010 /* Streaming Mode */ -#define L2CAP_EXTFEA_NO_CRC 0x00000020 /* Optional FCS (if set No FCS desired) */ -#define L2CAP_EXTFEA_EXT_FLOW_SPEC 0x00000040 /* Extended flow spec */ -#define L2CAP_EXTFEA_FIXED_CHNLS 0x00000080 /* Fixed channels */ -#define L2CAP_EXTFEA_EXT_WINDOW 0x00000100 /* Extended Window Size */ -#define L2CAP_EXTFEA_UCD_RECEPTION 0x00000200 /* Unicast Connectionless Data Reception */ - -/* Mask for locally supported features used in Information Response (default to none) */ -#ifndef L2CAP_EXTFEA_SUPPORTED_MASK -#define L2CAP_EXTFEA_SUPPORTED_MASK 0 -#endif - -/* Mask for LE supported features used in Information Response (default to none) */ -#ifndef L2CAP_BLE_EXTFEA_MASK -#define L2CAP_BLE_EXTFEA_MASK 0 -#endif - -/* Define a value that tells L2CAP to use the default HCI ACL buffer size */ -#define L2CAP_INVALID_ERM_BUF_SIZE 0 - -/* Define a value that tells L2CAP to use the default MPS */ -#define L2CAP_DEFAULT_ERM_MPS 0x0000 - -#define L2CAP_FCR_OVERHEAD 2 /* Control word */ -#define L2CAP_FCS_LEN 2 /* FCS takes 2 bytes */ -#define L2CAP_SDU_LEN_OVERHEAD 2 /* SDU length field is 2 bytes */ -#define L2CAP_SDU_LEN_OFFSET 2 /* SDU length offset is 2 bytes */ -#define L2CAP_EXT_CONTROL_OVERHEAD 4 /* Extended Control Field */ -#define L2CAP_MAX_HEADER_FCS (L2CAP_PKT_OVERHEAD + L2CAP_EXT_CONTROL_OVERHEAD + L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN) -/* length(2), channel(2), control(4), SDU length(2) FCS(2) */ -/* To optimize this, it must be a multiplum of the L2CAP PDU length AND match the 3DH5 air - * including the l2cap headers in each packet - to match the latter - the -5 is added - */ -#define L2CAP_MAX_SDU_LENGTH (8080 + 26 - (L2CAP_MIN_OFFSET + 6)) -#define L2CAP_MAX_BUF_SIZE (10240 + 24) - -/* Part of L2CAP_MIN_OFFSET that is not part of L2CAP -*/ -#define L2CAP_OFFSET_WO_L2HDR (L2CAP_MIN_OFFSET-(L2CAP_PKT_OVERHEAD+L2CAP_FCR_OVERHEAD)) - -/* SAR bits in the control word -*/ -#define L2CAP_FCR_UNSEG_SDU 0x0000 /* Control word to begin with for unsegmented PDU*/ -#define L2CAP_FCR_START_SDU 0x4000 /* ...for Starting PDU of a semented SDU */ -#define L2CAP_FCR_END_SDU 0x8000 /* ...for ending PDU of a segmented SDU */ -#define L2CAP_FCR_CONT_SDU 0xc000 /* ...for continuation PDU of a segmented SDU */ - -/* Supervisory frame types -*/ -#define L2CAP_FCR_SUP_RR 0x0000 /* Supervisory frame - RR */ -#define L2CAP_FCR_SUP_REJ 0x0001 /* Supervisory frame - REJ */ -#define L2CAP_FCR_SUP_RNR 0x0002 /* Supervisory frame - RNR */ -#define L2CAP_FCR_SUP_SREJ 0x0003 /* Supervisory frame - SREJ */ - -#define L2CAP_FCR_SAR_BITS 0xC000 /* Mask to get the SAR bits from control word */ -#define L2CAP_FCR_SAR_BITS_SHIFT 14 /* Bits to shift right to get the SAR bits from ctrl-word */ - -#define L2CAP_FCR_S_FRAME_BIT 0x0001 /* Mask to check if a PDU is S-frame */ -#define L2CAP_FCR_REQ_SEQ_BITS 0x3F00 /* Mask to get the req-seq from control word */ -#define L2CAP_FCR_REQ_SEQ_BITS_SHIFT 8 /* Bits to shift right to get the req-seq from ctrl-word */ -#define L2CAP_FCR_TX_SEQ_BITS 0x007E /* Mask on get the tx-seq from control word */ -#define L2CAP_FCR_TX_SEQ_BITS_SHIFT 1 /* Bits to shift right to get the tx-seq from ctrl-word */ - -#define L2CAP_FCR_F_BIT 0x0080 /* F-bit in the control word (Sup and I frames) */ -#define L2CAP_FCR_P_BIT 0x0010 /* P-bit in the control word (Sup frames only) */ - -#define L2CAP_FCR_F_BIT_SHIFT 7 -#define L2CAP_FCR_P_BIT_SHIFT 4 - -#define L2CAP_FCR_SEG_BITS 0xC000 /* Mask to get the segmentation bits from ctrl-word */ -#define L2CAP_FCR_SUP_SHIFT 2 /* Bits to shift right to get the S-bits from ctrl-word */ -#define L2CAP_FCR_SUP_BITS 0x000C /* Mask to get the supervisory bits from ctrl-word */ - -#define L2CAP_FCR_INIT_CRC 0 /* Initial state of the CRC register */ -#define L2CAP_FCR_SEQ_MODULO 0x3F /* Mask for sequence numbers (range 0 - 63) */ - -#endif diff --git a/tools/sdk/include/bluedroid/list.h b/tools/sdk/include/bluedroid/list.h deleted file mode 100644 index c0abd106e55..00000000000 --- a/tools/sdk/include/bluedroid/list.h +++ /dev/null @@ -1,110 +0,0 @@ -#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); -// 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 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); - -// 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/include/bluedroid/mutex.h b/tools/sdk/include/bluedroid/mutex.h deleted file mode 100644 index 65180a7850a..00000000000 --- a/tools/sdk/include/bluedroid/mutex.h +++ /dev/null @@ -1,53 +0,0 @@ -/****************************************************************************** - * - * 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" - - -#define OSI_MUTEX_MAX_TIMEOUT 0xffffffffUL - -#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/include/bluedroid/oi_assert.h b/tools/sdk/include/bluedroid/oi_assert.h deleted file mode 100644 index 9649f660c14..00000000000 --- a/tools/sdk/include/bluedroid/oi_assert.h +++ /dev/null @@ -1,86 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_ASSERT_H -#define _OI_ASSERT_H -/** @file - This file provides macros and functions for compile-time and run-time assertions. - - When the OI_DEBUG preprocessor value is defined, the macro OI_ASSERT is compiled into - the program, providing for a runtime assertion failure check. - C_ASSERT is a macro that can be used to perform compile time checks. -*/ -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - - -/** \addtogroup Debugging Debugging APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - - -#ifdef OI_DEBUG - -/** The macro OI_ASSERT takes a condition argument. If the asserted condition - does not evaluate to true, the OI_ASSERT macro calls the host-dependent function, - OI_AssertFail(), which reports the failure and generates a runtime error. -*/ -void OI_AssertFail(char *file, int line, char *reason); - - -#define OI_ASSERT(condition) \ - { if (!(condition)) OI_AssertFail(__FILE__, __LINE__, #condition); } - -#define OI_ASSERT_FAIL(msg) \ - { OI_AssertFail(__FILE__, __LINE__, msg); } - -#else - - -#define OI_ASSERT(condition) -#define OI_ASSERT_FAIL(msg) - -#endif - - -/** - C_ASSERT() can be used to perform many compile-time assertions: type sizes, field offsets, etc. - An assertion failure results in compile time error C2118: negative subscript. - Unfortunately, this elegant macro doesn't work with GCC, so it's all commented out - for now. Perhaps later..... -*/ - -#ifndef C_ASSERT -// #define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1] -// #define C_ASSERT(e) -#endif - - -/*****************************************************************************/ -#ifdef __cplusplus -} -#endif - -/**@}*/ - -#endif /* _OI_ASSERT_H */ - diff --git a/tools/sdk/include/bluedroid/oi_bitstream.h b/tools/sdk/include/bluedroid/oi_bitstream.h deleted file mode 100644 index c6ce59b4cef..00000000000 --- a/tools/sdk/include/bluedroid/oi_bitstream.h +++ /dev/null @@ -1,123 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_BITSTREAM_H -#define _OI_BITSTREAM_H - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - - -/** -@file -Function prototypes and macro definitions for manipulating input and output -bitstreams. - -@ingroup codec_internal -*/ - -/** -@addtogroup codec_internal -@{ -*/ - -#include "oi_codec_sbc_private.h" -#include "oi_stddefs.h" - -INLINE void OI_BITSTREAM_ReadInit(OI_BITSTREAM *bs, const OI_BYTE *buffer); - -INLINE void OI_BITSTREAM_WriteInit(OI_BITSTREAM *bs, OI_BYTE *buffer); - -INLINE OI_UINT32 OI_BITSTREAM_ReadUINT(OI_BITSTREAM *bs, OI_UINT bits); - -INLINE OI_UINT8 OI_BITSTREAM_ReadUINT4Aligned(OI_BITSTREAM *bs); - -INLINE OI_UINT8 OI_BITSTREAM_ReadUINT8Aligned(OI_BITSTREAM *bs); - -INLINE void OI_BITSTREAM_WriteUINT(OI_BITSTREAM *bs, - OI_UINT16 value, - OI_UINT bits); - -/* - * Use knowledge that the bitstream is aligned to optimize the write of a byte - */ -PRIVATE void OI_BITSTREAM_WriteUINT8Aligned(OI_BITSTREAM *bs, - OI_UINT8 datum); - -/* - * Use knowledge that the bitstream is aligned to optimize the write pair of nibbles - */ -PRIVATE void OI_BITSTREAM_Write2xUINT4Aligned(OI_BITSTREAM *bs, - OI_UINT8 datum1, - OI_UINT8 datum2); - -/** Internally the bitstream looks ahead in the stream. When - * OI_SBC_ReadScalefactors() goes to temporarily break the abstraction, it will - * need to know where the "logical" pointer is in the stream. - */ -#define OI_BITSTREAM_GetWritePtr(bs) ((bs)->ptr.w - 3) -#define OI_BITSTREAM_GetReadPtr(bs) ((bs)->ptr.r - 3) - -/** This is declared here as a macro because decoder.c breaks the bitsream - * encapsulation for efficiency reasons. - */ -#define OI_BITSTREAM_READUINT(result, bits, ptr, value, bitPtr) \ -do { \ - OI_ASSERT((bits) <= 16); \ - OI_ASSERT((bitPtr) < 16); \ - OI_ASSERT((bitPtr) >= 8); \ - \ - result = (value) << (bitPtr); \ - result >>= 32 - (bits); \ - \ - bitPtr += (bits); \ - while (bitPtr >= 16) { \ - value = ((value) << 8) | *ptr++; \ - bitPtr -= 8; \ - } \ - OI_ASSERT((bits == 0) || (result < (1u << (bits)))); \ -} while (0) - - -#define OI_BITSTREAM_WRITEUINT(ptr, value, bitPtr, datum, bits) \ -do {\ - bitPtr -= bits;\ - value |= datum << bitPtr;\ - \ - while (bitPtr <= 16) {\ - bitPtr += 8;\ - *ptr++ = (OI_UINT8)(value >> 24);\ - value <<= 8;\ - }\ -} while (0) - -#define OI_BITSTREAM_WRITEFLUSH(ptr, value, bitPtr) \ -do {\ - while (bitPtr < 32) {\ - bitPtr += 8;\ - *ptr++ = (OI_UINT8)(value >> 24);\ - value <<= 8;\ - }\ -} while (0) - -/** -@} -*/ - -#endif /* _OI_BITSTREAM_H */ diff --git a/tools/sdk/include/bluedroid/oi_bt_spec.h b/tools/sdk/include/bluedroid/oi_bt_spec.h deleted file mode 100644 index b98a5821dd4..00000000000 --- a/tools/sdk/include/bluedroid/oi_bt_spec.h +++ /dev/null @@ -1,229 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_BT_SPEC_H -#define _OI_BT_SPEC_H -/** - * @file - * - * This file contains common definitions from the Bluetooth specification. - * - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#include "oi_stddefs.h" - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - -/** The maximum number of active slaves in a piconet. */ -#define OI_BT_MAX_ACTIVE_SLAVES 7 - -/** the number of bytes in a Bluetooth device address (BD_ADDR) */ -#define OI_BD_ADDR_BYTE_SIZE 6 - -/** - * 48-bit Bluetooth device address - * - * Because 48-bit integers may not be supported on all platforms, the - * address is defined as an array of bytes. This array is big-endian, - * meaning that - * - array[0] contains bits 47-40, - * - array[1] contains bits 39-32, - * - array[2] contains bits 31-24, - * - array[3] contains bits 23-16, - * - array[4] contains bits 15-8, and - * - array[5] contains bits 7-0. - */ -typedef struct { - OI_UINT8 addr[OI_BD_ADDR_BYTE_SIZE] ; /**< Bluetooth device address represented as an array of 8-bit values */ -} OI_BD_ADDR ; - -/** - * @name Data types for working with UUIDs - * UUIDs are 16 bytes (128 bits). - * - * To avoid having to pass around 128-bit values all the time, 32-bit and 16-bit - * UUIDs are defined, along with a mapping from the shorter versions to the full - * version. - * - * @{ - */ - -/** - * 16-bit representation of a 128-bit UUID - */ -typedef OI_UINT16 OI_UUID16; - -/** - * 32-bit representation of a 128-bit UUID - */ -typedef OI_UINT32 OI_UUID32; - -/** - * number of bytes in a 128 bit UUID - */ -#define OI_BT_UUID128_SIZE 16 - -/** - * number of bytes in IPv6 style addresses - */ -#define OI_BT_IPV6ADDR_SIZE 16 - -/** - * type definition for a 128-bit UUID - * - * To simplify conversion between 128-bit UUIDs and 16-bit and 32-bit UUIDs, - * the most significant 32 bits are stored with the same endian-ness as is - * native on the target (local) device. The remainder of the 128-bit UUID is - * stored as bytes in big-endian order. - */ -typedef struct { - OI_UINT32 ms32bits; /**< most significant 32 bits of 128-bit UUID */ - OI_UINT8 base[OI_BT_UUID128_SIZE - sizeof(OI_UINT32)]; /**< remainder of 128-bit UUID, array of 8-bit values */ -} OI_UUID128; - -/** @} */ - -/** number of bytes in a link key */ -#define OI_BT_LINK_KEY_SIZE 16 - -/** - * type definition for a baseband link key - * - * Because 128-bit integers may not be supported on all platforms, we define - * link keys as an array of bytes. Unlike the Bluetooth device address, - * the link key is stored in little-endian order, meaning that - * - array[0] contains bits 0 - 7, - * - array[1] contains bits 8 - 15, - * - array[2] contains bits 16 - 23, - * - array[3] contains bits 24 - 31, - * - array[4] contains bits 32 - 39, - * - array[5] contains bits 40 - 47, - * - array[6] contains bits 48 - 55, - * - array[7] contains bits 56 - 63, - * - array[8] contains bits 64 - 71, - * - array[9] contains bits 72 - 79, - * - array[10] contains bits 80 - 87, - * - array[11] contains bits 88 - 95, - * - array[12] contains bits 96 - 103, - * - array[13] contains bits 104- 111, - * - array[14] contains bits 112- 119, and - * - array[15] contains bits 120- 127. - */ -typedef struct { - OI_UINT8 key[OI_BT_LINK_KEY_SIZE] ; /**< link key represented as an array of 8-bit values */ -} OI_LINK_KEY ; - - -/** Out-of-band data size - C and R values are 16-bytes each */ -#define OI_BT_OOB_NUM_BYTES 16 - -typedef struct { - OI_UINT8 value[OI_BT_OOB_NUM_BYTES] ; /**< same struct used for C and R values */ -} OI_OOB_DATA ; - - -/** - * link key types - */ -typedef enum { - OI_LINK_KEY_TYPE_COMBO = 0, /**< combination key */ - OI_LINK_KEY_TYPE_LOCAL_UNIT = 1, /**< local unit key */ - OI_LINK_KEY_TYPE_REMOTE_UNIT = 2, /**< remote unit key */ - OI_LINK_KEY_TYPE_DEBUG_COMBO = 3, /**< debug combination key */ - OI_LINK_KEY_TYPE_UNAUTHENTICATED = 4, /**< Unauthenticated */ - OI_LINK_KEY_TYPE_AUTHENTICATED = 5, /**< Authenticated */ - OI_LINK_KEY_TYPE_CHANGED_COMBO = 6 /**< Changed */ - -} OI_BT_LINK_KEY_TYPE ; - - -/** amount of space allocated for a PIN (personal indentification number) in bytes */ -#define OI_BT_PIN_CODE_SIZE 16 - -/** data type for a PIN (PINs are treated as strings, so endianness does not apply.) */ -typedef struct { - OI_UINT8 pin[OI_BT_PIN_CODE_SIZE] ; /**< PIN represented as an array of 8-bit values */ -} OI_PIN_CODE ; - -/** maximum number of SCO connections per device, which is 3 as of version 2.0+EDR - of the Bluetooth specification (see sec 4.3 of vol 2 part B) */ -#define OI_BT_MAX_SCO_CONNECTIONS 3 - -/** data type for clock offset */ -typedef OI_UINT16 OI_BT_CLOCK_OFFSET ; - -/** data type for a LM handle */ -typedef OI_UINT16 OI_HCI_LM_HANDLE; - -/** opaque data type for a SCO or ACL connection handle */ -typedef struct _OI_HCI_CONNECTION *OI_HCI_CONNECTION_HANDLE; - -/** data type for HCI Error Code, as defined in oi_hcispec.h */ -typedef OI_UINT8 OI_HCI_ERROR_CODE ; - -/** - * The Bluetooth device type is indicated by a 24-bit bitfield, represented as a - * 32-bit number in the stack. The bit layout and values for device class are specified - * in the file oi_bt_assigned_nos.h and in the Bluetooth "Assigned Numbers" specification - * at http://www.bluetooth.org/assigned-numbers/. - */ -typedef OI_UINT32 OI_BT_DEVICE_CLASS ; - -#define OI_BT_DEV_CLASS_FORMAT_MASK 0x000003 /**< Bits 0-1 contain format type. */ -#define OI_BT_DEV_CLASS_MINOR_DEVICE_MASK 0x0000FC /**< Bits 2-7 contain minor device class value. */ -#define OI_BT_DEV_CLASS_MAJOR_DEVICE_MASK 0x001F00 /**< Bits 8-12 contain major device class value. */ -#define OI_BT_DEV_CLASS_MAJOR_SERVICE_MASK 0xFFE000 /**< Bits 13-23 contain major service class value. */ - -/** There is currently only one device class format defined, type 00. */ -#define OI_BT_DEV_CLASS_FORMAT_TYPE 00 - -/** Bit 13 in device class indicates limited discoverability mode (GAP v2.0+EDR, section 4.1.2.2) */ -#define OI_BT_DEV_CLASS_LIMITED_DISCO_BIT BIT13 - -/** macro to test validity of the Device Class Format */ -#define OI_BT_VALID_DEVICE_CLASS_FORMAT(class) (OI_BT_DEV_CLASS_FORMAT_TYPE == ((class) & OI_BT_DEV_CLASS_FORMAT_MASK)) - -/** the time between baseband clock ticks, currently 625 microseconds (one slot) */ -#define OI_BT_TICK 625 -/** some macros to convert to/from baseband clock ticks - use no floating point! */ -#define OI_SECONDS_TO_BT_TICKS(secs) ((secs)*1600) -#define OI_BT_TICKS_TO_SECONDS(ticks) ((ticks)/1600) -#define OI_MSECS_TO_BT_TICKS(msecs) (((msecs)*8)/5) -#define OI_BT_TICKS_TO_MSECS(ticks) (((ticks)*5)/8) - -/** EIR byte order */ -#define OI_EIR_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER - - -#ifdef __cplusplus -} -#endif - -/**@}*/ - -/*****************************************************************************/ -#endif /* _OI_BT_SPEC_H */ diff --git a/tools/sdk/include/bluedroid/oi_codec_sbc.h b/tools/sdk/include/bluedroid/oi_codec_sbc.h deleted file mode 100644 index a3f7d875164..00000000000 --- a/tools/sdk/include/bluedroid/oi_codec_sbc.h +++ /dev/null @@ -1,484 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#ifndef _OI_CODEC_SBC_CORE_H -#define _OI_CODEC_SBC_CORE_H - -#ifdef __cplusplus -extern "C" { -#endif - -/** -@file -Declarations of codec functions, data types, and macros. - -@ingroup codec_lib -*/ - -/** -@addtogroup codec_lib -@{ -*/ - -/* Non-BM3 users of of the codec must include oi_codec_sbc_bm3defs.h prior to - * including this file, or else these includes will fail because the BM3 SDK is - * not in the include path */ -#ifndef _OI_CODEC_SBC_BM3DEFS_H -#include "oi_stddefs.h" -#include "oi_status.h" -#endif - -#include - -#define SBC_MAX_CHANNELS 2 -#define SBC_MAX_BANDS 8 -#define SBC_MAX_BLOCKS 16 -#define SBC_MIN_BITPOOL 2 /**< Minimum size of the bit allocation pool used to encode the stream */ -#define SBC_MAX_BITPOOL 250 /**< Maximum size of the bit allocation pool used to encode the stream */ -#define SBC_MAX_ONE_CHANNEL_BPS 320000 -#define SBC_MAX_TWO_CHANNEL_BPS 512000 - - -#define SBC_WBS_BITRATE 62000 -#define SBC_WBS_BITPOOL 27 -#define SBC_WBS_NROF_BLOCKS 16 -#define SBC_WBS_FRAME_LEN 62 -#define SBC_WBS_SAMPLES_PER_FRAME 128 - - -#define SBC_HEADER_LEN 4 -#define SBC_MAX_FRAME_LEN (SBC_HEADER_LEN + \ - ((SBC_MAX_BANDS * SBC_MAX_CHANNELS / 2) + \ - (SBC_MAX_BANDS + SBC_MAX_BLOCKS * SBC_MAX_BITPOOL + 7)/8)) -#define SBC_MAX_SAMPLES_PER_FRAME (SBC_MAX_BANDS * SBC_MAX_BLOCKS) - -#define SBC_MAX_SCALEFACTOR_BYTES ((4*(SBC_MAX_CHANNELS * SBC_MAX_BANDS) + 7)/8) - -#define OI_SBC_SYNCWORD 0x9c -#define OI_SBC_ENHANCED_SYNCWORD 0x9d - -/**@name Sampling frequencies */ -/**@{*/ -#define SBC_FREQ_16000 0 /**< The sampling frequency is 16 kHz. One possible value for the @a frequency parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_FREQ_32000 1 /**< The sampling frequency is 32 kHz. One possible value for the @a frequency parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_FREQ_44100 2 /**< The sampling frequency is 44.1 kHz. One possible value for the @a frequency parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_FREQ_48000 3 /**< The sampling frequency is 48 kHz. One possible value for the @a frequency parameter of OI_CODEC_SBC_EncoderConfigure() */ -/**@}*/ - -/**@name Channel modes */ -/**@{*/ -#define SBC_MONO 0 /**< The mode of the encoded channel is mono. One possible value for the @a mode parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_DUAL_CHANNEL 1 /**< The mode of the encoded channel is dual-channel. One possible value for the @a mode parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_STEREO 2 /**< The mode of the encoded channel is stereo. One possible value for the @a mode parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_JOINT_STEREO 3 /**< The mode of the encoded channel is joint stereo. One possible value for the @a mode parameter of OI_CODEC_SBC_EncoderConfigure() */ -/**@}*/ - -/**@name Subbands */ -/**@{*/ -#define SBC_SUBBANDS_4 0 /**< The encoded stream has 4 subbands. One possible value for the @a subbands parameter of OI_CODEC_SBC_EncoderConfigure()*/ -#define SBC_SUBBANDS_8 1 /**< The encoded stream has 8 subbands. One possible value for the @a subbands parameter of OI_CODEC_SBC_EncoderConfigure() */ -/**@}*/ - -/**@name Block lengths */ -/**@{*/ -#define SBC_BLOCKS_4 0 /**< A block size of 4 blocks was used to encode the stream. One possible value for the @a blocks parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_BLOCKS_8 1 /**< A block size of 8 blocks was used to encode the stream is. One possible value for the @a blocks parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_BLOCKS_12 2 /**< A block size of 12 blocks was used to encode the stream. One possible value for the @a blocks parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_BLOCKS_16 3 /**< A block size of 16 blocks was used to encode the stream. One possible value for the @a blocks parameter of OI_CODEC_SBC_EncoderConfigure() */ -/**@}*/ - -/**@name Bit allocation methods */ -/**@{*/ -#define SBC_LOUDNESS 0 /**< The bit allocation method. One possible value for the @a loudness parameter of OI_CODEC_SBC_EncoderConfigure() */ -#define SBC_SNR 1 /**< The bit allocation method. One possible value for the @a loudness parameter of OI_CODEC_SBC_EncoderConfigure() */ -/**@}*/ - -/** -@} - -@addtogroup codec_internal -@{ -*/ - -typedef OI_INT16 SBC_BUFFER_T; - - -/** Used internally. */ -typedef struct { - OI_UINT16 frequency; /**< The sampling frequency. Input parameter. */ - OI_UINT8 freqIndex; - - OI_UINT8 nrof_blocks; /**< The block size used to encode the stream. Input parameter. */ - OI_UINT8 blocks; - - - OI_UINT8 nrof_subbands; /**< The number of subbands of the encoded stream. Input parameter. */ - OI_UINT8 subbands; - - OI_UINT8 mode; /**< The mode of the encoded channel. Input parameter. */ - OI_UINT8 nrof_channels; /**< The number of channels of the encoded stream. */ - - OI_UINT8 alloc; /**< The bit allocation method. Input parameter. */ - OI_UINT8 bitpool; /**< Size of the bit allocation pool used to encode the stream. Input parameter. */ - OI_UINT8 crc; /**< Parity check byte used for error detection. */ - OI_UINT8 join; /**< Whether joint stereo has been used. */ - OI_UINT8 enhanced; - OI_UINT8 min_bitpool; /**< This value is only used when encoding. SBC_MAX_BITPOOL if variable - bitpools are disallowed, otherwise the minimum bitpool size that will - be used by the bit allocator. */ - - OI_UINT8 cachedInfo; /**< Information about the previous frame */ -} OI_CODEC_SBC_FRAME_INFO; - -/** Used internally. */ -typedef struct { - const OI_CHAR *codecInfo; - OI_CODEC_SBC_FRAME_INFO frameInfo; - OI_INT8 scale_factor[SBC_MAX_CHANNELS * SBC_MAX_BANDS]; - OI_UINT32 frameCount; - OI_INT32 *subdata; - - SBC_BUFFER_T *filterBuffer[SBC_MAX_CHANNELS]; - OI_INT32 filterBufferLen; - OI_UINT filterBufferOffset; - - union { - OI_UINT8 uint8[SBC_MAX_CHANNELS * SBC_MAX_BANDS]; - OI_UINT32 uint32[SBC_MAX_CHANNELS * SBC_MAX_BANDS / 4]; - } bits; - OI_UINT8 maxBitneed; /**< Running maximum bitneed */ - OI_BYTE formatByte; - OI_UINT8 pcmStride; - OI_UINT8 maxChannels; -} OI_CODEC_SBC_COMMON_CONTEXT; - - -/* - * A smaller value reduces RAM usage at the expense of increased CPU usage. Values in the range - * 27..50 are recommended, beyond 50 there is a diminishing return on reduced CPU usage. - */ -#define SBC_CODEC_MIN_FILTER_BUFFERS 16 -#define SBC_CODEC_FAST_FILTER_BUFFERS 27 - -/* Expands to the number of OI_UINT32s needed to ensure enough memory to encode - * or decode streams of numChannels channels, using numBuffers buffers. - * Example: - * OI_UINT32 decoderData[CODEC_DATA_WORDS(SBC_MAX_CHANNELS, SBC_DECODER_FAST_SYNTHESIS_BUFFERS)]; - * */ -#define CODEC_DATA_WORDS(numChannels, numBuffers) \ - ((\ - (sizeof(OI_INT32) * SBC_MAX_BLOCKS * numChannels * SBC_MAX_BANDS) \ - + (sizeof(SBC_BUFFER_T) * SBC_MAX_CHANNELS * SBC_MAX_BANDS * numBuffers) \ - + (sizeof (OI_UINT32) - 1) \ - ) / sizeof(OI_UINT32)) - -/** Opaque parameter to decoding functions; maintains decoder context. */ -typedef struct { - OI_CODEC_SBC_COMMON_CONTEXT common; - OI_UINT8 limitFrameFormat; /* Boolean, set by OI_CODEC_SBC_DecoderLimit() */ - OI_UINT8 restrictSubbands; - OI_UINT8 enhancedEnabled; - OI_UINT8 bufferedBlocks; -} OI_CODEC_SBC_DECODER_CONTEXT; - -typedef struct { - OI_UINT32 data[CODEC_DATA_WORDS(1, SBC_CODEC_FAST_FILTER_BUFFERS)]; -} OI_CODEC_SBC_CODEC_DATA_MONO; - -typedef struct { - OI_UINT32 data[CODEC_DATA_WORDS(2, SBC_CODEC_FAST_FILTER_BUFFERS)]; -} OI_CODEC_SBC_CODEC_DATA_STEREO; - -/** -@} - -@addtogroup codec_lib -@{ -*/ - -/** - * This function resets the decoder. The context must be reset when - * changing streams, or if the following stream parameters change: - * number of subbands, stereo mode, or frequency. - * - * @param context Pointer to the decoder context structure to be reset. - * - * @param enhanced If true, enhanced SBC operation is enabled. If enabled, - * the codec will recognize the alternative syncword for - * decoding an enhanced SBC stream. Enhancements should not - * be enabled unless the stream is known to be generated - * by an enhanced encoder, or there is a small possibility - * for decoding glitches if synchronization were to be lost. - */ -OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context, - OI_UINT32 *decoderData, - OI_UINT32 decoderDataBytes, - OI_UINT8 maxChannels, - OI_UINT8 pcmStride, - OI_BOOL enhanced); - -/** - * This function restricts the kind of SBC frames that the Decoder will - * process. Its use is optional. If used, it must be called after - * calling OI_CODEC_SBC_DecoderReset(). After it is called, any calls - * to OI_CODEC_SBC_DecodeFrame() with SBC frames that do not conform - * to the Subband and Enhanced SBC setting will be rejected with an - * OI_STATUS_INVALID_PARAMETERS return. - * - * @param context Pointer to the decoder context structure to be limited. - * - * @param enhanced If true, all frames passed to the decoder must be - * Enhanced SBC frames. If false, all frames must be - * standard SBC frames. - * - * @param subbands May be set to SBC_SUBBANDS_4 or SBC_SUBBANDS_8. All - * frames passed to the decoder must be encoded with - * the requested number of subbands. - * - */ -OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT *context, - OI_BOOL enhanced, - OI_UINT8 subbands); - -/** - * This function sets the decoder parameters for a raw decode where the decoder parameters are not - * available in the sbc data stream. OI_CODEC_SBC_DecoderReset must be called - * prior to calling this function. - * - * @param context Decoder context structure. This must be the context must be - * used each time a frame is decoded. - * - * @param enhanced Set to TRUE to enable Qualcomm proprietary - * quality enhancements. - * - * @param frequency One of SBC_FREQ_16000, SBC_FREQ_32000, SBC_FREQ_44100, - * SBC_FREQ_48000 - * - * @param mode One of SBC_MONO, SBC_DUAL_CHANNEL, SBC_STEREO, - * SBC_JOINT_STEREO - * - * @param subbands One of SBC_SUBBANDS_4, SBC_SUBBANDS_8 - * - * @param blocks One of SBC_BLOCKS_4, SBC_BLOCKS_8, SBC_BLOCKS_12, - * SBC_BLOCKS_16 - * - * @param alloc One of SBC_LOUDNESS, SBC_SNR - * - * @param maxBitpool The maximum bitpool size for this context - */ -OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw(OI_CODEC_SBC_DECODER_CONTEXT *context, - OI_BOOL enhanced, - OI_UINT8 frequency, - OI_UINT8 mode, - OI_UINT8 subbands, - OI_UINT8 blocks, - OI_UINT8 alloc, - OI_UINT8 maxBitpool); - -/** - * Decode one SBC frame. The frame has no header bytes. The context must have been previously - * initialized by calling OI_CODEC_SBC_DecoderConfigureRaw(). - * - * @param context Pointer to a decoder context structure. The same context - * must be used each time when decoding from the same stream. - * - * @param bitpool The actual bitpool size for this frame. Must be <= the maxbitpool specified - * in the call to OI_CODEC_SBC_DecoderConfigureRaw(), - * - * @param frameData Address of a pointer to the SBC data to decode. This - * value will be updated to point to the next frame after - * successful decoding. - * - * @param frameBytes Pointer to a UINT32 containing the number of available - * bytes of frame data. This value will be updated to reflect - * the number of bytes remaining after a decoding operation. - * - * @param pcmData Address of an array of OI_INT16 pairs, which will be - * populated with the decoded audio data. This address - * is not updated. - * - * @param pcmBytes Pointer to a UINT32 in/out parameter. On input, it - * should contain the number of bytes available for pcm - * data. On output, it will contain the number of bytes - * written. Note that this differs from the semantics of - * frameBytes. - */ -OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context, - OI_UINT8 bitpool, - const OI_BYTE **frameData, - OI_UINT32 *frameBytes, - OI_INT16 *pcmData, - OI_UINT32 *pcmBytes); - -/** - * Decode one SBC frame. - * - * @param context Pointer to a decoder context structure. The same context - * must be used each time when decoding from the same stream. - * - * @param frameData Address of a pointer to the SBC data to decode. This - * value will be updated to point to the next frame after - * successful decoding. - * - * @param frameBytes Pointer to a UINT32 containing the number of available - * bytes of frame data. This value will be updated to reflect - * the number of bytes remaining after a decoding operation. - * - * @param pcmData Address of an array of OI_INT16 pairs, which will be - * populated with the decoded audio data. This address - * is not updated. - * - * @param pcmBytes Pointer to a UINT32 in/out parameter. On input, it - * should contain the number of bytes available for pcm - * data. On output, it will contain the number of bytes - * written. Note that this differs from the semantics of - * frameBytes. - */ -OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, - const OI_BYTE **frameData, - OI_UINT32 *frameBytes, - OI_INT16 *pcmData, - OI_UINT32 *pcmBytes); - -/** - * Calculate the number of SBC frames but don't decode. CRC's are not checked, - * but the Sync word is found prior to count calculation. - * - * @param frameData Pointer to the SBC data. - * - * @param frameBytes Number of bytes avaiable in the frameData buffer - * - */ -OI_UINT8 OI_CODEC_SBC_FrameCount(OI_BYTE *frameData, - OI_UINT32 frameBytes); - -/** - * Analyze an SBC frame but don't do the decode. - * - * @param context Pointer to a decoder context structure. The same context - * must be used each time when decoding from the same stream. - * - * @param frameData Address of a pointer to the SBC data to decode. This - * value will be updated to point to the next frame after - * successful decoding. - * - * @param frameBytes Pointer to a UINT32 containing the number of available - * bytes of frame data. This value will be updated to reflect - * the number of bytes remaining after a decoding operation. - * - */ -OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, - const OI_BYTE **frameData, - OI_UINT32 *frameBytes); - -/* Common functions */ - -/** - Calculate the frame length. - - @param frame The frame whose length to calculate - - @return the length of an individual encoded frame in - bytes - */ -OI_UINT16 OI_CODEC_SBC_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame); - - -/** - * Calculate the maximum bitpool size that fits within a given frame length. - * - * @param frame The frame to calculate the bitpool size for - * @param frameLen The frame length to fit the bitpool to - * - * @return the maximum bitpool that will fit in the specified frame length - */ -OI_UINT16 OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO *frame, - OI_UINT16 frameLen); - -/** - Calculate the bit rate. - - @param frame The frame whose bit rate to calculate - - @return the approximate bit rate in bits per second, - assuming that stream parameters are constant - */ -OI_UINT32 OI_CODEC_SBC_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame); - -/** - Calculate decoded audio data length for one frame. - - @param frame The frame whose audio data length to calculate - - @return length of decoded audio data for a - single frame, in bytes - */ -OI_UINT16 OI_CODEC_SBC_CalculatePcmBytes(OI_CODEC_SBC_COMMON_CONTEXT *common); - -/** - * Get the codec version text. - * - * @return pointer to text string containing codec version text - * - */ -OI_CHAR *OI_CODEC_Version(void); - - -/** -@} - -@addtogroup codec_internal -@{ -*/ - -extern const OI_CHAR *const OI_CODEC_SBC_FreqText[]; -extern const OI_CHAR *const OI_CODEC_SBC_ModeText[]; -extern const OI_CHAR *const OI_CODEC_SBC_SubbandsText[]; -extern const OI_CHAR *const OI_CODEC_SBC_BlocksText[]; -extern const OI_CHAR *const OI_CODEC_SBC_AllocText[]; - -/** -@} - -@addtogroup codec_lib -@{ -*/ - -#ifdef OI_DEBUG -void OI_CODEC_SBC_DumpConfig(OI_CODEC_SBC_FRAME_INFO *frameInfo); -#else -#define OI_CODEC_SBC_DumpConfig(f) -#endif - -/** -@} -*/ - -#ifdef __cplusplus -} -#endif - - -#endif /* _OI_CODEC_SBC_CORE_H */ - - diff --git a/tools/sdk/include/bluedroid/oi_codec_sbc_private.h b/tools/sdk/include/bluedroid/oi_codec_sbc_private.h deleted file mode 100644 index 4e3897614ff..00000000000 --- a/tools/sdk/include/bluedroid/oi_codec_sbc_private.h +++ /dev/null @@ -1,229 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_CODEC_SBC_PRIVATE_H -#define _OI_CODEC_SBC_PRIVATE_H - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -/** -@file -Function prototypes and macro definitions used internally by the codec. - -@ingroup codec_internal -*/ - -/** -@addtogroup codec_internal -@{ -*/ - -#ifdef USE_RESTRICT_KEYWORD -#define RESTRICT restrict -#else -#define RESTRICT -#endif - -#ifdef CODEC_DEBUG -#include -#define ERROR(x) do { printf x; printf("\n"); } while (0) -#else -#define ERROR(x) -#endif - -#ifdef TRACE_EXECUTION -#define TRACE(x) do { printf x; printf("\n"); } while (0) -#else -#define TRACE(x) -#endif - -#ifndef PRIVATE -#define PRIVATE -#endif - -#ifndef INLINE -#define INLINE -#endif - -#include "oi_assert.h" -#include "oi_codec_sbc.h" - -#ifndef OI_SBC_SYNCWORD -#define OI_SBC_SYNCWORD 0x9c -#endif - -#ifndef DIVIDE -#define DIVIDE(a, b) ((a) / (b)) -#endif - -typedef union { - OI_UINT8 uint8[SBC_MAX_BANDS]; - OI_UINT32 uint32[SBC_MAX_BANDS / 4]; -} BITNEED_UNION1; - -typedef union { - OI_UINT8 uint8[2 * SBC_MAX_BANDS]; - OI_UINT32 uint32[2 * SBC_MAX_BANDS / 4]; -} BITNEED_UNION2; - -static const OI_UINT16 freq_values[] = { 16000, 32000, 44100, 48000 }; -static const OI_UINT8 block_values[] = { 4, 8, 12, 16 }; -static const OI_UINT8 channel_values[] = { 1, 2, 2, 2 }; -static const OI_UINT8 band_values[] = { 4, 8 }; - - -#define TEST_MODE_SENTINEL "OINA" -#define TEST_MODE_SENTINEL_LENGTH 4 - -/** Used internally. */ -typedef struct { - union { - const OI_UINT8 *r; - OI_UINT8 *w; - } ptr; - OI_UINT32 value; - OI_UINT bitPtr; -} OI_BITSTREAM; - - -#define VALID_INT16(x) (((x) >= OI_INT16_MIN) && ((x) <= OI_INT16_MAX)) -#define VALID_INT32(x) (((x) >= OI_INT32_MIN) && ((x) <= OI_INT32_MAX)) - -#define DCTII_8_SHIFT_IN 0 -#define DCTII_8_SHIFT_OUT 16-DCTII_8_SHIFT_IN - -#define DCTII_8_SHIFT_0 (DCTII_8_SHIFT_OUT) -#define DCTII_8_SHIFT_1 (DCTII_8_SHIFT_OUT) -#define DCTII_8_SHIFT_2 (DCTII_8_SHIFT_OUT) -#define DCTII_8_SHIFT_3 (DCTII_8_SHIFT_OUT) -#define DCTII_8_SHIFT_4 (DCTII_8_SHIFT_OUT) -#define DCTII_8_SHIFT_5 (DCTII_8_SHIFT_OUT) -#define DCTII_8_SHIFT_6 (DCTII_8_SHIFT_OUT-1) -#define DCTII_8_SHIFT_7 (DCTII_8_SHIFT_OUT-2) - -#define DCT_SHIFT 15 - -#define DCTIII_4_SHIFT_IN 2 -#define DCTIII_4_SHIFT_OUT 15 - -#define DCTIII_8_SHIFT_IN 3 -#define DCTIII_8_SHIFT_OUT 14 - -OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common, - OI_UINT8 *bitneeds, - OI_UINT ch, - OI_UINT *preferredBitpool); - -void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common, - BITNEED_UNION1 *bitneeds, - OI_UINT ch, - OI_UINT bitcount); - - -OI_INT adjustToFitBitpool(const OI_UINT bitpool, - OI_UINT32 *bitneeds, - const OI_UINT subbands, - OI_UINT bitcount, - OI_UINT *excess); - -INLINE OI_INT allocAdjustedBits(OI_UINT8 *dest, - OI_INT bits, - OI_INT excess); - -INLINE OI_INT allocExcessBits(OI_UINT8 *dest, - OI_INT excess); - -PRIVATE OI_UINT32 internal_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame); - -PRIVATE OI_UINT16 internal_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame); - -void monoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common); - -typedef void (*BIT_ALLOC)(OI_CODEC_SBC_COMMON_CONTEXT *common); - -PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context, - OI_UINT8 bitpool, - const OI_BYTE **frameData, - OI_UINT32 *frameBytes, - OI_INT16 *pcmData, - OI_UINT32 *pcmBytes); - -INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context, - OI_UINT32 *decoderData, - OI_UINT32 decoderDataBytes, - OI_BYTE maxChannels, - OI_BYTE pcmStride, - OI_BOOL enhanced); - -INLINE OI_UINT16 OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO *frame, OI_UINT *headerLen_); - -PRIVATE OI_UINT32 OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO *frame); - -PRIVATE void OI_SBC_ComputeBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *frame); -PRIVATE OI_UINT8 OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO *frame, OI_BYTE const *data); - -/* Transform functions */ -PRIVATE void shift_buffer(SBC_BUFFER_T *dest, SBC_BUFFER_T *src, OI_UINT wordCount); -PRIVATE void cosineModulateSynth4(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in); -PRIVATE void SynthWindow40_int32_int32_symmetry_with_sum(OI_INT16 *pcm, SBC_BUFFER_T buffer[80], OI_UINT strideShift); - -INLINE void dct3_4(OI_INT32 *RESTRICT out, OI_INT32 const *RESTRICT in); -PRIVATE void analyze4_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 40], - OI_INT16 *pcm, - OI_UINT strideShift, - OI_INT32 subband[4]); - -INLINE void dct3_8(OI_INT32 *RESTRICT out, OI_INT32 const *RESTRICT in); - -PRIVATE void analyze8_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 80], - OI_INT16 *pcm, - OI_UINT strideShift, - OI_INT32 subband[8]); - -#ifdef SBC_ENHANCED -PRIVATE void analyze8_enhanced_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 112], - OI_INT16 *pcm, - OI_UINT strideShift, - OI_INT32 subband[8]); -#endif - -/* Decoder functions */ - -INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT *common, const OI_BYTE *data); -PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT *common, const OI_BYTE *b, OI_BITSTREAM *bs); -PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT *common, OI_BITSTREAM *ob); -PRIVATE void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT *common, OI_BITSTREAM *global_bs); -PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT start_block, OI_UINT nrof_blocks); -INLINE OI_INT32 OI_SBC_Dequant(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits); -PRIVATE OI_BOOL OI_SBC_ExamineCommandPacket(OI_CODEC_SBC_DECODER_CONTEXT *context, const OI_BYTE *data, OI_UINT32 len); -PRIVATE void OI_SBC_GenerateTestSignal(OI_INT16 pcmData[][2], OI_UINT32 sampleCount); - -PRIVATE void OI_SBC_ExpandFrameFields(OI_CODEC_SBC_FRAME_INFO *frame); -PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT *common, - OI_UINT32 *codecDataAligned, - OI_UINT32 codecDataBytes, - OI_UINT8 maxChannels, - OI_UINT8 pcmStride); -/** -@} -*/ - -#endif /* _OI_CODEC_SBC_PRIVATE_H */ - diff --git a/tools/sdk/include/bluedroid/oi_common.h b/tools/sdk/include/bluedroid/oi_common.h deleted file mode 100644 index c4169f932c6..00000000000 --- a/tools/sdk/include/bluedroid/oi_common.h +++ /dev/null @@ -1,43 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_COMMON_H -#define _OI_COMMON_H -/** - * @file - * - * This file is used to group commonly used BLUEmagic 3.0 software - * header files. - * - * This file should be included in application source code along with the header - * files for the specific modules of the protocol stack being used. - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#include "oi_bt_spec.h" -#include "oi_stddefs.h" -#include "oi_status.h" -#include "oi_time.h" -#include "oi_osinterface.h" - - -/*****************************************************************************/ -#endif /* _OI_COMMON_H */ diff --git a/tools/sdk/include/bluedroid/oi_cpu_dep.h b/tools/sdk/include/bluedroid/oi_cpu_dep.h deleted file mode 100644 index dfa52c16b5e..00000000000 --- a/tools/sdk/include/bluedroid/oi_cpu_dep.h +++ /dev/null @@ -1,505 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_CPU_DEP_H -#define _OI_CPU_DEP_H -/** - * @file - * This file contains definitions for characteristics of the target CPU and - * compiler, including primitive data types and endianness. - * - * This file defines the byte order and primitive data types for various - * CPU families. The preprocessor symbol 'CPU' must be defined to be an - * appropriate value or this header will generate a compile-time error. - * - * @note The documentation for this header file uses the x86 family of processors - * as an illustrative example for CPU/compiler-dependent data type definitions. - * Go to the source code of this header file to see the details of primitive type - * definitions for each platform. - * - * Additional information is available in the @ref data_types_docpage section. - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -/** @name Definitions indicating family of target OI_CPU_TYPE - * @{ - */ - -#define OI_CPU_X86 1 /**< x86 processor family */ -#define OI_CPU_ARM 2 /**< ARM processor family. - @deprecated Use #OI_CPU_ARM7_LEND or - #OI_CPU_ARM7_BEND. */ -#define OI_CPU_ARC 3 /**< ARC processor family. - @deprecated Use #OI_CPU_ARC_LEND or - #OI_CPU_ARC_BEND. */ -#define OI_CPU_SH3 4 /**< Hitachi SH-3 processor family */ -#define OI_CPU_H8 5 /**< Hitachi H8 processor family */ -#define OI_CPU_MIPS 6 /**< MIPS processor family */ -#define OI_CPU_SPARC 7 /**< SPARC processor family */ -#define OI_CPU_M68000 8 /**< Motorola M68000 processor family */ -#define OI_CPU_PPC 9 /**< PowerPC (PPC) processor family */ -#define OI_CPU_SH4_7750 10 /**< Hitachi SH7750 series in SH-4 processor family */ -#define OI_CPU_SH2 11 /**< Hitachi SH-2 processor family */ -#define OI_CPU_ARM7_LEND 12 /**< ARM7, little-endian */ -#define OI_CPU_ARM7_BEND 13 /**< ARM7, big-endian */ -#define OI_CPU_GDM1202 14 /**< GCT GDM1202 */ -#define OI_CPU_ARC_LEND 15 /**< ARC processor family, little-endian */ -#define OI_CPU_ARC_BEND 16 /**< ARC processor family, big-endian */ -#define OI_CPU_M30833F 17 /**< Mitsubishi M308 processor family */ -#define OI_CPU_CR16C 18 /**< National Semiconductor 16 bit processor family */ -#define OI_CPU_M64111 19 /**< Renesas M64111 processor (M32R family) */ -#define OI_CPU_ARMV5_LEND 20 //*< ARM5, little-endian */ - -#define OI_CPU_TYPE 12 - -#ifndef OI_CPU_TYPE -#error "OI_CPU_TYPE type not defined" -#endif - -/**@}*/ - - -/** @name Definitions indicating byte-wise endianness of target CPU - * @{ - */ - -#define OI_BIG_ENDIAN_BYTE_ORDER 0 /**< Multiple-byte values are stored in memory beginning with the most significant byte at the lowest address. */ -#define OI_LITTLE_ENDIAN_BYTE_ORDER 1 /**< Multiple-byte values are stored in memory beginning with the least significant byte at the lowest address. */ - -/**@}*/ - - -/** @name CPU/compiler-independent primitive data type definitions - * @{ - */ - -typedef int OI_BOOL; /**< Boolean values use native integer data type for target CPU. */ -typedef int OI_INT; /**< Integer values use native integer data type for target CPU. */ -typedef unsigned int OI_UINT; /**< Unsigned integer values use native unsigned integer data type for target CPU. */ -typedef unsigned char OI_BYTE; /**< Raw bytes type uses native character data type for target CPU. */ - -/**@}*/ - - - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_X86 - -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER /**< x86 platform byte ordering is little-endian */ - -/** @name CPU/compiler-dependent primitive data type definitions for x86 processor family - * @{ - */ -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for x86 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for x86 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for x86 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for x86 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for x86 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for x86 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_ARM -/* This CPU type is deprecated (removed from use). Instead, use OI_CPU_ARM7_LEND or OI_CPU_ARM7_BEND for - little-endian or big-endian configurations of the ARM7, respectively. */ -#error OI_CPU_ARM is deprecated -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_ARC -/* This CPU type is deprecated (removed from use). Instead, use OI_CPU_ARC_LEND or OI_CPU_ARC_BEND for - little-endian or big-endian configurations of the ARC, respectively. */ -#error OI_CPU_ARC is deprecated -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_SH3 -/* The Hitachi SH C compiler defines _LIT or _BIG, depending on the endianness - specified to the compiler on the command line. */ -#if defined(_LIT) -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER /**< If _LIT is defined, SH-3 platform byte ordering is little-endian. */ -#elif defined(_BIG) -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER /**< If _BIG is defined, SH-3 platform byte ordering is big-endian. */ -#else -#error SH compiler endianness undefined -#endif - -/** @name CPU/compiler-dependent primitive data type definitions for SH-3 processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for SH-3 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for SH-3 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for SH-3 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for SH-3 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for SH-3 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for SH-3 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_SH2 - -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER /**< SH-2 platform byte ordering is big-endian. */ - -/** @name CPU/compiler-dependent primitive data type definitions for SH-2 processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for SH-2 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for SH-2 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for SH-2 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for SH-2 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for SH-2 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for SH-2 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_H8 -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER -#error basic types not defined -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_MIPS -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER -/** @name CPU/compiler-dependent primitive data type definitions for MIPS processor family - * @{ - */ -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for ARM7 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for ARM7 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for ARM7 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for ARM7 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARM7 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for ARM7 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_SPARC -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER -#error basic types not defined -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_M68000 -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER /**< M68000 platform byte ordering is big-endian. */ - -/** @name CPU/compiler-dependent primitive data type definitions for M68000 processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for M68000 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for M68000 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for M68000 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for M68000 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for M68000 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for M68000 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_PPC -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER - - -/** @name CPU/compiler-dependent primitive data type definitions for PPC 8XX processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for PPC8XX processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for PPC8XX processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for PPC8XX processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for PPC8XX processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for PPC8XX processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for PPC8XX processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_SH4_7750 -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER /**< SH7750 platform byte ordering is big-endian. */ - -/** @name CPU/compiler-dependent primitive data type definitions for SH7750 processor series of the SH-4 processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for SH7750 SH-4 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for SH7750 SH-4 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for SH7750 SH-4 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for SH7750 SH-4 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for SH7750 SH-4 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for SH7750 SH-4 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_ARM7_LEND -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER - -/** @name little-endian CPU/compiler-dependent primitive data type definitions for the ARM7 processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for ARM7 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for ARM7 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for ARM7 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for ARM7 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARM7 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for ARM7 processor. */ - -typedef void *OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_ARM7_BEND -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER -/** @name big-endian CPU/compiler-dependent primitive data type definitions for the ARM7 processor family - * @{ - */ -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for ARM7 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for ARM7 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for ARM7 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for ARM7 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARM7 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for ARM7 processor. */ - -typedef void *OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_GDM1202 -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER - -typedef signed char OI_INT8; /**< 8-bit signed integer. */ -typedef signed short OI_INT16; /**< 16-bit signed integer. */ -typedef signed long OI_INT32; /**< 32-bit signed integer. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_ARC_LEND - -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER - -/** @name CPU/compiler-dependent primitive data type definitions for ARC processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for ARC processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for ARC processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for ARC processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for ARC processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARC processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for ARC processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_ARC_BEND - -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER - -/** @name CPU/compiler-dependent primitive data type definitions for ARC processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for ARC processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for ARC processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for ARC processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for ARC processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARC processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for ARC processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_M30833F - -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER - -/** @name CPU/compiler-dependent primitive data type definitions for Mitsubishi M308 processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for M308 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for M308 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for M308 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for M308 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for M308 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for M308 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_CR16C - -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER - -/** @name CPU/compiler-dependent primitive data type definitions for National Semicnductor processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for CR16C processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for CR16C processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for CR16C processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for CR16C processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for CR16C processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for CR16C processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_M64111 - -#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER - -/** @name CPU/compiler-dependent primitive data type definitions for Renesas M32R processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for M64111 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for M64111 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for M64111 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for M64111 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for M64111 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for M64111 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ -#endif - -/*********************************************************************************/ - -#if OI_CPU_TYPE==OI_CPU_ARMV5_LEND -#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER - -/** @name little-endian CPU/compiler-dependent primitive data type definitions for the ARM7 processor family - * @{ - */ - -typedef signed char OI_INT8; /**< 8-bit signed integer values use native signed character data type for ARM7 processor. */ -typedef signed short OI_INT16; /**< 16-bit signed integer values use native signed short integer data type for ARM7 processor. */ -typedef signed long OI_INT32; /**< 32-bit signed integer values use native signed long integer data type for ARM7 processor. */ -typedef unsigned char OI_UINT8; /**< 8-bit unsigned integer values use native unsigned character data type for ARM7 processor. */ -typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARM7 processor. */ -typedef unsigned long OI_UINT32; /**< 32-bit unsigned integer values use native unsigned long integer data type for ARM7 processor. */ - -typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */ - -/**@}*/ - -#endif - -/*********************************************************************************/ - - -#ifndef OI_CPU_BYTE_ORDER -#error "Byte order (endian-ness) not defined" -#endif - - -/**@}*/ - -#ifdef __cplusplus -} -#endif - -/*********************************************************************************/ -#endif /* _OI_CPU_DEP_H */ diff --git a/tools/sdk/include/bluedroid/oi_modules.h b/tools/sdk/include/bluedroid/oi_modules.h deleted file mode 100644 index 7784212ad25..00000000000 --- a/tools/sdk/include/bluedroid/oi_modules.h +++ /dev/null @@ -1,171 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_MODULES_H -#define _OI_MODULES_H -/** - * @file - * - * Enumeration type defining the inidivual stack components. - * - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - - -/** - * This enumeration lists constants for referencing the components of - * the BLUEmagic 3.0 protocol stack, profiles, and other functionalities. - * - * In order to distinguish types of modules, items are grouped with markers to - * delineate start and end of the groups - * - * The module type is used for various purposes: - * identification in debug print statements - * access to initialization flags - * access to the configuration table - */ - -typedef enum { - /* profiles and protocols --> Updates to oi_debug.c and oi_config_table.c */ - - /* XX --> Keep Enum values up-to-date! */ - OI_MODULE_AT, /**< 00 AT command processing */ - OI_MODULE_A2DP, /**< 01 Advanced Audio Distribution Profile */ - OI_MODULE_AVCTP, /**< 02 Audio-Visual Control Transport Profile */ - OI_MODULE_AVDTP, /**< 03 Audio-Visual Distribution Protocol */ - OI_MODULE_AVRCP, /**< 04 Audio-Visual Remote Control Profile */ - OI_MODULE_BIP_CLI, /**< 05 Basic Imaging Profile protocol client */ - OI_MODULE_BIP_SRV, /**< 06 Basic Imaging Profile protocol server */ - OI_MODULE_BNEP, /**< 07 Bluetooth Network Encapsulation Protocol */ - OI_MODULE_BPP_SENDER, /**< 08 Basic Printing Profile */ - OI_MODULE_BPP_PRINTER, /**< 09 Basic Printing Profile */ - OI_MODULE_CTP, /**< 10 Cordless Telephony Profile */ - OI_MODULE_DUN, /**< 11 Dial-Up Networking Profile */ - OI_MODULE_FAX, /**< 12 Fax Profile */ - OI_MODULE_FTP_CLI, /**< 13 File Transfer Profile protocol client */ - OI_MODULE_FTP_SRV, /**< 14 File Transfer Profile protocol server */ - OI_MODULE_HANDSFREE, /**< 15 Hands-Free Profile */ - OI_MODULE_HANDSFREE_AG, /**< 16 Hands-Free Profile */ - OI_MODULE_HCRP_CLI, /**< 17 Hardcopy Cable Replacement Profile */ - OI_MODULE_HCRP_SRV, /**< 18 Hardcopy Cable Replacement Profile */ - OI_MODULE_HEADSET, /**< 19 Headset Profile */ - OI_MODULE_HEADSET_AG, /**< 20 Headset Profile */ - OI_MODULE_HID, /**< 21 Human Interface Device profile */ - OI_MODULE_INTERCOM, /**< 22 Intercom Profile */ - OI_MODULE_OBEX_CLI, /**< 23 OBEX protocol client, Generic Object Exchange Profile */ - OI_MODULE_OBEX_SRV, /**< 24 OBEX protocol server, Generic Object Exchange Profile */ - OI_MODULE_OPP_CLI, /**< 25 Object Push Profile protocol client */ - OI_MODULE_OPP_SRV, /**< 26 Object Push Profile protocol server */ - OI_MODULE_PAN, /**< 27 PAN profile */ - OI_MODULE_PBAP_CLI, /**< 28 Phonebook Access Profile client */ - OI_MODULE_PBAP_SRV, /**< 29 Phonebook Access Profile server */ - OI_MODULE_SAP_CLI, /**< 30 SIM Access Profile */ - OI_MODULE_SAP_SRV, /**< 31 SIM Access Profile */ - OI_MODULE_SPP, /**< 32 Serial Port Profile */ - OI_MODULE_SYNC_CLI, /**< 33 Synchronization Profile */ - OI_MODULE_SYNC_SRV, /**< 34 Synchronization Profile */ - OI_MODULE_SYNC_CMD_CLI, /**< 35 Synchronization Profile */ - OI_MODULE_SYNC_CMD_SRV, /**< 36 Synchronization Profile */ - OI_MODULE_SYNCML, /**< 37 SyncML Profile */ - OI_MODULE_TCS, /**< 38 TCS Binary */ - OI_MODULE_VDP, /**< 39 Video Distribution Profile */ - - /* corestack components --> Updates to oi_debug.c and oi_config_table.c */ - - OI_MODULE_COMMON_CONFIG, /**< 40 Common configuration, module has no meaning other than for config struct */ - OI_MODULE_CMDCHAIN, /**< 41 Command chaining utility */ - OI_MODULE_DISPATCH, /**< 42 Dispatcher */ - OI_MODULE_DATAELEM, /**< 43 Data Elements, marshaller */ - OI_MODULE_DEVMGR, /**< 44 Device Manager */ - OI_MODULE_DEVMGR_MODES, /**< 45 Device Manager connectability/discoverability modes */ - OI_MODULE_HCI, /**< 46 Host Controller Interface command layer */ - OI_MODULE_L2CAP, /**< 47 L2CAP */ - OI_MODULE_MEMMGR, /**< 48 modules that do memory management */ - OI_MODULE_POLICYMGR, /**< 49 Policy Manager */ - OI_MODULE_RFCOMM, /**< 50 RFCOMM */ - OI_MODULE_RFCOMM_SD, /**< 51 RFCOMM Service discovery */ - OI_MODULE_SDP_CLI, /**< 52 Service Discovery Protocol client */ - OI_MODULE_SDP_SRV, /**< 53 Service Discovery Protocol server */ - OI_MODULE_SDPDB, /**< 54 Service Discovery Protocol database */ - OI_MODULE_SECMGR, /**< 55 Security Manager */ - OI_MODULE_SNIFFLOG, /**< 56 sniff log */ - OI_MODULE_SUPPORT, /**< 57 support functions, including CThru Dispatcher, time functions, and stack initialization */ - OI_MODULE_TRANSPORT, /**< 58 transport layer between HCI command layer and driver */ - OI_MODULE_TEST, /**< 59 used to debug output from internal test programs */ - OI_MODULE_XML, /**< 60 XML/CSS parser */ - - OI_MODULE_DI, /**< 61 Device Identification Profile */ - - // bhapi components --> Updates to oi_debug.c - - OI_MODULE_BHAPI, /**< 62 BLUEmagic Host API generic */ - OI_MODULE_BHCLI, /**< 63 BLUEmagic Host API client side */ - OI_MODULE_BHSRV, /**< 64 BLUEmagic Host API server side */ - OI_MODULE_MSGQ, /**< 65 module that handles message queuing */ - OI_MODULE_BHAPI_TRANSPORT, /**< 66 module that handles message queuing */ - OI_MODULE_BLST_SRV, /**< 67 module that provides server side BHAPI Lightweight Serial Transport */ - OI_MODULE_BLST_CLI, /**< 68 module that provides client side BHAPI Lightweight Serial Transport */ - - // OEM files --> Updates to oi_debug.c - OI_MODULE_OEM, /**< 69 Application Memory allocation */ - - // Application glue --> Updates to oi_debug.c - OI_MODULE_APP, /**< 70 Application Memory allocation */ - - /* various pieces of code depend on these last 2 elements occuring in a specific order: - OI_MODULE_ALL must be the 2nd to last element - OI_MODULE_UNKNOWN must be the last element - */ - OI_MODULE_ALL, /**< 71 special value identifying all modules - used for control of debug print statements */ - OI_MODULE_UNKNOWN /**< 72 special value - used for debug print statements */ -} OI_MODULE; - -/** - * This constant is the number of actual modules in the list. ALL and UNKNOWN are - * special values that are not actually modules. - * Used for debug print and memmgr profiling - */ -#define OI_NUM_MODULES OI_MODULE_ALL - - -/** - * This constant is the number of profile and core components. It is used to size - * the initialization and configuration tables. - */ -#define OI_NUM_STACK_MODULES OI_MODULE_BHAPI - - -#ifdef __cplusplus -} -#endif - -/**@}*/ - -#endif /* _OI_MODULES_H */ - diff --git a/tools/sdk/include/bluedroid/oi_osinterface.h b/tools/sdk/include/bluedroid/oi_osinterface.h deleted file mode 100644 index 78680419001..00000000000 --- a/tools/sdk/include/bluedroid/oi_osinterface.h +++ /dev/null @@ -1,197 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_OSINTERFACE_H -#define _OI_OSINTERFACE_H -/** - @file - * This file provides the platform-independent interface for functions for which - * implementation is platform-specific. - * - * The functions in this header file define the operating system or hardware - * services needed by the BLUEmagic 3.0 protocol stack. The - * actual implementation of these services is platform-dependent. - * - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#include "oi_stddefs.h" -#include "oi_time.h" -#include "oi_status.h" -#include "oi_modules.h" - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - - -/** - * Terminates execution. - * - * @param reason Reason for termination - */ -void OI_FatalError(OI_STATUS reason); - -/** - * This function logs an error. - * - * When built for release mode, BLUEmagic 3 errors are logged to - * this function. (in debug mode, errors are logged via - * OI_Print()). - * - * @param module Module in which the error was detected (see - * oi_modules.h) - * @param lineno Line number of the C file OI_SLOG_ERROR called - * @param status Status code associated with the error event - */ -void OI_LogError(OI_MODULE module, OI_INT lineno, OI_STATUS status); - -/** - * This function initializes the debug code handling. - * - * When built for debug mode, this function performs platform - * dependent initialization to handle message codes passed in - * via OI_SetMsgCode(). - */ -void OI_InitDebugCodeHandler(void); - - -/** - * This function reads the time from the real time clock. - * - * All timing in BM3 is relative, typically a granularity - * of 5 or 10 msecs is adequate. - * - * @param[out] now Pointer to the buffer to which the current - * time will be returned - */ -void OI_Time_Now(OI_TIME *now); - -/** - * This function causes the current thread to sleep for the - * specified amount of time. This function must be called - * without the stack access token. - * - * @note BM3 corestack and profiles never suspend and never call - * OI_Sleep. The use of OI_Sleep is limited to applications and - * platform-specific code. - * - * If your port and applications never use OI_Sleep, this function can be left unimplemented. - * - * @param milliseconds Number of milliseconds to sleep - */ -void OI_Sleep(OI_UINT32 milliseconds); - - -/** - * Defines for message type codes. - */ -#define OI_MSG_CODE_APPLICATION 0 /**< Application output */ -#define OI_MSG_CODE_ERROR 1 /**< Error message output */ -#define OI_MSG_CODE_WARNING 2 /**< Warning message output */ -#define OI_MSG_CODE_TRACE 3 /**< User API function trace output */ -#define OI_MSG_CODE_PRINT1 4 /**< Catagory 1 debug print output */ -#define OI_MSG_CODE_PRINT2 5 /**< Catagory 2 debug print output */ -#define OI_MSG_CODE_HEADER 6 /**< Error/Debug output header */ - -/** - * This function is used to indicate the type of text being output with - * OI_Print(). For the Linux and Win32 platforms, it will set - * the color of the text. Other possible uses could be to insert - * HTML style tags, add some other message type indication, or - * be completely ignored altogether. - * - * @param code OI_MSG_CODE_* indicating setting the message type. - */ -void OI_SetMsgCode(OI_UINT8 code); - -/** - * All output from OI_Printf() and all debug output is sent to OI_Print. - * Typically, if the platform has a console, OI_Print() is sent to stdout. - * Embedded platforms typically send OI_Print() output to a serial port. - * - * @param str String to print - */ -void OI_Print(OI_CHAR const *str); - -/** - * In cases where OI_Print() is sending output to a logfile in addition to console, - * it is desirable to also put console input into the logfile. - * This function can be called by the console input process. - * - * @note This is an optional API which is strictly - * between the platform-specific stack_console and osinterface - * modules. This API need only be implemented on those - * platforms where is serves a useful purpose, e.g., win32. - * - * @param str Console input string - */ - -void OI_Print_ConsoleInput(OI_CHAR const *str); - -/** - * This function computes the CRC16 of the program image. - */ -OI_UINT16 OI_ProgramImageCRC16(void); - -/** - * Writes an integer to stdout in hex. This macro is intended - * for selective use when debugging in small memory - * configurations or other times when it is not possible to use - * OI_DBGPRINT. - * - * @param n the integer to print - */ - -#define OI_Print_Int(n) \ -{ \ - static const OI_CHAR _digits[] = "0123456789ABCDEF"; \ - OI_CHAR _buf[9]; \ - OI_CHAR *_str = &_buf[8]; \ - OI_UINT32 _i = n; \ - *_str = 0; \ - do { *(--_str) = _digits[(_i & 0xF)]; _i >>= 4; } while (_i); \ - OI_Print(_str); \ -} - -/** - * Application Dynamic Memory allocation. - * - * These APIs are provided for application use on those - * platforms which have no dynamic memory support. Memory is - * allocated from the pool-based heap managed by the stack's - * internal memory manager. - */ -void *OI_APP_Malloc(OI_INT32 size); -void OI_APP_Free(void *ptr); - -/*****************************************************************************/ -#ifdef __cplusplus -} -#endif - -/**@}*/ - -#endif /* _OI_OSINTERFACE_H */ - diff --git a/tools/sdk/include/bluedroid/oi_status.h b/tools/sdk/include/bluedroid/oi_status.h deleted file mode 100644 index 8c392a292de..00000000000 --- a/tools/sdk/include/bluedroid/oi_status.h +++ /dev/null @@ -1,579 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_STATUS_H -#define _OI_STATUS_H -/** - * @file - * This file contains status codes for BLUEmagic 3.0 software. - */ - -#include "oi_stddefs.h" - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - - -/** test it **/ - -/** - * OI_STATUS must fit in 16 bits, so status codes can range from 0 to 66535, inclusive. - */ - -typedef enum { - OI_STATUS_SUCCESS = 0, /**< function call succeeded alias for #OI_OK */ - OI_OK = 0, /**< function call succeeded alias for #OI_STATUS_SUCCESS */ - OI_STATUS_INVALID_PARAMETERS = 101, /**< invalid function input parameters */ - OI_STATUS_NOT_IMPLEMENTED = 102, /**< attempt to use an unimplemented function */ - OI_STATUS_NOT_INITIALIZED = 103, /**< data not initialized */ - OI_STATUS_NO_RESOURCES = 104, /**< generic resource allocation failure status */ - OI_STATUS_INTERNAL_ERROR = 105, /**< internal inconsistency */ - OI_STATUS_OUT_OF_MEMORY = 106, /**< generally, OI_Malloc failed */ - OI_ILLEGAL_REENTRANT_CALL = 107, /**< violation of non-reentrant module policy */ - OI_STATUS_INITIALIZATION_FAILED = 108, /**< module initialization failed */ - OI_STATUS_INITIALIZATION_PENDING = 109, /**< inititialization not yet complete */ - OI_STATUS_NO_SCO_SUPPORT = 110, /**< SCO operation rejected; system not configured for SCO */ - OI_STATUS_OUT_OF_STATIC_MEMORY = 111, /**< static malloc failed */ - OI_TIMEOUT = 112, /**< generic timeout */ - OI_OS_ERROR = 113, /**< some operating system error */ - OI_FAIL = 114, /**< generic failure */ - OI_STRING_FORMAT_ERROR = 115, /**< error in VarString formatting string */ - OI_STATUS_PENDING = 116, /**< The operation is pending. */ - OI_STATUS_INVALID_COMMAND = 117, /**< The command was invalid. */ - OI_BUSY_FAIL = 118, /**< command rejected due to busy */ - OI_STATUS_ALREADY_REGISTERED = 119, /**< The registration has already been performed. */ - OI_STATUS_NOT_FOUND = 120, /**< The referenced resource was not found. */ - OI_STATUS_NOT_REGISTERED = 121, /**< not registered */ - OI_STATUS_NOT_CONNECTED = 122, /**< not connected */ - OI_CALLBACK_FUNCTION_REQUIRED = 123, /**< A callback function parameter was required. */ - OI_STATUS_MBUF_OVERFLOW = 124, /**< There is no room to add another buffer to an mbuf. */ - OI_STATUS_MBUF_UNDERFLOW = 125, /**< There was an attempt to pull too many bytes from an mbuf. */ - OI_STATUS_CONNECTION_EXISTS = 126, /**< connection exists */ - OI_STATUS_NOT_CONFIGURED = 127, /**< module not configured */ - OI_LOWER_STACK_ERROR = 128, /**< An error was reported by lower stack API. This is used for embedded platforms. */ - OI_STATUS_RESET_IN_PROGRESS = 129, /**< Request failed/rejected because we're busy resetting. */ - OI_STATUS_ACCESS_DENIED = 130, /**< Generic access denied error. */ - OI_STATUS_DATA_ERROR = 131, /**< Generic data error. */ - OI_STATUS_INVALID_ROLE = 132, /**< The requested role was invalid. */ - OI_STATUS_ALREADY_CONNECTED = 133, /**< The requested connection is already established. */ - OI_STATUS_PARSE_ERROR = 134, /**< Parse error */ - OI_STATUS_END_OF_FILE = 135, /**< End of file */ - OI_STATUS_READ_ERROR = 136, /**< Generic read error */ - OI_STATUS_WRITE_ERROR = 137, /**< Generic write error */ - OI_STATUS_NEGOTIATION_FAILURE = 138, /**< Error in negotiation */ - OI_STATUS_READ_IN_PROGRESS = 139, /**< A read is already in progress */ - OI_STATUS_ALREADY_INITIALIZED = 140, /**< Initialization has already been done */ - OI_STATUS_STILL_CONNECTED = 141, /**< The service cannot be shutdown because there are still active connections. */ - OI_STATUS_MTU_EXCEEDED = 142, /**< The packet is too big */ - OI_STATUS_LINK_TERMINATED = 143, /**< The link was terminated */ - OI_STATUS_PIN_CODE_TOO_LONG = 144, /**< Application gave us a pin code that is too long */ - OI_STATUS_STILL_REGISTERED = 145, /**< The service cannot be shutdown because there are still active registrations. */ - OI_STATUS_SPEC_VIOLATION = 146, /**< Some application behavior contrary to BT specifications */ - - - OI_STATUS_PSM_ALREADY_REGISTERED = 402, /**< L2CAP: The specified PSM has already been registered. */ - OI_STATUS_INVALID_CID = 403, /**< L2CAP: CID is invalid or no longer valid (connection terminated) */ - OI_STATUS_CID_NOT_FOUND = 404, /**< L2CAP: CID does not represent a current connection */ - OI_STATUS_CHANNEL_NOT_FOUND = 406, /**< L2CAP: CID does not represent a current connection */ - OI_STATUS_PSM_NOT_FOUND = 407, /**< L2CAP: PSM not found */ - OI_STATUS_INVALID_STATE = 408, /**< L2CAP: invalid state */ - OI_STATUS_WRITE_IN_PROGRESS = 410, /**< L2CAP: write in progress */ - OI_STATUS_INVALID_PACKET = 411, /**< L2CAP: invalid packet */ - OI_STATUS_SEND_COMPLETE = 412, /**< L2CAP: send is complete */ - OI_STATUS_INVALID_HANDLE = 414, /**< L2CAP: handle is invalid */ - OI_STATUS_GROUP_FULL = 418, /**< L2CAP: No more members can be added to the specified group. */ - OI_STATUS_DEVICE_ALREADY_IN_GROUP = 423, /**< L2CAP: The device already exists in the group. */ - OI_STATUS_DUPLICATE_GROUP = 425, /**< L2CAP: attempt to add more than one group */ - OI_STATUS_EMPTY_GROUP = 426, /**< L2CAP: group is empty */ - OI_STATUS_PACKET_NOT_FOUND = 427, /**< L2CAP: packet not found */ - OI_STATUS_BUFFER_TOO_SMALL = 428, /**< L2CAP: The buffer size is too small. */ - OI_STATUS_IDENTIFIER_NOT_FOUND = 429, /**< L2CAP: identifier not found */ - - OI_L2CAP_DISCONNECT_LOWER_LAYER = 430, /**< L2CAP: The lower level forced a disconnect. */ - OI_L2CAP_DISCONNECT_REMOTE_REQUEST = 431, /**< L2CAP: The remote device requested a disconnect. */ - OI_L2CAP_GROUP_ADD_CONNECT_FAIL = 433, /**< L2CAP: Group add connect faiL */ - OI_L2CAP_GROUP_REMOVE_FAILURE = 434, /**< L2CAP: Group remove failure */ - OI_L2CAP_DATA_WRITE_ERROR_LINK_TERM = 435, /**< L2CAP: Data write error LINK_TERM */ - OI_L2CAP_DISCONNECT_LOCAL_REQUEST = 436, /**< L2CAP: Disconnect local request */ - - OI_L2CAP_CONNECT_TIMEOUT = 437, /**< L2CAP: Connect timeout */ - OI_L2CAP_DISCONNECT_TIMEOUT = 439, /**< L2CAP: Disconnect timeout */ - OI_L2CAP_PING_TIMEOUT = 440, /**< L2CAP: Ping timeout */ - OI_L2CAP_GET_INFO_TIMEOUT = 441, /**< L2CAP: Get info timeout */ - OI_L2CAP_INVALID_ADDRESS = 444, /**< L2CAP: Invalid address */ - OI_L2CAP_CMD_REJECT_RCVD = 445, /**< L2CAP: remote sent us 'command reject' response */ - - OI_L2CAP_CONNECT_BASE = 450, /**< L2CAP: Connect base */ - OI_L2CAP_CONNECT_PENDING = 451, /**< L2CAP: Connect pending */ - OI_L2CAP_CONNECT_REFUSED_INVALID_PSM = 452, /**< L2CAP: Connect refused invalid PSM */ - OI_L2CAP_CONNECT_REFUSED_SECURITY = 453, /**< L2CAP: Connect refused security */ - OI_L2CAP_CONNECT_REFUSED_NO_RESOURCES = 454, /**< L2CAP: Connect refused no resources */ - - OI_L2CAP_CONFIG_BASE = 460, /**< L2CAP: Config base */ - OI_L2CAP_CONFIG_FAIL_INVALID_PARAMETERS = 461, /**< L2CAP: Config fail invalid parameters */ - OI_L2CAP_CONFIG_FAIL_NO_REASON = 462, /**< L2CAP: Config fail no reason */ - OI_L2CAP_CONFIG_FAIL_UNKNOWN_OPTIONS = 463, /**< L2CAP: Config fail unknown options */ - - OI_L2CAP_GET_INFO_BASE = 470, /**< L2CAP: Get info base */ - OI_L2CAP_GET_INFO_NOT_SUPPORTED = 471, /**< L2CAP: Get info not supported */ - OI_L2CAP_MTU_EXCEEDED = 472, /**< L2CAP: The MTU of the channel was exceeded */ - OI_L2CAP_INVALID_PSM = 482, /**< L2CAP: Invalid PSM */ - OI_L2CAP_INVALID_MTU = 483, /**< L2CAP: Invalid MTU */ - OI_L2CAP_INVALID_FLUSHTO = 484, /**< L2CAP: Invalid flush timeout */ - - OI_HCI_NO_SUCH_CONNECTION = 601, /**< HCI: caller specified a non-existent connection handle */ - OI_HCI_CB_LIST_FULL = 603, /**< HCI: callback list is full, cannot attempt to send command */ - OI_HCI_EVENT_UNDERRUN = 605, /**< HCI: parsing event packet, premature end-of-parameters */ - OI_HCI_UNKNOWN_EVENT_CODE = 607, /**< HCI: event received - event code is unknown */ - OI_HCI_BAD_EVENT_PARM_LEN = 608, /**< HCI: event - parameter length is incorrect */ - OI_HCI_CMD_QUEUE_FULL = 611, /**< HCI: command queue is full */ - OI_HCI_SHORT_EVENT = 612, /**< HCI: event received, missing event code and/or parm len */ - OI_HCI_TRANSMIT_NOT_READY = 613, /**< HCI: ACL/SCO transmit request failed - busy or no buffers available */ - OI_HCI_ORPHAN_SENT_EVENT = 614, /**< HCI: got spurious 'sent' event from transport layer */ - OI_HCI_CMD_TABLE_ERROR = 615, /**< HCI: inconsistency in the internal command table */ - OI_HCI_UNKNOWN_CMD_ID = 616, /**< HCI: HciApi Command - unknown command id */ - OI_HCI_UNEXPECTED_EVENT = 619, /**< HCI: event received which only occurs in response to our cmd */ - OI_HCI_EVENT_TABLE_ERROR = 620, /**< HCI: inconsistency in the internal event table */ - OI_HCI_EXPECTED_EVENT_TIMOUT = 621, /**< HCI: timed out waiting for an expected event */ - OI_HCI_NO_CMD_DESC_FOR_OPCODE = 622, /**< HCI: event opcode is not known */ - OI_HCI_INVALID_OPCODE_ERROR = 623, /**< HCI: command opcode is invalid */ - OI_HCI_FLOW_CONTROL_DISABLED = 624, /**< HCI: can not use host flow control APIs if disabled in configuration */ - OI_HCI_TX_COMPLETE = 625, /**< HCI: packet delivery to Host Controler complete */ - OI_HCI_TX_ERROR = 626, /**< HCI: failed to deliver packet to Host Controler */ - OI_HCI_DEVICE_NOT_INITIALIZED = 627, /**< HCI: commands from upper layers disallowed until device is up and running */ - OI_HCI_UNSUPPORTED_COMMAND = 628, /**< HCI: command requested is not supported by local device */ - OI_HCI_PASSTHROUGH_ERROR = 629, /**< HCI: Error processing passthrough command */ - OI_HCI_PASSTHROUGH_ALREADY_SET = 630, /**< HCI: Passthrough mode already enabled */ - OI_HCI_RESET_FAILURE = 631, /**< HCI: failed to reset the device/baseband */ - OI_HCI_TRANSPORT_RESET = 632, /**< HCI: some operation failed because of a reset in the transport */ - OI_HCIERR_HCIIFC_INIT_FAILURE = 633, /**< HCI: failed to initialize transport layer interface */ - - OI_HCIERR_FIRST_ERROR_VALUE = 701, /**< marker for first HCI protocol error */ - OI_HCIERR_UNKNOWN_HCI_COMMAND = 701, /**< HCI: protocol error 0x01 */ - OI_HCIERR_NO_CONNECTION = 702, /**< HCI: protocol error 0x02 */ - OI_HCIERR_HARDWARE_FAILURE = 703, /**< HCI: protocol error 0x03 */ - OI_HCIERR_PAGE_TIMEOUT = 704, /**< HCI: protocol error 0x04 */ - OI_HCIERR_AUTHENTICATION_FAILURE = 705, /**< HCI: protocol error 0x05 */ - OI_HCIERR_KEY_MISSING = 706, /**< HCI: protocol error 0x06 */ - OI_HCIERR_MEMORY_FULL = 707, /**< HCI: protocol error 0x07 */ - OI_HCIERR_CONNECTION_TIMEOUT = 708, /**< HCI: protocol error 0x08 */ - OI_HCIERR_MAX_NUM_OF_CONNECTIONS = 709, /**< HCI: protocol error 0x09 */ - OI_HCIERR_MAX_NUM_OF_SCO_CONNECTIONS = 710, /**< HCI: protocol error 0x0A */ - OI_HCIERR_ACL_CONNECTION_ALREADY_EXISTS = 711, /**< HCI: protocol error 0x0B */ - OI_HCIERR_COMMAND_DISALLOWED = 712, /**< HCI: protocol error 0x0C */ - OI_HCIERR_HOST_REJECTED_RESOURCES = 713, /**< HCI: protocol error 0x0D */ - OI_HCIERR_HOST_REJECTED_SECURITY = 714, /**< HCI: protocol error 0x0E */ - OI_HCIERR_HOST_REJECTED_PERSONAL_DEVICE = 715, /**< HCI: protocol error 0x0F */ - OI_HCIERR_HOST_TIMEOUT = 716, /**< HCI: protocol error 0x10 */ - OI_HCIERR_UNSUPPORTED = 717, /**< HCI: protocol error 0x11 */ - OI_HCIERR_INVALID_PARAMETERS = 718, /**< HCI: protocol error 0x12 */ - OI_HCIERR_OTHER_END_USER_DISCONNECT = 719, /**< HCI: protocol error 0x13 */ - OI_HCIERR_OTHER_END_LOW_RESOURCES = 720, /**< HCI: protocol error 0x14 */ - OI_HCIERR_OTHER_END_POWERING_OFF = 721, /**< HCI: protocol error 0x15 */ - OI_HCIERR_CONNECTION_TERMINATED_LOCALLY = 722, /**< HCI: protocol error 0x16 */ - OI_HCIERR_REPEATED_ATTEMPTS = 723, /**< HCI: protocol error 0x17 */ - OI_HCIERR_PAIRING_NOT_ALLOWED = 724, /**< HCI: protocol error 0x18 */ - OI_HCIERR_UNKNOWN_LMP_PDU = 725, /**< HCI: protocol error 0x19 */ - OI_HCIERR_UNSUPPORTED_REMOTE_FEATURE = 726, /**< HCI: protocol error 0x1A */ - OI_HCIERR_SCO_OFFSET_REJECTED = 727, /**< HCI: protocol error 0x1B */ - OI_HCIERR_SCO_INTERVAL_REJECTED = 728, /**< HCI: protocol error 0x1C */ - OI_HCIERR_SCO_AIR_MODE_REJECTED = 729, /**< HCI: protocol error 0x1D */ - OI_HCIERR_INVALID_LMP_PARMS = 730, /**< HCI: protocol error 0x1E */ - OI_HCIERR_UNSPECIFIED_ERROR = 731, /**< HCI: protocol error 0x1F */ - OI_HCIERR_UNSUPPORTED_LMP_PARAMETERS = 732, /**< HCI: protocol error 0x20 */ - OI_HCIERR_ROLE_CHANGE_NOT_ALLOWED = 733, /**< HCI: protocol error 0x21 */ - OI_HCIERR_LMP_RESPONSE_TIMEOUT = 734, /**< HCI: protocol error 0x22 */ - OI_HCIERR_LMP_ERROR_TRANS_COLLISION = 735, /**< HCI: protocol error 0x23 */ - OI_HCIERR_LMP_PDU_NOT_ALLOWED = 736, /**< HCI: protocol error 0x24 */ - OI_HCIERR_ENCRYPTION_MODE_NOT_ACCEPTABLE = 737, /**< HCI: protocol error 0x25 */ - OI_HCIERR_UNIT_KEY_USED = 738, /**< HCI: protocol error 0x26 */ - OI_HCIERR_QOS_NOT_SUPPORTED = 739, /**< HCI: protocol error 0x27 */ - OI_HCIERR_INSTANT_PASSED = 740, /**< HCI: protocol error 0x28 */ - OI_HCIERR_UNIT_KEY_PAIRING_UNSUPPORTED = 741, /**< HCI: protocol error 0x29 */ - OI_HCIERR_DIFFERENT_TRANS_COLLISION = 742, /**< HCI: protocol error 0x2A */ - OI_HCIERR_RESERVED_2B = 743, /**< HCI: protocol error 0x2B */ - OI_HCIERR_QOS_UNACCEPTABLE_PARAMETER = 744, /**< HCI: protocol error 0x2C */ - OI_HCIERR_QOS_REJECTED = 745, /**< HCI: protocol error 0x2D */ - OI_HCIERR_CHANNEL_CLASSIFICATION_NS = 746, /**< HCI: protocol error 0x2E */ - OI_HCIERR_INSUFFICIENT_SECURITY = 747, /**< HCI: protocol error 0x2F */ - OI_HCIERR_PARM_OUT_OF_MANDATORY_RANGE = 748, /**< HCI: protocol error 0x30 */ - OI_HCIERR_RESERVED_31 = 749, /**< HCI: protocol error 0x31 */ - OI_HCIERR_ROLE_SWITCH_PENDING = 750, /**< HCI: protocol error 0x32 */ - OI_HCIERR_RESERVED_33 = 751, /**< HCI: protocol error 0x33 */ - OI_HCIERR_RESERVED_SLOT_VIOLATION = 752, /**< HCI: protocol error 0x34 */ - OI_HCIERR_ROLE_SWITCH_FAILED = 753, /**< HCI: protocol error 0x35 */ - OI_HCIERR_EIR_TOO_LARGE = 754, /**< HCI: protocol error 0x36 */ - OI_HCIERR_SSP_NOT_SUPPORTED_BY_HOST = 755, /**< HCI: protocol error 0x37 */ - OI_HCIERR_HOST_BUSY_PAIRING = 756, /**< HCI: protocol error 0x38 */ - - OI_HCIERR_UNKNOWN_ERROR = 757, /**< HCI: unknown error code */ - OI_HCIERR_LAST_ERROR_VALUE = 757, /**< marker for last HCI protocol error */ - - OI_SDP_SPEC_ERROR = 800, /**< SDP: Base error status for mapping OI_STATUS codes to SDP errors */ - OI_SDP_INVALID_SERVICE_RECORD_HANDLE = (OI_SDP_SPEC_ERROR + 2), /**< SDP: protocol error Invalid Service Record Handle */ - OI_SDP_INVALID_REQUEST_SYNTAX = (OI_SDP_SPEC_ERROR + 3), /**< SDP: protocol error Invalid Request Syntax */ - OI_SDP_INVALID_PDU_SIZE = (OI_SDP_SPEC_ERROR + 4), /**< SDP: protocol error Invalid PDU Size */ - OI_SDP_INVALID_CONTINUATION_STATE = (OI_SDP_SPEC_ERROR + 5), /**< SDP: protocol error Invalid Continuation State */ - OI_SDP_INSUFFICIENT_RESOURCES = (OI_SDP_SPEC_ERROR + 6), /**< SDP: protocol error Insufficient Resources */ - OI_SDP_ERROR = 807, /**< SDP: server returned an error code */ - OI_SDP_CORRUPT_DATA_ELEMENT = 808, /**< SDP: Invalid or corrupt data element representation */ - OI_SDP_SERVER_NOT_CONNECTED = 810, /**< SDP: Attempt to disconnect from an unconnected server */ - OI_SDP_ACCESS_DENIED = 811, /**< SDP: Server denied access to server */ - OI_SDP_ATTRIBUTES_OUT_OF_ORDER = 812, /**< SDP: Attributes in attribute list not in ascending order */ - OI_SDP_DEVICE_DOES_NOT_SUPPORT_SDP = 813, /**< SDP: Tried to connect to a device that does not support SDP */ - OI_SDP_NO_MORE_DATA = 815, /**< SDP: Server does not have more continuation data */ - OI_SDP_REQUEST_PARAMS_TOO_LONG = 816, /**< SDP: Parameters for a request exceed the L2CAP buffer size */ - OI_SDP_REQUEST_PENDING = 817, /**< SDP: Cannot make a request when another request is being processed */ - OI_SDP_SERVER_CONNECT_FAILED = 819, /**< SDP: Failed attempt to connect to an SDP server */ - OI_SDP_SERVER_TOO_MANY_CONNECTIONS = 821, /**< SDP: Exceeded maximum number of simultaneous server connections */ - OI_SDP_NO_MATCHING_SERVICE_RECORD = 823, /**< SDP: No service record matched the UUID list */ - OI_SDP_PARTIAL_RESPONSE = 824, /**< SDP: Internal use only */ - OI_SDP_ILLEGAL_ARGUMENT = 825, /**< SDP: Illegal argument passed to an SDP function */ - OI_SDP_ATTRIBUTE_NOT_FOUND = 826, /**< SDP: A requested attribute was not found in a service record */ - OI_SDP_DATABASE_OUT_OF_RESOURCES = 827, /**< SDP: server database is out of memory */ - OI_SDP_SHORT_PDU = 829, /**< SDP: Not enough bytes in the packet */ - OI_SDP_TRANSACTION_ID_MISMATCH = 830, /**< SDP: Transaction Id was not as expected */ - OI_SDP_UNEXPECTED_RESPONSE_PDU_ID = 831, /**< SDP: Did not expect this response PDU */ - OI_SDP_REQUEST_TIMEOUT = 832, /**< SDP: Did not get a response within the timeout period */ - OI_SDP_INVALID_RESPONSE_SYNTAX = 833, /**< SDP: Response is not correctly formatted */ - OI_SDP_CONNECTION_TIMEOUT = 834, /**< SDP: Connection attempt timed out at a lower layer */ - OI_SDP_RESPONSE_DATA_ERROR = 835, /**< SDP: Response to a service request appears to be corrupt */ - OI_SDP_TOO_MANY_ATTRIBUTE_BYTES = 836, /**< SDP: Response contained more bytes than requested. */ - OI_SDP_TOO_MANY_SERVICE_RECORDS = 837, /**< SDP: Response contained more service records than requested. */ - OI_SDP_INVALID_CONNECTION_ID = 838, /**< SDP: Invalid connection ID in an SDP request */ - OI_SDP_CANNOT_SET_ATTRIBUTE = 839, /**< SDP: Attempt to set a dynamic attribute value failed */ - OI_SDP_BADLY_FORMED_ATTRIBUTE_VALUE = 840, /**< SDP: An attribute value has the wrong type or structure */ - OI_SDP_NO_ATTRIBUTE_LIST_TO_REMOVE = 841, /**< SDP: Attempt to remove a non-existent attribute list from a service record */ - OI_SDP_ATTRIBUTE_LIST_ALREADY_ADDED = 842, /**< SDP: An attribute list has already been added to the service record */ - OI_SDP_DATA_ELEMENT_TRUNCATED = 843, /**< SDP: Data element truncated (too few bytes) */ - - OI_RFCOMM_WRITE_IN_PROGRESS = 901, /**< RFCOMM: Write in progress */ - OI_RFCOMM_INVALID_BAUDRATE = 903, /**< RFCOMM: Invalid baudrate */ - OI_RFCOMM_INVALID_DATABIT = 904, /**< RFCOMM: Invalid databit */ - OI_RFCOMM_INVALID_STOPBIT = 905, /**< RFCOMM: Invalid stopbit */ - OI_RFCOMM_INVALID_PARITY = 906, /**< RFCOMM: Invalid parity */ - OI_RFCOMM_INVALID_PARITYTYPE = 907, /**< RFCOMM: Invalid paritytype */ - OI_RFCOMM_INVALID_FLOWCONTROL = 908, /**< RFCOMM: Invalid flowcontrol */ - OI_RFCOMM_SESSION_EXISTS = 909, /**< RFCOMM: Session exists */ - OI_RFCOMM_INVALID_CHANNEL = 910, /**< RFCOMM: Invalid channel */ - OI_RFCOMM_DLCI_EXISTS = 911, /**< RFCOMM: DLCI exists */ - OI_RFCOMM_LINK_NOT_FOUND = 912, /**< RFCOMM: Link not found */ - OI_RFCOMM_REMOTE_REJECT = 913, /**< RFCOMM: Remote reject */ - OI_RFCOMM_TEST_IN_PROGRESS = 915, /**< RFCOMM: Test in progress */ - OI_RFCOMM_SESSION_NOT_FOUND = 916, /**< RFCOMM: Session not found */ - OI_RFCOMM_INVALID_PACKET = 917, /**< RFCOMM: Invalid packet */ - OI_RFCOMM_FRAMESIZE_EXCEEDED = 918, /**< RFCOMM: Framesize exceeded */ - OI_RFCOMM_INVALID_DLCI = 920, /**< RFCOMM: Invalid dlci */ - OI_RFCOMM_SERVER_NOT_REGISTERED = 921, /**< RFCOMM: Server not registered */ - OI_RFCOMM_CREDIT_ERROR = 922, /**< RFCOMM: Credit error */ - OI_RFCOMM_NO_CHANNEL_NUMBER = 923, /**< RFCOMM: No channel number */ - OI_RFCOMM_QUERY_IN_PROGRESS = 924, /**< RFCOMM: Query in progress */ - OI_RFCOMM_SESSION_SHUTDOWN = 925, /**< RFCOMM: Session shutdown */ - OI_RFCOMM_LOCAL_DEVICE_DISCONNECTED = 926, /**< RFCOMM: Local device disconnected */ - OI_RFCOMM_REMOTE_DEVICE_DISCONNECTED = 927, /**< RFCOMM: Remote device disconnected */ - OI_RFCOMM_OUT_OF_SERVER_CHANNELS = 928, /**< RFCOMM: Out of server channels */ - - OI_DISPATCH_INVALID_CB_HANDLE = 1001, /**< Dispatcher was handed an invalid callback handle */ - OI_DISPATCH_TABLE_OVERFLOW = 1002, /**< Dispatcher table is full */ - - OI_TEST_UNKNOWN_TEST = 1101, /**< TEST: Unknown test */ - OI_TEST_FAIL = 1102, /**< TEST: Fail */ - - OI_HCITRANS_CANNOT_CONNECT_TO_DEVICE = 1201, /**< TRANSPORT: Cannot connect to device */ - OI_HCITRANS_BUFFER_TOO_SMALL = 1203, /**< TRANSPORT: Buffer too small */ - OI_HCITRANS_NULL_DEVICE_HANDLE = 1204, /**< TRANSPORT: Null device handle */ - OI_HCITRANS_IO_ERROR = 1205, /**< TRANSPORT: IO error */ - OI_HCITRANS_DEVICE_NOT_READY = 1206, /**< TRANSPORT: Device not ready */ - OI_HCITRANS_FUNCTION_NOT_SUPPORTED = 1207, /**< TRANSPORT: Function not supporteD */ - OI_HCITRANS_ACCESS_DENIED = 1209, /**< TRANSPORT: win32 */ - OI_HCITRANS_ACL_DATA_ERROR = 1210, /**< TRANSPORT: ACL data error */ - OI_HCITRANS_SCO_DATA_ERROR = 1211, /**< TRANSPORT: SCO data error */ - OI_HCITRANS_EVENT_DATA_ERROR = 1212, /**< TRANSPORT: HCI event data error */ - OI_HCITRANS_INTERNAL_ERROR = 1214, /**< TRANSPORT: Internal error in the transport */ - OI_HCITRANS_LINK_NOT_ACTIVE = 1215, /**< TRANSPORT: Link to the device is not currently active */ - OI_HCITRANS_INITIALIZING = 1216, /**< TRANSPORT: Transport is initializing */ - - OI_DEVMGR_NO_CONNECTION = 1301, /**< DEVMGR: No connection */ - OI_DEVMGR_HARDWARE_ERROR = 1305, /**< DEVMGR: error reported by HCI */ - OI_DEVMGR_PENDING_CONNECT_LIST_FULL = 1307, /**< DEVMGR: Pending connect list full */ - OI_DEVMGR_CONNECTION_LIST_FULL = 1309, /**< DEVMGR: Connection list full */ - OI_DEVMGR_NO_SUCH_CONNECTION = 1310, /**< DEVMGR: No such connection */ - OI_DEVMGR_INQUIRY_IN_PROGRESS = 1311, /**< DEVMGR: Inquiry in progress */ - OI_DEVMGR_PERIODIC_INQUIRY_ACTIVE = 1312, /**< DEVMGR: Periodic inquiry active */ - OI_DEVMGR_NO_INQUIRIES_ACTIVE = 1313, /**< DEVMGR: can not cancel/exit if not active */ - OI_DEVMGR_DUPLICATE_CONNECTION = 1314, /**< DEVMGR: internal error */ - OI_DEVMGR_DUPLICATE_EVENT_CALLBACK = 1316, /**< DEVMGR: attempt to register same callback twice */ - OI_DEVMGR_EVENT_CALLBACK_LIST_FULL = 1317, /**< DEVMGR: can not register event callback, list is full */ - OI_DEVMGR_EVENT_CALLBACK_NOT_FOUND = 1318, /**< DEVMGR: attempt to unregister callback failed */ - OI_DEVMGR_BUSY = 1319, /**< DEVMGR: some operations can only execute one at a time */ - OI_DEVMGR_ENUM_UNEXPECTED_INQ_COMPLETE = 1320, /**< DEVMGR: inquiry complete event in inappropriate enumeration state */ - OI_DEVMGR_ENUM_UNEXPECTED_INQ_RESULT = 1321, /**< DEVMGR: inquiry result event in inappropriate enumeration state */ - OI_DEVMGR_ENUM_DATABASE_FULL = 1322, /**< DEVMGR: device enumeration, database is full, couldn't add a new device */ - OI_DEVMGR_ENUM_INQUIRIES_OVERLAP = 1323, /**< DEVMGR: device enumeration, periodic inquiries occurring too close together */ - OI_DEVMGR_UNKNOWN_LINK_TYPE = 1324, /**< DEVMGR: HCI connect request with unkown link type */ - OI_DEVMGR_PARAM_IO_ACTIVE = 1325, /**< DEVMGR: request for parameter read/write while param read/write active */ - OI_DEVMGR_UNKNOWN_IAC_LAP = 1326, /**< DEVMGR: unrecognized IAC LAP */ - OI_DEVMGR_SCO_ALREADY_REGISTERED = 1327, /**< DEVMGR: only one application can use SCO */ - OI_DEVMGR_SCO_NOT_REGISTERED = 1328, /**< DEVMGR: SCO applications must register before using the API */ - OI_DEVMGR_SCO_WITHOUT_ACL = 1329, /**< DEVMGR: Got SCO connection but there is no underlying ACL connection */ - OI_DEVMGR_NO_SUPPORT = 1330, /**< DEVMGR: Request is not supported by the device */ - OI_DEVMGR_WRITE_POLICY_FAILED = 1331, /**< DEVMGR: connection attempt failed - unable to write link policy */ - OI_DEVMGR_NOT_IN_MASTER_MODE = 1332, /**< DEVMGR: OI_DEVMGR EndMasterMode without prior OI_DEVMGR_BeginMasterMode */ - OI_DEVMGR_POLICY_VIOLATION = 1333, /**< DEVMGR: low-power request is rejected - link policy does not allow it */ - OI_DEVMGR_BUSY_TIMEOUT = 1334, /**< DEVMGR: queued operation timed out while in the queue; \n - timeout configurable via @ref OI_CONFIG_DEVMGR::connectQueueTimeoutSecs "connectQueueTimeoutSecs" */ - OI_DEVMGR_REENCRYPT_FAILED = 1335, /**< DEVMGR: failed to re-encrypt link after role switch */ - OI_DEVMGR_ROLE_POLICY_CONFLICT = 1336, /**< DEVMGR: requested role conflicts with current policy */ - OI_DEVMGR_BAD_INTERVAL = 1337, /**< DEVMGR: current linkTO outside range of requested min/max interval */ - OI_DEVMGR_INVALID_SCO_HANDLE = 1338, /**< DEVMGR: HCI SCO event, invalid handle */ - OI_DEVMGR_CONNECTION_OVERLAP = 1339, /**< DEVMGR: Connection failed due to race condition with remote side */ - OI_DEVMGR_ORPHAN_SUBRATE_COMPLETE = 1340, /**< DEVMGR: sniff subrate complete, but no callback */ - OI_DEVMGR_EIR_RESPONSE_2_LARGE = 1341, /**< DEVMGR: eir builder, response length would exceed spec max */ - - OI_SECMGR_NO_POLICY = 1401, /**< SECMGR: no security policy has been established */ - OI_SECMGR_INTERNAL_ERROR = 1402, /**< SECMGR: internal inconsistency */ - OI_SECMGR_ORPHANED_CALLBACK = 1403, /**< SECMGR: we've been called back, but CB context is gone */ - OI_SECMGR_BUSY = 1404, /**< SECMGR: configure and access request cannot be concurrent */ - OI_SECMGR_DEVICE_NOT_TRUSTED = 1405, /**< SECMGR: l2cap access denied - device is not trusted */ - OI_SECMGR_DEVICE_ENCRYPT_FAIL = 1407, /**< SECMGR: l2cap access denied - failed to start encryption */ - OI_SECMGR_DISCONNECTED_FAIL = 1408, /**< SECMGR: l2cap access denied - disconnected */ - OI_SECMGR_ACCESS_PENDING = 1409, /**< SECMGR: l2cap access request is still pending */ - OI_SECMGR_PIN_CODE_TOO_SHORT = 1410, /**< SECMGR: Higher-layer process gave us a pin code that is too short */ - OI_SECMGR_UNKNOWN_ENCRYPT_VALUE = 1411, /**< SECMGR: got EncryptionChange event, unknown encryption enable value */ - OI_SECMGR_INVALID_POLICY = 1412, /**< SECMGR: the specified security policy is not valid for security mode */ - OI_SECMGR_AUTHORIZATION_FAILED = 1413, /**< SECMGR: device authorization failed */ - OI_SECMGR_ENCRYPTION_FAILED = 1414, /**< SECMGR: device encryption failed */ - OI_SECMGR_UNIT_KEY_UNSUPPORTED = 1415, /**< SECMGR: authentication failed due to non-support of unit keys */ - OI_SECMGR_NOT_REGISTERED = 1416, /**< SECMGR: required registrations have not yet occurred */ - OI_SECMGR_ILLEGAL_WRITE_SSP_MODE = 1417, /**< SECMGR: 2.1 HCI spec does not allow SSP mode to be disabled */ - OI_SECMGR_INVALID_SEC_LEVEL = 1418, /**< SECMGR: security level for a service is not a valid value */ - OI_SECMGR_INSUFFICIENT_LINK_KEY = 1419, /**< SECMGR: link key type is not sufficient to meet service requirements */ - OI_SECMGR_INVALID_KEY_TYPE = 1420, /**< SECMGR: link key type is not a valid value */ - OI_SECMGR_SSP_NOT_ENCRYPTED = 1421, /**< SECMGR: ssp required encryption on incoming link */ - OI_SECMGR_ORPHAN_EVENT = 1422, /**< SECMGR: some HCI security event unrelated to current processes */ - OI_SECMGR_NOT_BONDABLE = 1423, /**< SECMGR: not in bondable mode */ - - OI_TCS_INVALID_ELEMENT_TYPE = 1602, /**< TCS: element type is invalid */ - OI_TCS_INVALID_PACKET = 1603, /**< TCS: packet is invalide */ - OI_TCS_CALL_IN_PROGRESS = 1604, /**< TCS: call is in progress */ - OI_TCS_NO_CALL_IN_PROGRESS = 1605, /**< TCS: no call in progress */ - - OI_OBEX_CONTINUE = 1701, /**< OBEX: Continue processing OBEX request */ - OI_OBEX_COMMAND_ERROR = 1702, /**< OBEX: An unrecognized OBEX command opcode */ - OI_OBEX_CONNECTION_TIMEOUT = 1703, /**< OBEX: Timeout waiting for a response to a request */ - OI_OBEX_CONNECT_FAILED = 1704, /**< OBEX: An OBEX connection request did not succeed */ - OI_OBEX_DISCONNECT_FAILED = 1705, /**< OBEX: A disconnect failed probably because the connection did not exist */ - OI_OBEX_ERROR = 1706, /**< OBEX: Unspecified OBEX error */ - OI_OBEX_INCOMPLETE_PACKET = 1707, /**< OBEX: Packet too short or corrupt */ - OI_OBEX_LENGTH_REQUIRED = 1708, /**< OBEX: Length header required in OBEX command */ - OI_OBEX_NOT_CONNECTED = 1709, /**< OBEX: No connection to OBEX server */ - OI_OBEX_NO_MORE_CONNECTIONS = 1710, /**< OBEX: Reached max connections limit */ - OI_OBEX_OPERATION_IN_PROGRESS = 1711, /**< OBEX: Another operation is still in progress on a connection */ - OI_OBEX_PUT_RESPONSE_ERROR = 1712, /**< OBEX: An error in the response to a PUT command */ - OI_OBEX_GET_RESPONSE_ERROR = 1713, /**< OBEX: An error in the response to a GET command */ - OI_OBEX_REQUIRED_HEADER_NOT_FOUND = 1714, /**< OBEX: packet was missing a required header */ - OI_OBEX_SERVICE_UNAVAILABLE = 1715, /**< OBEX: Unown OBEX target or required service */ - OI_OBEX_TOO_MANY_HEADER_BYTES = 1716, /**< OBEX: Headers will not fit in single OBEX packet */ - OI_OBEX_UNKNOWN_COMMAND = 1717, /**< OBEX: Unrecognized OBEX command */ - OI_OBEX_UNSUPPORTED_VERSION = 1718, /**< OBEX: Version mismatch */ - OI_OBEX_CLIENT_ABORTED_COMMAND = 1719, /**< OBEX: server received abort command */ - OI_OBEX_BAD_PACKET = 1720, /**< OBEX: Any malformed OBEX packet */ - OI_OBEX_BAD_REQUEST = 1721, /**< OBEX: Maps to OBEX response of the same name */ - OI_OBEX_OBJECT_OVERFLOW = 1723, /**< OBEX: Too many bytes received. */ - OI_OBEX_NOT_FOUND = 1724, /**< OBEX: Maps to obex response of same name */ - OI_OBEX_ACCESS_DENIED = 1735, /**< OBEX: Object could not be read or written. */ - OI_OBEX_VALUE_NOT_ACCEPTABLE = 1736, /**< OBEX: Value in a command was not in the acceptable range. */ - OI_OBEX_PACKET_OVERFLOW = 1737, /**< OBEX: Buffer will not fit in a single OBEX packet. */ - OI_OBEX_NO_SUCH_FOLDER = 1738, /**< OBEX: Error returned by a setpath operation. */ - OI_OBEX_NAME_REQUIRED = 1739, /**< OBEX: Name must be non-null and non-empty. */ - OI_OBEX_PASSWORD_TOO_LONG = 1740, /**< OBEX: Password exceeds implementation imposed length limit. */ - OI_OBEX_PRECONDITION_FAILED = 1741, /**< OBEX: response Precondition Failed */ - OI_OBEX_UNAUTHORIZED = 1742, /**< OBEX: authentication was not successful. */ - OI_OBEX_NOT_IMPLEMENTED = 1743, /**< OBEX: Unimplemented feature. */ - OI_OBEX_INVALID_AUTH_DIGEST = 1744, /**< OBEX: An authentication digest was bad. */ - OI_OBEX_INVALID_OPERATION = 1745, /**< OBEX: Operation not allowed at this time. */ - OI_OBEX_DATABASE_FULL = 1746, /**< OBEX: Sync database full. */ - OI_OBEX_DATABASE_LOCKED = 1747, /**< OBEX: Sync database locked. */ - OI_OBEX_INTERNAL_SERVER_ERROR = 1748, /**< OBEX: response Internal Server Error */ - OI_OBEX_UNSUPPORTED_MEDIA_TYPE = 1749, /**< OBEX: response Unsupported Media Type */ - OI_OBEX_PARTIAL_CONTENT = 1750, /**< OBEX: response Partial Content */ - OI_OBEX_METHOD_NOT_ALLOWED = 1751, /**< OBEX: response Method Not Allowed */ - OI_OBEXSRV_INCOMPLETE_GET = 1752, /**< OBEX: Indicates to a GET handler that the request phase is still in progress */ - OI_OBEX_FOLDER_BROWSING_NOT_ALLOWED = 1753, /**< OBEX: Indicates that an FTP server does not allow folder browsing */ - OI_OBEX_SERVER_FORCED_DISCONNECT = 1754, /**< OBEX: connection was forcibly terminated by the server */ - OI_OBEX_OFS_ERROR = 1755, /**< OBEX: OPP object file system error occurred */ - OI_OBEX_FILEOP_ERROR = 1756, /**< OBEX: FTP/PBAP file operation system error occurred */ - OI_OBEX_USERID_TOO_LONG = 1757, /**< OBEX: User Id exceeds spec limited length limit. */ - - OI_HANDSFREE_EVENT_REPORTING_DISABLED = 1801, /**< HANDSFREE: Event reporting disabled */ - OI_HANDSFREE_NOT_CONNECTED = 1802, /**< HANDSFREE: Not connected */ - OI_HANDSFREE_SERVICE_NOT_STARTED = 1803, /**< HANDSFREE: Cannot connect to handsfree AG if handsfree service not started */ - OI_HANDSFREE_AG_SERVICE_NOT_STARTED = 1804, /**< HANDSFREE: Cannot connect to handsfree device if handsfree AG service not started */ - OI_HANDSFREE_COMMAND_IN_PROGRESS = 1805, /**< HANDSFREE: Cannot accept a command at this time */ - OI_HANDSFREE_AUDIO_ALREADY_CONNECTED = 1806, /**< HANDSFREE: Audio is already connected */ - OI_HANDSFREE_AUDIO_NOT_CONNECTED = 1807, /**< HANDSFREE: Audio is not connected */ - OI_HANDSFREE_FEATURE_NOT_SUPPORTED = 1808, /**< HANDSFREE: Local or remote feature not supported for requested command */ - - OI_HEADSET_SERVICE_NOT_STARTED = 1901, /**< HEADSET: Cannot connect to headset AG if headset service not started */ - OI_HEADSET_AG_SERVICE_NOT_STARTED = 1902, /**< HEADSET: Cannot connect to headset device if headset AG service not started */ - OI_HEADSET_COMMAND_IN_PROGRESS = 1903, /**< HEADSET: Cannot accept a command at this time */ - - OI_BNEP_INVALID_MTU = 2001, /**< BNEP: The remote device cannot support the minimum BNEP MTU */ - OI_BNEP_SETUP_TIMEOUT = 2002, /**< BNEP: The setup request timed out. */ - OI_BNEP_SERVICE_NOT_REGISTERED = 2003, /**< BNEP: The requested service was not found. */ - OI_BNEP_INVALID_HANDLE = 2004, /**< BNEP: The specified connection handle is not valid. */ - OI_BNEP_RESPONSE_TIMEOUT = 2005, /**< BNEP: The timer for receiving a response has expired. */ - OI_BNEP_INVALID_CONNECTION = 2006, /**< BNEP: Invalid connection */ - OI_BNEP_INVALID_FILTER = 2007, /**< BNEP: The supplied filter was invalid. */ - OI_BNEP_CONNECTION_EXISTS = 2008, /**< BNEP: An attempt was made to create a duplicate connection. */ - OI_BNEP_NOT_INITIALIZED = 2009, /**< BNEP: Init has not been called */ - OI_BNEP_CONNECT_BASE = 2010, /**< BNEP: connection response codes */ - OI_BNEP_CONNECT_FAILED_INVALID_DEST_UUID = 2011, /**< BNEP: connect response code Invalid Dest UUID */ - OI_BNEP_CONNECT_FAILED_INVALID_SOURCE_UUID = 2012, /**< BNEP: connect response code Invalid Source UUID */ - OI_BNEP_CONNECT_FAILED_INVALID_UUID_SIZE = 2013, /**< BNEP: connect response code Invalid UUID Size */ - OI_BNEP_CONNECT_FAILED_NOT_ALLOWED = 2014, /**< BNEP: connect response code Not Allowed */ - OI_BNEP_FILTER_NET_BASE = 2020, /**< BNEP: filter response codes */ - OI_BNEP_FILTER_NET_UNSUPPORTED_REQUEST = 2021, /**< BNEP: filter response code Unsupported Request */ - OI_BNEP_FILTER_NET_FAILED_INVALID_PROTOCOL_TYPE = 2022, /**< BNEP: filter response code Invalid Protocol Type */ - OI_BNEP_FILTER_NET_FAILED_MAX_LIMIT_REACHED = 2023, /**< BNEP: filter response code Max Limit Reached */ - OI_BNEP_FILTER_NET_FAILED_SECURITY = 2024, /**< BNEP: filter response code Security */ - OI_BNEP_FILTER_MULTI_BASE = 2030, /**< BNEP: multicast response codes */ - OI_BNEP_FILTER_MULTI_UNSUPPORTED_REQUEST = 2031, /**< BNEP: multicast response code Unsupported Request */ - OI_BNEP_FILTER_MULTI_FAILED_INVALID_ADDRESS = 2032, /**< BNEP: multicast response code Invalid Address */ - OI_BNEP_FILTER_MULTI_FAILED_MAX_LIMIT_REACHED = 2033, /**< BNEP: multicast response code Max Limit Reached */ - OI_BNEP_FILTER_MULTI_FAILED_SECURITY = 2034, /**< BNEP: multicast response code Security */ - OI_BNEP_LOCAL_DEVICE_MUST_BE_MASTER = 2040, /**< BNEP: Device must be master of the piconet for this function */ - OI_BNEP_PACKET_FILTERED_OUT = 2041, /**< BNEP: Packet did not pass current filters */ - - OI_NETIFC_UP_FAILED = 2101, /**< NETIFC: Could not bring up network interface */ - OI_NETIFC_COULD_NOT_CREATE_THREAD = 2102, /**< NETIFC: Network interface could not create a read thread */ - OI_NETIFC_INITIALIZATION_FAILED = 2103, /**< NETIFC: Error in network interface initialization */ - OI_NETIFC_INTERFACE_ALREADY_UP = 2104, /**< NETIFC: Network interface is already up */ - OI_NETIFC_INTERFACE_NOT_UP = 2105, /**< NETIFC: Network interface is not up */ - OI_NETIFC_PACKET_TOO_BIG = 2106, /**< NETIFC: The packet is too big */ - - OI_PAN_ROLE_ALREADY_REGISTERED = 2201, /**< PAN: This PAN role was already registered */ - OI_PAN_ROLE_NOT_ALLOWED = 2202, /**< PAN: The PAN role is not currently allowed */ - OI_PAN_INCOMPATIBLE_ROLES = 2203, /**< PAN: Only certain local and remote role combinations are permitted */ - OI_PAN_INVALID_ROLE = 2204, /**< PAN: Role specified is not one the defined PAN roles */ - OI_PAN_CONNECTION_IN_PROGRESS = 2205, /**< PAN: A PAN connection is currently being established */ - OI_PAN_USER_ALREADY_CONNECTED = 2206, /**< PAN: PAN user role only allows a single connection */ - OI_PAN_DEVICE_CONNECTED = 2207, /**< PAN: A PAN connection already exists to specified device */ - - OI_CODEC_SBC_NO_SYNCWORD = 2301, /**< CODEC: Couldn't find an SBC SYNCWORD */ - OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA = 2302, /**< CODEC: Not enough data provided to decode an SBC header */ - OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA = 2303, /**< CODEC: Decoded the header, but not enough data to contain the rest of the frame */ - OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA = 2304, /**< CODEC: Not enough audio data for this frame */ - OI_CODEC_SBC_CHECKSUM_MISMATCH = 2305, /**< CODEC: The frame header didn't match the checksum */ - OI_CODEC_SBC_PARTIAL_DECODE = 2306, /**< CODEC: Decoding was successful, but frame data still remains. Next call will provide audio without consuming input data. */ - - OI_FIFOQ_QUEUE_NOT_ALIGNED = 2401, /**< FIFOQ: queue must be 32-bit aligned */ - OI_FIFOQ_INVALID_Q = 2402, /**< FIFOQ: queue parameter is not a valid queue */ - OI_FIFOQ_BUF_TOO_LARGE = 2403, /**< FIFOQ: attempt to queue a buffer which is too large */ - OI_FIFOQ_FULL = 2404, /**< FIFOQ: enqueue() failed, queue is full */ - OI_FIFOQ_NOT_ALLOCATED = 2405, /**< FIFOQ: Enqueue QBuf() failed, buffer not allocated */ - OI_FIFOQ_INVALID_DATA_PTR = 2406, /**< FIFOQ: Enqueue QBuf() failed, data pointer does not match */ - - OI_HID_HOST_SERVICE_NOT_STARTED = 2601, /**< HID: Cannot connect to a HID device unless HID host is started */ - OI_HID_DEVICE_SERVICE_NOT_STARTED = 2602, /**< HID: Cannot connect to a HID host unless HID device is started */ - - OI_AT_ERROR = 2701, /**< AT: ERROR response */ - OI_AT_NO_CARRIER = 2702, /**< AT: NO CARRIER response */ - OI_AT_BUSY = 2703, /**< AT: BUSY response */ - OI_AT_NO_ANSWER = 2704, /**< AT: NO ANSWER response */ - OI_AT_DELAYED = 2705, /**< AT: DELAYED response */ - OI_AT_BLACKLISTED = 2706, /**< AT: BLACKLISTED response */ - OI_AT_CME_ERROR = 2707, /**< AT: +CME ERROR response */ - OI_AT_CMS_ERROR = 2708, /**< AT: +CMS ERROR response */ - - OI_BLST_CHARACTER_TIMEOUT = 2801, /**< BLST: Timeout expired while waiting for a character from the client. */ - OI_BLST_ACKNOWLDGE_TIMEOUT = 2802, /**< BLST: Timeout expired while waiting for event acknowledgment from the client */ - OI_BLST_TX_NOT_READY = 2803, /**< BLST: BLST is not ready to send a BHAPI message to the client. */ - OI_BLST_TX_BUSY = 2804, /**< BLST: BLST transmit buffer is in use. */ - - OI_AVDTP_CONNECTION_SEQ_ERROR = 2901, /**< AVDTP: sequencing of signalling/media channel connections broken. */ - OI_AVDTP_OUT_OF_RESOURCES = 2902, /**< AVDTP: Tried to allocate too many endpoints or signalling channels. */ - - OI_PBAP_REPOSITORY_NOT_SET = 3001, /**< PBAP: Phonebook repository must be set for operation to complete. */ - OI_PBAP_PHONEBOOK_NOT_SET = 3002, /**< PBAP: Phonebook be set for operation to complete. */ - - OI_AADP_BAD_ENDPOINT = 3101, /**< AADP: Invalid local endpoint specified */ - OI_AADP_BAD_STATE = 3102, /**< AADP: AADP State is not correct for this operation. */ - - OI_UNICODE_INVALID_SOURCE = 3200, /**< Unicode Conversion: Source string has invalid character encoding. */ - OI_UNICODE_SOURCE_EXHAUSTED = 3201, /**< Unicode Conversion: Incomplete Unicode character at end of source buffer. */ - OI_UNICODE_DESTINATION_EXHAUSTED = 3202, /**< Unicode Conversion: Destination buffer not large enough to hold resulting Unicode string. */ - - OI_AVRCP_TOO_MANY_CONNECTIONS = 3300, /**< AVRCP: Exceeded maximum number of simultaneous AVCTP connections. */ - OI_AVRCP_NOT_IMPLEMENTED = 3301, /**< AVRCP: The target does not implement the command specified by the opcode and operand. */ - OI_AVRCP_REJECTED = 3302, /**< AVRCP: The target cannot respond because of invalid operands in command packet. */ - OI_AVRCP_INVALID_RESPONSE = 3303, /**< AVRCP: The controller received the response with invalid parameters */ - OI_AVRCP_RESPONSE_PACKET_OVERFLOW = 3304, /**< AVRCP: The response message does not fir in one AVRCP packet (512 bytes), has to be fragmented. */ - OI_AVRCP_RESPONSE_INVALID_PDU = 3305, /**< AVRCP: Command rejected: target received a PDU that it did not understand. */ - OI_AVRCP_RESPONSE_INVALID_PARAMETER = 3306, /**< AVRCP: Command rejected: target received a PDU with a parameter ID that it did not understand. */ - OI_AVRCP_RESPONSE_PARAMETER_NOT_FOUND = 3307, /**< AVRCP: Command rejected: specified parameter not found, sent if the parameter ID is understood, but content is wrong or corrupted.*/ - OI_AVRCP_RESPONSE_INTERNAL_ERROR = 3308, /**< AVRCP: Command rejected: target detected other error conditions. */ - OI_MAX_BM3_STATUS_VAL, /* Maximum BM3 status code */ - - /* Status code values reserved for BM3 SDK platform-specific implementations */ - OI_STATUS_RESERVED_FOR_BCOT = 9000, - - /* Status code values reserved for BHAPI products */ - OI_STATUS_RESERVED_FOR_BHAPI = 9200, - - /* Status code values reserved for Soundabout products */ - OI_STATUS_RESERVED_FOR_SOUNDABOUT = 9400, - - /* - * Status code values greater than or equal to this value are reserved for use by applications. - * However, because of differences between compilers, and differences between 16-bit and 32-bit - * platforms custom status codes should be in the 16-bit range, so status codes can range from 0 - * to 65534, inclusive (65535 is reserved) - */ - OI_STATUS_RESERVED_FOR_APPS = 10000, - - - - OI_STATUS_NONE = 0xffff /**< Special status code to indicate that there is no status. (Only to be used for special cases involving OI_SLOG_ERROR() and OI_SLOG_WARNING().) */ - -} OI_STATUS; - - -/* Remeber to update the #define below when new reserved blocks are added to - * the list above. */ -#define OI_NUM_RESERVED_STATUS_BLOCKS 4 /**< Number of status code blocks reserved, including user apps */ - - -/** - * Test for success - */ -#define OI_SUCCESS(x) ((x) == OI_OK) - -/*****************************************************************************/ -#ifdef __cplusplus -} -#endif - -/**@}*/ - -#endif /* _OI_STATUS_H */ - diff --git a/tools/sdk/include/bluedroid/oi_stddefs.h b/tools/sdk/include/bluedroid/oi_stddefs.h deleted file mode 100644 index 9ab424db2e5..00000000000 --- a/tools/sdk/include/bluedroid/oi_stddefs.h +++ /dev/null @@ -1,232 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 OI_STDDEFS_H -#define OI_STDDEFS_H -/** - * @file - * This file contains BM3 standard type definitions. - * - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#include "oi_cpu_dep.h" - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef FALSE -#define FALSE 0 /**< This define statement sets FALSE as a preprocessor alias for 0. */ -#endif - -#ifndef TRUE -#define TRUE (!FALSE) /**< This define statement sets TRUE as a preprocessor alias for !FALSE. */ -#endif - -#ifdef HEW_TOOLCHAIN -#ifdef NULL -#undef NULL /**< Override HEW toolchain NULL definition */ -#endif -#define NULL 0 /**< HEW toolchain does not allow us to compare (void*) type to function pointer */ -#else -#ifndef NULL -#define NULL ((void*)0) /**< This define statement sets NULL as a preprocessor alias for (void*)0 */ -#endif -#endif - -/** - * @name Maximum and minimum values for basic types - * @{ - */ -#define OI_INT8_MIN ((OI_INT8)0x80) /**< decimal value: -128 */ -#define OI_INT8_MAX ((OI_INT8)0x7F) /**< decimal value: 127 */ -#define OI_INT16_MIN ((OI_INT16)0x8000) /**< decimal value: -32768 */ -#define OI_INT16_MAX ((OI_INT16)0x7FFF) /**< decimal value: 32767 */ -#define OI_INT32_MIN ((OI_INT32)0x80000000) /**< decimal value: -2,147,483,648 */ -#define OI_INT32_MAX ((OI_INT32)0x7FFFFFFF) /**< decimal value: 2,147,483,647 */ -#define OI_UINT8_MIN ((OI_UINT8)0) /**< decimal value: 0 */ -#define OI_UINT8_MAX ((OI_UINT8)0xFF) /**< decimal value: 255 */ -#define OI_UINT16_MIN ((OI_UINT16)0) /**< decimal value: 0 */ -#define OI_UINT16_MAX ((OI_UINT16)0xFFFF) /**< decimal value: 65535 */ -#define OI_UINT32_MIN ((OI_UINT32)0) /**< decimal value: 0 */ -#define OI_UINT32_MAX ((OI_UINT32)0xFFFFFFFF) /**< decimal value: 4,294,967,295 */ - -/** - * @} - */ - -/** - * @name Integer types required by the Service Discovery Protocol - * @{ - */ - -/** unsigned 64-bit integer as a structure of two unsigned 32-bit integers */ -typedef struct { - OI_UINT32 I1; /**< most significant 32 bits */ - OI_UINT32 I2; /**< least significant 32 bits */ -} OI_UINT64; - -#define OI_UINT64_MIN { (OI_UINT32)0x00000000, (OI_UINT32)0x00000000 } -#define OI_UINT64_MAX { (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF } - -/** signed 64-bit integer as a structure of one unsigned 32-bit integer and one signed 32-bit integer */ -typedef struct { - OI_INT32 I1; /**< most significant 32 bits as a signed integer */ - OI_UINT32 I2; /**< least significant 32 bits as an unsigned integer */ -} OI_INT64; - -#define OI_INT64_MIN { (OI_INT32)0x80000000, (OI_UINT32)0x00000000 } -#define OI_INT64_MAX { (OI_INT32)0X7FFFFFFF, (OI_UINT32)0XFFFFFFFF } - -/** unsigned 128-bit integer as a structure of four unsigned 32-bit integers */ -typedef struct { - OI_UINT32 I1; /**< most significant 32 bits */ - OI_UINT32 I2; /**< second-most significant 32 bits */ - OI_UINT32 I3; /**< third-most significant 32 bits */ - OI_UINT32 I4; /**< least significant 32 bits */ -} OI_UINT128; - -#define OI_UINT128_MIN { (OI_UINT32)0x00000000, (OI_UINT32)0x00000000, (OI_UINT32)0x00000000, (OI_UINT32)0x00000000 } -#define OI_UINT128_MAX { (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF } - -/** signed 128-bit integer as a structure of three unsigned 32-bit integers and one signed 32-bit integer */ -typedef struct { - OI_INT32 I1; /**< most significant 32 bits as a signed integer */ - OI_UINT32 I2; /**< second-most significant 32 bits as an unsigned integer */ - OI_UINT32 I3; /**< third-most significant 32 bits as an unsigned integer */ - OI_UINT32 I4; /**< least significant 32 bits as an unsigned integer */ -} OI_INT128; - -#define OI_INT128_MIN { (OI_UINT32)0x80000000, (OI_UINT32)0x00000000, (OI_UINT32)0x00000000, (OI_UINT32)0x00000000 } -#define OI_INT128_MAX { (OI_UINT32)0X7FFFFFFF, (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF } - -/** - * @} - */ - - -/** - * type for ASCII character data items - */ -typedef char OI_CHAR; - -/** - * type for double-byte character data items - */ -typedef OI_UINT16 OI_CHAR16; - -/** - * types for UTF encoded strings. - */ -typedef OI_UINT8 OI_UTF8; -typedef OI_UINT16 OI_UTF16; -typedef OI_UINT32 OI_UTF32; - - -/** - * @name Single-bit operation macros - * @{ - * In these macros, x is the data item for which a bit is to be tested or set and y specifies which bit - * is to be tested or set. - */ - -/** This macro's value is TRUE if the bit specified by y is set in data item x. */ -#define OI_BIT_TEST(x,y) ((x) & (y)) - -/** This macro's value is TRUE if the bit specified by y is not set in data item x. */ -#define OI_BIT_CLEAR_TEST(x,y) (((x) & (y)) == 0) - -/** This macro sets the bit specified by y in data item x. */ -#define OI_BIT_SET(x,y) ((x) |= (y)) - -/** This macro clears the bit specified by y in data item x. */ -#define OI_BIT_CLEAR(x,y) ((x) &= ~(y)) - -/** @} */ - -/** - * The OI_ARRAYSIZE macro is set to the number of elements in an array - * (instead of the number of bytes, which is returned by sizeof()). - */ - -#ifndef OI_ARRAYSIZE -#define OI_ARRAYSIZE(a) (sizeof(a)/sizeof(a[0])) -#endif - -/** - * @name Preprocessor aliases for individual bit positions - * Bits are defined here only if they are not already defined. - * @{ - */ - -#ifndef BIT0 - -#define BIT0 0x00000001 /**< preprocessor alias for 32-bit value with bit 0 set, used to specify this single bit */ -#define BIT1 0x00000002 /**< preprocessor alias for 32-bit value with bit 1 set, used to specify this single bit */ -#define BIT2 0x00000004 /**< preprocessor alias for 32-bit value with bit 2 set, used to specify this single bit */ -#define BIT3 0x00000008 /**< preprocessor alias for 32-bit value with bit 3 set, used to specify this single bit */ -#define BIT4 0x00000010 /**< preprocessor alias for 32-bit value with bit 4 set, used to specify this single bit */ -#define BIT5 0x00000020 /**< preprocessor alias for 32-bit value with bit 5 set, used to specify this single bit */ -#define BIT6 0x00000040 /**< preprocessor alias for 32-bit value with bit 6 set, used to specify this single bit */ -#define BIT7 0x00000080 /**< preprocessor alias for 32-bit value with bit 7 set, used to specify this single bit */ -#define BIT8 0x00000100 /**< preprocessor alias for 32-bit value with bit 8 set, used to specify this single bit */ -#define BIT9 0x00000200 /**< preprocessor alias for 32-bit value with bit 9 set, used to specify this single bit */ -#define BIT10 0x00000400 /**< preprocessor alias for 32-bit value with bit 10 set, used to specify this single bit */ -#define BIT11 0x00000800 /**< preprocessor alias for 32-bit value with bit 11 set, used to specify this single bit */ -#define BIT12 0x00001000 /**< preprocessor alias for 32-bit value with bit 12 set, used to specify this single bit */ -#define BIT13 0x00002000 /**< preprocessor alias for 32-bit value with bit 13 set, used to specify this single bit */ -#define BIT14 0x00004000 /**< preprocessor alias for 32-bit value with bit 14 set, used to specify this single bit */ -#define BIT15 0x00008000 /**< preprocessor alias for 32-bit value with bit 15 set, used to specify this single bit */ -#define BIT16 0x00010000 /**< preprocessor alias for 32-bit value with bit 16 set, used to specify this single bit */ -#define BIT17 0x00020000 /**< preprocessor alias for 32-bit value with bit 17 set, used to specify this single bit */ -#define BIT18 0x00040000 /**< preprocessor alias for 32-bit value with bit 18 set, used to specify this single bit */ -#define BIT19 0x00080000 /**< preprocessor alias for 32-bit value with bit 19 set, used to specify this single bit */ -#define BIT20 0x00100000 /**< preprocessor alias for 32-bit value with bit 20 set, used to specify this single bit */ -#define BIT21 0x00200000 /**< preprocessor alias for 32-bit value with bit 21 set, used to specify this single bit */ -#define BIT22 0x00400000 /**< preprocessor alias for 32-bit value with bit 22 set, used to specify this single bit */ -#define BIT23 0x00800000 /**< preprocessor alias for 32-bit value with bit 23 set, used to specify this single bit */ -#define BIT24 0x01000000 /**< preprocessor alias for 32-bit value with bit 24 set, used to specify this single bit */ -#define BIT25 0x02000000 /**< preprocessor alias for 32-bit value with bit 25 set, used to specify this single bit */ -#define BIT26 0x04000000 /**< preprocessor alias for 32-bit value with bit 26 set, used to specify this single bit */ -#define BIT27 0x08000000 /**< preprocessor alias for 32-bit value with bit 27 set, used to specify this single bit */ -#define BIT28 0x10000000 /**< preprocessor alias for 32-bit value with bit 28 set, used to specify this single bit */ -#define BIT29 0x20000000 /**< preprocessor alias for 32-bit value with bit 29 set, used to specify this single bit */ -#define BIT30 0x40000000 /**< preprocessor alias for 32-bit value with bit 30 set, used to specify this single bit */ -#define BIT31 0x80000000 /**< preprocessor alias for 32-bit value with bit 31 set, used to specify this single bit */ - -#endif /* BIT0 et al */ - - -/** @} */ - - -#ifdef __cplusplus -} -#endif - -/**@}*/ - -/*****************************************************************************/ -#endif /* OI_STDDEFS_H */ diff --git a/tools/sdk/include/bluedroid/oi_string.h b/tools/sdk/include/bluedroid/oi_string.h deleted file mode 100644 index 928acb07df4..00000000000 --- a/tools/sdk/include/bluedroid/oi_string.h +++ /dev/null @@ -1,208 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 OI_STRING_H -#define OI_STRING_H -/** - * @file - * This file contains BM3 supplied portable string.h functions - * - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#include "oi_cpu_dep.h" -#include "oi_stddefs.h" - -#if defined(USE_NATIVE_MEMCPY) || defined(USE_NATIVE_MALLOC) -#include -#endif - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - - -/* - * If we are using Native malloc(), we must also use - * native Ansi string.h functions for memory manipulation. - */ -#ifdef USE_NATIVE_MALLOC -#ifndef USE_NATIVE_MEMCPY -#define USE_NATIVE_MEMCPY -#endif -#endif - -#ifdef USE_NATIVE_MEMCPY - -#define OI_MemCopy(to, from, size) memcpy((to), (from), (size)) -#define OI_MemSet(block, val, size) memset((block), (val), (size)) -#define OI_MemZero(block, size) memset((block), 0, (size)) -#define OI_MemCmp(s1, s2, n) memcmp((s1), (s2), (n)) -#define OI_Strcpy(dest, src) strcpy((dest),(src)) -#define OI_Strcat(dest, src) strcat((dest),(src)) -#define OI_StrLen(str) strlen((str)) -#define OI_Strcmp(s1, s2) strcmp((s1), (s2)) -#define OI_Strncmp(s1, s2, n) strncmp((s1), (s2), (n)) - -#else - -/* - * OI_MemCopy - * - * Copy an arbitrary number of bytes from one memory address to another. - * The underlying implementation is the ANSI memmove() or equivalant, so - * overlapping memory copies will work correctly. - */ -void OI_MemCopy(void *To, void const *From, OI_UINT32 Size); - - -/* - * OI_MemSet - * - * Sets all bytes in a block of memory to the same value - */ -void OI_MemSet(void *Block, OI_UINT8 Val, OI_UINT32 Size); - - -/* - * OI_MemZero - * - * Sets all bytes in a block of memory to zero - */ -void OI_MemZero(void *Block, OI_UINT32 Size); - - -/* - * OI_MemCmp - * - * Compare two blocks of memory - * - * Returns: - * 0, if s1 == s2 - * < 0, if s1 < s2 - * > 0, if s2 > s2 - */ -OI_INT OI_MemCmp(void const *s1, void const *s2, OI_UINT32 n); - -/* - * OI_Strcpy - * - * Copies the Null terminated string from pStr to pDest, and - * returns pDest. - */ - -OI_CHAR *OI_Strcpy(OI_CHAR *pDest, - OI_CHAR const *pStr); - -/* - * OI_Strcat - * - * Concatonates the pStr string to the end of pDest, and - * returns pDest. - */ - -OI_CHAR *OI_Strcat(OI_CHAR *pDest, - OI_CHAR const *pStr) ; - -/* - * OI_StrLen - * - * Calculates the number of OI_CHARs in pStr (not including - * the Null terminator) and returns the value. - */ -OI_UINT OI_StrLen(OI_CHAR const *pStr) ; - -/* - * OI_Strcmp - * - * Compares two Null terminated strings - * - * Returns: - * 0, if s1 == s2 - * < 0, if s1 < s2 - * > 0, if s2 > s2 - */ -OI_INT OI_Strcmp(OI_CHAR const *s1, - OI_CHAR const *s2); - -/* - * OI_Strncmp - * - * Compares the first "len" OI_CHARs of strings s1 and s2. - * - * Returns: - * 0, if s1 == s2 - * < 0, if s1 < s2 - * > 0, if s2 > s2 - */ -OI_INT OI_Strncmp(OI_CHAR const *s1, - OI_CHAR const *s2, - OI_UINT32 len); - - -#endif /* USE_NATIVE_MEMCPY */ - -/* - * OI_StrcmpInsensitive - * - * Compares two Null terminated strings, treating - * the Upper and Lower case of 'A' through 'Z' as - * equivilent. - * - * Returns: - * 0, if s1 == s2 - * < 0, if s1 < s2 - * > 0, if s2 > s2 - */ -OI_INT OI_StrcmpInsensitive(OI_CHAR const *s1, - OI_CHAR const *s2); - -/* - * OI_StrncmpInsensitive - * - * Compares the first "len" OI_CHARs of strings s1 and s2, - * treating the Upper and Lower case of 'A' through 'Z' as - * equivilent. - * - * - * Returns: - * 0, if s1 == s2 - * < 0, if s1 < s2 - * > 0, if s2 > s2 - */ -OI_INT OI_StrncmpInsensitive(OI_CHAR const *s1, - OI_CHAR const *s2, - OI_UINT len); - - - -#ifdef __cplusplus -} -#endif - -/** @} */ - -/*****************************************************************************/ -#endif /* OI_STRING_H */ - diff --git a/tools/sdk/include/bluedroid/oi_time.h b/tools/sdk/include/bluedroid/oi_time.h deleted file mode 100644 index 40b8dfc4d73..00000000000 --- a/tools/sdk/include/bluedroid/oi_time.h +++ /dev/null @@ -1,200 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_TIME_H -#define _OI_TIME_H -/** @file - * - * This file provides time type definitions and interfaces to time-related functions. - * - * The stack maintains a 64-bit real-time millisecond clock. The choice of - * milliseconds is for convenience, not accuracy. - * - * Timeouts are specified as tenths of seconds in a 32-bit value. Timeout values - * specified by the Bluetooth specification are usually muliple seconds, so - * accuracy to a tenth of a second is more than adequate. - * - * This file also contains macros to convert between seconds and the Link - * Manager's 1.28-second units. - * - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#include "oi_stddefs.h" - - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -/** - * Within the core stack timeouts are specified in intervals of tenths of seconds - */ - -typedef OI_UINT16 OI_INTERVAL; -#define OI_INTERVALS_PER_SECOND 10 -#define MSECS_PER_OI_INTERVAL (1000 / OI_INTERVALS_PER_SECOND) - -/** maximum interval (54 min 36.7 sec) */ -#define OI_MAX_INTERVAL 0x7fff - - -/** - * Macro to convert seconds to OI_INTERVAL time units - */ - -#define OI_SECONDS(n) ((OI_INTERVAL) ((n) * OI_INTERVALS_PER_SECOND)) - -/** - * Macro to convert milliseconds to OI_INTERVAL time units (Rounded Up) - */ - -#define OI_MSECONDS(n) ((OI_INTERVAL) ((n + MSECS_PER_OI_INTERVAL - 1) / MSECS_PER_OI_INTERVAL)) - -/** - * Macro to convert minutes to OI_INTERVAL time units - */ - -#define OI_MINUTES(n) ((OI_INTERVAL) ((n) * OI_SECONDS(60))) - -/** Convert an OI_INTERVAL to milliseconds. */ -#define OI_INTERVAL_TO_MILLISECONDS(i) ((i) * MSECS_PER_OI_INTERVAL) - -/** - * The stack depends on relative not absolute time. Any mapping between the - * stack's real-time clock and absolute time and date is implementation-dependent. - */ - -typedef struct { - OI_INT32 seconds; - OI_INT16 mseconds; -} OI_TIME; - -/** - * Convert an OI_TIME to milliseconds. - * - * @param t the time to convert - * - * @return the time in milliseconds - */ -OI_UINT32 OI_Time_ToMS(OI_TIME *t); - - -/** - * This function compares two time values. - * - * @param T1 first time to compare. - * - * @param T2 second time to compare. - * - * @return - @verbatim - -1 if t1 < t2 - 0 if t1 = t2 - +1 if t1 > t2 - @endverbatim - */ - -OI_INT16 OI_Time_Compare(OI_TIME *T1, - OI_TIME *T2); - - -/** - * This function returns the interval between two times to a granularity of 0.1 seconds. - * - * @param Sooner a time value more recent that Later - * - * @param Later a time value later than Sooner - * - * @note The result is an OI_INTERVAL value so this function only works for time intervals - * that are less than about 71 minutes. - * - * @return the time interval between the two times = (Later - Sooner) - */ - -OI_INTERVAL OI_Time_Interval(OI_TIME *Sooner, - OI_TIME *Later); - - - -/** - * This function returns the interval between two times to a granularity of milliseconds. - * - * @param Sooner a time value more recent that Later - * - * @param Later a time value later than Sooner - * - * @note The result is an OI_UINT32 value so this function only works for time intervals - * that are less than about 50 days. - * - * @return the time interval between the two times = (Later - Sooner) - */ - -OI_UINT32 OI_Time_IntervalMsecs(OI_TIME *Sooner, - OI_TIME *Later); - - - -/** - * This function answers the question, Have we reached or gone past the target time? - * - * @param pTargetTime target time - * - * @return TRUE means time now is at or past target time - * FALSE means target time is still some time in the future - */ - -OI_BOOL OI_Time_NowReachedTime(OI_TIME *pTargetTime); - -/** - * Convert seconds to the Link Manager 1.28-second units - * Approximate by using 1.25 conversion factor. - */ - -#define OI_SECONDS_TO_LM_TIME_UNITS(lmUnits) ((lmUnits)<4?(lmUnits):(lmUnits)-((lmUnits)>>2)) - - -/** - * Convert Link Manager 1.28-second units to seconds. - * Approximate by using 1.25 conversion factor. - */ - -#define OI_LM_TIME_UNITS_TO_SECONDS(lmUnits) ((lmUnits) + ((lmUnits)>>2)) - -#ifdef __cplusplus -} -#endif - -/**@}*/ - -/* Include for OI_Time_Now() prototype - * Must be included at end to obtain OI_TIME typedef - */ -#include "oi_osinterface.h" - -/*****************************************************************************/ -#endif /* _OI_TIME_H */ - diff --git a/tools/sdk/include/bluedroid/oi_utils.h b/tools/sdk/include/bluedroid/oi_utils.h deleted file mode 100644 index f12ef0d4bc2..00000000000 --- a/tools/sdk/include/bluedroid/oi_utils.h +++ /dev/null @@ -1,377 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 The Android Open Source Project - * Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _OI_UTILS_H -#define _OI_UTILS_H -/** - * @file - * - * This file provides the interface for utility functions. - * Among the utilities are strlen (string length), strcmp (string compare), and - * other string manipulation functions. These are provided for those plaforms - * where this functionality is not available in stdlib. - */ - -/********************************************************************************** - $Revision: #1 $ -***********************************************************************************/ - -#include -#include "oi_common.h" -#include "oi_string.h" -#include "oi_bt_spec.h" - -/** \addtogroup Misc Miscellaneous APIs */ -/**@{*/ - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Opaque type for a callback function handle. See OI_ScheduleCallbackFunction() - */ -typedef OI_UINT32 OI_CALLBACK_HANDLE; - - -/** - * Function prototype for a timed procedure callback. - * - * @param arg Value that was passed into the OI_ScheduleCallback() function - * - */ -typedef void (*OI_SCHEDULED_CALLBACK)(void *arg); - - -/** - * Registers a function to be called when a timeout expires. This API uses BLUEmagic's internal - * function dispatch mechanism, so applications that make extensive use of this facility may need to - * increase the value of DispatchTableSize in the configuration block for the dispatcher (see - * oi_bt_stack_config.h). - * - * @param callbackFunction The function that will be called when the timeout expires - * - * @param arg Value that will be returned as the parameter to the callback function. - * - * @param timeout A timeout expressed in OI_INTERVALs (tenths of seconds). This can be - * zero in which case the callback function will be called as soon as - * possible. - * - * @param handle NULL or a pointer receive the callback handle. - * - * @return OI_OK if the function was reqistered, or an error status. - */ -OI_STATUS OI_ScheduleCallbackFunction(OI_SCHEDULED_CALLBACK callbackFunction, - void *arg, - OI_INTERVAL timeout, - OI_CALLBACK_HANDLE *handle); - - -/** - * Cancels a function registered with OI_ScheduleCallbackFunction() before its timer expires. - * - * @param handle handle returned by OI_ScheduleCallbackFunction(). - * - * @return OI_OK if the function was cancelled, or an error status. - */ -OI_STATUS OI_CancelCallbackFunction(OI_CALLBACK_HANDLE handle); - - -/** - * Registers a function to be called when a timeout expires. This version does not return a handle - * so can only be canceled by calling OI_CancelCallback(). - * - * @param callbackFunction The function that will be called when the timeout expires - * - * @param arg Value that will be returned as the parameter to the callback function. - * - * @param timeout A timeout expressed in OI_INTERVALs (tenths of seconds). This can be - * zero in which case the callback function will be called as soon as - * possible. - * - * @return OI_OK if the function was reqistered, or an error status. - */ -#define OI_ScheduleCallback(f, a, t) OI_ScheduleCallbackFunction(f, a, t, NULL); - - -/** - * Cancels a function registered with OI_ScheduleCallback() before its timer expires. This - * function will cancel the first entry matches the indicated callback function pointer. - * - * @param callbackFunction The function that was originally registered - * - * @return OI_OK if the function was cancelled, or an error status. - */ -OI_STATUS OI_CancelCallback(OI_SCHEDULED_CALLBACK callbackFunction); - - -/** - * Parse a Bluetooth device address from the specified string. - * - * @param str the string to parse - * @param addr the parsed address, if successful - * - * @return TRUE if an address was successfully parsed, FALSE otherwise - */ - -OI_BOOL OI_ParseBdAddr(const OI_CHAR *str, - OI_BD_ADDR *addr) ; - -/** - * Printf function for platforms which have no stdio or printf available. - * OI_Printf supports the basic formatting types, with the exception of - * floating point types. Additionally, OI_Printf supports several formats - * specific to BLUEmagic 3.0 software: - * - * \%! prints the string for an #OI_STATUS value. - * @code OI_Printf("There was an error %!", status); @endcode - * - * \%@ prints a hex dump of a buffer. - * Requires a pointer to the buffer and a signed integer length - * (0 for default length). If the buffer is large, only an excerpt will - * be printed. - * @code OI_Printf("Contents of buffer %@", buffer, sizeof(buffer)); @endcode - * - * \%: prints a Bluetooth address in the form "HH:HH:HH:HH:HH:HH". - * Requires a pointer to an #OI_BD_ADDR. - * @code OI_Printf("Bluetooth address %:", &bdaddr); @endcode - * - * \%^ decodes and prints a data element as formatted XML. - * Requires a pointer to an #OI_DATAELEM. - * @code OI_Printf("Service attribute list is:\n%^", &attributes); @endcode - * - * \%/ prints the base file name of a path, that is, the final substring - * following a '/' or '\\' character. Requires a pointer to a null - * terminated string. - * @code OI_Printf("File %/", "c:\\dir1\\dir2\\file.txt"); @endcode - * - * \%~ prints a string, escaping characters as needed to display it in - * ASCII. Requires a pointer to an #OI_PSTR and an #OI_UNICODE_ENCODING - * parameter. - * @code OI_Printf("Identifier %~", &id, OI_UNICODE_UTF16_BE); @endcode - * - * \%[ inserts an ANSI color escape sequence. Requires a single character - * identifying the color to select. Colors are red (r/R), green (g/G), - * blue (b/B), yellow (y/Y), cyan (c/C), magenta (m/M), white (W), - * light-gray (l/L), dark-gray (d/D), and black (0). The lower case is - * dim, the upper case is bright (except in the case of light-gray and - * dark-gray, where bright and dim are identical). Any other value will - * select the default color. - * @code OI_Printf("%[red text %[black %[normal\n", 'r', '0', 0); @endcode - * - * \%a same as \%s, except '\\r' and '\\n' are output as "" and "". - * \%?a is valid, but \%la is not. - * - * \%b prints an integer in base 2. - * @code OI_Printf("Bits are %b", I); @endcode - * - * \%lb prints a long integer in base 2. - * - * \%?b prints the least significant N bits of an integer (or long integer) - * in base 2. Requires the integer and a length N. - * @code OI_Printf("Bottom 4 bits are: %?b", I, 4); @endcode - * - * \%B prints an integer as boolean text, "TRUE" or "FALSE". - * @code OI_Printf("The value 0 is %B, the value 1 is %B", 0, 1); @endcode - * - * \%?s prints a substring up to a specified maximum length. - * Requires a pointer to a string and a length parameter. - * @code OI_Printf("String prefix is %?s", str, 3); @endcode - * - * \%ls same as \%S. - * - * \%S prints a UTF16 string as UTF8 (plain ASCII, plus 8-bit char sequences - * where needed). Requires a pointer to #OI_CHAR16. \%?S is valid. The - * length parameter is in OI_CHAR16 characters. - * - * \%T prints time, formatted as "secs.msecs". - * Requires pointer to #OI_TIME struct, NULL pointer prints current time. - * @code OI_Printf("The time now is %T", NULL); @endcode - * - * @param format The format string - * - */ -void OI_Printf(const OI_CHAR *format, ...); - - -/** - * Var-args version OI_Printf - * - * @param format Same as for OI_Printf. - * - * @param argp Var-args list. - */ -void OI_VPrintf(const OI_CHAR *format, va_list argp); - - -/** - * Writes a formatted string to a buffer. This function supports the same format specifiers as - * OI_Printf(). - * - * @param buffer Destination buffer for the formatted string. - * - * @param bufLen The length of the destination buffer. - * - * @param format The format string - * - * @return Number of characters written or -1 in the case of an error. - */ -OI_INT32 OI_SNPrintf(OI_CHAR *buffer, - OI_UINT16 bufLen, - const OI_CHAR *format, ...); - - -/** - * Var-args version OI_SNPrintf - * - * @param buffer Destination buffer for the formatted string. - * - * @param bufLen The length of the destination buffer. - * - * @param format The format string - * - * @param argp Var-args list. - * - * @return Number of characters written or -1 in the case of an error. - */ -OI_INT32 OI_VSNPrintf(OI_CHAR *buffer, - OI_UINT16 bufLen, - const OI_CHAR *format, va_list argp); - - -/** - * Convert a string to an integer. - * - * @param str the string to parse - * - * @return the integer value of the string or 0 if the string could not be parsed - */ -OI_INT OI_atoi(const OI_CHAR *str); - - -/** - * Parse a signed integer in a string. - * - * Skips leading whitespace (space and tabs only) and parses a decimal or hex string. Hex string - * must be prefixed by "0x". Returns pointer to first character following the integer. Returns the - * pointer passed in if the string does not describe an integer. - * - * @param str String to parse. - * - * @param val Pointer to receive the parsed integer value. - * - * @return A pointer to the first character following the integer or the pointer passed in. - */ -const OI_CHAR *OI_ScanInt(const OI_CHAR *str, - OI_INT32 *val); - - -/** - * Parse an unsigned integer in a string. - * - * Skips leading whitespace (space and tabs only) and parses a decimal or hex string. Hex string - * must be prefixed by "0x". Returns pointer to first character following the integer. Returns the - * pointer passed in if the string does not describe an integer. - * - * @param str String to parse. - * - * @param val Pointer to receive the parsed unsigned integer value. - * - * @return A pointer to the first character following the unsigned integer or the pointer passed in. - */ -const OI_CHAR *OI_ScanUInt(const OI_CHAR *str, - OI_UINT32 *val); - -/** - * Parse a whitespace delimited substring out of a string. - * - * @param str Input string to parse. - * @param outStr Buffer to return the substring - * @param len Length of outStr - * - * - * @return A pointer to the first character following the substring or the pointer passed in. - */ -const OI_CHAR *OI_ScanStr(const OI_CHAR *str, - OI_CHAR *outStr, - OI_UINT16 len); - - -/** - * Parse a string for one of a set of alternative value. Skips leading whitespace (space and tabs - * only) and parses text matching one of the alternative strings. Returns pointer to first character - * following the matched text. - * - * @param str String to parse. - * - * @param alts Alternative matching strings separated by '|' - * - * @param index Pointer to receive the index of the matching alternative, return value is -1 if - * there is no match. - * - * @return A pointer to the first character following the matched value or the pointer passed in - * if there was no matching text. - */ -const OI_CHAR *OI_ScanAlt(const OI_CHAR *str, - const OI_CHAR *alts, - OI_INT *index); - -/** - * Parse a string for a BD Addr. Skips leading whitespace (space and tabs only) and parses a - * Bluetooth device address with nibbles optionally separated by colons. Return pointet to first - * character following the BD Addr. - * - * @param str String to parse. - * - * @param addr Pointer to receive the Bluetooth device address - * - * @return A pointer to the first character following the BD Addr or the pointer passed in. - */ -const OI_CHAR *OI_ScanBdAddr(const OI_CHAR *str, - OI_BD_ADDR *addr); - - -/** Get a character from a digit integer value (0 - 9). */ -#define OI_DigitToChar(d) ((d) + '0') - -/** - * Determine Maximum and Minimum between two arguments. - * - * @param a 1st value - * @param b 2nd value - * - * @return the max or min value between a & b - */ -#define OI_MAX(a, b) (((a) < (b)) ? (b) : (a) ) -#define OI_MIN(a, b) (((a) > (b)) ? (b) : (a) ) - -/** - * Compare two BD_ADDRs - * SAME_BD_ADDR - Boolean: TRUE if they are the same address - */ - -#define SAME_BD_ADDR(x, y) (0 == OI_MemCmp((x),(y),OI_BD_ADDR_BYTE_SIZE) ) - -#ifdef __cplusplus -} -#endif - -/**@}*/ - -#endif /* _OI_UTILS_H */ - diff --git a/tools/sdk/include/bluedroid/osi.h b/tools/sdk/include/bluedroid/osi.h deleted file mode 100644 index 3bd217af3eb..00000000000 --- a/tools/sdk/include/bluedroid/osi.h +++ /dev/null @@ -1,16 +0,0 @@ - -#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/include/bluedroid/p_256_ecc_pp.h b/tools/sdk/include/bluedroid/p_256_ecc_pp.h deleted file mode 100644 index 029a79ff160..00000000000 --- a/tools/sdk/include/bluedroid/p_256_ecc_pp.h +++ /dev/null @@ -1,65 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2006-2015 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains simple pairing algorithms using Elliptic Curve Cryptography for private public key - * - ******************************************************************************/ - -#pragma once - -#include "p_256_multprecision.h" - -typedef unsigned long DWORD; - -typedef struct { - DWORD x[KEY_LENGTH_DWORDS_P256]; - DWORD y[KEY_LENGTH_DWORDS_P256]; - DWORD z[KEY_LENGTH_DWORDS_P256]; -} Point; - -typedef struct { - // curve's coefficients - DWORD a[KEY_LENGTH_DWORDS_P256]; - DWORD b[KEY_LENGTH_DWORDS_P256]; - - //whether a is -3 - int a_minus3; - - // prime modulus - DWORD p[KEY_LENGTH_DWORDS_P256]; - - // Omega, p = 2^m -omega - DWORD omega[KEY_LENGTH_DWORDS_P256]; - - // base point, a point on E of order r - Point G; - -} elliptic_curve_t; - -extern elliptic_curve_t curve; -extern elliptic_curve_t curve_p256; - -void ECC_PointMult_Bin_NAF(Point *q, Point *p, DWORD *n, uint32_t keyLength); - -#define ECC_PointMult(q, p, n, keyLength) ECC_PointMult_Bin_NAF(q, p, n, keyLength) - -void p_256_init_curve(UINT32 keyLength); - - diff --git a/tools/sdk/include/bluedroid/p_256_multprecision.h b/tools/sdk/include/bluedroid/p_256_multprecision.h deleted file mode 100644 index ac32320aad6..00000000000 --- a/tools/sdk/include/bluedroid/p_256_multprecision.h +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2006-2015 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains simple pairing algorithms - * - ******************************************************************************/ -#pragma once - -#include "bt_types.h" - -/* Type definitions */ -typedef unsigned long DWORD; - -#define DWORD_BITS 32 -#define DWORD_BYTES 4 -#define DWORD_BITS_SHIFT 5 - -#define KEY_LENGTH_DWORDS_P192 6 -#define KEY_LENGTH_DWORDS_P256 8 -/* Arithmetic Operations */ - -int multiprecision_compare(DWORD *a, DWORD *b, uint32_t keyLength); -int multiprecision_iszero(DWORD *a, uint32_t keyLength); -void multiprecision_init(DWORD *c, uint32_t keyLength); -void multiprecision_copy(DWORD *c, DWORD *a, uint32_t keyLength); -UINT32 multiprecision_dword_bits (DWORD a); -UINT32 multiprecision_most_signdwords(DWORD *a, uint32_t keyLength); -UINT32 multiprecision_most_signbits(DWORD *a, uint32_t keyLength); -void multiprecision_inv_mod(DWORD *aminus, DWORD *a, uint32_t keyLength); -DWORD multiprecision_add(DWORD *c, DWORD *a, DWORD *b, uint32_t keyLength); // c=a+b -void multiprecision_add_mod(DWORD *c, DWORD *a, DWORD *b, uint32_t keyLength); -DWORD multiprecision_sub(DWORD *c, DWORD *a, DWORD *b, uint32_t keyLength); // c=a-b -void multiprecision_sub_mod(DWORD *c, DWORD *a, DWORD *b, uint32_t keyLength); -void multiprecision_rshift(DWORD *c, DWORD *a, uint32_t keyLength); // c=a>>1, return carrier -void multiprecision_lshift_mod(DWORD *c, DWORD *a, uint32_t keyLength); // c=a<> RFCOMM_SHIFT_CR; \ - dlci = *p_data++ >> RFCOMM_SHIFT_DLCI; \ - if (!ea) dlci += *p_data++ << RFCOMM_SHIFT_DLCI2; \ -} - -#define RFCOMM_FORMAT_CTRL_FIELD(p_data, ea, cr, dlci) \ - *p_data++ = ea | cr | (dlci << RFCOMM_SHIFT_DLCI) - -#define RFCOMM_PARSE_TYPE_FIELD(type, pf, p_data) \ -{ \ - type = *p_data & ~RFCOMM_PF_MASK; \ - pf = (*p_data++ & RFCOMM_PF_MASK) >> RFCOMM_PF_OFFSET;\ -} - -#define RFCOMM_FORMAT_TYPE_FIELD(p_data, type, pf) \ - *p_data++ = (type | (pf << RFCOMM_PF_OFFSET)) \ -{ \ - type = *p_data & ~RFCOMM_PF_MASK; \ - pf = (*p_data++ & RFCOMM_PF_MASK) >> RFCOMM_PF_OFFSET;\ -} - -#define RFCOMM_PARSE_LEN_FIELD(ea, length, p_data) \ -{ \ - ea = (*p_data & RFCOMM_EA); \ - length = (*p_data++ >> RFCOMM_SHIFT_LENGTH1); \ - if (!ea) length += (*p_data++ << RFCOMM_SHIFT_LENGTH2); \ -} - -#define RFCOMM_FRAME_IS_CMD(initiator, cr) \ - (( (initiator) && !(cr)) || (!(initiator) && (cr))) - -#define RFCOMM_FRAME_IS_RSP(initiator, cr) \ - (( (initiator) && (cr)) || (!(initiator) && !(cr))) - -#define RFCOMM_CR(initiator, is_command) \ - (( ( (initiator) && (is_command)) \ - || (!(initiator) && !(is_command))) << 1) - -#define RFCOMM_I_CR(is_command) ((is_command) ? 0x02 : 0x00) - -#define RFCOMM_MAX_DLCI 61 - -#define RFCOMM_VALID_DLCI(dlci) \ - (((dlci) == 0) || (((dlci) >= 2) && ((dlci) <= RFCOMM_MAX_DLCI))) - - -/* Port Negotiation (PN) */ -#define RFCOMM_PN_DLCI_MASK 0x3F - -#define RFCOMM_PN_FRAM_TYPE_UIH 0x00 -#define RFCOMM_PN_FRAME_TYPE_MASK 0x0F - -#define RFCOMM_PN_CONV_LAYER_MASK 0xF0 -#define RFCOMM_PN_CONV_LAYER_TYPE_1 0 -#define RFCOMM_PN_CONV_LAYER_CBFC_I 0xF0 -#define RFCOMM_PN_CONV_LAYER_CBFC_R 0xE0 - -#define RFCOMM_PN_PRIORITY_MASK 0x3F -#define RFCOMM_PN_PRIORITY_0 0 - -#define RFCOMM_PN_K_MASK 0x07 - -#define RFCOMM_T1_DSEC 0 /* None negotiable in RFCOMM */ -#define RFCOMM_N2 0 /* Number of retransmissions */ -#define RFCOMM_K 0 /* Window size */ -#define RFCOMM_K_MAX 7 /* Max value of K for credit based flow control */ - -#define RFCOMM_MSC_FC 0x02 /* Flow control*/ -#define RFCOMM_MSC_RTC 0x04 /* Ready to communicate*/ -#define RFCOMM_MSC_RTR 0x08 /* Ready to receive*/ -#define RFCOMM_MSC_IC 0x40 /* Incomming call indicator*/ -#define RFCOMM_MSC_DV 0x80 /* Data Valid*/ - -#define RFCOMM_MSC_SHIFT_BREAK 4 -#define RFCOMM_MSC_BREAK_MASK 0xF0 -#define RFCOMM_MSC_BREAK_PRESENT_MASK 0x02 - -#define RFCOMM_BAUD_RATE_2400 0x00 -#define RFCOMM_BAUD_RATE_4800 0x01 -#define RFCOMM_BAUD_RATE_7200 0x02 -#define RFCOMM_BAUD_RATE_9600 0x03 -#define RFCOMM_BAUD_RATE_19200 0x04 -#define RFCOMM_BAUD_RATE_38400 0x05 -#define RFCOMM_BAUD_RATE_57600 0x06 -#define RFCOMM_BAUD_RATE_115200 0x07 -#define RFCOMM_BAUD_RATE_230400 0x08 - -#define RFCOMM_5_BITS 0x00 -#define RFCOMM_6_BITS 0x01 -#define RFCOMM_7_BITS 0x02 -#define RFCOMM_8_BITS 0x03 - -#define RFCOMM_RPN_BITS_MASK 0x03 -#define RFCOMM_RPN_BITS_SHIFT 0 - -#define RFCOMM_ONESTOPBIT 0x00 -#define RFCOMM_ONE5STOPBITS 0x01 - -#define RFCOMM_RPN_STOP_BITS_MASK 0x01 -#define RFCOMM_RPN_STOP_BITS_SHIFT 2 - -#define RFCOMM_PARITY_NO 0x00 -#define RFCOMM_PARITY_YES 0x01 -#define RFCOMM_RPN_PARITY_MASK 0x01 -#define RFCOMM_RPN_PARITY_SHIFT 3 - -#define RFCOMM_ODD_PARITY 0x00 -#define RFCOMM_EVEN_PARITY 0x01 -#define RFCOMM_MARK_PARITY 0x02 -#define RFCOMM_SPACE_PARITY 0x03 - -#define RFCOMM_RPN_PARITY_TYPE_MASK 0x03 -#define RFCOMM_RPN_PARITY_TYPE_SHIFT 4 - -#define RFCOMM_FC_OFF 0x00 -#define RFCOMM_FC_XONXOFF_ON_INPUT 0x01 -#define RFCOMM_FC_XONXOFF_ON_OUTPUT 0x02 -#define RFCOMM_FC_RTR_ON_INPUT 0x04 -#define RFCOMM_FC_RTR_ON_OUTPUT 0x08 -#define RFCOMM_FC_RTC_ON_INPUT 0x10 -#define RFCOMM_FC_RTC_ON_OUTPUT 0x20 -#define RFCOMM_FC_MASK 0x3F - -#define RFCOMM_RPN_PM_BIT_RATE 0x0001 -#define RFCOMM_RPN_PM_DATA_BITS 0x0002 -#define RFCOMM_RPN_PM_STOP_BITS 0x0004 -#define RFCOMM_RPN_PM_PARITY 0x0008 -#define RFCOMM_RPN_PM_PARITY_TYPE 0x0010 -#define RFCOMM_RPN_PM_XON_CHAR 0x0020 -#define RFCOMM_RPN_PM_XOFF_CHAR 0x0040 -#define RFCOMM_RPN_PM_XONXOFF_ON_INPUT 0x0100 -#define RFCOMM_RPN_PM_XONXOFF_ON_OUTPUT 0x0200 -#define RFCOMM_RPN_PM_RTR_ON_INPUT 0x0400 -#define RFCOMM_RPN_PM_RTR_ON_OUTPUT 0x0800 -#define RFCOMM_RPN_PM_RTC_ON_INPUT 0x1000 -#define RFCOMM_RPN_PM_RTC_ON_OUTPUT 0x2000 -#define RFCOMM_RPN_PM_MASK 0x3F7F - -#define RFCOMM_RLS_ERROR 0x01 -#define RFCOMM_RLS_OVERRUN 0x02 -#define RFCOMM_RLS_PARITY 0x04 -#define RFCOMM_RLS_FRAMING 0x08 - -/* Multiplexor channel uses DLCI 0 */ -#define RFCOMM_MX_DLCI 0 - -/* -** Define RFCOMM Multiplexer message types -*/ -#define RFCOMM_MX_PN 0x80 -#define RFCOMM_MX_PN_LEN 8 - -#define RFCOMM_MX_CLD 0xC0 -#define RFCOMM_MX_CLD_LEN 0 - -#define RFCOMM_MX_TEST 0x20 - -#define RFCOMM_MX_FCON 0xA0 -#define RFCOMM_MX_FCON_LEN 0 - -#define RFCOMM_MX_FCOFF 0x60 -#define RFCOMM_MX_FCOFF_LEN 0 - -#define RFCOMM_MX_MSC 0xE0 -#define RFCOMM_MX_MSC_LEN_NO_BREAK 2 -#define RFCOMM_MX_MSC_LEN_WITH_BREAK 3 - -#define RFCOMM_MX_NSC 0x10 -#define RFCOMM_MX_NSC_LEN 1 - -#define RFCOMM_MX_RPN 0x90 -#define RFCOMM_MX_RPN_REQ_LEN 1 -#define RFCOMM_MX_RPN_LEN 8 - -#define RFCOMM_MX_RLS 0x50 -#define RFCOMM_MX_RLS_LEN 2 -#endif diff --git a/tools/sdk/include/bluedroid/sbc_dct.h b/tools/sdk/include/bluedroid/sbc_dct.h deleted file mode 100644 index 165a8c1cd97..00000000000 --- a/tools/sdk/include/bluedroid/sbc_dct.h +++ /dev/null @@ -1,91 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * Definitions for the fast DCT. - * - ******************************************************************************/ - -#ifndef SBC_DCT_H -#define SBC_DCT_H - -#if (SBC_ARM_ASM_OPT==TRUE) -#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1, s32OutLow) \ -{ \ - __asm \ -{ \ - MUL s32OutLow,(SINT32)s16In2, (s32In1>>15) \ -} \ -} -#else -#if (SBC_DSP_OPT==TRUE) -#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1 , s32OutLow) s32OutLow = SBC_Multiply_32_16_Simplified((SINT32)s16In2,s32In1); -#else -#if (SBC_IPAQ_OPT==TRUE) -/*#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1 , s32OutLow) s32OutLow=(SINT32)((SINT32)(s16In2)*(SINT32)(s32In1>>15)); */ -#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1 , s32OutLow) s32OutLow=(SINT32)(((SINT64)s16In2*(SINT64)s32In1)>>15); -#if (SBC_IS_64_MULT_IN_IDCT == TRUE) -#define SBC_MULT_32_32(s32In2, s32In1, s32OutLow) \ -{ \ - s64Temp = ((SINT64) s32In2) * ((SINT64) s32In1)>>31; \ - s32OutLow = (SINT32) s64Temp; \ -} -#endif -#else -#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1 , s32OutLow) \ -{ \ - s32In1Temp = s32In1; \ - s32In2Temp = (SINT32)s16In2; \ - \ - /* Multiply one +ve and the other -ve number */ \ - if (s32In1Temp < 0) \ - { \ - s32In1Temp ^= 0xFFFFFFFF; \ - s32In1Temp++; \ - s32OutLow = (s32In2Temp * (s32In1Temp >> 16)); \ - s32OutLow += (( s32In2Temp * (s32In1Temp & 0xFFFF)) >> 16); \ - s32OutLow ^= 0xFFFFFFFF; \ - s32OutLow++; \ - } \ - else \ - { \ - s32OutLow = (s32In2Temp * (s32In1Temp >> 16)); \ - s32OutLow += (( s32In2Temp * (s32In1Temp & 0xFFFF)) >> 16); \ - } \ - s32OutLow <<= 1; \ -} -#if (SBC_IS_64_MULT_IN_IDCT == TRUE) -#define SBC_MULT_64(s32In1, s32In2, s32OutLow, s32OutHi) \ -{\ - s32OutLow=(SINT32)(((SINT64)s32In1*(SINT64)s32In2)& 0x00000000FFFFFFFF);\ - s32OutHi=(SINT32)(((SINT64)s32In1*(SINT64)s32In2)>>32);\ -} -#define SBC_MULT_32_32(s32In2, s32In1, s32OutLow) \ -{ \ - s32HiTemp = 0; \ - SBC_MULT_64(s32In2,s32In1 , s32OutLow, s32HiTemp); \ - s32OutLow = (((s32OutLow>>15)&0x1FFFF) | (s32HiTemp << 17)); \ -} -#endif - -#endif -#endif -#endif - -#endif diff --git a/tools/sdk/include/bluedroid/sbc_enc_func_declare.h b/tools/sdk/include/bluedroid/sbc_enc_func_declare.h deleted file mode 100644 index cc85b716435..00000000000 --- a/tools/sdk/include/bluedroid/sbc_enc_func_declare.h +++ /dev/null @@ -1,57 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * Function declarations. - * - ******************************************************************************/ - -#ifndef SBC_FUNCDECLARE_H -#define SBC_FUNCDECLARE_H - -/*#include "sbc_encoder.h"*/ -/* Global data */ -#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE) -extern const SINT16 gas32CoeffFor4SBs[]; -extern const SINT16 gas32CoeffFor8SBs[]; -#else -extern const SINT32 gas32CoeffFor4SBs[]; -extern const SINT32 gas32CoeffFor8SBs[]; -#endif - -/* Global functions*/ - -extern void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS *CodecParams); -extern void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS *CodecParams); - -extern void SbcAnalysisInit (void); - -extern void SbcAnalysisFilter4(SBC_ENC_PARAMS *strEncParams); -extern void SbcAnalysisFilter8(SBC_ENC_PARAMS *strEncParams); - -extern void SBC_FastIDCT8 (SINT32 *pInVect, SINT32 *pOutVect); -extern void SBC_FastIDCT4 (SINT32 *x0, SINT32 *pOutVect); - -extern void EncPacking(SBC_ENC_PARAMS *strEncParams); -extern void EncQuantizer(SBC_ENC_PARAMS *); -#if (SBC_DSP_OPT==TRUE) -SINT32 SBC_Multiply_32_16_Simplified(SINT32 s32In2Temp, SINT32 s32In1Temp); -#endif -#endif - diff --git a/tools/sdk/include/bluedroid/sbc_encoder.h b/tools/sdk/include/bluedroid/sbc_encoder.h deleted file mode 100644 index 8e2e6dd3649..00000000000 --- a/tools/sdk/include/bluedroid/sbc_encoder.h +++ /dev/null @@ -1,201 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains constants and structures used by Encoder. - * - ******************************************************************************/ - -#ifndef SBC_ENCODER_H -#define SBC_ENCODER_H - -#define ENCODER_VERSION "0025" - -#ifdef BUILDCFG -#include "bt_target.h" -#endif - -/*DEFINES*/ -#ifndef FALSE -#define FALSE 0 -#endif - -#ifndef TRUE -#define TRUE (!FALSE) -#endif - -#define SBC_MAX_NUM_OF_SUBBANDS 8 -#define SBC_MAX_NUM_OF_CHANNELS 2 -#define SBC_MAX_NUM_OF_BLOCKS 16 - -#define SBC_LOUDNESS 0 -#define SBC_SNR 1 - -#define SUB_BANDS_8 8 -#define SUB_BANDS_4 4 - -#define SBC_sf16000 0 -#define SBC_sf32000 1 -#define SBC_sf44100 2 -#define SBC_sf48000 3 - -#define SBC_MONO 0 -#define SBC_DUAL 1 -#define SBC_STEREO 2 -#define SBC_JOINT_STEREO 3 - -#define SBC_BLOCK_0 4 -#define SBC_BLOCK_1 8 -#define SBC_BLOCK_2 12 -#define SBC_BLOCK_3 16 - -#define SBC_NULL 0 - -#ifndef SBC_MAX_NUM_FRAME -#define SBC_MAX_NUM_FRAME 1 -#endif - -#ifndef SBC_DSP_OPT -#define SBC_DSP_OPT FALSE -#endif - -/* Set SBC_USE_ARM_PRAGMA to TRUE to use "#pragma arm section zidata" */ -#ifndef SBC_USE_ARM_PRAGMA -#define SBC_USE_ARM_PRAGMA FALSE -#endif - -/* Set SBC_ARM_ASM_OPT to TRUE in case the target is an ARM */ -/* this will replace all the 32 and 64 bit mult by in line assembly code */ -#ifndef SBC_ARM_ASM_OPT -#define SBC_ARM_ASM_OPT FALSE -#endif - -/* green hill compiler option -> Used to distinguish the syntax for inline assembly code*/ -#ifndef SBC_GHS_COMPILER -#define SBC_GHS_COMPILER FALSE -#endif - -/* ARM compiler option -> Used to distinguish the syntax for inline assembly code */ -#ifndef SBC_ARM_COMPILER -#define SBC_ARM_COMPILER TRUE -#endif - -/* Set SBC_IPAQ_OPT to TRUE in case the target is an ARM */ -/* 32 and 64 bit mult will be performed using SINT64 ( usualy __int64 ) cast that usualy give optimal performance if supported */ -#ifndef SBC_IPAQ_OPT -#define SBC_IPAQ_OPT TRUE -#endif - -/* Debug only: set SBC_IS_64_MULT_IN_WINDOW_ACCU to TRUE to use 64 bit multiplication in the windowing */ -/* -> not recomended, more MIPS for the same restitution. */ -#ifndef SBC_IS_64_MULT_IN_WINDOW_ACCU -#define SBC_IS_64_MULT_IN_WINDOW_ACCU FALSE -#endif /*SBC_IS_64_MULT_IN_WINDOW_ACCU */ - -/* Set SBC_IS_64_MULT_IN_IDCT to TRUE to use 64 bits multiplication in the DCT of Matrixing */ -/* -> more MIPS required for a better audio quality. comparasion with the SIG utilities shows a division by 10 of the RMS */ -/* CAUTION: It only apply in the if SBC_FAST_DCT is set to TRUE */ -#ifndef SBC_IS_64_MULT_IN_IDCT -#define SBC_IS_64_MULT_IN_IDCT FALSE -#endif /*SBC_IS_64_MULT_IN_IDCT */ - -/* set SBC_IS_64_MULT_IN_QUANTIZER to TRUE to use 64 bits multiplication in the quantizer */ -/* setting this flag to FALSE add whistling noise at 5.5 and 11 KHz usualy not perceptible by human's hears. */ -#ifndef SBC_IS_64_MULT_IN_QUANTIZER -#define SBC_IS_64_MULT_IN_QUANTIZER TRUE -#endif /*SBC_IS_64_MULT_IN_IDCT */ - -/* Debug only: set this flag to FALSE to disable fast DCT algorithm */ -#ifndef SBC_FAST_DCT -#define SBC_FAST_DCT TRUE -#endif /*SBC_FAST_DCT */ - -/* In case we do not use joint stereo mode the flag save some RAM and ROM in case it is set to FALSE */ -#ifndef SBC_JOINT_STE_INCLUDED -#define SBC_JOINT_STE_INCLUDED TRUE -#endif - -/* TRUE -> application should provide PCM buffer, FALSE PCM buffer reside in SBC_ENC_PARAMS */ -#ifndef SBC_NO_PCM_CPY_OPTION -#define SBC_NO_PCM_CPY_OPTION FALSE -#endif - -#define MINIMUM_ENC_VX_BUFFER_SIZE (8*10*2) -#ifndef ENC_VX_BUFFER_SIZE -#define ENC_VX_BUFFER_SIZE (MINIMUM_ENC_VX_BUFFER_SIZE + 64) -/*#define ENC_VX_BUFFER_SIZE MINIMUM_ENC_VX_BUFFER_SIZE + 1024*/ -#endif - -#ifndef SBC_FOR_EMBEDDED_LINUX -#define SBC_FOR_EMBEDDED_LINUX FALSE -#endif - -/*constants used for index calculation*/ -#define SBC_BLK (SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS) - -#include "sbc_types.h" - -typedef struct SBC_ENC_PARAMS_TAG { - SINT16 s16SamplingFreq; /* 16k, 32k, 44.1k or 48k*/ - SINT16 s16ChannelMode; /* mono, dual, streo or joint streo*/ - SINT16 s16NumOfSubBands; /* 4 or 8 */ - SINT16 s16NumOfChannels; - SINT16 s16NumOfBlocks; /* 4, 8, 12 or 16*/ - SINT16 s16AllocationMethod; /* loudness or SNR*/ - SINT16 s16BitPool; /* 16*numOfSb for mono & dual; - 32*numOfSb for stereo & joint stereo */ - UINT16 u16BitRate; - UINT8 u8NumPacketToEncode; /* number of sbc frame to encode. Default is 1 */ -#if (SBC_JOINT_STE_INCLUDED == TRUE) - SINT16 as16Join[SBC_MAX_NUM_OF_SUBBANDS]; /*1 if JS, 0 otherwise*/ -#endif - - SINT16 s16MaxBitNeed; - SINT16 as16ScaleFactor[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS]; - - SINT16 *ps16NextPcmBuffer; -#if (SBC_NO_PCM_CPY_OPTION == TRUE) - SINT16 *ps16PcmBuffer; -#else - SINT16 as16PcmBuffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS]; -#endif - - SINT16 s16ScartchMemForBitAlloc[16]; - - SINT32 s32SbBuffer[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS * SBC_MAX_NUM_OF_BLOCKS]; - - SINT16 as16Bits[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS]; - - UINT8 *pu8Packet; - UINT8 *pu8NextPacket; - UINT16 FrameHeader; - UINT16 u16PacketLength; - -} SBC_ENC_PARAMS; - -#ifdef __cplusplus -extern "C" -{ -#endif -extern void SBC_Encoder(SBC_ENC_PARAMS *strEncParams); -extern void SBC_Encoder_Init(SBC_ENC_PARAMS *strEncParams); -#ifdef __cplusplus -} -#endif -#endif diff --git a/tools/sdk/include/bluedroid/sbc_if.h b/tools/sdk/include/bluedroid/sbc_if.h deleted file mode 100644 index 993b066340e..00000000000 --- a/tools/sdk/include/bluedroid/sbc_if.h +++ /dev/null @@ -1,47 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _SBC_IF_H -#define _SBC_IF_H - -#define PCM_BUFFER_SIZE 512 - -/* - SBC_Init - called once for each track played - - pcm_sample_freq - 4000 to 48000 - channels - 1 mono 2 stereo - bits_per_sample - 8 or 16 - return - 0 sucess -*/ - -int SBC_init(int pcm_sample_freq, int channels, int bits_per_sample); - -/* - SBC_write - called repeatedly with pcm_in pointer - increasing by length until track is finished. - - pcm_in - pointer to PCM buffer - length - any - sbc_out - pointer to SBC output buffer - return - number of bytes written to sbc_out -*/ - -int SBC_write(unsigned char *pcm_in, int length, unsigned char *sbc_out); - -#endif diff --git a/tools/sdk/include/bluedroid/sbc_types.h b/tools/sdk/include/bluedroid/sbc_types.h deleted file mode 100644 index 4bb8829c707..00000000000 --- a/tools/sdk/include/bluedroid/sbc_types.h +++ /dev/null @@ -1,59 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * Data type declarations. - * - ******************************************************************************/ - -#ifndef SBC_TYPES_H -#define SBC_TYPES_H - -#include - -#ifdef BUILDCFG -#include "bt_target.h" -#endif - -#include "bt_types.h" - -typedef short SINT16; -typedef long SINT32; - -#if (SBC_IPAQ_OPT == TRUE) - -#if (SBC_FOR_EMBEDDED_LINUX == TRUE) -typedef long long SINT64; -#else -typedef int64_t SINT64; -#endif - -#elif (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE) || (SBC_IS_64_MULT_IN_IDCT == TRUE) - -#if (SBC_FOR_EMBEDDED_LINUX == TRUE) -typedef long long SINT64; -#else -typedef int64_t SINT64; -#endif - -#endif - -#define abs32(x) ( (x >= 0) ? x : (-x) ) - -#endif diff --git a/tools/sdk/include/bluedroid/sdp_api.h b/tools/sdk/include/bluedroid/sdp_api.h deleted file mode 100644 index db11df55803..00000000000 --- a/tools/sdk/include/bluedroid/sdp_api.h +++ /dev/null @@ -1,726 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 SDP_API_H -#define SDP_API_H - -#include "bt_target.h" -#include "sdpdefs.h" -#if (SDP_INCLUDED == TRUE) -/***************************************************************************** -** Constants -*****************************************************************************/ - -/* Success code and error codes */ -#define SDP_SUCCESS 0x0000 -#define SDP_INVALID_VERSION 0x0001 -#define SDP_INVALID_SERV_REC_HDL 0x0002 -#define SDP_INVALID_REQ_SYNTAX 0x0003 -#define SDP_INVALID_PDU_SIZE 0x0004 -#define SDP_INVALID_CONT_STATE 0x0005 -#define SDP_NO_RESOURCES 0x0006 -#define SDP_DI_REG_FAILED 0x0007 -#define SDP_DI_DISC_FAILED 0x0008 -#define SDP_NO_DI_RECORD_FOUND 0x0009 -#define SDP_ERR_ATTR_NOT_PRESENT 0x000A -#define SDP_ILLEGAL_PARAMETER 0x000B - -#define SDP_NO_RECS_MATCH 0xFFF0 -#define SDP_CONN_FAILED 0xFFF1 -#define SDP_CFG_FAILED 0xFFF2 -#define SDP_GENERIC_ERROR 0xFFF3 -#define SDP_DB_FULL 0xFFF4 -#define SDP_INVALID_PDU 0xFFF5 -#define SDP_SECURITY_ERR 0xFFF6 -#define SDP_CONN_REJECTED 0xFFF7 -#define SDP_CANCEL 0xFFF8 - -/* Define the PSM that SDP uses */ -#define SDP_PSM 0x0001 - -/* Legacy #define to avoid code changes - SDP UUID is same as BT UUID */ -#define tSDP_UUID tBT_UUID - -/* Masks for attr_value field of tSDP_DISC_ATTR */ -#define SDP_DISC_ATTR_LEN_MASK 0x0FFF -#define SDP_DISC_ATTR_TYPE(len_type) (len_type >> 12) -#define SDP_DISC_ATTR_LEN(len_type) (len_type & SDP_DISC_ATTR_LEN_MASK) - -/* Maximum number of protocol list items (list_elem in tSDP_PROTOCOL_ELEM) */ -#define SDP_MAX_LIST_ELEMS 3 - - -/***************************************************************************** -** Type Definitions -*****************************************************************************/ - -/* Define a callback function for when discovery is complete. */ -typedef void (tSDP_DISC_CMPL_CB) (UINT16 result); -typedef void (tSDP_DISC_CMPL_CB2) (UINT16 result, void *user_data); - -typedef struct { - BD_ADDR peer_addr; - UINT16 peer_mtu; -} tSDP_DR_OPEN; - -typedef struct { - UINT8 *p_data; - UINT16 data_len; -} tSDP_DR_DATA; - -typedef union { - tSDP_DR_OPEN open; - tSDP_DR_DATA data; -} tSDP_DATA; - -/* Define a callback function for when discovery result is received. */ -typedef void (tSDP_DISC_RES_CB) (UINT16 event, tSDP_DATA *p_data); - -/* Define a structure to hold the discovered service information. */ -typedef struct { - union { - UINT8 u8; /* 8-bit integer */ - UINT16 u16; /* 16-bit integer */ - UINT32 u32; /* 32-bit integer */ - UINT8 array[4]; /* Variable length field */ - struct t_sdp_disc_attr *p_sub_attr; /* Addr of first sub-attr (list)*/ - } v; - -} tSDP_DISC_ATVAL; - -typedef struct t_sdp_disc_attr { - struct t_sdp_disc_attr *p_next_attr; /* Addr of next linked attr */ - UINT16 attr_id; /* Attribute ID */ - UINT16 attr_len_type; /* Length and type fields */ - tSDP_DISC_ATVAL attr_value; /* Variable length entry data */ -} tSDP_DISC_ATTR; - -typedef struct t_sdp_disc_rec { - tSDP_DISC_ATTR *p_first_attr; /* First attribute of record */ - struct t_sdp_disc_rec *p_next_rec; /* Addr of next linked record */ - UINT32 time_read; /* The time the record was read */ - BD_ADDR remote_bd_addr; /* Remote BD address */ -} tSDP_DISC_REC; - -typedef struct { - UINT32 mem_size; /* Memory size of the DB */ - UINT32 mem_free; /* Memory still available */ - tSDP_DISC_REC *p_first_rec; /* Addr of first record in DB */ - UINT16 num_uuid_filters; /* Number of UUIds to filter */ - tSDP_UUID uuid_filters[SDP_MAX_UUID_FILTERS]; /* UUIDs to filter */ - UINT16 num_attr_filters; /* Number of attribute filters */ - UINT16 attr_filters[SDP_MAX_ATTR_FILTERS]; /* Attributes to filter */ - UINT8 *p_free_mem; /* Pointer to free memory */ -#if (SDP_RAW_DATA_INCLUDED == TRUE) - UINT8 *raw_data; /* Received record from server. allocated/released by client */ - UINT32 raw_size; /* size of raw_data */ - UINT32 raw_used; /* length of raw_data used */ -#endif -} tSDP_DISCOVERY_DB; - -/* This structure is used to add protocol lists and find protocol elements */ -typedef struct { - UINT16 protocol_uuid; - UINT16 num_params; - UINT16 params[SDP_MAX_PROTOCOL_PARAMS]; -} tSDP_PROTOCOL_ELEM; - -typedef struct { - UINT16 num_elems; - tSDP_PROTOCOL_ELEM list_elem[SDP_MAX_LIST_ELEMS]; -} tSDP_PROTO_LIST_ELEM; - -/* Device Identification (DI) data structure -*/ -/* Used to set the DI record */ -typedef struct t_sdp_di_record { - UINT16 vendor; - UINT16 vendor_id_source; - UINT16 product; - UINT16 version; - BOOLEAN primary_record; - char client_executable_url[SDP_MAX_ATTR_LEN]; /* optional */ - char service_description[SDP_MAX_ATTR_LEN]; /* optional */ - char documentation_url[SDP_MAX_ATTR_LEN]; /* optional */ -} tSDP_DI_RECORD; - -/* Used to get the DI record */ -typedef struct t_sdp_di_get_record { - UINT16 spec_id; - tSDP_DI_RECORD rec; -} tSDP_DI_GET_RECORD; - - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif - -/* API into the SDP layer for service discovery. */ - -/******************************************************************************* -** -** Function SDP_InitDiscoveryDb -** -** Description This function is called to initialize a discovery database. -** -** Returns TRUE if successful, FALSE if one or more parameters are bad -** -*******************************************************************************/ -extern BOOLEAN SDP_InitDiscoveryDb (tSDP_DISCOVERY_DB *p_db, UINT32 len, - UINT16 num_uuid, - tSDP_UUID *p_uuid_list, - UINT16 num_attr, - UINT16 *p_attr_list); - -/******************************************************************************* -** -** Function SDP_CancelServiceSearch -** -** Description This function cancels an active query to an SDP server. -** -** Returns TRUE if discovery cancelled, FALSE if a matching activity is not found. -** -*******************************************************************************/ -extern BOOLEAN SDP_CancelServiceSearch (tSDP_DISCOVERY_DB *p_db); - -/******************************************************************************* -** -** Function SDP_ServiceSearchRequest -** -** Description This function queries an SDP server for information. -** -** Returns TRUE if discovery started, FALSE if failed. -** -*******************************************************************************/ -extern BOOLEAN SDP_ServiceSearchRequest (UINT8 *p_bd_addr, - tSDP_DISCOVERY_DB *p_db, - tSDP_DISC_CMPL_CB *p_cb); - - -/******************************************************************************* -** -** Function SDP_ServiceSearchAttributeRequest -** -** Description This function queries an SDP server for information. -** -** The difference between this API function and the function -** SDP_ServiceSearchRequest is that this one does a -** combined ServiceSearchAttributeRequest SDP function. -** -** Returns TRUE if discovery started, FALSE if failed. -** -*******************************************************************************/ -extern BOOLEAN SDP_ServiceSearchAttributeRequest (UINT8 *p_bd_addr, - tSDP_DISCOVERY_DB *p_db, - tSDP_DISC_CMPL_CB *p_cb); - -/******************************************************************************* -** -** Function SDP_ServiceSearchAttributeRequest2 -** -** Description This function queries an SDP server for information. -** -** The difference between this API function and the function -** SDP_ServiceSearchRequest is that this one does a -** combined ServiceSearchAttributeRequest SDP function with the -** user data piggyback -** -** Returns TRUE if discovery started, FALSE if failed. -** -*******************************************************************************/ -extern BOOLEAN SDP_ServiceSearchAttributeRequest2 (UINT8 *p_bd_addr, - tSDP_DISCOVERY_DB *p_db, - tSDP_DISC_CMPL_CB2 *p_cb, void *user_data); - -/* API of utilities to find data in the local discovery database */ - -/******************************************************************************* -** -** Function SDP_FindAttributeInDb -** -** Description This function queries an SDP database for a specific attribute. -** If the p_start_rec pointer is NULL, it looks from the beginning -** of the database, else it continues from the next record after -** p_start_rec. -** -** Returns Pointer to matching record, or NULL -** -*******************************************************************************/ -extern tSDP_DISC_REC *SDP_FindAttributeInDb (tSDP_DISCOVERY_DB *p_db, - UINT16 attr_id, - tSDP_DISC_REC *p_start_rec); - - -/******************************************************************************* -** -** Function SDP_FindAttributeInRec -** -** Description This function searches an SDP discovery record for a -** specific attribute. -** -** Returns Pointer to matching attribute entry, or NULL -** -*******************************************************************************/ -extern tSDP_DISC_ATTR *SDP_FindAttributeInRec (tSDP_DISC_REC *p_rec, - UINT16 attr_id); - - -/******************************************************************************* -** -** Function SDP_FindServiceInDb -** -** Description This function queries an SDP database for a specific service. -** If the p_start_rec pointer is NULL, it looks from the beginning -** of the database, else it continues from the next record after -** p_start_rec. -** -** Returns Pointer to record containing service class, or NULL -** -*******************************************************************************/ -extern tSDP_DISC_REC *SDP_FindServiceInDb (tSDP_DISCOVERY_DB *p_db, - UINT16 service_uuid, - tSDP_DISC_REC *p_start_rec); - - -/******************************************************************************* -** -** Function SDP_FindServiceUUIDInDb -** -** Description This function queries an SDP database for a specific service. -** If the p_start_rec pointer is NULL, it looks from the beginning -** of the database, else it continues from the next record after -** p_start_rec. -** -** NOTE the only difference between this function and the previous -** function "SDP_FindServiceInDb()" is that this function takes -** a tBT_UUID input. -** -** Returns Pointer to record containing service class, or NULL -** -*******************************************************************************/ -extern tSDP_DISC_REC *SDP_FindServiceUUIDInDb (tSDP_DISCOVERY_DB *p_db, - tBT_UUID *p_uuid, - tSDP_DISC_REC *p_start_rec); - -/******************************************************************************* -** -** Function SDP_FindServiceUUIDInRec_128bit -** -** Description This function is called to read the 128-bit service UUID within a record -** if there is any. -** -** Parameters: p_rec - pointer to a SDP record. -** p_uuid - output parameter to save the UUID found. -** -** Returns TRUE if found, otherwise FALSE. -** -*******************************************************************************/ -extern BOOLEAN SDP_FindServiceUUIDInRec_128bit(tSDP_DISC_REC *p_rec, tBT_UUID *p_uuid); - -/******************************************************************************* -** -** Function SDP_FindServiceInDb_128bit -** -** Description This function queries an SDP database for a specific service. -** If the p_start_rec pointer is NULL, it looks from the beginning -** of the database, else it continues from the next record after -** p_start_rec. -** -** Returns Pointer to record containing service class, or NULL -** -*******************************************************************************/ -extern tSDP_DISC_REC *SDP_FindServiceInDb_128bit(tSDP_DISCOVERY_DB *p_db, - tSDP_DISC_REC *p_start_rec); - -/******************************************************************************* -** -** Function SDP_FindProtocolListElemInRec -** -** Description This function looks at a specific discovery record for a -** protocol list element. -** -** Returns TRUE if found, FALSE if not -** If found, the passed protocol list element is filled in. -** -*******************************************************************************/ -extern BOOLEAN SDP_FindProtocolListElemInRec (tSDP_DISC_REC *p_rec, - UINT16 layer_uuid, - tSDP_PROTOCOL_ELEM *p_elem); - - -/******************************************************************************* -** -** Function SDP_FindAddProtoListsElemInRec -** -** Description This function looks at a specific discovery record for a -** protocol list element. -** -** Returns TRUE if found, FALSE if not -** If found, the passed protocol list element is filled in. -** -*******************************************************************************/ -extern BOOLEAN SDP_FindAddProtoListsElemInRec (tSDP_DISC_REC *p_rec, - UINT16 layer_uuid, - tSDP_PROTOCOL_ELEM *p_elem); - - -/******************************************************************************* -** -** Function SDP_FindProfileVersionInRec -** -** Description This function looks at a specific discovery record for the -** Profile list descriptor, and pulls out the version number. -** The version number consists of an 8-bit major version and -** an 8-bit minor version. -** -** Returns TRUE if found, FALSE if not -** If found, the major and minor version numbers that were passed -** in are filled in. -** -*******************************************************************************/ -extern BOOLEAN SDP_FindProfileVersionInRec (tSDP_DISC_REC *p_rec, - UINT16 profile_uuid, - UINT16 *p_version); - - -/* API into SDP for local service database updates */ - -/******************************************************************************* -** -** Function SDP_CreateRecord -** -** Description This function is called to create a record in the database. -** This would be through the SDP database maintenance API. The -** record is created empty, teh application should then call -** "add_attribute" to add the record's attributes. -** -** Returns Record handle if OK, else 0. -** -*******************************************************************************/ -extern UINT32 SDP_CreateRecord (void); - - -/******************************************************************************* -** -** Function SDP_DeleteRecord -** -** Description This function is called to add a record (or all records) -** from the database. This would be through the SDP database -** maintenance API. -** -** If a record handle of 0 is passed, all records are deleted. -** -** Returns TRUE if succeeded, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_DeleteRecord (UINT32 handle); - - -/******************************************************************************* -** -** Function SDP_ReadRecord -** -** Description This function is called to get the raw data of the record -** with the given handle from the database. -** -** Returns -1, if the record is not found. -** Otherwise, the offset (0 or 1) to start of data in p_data. -** -** The size of data copied into p_data is in *p_data_len. -** -*******************************************************************************/ -extern INT32 SDP_ReadRecord(UINT32 handle, UINT8 *p_data, INT32 *p_data_len); - -/******************************************************************************* -** -** Function SDP_AddAttribute -** -** Description This function is called to add an attribute to a record. -** This would be through the SDP database maintenance API. -** If the attribute already exists in the record, it is replaced -** with the new value. -** -** NOTE Attribute values must be passed as a Big Endian stream. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_AddAttribute (UINT32 handle, UINT16 attr_id, - UINT8 attr_type, UINT32 attr_len, - UINT8 *p_val); - - -/******************************************************************************* -** -** Function SDP_AddSequence -** -** Description This function is called to add a sequence to a record. -** This would be through the SDP database maintenance API. -** If the sequence already exists in the record, it is replaced -** with the new sequence. -** -** NOTE Element values must be passed as a Big Endian stream. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_AddSequence (UINT32 handle, UINT16 attr_id, - UINT16 num_elem, UINT8 type[], - UINT8 len[], UINT8 *p_val[]); - - -/******************************************************************************* -** -** Function SDP_AddUuidSequence -** -** Description This function is called to add a UUID sequence to a record. -** This would be through the SDP database maintenance API. -** If the sequence already exists in the record, it is replaced -** with the new sequence. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_AddUuidSequence (UINT32 handle, UINT16 attr_id, - UINT16 num_uuids, UINT16 *p_uuids); - - -/******************************************************************************* -** -** Function SDP_AddProtocolList -** -** Description This function is called to add a protocol descriptor list to -** a record. This would be through the SDP database maintenance API. -** If the protocol list already exists in the record, it is replaced -** with the new list. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_AddProtocolList (UINT32 handle, UINT16 num_elem, - tSDP_PROTOCOL_ELEM *p_elem_list); - - -/******************************************************************************* -** -** Function SDP_AddAdditionProtoLists -** -** Description This function is called to add a protocol descriptor list to -** a record. This would be through the SDP database maintenance API. -** If the protocol list already exists in the record, it is replaced -** with the new list. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_AddAdditionProtoLists (UINT32 handle, UINT16 num_elem, - tSDP_PROTO_LIST_ELEM *p_proto_list); - - -/******************************************************************************* -** -** Function SDP_AddProfileDescriptorList -** -** Description This function is called to add a profile descriptor list to -** a record. This would be through the SDP database maintenance API. -** If the version already exists in the record, it is replaced -** with the new one. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_AddProfileDescriptorList (UINT32 handle, - UINT16 profile_uuid, - UINT16 version); - - -/******************************************************************************* -** -** Function SDP_AddLanguageBaseAttrIDList -** -** Description This function is called to add a language base attr list to -** a record. This would be through the SDP database maintenance API. -** If the version already exists in the record, it is replaced -** with the new one. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_AddLanguageBaseAttrIDList (UINT32 handle, - UINT16 lang, UINT16 char_enc, - UINT16 base_id); - - -/******************************************************************************* -** -** Function SDP_AddServiceClassIdList -** -** Description This function is called to add a service list to a record. -** This would be through the SDP database maintenance API. -** If the service list already exists in the record, it is replaced -** with the new list. -** -** Returns TRUE if added OK, else FALSE -** -*******************************************************************************/ -extern BOOLEAN SDP_AddServiceClassIdList (UINT32 handle, - UINT16 num_services, - UINT16 *p_service_uuids); - - -/******************************************************************************* -** -** Function SDP_DeleteAttribute -** -** Description This function is called to delete an attribute from a record. -** This would be through the SDP database maintenance API. -** -** Returns TRUE if deleted OK, else FALSE if not found -** -*******************************************************************************/ -extern BOOLEAN SDP_DeleteAttribute (UINT32 handle, UINT16 attr_id); - - -/* Device Identification APIs */ - -/******************************************************************************* -** -** Function SDP_SetLocalDiRecord -** -** Description This function adds a DI record to the local SDP database. -** -** Returns Returns SDP_SUCCESS if record added successfully, else error -** -*******************************************************************************/ -extern UINT16 SDP_SetLocalDiRecord (tSDP_DI_RECORD *device_info, - UINT32 *p_handle); - -/******************************************************************************* -** -** Function SDP_DiDiscover -** -** Description This function queries a remote device for DI information. -** -** Returns SDP_SUCCESS if query started successfully, else error -** -*******************************************************************************/ -extern UINT16 SDP_DiDiscover (BD_ADDR remote_device, - tSDP_DISCOVERY_DB *p_db, UINT32 len, - tSDP_DISC_CMPL_CB *p_cb); - - -/******************************************************************************* -** -** Function SDP_GetNumDiRecords -** -** Description Searches specified database for DI records -** -** Returns number of DI records found -** -*******************************************************************************/ -extern UINT8 SDP_GetNumDiRecords (tSDP_DISCOVERY_DB *p_db); - - -/******************************************************************************* -** -** Function SDP_GetDiRecord -** -** Description This function retrieves a remote device's DI record from -** the specified database. -** -** Returns SDP_SUCCESS if record retrieved, else error -** -*******************************************************************************/ -extern UINT16 SDP_GetDiRecord (UINT8 getRecordIndex, - tSDP_DI_GET_RECORD *device_info, - tSDP_DISCOVERY_DB *p_db); - - -/******************************************************************************* -** -** Function SDP_SetTraceLevel -** -** Description This function sets the trace level for SDP. If called with -** a value of 0xFF, it simply reads the current trace level. -** -** Returns the new (current) trace level -** -*******************************************************************************/ -extern UINT8 SDP_SetTraceLevel (UINT8 new_level); - -/******************************************************************************* -** -** Function SDP_ConnOpen -** -** Description This function creates a connection to the SDP server on the -** given device. -** -** Returns 0, if failed to initiate connection. Otherwise, the handle. -** -*******************************************************************************/ -UINT32 SDP_ConnOpen (UINT8 *p_bd_addr, tSDP_DISC_RES_CB *p_rcb, - tSDP_DISC_CMPL_CB *p_cb); - -/******************************************************************************* -** -** Function SDP_WriteData -** -** Description This function sends data to the connected SDP server. -** -** Returns TRUE if data is sent, FALSE if failed. -** -*******************************************************************************/ -BOOLEAN SDP_WriteData (UINT32 handle, BT_HDR *p_msg); - -/******************************************************************************* -** -** Function SDP_ConnClose -** -** Description This function is called to close a SDP connection. -** -** Parameters: handle - Handle of the connection returned by SDP_ConnOpen -** -** Returns TRUE if connection is closed, FALSE if failed to find the handle. -** -*******************************************************************************/ -BOOLEAN SDP_ConnClose (UINT32 handle); - -/******************************************************************************* -** -** Function SDP_FindServiceUUIDInRec -** -** Description This function is called to read the service UUID within a record -** if there is any. -** -** Parameters: p_rec - pointer to a SDP record. -** -** Returns TRUE if found, otherwise FALSE. -** -*******************************************************************************/ -BOOLEAN SDP_FindServiceUUIDInRec(tSDP_DISC_REC *p_rec, tBT_UUID *p_uuid); - -#ifdef __cplusplus -} -#endif - -#endif ///SDP_INCLUDED == TRUE - -#endif /* SDP_API_H */ diff --git a/tools/sdk/include/bluedroid/sdpdefs.h b/tools/sdk/include/bluedroid/sdpdefs.h deleted file mode 100644 index 44d87e74bcb..00000000000 --- a/tools/sdk/include/bluedroid/sdpdefs.h +++ /dev/null @@ -1,327 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains the definitions for the SDP API - * - ******************************************************************************/ - -#ifndef SDP_DEFS_H -#define SDP_DEFS_H - -/* Define the service attribute IDs. -*/ -#define ATTR_ID_SERVICE_RECORD_HDL 0x0000 -#define ATTR_ID_SERVICE_CLASS_ID_LIST 0x0001 -#define ATTR_ID_SERVICE_RECORD_STATE 0x0002 -#define ATTR_ID_SERVICE_ID 0x0003 -#define ATTR_ID_PROTOCOL_DESC_LIST 0x0004 -#define ATTR_ID_BROWSE_GROUP_LIST 0x0005 -#define ATTR_ID_LANGUAGE_BASE_ATTR_ID_LIST 0x0006 -#define ATTR_ID_SERVICE_INFO_TIME_TO_LIVE 0x0007 -#define ATTR_ID_SERVICE_AVAILABILITY 0x0008 -#define ATTR_ID_BT_PROFILE_DESC_LIST 0x0009 -#define ATTR_ID_DOCUMENTATION_URL 0x000A -#define ATTR_ID_CLIENT_EXE_URL 0x000B -#define ATTR_ID_ICON_URL 0x000C -#define ATTR_ID_ADDITION_PROTO_DESC_LISTS 0x000D - -#define LANGUAGE_BASE_ID 0x0100 -#define ATTR_ID_SERVICE_NAME LANGUAGE_BASE_ID + 0x0000 -#define ATTR_ID_SERVICE_DESCRIPTION LANGUAGE_BASE_ID + 0x0001 -#define ATTR_ID_PROVIDER_NAME LANGUAGE_BASE_ID + 0x0002 - -/* Device Identification (DI) -*/ -#define ATTR_ID_SPECIFICATION_ID 0x0200 -#define ATTR_ID_VENDOR_ID 0x0201 -#define ATTR_ID_PRODUCT_ID 0x0202 -#define ATTR_ID_PRODUCT_VERSION 0x0203 -#define ATTR_ID_PRIMARY_RECORD 0x0204 -#define ATTR_ID_VENDOR_ID_SOURCE 0x0205 - -#define BLUETOOTH_DI_SPECIFICATION 0x0103 /* 1.3 */ -#define DI_VENDOR_ID_DEFAULT 0xFFFF -#define DI_VENDOR_ID_SOURCE_BTSIG 0x0001 -#define DI_VENDOR_ID_SOURCE_USBIF 0x0002 - - -#define ATTR_ID_IP_SUBNET 0x0200 /* PAN Profile (***) */ -#define ATTR_ID_VERSION_NUMBER_LIST 0x0200 -#define ATTR_ID_GOEP_L2CAP_PSM 0x0200 -#define ATTR_ID_GROUP_ID 0x0200 -#define ATTR_ID_SERVICE_DATABASE_STATE 0x0201 -#define ATTR_ID_SERVICE_VERSION 0x0300 -#define ATTR_ID_HCRP_1284ID 0x0300 - -#define ATTR_ID_SUPPORTED_DATA_STORES 0x0301 -#define ATTR_ID_NETWORK 0x0301 -#define ATTR_ID_EXTERNAL_NETWORK 0x0301 -#define ATTR_ID_FAX_CLASS_1_SUPPORT 0x0302 -#define ATTR_ID_REMOTE_AUDIO_VOLUME_CONTROL 0x0302 -#define ATTR_ID_DEVICE_NAME 0x0302 -#define ATTR_ID_SUPPORTED_FORMATS_LIST 0x0303 -#define ATTR_ID_FAX_CLASS_2_0_SUPPORT 0x0303 -#define ATTR_ID_FAX_CLASS_2_SUPPORT 0x0304 -#define ATTR_ID_FRIENDLY_NAME 0x0304 -#define ATTR_ID_AUDIO_FEEDBACK_SUPPORT 0x0305 -#define ATTR_ID_NETWORK_ADDRESS 0x0306 -#define ATTR_ID_DEVICE_LOCATION 0x0306 -#define ATTR_ID_WAP_GATEWAY 0x0307 -#define ATTR_ID_HOME_PAGE_URL 0x0308 -#define ATTR_ID_WAP_STACK_TYPE 0x0309 -#define ATTR_ID_IMG_SUPPORTED_CAPABILITIES 0x0310 /* Imaging Profile */ -#define ATTR_ID_SUPPORTED_FEATURES 0x0311 /* HFP, BIP */ -#define ATTR_ID_IMG_SUPPORTED_FUNCTIONS 0x0312 /* Imaging Profile */ -#define ATTR_ID_IMG_TOT_DATA_CAPABILITY 0x0313 /* Imaging Profile */ -#define ATTR_ID_SUPPORTED_REPOSITORIES 0x0314 /* Phone book access Profile */ -#define ATTR_ID_MAS_INSTANCE_ID 0x0315 /* MAP profile */ -#define ATTR_ID_SUPPORTED_MSG_TYPE 0x0316 /* MAP profile */ -#define ATTR_ID_MAP_SUPPORTED_FEATURES 0x0317 /* MAP profile */ -#define ATTR_ID_PBAP_SUPPORTED_FEATURES 0x0317 /* PBAP profile */ - - -/* These values are for the BPP profile */ -#define ATTR_ID_DOCUMENT_FORMATS_SUPPORTED 0x0350 -#define ATTR_ID_CHARACTER_REPERTOIRES_SUPPORTED 0x0352 -#define ATTR_ID_XHTML_IMAGE_FORMATS_SUPPORTED 0x0354 -#define ATTR_ID_COLOR_SUPPORTED 0x0356 -#define ATTR_ID_1284ID 0x0358 -#define ATTR_ID_PRINTER_NAME 0x035A -#define ATTR_ID_PRINTER_LOCATION 0x035C -#define ATTR_ID_DUPLEX_SUPPORTED 0x035E -#define ATTR_ID_MEDIA_TYPES_SUPPORTED 0x0360 -#define ATTR_ID_MAX_MEDIA_WIDTH 0x0362 -#define ATTR_ID_MAX_MEDIA_LENGTH 0x0364 -#define ATTR_ID_ENHANCED_LAYOUT_SUPPORTED 0x0366 -#define ATTR_ID_RUI_FORMATS_SUPPORTED 0x0368 -#define ATTR_ID_RUI_REF_PRINTING_SUPPORTED 0x0370 /* Boolean */ -#define ATTR_ID_RUI_DIRECT_PRINTING_SUPPORTED 0x0372 /* Boolean */ -#define ATTR_ID_REF_PRINTING_TOP_URL 0x0374 -#define ATTR_ID_DIRECT_PRINTING_TOP_URL 0x0376 -#define ATTR_ID_PRINTER_ADMIN_RUI_TOP_URL 0x0378 -#define ATTR_ID_BPP_DEVICE_NAME 0x037A - -/* These values are for the PAN profile */ -#define ATTR_ID_SECURITY_DESCRIPTION 0x030A -#define ATTR_ID_NET_ACCESS_TYPE 0x030B -#define ATTR_ID_MAX_NET_ACCESS_RATE 0x030C -#define ATTR_ID_IPV4_SUBNET 0x030D -#define ATTR_ID_IPV6_SUBNET 0x030E -#define ATTR_ID_PAN_SECURITY 0x0400 - -/* These values are for HID profile */ -#define ATTR_ID_HID_DEVICE_RELNUM 0x0200 -#define ATTR_ID_HID_PARSER_VERSION 0x0201 -#define ATTR_ID_HID_DEVICE_SUBCLASS 0x0202 -#define ATTR_ID_HID_COUNTRY_CODE 0x0203 -#define ATTR_ID_HID_VIRTUAL_CABLE 0x0204 -#define ATTR_ID_HID_RECONNECT_INITIATE 0x0205 -#define ATTR_ID_HID_DESCRIPTOR_LIST 0x0206 -#define ATTR_ID_HID_LANGUAGE_ID_BASE 0x0207 -#define ATTR_ID_HID_SDP_DISABLE 0x0208 -#define ATTR_ID_HID_BATTERY_POWER 0x0209 -#define ATTR_ID_HID_REMOTE_WAKE 0x020A -#define ATTR_ID_HID_PROFILE_VERSION 0x020B -#define ATTR_ID_HID_LINK_SUPERVISION_TO 0x020C -#define ATTR_ID_HID_NORMALLY_CONNECTABLE 0x020D -#define ATTR_ID_HID_BOOT_DEVICE 0x020E -#define ATTR_ID_HID_SSR_HOST_MAX_LAT 0x020F -#define ATTR_ID_HID_SSR_HOST_MIN_TOUT 0x0210 - -/* These values are for the HDP profile */ -#define ATTR_ID_HDP_SUP_FEAT_LIST 0x0200 /* Supported features list */ -#define ATTR_ID_HDP_DATA_EXCH_SPEC 0x0301 /* Data exchange specification */ -#define ATTR_ID_HDP_MCAP_SUP_PROC 0x0302 /* MCAP supported procedures */ - -/* Define common 16-bit protocol UUIDs -*/ -#define UUID_PROTOCOL_SDP 0x0001 -#define UUID_PROTOCOL_UDP 0x0002 -#define UUID_PROTOCOL_RFCOMM 0x0003 -#define UUID_PROTOCOL_TCP 0x0004 -#define UUID_PROTOCOL_TCS_BIN 0x0005 -#define UUID_PROTOCOL_TCS_AT 0x0006 -#define UUID_PROTOCOL_OBEX 0x0008 -#define UUID_PROTOCOL_IP 0x0009 -#define UUID_PROTOCOL_FTP 0x000A -#define UUID_PROTOCOL_HTTP 0x000C -#define UUID_PROTOCOL_WSP 0x000E -#define UUID_PROTOCOL_BNEP 0x000F -#define UUID_PROTOCOL_UPNP 0x0010 -#define UUID_PROTOCOL_HIDP 0x0011 -#define UUID_PROTOCOL_HCRP_CTRL 0x0012 -#define UUID_PROTOCOL_HCRP_DATA 0x0014 -#define UUID_PROTOCOL_HCRP_NOTIF 0x0016 -#define UUID_PROTOCOL_AVCTP 0x0017 -#define UUID_PROTOCOL_AVDTP 0x0019 -#define UUID_PROTOCOL_CMTP 0x001B -#define UUID_PROTOCOL_UDI 0x001D -#define UUID_PROTOCOL_MCAP_CTRL 0x001E -#define UUID_PROTOCOL_MCAP_DATA 0x001F -#define UUID_PROTOCOL_L2CAP 0x0100 -#define UUID_PROTOCOL_ATT 0x0007 - -/* Define common 16-bit service class UUIDs -*/ -#define UUID_SERVCLASS_SERVICE_DISCOVERY_SERVER 0X1000 -#define UUID_SERVCLASS_BROWSE_GROUP_DESCRIPTOR 0X1001 -#define UUID_SERVCLASS_PUBLIC_BROWSE_GROUP 0X1002 -#define UUID_SERVCLASS_SERIAL_PORT 0X1101 -#define UUID_SERVCLASS_LAN_ACCESS_USING_PPP 0X1102 -#define UUID_SERVCLASS_DIALUP_NETWORKING 0X1103 -#define UUID_SERVCLASS_IRMC_SYNC 0X1104 -#define UUID_SERVCLASS_OBEX_OBJECT_PUSH 0X1105 -#define UUID_SERVCLASS_OBEX_FILE_TRANSFER 0X1106 -#define UUID_SERVCLASS_IRMC_SYNC_COMMAND 0X1107 -#define UUID_SERVCLASS_HEADSET 0X1108 -#define UUID_SERVCLASS_CORDLESS_TELEPHONY 0X1109 -#define UUID_SERVCLASS_AUDIO_SOURCE 0X110A -#define UUID_SERVCLASS_AUDIO_SINK 0X110B -#define UUID_SERVCLASS_AV_REM_CTRL_TARGET 0X110C /* Audio/Video Control profile */ -#define UUID_SERVCLASS_ADV_AUDIO_DISTRIBUTION 0X110D /* Advanced Audio Distribution profile */ -#define UUID_SERVCLASS_AV_REMOTE_CONTROL 0X110E /* Audio/Video Control profile */ -#define UUID_SERVCLASS_AV_REM_CTRL_CONTROL 0X110F /* Audio/Video Control profile */ -#define UUID_SERVCLASS_INTERCOM 0X1110 -#define UUID_SERVCLASS_FAX 0X1111 -#define UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY 0X1112 -#define UUID_SERVCLASS_WAP 0X1113 -#define UUID_SERVCLASS_WAP_CLIENT 0X1114 -#define UUID_SERVCLASS_PANU 0X1115 /* PAN profile */ -#define UUID_SERVCLASS_NAP 0X1116 /* PAN profile */ -#define UUID_SERVCLASS_GN 0X1117 /* PAN profile */ -#define UUID_SERVCLASS_DIRECT_PRINTING 0X1118 /* BPP profile */ -#define UUID_SERVCLASS_REFERENCE_PRINTING 0X1119 /* BPP profile */ -#define UUID_SERVCLASS_IMAGING 0X111A /* Imaging profile */ -#define UUID_SERVCLASS_IMAGING_RESPONDER 0X111B /* Imaging profile */ -#define UUID_SERVCLASS_IMAGING_AUTO_ARCHIVE 0X111C /* Imaging profile */ -#define UUID_SERVCLASS_IMAGING_REF_OBJECTS 0X111D /* Imaging profile */ -#define UUID_SERVCLASS_HF_HANDSFREE 0X111E /* Handsfree profile */ -#define UUID_SERVCLASS_AG_HANDSFREE 0X111F /* Handsfree profile */ -#define UUID_SERVCLASS_DIR_PRT_REF_OBJ_SERVICE 0X1120 /* BPP profile */ -#define UUID_SERVCLASS_REFLECTED_UI 0X1121 /* BPP profile */ -#define UUID_SERVCLASS_BASIC_PRINTING 0X1122 /* BPP profile */ -#define UUID_SERVCLASS_PRINTING_STATUS 0X1123 /* BPP profile */ -#define UUID_SERVCLASS_HUMAN_INTERFACE 0X1124 /* HID profile */ -#define UUID_SERVCLASS_CABLE_REPLACEMENT 0X1125 /* HCRP profile */ -#define UUID_SERVCLASS_HCRP_PRINT 0X1126 /* HCRP profile */ -#define UUID_SERVCLASS_HCRP_SCAN 0X1127 /* HCRP profile */ -#define UUID_SERVCLASS_COMMON_ISDN_ACCESS 0X1128 /* CAPI Message Transport Protocol*/ -#define UUID_SERVCLASS_VIDEO_CONFERENCING_GW 0X1129 /* Video Conferencing profile */ -#define UUID_SERVCLASS_UDI_MT 0X112A /* Unrestricted Digital Information profile */ -#define UUID_SERVCLASS_UDI_TA 0X112B /* Unrestricted Digital Information profile */ -#define UUID_SERVCLASS_VCP 0X112C /* Video Conferencing profile */ -#define UUID_SERVCLASS_SAP 0X112D /* SIM Access profile */ -#define UUID_SERVCLASS_PBAP_PCE 0X112E /* Phonebook Access - PCE */ -#define UUID_SERVCLASS_PBAP_PSE 0X112F /* Phonebook Access - PSE */ -#define UUID_SERVCLASS_PHONE_ACCESS 0x1130 -#define UUID_SERVCLASS_HEADSET_HS 0x1131 /* Headset - HS, from HSP v1.2 */ -#define UUID_SERVCLASS_PNP_INFORMATION 0X1200 /* Device Identification */ -#define UUID_SERVCLASS_GENERIC_NETWORKING 0X1201 -#define UUID_SERVCLASS_GENERIC_FILETRANSFER 0X1202 -#define UUID_SERVCLASS_GENERIC_AUDIO 0X1203 -#define UUID_SERVCLASS_GENERIC_TELEPHONY 0X1204 -#define UUID_SERVCLASS_UPNP_SERVICE 0X1205 /* UPNP_Service [ESDP] */ -#define UUID_SERVCLASS_UPNP_IP_SERVICE 0X1206 /* UPNP_IP_Service [ESDP] */ -#define UUID_SERVCLASS_ESDP_UPNP_IP_PAN 0X1300 /* UPNP_IP_PAN [ESDP] */ -#define UUID_SERVCLASS_ESDP_UPNP_IP_LAP 0X1301 /* UPNP_IP_LAP [ESDP] */ -#define UUID_SERVCLASS_ESDP_UPNP_IP_L2CAP 0X1302 /* UPNP_L2CAP [ESDP] */ -#define UUID_SERVCLASS_VIDEO_SOURCE 0X1303 /* Video Distribution Profile (VDP) */ -#define UUID_SERVCLASS_VIDEO_SINK 0X1304 /* Video Distribution Profile (VDP) */ -#define UUID_SERVCLASS_VIDEO_DISTRIBUTION 0X1305 /* Video Distribution Profile (VDP) */ -#define UUID_SERVCLASS_HDP_PROFILE 0X1400 /* Health Device profile (HDP) */ -#define UUID_SERVCLASS_HDP_SOURCE 0X1401 /* Health Device profile (HDP) */ -#define UUID_SERVCLASS_HDP_SINK 0X1402 /* Health Device profile (HDP) */ -#define UUID_SERVCLASS_MAP_PROFILE 0X1134 /* MAP profile UUID */ -#define UUID_SERVCLASS_MESSAGE_ACCESS 0X1132 /* Message Access Service UUID */ -#define UUID_SERVCLASS_MESSAGE_NOTIFICATION 0X1133 /* Message Notification Service UUID */ - -#define UUID_SERVCLASS_GAP_SERVER 0x1800 -#define UUID_SERVCLASS_GATT_SERVER 0x1801 -#define UUID_SERVCLASS_IMMEDIATE_ALERT 0x1802 /* immediate alert */ -#define UUID_SERVCLASS_LINKLOSS 0x1803 /* Link Loss Alert */ -#define UUID_SERVCLASS_TX_POWER 0x1804 /* TX power */ -#define UUID_SERVCLASS_CURRENT_TIME 0x1805 /* Link Loss Alert */ -#define UUID_SERVCLASS_DST_CHG 0x1806 /* DST Time change */ -#define UUID_SERVCLASS_REF_TIME_UPD 0x1807 /* reference time update */ -#define UUID_SERVCLASS_THERMOMETER 0x1809 /* Thermometer UUID */ -#define UUID_SERVCLASS_DEVICE_INFO 0x180A /* device info service */ -#define UUID_SERVCLASS_NWA 0x180B /* Network availability */ -#define UUID_SERVCLASS_HEART_RATE 0x180D /* Heart Rate service */ -#define UUID_SERVCLASS_PHALERT 0x180E /* phone alert service */ -#define UUID_SERVCLASS_BATTERY 0x180F /* battery service */ -#define UUID_SERVCLASS_BPM 0x1810 /* blood pressure service */ -#define UUID_SERVCLASS_ALERT_NOTIFICATION 0x1811 /* alert notification service */ -#define UUID_SERVCLASS_LE_HID 0x1812 /* HID over LE */ -#define UUID_SERVCLASS_SCAN_PARAM 0x1813 /* Scan Parameter service */ -#define UUID_SERVCLASS_GLUCOSE 0x1808 /* Glucose Meter Service */ -#define UUID_SERVCLASS_RSC 0x1814 /* RUNNERS SPEED AND CADENCE SERVICE */ -#define UUID_SERVCLASS_CSC 0x1816 /* Cycling SPEED AND CADENCE SERVICE */ - -#define UUID_SERVCLASS_TEST_SERVER 0x9000 /* Test Group UUID */ - -#if (BTM_WBS_INCLUDED == TRUE ) -#define UUID_CODEC_CVSD 0x0001 /* CVSD */ -#define UUID_CODEC_MSBC 0x0002 /* mSBC */ -#endif - -/* Define all the 'Descriptor Type' values. -*/ -#define NULL_DESC_TYPE 0 -#define UINT_DESC_TYPE 1 -#define TWO_COMP_INT_DESC_TYPE 2 -#define UUID_DESC_TYPE 3 -#define TEXT_STR_DESC_TYPE 4 -#define BOOLEAN_DESC_TYPE 5 -#define DATA_ELE_SEQ_DESC_TYPE 6 -#define DATA_ELE_ALT_DESC_TYPE 7 -#define URL_DESC_TYPE 8 - -/* Define all the "Descriptor Size" values. -*/ -#define SIZE_ONE_BYTE 0 -#define SIZE_TWO_BYTES 1 -#define SIZE_FOUR_BYTES 2 -#define SIZE_EIGHT_BYTES 3 -#define SIZE_SIXTEEN_BYTES 4 -#define SIZE_IN_NEXT_BYTE 5 -#define SIZE_IN_NEXT_WORD 6 -#define SIZE_IN_NEXT_LONG 7 - -/* Language Encoding Constants */ -#define LANG_ID_CODE_ENGLISH ((UINT16) 0x656e) /* "en" */ -#define LANG_ID_CHAR_ENCODE_UTF8 ((UINT16) 0x006a) /* UTF-8 */ - -/* Constants used for display purposes only. These define ovelapping attribute values */ -#define ATTR_ID_VERS_OR_GRP_OR_DRELNUM_OR_IPSUB_OR_SPECID 0x0200 -#define ATTR_ID_VEND_ID_OR_SERVICE_DB_STATE_OR_PARSE_VER 0x0201 -#define ATTR_ID_PROD_ID_OR_HID_DEV_SUBCLASS 0x0202 -#define ATTR_ID_PROD_VER_OR_HID_COUNTRY_CODE 0x0203 -#define ATTR_ID_PRIMARY_REC_OR_HID_VIRTUAL_CABLE 0x0204 -#define ATTR_ID_DI_VENDOR_ID_SOURCE_OR_HID_INIT_RECONNECT 0x0205 -#define ATTR_ID_SERV_VERS_OR_1284ID 0x0300 -#define ATTR_ID_DATA_STORES_OR_NETWORK 0x0301 -#define ATTR_ID_FAX_1_OR_AUD_VOL_OR_DEV_NAME 0x0302 -#define ATTR_ID_FORMATS_OR_FAX_2_0 0x0303 -#define ATTR_ID_FAX_CLASS_2_OR_FRIENDLY_NAME 0x0304 -#define ATTR_ID_NETADDRESS_OR_DEVLOCATION 0x0306 - -#endif - - diff --git a/tools/sdk/include/bluedroid/sdpint.h b/tools/sdk/include/bluedroid/sdpint.h deleted file mode 100644 index 058257b8ef1..00000000000 --- a/tools/sdk/include/bluedroid/sdpint.h +++ /dev/null @@ -1,316 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains internally used SDP definitions - * - ******************************************************************************/ - -#ifndef SDP_INT_H -#define SDP_INT_H - -#include "bt_target.h" -#include "bt_defs.h" -#include "sdp_api.h" -#include "l2c_api.h" - -#if (SDP_INCLUDED == TRUE) -/* Continuation length - we use a 2-byte offset */ -#define SDP_CONTINUATION_LEN 2 -#define SDP_MAX_CONTINUATION_LEN 16 /* As per the spec */ - -/* Timeout definitions. */ -#define SDP_INACT_TIMEOUT 30 /* Inactivity timeout */ - - -/* Define the Out-Flow default values. */ -#define SDP_OFLOW_QOS_FLAG 0 -#define SDP_OFLOW_SERV_TYPE 0 -#define SDP_OFLOW_TOKEN_RATE 0 -#define SDP_OFLOW_TOKEN_BUCKET_SIZE 0 -#define SDP_OFLOW_PEAK_BANDWIDTH 0 -#define SDP_OFLOW_LATENCY 0 -#define SDP_OFLOW_DELAY_VARIATION 0 - -/* Define the In-Flow default values. */ -#define SDP_IFLOW_QOS_FLAG 0 -#define SDP_IFLOW_SERV_TYPE 0 -#define SDP_IFLOW_TOKEN_RATE 0 -#define SDP_IFLOW_TOKEN_BUCKET_SIZE 0 -#define SDP_IFLOW_PEAK_BANDWIDTH 0 -#define SDP_IFLOW_LATENCY 0 -#define SDP_IFLOW_DELAY_VARIATION 0 - -#define SDP_LINK_TO 0 - -/* Define the type of device notification. */ -/* (Inquiry Scan and Page Scan) */ -#define SDP_DEVICE_NOTI_LEN sizeof (BT_HDR) + \ - HCIC_PREAMBLE_SIZE + \ - HCIC_PARAM_SIZE_WRITE_PARAM1 - -#define SDP_DEVICE_NOTI_FLAG 0x03 - -/* Define the Protocol Data Unit (PDU) types. -*/ -#define SDP_PDU_ERROR_RESPONSE 0x01 -#define SDP_PDU_SERVICE_SEARCH_REQ 0x02 -#define SDP_PDU_SERVICE_SEARCH_RSP 0x03 -#define SDP_PDU_SERVICE_ATTR_REQ 0x04 -#define SDP_PDU_SERVICE_ATTR_RSP 0x05 -#define SDP_PDU_SERVICE_SEARCH_ATTR_REQ 0x06 -#define SDP_PDU_SERVICE_SEARCH_ATTR_RSP 0x07 - -/* Max UUIDs and attributes we support per sequence */ -#define MAX_UUIDS_PER_SEQ 8 -#define MAX_ATTR_PER_SEQ 8 - -/* Max length we support for any attribute */ -// btla-specific ++ -#ifdef SDP_MAX_ATTR_LEN -#define MAX_ATTR_LEN SDP_MAX_ATTR_LEN -#else -#define MAX_ATTR_LEN 256 -#endif -// btla-specific -- - -/* Internal UUID sequence representation */ -typedef struct { - UINT16 len; - UINT8 value[MAX_UUID_SIZE]; -} tUID_ENT; - -typedef struct { - UINT16 num_uids; - tUID_ENT uuid_entry[MAX_UUIDS_PER_SEQ]; -} tSDP_UUID_SEQ; - - -/* Internal attribute sequence definitions */ -typedef struct { - UINT16 start; - UINT16 end; -} tATT_ENT; - -typedef struct { - UINT16 num_attr; - tATT_ENT attr_entry[MAX_ATTR_PER_SEQ]; -} tSDP_ATTR_SEQ; - - -/* Define the attribute element of the SDP database record */ -typedef struct { - UINT32 len; /* Number of bytes in the entry */ - UINT8 *value_ptr; /* Points to attr_pad */ - UINT16 id; - UINT8 type; -} tSDP_ATTRIBUTE; - -/* An SDP record consists of a handle, and 1 or more attributes */ -typedef struct { - UINT32 record_handle; - UINT32 free_pad_ptr; - UINT16 num_attributes; - tSDP_ATTRIBUTE attribute[SDP_MAX_REC_ATTR]; - UINT8 attr_pad[SDP_MAX_PAD_LEN]; -} tSDP_RECORD; - - -/* Define the SDP database */ -typedef struct { - UINT32 di_primary_handle; /* Device ID Primary record or NULL if nonexistent */ - UINT16 num_records; - tSDP_RECORD record[SDP_MAX_RECORDS]; -} tSDP_DB; - -enum { - SDP_IS_SEARCH, - SDP_IS_ATTR_SEARCH, -}; - -#if SDP_SERVER_ENABLED == TRUE -/* Continuation information for the SDP server response */ -typedef struct { - UINT16 next_attr_index; /* attr index for next continuation response */ - UINT16 next_attr_start_id; /* attr id to start with for the attr index in next cont. response */ - tSDP_RECORD *prev_sdp_rec; /* last sdp record that was completely sent in the response */ - BOOLEAN last_attr_seq_desc_sent; /* whether attr seq length has been sent previously */ - UINT16 attr_offset; /* offset within the attr to keep trak of partial attributes in the responses */ -} tSDP_CONT_INFO; -#endif /* SDP_SERVER_ENABLED == TRUE */ - -/* Define the SDP Connection Control Block */ -typedef struct { -#define SDP_STATE_IDLE 0 -#define SDP_STATE_CONN_SETUP 1 -#define SDP_STATE_CFG_SETUP 2 -#define SDP_STATE_CONNECTED 3 - UINT8 con_state; - -#define SDP_FLAGS_IS_ORIG 0x01 -#define SDP_FLAGS_HIS_CFG_DONE 0x02 -#define SDP_FLAGS_MY_CFG_DONE 0x04 - UINT8 con_flags; - - BD_ADDR device_address; - TIMER_LIST_ENT timer_entry; - UINT16 rem_mtu_size; - UINT16 connection_id; - UINT16 list_len; /* length of the response in the GKI buffer */ - UINT8 *rsp_list; /* pointer to GKI buffer holding response */ - -#if SDP_CLIENT_ENABLED == TRUE - tSDP_DISCOVERY_DB *p_db; /* Database to save info into */ - tSDP_DISC_CMPL_CB *p_cb; /* Callback for discovery done */ - tSDP_DISC_CMPL_CB2 *p_cb2; /* Callback for discovery done piggy back with the user data */ - void *user_data; /* piggy back user data */ - UINT32 handles[SDP_MAX_DISC_SERVER_RECS]; /* Discovered server record handles */ - UINT16 num_handles; /* Number of server handles */ - UINT16 cur_handle; /* Current handle being processed */ - UINT16 transaction_id; - UINT16 disconnect_reason; /* Disconnect reason */ -#if (defined(SDP_BROWSE_PLUS) && SDP_BROWSE_PLUS == TRUE) - UINT16 cur_uuid_idx; -#endif - -#define SDP_DISC_WAIT_CONN 0 -#define SDP_DISC_WAIT_HANDLES 1 -#define SDP_DISC_WAIT_ATTR 2 -#define SDP_DISC_WAIT_SEARCH_ATTR 3 -#define SDP_DISC_WAIT_CANCEL 5 - - UINT8 disc_state; - UINT8 is_attr_search; -#endif /* SDP_CLIENT_ENABLED == TRUE */ - -#if SDP_SERVER_ENABLED == TRUE - UINT16 cont_offset; /* Continuation state data in the server response */ - tSDP_CONT_INFO cont_info; /* structure to hold continuation information for the server response */ -#endif /* SDP_SERVER_ENABLED == TRUE */ - -} tCONN_CB; - - -/* The main SDP control block */ -typedef struct { - tL2CAP_CFG_INFO l2cap_my_cfg; /* My L2CAP config */ - tCONN_CB ccb[SDP_MAX_CONNECTIONS]; -#if SDP_SERVER_ENABLED == TRUE - tSDP_DB server_db; -#endif - tL2CAP_APPL_INFO reg_info; /* L2CAP Registration info */ - UINT16 max_attr_list_size; /* Max attribute list size to use */ - UINT16 max_recs_per_search; /* Max records we want per seaarch */ - UINT8 trace_level; -} tSDP_CB; - -#ifdef __cplusplus -extern "C" { -#endif -/* Global SDP data */ -#if SDP_DYNAMIC_MEMORY == FALSE -extern tSDP_CB sdp_cb; -#else -extern tSDP_CB *sdp_cb_ptr; -#define sdp_cb (*sdp_cb_ptr) -#endif - -#ifdef __cplusplus -} -#endif - -/* Functions provided by sdp_main.c */ -extern void sdp_init (void); -extern void sdp_deinit (void); -extern void sdp_disconnect (tCONN_CB *p_ccb, UINT16 reason); - -#if (defined(SDP_DEBUG) && SDP_DEBUG == TRUE) -extern UINT16 sdp_set_max_attr_list_size (UINT16 max_size); -#endif - -/* Functions provided by sdp_conn.c -*/ -extern void sdp_conn_rcv_l2e_conn_ind (BT_HDR *p_msg); -extern void sdp_conn_rcv_l2e_conn_cfm (BT_HDR *p_msg); -extern void sdp_conn_rcv_l2e_disc (BT_HDR *p_msg); -extern void sdp_conn_rcv_l2e_config_ind (BT_HDR *p_msg); -extern void sdp_conn_rcv_l2e_config_cfm (BT_HDR *p_msg); -extern void sdp_conn_rcv_l2e_conn_failed (BT_HDR *p_msg); -extern void sdp_conn_rcv_l2e_connected (BT_HDR *p_msg); -extern void sdp_conn_rcv_l2e_conn_failed (BT_HDR *p_msg); -extern void sdp_conn_rcv_l2e_data (BT_HDR *p_msg); -extern void sdp_conn_timeout (tCONN_CB *p_ccb); - -extern tCONN_CB *sdp_conn_originate (UINT8 *p_bd_addr); - -/* Functions provided by sdp_utils.c -*/ -extern tCONN_CB *sdpu_find_ccb_by_cid (UINT16 cid); -extern tCONN_CB *sdpu_find_ccb_by_db (tSDP_DISCOVERY_DB *p_db); -extern tCONN_CB *sdpu_allocate_ccb (void); -extern void sdpu_release_ccb (tCONN_CB *p_ccb); - -extern UINT8 *sdpu_build_attrib_seq (UINT8 *p_out, UINT16 *p_attr, UINT16 num_attrs); -extern UINT8 *sdpu_build_attrib_entry (UINT8 *p_out, tSDP_ATTRIBUTE *p_attr); -extern void sdpu_build_n_send_error (tCONN_CB *p_ccb, UINT16 trans_num, UINT16 error_code, char *p_error_text); - -extern UINT8 *sdpu_extract_attr_seq (UINT8 *p, UINT16 param_len, tSDP_ATTR_SEQ *p_seq); -extern UINT8 *sdpu_extract_uid_seq (UINT8 *p, UINT16 param_len, tSDP_UUID_SEQ *p_seq); - -extern UINT8 *sdpu_get_len_from_type (UINT8 *p, UINT8 type, UINT32 *p_len); -extern BOOLEAN sdpu_is_base_uuid (UINT8 *p_uuid); -extern BOOLEAN sdpu_compare_uuid_arrays (UINT8 *p_uuid1, UINT32 len1, UINT8 *p_uuid2, UINT16 len2); -extern BOOLEAN sdpu_compare_bt_uuids (tBT_UUID *p_uuid1, tBT_UUID *p_uuid2); -extern BOOLEAN sdpu_compare_uuid_with_attr (tBT_UUID *p_btuuid, tSDP_DISC_ATTR *p_attr); - -extern void sdpu_sort_attr_list( UINT16 num_attr, tSDP_DISCOVERY_DB *p_db ); -extern UINT16 sdpu_get_list_len( tSDP_UUID_SEQ *uid_seq, tSDP_ATTR_SEQ *attr_seq ); -extern UINT16 sdpu_get_attrib_seq_len(tSDP_RECORD *p_rec, tSDP_ATTR_SEQ *attr_seq); -extern UINT16 sdpu_get_attrib_entry_len(tSDP_ATTRIBUTE *p_attr); -extern UINT8 *sdpu_build_partial_attrib_entry (UINT8 *p_out, tSDP_ATTRIBUTE *p_attr, UINT16 len, UINT16 *offset); -extern void sdpu_uuid16_to_uuid128(UINT16 uuid16, UINT8 *p_uuid128); - -/* Functions provided by sdp_db.c -*/ -extern tSDP_RECORD *sdp_db_service_search (tSDP_RECORD *p_rec, tSDP_UUID_SEQ *p_seq); -extern tSDP_RECORD *sdp_db_find_record (UINT32 handle); -extern tSDP_ATTRIBUTE *sdp_db_find_attr_in_rec (tSDP_RECORD *p_rec, UINT16 start_attr, UINT16 end_attr); - - -/* Functions provided by sdp_server.c -*/ -#if SDP_SERVER_ENABLED == TRUE -extern void sdp_server_handle_client_req (tCONN_CB *p_ccb, BT_HDR *p_msg); -#else -#define sdp_server_handle_client_req(p_ccb, p_msg) -#endif - -/* Functions provided by sdp_discovery.c -*/ -#if SDP_CLIENT_ENABLED == TRUE -extern void sdp_disc_connected (tCONN_CB *p_ccb); -extern void sdp_disc_server_rsp (tCONN_CB *p_ccb, BT_HDR *p_msg); -#else -#define sdp_disc_connected(p_ccb) -#define sdp_disc_server_rsp(p_ccb, p_msg) -#endif - -#endif ///SDP_INCLUDED == TRUE - -#endif diff --git a/tools/sdk/include/bluedroid/semaphore.h b/tools/sdk/include/bluedroid/semaphore.h deleted file mode 100644 index 621d5a2c1e9..00000000000 --- a/tools/sdk/include/bluedroid/semaphore.h +++ /dev/null @@ -1,43 +0,0 @@ -/****************************************************************************** - * - * 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/include/bluedroid/smp_api.h b/tools/sdk/include/bluedroid/smp_api.h deleted file mode 100644 index 193cfe33b15..00000000000 --- a/tools/sdk/include/bluedroid/smp_api.h +++ /dev/null @@ -1,496 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains the SMP API function external definitions. - * - ******************************************************************************/ -#ifndef SMP_API_H -#define SMP_API_H - -#include "bt_target.h" - -#define SMP_PIN_CODE_LEN_MAX PIN_CODE_LEN -#define SMP_PIN_CODE_LEN_MIN 6 - -#if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE -/* SMP command code */ -#define SMP_OPCODE_PAIRING_REQ 0x01 -#define SMP_OPCODE_PAIRING_RSP 0x02 -#define SMP_OPCODE_CONFIRM 0x03 -#define SMP_OPCODE_RAND 0x04 -#define SMP_OPCODE_PAIRING_FAILED 0x05 -#define SMP_OPCODE_ENCRYPT_INFO 0x06 -#define SMP_OPCODE_MASTER_ID 0x07 -#define SMP_OPCODE_IDENTITY_INFO 0x08 -#define SMP_OPCODE_ID_ADDR 0x09 -#define SMP_OPCODE_SIGN_INFO 0x0A -#define SMP_OPCODE_SEC_REQ 0x0B -#define SMP_OPCODE_PAIR_PUBLIC_KEY 0x0C -#define SMP_OPCODE_PAIR_DHKEY_CHECK 0x0D -#define SMP_OPCODE_PAIR_KEYPR_NOTIF 0x0E -#define SMP_OPCODE_MAX SMP_OPCODE_PAIR_KEYPR_NOTIF -#define SMP_OPCODE_MIN SMP_OPCODE_PAIRING_REQ -#define SMP_OPCODE_PAIR_COMMITM 0x0F -#endif - -/* SMP event type */ -#define SMP_IO_CAP_REQ_EVT 1 /* IO capability request event */ -#define SMP_SEC_REQUEST_EVT 2 /* SMP pairing request */ -#define SMP_PASSKEY_NOTIF_EVT 3 /* passkey notification event */ -#define SMP_PASSKEY_REQ_EVT 4 /* passkey request event */ -#define SMP_OOB_REQ_EVT 5 /* OOB request event */ -#define SMP_NC_REQ_EVT 6 /* Numeric Comparison request event */ -#define SMP_COMPLT_EVT 7 /* SMP complete event */ -#define SMP_PEER_KEYPR_NOT_EVT 8 /* Peer keypress notification received event */ -#define SMP_SC_OOB_REQ_EVT 9 /* SC OOB request event (both local and peer OOB data */ -/* can be expected in response) */ -#define SMP_SC_LOC_OOB_DATA_UP_EVT 10 /* SC OOB local data set is created */ -/* (as result of SMP_CrLocScOobData(...)) */ -#define SMP_BR_KEYS_REQ_EVT 12 /* SMP over BR keys request event */ -typedef UINT8 tSMP_EVT; - - -/* pairing failure reason code */ -#define SMP_PASSKEY_ENTRY_FAIL 0x01 -#define SMP_OOB_FAIL 0x02 -#define SMP_PAIR_AUTH_FAIL 0x03 -#define SMP_CONFIRM_VALUE_ERR 0x04 -#define SMP_PAIR_NOT_SUPPORT 0x05 -#define SMP_ENC_KEY_SIZE 0x06 -#define SMP_INVALID_CMD 0x07 -#define SMP_PAIR_FAIL_UNKNOWN 0x08 -#define SMP_REPEATED_ATTEMPTS 0x09 -#define SMP_INVALID_PARAMETERS 0x0A -#define SMP_DHKEY_CHK_FAIL 0x0B -#define SMP_NUMERIC_COMPAR_FAIL 0x0C -#define SMP_BR_PARING_IN_PROGR 0x0D -#define SMP_XTRANS_DERIVE_NOT_ALLOW 0x0E -#define SMP_MAX_FAIL_RSN_PER_SPEC SMP_XTRANS_DERIVE_NOT_ALLOW - -/* self defined error code */ -#define SMP_PAIR_INTERNAL_ERR (SMP_MAX_FAIL_RSN_PER_SPEC + 0x01) /* 0x0E */ - -/* 0x0F unknown IO capability, unable to decide association model */ -#define SMP_UNKNOWN_IO_CAP (SMP_MAX_FAIL_RSN_PER_SPEC + 0x02) /* 0x0F */ - -#define SMP_INIT_FAIL (SMP_MAX_FAIL_RSN_PER_SPEC + 0x03) /* 0x10 */ -#define SMP_CONFIRM_FAIL (SMP_MAX_FAIL_RSN_PER_SPEC + 0x04) /* 0x11 */ -#define SMP_BUSY (SMP_MAX_FAIL_RSN_PER_SPEC + 0x05) /* 0x12 */ -#define SMP_ENC_FAIL (SMP_MAX_FAIL_RSN_PER_SPEC + 0x06) /* 0x13 */ -#define SMP_STARTED (SMP_MAX_FAIL_RSN_PER_SPEC + 0x07) /* 0x14 */ -#define SMP_RSP_TIMEOUT (SMP_MAX_FAIL_RSN_PER_SPEC + 0x08) /* 0x15 */ -#define SMP_DIV_NOT_AVAIL (SMP_MAX_FAIL_RSN_PER_SPEC + 0x09) /* 0x16 */ - -/* 0x17 unspecified failed reason */ -#define SMP_FAIL (SMP_MAX_FAIL_RSN_PER_SPEC + 0x0A) /* 0x17 */ - -#define SMP_CONN_TOUT (SMP_MAX_FAIL_RSN_PER_SPEC + 0x0B) -#define SMP_SUCCESS 0 - -typedef UINT8 tSMP_STATUS; - - -/* Device IO capability */ -#define SMP_IO_CAP_OUT BTM_IO_CAP_OUT /* DisplayOnly */ -#define SMP_IO_CAP_IO BTM_IO_CAP_IO /* DisplayYesNo */ -#define SMP_IO_CAP_IN BTM_IO_CAP_IN /* KeyboardOnly */ -#define SMP_IO_CAP_NONE BTM_IO_CAP_NONE /* NoInputNoOutput */ -#define SMP_IO_CAP_KBDISP BTM_IO_CAP_KBDISP /* Keyboard Display */ -#define SMP_IO_CAP_MAX BTM_IO_CAP_MAX -typedef UINT8 tSMP_IO_CAP; - -#ifndef SMP_DEFAULT_IO_CAPS -#define SMP_DEFAULT_IO_CAPS SMP_IO_CAP_KBDISP -#endif - -/* OOB data present or not */ -enum { - SMP_OOB_NONE, - SMP_OOB_PRESENT, - SMP_OOB_UNKNOWN -}; -typedef UINT8 tSMP_OOB_FLAG; - -/* type of OOB data required from application */ -enum { - SMP_OOB_INVALID_TYPE, - SMP_OOB_PEER, - SMP_OOB_LOCAL, - SMP_OOB_BOTH -}; -typedef UINT8 tSMP_OOB_DATA_TYPE; - -#define SMP_AUTH_NO_BOND 0x00 -#define SMP_AUTH_GEN_BOND 0x01 //todo sdh change GEN_BOND to BOND - -/* SMP Authentication requirement */ -#define SMP_AUTH_YN_BIT (1 << 2) -#define SMP_SC_SUPPORT_BIT (1 << 3) -#define SMP_KP_SUPPORT_BIT (1 << 4) - -#define SMP_AUTH_MASK (SMP_AUTH_GEN_BOND|SMP_AUTH_YN_BIT|SMP_SC_SUPPORT_BIT|SMP_KP_SUPPORT_BIT) - -#define SMP_AUTH_BOND SMP_AUTH_GEN_BOND - -/* no MITM, No Bonding, encryption only */ -#define SMP_AUTH_NB_ENC_ONLY 0x00 //(SMP_AUTH_MASK | BTM_AUTH_SP_NO) - -/* MITM, No Bonding, Use IO Capability to determine authentication procedure */ -#define SMP_AUTH_NB_IOCAP (SMP_AUTH_NO_BOND | SMP_AUTH_YN_BIT) - -/* No MITM, General Bonding, Encryption only */ -#define SMP_AUTH_GB_ENC_ONLY (SMP_AUTH_GEN_BOND ) - -/* MITM, General Bonding, Use IO Capability to determine authentication procedure */ -#define SMP_AUTH_GB_IOCAP (SMP_AUTH_GEN_BOND | SMP_AUTH_YN_BIT) - -/* Secure Connections, no MITM, no Bonding */ -#define SMP_AUTH_SC_ENC_ONLY (SMP_SC_SUPPORT_BIT) - -/* Secure Connections, no MITM, Bonding */ -#define SMP_AUTH_SC_GB (SMP_SC_SUPPORT_BIT | SMP_AUTH_GEN_BOND) - -/* Secure Connections, MITM, no Bonding */ -#define SMP_AUTH_SC_MITM_NB (SMP_SC_SUPPORT_BIT | SMP_AUTH_YN_BIT | SMP_AUTH_NO_BOND) - -/* Secure Connections, MITM, Bonding */ -#define SMP_AUTH_SC_MITM_GB (SMP_SC_SUPPORT_BIT | SMP_AUTH_YN_BIT | SMP_AUTH_GEN_BOND) - -/* All AuthReq RFU bits are set to 1 - NOTE: reserved bit in Bonding_Flags is not set */ -#define SMP_AUTH_ALL_RFU_SET 0xF8 - -typedef UINT8 tSMP_AUTH_REQ; - -#define SMP_SEC_NONE 0 -#define SMP_SEC_UNAUTHENTICATE (1 << 0) -#define SMP_SEC_AUTHENTICATED (1 << 2) -typedef UINT8 tSMP_SEC_LEVEL; - -/* Maximum Encryption Key Size range */ -#define SMP_ENCR_KEY_SIZE_MIN 7 -#define SMP_ENCR_KEY_SIZE_MAX 16 - -/* SMP key types */ -#define SMP_SEC_KEY_TYPE_ENC (1 << 0) /* encryption key */ -#define SMP_SEC_KEY_TYPE_ID (1 << 1) /* identity key */ -#define SMP_SEC_KEY_TYPE_CSRK (1 << 2) /* slave CSRK */ -#define SMP_SEC_KEY_TYPE_LK (1 << 3) /* BR/EDR link key */ -typedef UINT8 tSMP_KEYS; - -#define SMP_BR_SEC_DEFAULT_KEY (SMP_SEC_KEY_TYPE_ENC | SMP_SEC_KEY_TYPE_ID | \ - SMP_SEC_KEY_TYPE_CSRK) - -/* default security key distribution value */ -#define SMP_SEC_DEFAULT_KEY (SMP_SEC_KEY_TYPE_ENC | SMP_SEC_KEY_TYPE_ID | \ - SMP_SEC_KEY_TYPE_CSRK | SMP_SEC_KEY_TYPE_LK) - -#define SMP_SC_KEY_STARTED 0 /* passkey entry started */ -#define SMP_SC_KEY_ENTERED 1 /* passkey digit entered */ -#define SMP_SC_KEY_ERASED 2 /* passkey digit erased */ -#define SMP_SC_KEY_CLEARED 3 /* passkey cleared */ -#define SMP_SC_KEY_COMPLT 4 /* passkey entry completed */ -#define SMP_SC_KEY_OUT_OF_RANGE 5 /* out of range */ -typedef UINT8 tSMP_SC_KEY_TYPE; - -/* data type for BTM_SP_IO_REQ_EVT */ -typedef struct { - tSMP_IO_CAP io_cap; /* local IO capabilities */ - tSMP_OOB_FLAG oob_data; /* OOB data present (locally) for the peer device */ - tSMP_AUTH_REQ auth_req; /* Authentication required (for local device) */ - UINT8 max_key_size; /* max encryption key size */ - tSMP_KEYS init_keys; /* initiator keys to be distributed */ - tSMP_KEYS resp_keys; /* responder keys */ -} tSMP_IO_REQ; - -typedef struct { - tSMP_STATUS reason; - tSMP_SEC_LEVEL sec_level; - BOOLEAN is_pair_cancel; - BOOLEAN smp_over_br; -} tSMP_CMPL; - -typedef struct { - BT_OCTET32 x; - BT_OCTET32 y; -} tSMP_PUBLIC_KEY; - -/* the data associated with the info sent to the peer via OOB interface */ -typedef struct { - BOOLEAN present; - BT_OCTET16 randomizer; - BT_OCTET16 commitment; - - tBLE_BD_ADDR addr_sent_to; - BT_OCTET32 private_key_used; /* is used to calculate: */ - /* publ_key_used = P-256(private_key_used, curve_p256.G) - send it to the */ - /* other side */ - /* dhkey = P-256(private_key_used, publ key rcvd from the other side) */ - tSMP_PUBLIC_KEY publ_key_used; /* P-256(private_key_used, curve_p256.G) */ -} tSMP_LOC_OOB_DATA; - -/* the data associated with the info received from the peer via OOB interface */ -typedef struct { - BOOLEAN present; - BT_OCTET16 randomizer; - BT_OCTET16 commitment; - tBLE_BD_ADDR addr_rcvd_from; -} tSMP_PEER_OOB_DATA; - -typedef struct { - tSMP_LOC_OOB_DATA loc_oob_data; - tSMP_PEER_OOB_DATA peer_oob_data; -} tSMP_SC_OOB_DATA; - - -typedef union { - UINT32 passkey; - tSMP_IO_REQ io_req; /* IO request */ - tSMP_CMPL cmplt; - tSMP_OOB_DATA_TYPE req_oob_type; - tSMP_LOC_OOB_DATA loc_oob_data; -} tSMP_EVT_DATA; - - -/* AES Encryption output */ -typedef struct { - UINT8 status; - UINT8 param_len; - UINT16 opcode; - UINT8 param_buf[BT_OCTET16_LEN]; -} tSMP_ENC; - -/* Security Manager events - Called by the stack when Security Manager related events occur.*/ -typedef UINT8 (tSMP_CALLBACK) (tSMP_EVT event, BD_ADDR bd_addr, tSMP_EVT_DATA *p_data); - -/* callback function for CMAC algorithm -*/ -typedef void (tCMAC_CMPL_CBACK)(UINT8 *p_mac, UINT16 tlen, UINT32 sign_counter); - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif -/* API of SMP */ - -/******************************************************************************* -** -** Function SMP_Init -** -** Description This function initializes the SMP unit. -** -** Returns void -** -*******************************************************************************/ -extern void SMP_Init(void); - -/******************************************************************************* -** -** Function SMP_Free -** -** Description This function de initializes the SMP unit. -** -** Returns void -** -*******************************************************************************/ -extern void SMP_Free(void); - - -/******************************************************************************* -** -** Function SMP_SetTraceLevel -** -** Description This function sets the trace level for SMP. If called with -** a value of 0xFF, it simply returns the current trace level. -** -** Returns The new or current trace level -** -*******************************************************************************/ -extern UINT8 SMP_SetTraceLevel (UINT8 new_level); - -/******************************************************************************* -** -** Function SMP_Register -** -** Description This function register for the SMP service callback. -** -** Returns void -** -*******************************************************************************/ -extern BOOLEAN SMP_Register (tSMP_CALLBACK *p_cback); - -/******************************************************************************* -** -** Function SMP_Pair -** -** Description This function is called to start a SMP pairing. -** -** Returns SMP_STARTED if bond started, else otherwise exception. -** -*******************************************************************************/ -extern tSMP_STATUS SMP_Pair (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function SMP_BR_PairWith -** -** Description This function is called to start a SMP pairing over BR/EDR. -** -** Returns SMP_STARTED if pairing started, otherwise reason for failure. -** -*******************************************************************************/ -extern tSMP_STATUS SMP_BR_PairWith (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function SMP_PairCancel -** -** Description This function is called to cancel a SMP pairing. -** -** Returns TRUE - pairing cancelled -** -*******************************************************************************/ -extern BOOLEAN SMP_PairCancel (BD_ADDR bd_addr); - -/******************************************************************************* -** -** Function SMP_SecurityGrant -** -** Description This function is called to grant security process. -** -** Parameters bd_addr - peer device bd address. -** res - result of the operation SMP_SUCCESS if success. -** Otherwise, SMP_REPEATED_ATTEMPTS is too many attempts. -** -** Returns None -** -*******************************************************************************/ -extern void SMP_SecurityGrant(BD_ADDR bd_addr, UINT8 res); - -/******************************************************************************* -** -** Function SMP_PasskeyReply -** -** Description This function is called after Security Manager submitted -** Passkey request to the application. -** -** Parameters: bd_addr - Address of the device for which PIN was requested -** res - result of the operation SMP_SUCCESS if success -** passkey - numeric value in the range of -** BTM_MIN_PASSKEY_VAL(0) - BTM_MAX_PASSKEY_VAL(999999(0xF423F)). -** -*******************************************************************************/ -extern void SMP_PasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey); - -/******************************************************************************* -** -** Function SMP_ConfirmReply -** -** Description This function is called after Security Manager submitted -** numeric comparison request to the application. -** -** Parameters: bd_addr - Address of the device with which numeric -** comparison was requested -** res - comparison result SMP_SUCCESS if success -** -*******************************************************************************/ -extern void SMP_ConfirmReply (BD_ADDR bd_addr, UINT8 res); - -/******************************************************************************* -** -** Function SMP_OobDataReply -** -** Description This function is called to provide the OOB data for -** SMP in response to SMP_OOB_REQ_EVT -** -** Parameters: bd_addr - Address of the peer device -** res - result of the operation SMP_SUCCESS if success -** p_data - SM Randomizer C. -** -*******************************************************************************/ -extern void SMP_OobDataReply(BD_ADDR bd_addr, tSMP_STATUS res, UINT8 len, - UINT8 *p_data); - -/******************************************************************************* -** -** Function SMP_SecureConnectionOobDataReply -** -** Description This function is called to provide the SC OOB data for -** SMP in response to SMP_SC_OOB_REQ_EVT -** -** Parameters: p_data - pointer to the data -** -*******************************************************************************/ -extern void SMP_SecureConnectionOobDataReply(UINT8 *p_data); - -/******************************************************************************* -** -** Function SMP_Encrypt -** -** Description This function is called to encrypt the data with the specified -** key -** -** Parameters: key - Pointer to key key[0] conatins the MSB -** key_len - key length -** plain_text - Pointer to data to be encrypted -** plain_text[0] conatins the MSB -** pt_len - plain text length -** p_out - pointer to the encrypted outputs -** -** Returns Boolean - TRUE: encryption is successful -*******************************************************************************/ -extern BOOLEAN SMP_Encrypt (UINT8 *key, UINT8 key_len, - UINT8 *plain_text, UINT8 pt_len, - tSMP_ENC *p_out); - -/******************************************************************************* -** -** Function SMP_KeypressNotification -** -** Description This function is called to notify SM about Keypress Notification. -** -** Parameters: bd_addr - Address of the device to send keypress -** notification to -** value - keypress notification parameter value -** -*******************************************************************************/ -extern void SMP_KeypressNotification (BD_ADDR bd_addr, UINT8 value); - -/******************************************************************************* -** -** Function SMP_CreateLocalSecureConnectionsOobData -** -** Description This function is called to start creation of local SC OOB -** data set (tSMP_LOC_OOB_DATA). -** -** Parameters: bd_addr - Address of the device to send OOB data block -** to. -** -** Returns Boolean - TRUE: creation of local SC OOB data set started. -*******************************************************************************/ -extern BOOLEAN SMP_CreateLocalSecureConnectionsOobData ( - tBLE_BD_ADDR *addr_to_send_to); - -#ifdef __cplusplus -} -#endif -#endif /* SMP_API_H */ diff --git a/tools/sdk/include/bluedroid/smp_int.h b/tools/sdk/include/bluedroid/smp_int.h deleted file mode 100644 index 734c3fcba36..00000000000 --- a/tools/sdk/include/bluedroid/smp_int.h +++ /dev/null @@ -1,535 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * This file contains internally used SMP definitions - * - ******************************************************************************/ -#ifndef SMP_INT_H -#define SMP_INT_H - -#if (BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE) - -#include "btu.h" -#include "btm_ble_api.h" -#include "btm_api.h" -#include "smp_api.h" - -#define SMP_MODEL_ENCRYPTION_ONLY 0 /* Legacy mode, Just Works model */ -#define SMP_MODEL_PASSKEY 1 /* Legacy mode, Passkey Entry model, this side inputs the key */ -#define SMP_MODEL_OOB 2 /* Legacy mode, OOB model */ -#define SMP_MODEL_KEY_NOTIF 3 /* Legacy mode, Passkey Entry model, this side displays the key */ -#define SMP_MODEL_SEC_CONN_JUSTWORKS 4 /* Secure Connections mode, Just Works model */ -#define SMP_MODEL_SEC_CONN_NUM_COMP 5 /* Secure Connections mode, Numeric Comparison model */ -#define SMP_MODEL_SEC_CONN_PASSKEY_ENT 6 /* Secure Connections mode, Passkey Entry model, */ -/* this side inputs the key */ -#define SMP_MODEL_SEC_CONN_PASSKEY_DISP 7 /* Secure Connections mode, Passkey Entry model, */ -/* this side displays the key */ -#define SMP_MODEL_SEC_CONN_OOB 8 /* Secure Connections mode, OOB model */ -#define SMP_MODEL_OUT_OF_RANGE 9 -typedef UINT8 tSMP_ASSO_MODEL; - - -#ifndef SMP_MAX_CONN -#define SMP_MAX_CONN 2 -#endif - -#define SMP_WAIT_FOR_RSP_TOUT 30 - -#define SMP_OPCODE_INIT 0x04 - -/* SMP events */ -#define SMP_PAIRING_REQ_EVT SMP_OPCODE_PAIRING_REQ -#define SMP_PAIRING_RSP_EVT SMP_OPCODE_PAIRING_RSP -#define SMP_CONFIRM_EVT SMP_OPCODE_CONFIRM -#define SMP_RAND_EVT SMP_OPCODE_RAND -#define SMP_PAIRING_FAILED_EVT SMP_OPCODE_PAIRING_FAILED -#define SMP_ENCRPTION_INFO_EVT SMP_OPCODE_ENCRYPT_INFO -#define SMP_MASTER_ID_EVT SMP_OPCODE_MASTER_ID -#define SMP_ID_INFO_EVT SMP_OPCODE_IDENTITY_INFO -#define SMP_ID_ADDR_EVT SMP_OPCODE_ID_ADDR -#define SMP_SIGN_INFO_EVT SMP_OPCODE_SIGN_INFO -#define SMP_SECURITY_REQ_EVT SMP_OPCODE_SEC_REQ - -#define SMP_PAIR_PUBLIC_KEY_EVT SMP_OPCODE_PAIR_PUBLIC_KEY -#define SMP_PAIR_KEYPRESS_NOTIFICATION_EVT SMP_OPCODE_PAIR_KEYPR_NOTIF - -#define SMP_PAIR_COMMITM_EVT SMP_OPCODE_PAIR_COMMITM - -#define SMP_SELF_DEF_EVT (SMP_PAIR_COMMITM_EVT + 1) -#define SMP_KEY_READY_EVT (SMP_SELF_DEF_EVT) -#define SMP_ENCRYPTED_EVT (SMP_SELF_DEF_EVT + 1) -#define SMP_L2CAP_CONN_EVT (SMP_SELF_DEF_EVT + 2) -#define SMP_L2CAP_DISCONN_EVT (SMP_SELF_DEF_EVT + 3) -#define SMP_IO_RSP_EVT (SMP_SELF_DEF_EVT + 4) -#define SMP_API_SEC_GRANT_EVT (SMP_SELF_DEF_EVT + 5) -#define SMP_TK_REQ_EVT (SMP_SELF_DEF_EVT + 6) -#define SMP_AUTH_CMPL_EVT (SMP_SELF_DEF_EVT + 7) -#define SMP_ENC_REQ_EVT (SMP_SELF_DEF_EVT + 8) -#define SMP_BOND_REQ_EVT (SMP_SELF_DEF_EVT + 9) -#define SMP_DISCARD_SEC_REQ_EVT (SMP_SELF_DEF_EVT + 10) - -#define SMP_PAIR_DHKEY_CHCK_EVT SMP_OPCODE_PAIR_DHKEY_CHECK - -#define SMP_PUBL_KEY_EXCH_REQ_EVT (SMP_SELF_DEF_EVT + 11) /* request to start public */ -/* key exchange */ - -#define SMP_LOC_PUBL_KEY_CRTD_EVT (SMP_SELF_DEF_EVT + 12) /* local public key created */ - -#define SMP_BOTH_PUBL_KEYS_RCVD_EVT (SMP_SELF_DEF_EVT + 13) /* both local and peer public */ -/* keys are saved in cb */ - -#define SMP_SC_DHKEY_CMPLT_EVT (SMP_SELF_DEF_EVT + 14) /* DHKey computation is completed,*/ -/* time to start SC phase1 */ - -#define SMP_HAVE_LOC_NONCE_EVT (SMP_SELF_DEF_EVT + 15) /* new local nonce is generated */ -/*and saved in p_cb->rand */ - -#define SMP_SC_PHASE1_CMPLT_EVT (SMP_SELF_DEF_EVT + 16) /* time to start SC phase2 */ - -#define SMP_SC_CALC_NC_EVT (SMP_SELF_DEF_EVT + 17) /* request to calculate number */ -/* for user check. Used only in the */ -/* numeric compare protocol */ - -/* Request to display the number for user check to the user.*/ -/* Used only in the numeric compare protocol */ -#define SMP_SC_DSPL_NC_EVT (SMP_SELF_DEF_EVT + 18) - -#define SMP_SC_NC_OK_EVT (SMP_SELF_DEF_EVT + 19) /* user confirms 'OK' numeric */ -/*comparison request */ - -/* both local and peer DHKey Checks are already present - it is used on slave to prevent race condition */ -#define SMP_SC_2_DHCK_CHKS_PRES_EVT (SMP_SELF_DEF_EVT + 20) - -/* same meaning as SMP_KEY_READY_EVT to separate between SC and legacy actions */ -#define SMP_SC_KEY_READY_EVT (SMP_SELF_DEF_EVT + 21) -#define SMP_KEYPRESS_NOTIFICATION_EVENT (SMP_SELF_DEF_EVT + 22) - -#define SMP_SC_OOB_DATA_EVT (SMP_SELF_DEF_EVT + 23) /* SC OOB data from some */ -/* repository is provided */ - -#define SMP_CR_LOC_SC_OOB_DATA_EVT (SMP_SELF_DEF_EVT + 24) -#define SMP_MAX_EVT SMP_CR_LOC_SC_OOB_DATA_EVT - -typedef UINT8 tSMP_EVENT; - -/* Assumption it's only using the low 8 bits, if bigger than that, need to expand it to 16 bits */ -#define SMP_SEC_KEY_MASK 0x00ff - -/* SMP pairing state */ -enum { - SMP_STATE_IDLE, - SMP_STATE_WAIT_APP_RSP, - SMP_STATE_SEC_REQ_PENDING, - SMP_STATE_PAIR_REQ_RSP, - SMP_STATE_WAIT_CONFIRM, - SMP_STATE_CONFIRM, - SMP_STATE_RAND, - SMP_STATE_PUBLIC_KEY_EXCH, - SMP_STATE_SEC_CONN_PHS1_START, - SMP_STATE_WAIT_COMMITMENT, - SMP_STATE_WAIT_NONCE, - SMP_STATE_SEC_CONN_PHS2_START, - SMP_STATE_WAIT_DHK_CHECK, - SMP_STATE_DHK_CHECK, - SMP_STATE_ENCRYPTION_PENDING, - SMP_STATE_BOND_PENDING, - SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA, - SMP_STATE_MAX -}; -typedef UINT8 tSMP_STATE; - -/* SMP over BR/EDR events */ -#define SMP_BR_PAIRING_REQ_EVT SMP_OPCODE_PAIRING_REQ -#define SMP_BR_PAIRING_RSP_EVT SMP_OPCODE_PAIRING_RSP -#define SMP_BR_CONFIRM_EVT SMP_OPCODE_CONFIRM /* not expected over BR/EDR */ -#define SMP_BR_RAND_EVT SMP_OPCODE_RAND /* not expected over BR/EDR */ -#define SMP_BR_PAIRING_FAILED_EVT SMP_OPCODE_PAIRING_FAILED -#define SMP_BR_ENCRPTION_INFO_EVT SMP_OPCODE_ENCRYPT_INFO /* not expected over BR/EDR */ -#define SMP_BR_MASTER_ID_EVT SMP_OPCODE_MASTER_ID /* not expected over BR/EDR */ -#define SMP_BR_ID_INFO_EVT SMP_OPCODE_IDENTITY_INFO -#define SMP_BR_ID_ADDR_EVT SMP_OPCODE_ID_ADDR -#define SMP_BR_SIGN_INFO_EVT SMP_OPCODE_SIGN_INFO -#define SMP_BR_SECURITY_REQ_EVT SMP_OPCODE_SEC_REQ /* not expected over BR/EDR */ -#define SMP_BR_PAIR_PUBLIC_KEY_EVT SMP_OPCODE_PAIR_PUBLIC_KEY /* not expected over BR/EDR */ -#define SMP_BR_PAIR_DHKEY_CHCK_EVT SMP_OPCODE_PAIR_DHKEY_CHECK /* not expected over BR/EDR */ -#define SMP_BR_PAIR_KEYPR_NOTIF_EVT SMP_OPCODE_PAIR_KEYPR_NOTIF /* not expected over BR/EDR */ -#define SMP_BR_SELF_DEF_EVT SMP_BR_PAIR_KEYPR_NOTIF_EVT -#define SMP_BR_KEY_READY_EVT (SMP_BR_SELF_DEF_EVT + 1) -#define SMP_BR_ENCRYPTED_EVT (SMP_BR_SELF_DEF_EVT + 2) -#define SMP_BR_L2CAP_CONN_EVT (SMP_BR_SELF_DEF_EVT + 3) -#define SMP_BR_L2CAP_DISCONN_EVT (SMP_BR_SELF_DEF_EVT + 4) -#define SMP_BR_KEYS_RSP_EVT (SMP_BR_SELF_DEF_EVT + 5) -#define SMP_BR_API_SEC_GRANT_EVT (SMP_BR_SELF_DEF_EVT + 6) -#define SMP_BR_TK_REQ_EVT (SMP_BR_SELF_DEF_EVT + 7) -#define SMP_BR_AUTH_CMPL_EVT (SMP_BR_SELF_DEF_EVT + 8) -#define SMP_BR_ENC_REQ_EVT (SMP_BR_SELF_DEF_EVT + 9) -#define SMP_BR_BOND_REQ_EVT (SMP_BR_SELF_DEF_EVT + 10) -#define SMP_BR_DISCARD_SEC_REQ_EVT (SMP_BR_SELF_DEF_EVT + 11) -#define SMP_BR_MAX_EVT (SMP_BR_SELF_DEF_EVT + 12) -typedef UINT8 tSMP_BR_EVENT; - -/* SMP over BR/EDR pairing states */ -enum { - SMP_BR_STATE_IDLE = SMP_STATE_IDLE, - SMP_BR_STATE_WAIT_APP_RSP, - SMP_BR_STATE_PAIR_REQ_RSP, - SMP_BR_STATE_BOND_PENDING, - SMP_BR_STATE_MAX -}; -typedef UINT8 tSMP_BR_STATE; - -/* random and encrption activity state */ -enum { - SMP_GEN_COMPARE = 1, - SMP_GEN_CONFIRM, - - SMP_GEN_DIV_LTK, - SMP_GEN_DIV_CSRK, - SMP_GEN_RAND_V, - SMP_GEN_TK, - SMP_GEN_SRAND_MRAND, - SMP_GEN_SRAND_MRAND_CONT, - SMP_GENERATE_PRIVATE_KEY_0_7, - SMP_GENERATE_PRIVATE_KEY_8_15, - SMP_GENERATE_PRIVATE_KEY_16_23, - SMP_GENERATE_PRIVATE_KEY_24_31, - SMP_GEN_NONCE_0_7, - SMP_GEN_NONCE_8_15 -}; - -enum { - SMP_KEY_TYPE_TK, - SMP_KEY_TYPE_CFM, - SMP_KEY_TYPE_CMP, - SMP_KEY_TYPE_PEER_DHK_CHCK, - SMP_KEY_TYPE_STK, - SMP_KEY_TYPE_LTK -}; -typedef struct { - UINT8 key_type; - UINT8 *p_data; -} tSMP_KEY; - -typedef union { - UINT8 *p_data; /* UINT8 type data pointer */ - tSMP_KEY key; - UINT16 reason; - UINT32 passkey; - tSMP_OOB_DATA_TYPE req_oob_type; -} tSMP_INT_DATA; - -/* internal status mask */ -#define SMP_PAIR_FLAGS_WE_STARTED_DD (1) -#define SMP_PAIR_FLAGS_PEER_STARTED_DD (1 << 1) -#define SMP_PAIR_FLAGS_CMD_CONFIRM (1 << SMP_OPCODE_CONFIRM) /* 1 << 3 */ -#define SMP_PAIR_FLAG_ENC_AFTER_PAIR (1 << 4) -#define SMP_PAIR_FLAG_HAVE_PEER_DHK_CHK (1 << 5) /* used on slave to resolve race condition */ -#define SMP_PAIR_FLAG_HAVE_PEER_PUBL_KEY (1 << 6) /* used on slave to resolve race condition */ -#define SMP_PAIR_FLAG_HAVE_PEER_COMM (1 << 7) /* used to resolve race condition */ -#define SMP_PAIR_FLAG_HAVE_LOCAL_PUBL_KEY (1 << 8) /* used on slave to resolve race condition */ - -/* check if authentication requirement need MITM protection */ -#define SMP_NO_MITM_REQUIRED(x) (((x) & SMP_AUTH_YN_BIT) == 0) - -#define SMP_ENCRYT_KEY_SIZE 16 -#define SMP_ENCRYT_DATA_SIZE 16 -#define SMP_ECNCRPYT_STATUS HCI_SUCCESS - -typedef struct { - BD_ADDR bd_addr; - BT_HDR *p_copy; -} tSMP_REQ_Q_ENTRY; - -/* SMP control block */ -typedef struct { - tSMP_CALLBACK *p_callback; - TIMER_LIST_ENT rsp_timer_ent; - UINT8 trace_level; - BD_ADDR pairing_bda; - tSMP_STATE state; - BOOLEAN derive_lk; - BOOLEAN id_addr_rcvd; - tBLE_ADDR_TYPE id_addr_type; - BD_ADDR id_addr; - BOOLEAN smp_over_br; - tSMP_BR_STATE br_state; /* if SMP over BR/ERD has priority over SMP */ - UINT8 failure; - UINT8 status; - UINT8 role; - UINT16 flags; - UINT8 cb_evt; - tSMP_SEC_LEVEL sec_level; - BOOLEAN connect_initialized; - BT_OCTET16 confirm; - BT_OCTET16 rconfirm; - BT_OCTET16 rrand; /* for SC this is peer nonce */ - BT_OCTET16 rand; /* for SC this is local nonce */ - BT_OCTET32 private_key; - BT_OCTET32 dhkey; - BT_OCTET16 commitment; - BT_OCTET16 remote_commitment; - BT_OCTET16 local_random; /* local randomizer - passkey or OOB randomizer */ - BT_OCTET16 peer_random; /* peer randomizer - passkey or OOB randomizer */ - BT_OCTET16 dhkey_check; - BT_OCTET16 remote_dhkey_check; - tSMP_PUBLIC_KEY loc_publ_key; - tSMP_PUBLIC_KEY peer_publ_key; - tSMP_OOB_DATA_TYPE req_oob_type; - tSMP_SC_OOB_DATA sc_oob_data; - tSMP_IO_CAP peer_io_caps; - tSMP_IO_CAP local_io_capability; - tSMP_OOB_FLAG peer_oob_flag; - tSMP_OOB_FLAG loc_oob_flag; - tSMP_AUTH_REQ peer_auth_req; - tSMP_AUTH_REQ loc_auth_req; - BOOLEAN secure_connections_only_mode_required;/* TRUE if locally SM is required to operate */ - /* either in Secure Connections mode or not at all */ - tSMP_ASSO_MODEL selected_association_model; - BOOLEAN le_secure_connections_mode_is_used; - BOOLEAN le_sc_kp_notif_is_used; - tSMP_SC_KEY_TYPE local_keypress_notification; - tSMP_SC_KEY_TYPE peer_keypress_notification; - UINT8 round; /* authentication stage 1 round for passkey association model */ - UINT32 number_to_display; - BT_OCTET16 mac_key; - UINT8 peer_enc_size; - UINT8 loc_enc_size; - UINT8 peer_i_key; - UINT8 peer_r_key; - UINT8 local_i_key; - UINT8 local_r_key; - - BT_OCTET16 tk; - BT_OCTET16 ltk; - UINT16 div; - BT_OCTET16 csrk; /* storage for local CSRK */ - UINT16 ediv; - BT_OCTET8 enc_rand; - UINT8 rand_enc_proc_state; - UINT8 addr_type; - BD_ADDR local_bda; - BOOLEAN is_pair_cancel; - BOOLEAN discard_sec_req; - UINT8 rcvd_cmd_code; - UINT8 rcvd_cmd_len; - UINT16 total_tx_unacked; - BOOLEAN wait_for_authorization_complete; -} tSMP_CB; - -/* Server Action functions are of this type */ -typedef void (*tSMP_ACT)(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); - - -#ifdef __cplusplus -extern "C" -{ -#endif - -#if SMP_DYNAMIC_MEMORY == FALSE -extern tSMP_CB smp_cb; -#else -extern tSMP_CB *smp_cb_ptr; -#define smp_cb (*smp_cb_ptr) -#endif - -#ifdef __cplusplus -} -#endif - -/* Functions provided by att_main.c */ -extern void smp_init (void); - -/* smp main */ -extern void smp_sm_event(tSMP_CB *p_cb, tSMP_EVENT event, void *p_data); - -extern void smp_proc_sec_request(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_set_fail_nc (BOOLEAN enable); -extern void smp_set_fail_conf (BOOLEAN enable); -extern void smp_set_passk_entry_fail(BOOLEAN enable); -extern void smp_set_oob_fail(BOOLEAN enable); -extern void smp_set_peer_sc_notif(BOOLEAN enable); -extern void smp_aes_cmac_rfc4493_chk (UINT8 *key, UINT8 *msg, UINT8 msg_len, - UINT8 mac_len, UINT8 *mac); -extern void smp_f4_calc_chk (UINT8 *U, UINT8 *V, UINT8 *X, UINT8 *Z, UINT8 *mac); -extern void smp_g2_calc_chk (UINT8 *U, UINT8 *V, UINT8 *X, UINT8 *Y); -extern void smp_h6_calc_chk (UINT8 *key, UINT8 *key_id, UINT8 *mac); -extern void smp_f5_key_calc_chk (UINT8 *w, UINT8 *mac); -extern void smp_f5_mackey_or_ltk_calc_chk(UINT8 *t, UINT8 *counter, - UINT8 *key_id, UINT8 *n1, - UINT8 *n2, UINT8 *a1, UINT8 *a2, - UINT8 *length, UINT8 *mac); -extern void smp_f5_calc_chk (UINT8 *w, UINT8 *n1, UINT8 *n2, UINT8 *a1, UINT8 *a2, - UINT8 *mac_key, UINT8 *ltk); -extern void smp_f6_calc_chk (UINT8 *w, UINT8 *n1, UINT8 *n2, UINT8 *r, - UINT8 *iocap, UINT8 *a1, UINT8 *a2, UINT8 *mac); -/* smp_main */ -extern void smp_sm_event(tSMP_CB *p_cb, tSMP_EVENT event, void *p_data); -extern tSMP_STATE smp_get_state(void); -extern void smp_set_state(tSMP_STATE state); - -/* smp_br_main */ -extern void smp_br_state_machine_event(tSMP_CB *p_cb, tSMP_BR_EVENT event, void *p_data); -extern tSMP_BR_STATE smp_get_br_state(void); -extern void smp_set_br_state(tSMP_BR_STATE state); - - -/* smp_act.c */ -extern void smp_send_pair_req(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_confirm(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_pair_fail(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_rand(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_pair_public_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_commitment(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_dhkey_check(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_keypress_notification(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_pair_fail(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_confirm(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_rand(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_pairing_public_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_enc_info(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_master_id(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_id_info(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_id_addr(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_sec_grant(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_sec_req(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_sl_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_start_enc(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_enc_cmpl(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_discard(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_pairing_cmpl(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_decide_association_model(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_app_cback(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_compare(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_check_auth_req(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_io_response(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_id_info(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_enc_info(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_csrk_info(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_ltk_reply(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_pair_cmd(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_pair_terminate(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_idle_terminate(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_send_pair_rsp(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_key_distribution(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_proc_srk_info(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_generate_csrk(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_fast_conn_param(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_key_pick_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_both_have_public_keys(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_start_secure_connection_phase1(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_local_nonce(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_pairing_commitment(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_peer_nonce(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_dhkey_check(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_match_dhkey_checks(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_keypress_notification(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_move_to_secure_connections_phase2(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_phase_2_dhkey_checks_are_present(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_wait_for_both_public_keys(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_start_passkey_verification(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_secure_connection_oob_data(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_process_secure_connection_long_term_key(void); -extern void smp_set_local_oob_keys(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_set_local_oob_random_commitment(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_set_derive_link_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_derive_link_key_from_long_term_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_br_process_pairing_command(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_br_process_security_grant(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_br_process_slave_keys_response(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_br_send_pair_response(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_br_check_authorization_request(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_br_select_next_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_br_process_link_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_key_distribution_by_transport(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_br_pairing_complete(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); - -/* smp_l2c */ -extern void smp_l2cap_if_init (void); -extern void smp_data_ind (BD_ADDR bd_addr, BT_HDR *p_buf); - -/* smp_util.c */ -extern BOOLEAN smp_send_cmd(UINT8 cmd_code, tSMP_CB *p_cb); -extern void smp_cb_cleanup(tSMP_CB *p_cb); -extern void smp_reset_control_value(tSMP_CB *p_cb); -extern void smp_proc_pairing_cmpl(tSMP_CB *p_cb); -extern void smp_convert_string_to_tk(BT_OCTET16 tk, UINT32 passkey); -extern void smp_mask_enc_key(UINT8 loc_enc_size, UINT8 *p_data); -extern void smp_rsp_timeout(TIMER_LIST_ENT *p_tle); -extern void smp_xor_128(BT_OCTET16 a, BT_OCTET16 b); -extern BOOLEAN smp_encrypt_data (UINT8 *key, UINT8 key_len, - UINT8 *plain_text, UINT8 pt_len, - tSMP_ENC *p_out); -extern BOOLEAN smp_command_has_invalid_parameters(tSMP_CB *p_cb); -extern void smp_reject_unexpected_pairing_command(BD_ADDR bd_addr); -extern tSMP_ASSO_MODEL smp_select_association_model(tSMP_CB *p_cb); -extern void smp_reverse_array(UINT8 *arr, UINT8 len); -extern UINT8 smp_calculate_random_input(UINT8 *random, UINT8 round); -extern void smp_collect_local_io_capabilities(UINT8 *iocap, tSMP_CB *p_cb); -extern void smp_collect_peer_io_capabilities(UINT8 *iocap, tSMP_CB *p_cb); -extern void smp_collect_local_ble_address(UINT8 *le_addr, tSMP_CB *p_cb); -extern void smp_collect_peer_ble_address(UINT8 *le_addr, tSMP_CB *p_cb); -extern BOOLEAN smp_check_commitment(tSMP_CB *p_cb); -extern void smp_save_secure_connections_long_term_key(tSMP_CB *p_cb); -extern BOOLEAN smp_calculate_f5_mackey_and_long_term_key(tSMP_CB *p_cb); -extern void smp_remove_fixed_channel(tSMP_CB *p_cb); -extern BOOLEAN smp_request_oob_data(tSMP_CB *p_cb); - -/* smp_keys.c */ -extern void smp_generate_srand_mrand_confirm (tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_generate_compare (tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_generate_stk (tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_generate_ltk(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_generate_passkey (tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_generate_rand_cont(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_create_private_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_use_oob_private_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_compute_dhkey(tSMP_CB *p_cb); -extern void smp_calculate_local_commitment(tSMP_CB *p_cb); -extern void smp_calculate_peer_commitment(tSMP_CB *p_cb, BT_OCTET16 output_buf); -extern void smp_calculate_numeric_comparison_display_number(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_calculate_local_dhkey_check(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_calculate_peer_dhkey_check(tSMP_CB *p_cb, tSMP_INT_DATA *p_data); -extern void smp_start_nonce_generation(tSMP_CB *p_cb); -extern BOOLEAN smp_calculate_link_key_from_long_term_key(tSMP_CB *p_cb); -extern BOOLEAN smp_calculate_long_term_key_from_link_key(tSMP_CB *p_cb); -extern void smp_calculate_f4(UINT8 *u, UINT8 *v, UINT8 *x, UINT8 z, UINT8 *c); -extern UINT32 smp_calculate_g2(UINT8 *u, UINT8 *v, UINT8 *x, UINT8 *y); -extern BOOLEAN smp_calculate_f5(UINT8 *w, UINT8 *n1, UINT8 *n2, UINT8 *a1, UINT8 *a2, - UINT8 *mac_key, UINT8 *ltk); -extern BOOLEAN smp_calculate_f5_mackey_or_long_term_key(UINT8 *t, UINT8 *counter, - UINT8 *key_id, UINT8 *n1, UINT8 *n2, UINT8 *a1, - UINT8 *a2, UINT8 *length, UINT8 *mac); -extern BOOLEAN smp_calculate_f5_key(UINT8 *w, UINT8 *t); -extern BOOLEAN smp_calculate_f6(UINT8 *w, UINT8 *n1, UINT8 *n2, UINT8 *r, UINT8 *iocap, - UINT8 *a1, UINT8 *a2, UINT8 *f3); -extern BOOLEAN smp_calculate_h6(UINT8 *w, UINT8 *keyid, UINT8 *h2); -#if SMP_DEBUG == TRUE -extern void smp_debug_print_nbyte_little_endian (UINT8 *p, const UINT8 *key_name, - UINT8 len); -#endif - -/* smp_cmac.c */ -extern BOOLEAN aes_cipher_msg_auth_code(BT_OCTET16 key, UINT8 *input, UINT16 length, - UINT16 tlen, UINT8 *p_signature); -extern void print128(BT_OCTET16 x, const UINT8 *key_name); - -#endif ///BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE - -#endif /* SMP_INT_H */ diff --git a/tools/sdk/include/bluedroid/srvc_api.h b/tools/sdk/include/bluedroid/srvc_api.h deleted file mode 100644 index a7a46b8e8f6..00000000000 --- a/tools/sdk/include/bluedroid/srvc_api.h +++ /dev/null @@ -1,210 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2013 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 SRVC_DIS_API_H -#define SRVC_DIS_API_H - -#include "bt_target.h" -#include "gatt_api.h" -#include "gattdefs.h" - -#define DIS_SUCCESS GATT_SUCCESS -#define DIS_ILLEGAL_PARAM GATT_ILLEGAL_PARAMETER -#define DIS_NO_RESOURCES GATT_NO_RESOURCES -typedef UINT8 tDIS_STATUS; - - -/***************************************************************************** -** Data structure for DIS -*****************************************************************************/ - -#define DIS_ATTR_SYS_ID_BIT 0x0001 -#define DIS_ATTR_MODEL_NUM_BIT 0x0002 -#define DIS_ATTR_SERIAL_NUM_BIT 0x0004 -#define DIS_ATTR_FW_NUM_BIT 0x0008 -#define DIS_ATTR_HW_NUM_BIT 0x0010 -#define DIS_ATTR_SW_NUM_BIT 0x0020 -#define DIS_ATTR_MANU_NAME_BIT 0x0040 -#define DIS_ATTR_IEEE_DATA_BIT 0x0080 -#define DIS_ATTR_PNP_ID_BIT 0x0100 -typedef UINT16 tDIS_ATTR_MASK; - -#define DIS_ATTR_ALL_MASK 0xffff - -typedef tDIS_ATTR_MASK tDIS_ATTR_BIT ; - -typedef struct { - UINT16 len; - UINT8 *p_data; -} tDIS_STRING; - -typedef struct { - UINT16 vendor_id; - UINT16 product_id; - UINT16 product_version; - UINT8 vendor_id_src; - -} tDIS_PNP_ID; - -typedef union { - UINT64 system_id; - tDIS_PNP_ID pnp_id; - tDIS_STRING data_str; -} tDIS_ATTR; - -#define DIS_MAX_STRING_DATA 7 - -typedef struct { - UINT16 attr_mask; - UINT64 system_id; - tDIS_PNP_ID pnp_id; - UINT8 *data_string[DIS_MAX_STRING_DATA]; -} tDIS_VALUE; - - -typedef void (tDIS_READ_CBACK)(BD_ADDR addr, tDIS_VALUE *p_dis_value); - -/***************************************************************************** -** Data structure used by Battery Service -*****************************************************************************/ -typedef struct { - BD_ADDR remote_bda; - BOOLEAN need_rsp; - UINT16 clt_cfg; -} tBA_WRITE_DATA; - -#define BA_READ_CLT_CFG_REQ 1 -#define BA_READ_PRE_FMT_REQ 2 -#define BA_READ_RPT_REF_REQ 3 -#define BA_READ_LEVEL_REQ 4 -#define BA_WRITE_CLT_CFG_REQ 5 - -typedef void (tBA_CBACK)(UINT8 app_id, UINT8 event, tBA_WRITE_DATA *p_data); - -#define BA_LEVEL_NOTIFY 0x01 -#define BA_LEVEL_PRE_FMT 0x02 -#define BA_LEVEL_RPT_REF 0x04 -typedef UINT8 tBA_LEVEL_DESCR; - -typedef struct { - BOOLEAN is_pri; - tBA_LEVEL_DESCR ba_level_descr; - tGATT_TRANSPORT transport; - tBA_CBACK *p_cback; - -} tBA_REG_INFO; - -typedef union { - UINT8 ba_level; - UINT16 clt_cfg; - tGATT_CHAR_RPT_REF rpt_ref; - tGATT_CHAR_PRES pres_fmt; -} tBA_RSP_DATA; - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ -#ifdef __cplusplus -extern "C" -{ -#endif -/***************************************************************************** -** Service Engine API -*****************************************************************************/ -/******************************************************************************* -** -** Function srvc_eng_init -** -** Description Initializa the GATT Service engine, register a GATT application -** as for a central service management. -** -*******************************************************************************/ -extern tGATT_STATUS srvc_eng_init (void); - - -/***************************************************************************** -** DIS Server Function -*****************************************************************************/ - -/******************************************************************************* -** -** Function DIS_SrInit -** -** Description Initializa the Device Information Service Server. -** -*******************************************************************************/ -extern tDIS_STATUS DIS_SrInit (tDIS_ATTR_MASK dis_attr_mask); -/******************************************************************************* -** -** Function DIS_SrUpdate -** -** Description Update the DIS server attribute values -** -*******************************************************************************/ -extern tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT dis_attr_bit, tDIS_ATTR *p_info); -/***************************************************************************** -** DIS Client Function -*****************************************************************************/ -/******************************************************************************* -** -** Function DIS_ReadDISInfo -** -** Description Read remote device DIS information. -** -** Returns void -** -*******************************************************************************/ -extern BOOLEAN DIS_ReadDISInfo(BD_ADDR peer_bda, tDIS_READ_CBACK *p_cback, - tDIS_ATTR_MASK mask); - -/******************************************************************************* -** BATTERY SERVICE API -*******************************************************************************/ -/******************************************************************************* -** -** Function Battery_Instantiate -** -** Description Instantiate a Battery service -** -*******************************************************************************/ -extern UINT16 Battery_Instantiate (UINT8 app_id, tBA_REG_INFO *p_reg_info); - -/******************************************************************************* -** -** Function Battery_Rsp -** -** Description Respond to a battery service request -** -*******************************************************************************/ -extern void Battery_Rsp (UINT8 app_id, tGATT_STATUS st, UINT8 event, tBA_RSP_DATA *p_rsp); -/******************************************************************************* -** -** Function Battery_Notify -** -** Description Send battery level notification -** -*******************************************************************************/ -extern void Battery_Notify (UINT8 app_id, BD_ADDR remote_bda, UINT8 battery_level); - - -#ifdef __cplusplus - -} -#endif - -#endif diff --git a/tools/sdk/include/bluedroid/srvc_battery_int.h b/tools/sdk/include/bluedroid/srvc_battery_int.h deleted file mode 100644 index 4979f101eda..00000000000 --- a/tools/sdk/include/bluedroid/srvc_battery_int.h +++ /dev/null @@ -1,79 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 SRVC_BATTERY_INT_H -#define SRVC_BATTERY_INT_H - -#include "bt_target.h" -#include "srvc_api.h" -#include "gatt_api.h" - -#ifndef BA_MAX_INT_NUM -#define BA_MAX_INT_NUM 4 -#endif - -#define BATTERY_LEVEL_SIZE 1 - - -typedef struct { - UINT8 app_id; - UINT16 ba_level_hdl; - UINT16 clt_cfg_hdl; - UINT16 rpt_ref_hdl; - UINT16 pres_fmt_hdl; - - tBA_CBACK *p_cback; - - UINT16 pending_handle; - UINT8 pending_clcb_idx; - UINT8 pending_evt; - -} tBA_INST; - -typedef struct { - tBA_INST battery_inst[BA_MAX_INT_NUM]; - UINT8 inst_id; - BOOLEAN enabled; - -} tBATTERY_CB; - -#ifdef __cplusplus -extern "C" { -#endif - -/* Global GATT data */ -#if GATT_DYNAMIC_MEMORY == FALSE -extern tBATTERY_CB battery_cb; -#else -extern tBATTERY_CB *battery_cb_ptr; -#define battery_cb (*battery_cb_ptr) -#endif - - -extern BOOLEAN battery_valid_handle_range(UINT16 handle); - -extern UINT8 battery_s_write_attr_value(UINT8 clcb_idx, tGATT_WRITE_REQ *p_value, - tGATT_STATUS *p_status); -extern UINT8 battery_s_read_attr_value (UINT8 clcb_idx, UINT16 handle, tGATT_VALUE *p_value, BOOLEAN is_long, tGATT_STATUS *p_status); - - - -#ifdef __cplusplus -} -#endif -#endif diff --git a/tools/sdk/include/bluedroid/srvc_dis_int.h b/tools/sdk/include/bluedroid/srvc_dis_int.h deleted file mode 100644 index 5da32d1e460..00000000000 --- a/tools/sdk/include/bluedroid/srvc_dis_int.h +++ /dev/null @@ -1,82 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 1999-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 SRVC_DIS_INT_H -#define SRVC_DIS_INT_H - -#include "bt_target.h" -#include "srvc_api.h" -#include "gatt_api.h" - -#define DIS_MAX_CHAR_NUM 9 - - -typedef struct { - UINT16 uuid; - UINT16 handle; -} tDIS_DB_ENTRY; - -#define DIS_SYSTEM_ID_SIZE 8 -#define DIS_PNP_ID_SIZE 7 - - - -typedef struct { - tDIS_DB_ENTRY dis_attr[DIS_MAX_CHAR_NUM]; - tDIS_VALUE dis_value; - - tDIS_READ_CBACK *p_read_dis_cback; - - UINT16 service_handle; - UINT16 max_handle; - - BOOLEAN enabled; - - UINT8 dis_read_uuid_idx; - - tDIS_ATTR_MASK request_mask; -} tDIS_CB; - - - -#ifdef __cplusplus -extern "C" { -#endif - -/* Global GATT data */ -#if GATT_DYNAMIC_MEMORY == FALSE -extern tDIS_CB dis_cb; -#else -extern tDIS_CB *dis_cb_ptr; -#define dis_cb (*dis_cb_ptr) -#endif - - -extern BOOLEAN dis_valid_handle_range(UINT16 handle); -extern UINT8 dis_read_attr_value (UINT8 clcb_idx, UINT16 handle, tGATT_VALUE *p_value, - BOOLEAN is_long, tGATT_STATUS *p_status); -extern UINT8 dis_write_attr_value(tGATT_WRITE_REQ *p_data, tGATT_STATUS *p_status); - -extern void dis_c_cmpl_cback (tSRVC_CLCB *p_clcb, tGATTC_OPTYPE op, - tGATT_STATUS status, tGATT_CL_COMPLETE *p_data); - - -#ifdef __cplusplus -} -#endif -#endif diff --git a/tools/sdk/include/bluedroid/thread.h b/tools/sdk/include/bluedroid/thread.h deleted file mode 100644 index 6a92388d373..00000000000 --- a/tools/sdk/include/bluedroid/thread.h +++ /dev/null @@ -1,115 +0,0 @@ -// 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/xtensa_api.h" -#include "freertos/FreeRTOSConfig.h" -#include "freertos/FreeRTOS.h" -#include "freertos/queue.h" -#include "freertos/task.h" -#include "esp_task.h" -#include "bt_defs.h" - -#define portBASE_TYPE int - -struct bt_task_evt { - uint32_t sig; //task sig - void *par; //point to task param - void *cb; //point to function cb - void *arg; //point to function arg -}; -typedef struct bt_task_evt BtTaskEvt_t; - -typedef bt_status_t (* BtTaskCb_t)(void *arg); - -typedef enum { - SIG_HCI_HAL_RECV_PACKET = 0, - SIG_HCI_HAL_NUM, -} SIG_HCI_HAL_t; - - -typedef enum { - SIG_HCI_HOST_SEND_AVAILABLE = 0, - SIG_HCI_HOST_NUM, -} SIG_HCI_HOST_t; - -typedef enum { - SIG_BTU_START_UP = 0, - SIG_BTU_HCI_MSG, - SIG_BTU_BTA_MSG, - SIG_BTU_BTA_ALARM, - SIG_BTU_GENERAL_ALARM, - SIG_BTU_ONESHOT_ALARM, - SIG_BTU_L2CAP_ALARM, - SIG_BTU_NUM, -} SIG_BTU_t; - -#define TASK_PINNED_TO_CORE (CONFIG_BLUEDROID_PINNED_TO_CORE < portNUM_PROCESSORS ? CONFIG_BLUEDROID_PINNED_TO_CORE : tskNO_AFFINITY) - -#define HCI_HOST_TASK_PINNED_TO_CORE (TASK_PINNED_TO_CORE) -#define HCI_HOST_TASK_STACK_SIZE (2048 + BT_TASK_EXTRA_STACK_SIZE) -#define HCI_HOST_TASK_PRIO (configMAX_PRIORITIES - 3) -#define HCI_HOST_TASK_NAME "hciHostT" -#define HCI_HOST_QUEUE_LEN 40 - -#define HCI_H4_TASK_PINNED_TO_CORE (TASK_PINNED_TO_CORE) -#define HCI_H4_TASK_STACK_SIZE (2048 + BT_TASK_EXTRA_STACK_SIZE) -#define HCI_H4_TASK_PRIO (configMAX_PRIORITIES - 4) -#define HCI_H4_TASK_NAME "hciH4T" -#define HCI_H4_QUEUE_LEN 60 - -#define BTU_TASK_PINNED_TO_CORE (TASK_PINNED_TO_CORE) -#define BTU_TASK_STACK_SIZE (4096 + BT_TASK_EXTRA_STACK_SIZE) -#define BTU_TASK_PRIO (configMAX_PRIORITIES - 5) -#define BTU_TASK_NAME "btuT" -#define BTU_QUEUE_LEN 50 - -#define BTC_TASK_PINNED_TO_CORE (TASK_PINNED_TO_CORE) -#define BTC_TASK_STACK_SIZE (CONFIG_BTC_TASK_STACK_SIZE + BT_TASK_EXTRA_STACK_SIZE) //by menuconfig -#define BTC_TASK_NAME "btcT" -#define BTC_TASK_PRIO (configMAX_PRIORITIES - 6) -#define BTC_TASK_QUEUE_LEN 60 - -#define BTC_A2DP_SINK_TASK_PINNED_TO_CORE (TASK_PINNED_TO_CORE) -#define BTC_A2DP_SINK_TASK_STACK_SIZE (CONFIG_A2DP_SINK_TASK_STACK_SIZE + BT_TASK_EXTRA_STACK_SIZE) // by menuconfig -#define BTC_A2DP_SINK_TASK_NAME "BtA2dSinkT" -#define BTC_A2DP_SINK_TASK_PRIO (configMAX_PRIORITIES - 3) -#define BTC_A2DP_SINK_DATA_QUEUE_LEN (3) -#define BTC_A2DP_SINK_CTRL_QUEUE_LEN (5) -#define BTC_A2DP_SINK_TASK_QUEUE_SET_LEN (BTC_A2DP_SINK_DATA_QUEUE_LEN + BTC_A2DP_SINK_CTRL_QUEUE_LEN) - -#define BTC_A2DP_SOURCE_TASK_PINNED_TO_CORE (TASK_PINNED_TO_CORE) -#define BTC_A2DP_SOURCE_TASK_STACK_SIZE (CONFIG_A2DP_SOURCE_TASK_STACK_SIZE + BT_TASK_EXTRA_STACK_SIZE) // by menuconfig -#define BTC_A2DP_SOURCE_TASK_NAME "BtA2dSourceT" -#define BTC_A2DP_SOURCE_TASK_PRIO (configMAX_PRIORITIES - 3) -#define BTC_A2DP_SOURCE_DATA_QUEUE_LEN (3) -#define BTC_A2DP_SOURCE_CTRL_QUEUE_LEN (5) -#define BTC_A2DP_SOURCE_TASK_QUEUE_SET_LEN (BTC_A2DP_SOURCE_DATA_QUEUE_LEN + BTC_A2DP_SOURCE_CTRL_QUEUE_LEN) - -#define TASK_POST_NON_BLOCKING (0) -#define TASK_POST_BLOCKING (portMAX_DELAY) -typedef uint32_t task_post_t; /* Timeout of task post return, unit TICK */ - -typedef enum { - TASK_POST_SUCCESS = 0, - TASK_POST_FAIL, -} task_post_status_t; - -task_post_status_t btu_task_post(uint32_t sig, void *param, task_post_t timeout); -task_post_status_t hci_host_task_post(task_post_t timeout); -task_post_status_t hci_hal_h4_task_post(task_post_t timeout); - -#endif /* __THREAD_H__ */ diff --git a/tools/sdk/include/bluedroid/utl.h b/tools/sdk/include/bluedroid/utl.h deleted file mode 100644 index eab971e7dc6..00000000000 --- a/tools/sdk/include/bluedroid/utl.h +++ /dev/null @@ -1,169 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2003-2012 Broadcom Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/****************************************************************************** - * - * Basic utility functions. - * - ******************************************************************************/ -#ifndef UTL_H -#define UTL_H - -#include "bt_types.h" -// #include "bt_utils.h" - -/***************************************************************************** -** Constants -*****************************************************************************/ -/*** class of device settings ***/ -#define BTA_UTL_SET_COD_MAJOR_MINOR 0x01 -#define BTA_UTL_SET_COD_SERVICE_CLASS 0x02 /* only set the bits in the input */ -#define BTA_UTL_CLR_COD_SERVICE_CLASS 0x04 -#define BTA_UTL_SET_COD_ALL 0x08 /* take service class as the input (may clear some set bits!!) */ -#define BTA_UTL_INIT_COD 0x0a - -/***************************************************************************** -** Type Definitions -*****************************************************************************/ - -/** for utl_set_device_class() **/ -typedef struct { - UINT8 minor; - UINT8 major; - UINT16 service; -} tBTA_UTL_COD; - - -#ifdef __cplusplus -extern "C" -{ -#endif - -/***************************************************************************** -** External Function Declarations -*****************************************************************************/ - -/******************************************************************************* -** -** Function utl_str2int -** -** Description This utility function converts a character string to an -** integer. Acceptable values in string are 0-9. If invalid -** string or string value too large, -1 is returned. -** -** -** Returns Integer value or -1 on error. -** -*******************************************************************************/ -extern INT16 utl_str2int(const char *p_s); - -/******************************************************************************* -** -** Function utl_strucmp -** -** Description This utility function compares two strings in uppercase. -** String p_s must be uppercase. String p_t is converted to -** uppercase if lowercase. If p_s ends first, the substring -** match is counted as a match. -** -** -** Returns 0 if strings match, nonzero otherwise. -** -*******************************************************************************/ -extern int utl_strucmp(const char *p_s, const char *p_t); - -/******************************************************************************* -** -** Function utl_itoa -** -** Description This utility function converts a UINT16 to a string. The -** string is NULL-terminated. The length of the string is -** returned. -** -** -** Returns Length of string. -** -*******************************************************************************/ -extern UINT8 utl_itoa(UINT16 i, char *p_s); - -/******************************************************************************* -** -** Function utl_freebuf -** -** Description This function calls osi_free to free the buffer passed -** in, if buffer pointer is not NULL, and also initializes -** buffer pointer to NULL. -** -** -** Returns Nothing. -** -*******************************************************************************/ -extern void utl_freebuf(void **p); - -/******************************************************************************* -** -** Function utl_set_device_class -** -** Description This function updates the local Device Class. -** -** Parameters: -** p_cod - Pointer to the device class to set to -** -** cmd - the fields of the device class to update. -** BTA_UTL_SET_COD_MAJOR_MINOR, - overwrite major, minor class -** BTA_UTL_SET_COD_SERVICE_CLASS - set the bits in the input -** BTA_UTL_CLR_COD_SERVICE_CLASS - clear the bits in the input -** BTA_UTL_SET_COD_ALL - overwrite major, minor, set the bits in service class -** BTA_UTL_INIT_COD - overwrite major, minor, and service class -** -** Returns TRUE if successful, Otherwise FALSE -** -*******************************************************************************/ -extern BOOLEAN utl_set_device_class(tBTA_UTL_COD *p_cod, UINT8 cmd); - -/******************************************************************************* -** -** Function utl_isintstr -** -** Description This utility function checks if the given string is an -** integer string or not -** -** -** Returns TRUE if successful, Otherwise FALSE -** -*******************************************************************************/ -extern BOOLEAN utl_isintstr(const char *p_s); - -/******************************************************************************* -** -** Function utl_isdialstr -** -** Description This utility function checks if the given string contains -** only dial digits or not -** -** -** Returns TRUE if successful, Otherwise FALSE -** -*******************************************************************************/ -extern BOOLEAN utl_isdialstr(const char *p_s); - -#ifdef __cplusplus -} -#endif - -#endif /* UTL_H */ diff --git a/tools/sdk/include/bluedroid/version.h b/tools/sdk/include/bluedroid/version.h deleted file mode 100644 index c63b03bd2f5..00000000000 --- a/tools/sdk/include/bluedroid/version.h +++ /dev/null @@ -1,31 +0,0 @@ -/****************************************************************************** - * - * 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 _VERSION_H_ -#define _VERSION_H_ - -#include - -typedef struct { - uint8_t hci_version; - uint16_t hci_revision; - uint8_t lmp_version; - uint16_t manufacturer; - uint16_t lmp_subversion; -} bt_version_t; - -#endif /*_VERSION_H_*/ diff --git a/tools/sdk/include/bluedroid/wx_airsync_prf.h b/tools/sdk/include/bluedroid/wx_airsync_prf.h deleted file mode 100644 index f008ce64382..00000000000 --- a/tools/sdk/include/bluedroid/wx_airsync_prf.h +++ /dev/null @@ -1,110 +0,0 @@ -// 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. - -#include "prf_defs.h" - -#if (WX_AIRSYNC_CFG) - -#include "bt_target.h" -#include "gatt_api.h" -#include "gattdefs.h" -#include "bt_app_api.h" - - -/// Maximum Transmission Unit -#define ATT_DEFAULT_MTU (23) - -#define BLE_WECHAT_MAX_DATA_LEN (ATT_DEFAULT_MTU - 3) - - -//define the key serivce uuid -#define ATT_SVC_AIRSYNC 0xFEE7 -//define the airsync Char uuid -#define ATT_CHAR_AIRSYNC_WIT 0xFEC7 -#define ATT_CHAR_AIRSYBC_NTF 0xFEC8 -#define ATT_CHAR_AIRSYNC_READ 0xFEC9 - - -typedef void (tAIRSYNC_CBACK)(UINT8 app_id, UINT8 event, UINT8 len, UINT8 *data); - - -/// WX AirSync Service Attributes Indexes -enum { - WX_IDX_SVC, - WX_IDX_AIRSYNC_WIT_CHAR, - WX_IDX_AIRSYNC_WIT_VAL, - WX_IDX_AIRSYNC_NTF_CHAR, - WX_IDX_AIRSYNC_NTF_VAL, - WX_IDX_AIRSYNC_READ_CHAR, - WX_IDX_AIRSYNC_READ_VAL, - WX_IDX_AIRSYNC_NTF_CFG, - - WX_IDX_NB, -}; - -typedef struct { - BD_ADDR remote_bda; - BOOLEAN need_rsp; - UINT16 clt_cfg; -} tAirSync_WRITE_DATA; - -typedef struct { - BOOLEAN in_use; - BOOLEAN congest; - UINT16 conn_id; - BOOLEAN connected; - BD_ADDR remote_bda; - UINT32 trans_id; - UINT8 cur_srvc_id; - -} tAirSync_CLCB; - - -typedef struct { - UINT8 app_id; - UINT16 airsync_wirt_hdl; - UINT16 airsync_ntf_hdl; - UINT16 airsync_read_hdl; - UINT16 airsync_cfg_hdl; - - tAIRSYNC_CBACK *p_cback; - -} tAirSync_INST; - - -/* service engine control block */ -typedef struct { - tAirSync_CLCB clcb; /* connection link*/ - tGATT_IF gatt_if; - BOOLEAN enabled; - BOOLEAN is_primery; - tAirSync_INST airsync_inst; - UINT8 inst_id; -} tAIRSYNC_CB_ENV; - -void AirSync_CreateService(void); - -tAirSync_CLCB *airsync_env_clcb_alloc (UINT16 conn_id, BD_ADDR remote_bda); - -UINT16 AirSync_env_find_conn_id_by_bd_adddr(BD_ADDR bda); - -BOOLEAN AirSync_env_clcb_dealloc(UINT16 conn_id); - -tGATT_STATUS AirSync_Init(tAIRSYNC_CBACK *call_back); - -void AirSync_msg_notify(UINT8 len, UINT8 *button_msg); - -extern tAIRSYNC_CB_ENV airsync_cb_env; - -#endif ///WX_AIRSYNC_CFG diff --git a/tools/sdk/include/bootloader_support/bootloader_common.h b/tools/sdk/include/bootloader_support/bootloader_common.h new file mode 100644 index 00000000000..e884856f6d2 --- /dev/null +++ b/tools/sdk/include/bootloader_support/bootloader_common.h @@ -0,0 +1,118 @@ +// 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_data_types.h" +#include "esp_image_format.h" + +/// 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; + +/** + * @brief Calculate crc for the OTA data partition. + * + * @param[in] ota_data The OTA data partition. + * @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 partition + * + * @param[in] ota_data The OTA data partition. + * @return Returns true on valid, false otherwise. + */ +bool bootloader_common_ota_select_valid(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 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 Check if the image (bootloader and application) has valid chip ID and revision + * + * @param img_hdr: image header + * @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); + + +/** + * @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(); + +/** + * @brief Set the flash CS setup and hold time. + * + * 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 + */ +void bootloader_common_set_flash_cs_timing(); diff --git a/tools/sdk/include/bootloader_support/bootloader_random.h b/tools/sdk/include/bootloader_support/bootloader_random.h new file mode 100644 index 00000000000..bb3b2a81dde --- /dev/null +++ b/tools/sdk/include/bootloader_support/bootloader_random.h @@ -0,0 +1,49 @@ +// 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 + +/** + * @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); diff --git a/tools/sdk/include/bootloader_support/bootloader_util.h b/tools/sdk/include/bootloader_support/bootloader_util.h new file mode 100644 index 00000000000..30f8bd8d2c0 --- /dev/null +++ b/tools/sdk/include/bootloader_support/bootloader_util.h @@ -0,0 +1,34 @@ +// 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 + +/** + * @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) +{ + return (end1 > start2 && end2 > start1) || + !(end1 <= start2 || end2 <= start1); +} diff --git a/tools/sdk/include/bootloader_support/esp_efuse.h b/tools/sdk/include/bootloader_support/esp_efuse.h index 2f33b05a98b..047a971a4c1 100644 --- a/tools/sdk/include/bootloader_support/esp_efuse.h +++ b/tools/sdk/include/bootloader_support/esp_efuse.h @@ -15,6 +15,7 @@ #define _ESP_EFUSE_H #include "soc/efuse_reg.h" +#include "esp_err.h" #ifdef __cplusplus extern "C" { @@ -58,6 +59,45 @@ void esp_efuse_reset(void); */ void esp_efuse_disable_basic_rom_console(void); +/* @brief Encode one or more sets of 6 byte sequences into + * 8 bytes suitable for 3/4 Coding Scheme. + * + * This function is only useful if the CODING_SCHEME efuse + * is set to value 1 for 3/4 Coding Scheme. + * + * @param[in] in_bytes Pointer to a sequence of bytes to encode for 3/4 Coding Scheme. Must have length in_bytes_len. After being written to hardware, these bytes will read back as little-endian words. + * @param[out] out_words Pointer to array of words suitable for writing to efuse write registers. Array must contain 2 words (8 bytes) for every 6 bytes in in_bytes_len. Can be a pointer to efuse write registers. + * @param in_bytes_len. Length of array pointed to by in_bytes, in bytes. Must be a multiple of 6. + * + * @return ESP_ERR_INVALID_ARG if either pointer is null or in_bytes_len is not a multiple of 6. ESP_OK otherwise. + */ +esp_err_t esp_efuse_apply_34_encoding(const uint8_t *in_bytes, uint32_t *out_words, size_t in_bytes_len); + +/* @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 Returns chip version from efuse + * + * @return chip version + */ +uint8_t esp_efuse_get_chip_ver(void); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/bootloader_support/esp_flash_encrypt.h b/tools/sdk/include/bootloader_support/esp_flash_encrypt.h index ba370644a46..59eca33b246 100644 --- a/tools/sdk/include/bootloader_support/esp_flash_encrypt.h +++ b/tools/sdk/include/bootloader_support/esp_flash_encrypt.h @@ -17,7 +17,9 @@ #include #include "esp_attr.h" #include "esp_err.h" +#ifndef BOOTLOADER_BUILD #include "esp_spi_flash.h" +#endif #include "soc/efuse_reg.h" /** @@ -83,6 +85,8 @@ static inline /** @cond */ IRAM_ATTR /** @endcond */ bool esp_flash_encryption_e * @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. */ @@ -91,6 +95,7 @@ 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. * @@ -99,4 +104,14 @@ esp_err_t esp_flash_encrypt_check_and_update(void); */ 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. + * + * @return + */ +void esp_flash_write_protect_crypt_cnt(); + #endif diff --git a/tools/sdk/include/bootloader_support/esp_flash_partitions.h b/tools/sdk/include/bootloader_support/esp_flash_partitions.h index 843e5a283c3..b5f37aa5fc6 100644 --- a/tools/sdk/include/bootloader_support/esp_flash_partitions.h +++ b/tools/sdk/include/bootloader_support/esp_flash_partitions.h @@ -17,17 +17,17 @@ #include "esp_err.h" #include "esp_flash_data_types.h" #include +#include "sdkconfig.h" /* Pre-partition table fixed flash offsets */ #define ESP_BOOTLOADER_DIGEST_OFFSET 0x0 #define ESP_BOOTLOADER_OFFSET 0x1000 /* Offset of bootloader image. Has matching value in bootloader KConfig.projbuild file. */ -#define ESP_BOOTLOADER_SIZE (ESP_PARTITION_TABLE_OFFSET - ESP_BOOTLOADER_OFFSET) -#define ESP_PARTITION_TABLE_OFFSET 0x8000 /* Offset of partition table. Has matching value in partition_table 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 */ -/* @brief Verify the partition table (does not include verifying secure boot cryptographic signature) +/* @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. @@ -35,6 +35,13 @@ * * @return ESP_OK on success, ESP_ERR_INVALID_STATE if partition table is not valid. */ -esp_err_t esp_partition_table_basic_verify(const esp_partition_info_t *partition_table, bool log_errors, int *num_partitions); +esp_err_t esp_partition_table_verify(const esp_partition_info_t *partition_table, bool log_errors, int *num_partitions); + + +/* This function is included for compatibility with the ESP-IDF v3.x API */ +inline static __attribute__((deprecated)) esp_err_t esp_partition_table_basic_verify(const esp_partition_info_t *partition_table, bool log_errors, int *num_partitions) +{ + return esp_partition_table_verify(partition_table, log_errors, num_partitions); +} #endif diff --git a/tools/sdk/include/bootloader_support/esp_image_format.h b/tools/sdk/include/bootloader_support/esp_image_format.h index d2dcfd312cd..0e2bb5283dd 100644 --- a/tools/sdk/include/bootloader_support/esp_image_format.h +++ b/tools/sdk/include/bootloader_support/esp_image_format.h @@ -36,7 +36,7 @@ typedef enum { } esp_image_spi_mode_t; /* SPI flash clock frequency */ -enum { +typedef enum { ESP_IMAGE_SPI_SPEED_40M, ESP_IMAGE_SPI_SPEED_26M, ESP_IMAGE_SPI_SPEED_20M, @@ -55,6 +55,19 @@ typedef enum { #define ESP_IMAGE_HEADER_MAGIC 0xE9 +/** + * @brief ESP chip ID + * + */ +typedef enum { + ESP_CHIP_ID_ESP32 = 0x0000, /*!< chip ID: ESP32 */ + 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"); + + /* Main header of binary image */ typedef struct { uint8_t magic; @@ -71,8 +84,12 @@ typedef struct { uint8_t wp_pin; /* Drive settings for the SPI flash pins (read by ROM bootloader) */ uint8_t spi_pin_drv[3]; - /* Reserved bytes in ESP32 additional header space, currently unused */ - uint8_t reserved[11]; + /*!< Chip identification number */ + esp_chip_id_t chip_id; + /*!< Minimum chip revision supported by image */ + uint8_t min_chip_rev; + /*!< Reserved bytes in additional header space, currently unused */ + uint8_t reserved[8]; /* 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). */ @@ -81,6 +98,8 @@ typedef struct { _Static_assert(sizeof(esp_image_header_t) == 24, "binary image header should be 24 bytes"); +#define ESP_IMAGE_HASH_LEN 32 /* Length of the appended SHA-256 digest */ + /* Header of binary image segment */ typedef struct { uint32_t load_addr; @@ -96,11 +115,12 @@ typedef struct { 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; /* Mode selection for esp_image_load() */ typedef enum { - ESP_IMAGE_VERIFY, /* Verify image contents, load metadata. Print errorsors. */ + ESP_IMAGE_VERIFY, /* Verify image contents, load metadata. Print errors. */ ESP_IMAGE_VERIFY_SILENT, /* Verify image contents, load metadata. Don't print errors. */ #ifdef BOOTLOADER_BUILD ESP_IMAGE_LOAD, /* Verify image contents, load to memory. Print errors. */ @@ -110,6 +130,11 @@ typedef enum { /** * @brief Verify and (optionally, in bootloader mode) load an app image. * + * This name is deprecated and is included for compatibility with the ESP-IDF v3.x API. + * It will be removed in V4.0 version. + * Function has been renamed to esp_image_verify(). + * Use function esp_image_verify() to verify a image. And use function bootloader_load_image() to load image from a bootloader space. + * * If encryption is enabled, data will be transparently decrypted. * * @param mode Mode of operation (verify, silent verify, or load). @@ -130,7 +155,60 @@ typedef enum { * - 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_load(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data); +esp_err_t esp_image_load(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data) __attribute__((deprecated)); + +/** + * @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 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 Verify the bootloader image. @@ -142,6 +220,16 @@ esp_err_t esp_image_load(esp_image_load_mode_t mode, const esp_partition_pos_t * */ 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); + + typedef struct { uint32_t drom_addr; uint32_t drom_load_addr; diff --git a/tools/sdk/include/bootloader_support/esp_secure_boot.h b/tools/sdk/include/bootloader_support/esp_secure_boot.h index 6aa4b6285e2..370bdd36332 100644 --- a/tools/sdk/include/bootloader_support/esp_secure_boot.h +++ b/tools/sdk/include/bootloader_support/esp_secure_boot.h @@ -17,6 +17,14 @@ #include #include "soc/efuse_reg.h" +#include "sdkconfig.h" + +#ifdef CONFIG_SECURE_BOOT_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 diff --git a/tools/sdk/include/bluedroid/esp_a2dp_api.h b/tools/sdk/include/bt/esp_a2dp_api.h similarity index 99% rename from tools/sdk/include/bluedroid/esp_a2dp_api.h rename to tools/sdk/include/bt/esp_a2dp_api.h index 8117d4c54c8..3b002a405fb 100644 --- a/tools/sdk/include/bluedroid/esp_a2dp_api.h +++ b/tools/sdk/include/bt/esp_a2dp_api.h @@ -116,7 +116,7 @@ typedef union { 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 infomation */ + } audio_cfg; /*!< media codec configuration information */ /** * @brief ESP_A2D_MEDIA_CTRL_ACK_EVT @@ -147,12 +147,12 @@ 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 higer layer + * @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 argumetn len is -1, this value is ignored. + * @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); diff --git a/tools/sdk/include/bluedroid/esp_avrc_api.h b/tools/sdk/include/bt/esp_avrc_api.h similarity index 99% rename from tools/sdk/include/bluedroid/esp_avrc_api.h rename to tools/sdk/include/bt/esp_avrc_api.h index 228beb8ae67..e1f68392c86 100644 --- a/tools/sdk/include/bluedroid/esp_avrc_api.h +++ b/tools/sdk/include/bt/esp_avrc_api.h @@ -111,7 +111,7 @@ typedef enum { /// AVRC shuffle modes typedef enum { ESP_AVRC_PS_SHUFFLE_OFF = 0x1, /* 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 initialisation time to free unused BT Classic memory. + * esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT) at initialization time to free unused BT Classic memory. * - * If user never use bluetooth controller, could call esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) - * before esp_bt_controller_init or after esp_bt_controller_deinit. - * - * For example, user only use bluetooth to config SSID and PASSWORD of WIFI, after config, will never use bluetooth. - * Then, could call esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) after esp_bt_controller_deinit. + * 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 Manually clear scan duplicate list + * + * Note that scan duplicate list will be automatically cleared when the maximum amount of device in the filter is reached + * the amount of device in the filter can be configured in menuconfig. + * + * + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_ble_scan_dupilcate_list_flush(void); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/bluedroid/esp_bt_defs.h b/tools/sdk/include/bt/esp_bt_defs.h similarity index 87% rename from tools/sdk/include/bluedroid/esp_bt_defs.h rename to tools/sdk/include/bt/esp_bt_defs.h index aa3cdb45ad6..da93b87bcad 100644 --- a/tools/sdk/include/bluedroid/esp_bt_defs.h +++ b/tools/sdk/include/bt/esp_bt_defs.h @@ -48,9 +48,9 @@ typedef enum { 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 btm_api.h */ - ESP_BT_STATUS_CONTROL_LE_DATA_LEN_UNSUPPORTED,/* relate to BTM_CONTROL_LE_DATA_LEN_UNSUPPORTED in btm_api.h */ - ESP_BT_STATUS_ERR_ILLEGAL_PARAMETER_FMT, /* relate to HCI_ERR_ILLEGAL_PARAMETER_FMT in hcidefs.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, /* relate to BT_STATUS_MEMORY_FULL in bt_def.h */ } esp_bt_status_t; @@ -67,13 +67,13 @@ 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 btm_ble_api.h */ -#define ESP_BLE_CONN_INT_MAX 0x0C80 /*!< relate to BTM_BLE_CONN_INT_MAX in btm_ble_api.h */ -#define ESP_BLE_CONN_LATENCY_MAX 500 /*!< relate to ESP_BLE_CONN_LATENCY_MAX in btm_ble_api.h */ -#define ESP_BLE_CONN_SUP_TOUT_MIN 0x000A /*!< relate to BTM_BLE_CONN_SUP_TOUT_MIN in btm_ble_api.h */ -#define ESP_BLE_CONN_SUP_TOUT_MAX 0x0C80 /*!< relate to ESP_BLE_CONN_SUP_TOUT_MAX in 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 btm_ble_api.h */ -#define ESP_BLE_SCAN_PARAM_UNDEF 0xffffffff /* relate to ESP_BLE_SCAN_PARAM_UNDEF in btm_ble_api.h */ +#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 500 /*!< 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)) @@ -112,14 +112,14 @@ typedef enum { BLE_ADDR_TYPE_RPA_RANDOM = 0x03, } esp_ble_addr_type_t; -/// Used to exchange the encrytyption key in the init key & response key -#define ESP_BLE_ENC_KEY_MASK (1 << 0) /* relate to BTM_BLE_ENC_KEY_MASK in btm_api.h */ +/// 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 btm_api.h */ +#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 btm_api.h */ +#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 btm_api.h */ +#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 diff --git a/tools/sdk/include/bluedroid/esp_bt_device.h b/tools/sdk/include/bt/esp_bt_device.h similarity index 79% rename from tools/sdk/include/bluedroid/esp_bt_device.h rename to tools/sdk/include/bt/esp_bt_device.h index d3c3f79c55c..76fb1b9d34f 100644 --- a/tools/sdk/include/bluedroid/esp_bt_device.h +++ b/tools/sdk/include/bt/esp_bt_device.h @@ -27,22 +27,24 @@ extern "C" { /** * * @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 + * @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_INVALID_STATE : if bluetooth stack is not yet enabled + * - 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); diff --git a/tools/sdk/include/bluedroid/esp_bt_main.h b/tools/sdk/include/bt/esp_bt_main.h similarity index 100% rename from tools/sdk/include/bluedroid/esp_bt_main.h rename to tools/sdk/include/bt/esp_bt_main.h diff --git a/tools/sdk/include/bt/esp_gap_ble_api.h b/tools/sdk/include/bt/esp_gap_ble_api.h new file mode 100644 index 00000000000..ff30f5f354a --- /dev/null +++ b/tools/sdk/include/bt/esp_gap_ble_api.h @@ -0,0 +1,1220 @@ +// 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_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 + +/* 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 { + 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 */ + ESP_GAP_BLE_AUTH_CMPL_EVT, /* 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 */ + 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 */ + ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT, /*!< 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 */ + ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT, /*!< When update duplicate exceptional list complete, the event comes */ + ESP_GAP_BLE_EVT_MAX, +} esp_gap_ble_cb_event_t; +/// 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, + ESP_BLE_SM_AUTHEN_REQ_MODE, + ESP_BLE_SM_IOCAP_MODE, + ESP_BLE_SM_SET_INIT_KEY, + ESP_BLE_SM_SET_RSP_KEY, + ESP_BLE_SM_MAX_KEY_SIZE, + ESP_BLE_SM_SET_STATIC_PASSKEY, + ESP_BLE_SM_CLEAR_STATIC_PASSKEY, + ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, + ESP_BLE_SM_MAX_PARAM, +} esp_ble_sm_param_t; + +/// 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; + +/// 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_PRA_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; + +/// 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; + +/// 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 */ + +/// 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; + +/** + * @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; + +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; + +#define BLE_BIT(n) (1UL<<(n)) + +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]; + +/** + * @brief Gap callback parameters union + */ +typedef union { + /** + * @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 */ + + esp_ble_sec_t ble_security; /*!< ble gap security union type */ + /** + * @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 */ + /** + * @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 */ + /** + * @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 */ +} 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); + + +/** + * @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); + + + +/** + * @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 random 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. +* @return +* - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_update_whitelist(bool add_remove, esp_bd_addr_t remote_bda); + +/** +* @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); + +/** +* @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); + +/** + * @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); + +/** + * @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); + +/** + * @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); + +/** + * @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); + +#if (SMP_INCLUDED == TRUE) +/** +* @brief Set a GAP security parameter value. Overrides the default value. +* +* @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 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 +* - 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); + +#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); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_GAP_BLE_API_H__ */ diff --git a/tools/sdk/include/bt/esp_gap_bt_api.h b/tools/sdk/include/bt/esp_gap_bt_api.h new file mode 100644 index 00000000000..f5b2c8f15a2 --- /dev/null +++ b/tools/sdk/include/bt/esp_gap_bt_api.h @@ -0,0 +1,588 @@ +// 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; + +/// Discoverability and Connectability mode +typedef enum { + ESP_BT_SCAN_MODE_NONE = 0, /*!< Neither discoverable nor connectable */ + ESP_BT_SCAN_MODE_CONNECTABLE, /*!< Connectable but not discoverable */ + ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE /*!< both discoverable and connectable */ +} esp_bt_scan_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 +typedef enum { + ESP_BT_EIR_TYPE_FLAGS = 0x01, /*!< Flag with information such as BR/EDR and LE support */ + ESP_BT_EIR_TYPE_INCMPL_16BITS_UUID = 0x02, /*!< Incomplete list of 16-bit service UUIDs */ + ESP_BT_EIR_TYPE_CMPL_16BITS_UUID = 0x03, /*!< Complete list of 16-bit service UUIDs */ + ESP_BT_EIR_TYPE_INCMPL_32BITS_UUID = 0x04, /*!< Incomplete list of 32-bit service UUIDs */ + ESP_BT_EIR_TYPE_CMPL_32BITS_UUID = 0x05, /*!< Complete list of 32-bit service UUIDs */ + ESP_BT_EIR_TYPE_INCMPL_128BITS_UUID = 0x06, /*!< Incomplete list of 128-bit service UUIDs */ + ESP_BT_EIR_TYPE_CMPL_128BITS_UUID = 0x07, /*!< Complete list of 128-bit service UUIDs */ + ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME = 0x08, /*!< Shortened Local Name */ + ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME = 0x09, /*!< Complete Local Name */ + ESP_BT_EIR_TYPE_TX_POWER_LEVEL = 0x0a, /*!< Tx power level, value is 1 octet ranging from -127 to 127, unit is dBm*/ + ESP_BT_EIR_TYPE_MANU_SPECIFIC = 0xff, /*!< Manufacturer specific data */ +} esp_bt_eir_type_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 */ + +/// 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, /*!< AUTH complete event */ + ESP_BT_GAP_PIN_REQ_EVT, /*!< Legacy Pairing Pin code request */ + ESP_BT_GAP_CFM_REQ_EVT, /*!< Simple Pairing User Confirmation request. */ + ESP_BT_GAP_KEY_NOTIF_EVT, /*!< Simple Pairing Passkey Notification */ + ESP_BT_GAP_KEY_REQ_EVT, /*!< Simple Pairing Passkey request */ + ESP_BT_GAP_READ_RSSI_DELTA_EVT, /*!< read rssi 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_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 */ +} 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 + */ +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 + */ +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 + */ +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 + */ +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 + */ +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] mode : one of the enums of bt_scan_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_scan_mode_t mode); + +/** + * @brief Start device discovery. This function should be called after esp_bluedroid_enable() completes successfully. + * esp_bt_gap_cb_t will is called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT if discovery is started or halted. + * esp_bt_gap_cb_t will is called with ESP_BT_GAP_DISC_RES_EVT if discovery result is got. + * + * @param[in] mode - inquiry mode + * @param[in] inq_len - inquiry duration in 1.28 sec units, ranging from 0x01 to 0x30 + * @param[in] num_rsps - number of inquiry responses that can be received, 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 device discovery. This function should be called after esp_bluedroid_enable() completes successfully + * esp_bt_gap_cb_t will is called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT if discovery is stopped. + * + * @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 is 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 is 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 set class of device. + * esp_bt_gap_cb_t will is 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)*/ + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_GAP_BT_API_H__ */ diff --git a/tools/sdk/include/bluedroid/esp_gatt_common_api.h b/tools/sdk/include/bt/esp_gatt_common_api.h similarity index 88% rename from tools/sdk/include/bluedroid/esp_gatt_common_api.h rename to tools/sdk/include/bt/esp_gatt_common_api.h index 33bc11250a3..3a9b7445815 100644 --- a/tools/sdk/include/bluedroid/esp_gatt_common_api.h +++ b/tools/sdk/include/bt/esp_gatt_common_api.h @@ -12,6 +12,9 @@ // 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 @@ -23,10 +26,10 @@ 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 gatt_api.h */ +#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 gatt_api.h */ +#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, @@ -44,3 +47,5 @@ extern esp_err_t esp_ble_gatt_set_local_mtu (uint16_t mtu); #ifdef __cplusplus } #endif + +#endif /* __ESP_GATT_COMMON_API_H__ */ diff --git a/tools/sdk/include/bluedroid/esp_gatt_defs.h b/tools/sdk/include/bt/esp_gatt_defs.h similarity index 82% rename from tools/sdk/include/bluedroid/esp_gatt_defs.h rename to tools/sdk/include/bt/esp_gatt_defs.h index a98069eadb5..d6c140a1400 100644 --- a/tools/sdk/include/bluedroid/esp_gatt_defs.h +++ b/tools/sdk/include/bt/esp_gatt_defs.h @@ -154,81 +154,81 @@ extern "C" { * @} */ -/* relate to BTA_GATT_PREP_WRITE_xxx in bta_gatt_api.h */ +/* 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_gatt_api.h */ - ESP_GATT_PREP_WRITE_EXEC = 0x01, /*!< Prepare write execute */ /* relate to BTA_GATT_PREP_WRITE_EXEC in bta_gatt_api.h */ + 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_gatt_api.h */ +/* 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_gatt_api.h */ - ESP_GATT_INVALID_HANDLE = 0x01, /* 0x0001 */ /* relate to BTA_GATT_INVALID_HANDLE in bta_gatt_api.h */ - ESP_GATT_READ_NOT_PERMIT = 0x02, /* 0x0002 */ /* relate to BTA_GATT_READ_NOT_PERMIT in bta_gatt_api.h */ - ESP_GATT_WRITE_NOT_PERMIT = 0x03, /* 0x0003 */ /* relate to BTA_GATT_WRITE_NOT_PERMIT in bta_gatt_api.h */ - ESP_GATT_INVALID_PDU = 0x04, /* 0x0004 */ /* relate to BTA_GATT_INVALID_PDU in bta_gatt_api.h */ - ESP_GATT_INSUF_AUTHENTICATION = 0x05, /* 0x0005 */ /* relate to BTA_GATT_INSUF_AUTHENTICATION in bta_gatt_api.h */ - ESP_GATT_REQ_NOT_SUPPORTED = 0x06, /* 0x0006 */ /* relate to BTA_GATT_REQ_NOT_SUPPORTED in bta_gatt_api.h */ - ESP_GATT_INVALID_OFFSET = 0x07, /* 0x0007 */ /* relate to BTA_GATT_INVALID_OFFSET in bta_gatt_api.h */ - ESP_GATT_INSUF_AUTHORIZATION = 0x08, /* 0x0008 */ /* relate to BTA_GATT_INSUF_AUTHORIZATION in bta_gatt_api.h */ - ESP_GATT_PREPARE_Q_FULL = 0x09, /* 0x0009 */ /* relate to BTA_GATT_PREPARE_Q_FULL in bta_gatt_api.h */ - ESP_GATT_NOT_FOUND = 0x0a, /* 0x000a */ /* relate to BTA_GATT_NOT_FOUND in bta_gatt_api.h */ - ESP_GATT_NOT_LONG = 0x0b, /* 0x000b */ /* relate to BTA_GATT_NOT_LONG in bta_gatt_api.h */ - ESP_GATT_INSUF_KEY_SIZE = 0x0c, /* 0x000c */ /* relate to BTA_GATT_INSUF_KEY_SIZE in bta_gatt_api.h */ - ESP_GATT_INVALID_ATTR_LEN = 0x0d, /* 0x000d */ /* relate to BTA_GATT_INVALID_ATTR_LEN in bta_gatt_api.h */ - ESP_GATT_ERR_UNLIKELY = 0x0e, /* 0x000e */ /* relate to BTA_GATT_ERR_UNLIKELY in bta_gatt_api.h */ - ESP_GATT_INSUF_ENCRYPTION = 0x0f, /* 0x000f */ /* relate to BTA_GATT_INSUF_ENCRYPTION in bta_gatt_api.h */ - ESP_GATT_UNSUPPORT_GRP_TYPE = 0x10, /* 0x0010 */ /* relate to BTA_GATT_UNSUPPORT_GRP_TYPE in bta_gatt_api.h */ - ESP_GATT_INSUF_RESOURCE = 0x11, /* 0x0011 */ /* relate to BTA_GATT_INSUF_RESOURCE in bta_gatt_api.h */ - - ESP_GATT_NO_RESOURCES = 0x80, /* 0x80 */ /* relate to BTA_GATT_NO_RESOURCES in bta_gatt_api.h */ - ESP_GATT_INTERNAL_ERROR = 0x81, /* 0x81 */ /* relate to BTA_GATT_INTERNAL_ERROR in bta_gatt_api.h */ - ESP_GATT_WRONG_STATE = 0x82, /* 0x82 */ /* relate to BTA_GATT_WRONG_STATE in bta_gatt_api.h */ - ESP_GATT_DB_FULL = 0x83, /* 0x83 */ /* relate to BTA_GATT_DB_FULL in bta_gatt_api.h */ - ESP_GATT_BUSY = 0x84, /* 0x84 */ /* relate to BTA_GATT_BUSY in bta_gatt_api.h */ - ESP_GATT_ERROR = 0x85, /* 0x85 */ /* relate to BTA_GATT_ERROR in bta_gatt_api.h */ - ESP_GATT_CMD_STARTED = 0x86, /* 0x86 */ /* relate to BTA_GATT_CMD_STARTED in bta_gatt_api.h */ - ESP_GATT_ILLEGAL_PARAMETER = 0x87, /* 0x87 */ /* relate to BTA_GATT_ILLEGAL_PARAMETER in bta_gatt_api.h */ - ESP_GATT_PENDING = 0x88, /* 0x88 */ /* relate to BTA_GATT_PENDING in bta_gatt_api.h */ - ESP_GATT_AUTH_FAIL = 0x89, /* 0x89 */ /* relate to BTA_GATT_AUTH_FAIL in bta_gatt_api.h */ - ESP_GATT_MORE = 0x8a, /* 0x8a */ /* relate to BTA_GATT_MORE in bta_gatt_api.h */ - ESP_GATT_INVALID_CFG = 0x8b, /* 0x8b */ /* relate to BTA_GATT_INVALID_CFG in bta_gatt_api.h */ - ESP_GATT_SERVICE_STARTED = 0x8c, /* 0x8c */ /* relate to BTA_GATT_SERVICE_STARTED in bta_gatt_api.h */ - ESP_GATT_ENCRYPED_MITM = ESP_GATT_OK, /* relate to BTA_GATT_ENCRYPED_MITM in bta_gatt_api.h */ - ESP_GATT_ENCRYPED_NO_MITM = 0x8d, /* 0x8d */ /* relate to BTA_GATT_ENCRYPED_NO_MITM in bta_gatt_api.h */ - ESP_GATT_NOT_ENCRYPTED = 0x8e, /* 0x8e */ /* relate to BTA_GATT_NOT_ENCRYPTED in bta_gatt_api.h */ - ESP_GATT_CONGESTED = 0x8f, /* 0x8f */ /* relate to BTA_GATT_CONGESTED in bta_gatt_api.h */ - ESP_GATT_DUP_REG = 0x90, /* 0x90 */ /* relate to BTA_GATT_DUP_REG in bta_gatt_api.h */ - ESP_GATT_ALREADY_OPEN = 0x91, /* 0x91 */ /* relate to BTA_GATT_ALREADY_OPEN in bta_gatt_api.h */ - ESP_GATT_CANCEL = 0x92, /* 0x92 */ /* relate to BTA_GATT_CANCEL in bta_gatt_api.h */ + 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_gatt_api.h */ - ESP_GATT_APP_RSP = 0xe1, /* 0xe1 */ /* relate to BTA_GATT_APP_RSP in bta_gatt_api.h */ + 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_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_gatt_api.h */ - ESP_GATT_PRC_IN_PROGRESS = 0xfe, /* 0xFE Procedure Already in progress */ /* relate to BTA_GATT_PRC_IN_PROGRESS in bta_gatt_api.h */ - ESP_GATT_OUT_OF_RANGE = 0xff, /* 0xFFAttribute value out of range */ /* relate to BTA_GATT_OUT_OF_RANGE in bta_gatt_api.h */ + 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_gatt_api.h */ +/* 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_gatt_api.h */ - ESP_GATT_CONN_L2C_FAILURE = 1, /*!< General L2cap failure */ /* relate to BTA_GATT_CONN_L2C_FAILURE in bta_gatt_api.h */ - ESP_GATT_CONN_TIMEOUT = 0x08, /*!< Connection timeout */ /* relate to BTA_GATT_CONN_TIMEOUT in 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_gatt_api.h */ - ESP_GATT_CONN_TERMINATE_LOCAL_HOST = 0x16, /*!< Connectionterminated by local host */ /* relate to BTA_GATT_CONN_TERMINATE_LOCAL_HOST in bta_gatt_api.h */ - ESP_GATT_CONN_FAIL_ESTABLISH = 0x3e, /*!< Connection fail to establish */ /* relate to BTA_GATT_CONN_FAIL_ESTABLISH in 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_gatt_api.h */ - ESP_GATT_CONN_CONN_CANCEL = 0x0100, /*!< L2CAP connection cancelled */ /* relate to BTA_GATT_CONN_CONN_CANCEL in bta_gatt_api.h */ - ESP_GATT_CONN_NONE = 0x0101 /*!< No connection to cancel */ /* relate to BTA_GATT_CONN_NONE in bta_gatt_api.h */ + 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; /** @@ -248,47 +248,52 @@ typedef struct { 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_gatt_api.h */ +/* 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_gatt_api.h */ - ESP_GATT_AUTH_REQ_NO_MITM = 1, /* unauthenticated encryption */ /* relate to BTA_GATT_AUTH_REQ_NO_MITM in bta_gatt_api.h */ - ESP_GATT_AUTH_REQ_MITM = 2, /* authenticated encryption */ /* relate to BTA_GATT_AUTH_REQ_MITM in bta_gatt_api.h */ - ESP_GATT_AUTH_REQ_SIGNED_NO_MITM = 3, /* relate to BTA_GATT_AUTH_REQ_SIGNED_NO_MITM in bta_gatt_api.h */ - ESP_GATT_AUTH_REQ_SIGNED_MITM = 4, /* relate to BTA_GATT_AUTH_REQ_SIGNED_MITM in bta_gatt_api.h */ + 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_gatt_api.h */ +/* 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_gatt_api.h */ -#define ESP_GATT_PERM_READ_ENCRYPTED (1 << 1) /* bit 1 - 0x0002 */ /* relate to BTA_GATT_PERM_READ_ENCRYPTED in 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_gatt_api.h */ -#define ESP_GATT_PERM_WRITE (1 << 4) /* bit 4 - 0x0010 */ /* relate to BTA_GATT_PERM_WRITE in bta_gatt_api.h */ -#define ESP_GATT_PERM_WRITE_ENCRYPTED (1 << 5) /* bit 5 - 0x0020 */ /* relate to BTA_GATT_PERM_WRITE_ENCRYPTED in 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_gatt_api.h */ -#define ESP_GATT_PERM_WRITE_SIGNED (1 << 7) /* bit 7 - 0x0080 */ /* relate to BTA_GATT_PERM_WRITE_SIGNED in 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_gatt_api.h */ +#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 */ typedef uint16_t esp_gatt_perm_t; -/* relate to BTA_GATT_CHAR_PROP_BIT_xxx in bta_gatt_api.h */ +/* 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_gatt_api.h */ -#define ESP_GATT_CHAR_PROP_BIT_READ (1 << 1) /* 0x02 */ /* relate to BTA_GATT_CHAR_PROP_BIT_READ in 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_gatt_api.h */ -#define ESP_GATT_CHAR_PROP_BIT_WRITE (1 << 3) /* 0x08 */ /* relate to BTA_GATT_CHAR_PROP_BIT_WRITE in bta_gatt_api.h */ -#define ESP_GATT_CHAR_PROP_BIT_NOTIFY (1 << 4) /* 0x10 */ /* relate to BTA_GATT_CHAR_PROP_BIT_NOTIFY in bta_gatt_api.h */ -#define ESP_GATT_CHAR_PROP_BIT_INDICATE (1 << 5) /* 0x20 */ /* relate to BTA_GATT_CHAR_PROP_BIT_INDICATE in bta_gatt_api.h */ -#define ESP_GATT_CHAR_PROP_BIT_AUTH (1 << 6) /* 0x40 */ /* relate to BTA_GATT_CHAR_PROP_BIT_AUTH in 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_gatt_api.h */ +#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) @@ -422,7 +427,7 @@ typedef struct { * @brief service element */ typedef struct { - bool is_primary; /*!< The service flag, ture if the service is primary service, else is secondly service */ + bool is_primary; /*!< The service flag, true if the service is primary service, else is secondly 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 */ @@ -450,9 +455,10 @@ typedef struct { */ typedef struct { uint16_t handle; /*!< The include service current attribute handle */ - uint16_t incl_srvc_s_handle; /*!< The start hanlde of the service which has been included */ + 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 inclue service element */ +} esp_gattc_incl_svc_elem_t; /*!< The gattc include service element */ #ifdef __cplusplus diff --git a/tools/sdk/include/bluedroid/esp_gattc_api.h b/tools/sdk/include/bt/esp_gattc_api.h similarity index 90% rename from tools/sdk/include/bluedroid/esp_gattc_api.h rename to tools/sdk/include/bt/esp_gattc_api.h index 5f9ae198c7d..b494bcfd398 100644 --- a/tools/sdk/include/bluedroid/esp_gattc_api.h +++ b/tools/sdk/include/bt/esp_gattc_api.h @@ -65,6 +65,8 @@ typedef enum { 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_cb_event_t; @@ -113,9 +115,10 @@ typedef union { * @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 */ - } search_cmpl; /*!< Gatt client callback param of ESP_GATTC_SEARCH_CMPL_EVT */ + 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 @@ -125,6 +128,7 @@ typedef union { 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 */ /** @@ -215,6 +219,20 @@ typedef union { 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 @@ -295,7 +313,7 @@ esp_err_t esp_ble_gattc_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, e /** - * @brief Close a virtual connection to a GATT server. gattc maybe have multiple virtual GATT server connections when multiple app_id registed, + * @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). @@ -329,7 +347,8 @@ 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 request a GATT service discovery + * @brief This function is called to get service from local cache. + * If it does not exist, request a GATT service discovery * on a GATT server. This function report service search result * by a callback event, and followed by a service search complete * event. @@ -354,7 +373,7 @@ esp_err_t esp_ble_gattc_search_service(esp_gatt_if_t gattc_if, uint16_t conn_id, * @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 whith has been found in the gattc cache. + * @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. @@ -375,7 +394,7 @@ esp_gatt_status_t esp_ble_gattc_get_service(esp_gatt_if_t gattc_if, uint16_t con * @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 charateristic in the service. + * @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. @@ -678,7 +697,7 @@ esp_err_t esp_ble_gattc_write_char_descr (esp_gatt_if_t gattc_if, * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. - * @param[in] handle : charateristic handle to prepare write. + * @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. @@ -703,7 +722,7 @@ esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. - * @param[in] handle : characteristic descriptor hanlde to prepare write. + * @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. @@ -784,6 +803,41 @@ esp_err_t esp_ble_gattc_unregister_for_notify (esp_gatt_if_t gattc_if, */ 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); + + + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/bluedroid/esp_gatts_api.h b/tools/sdk/include/bt/esp_gatts_api.h similarity index 84% rename from tools/sdk/include/bluedroid/esp_gatts_api.h rename to tools/sdk/include/bt/esp_gatts_api.h index bc97b76e46f..97296b1c7a8 100644 --- a/tools/sdk/include/bluedroid/esp_gatts_api.h +++ b/tools/sdk/include/bt/esp_gatts_api.h @@ -25,31 +25,32 @@ extern "C" { /// 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 */ + 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, - ESP_GATTS_SET_ATTR_VAL_EVT = 23, + 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; /** @@ -119,6 +120,7 @@ typedef union { 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) */ @@ -267,6 +269,13 @@ typedef union { 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; /** @@ -350,7 +359,8 @@ esp_err_t esp_ble_gatts_create_attr_tab(const esp_gatts_attr_db_t *gatts_attr_db uint8_t max_nb_attr, uint8_t srvc_inst_id); /** - * @brief This function is called to add an included service. After included + * @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 BTA_GATTS_ADD_INCL_SRVC_EVT * is reported the included service ID. * @@ -549,6 +559,22 @@ esp_err_t esp_ble_gatts_open(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda, b */ 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 diff --git a/tools/sdk/include/bt/esp_hf_client_api.h b/tools/sdk/include/bt/esp_hf_client_api.h new file mode 100644 index 00000000000..dfc06ed5d1c --- /dev/null +++ b/tools/sdk/include/bt/esp_hf_client_api.h @@ -0,0 +1,635 @@ +// 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_service_availability_status_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; + +/** + * @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, used by HFP client + * + * @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 Connect to remote bluetooth HFP audio gateway(AG) device, must after esp_hf_client_init() + * + * @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 + * + * @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. + * + * @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 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. Precondition is that + * the HFP audio connection is connected. After this function is called, lower + * layer will invoke esp_hf_client_outgoing_data_cb_t to fetch data + * + */ +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 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/include/bt/esp_hf_defs.h b/tools/sdk/include/bt/esp_hf_defs.h new file mode 100644 index 00000000000..1ff9f14f6e7 --- /dev/null +++ b/tools/sdk/include/bt/esp_hf_defs.h @@ -0,0 +1,181 @@ +// 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 + + +/// 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; + +/// +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 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_NONE = 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 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; + +/// +CIND network service availability status +typedef enum { + ESP_HF_SERVICE_AVAILABILITY_STATUS_UNAVAILABLE = 0, /*!< service not available */ + ESP_HF_SERVICE_AVAILABILITY_STATUS_AVAILABLE, /*!< service available */ +} esp_hf_service_availability_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; + +/// response indication codes for AT commands +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; + +/// 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; + +/// 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; + +/// 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; + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_HF_DEFS_H__ */ diff --git a/tools/sdk/include/bluedroid/esp_spp_api.h b/tools/sdk/include/bt/esp_spp_api.h similarity index 89% rename from tools/sdk/include/bluedroid/esp_spp_api.h rename to tools/sdk/include/bt/esp_spp_api.h index 5a6bb7d463b..31bcf1c687f 100644 --- a/tools/sdk/include/bluedroid/esp_spp_api.h +++ b/tools/sdk/include/bt/esp_spp_api.h @@ -31,13 +31,13 @@ typedef enum { } esp_spp_status_t; /* Security Setting Mask */ -#define ESP_SPP_SEC_NONE 0x0000 /*!< No security. relate to BTA_SEC_NONE in bta_api.h */ -#define ESP_SPP_SEC_AUTHORIZE 0x0001 /*!< Authorization required (only needed for out going connection ) relate to BTA_SEC_AUTHORIZE in bta_api.h*/ -#define ESP_SPP_SEC_AUTHENTICATE 0x0012 /*!< Authentication required. relate to BTA_SEC_AUTHENTICATE in bta_api.h*/ -#define ESP_SPP_SEC_ENCRYPT 0x0024 /*!< Encryption required. relate to BTA_SEC_ENCRYPT in 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_api.h*/ -#define ESP_SPP_SEC_MITM 0x3000 /*!< Man-In-The_Middle protection relate to BTA_SEC_MITM in 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_api.h*/ +#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 { @@ -62,9 +62,9 @@ typedef enum { 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 */ - ESP_SPP_CONG_EVT = 31, /*!< When SPP connection congestion status changed, the event comes */ - ESP_SPP_WRITE_EVT = 33, /*!< When SPP write operation completes, 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_cb_event_t; @@ -95,6 +95,7 @@ typedef union { 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 */ @@ -105,6 +106,7 @@ typedef union { 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 */ /** @@ -142,7 +144,6 @@ typedef union { struct spp_write_evt_param { esp_spp_status_t status; /*!< status */ uint32_t handle; /*!< The connection handle */ - uint32_t req_id; /*!< The req_id in the associated BTA_JvRfcommWrite() */ int len; /*!< The length of the data written. */ bool cong; /*!< congestion status */ } write; /*!< SPP callback param of ESP_SPP_WRITE_EVT */ @@ -154,7 +155,7 @@ typedef union { esp_spp_status_t status; /*!< status */ uint32_t handle; /*!< The connection handle */ uint16_t len; /*!< The length of data */ - uint8_t *data; /*!< The data recived */ + uint8_t *data; /*!< The data received */ } data_ind; /*!< SPP callback param of ESP_SPP_DATA_IND_EVT */ /** @@ -189,8 +190,7 @@ esp_err_t esp_spp_register_callback(esp_spp_cb_t callback); /** * @brief This function is called to init SPP. * - * @param[in] mode: Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_CB. - * Now only supports ESP_SPP_MODE_CB mode, we will continue to update. + * @param[in] mode: Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS. * * @return * - ESP_OK: success @@ -223,14 +223,14 @@ esp_err_t esp_spp_deinit(); esp_err_t esp_spp_start_discovery(esp_bd_addr_t bd_addr); /** - * @brief This function makes an SPP conection to a remote BD Address. + * @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. * * @param[in] sec_mask: Security Setting Mask . - * @param[in] role: Msater or slave. + * @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. * @@ -261,7 +261,7 @@ esp_err_t esp_spp_disconnect(uint32_t handle); * with ESP_SPP_SRV_OPEN_EVT. * * @param[in] sec_mask: Security Setting Mask . - * @param[in] role: Msater or slave. + * @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. @@ -275,7 +275,7 @@ esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, /** - * @brief This function closes an SPP connection. + * @brief This function is used to write data, only for ESP_SPP_MODE_CB. * * @param[in] handle: The connection handle. * @param[in] len: The length of the data written. @@ -287,8 +287,18 @@ esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, */ esp_err_t esp_spp_write(uint32_t handle, int len, uint8_t *p_data); + +/** + * @brief This function is used to register VFS. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_vfs_register(void); + #ifdef __cplusplus } #endif -#endif ///__ESP_SPP_API_H__ \ No newline at end of file +#endif ///__ESP_SPP_API_H__ diff --git a/tools/sdk/include/coap/address.h b/tools/sdk/include/coap/address.h new file mode 100644 index 00000000000..85db2046e36 --- /dev/null +++ b/tools/sdk/include/coap/address.h @@ -0,0 +1,152 @@ +/* + * 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" + +#ifdef 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) (!!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) +#endif /* WITH_LWIP */ + +#ifdef WITH_CONTIKI +#include "uip.h" + +typedef struct coap_address_t { + uip_ipaddr_t addr; + unsigned short 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)) +#endif /* WITH_CONTIKI */ + +#ifdef WITH_POSIX +/** multi-purpose address abstraction */ +typedef struct coap_address_t { + socklen_t size; /**< size of addr */ + union { + struct sockaddr sa; + struct sockaddr_storage st; + 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); + +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_POSIX */ + +/** + * 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. + */ +static inline void +coap_address_init(coap_address_t *addr) { + assert(addr); + memset(addr, 0, sizeof(coap_address_t)); +#ifdef WITH_POSIX + /* lwip and Contiki have constant address sizes and doesn't need the .size part */ + addr->size = sizeof(addr->addr); +#endif +} + +#ifndef WITH_POSIX +/** + * 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; + */ +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; + */ +static inline int +coap_address_isany(const coap_address_t *a) { + assert(a); + return _coap_address_isany_impl(a); +} + +#ifdef WITH_POSIX +/** + * 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_POSIX */ +/** + * Checks if given address @p a denotes a multicast address. This function + * returns @c 1 if @p a is multicast, @c 0 otherwise. + */ +static inline int +coap_is_mcast(const coap_address_t *a) { + return a && _coap_is_mcast_impl(a); +} +#endif /* WITH_POSIX */ + +#endif /* _COAP_ADDRESS_H_ */ diff --git a/tools/sdk/include/coap/async.h b/tools/sdk/include/coap/async.h new file mode 100644 index 00000000000..0c36defacdb --- /dev/null +++ b/tools/sdk/include/coap/async.h @@ -0,0 +1,146 @@ +/* + * 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; + unsigned short message_id; /**< id of last message seen */ + coap_tid_t id; /**< transaction id */ + struct coap_async_state_t *next; /**< internally used for linking */ + coap_address_t peer; /**< the peer to notify */ + size_t tokenlen; /**< length of the token */ + unsigned char token[]; /**< 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 peer The remote peer that is to be asynchronously notified. + * @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_address_t *peer, + 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 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_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 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_tid_t id); + +/** + * Updates the time stamp of @p s. + * + * @param s The state object to update. + */ +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/include/coap/bits.h b/tools/sdk/include/coap/bits.h new file mode 100644 index 00000000000..0b269166d57 --- /dev/null +++ b/tools/sdk/include/coap/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. + */ +inline static int +bits_setb(uint8_t *vec, size_t size, uint8_t bit) { + if (size <= (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. + */ +inline static int +bits_clrb(uint8_t *vec, size_t size, uint8_t bit) { + if (size <= (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. + */ +inline static int +bits_getb(const uint8_t *vec, size_t size, uint8_t bit) { + if (size <= (bit >> 3)) + return -1; + + return (*(vec + (bit >> 3)) & (1 << (bit & 0x07))) != 0; +} + +#endif /* _COAP_BITS_H_ */ diff --git a/tools/sdk/include/coap/block.h b/tools/sdk/include/coap/block.h new file mode 100644 index 00000000000..9ce00311cc4 --- /dev/null +++ b/tools/sdk/include/coap/block.h @@ -0,0 +1,137 @@ +/* + * 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" + +/** + * @defgroup block Block Transfer + * @{ + */ + +#ifndef COAP_MAX_BLOCK_SZX +/** + * The largest value for the SZX component in a Block option. Note that + * 1 << (COAP_MAX_BLOCK_SZX + 4) should not exceed COAP_MAX_PDU_SIZE. + */ +#define COAP_MAX_BLOCK_SZX 4 +#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). + */ +static inline int +coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx) { + return ((num+1) << (szx + 4)) < data_len; +} + +/** Sets the More-bit in @p block_opt */ +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; +} + +/** + * 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, unsigned short 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, + unsigned short 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 unsigned char *data, + unsigned int block_num, + unsigned char block_szx); +/**@}*/ + +#endif /* _COAP_BLOCK_H_ */ diff --git a/tools/sdk/include/coap/coap.h b/tools/sdk/include/coap/coap.h new file mode 100644 index 00000000000..cbdc9dfc81b --- /dev/null +++ b/tools/sdk/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_ + +#include "libcoap.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#include "address.h" +#include "async.h" +#include "bits.h" +#include "block.h" +#include "coap_io.h" +#include "coap_time.h" +#include "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" +#include "uthash.h" +#include "utlist.h" + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_H_ */ diff --git a/tools/sdk/include/coap/coap/coap.h.in b/tools/sdk/include/coap/coap/coap.h.in deleted file mode 100644 index 76ebc5eb0d2..00000000000 --- a/tools/sdk/include/coap/coap/coap.h.in +++ /dev/null @@ -1,59 +0,0 @@ -/* - * coap.h -- main header file for CoAP stack of libcoap - * - * Copyright (C) 2010-2012,2015-2016 Olaf Bergmann - * 2015 Carsten Schoenert - * - * This file is part of the CoAP library libcoap. Please see README for terms - * of use. - */ - -#ifndef _COAP_H_ -#define _COAP_H_ - -#include "libcoap.h" - -/* Define the address where bug reports for libcoap should be sent. */ -#define LIBCOAP_PACKAGE_BUGREPORT @PACKAGE_BUGREPORT@ - -/* Define the full name of libcoap. */ -#define LIBCOAP_PACKAGE_NAME @PACKAGE_NAME@ - -/* Define the full name and version of libcoap. */ -#define LIBCOAP_PACKAGE_STRING @PACKAGE_STRING@ - -/* Define the home page for libcoap. */ -#define LIBCOAP_PACKAGE_URL @PACKAGE_URL@ - -/* Define the version of libcoap this file belongs to. */ -#define LIBCOAP_PACKAGE_VERSION @PACKAGE_VERSION@ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "address.h" -#include "async.h" -#include "bits.h" -#include "block.h" -#include "coap_io.h" -#include "coap_time.h" -#include "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" -#include "uthash.h" -#include "utlist.h" - -#ifdef __cplusplus -} -#endif - -#endif /* _COAP_H_ */ diff --git a/tools/sdk/include/coap/coap_io.h b/tools/sdk/include/coap/coap_io.h new file mode 100644 index 00000000000..7a48b319a1d --- /dev/null +++ b/tools/sdk/include/coap/coap_io.h @@ -0,0 +1,167 @@ +/* + * 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" + +/** + * Abstract handle that is used to identify a local network interface. + */ +typedef int coap_if_handle_t; + +/** Invalid interface handle */ +#define COAP_IF_INVALID -1 + +struct coap_packet_t; +typedef struct coap_packet_t coap_packet_t; + +struct coap_context_t; + +/** + * 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 { +#if defined(WITH_POSIX) || defined(WITH_CONTIKI) + union { + int fd; /**< on POSIX systems */ + void *conn; /**< opaque connection (e.g. uip_conn in Contiki) */ + } handle; /**< opaque handle to identify this endpoint */ +#endif /* WITH_POSIX or WITH_CONTIKI */ + +#ifdef WITH_LWIP + struct udp_pcb *pcb; + /**< @FIXME --chrysn + * this was added in a hurry, not sure it confirms to the overall model */ + struct coap_context_t *context; +#endif /* WITH_LWIP */ + + coap_address_t addr; /**< local interface address */ + int ifindex; + int flags; +} coap_endpoint_t; + +#define COAP_ENDPOINT_NOSEC 0x00 +#define COAP_ENDPOINT_DTLS 0x01 + +coap_endpoint_t *coap_new_endpoint(const coap_address_t *addr, int flags); + +void coap_free_endpoint(coap_endpoint_t *ep); + +/** + * 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 context The calling CoAP context. + * @param local_interface The local interface to send the data. + * @param dst The address of the receiver. + * @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(struct coap_context_t *context, + const coap_endpoint_t *local_interface, + const coap_address_t *dst, + unsigned char *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 ep The endpoint that is used for reading data from the network. + * @param packet A result parameter where a pointer to the received packet + * structure is stored. The caller must call coap_free_packet to + * release the storage used by this packet. + * + * @return The number of bytes received on success, or a value less than + * zero on error. + */ +ssize_t coap_network_read(coap_endpoint_t *ep, coap_packet_t **packet); + +#ifndef coap_mcast_interface +# define coap_mcast_interface(Local) 0 +#endif + +/** + * Releases the storage allocated for @p packet. + */ +void coap_free_packet(coap_packet_t *packet); + +/** + * Populate the coap_endpoint_t *target from the incoming packet's destination + * data. + * + * This is usually used to copy a packet's data into a node's local_if member. + */ +void coap_packet_populate_endpoint(coap_packet_t *packet, + coap_endpoint_t *target); + +/** + * Given an incoming packet, copy its source address into an address struct. + */ +void coap_packet_copy_source(coap_packet_t *packet, coap_address_t *target); + +/** + * 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(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(coap_packet_t *packet); +#endif + +#ifdef WITH_CONTIKI +/* + * This is only included in coap_io.h instead of .c in order to be available for + * sizeof in mem.c. + */ +struct coap_packet_t { + coap_if_handle_t hnd; /**< the interface handle */ + coap_address_t src; /**< the packet's source address */ + coap_address_t dst; /**< the packet's destination address */ + const coap_endpoint_t *interface; + int ifindex; + void *session; /**< opaque session data */ + size_t length; /**< length of payload */ + unsigned char payload[]; /**< payload */ +}; +#endif + +#ifdef 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 coap_endpoint_t *local_interface; + uint16_t srcport; +}; +#endif + +#endif /* _COAP_IO_H_ */ diff --git a/tools/sdk/include/coap/coap_time.h b/tools/sdk/include/coap/coap_time.h new file mode 100644 index 00000000000..9357e5ff7d0 --- /dev/null +++ b/tools/sdk/include/coap/coap_time.h @@ -0,0 +1,142 @@ +/* + * coap_time.h -- Clock Handling + * + * Copyright (C) 2010-2013 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. + * @{ + */ + +#ifdef 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; + +static inline void coap_ticks_impl(coap_tick_t *t) { + *t = sys_now(); +} + +static inline void coap_clock_init_impl(void) { +} + +#define coap_clock_init coap_clock_init_impl +#define coap_ticks coap_ticks_impl + +static inline coap_time_t coap_ticks_to_rt(coap_tick_t t) { + return t / COAP_TICKS_PER_SECOND; +} +#endif + +#ifdef 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 + +static inline void coap_clock_init(void) { + clock_init(); +} + +static inline void coap_ticks(coap_tick_t *t) { + *t = clock_time(); +} + +static inline coap_time_t coap_ticks_to_rt(coap_tick_t t) { + return t / COAP_TICKS_PER_SECOND; +} +#endif /* WITH_CONTIKI */ + +#ifdef WITH_POSIX +/** + * This data type represents internal timer ticks with COAP_TICKS_PER_SECOND + * resolution. + */ +typedef unsigned long 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 long coap_tick_diff_t; + +/** Use ms resolution on POSIX systems */ +#define COAP_TICKS_PER_SECOND 1000 + +/** + * 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); +#endif /* WITH_POSIX */ + +/** + * Returns @c 1 if and only if @p a is less than @p b where less is defined on a + * signed data type. + */ +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. + */ +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/include/coap/debug.h b/tools/sdk/include/coap/debug.h new file mode 100644 index 00000000000..e7c86aff517 --- /dev/null +++ b/tools/sdk/include/coap/debug.h @@ -0,0 +1,85 @@ +/* + * 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_ + +#ifndef COAP_DEBUG_FD +#define COAP_DEBUG_FD stdout +#endif + +#ifndef COAP_ERR_FD +#define COAP_ERR_FD stderr +#endif + +#ifdef HAVE_SYSLOG_H +#include +typedef short coap_log_t; +#else +/** Pre-defined log levels akin to what is used in \b syslog. */ +typedef enum { + LOG_EMERG=0, + LOG_ALERT, + LOG_CRIT, + LOG_ERR, + LOG_WARNING, + LOG_NOTICE, + LOG_INFO, + LOG_DEBUG +} coap_log_t; +#endif + +/** Returns the current log level. */ +coap_log_t coap_get_log_level(void); + +/** Sets the log level to the specified value. */ +void coap_set_log_level(coap_log_t level); + +/** Returns a zero-terminated string with the name of this library. */ +const char *coap_package_name(void); + +/** Returns a 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_WARNING). The text is output only when + * @p level is below or equal to the log level that set by coap_set_log_level(). + */ +void coap_log_impl(coap_log_t level, const char *format, ...); + +#ifndef coap_log +#define coap_log(...) coap_log_impl(__VA_ARGS__) +#endif + +#ifndef NDEBUG + +/* A set of convenience macros for common log levels. */ +#define info(...) coap_log(LOG_INFO, __VA_ARGS__) +#define warn(...) coap_log(LOG_WARNING, __VA_ARGS__) +#define debug(...) coap_log(LOG_DEBUG, __VA_ARGS__) + +#include "pdu.h" +void coap_show_pdu(const coap_pdu_t *); + +struct coap_address_t; +size_t coap_print_addr(const struct coap_address_t *, unsigned char *, size_t); + +#else + +#define debug(...) +#define info(...) +#define warn(...) + +#define coap_show_pdu(x) +#define coap_print_addr(...) + +#endif /* NDEBUG */ + +#endif /* _COAP_DEBUG_H_ */ diff --git a/tools/sdk/include/coap/encode.h b/tools/sdk/include/coap/encode.h new file mode 100644 index 00000000000..a5d290c4ecf --- /dev/null +++ b/tools/sdk/include/coap/encode.h @@ -0,0 +1,52 @@ +/* + * 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) +# include +#else +# include +#endif + +#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 + +/* 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. buf points to an input byte sequence + * of length len. Returns the decoded value. + */ +unsigned int coap_decode_var_bytes(unsigned char *buf,unsigned int len); + +/** + * Encodes multiple-length byte sequences. buf points to an output buffer of + * sufficient length to store the encoded bytes. val is the value to encode. + * Returns the number of bytes used to encode val or 0 on error. + */ +unsigned int coap_encode_var_bytes(unsigned char *buf, unsigned int val); + +#endif /* _COAP_ENCODE_H_ */ diff --git a/tools/sdk/include/coap/hashkey.h b/tools/sdk/include/coap/hashkey.h new file mode 100644 index 00000000000..5cff67d2d8a --- /dev/null +++ b/tools/sdk/include/coap/hashkey.h @@ -0,0 +1,57 @@ +/* + * 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 hashkey.h + * @brief definition of hash key type and helper functions + */ + +#ifndef _COAP_HASHKEY_H_ +#define _COAP_HASHKEY_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 str 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/include/coap/libcoap.h b/tools/sdk/include/coap/libcoap.h new file mode 100644 index 00000000000..214b9e235e8 --- /dev/null +++ b/tools/sdk/include/coap/libcoap.h @@ -0,0 +1,26 @@ +/* + * 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 _LIBCOAP_H_ +#define _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 (CONTIKI) +#include +#include +#endif /* CONTIKI */ + +#endif /* _LIBCOAP_H_ */ diff --git a/tools/sdk/include/coap/lwippools.h b/tools/sdk/include/coap/lwippools.h new file mode 100644 index 00000000000..0bfb3f527a7 --- /dev/null +++ b/tools/sdk/include/coap/lwippools.h @@ -0,0 +1,57 @@ +/* + * 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_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 + +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_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") diff --git a/tools/sdk/include/coap/mem.h b/tools/sdk/include/coap/mem.h new file mode 100644 index 00000000000..fd3c69aafde --- /dev/null +++ b/tools/sdk/include/coap/mem.h @@ -0,0 +1,111 @@ +/* + * 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 +} 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. + */ +static inline void *coap_malloc(size_t size) { + return coap_malloc_type(COAP_STRING, size); +} + +/** + * Wrapper function to coap_free_type() for backwards compatibility. + */ +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) */ +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. + */ +static inline void *coap_malloc(size_t size) { + LWIP_ASSERT("coap_malloc must not be used in lwIP", 0); +} + +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/include/coap/net.h b/tools/sdk/include/coap/net.h new file mode 100644 index 00000000000..014b4903ab4 --- /dev/null +++ b/tools/sdk/include/coap/net.h @@ -0,0 +1,521 @@ +/* + * 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 +#include +#include + +#ifdef WITH_LWIP +#include +#endif + +#include "coap_io.h" +#include "coap_time.h" +#include "option.h" +#include "pdu.h" +#include "prng.h" + +struct coap_queue_t; + +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_endpoint_t local_if; /**< the local address interface */ + coap_address_t remote; /**< remote address */ + coap_tid_t id; /**< unique transaction id */ + coap_pdu_t *pdu; /**< the CoAP PDU to send */ +} coap_queue_t; + +/** Adds node to given queue, ordered by node->t. */ +int coap_insert_node(coap_queue_t **queue, coap_queue_t *node); + +/** Destroys specified node. */ +int coap_delete_node(coap_queue_t *node); + +/** Removes all items from given queue and frees the allocated storage. */ +void coap_delete_all(coap_queue_t *queue); + +/** Creates a new node suitable for adding to the CoAP sendqueue. */ +coap_queue_t *coap_new_node(void); + +struct coap_resource_t; +struct coap_context_t; +#ifndef WITHOUT_ASYNC +struct coap_async_state_t; +#endif + +/** Message handler that is used as call-back in coap_context_t */ +typedef void (*coap_response_handler_t)(struct coap_context_t *, + const coap_endpoint_t *local_interface, + const coap_address_t *remote, + coap_pdu_t *sent, + coap_pdu_t *received, + const coap_tid_t id); + +#define COAP_MID_CACHE_SIZE 3 +typedef struct { + unsigned char flags[COAP_MID_CACHE_SIZE]; + coap_key_t item[COAP_MID_CACHE_SIZE]; +} coap_mid_cache_t; + +/** 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 */ + +#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 endpoint used for listening */ + +#ifdef WITH_POSIX + int sockfd; /**< send/receive socket */ +#endif /* WITH_POSIX */ + +#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 */ + + /** + * The last message id that was used is stored in this field. The initial + * value is set by coap_new_context() and is usually a random value. A new + * message id can be created with coap_new_message_id(). + */ + unsigned short message_id; + + /** + * The next value to be used for Observe. This field is global for all + * resources and will be updated when notifications are created. + */ + unsigned int observe; + + coap_response_handler_t response_handler; + + ssize_t (*network_send)(struct coap_context_t *context, + const coap_endpoint_t *local_interface, + const coap_address_t *dst, + unsigned char *data, size_t datalen); + + ssize_t (*network_read)(coap_endpoint_t *ep, coap_packet_t **packet); + +} 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. + */ +static inline void +coap_register_response_handler(coap_context_t *context, + coap_response_handler_t handler) { + context->response_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. + */ +inline static void +coap_register_option(coap_context_t *ctx, unsigned char 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); + +/** + * Returns a new message id and updates @p context->message_id accordingly. The + * message id is returned in network byte order to make it easier to read in + * tracing tools. + * + * @param context The current coap_context_t object. + * + * @return Incremented message id in network byte order. + */ +static inline unsigned short +coap_new_message_id(coap_context_t *context) { + context->message_id++; +#ifndef WITH_CONTIKI + return htons(context->message_id); +#else /* WITH_CONTIKI */ + return uip_htons(context->message_id); +#endif +} + +/** + * 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. + */ +void coap_free_context(coap_context_t *context); + + +/** + * Sends a confirmed CoAP message to given destination. The memory that is + * allocated by pdu will not be released by coap_send_confirmed(). The caller + * must release the memory. + * + * @param context The CoAP context to use. + * @param local_interface The local network interface where the outbound + * packet is sent. + * @param dst The address to send to. + * @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_confirmed(coap_context_t *context, + const coap_endpoint_t *local_interface, + const coap_address_t *dst, + coap_pdu_t *pdu); + +/** + * 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 a non-confirmed CoAP message to given destination. The memory that is + * allocated by pdu will not be released by coap_send(). + * The caller must release the memory. + * + * @param context The CoAP context to use. + * @param local_interface The local network interface where the outbound packet + * is sent. + * @param dst The address to send to. + * @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_context_t *context, + const coap_endpoint_t *local_interface, + const coap_address_t *dst, + coap_pdu_t *pdu); + +/** + * 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 context The context to use. + * @param request The original request to respond to. + * @param local_interface The local network interface where the outbound packet + * is sent. + * @param dst The remote peer that sent the request. + * @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_context_t *context, + coap_pdu_t *request, + const coap_endpoint_t *local_interface, + const coap_address_t *dst, + 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 context The CoAP context. + * @param local_interface The local network interface where the outbound packet + * is sent. + * @param dst Where to send the context. + * @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_context_t *context, + const coap_endpoint_t *local_interface, + const coap_address_t *dst, + 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 context The context to use. + * @param local_interface The local network interface where the outbound packet + * is sent. + * @param dst The destination address. + * @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_context_t *context, + const coap_endpoint_t *local_interface, + const coap_address_t *dst, + 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 context The context to use. + * @param local_interface The local network interface where the outbound packet + * is sent. + * @param dst The destination address. + * @param request The request to be reset. + * + * @return The transaction id if RST was sent or @c + * COAP_INVALID_TID on error. + */ +static inline coap_tid_t +coap_send_rst(coap_context_t *context, + const coap_endpoint_t *local_interface, + const coap_address_t *dst, + coap_pdu_t *request) { + return coap_send_message_type(context, + local_interface, + dst, request, + COAP_MESSAGE_RST); +} + +/** + * Handles retransmissions of confirmable messages + */ +coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node); + +/** + * Reads data from the network and tries to parse as CoAP PDU. On success, 0 is + * returned and a new node with the parsed PDU is added to the receive queue in + * the specified context object. + */ +int coap_read(coap_context_t *context); + +/** + * Parses and interprets a CoAP message with context @p ctx. This function + * returns @c 0 if the message was handled, or a value less than zero on + * error. + * + * @param ctx The current CoAP context. + * @param packet The received packet. + * + * @return @c 0 if message was handled successfully, or less than zero on + * error. + */ +int coap_handle_message(coap_context_t *ctx, + coap_packet_t *packet); + +/** + * Calculates a unique transaction id from given arguments @p peer and @p pdu. + * The id is returned in @p id. + * + * @param peer The remote party who sent @p pdu. + * @param pdu The message that initiated the transaction. + * @param id Set to the new id. + */ +void coap_transaction_id(const coap_address_t *peer, + const coap_pdu_t *pdu, + coap_tid_t *id); + +/** + * 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 id The node 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_tid_t id, + coap_queue_t **node); + +/** + * Removes the transaction identified by @p id from given @p queue. This is a + * convenience function for coap_remove_from_queue() with automatic deletion of + * the removed node. + * + * @param queue The queue to search for @p id. + * @param id The transaction id. + * + * @return @c 1 if node was found, removed and destroyed, @c 0 otherwise. + */ +inline static int +coap_remove_transaction(coap_queue_t **queue, coap_tid_t id) { + coap_queue_t *node; + if (!coap_remove_from_queue(queue, id, &node)) + return 0; + + coap_delete_node(node); + return 1; +} + +/** + * Retrieves transaction from the queue. + * + * @param queue The transaction queue to be searched. + * @param id Unique key of the transaction to find. + * + * @return A pointer to the transaction object or NULL if not found. + */ +coap_queue_t *coap_find_transaction(coap_queue_t *queue, coap_tid_t id); + +/** + * Cancels all outstanding messages for peer @p dst that have the specified + * token. + * + * @param context The context in use. + * @param dst Destination address 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, + const coap_address_t *dst, + const unsigned char *token, + size_t token_length); + +/** + * Dispatches the PDUs from the receive queue in given context. + */ +void coap_dispatch(coap_context_t *context, coap_queue_t *rcvd); + +/** + * 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 released by coap_delete_pdu(). + * + * @param context The current coap context to use. + * @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_pdu_t *request); + +#endif /* _COAP_NET_H_ */ diff --git a/tools/sdk/include/coap/option.h b/tools/sdk/include/coap/option.h new file mode 100644 index 00000000000..ace2b81c713 --- /dev/null +++ b/tools/sdk/include/coap/option.h @@ -0,0 +1,410 @@ +/* + * 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 unsigned char coap_opt_t; +#define PCHAR(p) ((coap_opt_t *)(p)) + +/** Representation of CoAP options. */ +typedef struct { + unsigned short delta; + size_t length; + unsigned char *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); + +/** @deprecated { Use coap_opt_size() instead. } */ +#define COAP_OPT_SIZE(opt) coap_opt_size(opt) + +/** + * Calculates the beginning of the PDU's option section. + * + * @param pdu The PDU containing the options. + * @return A pointer to the first option if available, or @c NULL otherwise. + */ +coap_opt_t *options_start(coap_pdu_t *pdu); + +/** + * Interprets @p opt as pointer to a CoAP option and advances to + * the next byte past this option. + * @hideinitializer + */ +#define options_next(opt) \ + ((coap_opt_t *)((unsigned char *)(opt) + COAP_OPT_SIZE(opt))) + +/** + * @defgroup opt_filter 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. + */ +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, unsigned short 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, unsigned short 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(const coap_opt_filter_t filter, unsigned short 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. + */ +inline static int +coap_option_setb(coap_opt_filter_t filter, unsigned short 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. + */ +inline static int +coap_option_clrb(coap_opt_filter_t filter, unsigned short 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. + */ +inline static int +coap_option_getb(const coap_opt_filter_t filter, unsigned short 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 */ + unsigned short 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(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, + unsigned short 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, + unsigned short 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, + unsigned short delta, + const unsigned char *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. + */ +unsigned short coap_opt_delta(const coap_opt_t *opt); + +/** @deprecated { Use coap_opt_delta() instead. } */ +#define COAP_OPT_DELTA(opt) coap_opt_delta(opt) + +/** @deprecated { Use coap_opt_encode() instead. } */ +#define COAP_OPT_SETDELTA(opt,val) \ + coap_opt_encode((opt), COAP_MAX_PDU_SIZE, (val), NULL, 0) + +/** + * 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. + */ +unsigned short coap_opt_length(const coap_opt_t *opt); + +/** @deprecated { Use coap_opt_length() instead. } */ +#define COAP_OPT_LENGTH(opt) coap_opt_length(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. + */ +unsigned char *coap_opt_value(coap_opt_t *opt); + +/** @deprecated { Use coap_opt_value() instead. } */ +#define COAP_OPT_VALUE(opt) coap_opt_value((coap_opt_t *)opt) + +/** @} */ + +#endif /* _OPTION_H_ */ diff --git a/tools/sdk/include/coap/pdu.h b/tools/sdk/include/coap/pdu.h new file mode 100644 index 00000000000..7ed482deee0 --- /dev/null +++ b/tools/sdk/include/coap/pdu.h @@ -0,0 +1,388 @@ +/* + * 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" + +#ifdef WITH_LWIP +#include +#endif + +#define COAP_DEFAULT_PORT 5683 /* CoAP default UDP port */ +#define COAP_DEFAULT_MAX_AGE 60 /* default maximum object lifetime in seconds */ +#ifndef COAP_MAX_PDU_SIZE +#define COAP_MAX_PDU_SIZE 1400 /* maximum size of a CoAP PDU */ +#endif /* COAP_MAX_PDU_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" + +#ifdef __COAP_DEFAULT_HASH +/* pre-calculated hash key for the default well-known URI */ +#define COAP_DEFAULT_WKC_HASHKEY "\345\130\144\245" +#endif + +/* 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 + +/* CoAP option types (be sure to update 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_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. + */ +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 */ + +/* 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 */ + +/* 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 + +#ifdef WORDS_BIGENDIAN +typedef struct { + unsigned int version:2; /* protocol version */ + unsigned int type:2; /* type flag */ + unsigned int token_length:4; /* length of Token */ + unsigned int code:8; /* request method (value 1--10) or response + code (value 40-255) */ + unsigned short id; /* message id */ + unsigned char token[]; /* the actual token, if any */ +} coap_hdr_t; +#else +typedef struct { + unsigned int token_length:4; /* length of Token */ + unsigned int type:2; /* type flag */ + unsigned int version:2; /* protocol version */ + unsigned int code:8; /* request method (value 1--10) or response + code (value 40-255) */ + unsigned short id; /* transaction id (network byte order!) */ + unsigned char token[]; /* the actual token, if any */ +} coap_hdr_t; +#endif + +#define COAP_MESSAGE_IS_EMPTY(MSG) ((MSG)->code == 0) +#define COAP_MESSAGE_IS_REQUEST(MSG) (!COAP_MESSAGE_IS_EMPTY(MSG) \ + && ((MSG)->code < 32)) +#define COAP_MESSAGE_IS_RESPONSE(MSG) ((MSG)->code >= 64) + +#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 */ + +/** + * 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). + */ +typedef struct { + unsigned short 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)) + +/** + * Header structure for CoAP PDUs + */ + +typedef struct { + size_t max_size; /**< allocated storage for options and data */ + coap_hdr_t *hdr; /**< Address of the first byte of the CoAP message. + * This may or may not equal (coap_hdr_t*)(pdu+1) + * depending on the memory management + * implementation. */ + unsigned short max_delta; /**< highest option number */ + unsigned short length; /**< PDU length (including header, options, data) */ + unsigned char *data; /**< payload */ + +#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; + +/** + * Options in coap_pdu_t are accessed with the macro COAP_OPTION. + */ +#define COAP_OPTION(node) ((coap_option *)(node)->options) + +#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 + +/** + * Creates a new CoAP PDU of given @p size (must be large enough to hold the + * basic CoAP message header (coap_hdr_t). 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(). + * + * @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 id The message id to set or COAP_INVALID_TID if unknown. + * @param size The number of bytes to allocate for the actual message. + * + * @return A pointer to the new PDU object or @c NULL on error. + */ +coap_pdu_t * +coap_pdu_init(unsigned char type, + unsigned char code, + unsigned short id, + size_t size); + +/** + * Clears any contents from @p pdu and resets @c version field, @c + * length 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. + * The object is created on the heap and must be released using + * coap_delete_pdu(); + * + * @deprecated This function allocates the maximum storage for each + * PDU. Use coap_pdu_init() instead. + */ +coap_pdu_t *coap_new_pdu(void); + +void coap_delete_pdu(coap_pdu_t *); + +/** + * Parses @p data into the CoAP PDU structure given in @p result. + * This function returns @c 0 on error or a number greater than zero on success. + * + * @param data The raw data to parse as CoAP PDU. + * @param length The actual size of @p data. + * @param result The PDU structure to fill. Note that the structure must + * provide space for at least @p length bytes to hold the + * entire CoAP PDU. + * + * @return A value greater than zero on success or @c 0 on error. + */ +int coap_pdu_parse(unsigned char *data, + size_t length, + coap_pdu_t *result); + +/** + * 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 funtion + * 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 unsigned char *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, + unsigned short type, + unsigned int len, + const unsigned char *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. + */ +unsigned char *coap_add_option_later(coap_pdu_t *pdu, + unsigned short type, + unsigned int 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, + unsigned int len, + const unsigned char *data); + +/** + * 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(coap_pdu_t *pdu, + size_t *len, + unsigned char **data); + +#endif /* _COAP_PDU_H_ */ diff --git a/tools/sdk/include/coap/prng.h b/tools/sdk/include/coap/prng.h new file mode 100644 index 00000000000..da6d9534404 --- /dev/null +++ b/tools/sdk/include/coap/prng.h @@ -0,0 +1,106 @@ +/* + * 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 + * @{ + */ + +#if defined(WITH_POSIX) || (defined(WITH_LWIP) && !defined(LWIP_RAND)) +#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. + */ +static inline int +coap_prng_impl(unsigned char *buf, size_t len) { + while (len--) + *buf++ = rand() & 0xFF; + return 1; +} +#endif /* WITH_POSIX */ + +#ifdef 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. + */ +static inline int +contiki_prng_impl(unsigned char *buf, size_t len) { + unsigned short 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((unsigned short)(Value)) +#endif /* WITH_CONTIKI */ + +#if defined(WITH_LWIP) && defined(LWIP_RAND) +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) + +#endif /* WITH_LWIP */ + +#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/include/coap/resource.h b/tools/sdk/include/coap/resource.h new file mode 100644 index 00000000000..dbb19a8d1f6 --- /dev/null +++ b/tools/sdk/include/coap/resource.h @@ -0,0 +1,408 @@ +/* + * 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 */ + +#ifdef COAP_RESOURCES_NOHASH +# include "utlist.h" +#else +# include "uthash.h" +#endif + +#include "hashkey.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 *, + const coap_endpoint_t *, + coap_address_t *, + coap_pdu_t *, + str * /* token */, + 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; + str name; + str 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 */ + + /** + * Used to store handlers for the four coap methods @c GET, @c POST, @c PUT, + * and @c DELETE. 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[4]; + + coap_key_t key; /**< the actual key bytes for this resource */ + +#ifdef COAP_RESOURCES_NOHASH + struct coap_resource_t *next; +#else + UT_hash_handle hh; +#endif + + 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 for this resource. This field will point into the static + * memory. + */ + str uri; + int flags; + +} coap_resource_t; + +/** + * Creates a new resource object and initializes the link field to the string + * of length @p len. This function returns the new coap_resource_t object. + * + * @param uri The URI path of the new resource. + * @param len The length of @p uri. + * @param flags Flags for memory management (in particular release of memory). + * + * @return A pointer to the new object or @c NULL on error. + */ +coap_resource_t *coap_resource_init(const unsigned char *uri, + size_t len, int flags); + + +/** + * Sets the notification message type of resource @p r to given + * @p mode which must be one of @c COAP_RESOURCE_FLAGS_NOTIFY_NON + * or @c COAP_RESOURCE_FLAGS_NOTIFY_CON. + */ +static inline void +coap_resource_set_mode(coap_resource_t *r, int mode) { + r->flags = (r->flags & !COAP_RESOURCE_FLAGS_NOTIFY_CON) | mode; +} + +/** + * Registers the given @p resource for @p context. The resource must have been + * created by coap_resource_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 key. The storage allocated for that + * resource is freed. + * + * @param context The context where the resources are stored. + * @param key The unique key for 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_key_t key); + +/** + * 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 + * attributes str fields will point to @p name and @p val the + * caller must ensure that these pointers are valid during the + * attribute's lifetime. + * + * @param resource The resource to register the attribute with. + * @param name The attribute's name. + * @param nlen Length of @p name. + * @param val The attribute's value or @c NULL if none. + * @param vlen Length of @p val if specified. + * @param flags Flags for memory management (in particular release of + * memory). + * + * @return A pointer to the new attribute or @c NULL on error. + */ +coap_attr_t *coap_add_attr(coap_resource_t *resource, + const unsigned char *name, + size_t nlen, + const unsigned char *val, + size_t vlen, + 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. + * @param nlen Actual length of @p name. + * @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, + const unsigned char *name, + size_t nlen); + +/** + * Deletes an attribute. + * + * @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. + */ +static inline void +coap_register_handler(coap_resource_t *resource, + unsigned char method, + coap_method_handler_t handler) { + assert(resource); + assert(method > 0 && (size_t)(method-1) < sizeof(resource->handler)/sizeof(coap_method_handler_t)); + resource->handler[method-1] = handler; +} + +/** + * Returns the resource identified by the unique string @p key. If no resource + * was found, this function returns @c NULL. + * + * @param context The context to look for this resource. + * @param key The unique key of the resource. + * + * @return A pointer to the resource or @c NULL if not found. + */ +coap_resource_t *coap_get_resource_from_key(coap_context_t *context, + coap_key_t key); + +/** + * Calculates the hash key for the resource requested by the Uri-Options of @p + * request. This function calls coap_hash() for every path segment. + * + * @param request The requesting pdu. + * @param key The resulting hash is stored in @p key. + */ +void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key); + +/** + * @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 local_interface The local network interface where the observer is + * attached to. + * @param observer The remote peer that wants to received status updates. + * @param token The token that identifies this subscription. + * @return A pointer to the added/updated subscription + * information or @c NULL on error. + */ +coap_subscription_t *coap_add_observer(coap_resource_t *resource, + const coap_endpoint_t *local_interface, + const coap_address_t *observer, + const str *token); + +/** + * Returns a subscription object for given @p peer. + * + * @param resource The observed resource. + * @param peer The address to search for. + * @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, + const coap_address_t *peer, + const str *token); + +/** + * Marks an observer as alive. + * + * @param context The CoAP context to use. + * @param observer The transport address of the observer. + * @param token The corresponding token that has been used for the + * subscription. + */ +void coap_touch_observer(coap_context_t *context, + const coap_address_t *observer, + const str *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 observer The observer's address. + * @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, + const coap_address_t *observer, + const str *token); + +/** + * Checks for all known resources, if they are dirty and notifies subscribed + * observers. + */ +void coap_check_notify(coap_context_t *context); + +#ifdef COAP_RESOURCES_NOHASH + +#define RESOURCES_ADD(r, obj) \ + LL_PREPEND((r), (obj)) + +#define RESOURCES_DELETE(r, obj) \ + LL_DELETE((r), (obj)) + +#define RESOURCES_ITER(r,tmp) \ + coap_resource_t *tmp; \ + LL_FOREACH((r), tmp) + +#define RESOURCES_FIND(r, k, res) { \ + coap_resource_t *tmp; \ + (res) = tmp = NULL; \ + LL_FOREACH((r), tmp) { \ + if (memcmp((k), tmp->key, sizeof(coap_key_t)) == 0) { \ + (res) = tmp; \ + break; \ + } \ + } \ + } +#else /* COAP_RESOURCES_NOHASH */ + +#define RESOURCES_ADD(r, obj) \ + HASH_ADD(hh, (r), key, sizeof(coap_key_t), (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), sizeof(coap_key_t), (res)); \ + } + +#endif /* COAP_RESOURCES_NOHASH */ + +/** @} */ + +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 *, + const coap_address_t *, + const str *); + +#endif /* _COAP_RESOURCE_H_ */ diff --git a/tools/sdk/include/coap/str.h b/tools/sdk/include/coap/str.h new file mode 100644 index 00000000000..3dfa6731550 --- /dev/null +++ b/tools/sdk/include/coap/str.h @@ -0,0 +1,33 @@ +/* + * 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 + +typedef struct { + size_t length; /* length of string */ + unsigned char *s; /* string data */ +} str; + +#define COAP_SET_STR(st,l,v) { (st)->length = (l), (st)->s = (v); } + +/** + * Returns a new string object with at least size bytes storage allocated. The + * string must be released using coap_delete_string(); + */ +str *coap_new_string(size_t size); + +/** + * Deletes the given string and releases any memory allocated. + */ +void coap_delete_string(str *); + +#endif /* _COAP_STR_H_ */ diff --git a/tools/sdk/include/coap/subscribe.h b/tools/sdk/include/coap/subscribe.h new file mode 100644 index 00000000000..52068642dd7 --- /dev/null +++ b/tools/sdk/include/coap/subscribe.h @@ -0,0 +1,72 @@ +/* + * subscribe.h -- subscription handling for CoAP + * see draft-ietf-core-observe-16 + * + * 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" + +/** + * @defgroup observe Resource observation + * @{ + */ + +/** + * 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_endpoint_t local_if; /**< local communication interface */ + coap_address_t subscriber; /**< address and port of subscriber */ + + 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) */ + size_t token_length; /**< actual length of token */ + unsigned char token[8]; /**< token used for subscription */ +} coap_subscription_t; + +void coap_subscription_init(coap_subscription_t *); + +/** @} */ + +#endif /* _COAP_SUBSCRIBE_H_ */ diff --git a/tools/sdk/include/coap/uri.h b/tools/sdk/include/coap/uri.h new file mode 100644 index 00000000000..2340a7a6c88 --- /dev/null +++ b/tools/sdk/include/coap/uri.h @@ -0,0 +1,121 @@ +/* + * 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 "hashkey.h" +#include "str.h" + +/** + * 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 { + str host; /**< host part of the URI */ + unsigned short port; /**< The port in host byte order */ + str path; /**< Beginning of the first path segment. + Use coap_split_path() to create Uri-Path options */ + str query; /**< The query part if present */ +} coap_uri_t; + +/** + * 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 unsigned char *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); + +/** + * Calculates a hash over the given path and stores the result in + * @p key. This function returns @c 0 on error or @c 1 on success. + * + * @param path The URI path to generate hash for. + * @param len The length of @p path. + * @param key The output buffer. + * + * @return @c 1 if @p key was set, @c 0 otherwise. + */ +int coap_hash_path(const unsigned char *path, size_t len, coap_key_t key); + +/** + * @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 unsigned char *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 unsigned char *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 unsigned char *s, + size_t length, + unsigned char *buf, + size_t *buflen); + +/** @} */ + +#endif /* _COAP_URI_H_ */ diff --git a/tools/sdk/include/coap/uthash.h b/tools/sdk/include/coap/uthash.h new file mode 100644 index 00000000000..32b7a81cfbb --- /dev/null +++ b/tools/sdk/include/coap/uthash.h @@ -0,0 +1,963 @@ +/* +Copyright (c) 2003-2014, 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 + +#include /* memcmp,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(_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 +#define DECLTYPE(x) +#endif +#elif defined(__BORLANDC__) || defined(__LCC__) || defined(__WATCOMC__) +#define NO_DECLTYPE +#define DECLTYPE(x) +#else /* GNU, Sun and other compilers */ +#define DECLTYPE(x) (__typeof(x)) +#endif + +#ifdef NO_DECLTYPE +#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__) +#include +#else +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; +#endif +#else +#include +#endif + +#define UTHASH_VERSION 1.9.9 + +#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_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 32 /* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of buckets */ +#define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ + +/* calculate the element whose hash handle address is hhe */ +#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) + +#define HASH_FIND(hh,head,keyptr,keylen,out) \ +do { \ + out=NULL; \ + if (head) { \ + unsigned _hf_bkt,_hf_hashv; \ + HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ + keyptr,keylen,out); \ + } \ + } \ +} while (0) + +#ifdef HASH_BLOOM +#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM) +#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0) +#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"); } \ + memset((tbl)->bloom_bv, 0, 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)/8] |= (1U << ((idx)%8))) +#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) + +#define HASH_BLOOM_ADD(tbl,hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) + +#define HASH_BLOOM_TEST(tbl,hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) + +#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 0 +#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"); } \ + memset((head)->hh.tbl, 0, 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"); } \ + memset((head)->hh.tbl->buckets, 0, \ + 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_ADD(hh,head,fieldname,keylen_in,add) \ + HASH_ADD_KEYPTR(hh,head,&((add)->fieldname),keylen_in,add) + +#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ +do { \ + replaced=NULL; \ + HASH_FIND(hh,head,&((add)->fieldname),keylen_in,replaced); \ + if (replaced!=NULL) { \ + HASH_DELETE(hh,head,replaced); \ + }; \ + HASH_ADD(hh,head,fieldname,keylen_in,add); \ +} while(0) + +#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ +do { \ + unsigned _ha_bkt; \ + (add)->hh.next = NULL; \ + (add)->hh.key = (char*)(keyptr); \ + (add)->hh.keylen = (unsigned)(keylen_in); \ + if (!(head)) { \ + head = (add); \ + (head)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh,head); \ + } else { \ + (head)->hh.tbl->tail->next = (add); \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail = &((add)->hh); \ + } \ + (head)->hh.tbl->num_items++; \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ + (add)->hh.hashv, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv); \ + HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ + HASH_FSCK(hh,head); \ +} while(0) + +#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ +do { \ + bkt = ((hashv) & ((num_bkts) - 1)); \ +} 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) \ +do { \ + struct UT_hash_handle *_hd_hh_del; \ + if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + head = NULL; \ + } else { \ + unsigned _hd_bkt; \ + _hd_hh_del = &((delptr)->hh); \ + if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ + (head)->hh.tbl->tail = \ + (UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho); \ + } \ + if ((delptr)->hh.prev) { \ + ((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ + } else { \ + DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ + } \ + if (_hd_hh_del->next) { \ + ((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next + \ + (head)->hh.tbl->hho))->prev = \ + _hd_hh_del->prev; \ + } \ + HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh,head); \ +} while (0) + + +/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ +#define HASH_FIND_STR(head,findstr,out) \ + HASH_FIND(hh,head,findstr,(unsigned)strlen(findstr),out) +#define HASH_ADD_STR(head,strfield,add) \ + HASH_ADD(hh,head,strfield[0],strlen(add->strfield),add) +#define HASH_REPLACE_STR(head,strfield,add,replaced) \ + HASH_REPLACE(hh,head,strfield[0],(unsigned)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) \ +do { \ + struct UT_hash_handle *_thh; \ + if (head) { \ + unsigned _bkt_i; \ + unsigned _count; \ + char *_prev; \ + _count = 0; \ + 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("invalid hh_prev %p, actual %p\n", \ + _thh->hh_prev, _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("invalid bucket count %u, actual %u\n", \ + (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid hh item count %u, actual %u\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + /* traverse hh in app order; check next/prev integrity, count */ \ + _count = 0; \ + _prev = NULL; \ + _thh = &(head)->hh; \ + while (_thh) { \ + _count++; \ + if (_prev !=(char*)(_thh->prev)) { \ + HASH_OOPS("invalid prev %p, actual %p\n", \ + _thh->prev, _prev ); \ + } \ + _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ + (head)->hh.tbl->hho) : NULL ); \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid app item count %u, actual %u\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + } \ +} while (0) +#else +#define HASH_FSCK(hh,head) +#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, 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,num_bkts,hashv,bkt) \ +do { \ + unsigned _hb_keylen=keylen; \ + char *_hb_key=(char*)(key); \ + (hashv) = 0; \ + while (_hb_keylen--) { (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; } \ + bkt = (hashv) & (num_bkts-1); \ +} 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,num_bkts,hashv,bkt) \ +do { \ + unsigned _sx_i; \ + char *_hs_key=(char*)(key); \ + hashv = 0; \ + for(_sx_i=0; _sx_i < keylen; _sx_i++) \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ + bkt = hashv & (num_bkts-1); \ +} while (0) +/* FNV-1a variation */ +#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _fn_i; \ + char *_hf_key=(char*)(key); \ + hashv = 2166136261UL; \ + for(_fn_i=0; _fn_i < keylen; _fn_i++) { \ + hashv = hashv ^ _hf_key[_fn_i]; \ + hashv = hashv * 16777619; \ + } \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _ho_i; \ + char *_ho_key=(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); \ + bkt = hashv & (num_bkts-1); \ +} 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,num_bkts,hashv,bkt) \ +do { \ + unsigned _hj_i,_hj_j,_hj_k; \ + unsigned char *_hj_key=(unsigned char*)(key); \ + hashv = 0xfeedbeef; \ + _hj_i = _hj_j = 0x9e3779b9; \ + _hj_k = (unsigned)(keylen); \ + while (_hj_k >= 12) { \ + _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 -= 12; \ + } \ + hashv += keylen; \ + switch ( _hj_k ) { \ + case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ + case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ + case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ + case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ + case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ + case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ + case 5: _hj_j += _hj_key[4]; \ + case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ + case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ + case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ + case 1: _hj_i += _hj_key[0]; \ + /* case 0: nothing left to add */ \ + default: /* make gcc -Wswitch-default happy */ \ + ; \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + bkt = hashv & (num_bkts-1); \ +} 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,num_bkts,hashv,bkt) \ +do { \ + unsigned char *_sfh_key=(unsigned char*)(key); \ + uint32_t _sfh_tmp, _sfh_len = keylen; \ + \ + int _sfh_rem = _sfh_len & 3; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabe; \ + \ + /* Main loop */ \ + for (;_sfh_len > 0; _sfh_len--) { \ + hashv += get16bits (_sfh_key); \ + _sfh_tmp = (uint32_t)(get16bits (_sfh_key+2)) << 11 ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2*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; \ + bkt = hashv & (num_bkts-1); \ +} 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 & 0x3) == 0) +#define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 0x3) == 1) +#define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 0x3) == 2) +#define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 0x3) == 3) +#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 *= 0x85ebca6b; \ + _h ^= _h >> 13; \ + _h *= 0xc2b2ae35l; \ + _h ^= _h >> 16; \ +} while(0) + +#define HASH_MUR(key,keylen,num_bkts,hashv,bkt) \ +do { \ + const uint8_t *_mur_data = (const uint8_t*)(key); \ + const int _mur_nblocks = (keylen) / 4; \ + uint32_t _mur_h1 = 0xf88D5353; \ + uint32_t _mur_c1 = 0xcc9e2d51; \ + uint32_t _mur_c2 = 0x1b873593; \ + 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; _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*5+0xe6546b64; \ + } \ + _mur_tail = (const uint8_t*)(_mur_data + _mur_nblocks*4); \ + _mur_k1=0; \ + switch((keylen) & 3) { \ + case 3: _mur_k1 ^= _mur_tail[2] << 16; \ + case 2: _mur_k1 ^= _mur_tail[1] << 8; \ + case 1: _mur_k1 ^= _mur_tail[0]; \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1,15); \ + _mur_k1 *= _mur_c2; \ + _mur_h1 ^= _mur_k1; \ + } \ + _mur_h1 ^= (keylen); \ + MUR_FMIX(_mur_h1); \ + hashv = _mur_h1; \ + bkt = hashv & (num_bkts-1); \ +} while(0) +#endif /* HASH_USING_NO_STRICT_ALIASING */ + +/* key comparison function; return 0 if keys equal */ +#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) + +/* iterate over items in a known bucket to find desired item */ +#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ +do { \ + if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ + else out=NULL; \ + while (out) { \ + if ((out)->hh.keylen == keylen_in) { \ + if ((HASH_KEYCMP((out)->hh.key,keyptr,keylen_in)) == 0) break; \ + } \ + if ((out)->hh.hh_next) 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 { \ + head.count++; \ + (addhh)->hh_next = head.hh_head; \ + (addhh)->hh_prev = NULL; \ + if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ + (head).hh_head=addhh; \ + if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ + && (addhh)->tbl->noexpand != 1) { \ + HASH_EXPAND_BUCKETS((addhh)->tbl); \ + } \ +} while(0) + +/* remove an item from a given bucket */ +#define HASH_DEL_IN_BKT(hh,head,hh_del) \ + (head).count--; \ + if ((head).hh_head == hh_del) { \ + (head).hh_head = hh_del->hh_next; \ + } \ + if (hh_del->hh_prev) { \ + hh_del->hh_prev->hh_next = hh_del->hh_next; \ + } \ + if (hh_del->hh_next) { \ + hh_del->hh_next->hh_prev = hh_del->hh_prev; \ + } + +/* 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( \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ + memset(_he_new_buckets, 0, \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + tbl->ideal_chain_maxlen = \ + (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ + ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ + 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) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _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) _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 *= 2; \ + tbl->log2_num_buckets++; \ + tbl->buckets = _he_new_buckets; \ + tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ + (tbl->ineff_expands+1) : 0; \ + if (tbl->ineff_expands > 1) { \ + 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) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ + _hs_psize++; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + if (! (_hs_q) ) break; \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ + if (_hs_psize == 0) { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ + _hs_e = _hs_p; \ + if (_hs_p){ \ + _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : 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){ \ + _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + } \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } \ + if ( _hs_tail ) { \ + _hs_tail->next = ((_hs_e) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + if (_hs_e) { \ + _hs_e->prev = ((_hs_tail) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ + } \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + if (_hs_tail){ \ + _hs_tail->next = NULL; \ + } \ + if ( _hs_nmerges <= 1 ) { \ + _hs_looping=0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2; \ + } \ + HASH_FSCK(hh,head); \ + } \ +} 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) { \ + 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; \ + _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) { _last_elt_hh->next = _elt; } \ + if (!dst) { \ + 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); \ + (dst)->hh_dst.tbl->num_items++; \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ + } \ + } \ + HASH_FSCK(hh_dst,dst); \ +} while (0) + +#define HASH_CLEAR(hh,head) \ +do { \ + if (head) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head)=NULL; \ + } \ +} while(0) + +#define HASH_OVERHEAD(hh,head) \ + ((head) ? ( \ + (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)))) : 0) + +#ifdef NO_DECLTYPE +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) +#else +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(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)?((head)->hh.tbl->num_items):0) + +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 0xa0111fe1 +#define HASH_BLOOM_SIGNATURE 0xb12220f2 + +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; + char 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 */ + 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/include/coap/utlist.h b/tools/sdk/include/coap/utlist.h new file mode 100644 index 00000000000..b5f3f04c104 --- /dev/null +++ b/tools/sdk/include/coap/utlist.h @@ -0,0 +1,757 @@ +/* +Copyright (c) 2007-2014, 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 1.9.9 + +#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++ code), this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#ifdef _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 +#define LDECLTYPE(x) char* +#endif +#elif defined(__ICCARM__) +#define NO_DECLTYPE +#define LDECLTYPE(x) char* +#else /* GNU, Sun and other compilers */ +#define LDECLTYPE(x) __typeof(x) +#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 _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } +#define _NEXT(elt,list,next) ((char*)((list)->next)) +#define _NEXTASGN(elt,list,to,next) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } +/* #define _PREV(elt,list,prev) ((char*)((list)->prev)) */ +#define _PREVASGN(elt,list,to,prev) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } +#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } +#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } +#else +#define _SV(elt,list) +#define _NEXT(elt,list,next) ((elt)->next) +#define _NEXTASGN(elt,list,to,next) ((elt)->next)=(to) +/* #define _PREV(elt,list,prev) ((elt)->prev) */ +#define _PREVASGN(elt,list,to,prev) ((elt)->prev)=(to) +#define _RS(list) +#define _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; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _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++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list,next); _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; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e,next); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL,next); _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; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _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++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list,next); _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; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e,next); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail,prev); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN(list->prev, _ls_tail); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL,next); _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) { \ + _CASTASGN(_ls_p,list); \ + _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++; \ + _SV(_ls_q,list); \ + if (_NEXT(_ls_q,list,next) == _ls_oldhead) { \ + _ls_q = NULL; \ + } else { \ + _ls_q = _NEXT(_ls_q,list,next); \ + } \ + _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; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = \ + _NEXT(_ls_p,list,next); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = \ + _NEXT(_ls_q,list,next); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e,next); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail,prev); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN(list->prev,_ls_tail); \ + _CASTASGN(_tmp,list); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp,next); _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_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) + +/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */ +#define LL_APPEND_VS2008(head,add) \ + LL_APPEND2_VS2008(head,add,next) + +#define LL_APPEND2_VS2008(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) + +#define LL_DELETE_VS2008(head,del) \ + LL_DELETE2_VS2008(head,del,next) + +#define LL_DELETE2_VS2008(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); \ + } \ + { \ + char **_head_alias = (char**)&(head); \ + *_head_alias = _tmp; \ + } \ + } \ +} while (0) +#ifdef NO_DECLTYPE +#undef LL_APPEND +#define LL_APPEND LL_APPEND_VS2008 +#undef LL_DELETE +#define LL_DELETE LL_DELETE_VS2008 +#undef LL_DELETE2 +#define LL_DELETE2 LL_DELETE2_VS2008 +#undef LL_APPEND2 +#define LL_APPEND2 LL_APPEND2_VS2008 +#undef LL_CONCAT /* no LL_CONCAT_VS2008 */ +#undef DL_CONCAT /* no DL_CONCAT_VS2008 */ +#endif +/* end VS2008 replacements */ + +#define LL_COUNT(head,el,counter) \ + LL_COUNT2(head,el,counter,next) \ + +#define LL_COUNT2(head,el,counter,next) \ +{ \ + counter = 0; \ + LL_FOREACH2(head,el,next){ ++counter; } \ +} + +#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_ELEM(head, el, add) \ +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_PREPEND_ELEM(head, el, add) \ +do { \ + LDECLTYPE(head) _tmp; \ + assert(head != NULL); \ + assert(el != 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); \ + } \ + } \ +} while (0) \ + + +/****************************************************************************** + * 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_CONCAT(head1,head2) \ + DL_CONCAT2(head1,head2,prev,next) + +#define DL_CONCAT2(head1,head2,prev,next) \ +do { \ + LDECLTYPE(head1) _tmp; \ + if (head2) { \ + if (head1) { \ + _tmp = (head2)->prev; \ + (head2)->prev = (head1)->prev; \ + (head1)->prev->next = (head2); \ + (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((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) \ +{ \ + counter = 0; \ + DL_FOREACH2(head,el,next){ ++counter; } \ +} + +#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_ELEM(head, el, add) \ +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_PREPEND_ELEM(head, el, add) \ +do { \ + assert(head != NULL); \ + assert(el != NULL); \ + assert(add != NULL); \ + (add)->next = (el); \ + (add)->prev = (el)->prev; \ + (el)->prev = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->prev->next = (add); \ + } \ +} while (0) \ + + +/****************************************************************************** + * circular doubly linked list macros * + *****************************************************************************/ +#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_DELETE(head,del) \ + CDL_DELETE2(head,del,prev,next) + +#define CDL_DELETE2(head,del,prev,next) \ +do { \ + if ( ((head)==(del)) && ((head)->next == (head))) { \ + (head) = 0L; \ + } 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) \ +{ \ + counter = 0; \ + CDL_FOREACH2(head,el,next){ ++counter; } \ +} + +#define CDL_FOREACH(head,el) \ + CDL_FOREACH2(head,el,next) + +#define CDL_FOREACH2(head,el,next) \ + for(el=head;el;el=((el)->next==head ? 0L : (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)) ? 0L : (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_ELEM(head, el, add) \ +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_PREPEND_ELEM(head, el, add) \ +do { \ + assert(head != NULL); \ + assert(el != NULL); \ + assert(add != NULL); \ + (add)->next = (el); \ + (add)->prev = (el)->prev; \ + (el)->prev = (add); \ + (add)->prev->next = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } \ +} while (0) \ + +#endif /* UTLIST_H */ + diff --git a/tools/sdk/include/config/sdkconfig.h b/tools/sdk/include/config/sdkconfig.h index 87acda19039..444fb1a682a 100644 --- a/tools/sdk/include/config/sdkconfig.h +++ b/tools/sdk/include/config/sdkconfig.h @@ -8,12 +8,18 @@ #define CONFIG_ESP32_PHY_MAX_TX_POWER 20 #define CONFIG_TRACEMEM_RESERVE_DRAM 0x0 #define CONFIG_FREERTOS_MAX_TASK_NAME_LEN 16 +#define CONFIG_MQTT_TRANSPORT_SSL 1 #define CONFIG_BLE_SMP_ENABLE 1 +#define CONFIG_SPIRAM_TYPE_AUTO 1 #define CONFIG_STACK_CHECK 1 +#define CONFIG_MB_SERIAL_TASK_PRIO 10 +#define CONFIG_MQTT_PROTOCOL_311 1 #define CONFIG_TCP_RECVMBOX_SIZE 6 #define CONFIG_LWIP_ETHARP_TRUST_IP_MAC 1 +#define CONFIG_BLE_SCAN_DUPLICATE 1 #define CONFIG_STACK_CHECK_NORM 1 #define CONFIG_TCP_WND_DEFAULT 5744 +#define CONFIG_PARTITION_TABLE_OFFSET 0x8000 #define CONFIG_SW_COEXIST_ENABLE 1 #define CONFIG_SPIFFS_USE_MAGIC_LENGTH 1 #define CONFIG_ESPTOOLPY_FLASHSIZE_4MB 1 @@ -23,46 +29,67 @@ #define CONFIG_ESPTOOLPY_FLASHFREQ "40m" #define CONFIG_MBEDTLS_KEY_EXCHANGE_RSA 1 #define CONFIG_UDP_RECVMBOX_SIZE 6 +#define CONFIG_ARDUHAL_PARTITION_SCHEME_DEFAULT 1 #define CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE 0 #define CONFIG_MBEDTLS_AES_C 1 #define CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED 1 #define CONFIG_A2DP_SINK_TASK_STACK_SIZE 2048 +#define CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN 752 #define CONFIG_MBEDTLS_GCM_C 1 #define CONFIG_ESPTOOLPY_FLASHSIZE "4MB" #define CONFIG_SPIFFS_CACHE_WR 1 +#define CONFIG_SPIRAM_CACHE_WORKAROUND 1 #define CONFIG_BROWNOUT_DET_LVL_SEL_0 1 +#define CONFIG_D0WD_PSRAM_CS_IO 16 #define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER 1 #define CONFIG_EMAC_L2_TO_L3_RX_BUF_MODE 1 +#define CONFIG_BTDM_CONTROLLER_MODEM_SLEEP 1 #define CONFIG_SPIFFS_CACHE 1 #define CONFIG_INT_WDT 1 #define CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL 1 +#define CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN 3 #define CONFIG_MBEDTLS_SSL_PROTO_TLS1 1 +#define CONFIG_BT_STACK_NO_LOG 1 +#define CONFIG_ESP_GRATUITOUS_ARP 1 #define CONFIG_MBEDTLS_ECDSA_C 1 #define CONFIG_ESPTOOLPY_FLASHFREQ_40M 1 +#define CONFIG_HTTPD_MAX_REQ_HDR_LEN 512 #define CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE 0 #define CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS 1 #define CONFIG_MBEDTLS_ECDH_C 1 +#define CONFIG_SPIRAM_USE_CAPS_ALLOC 1 +#define CONFIG_FRMN1_QUANT 1 #define CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE 1 -#define CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM 10 +#define CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM 16 #define CONFIG_MBEDTLS_SSL_ALPN 1 #define CONFIG_MBEDTLS_PEM_WRITE_C 1 #define CONFIG_BT_SPP_ENABLED 1 -#define CONFIG_BT_RESERVE_DRAM 0x10000 +#define CONFIG_BT_RESERVE_DRAM 0xdb5c #define CONFIG_CXX_EXCEPTIONS 1 +#define CONFIG_D2WD_PSRAM_CLK_IO 9 #define CONFIG_FATFS_FS_LOCK 0 #define CONFIG_IP_LOST_TIMER_INTERVAL 120 #define CONFIG_SPIFFS_META_LENGTH 4 #define CONFIG_ESP32_PANIC_PRINT_REBOOT 1 +#define CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE 20 #define CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED 1 #define CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED 1 +#define CONFIG_CAMERA_CORE1 1 +#define CONFIG_ESP32_DPORT_DIS_INTERRUPT_LVL 5 +#define CONFIG_MB_SERIAL_BUF_SIZE 256 #define CONFIG_CONSOLE_UART_BAUDRATE 115200 +#define CONFIG_SPIRAM_SUPPORT 1 #define CONFIG_LWIP_MAX_SOCKETS 10 #define CONFIG_LWIP_NETIF_LOOPBACK 1 #define CONFIG_EMAC_TASK_PRIORITY 20 #define CONFIG_TIMER_TASK_STACK_DEPTH 2048 #define CONFIG_TCP_MSS 1436 #define CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED 1 +#define CONFIG_BTDM_CONTROLLER_MODE_BTDM 1 +#define CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF 3 +#define CONFIG_TCPIP_TASK_AFFINITY_CPU0 1 #define CONFIG_FATFS_CODEPAGE 850 +#define CONFIG_SPIRAM_SPIWP_SD3_PIN 7 #define CONFIG_ULP_COPROC_RESERVE_MEM 512 #define CONFIG_LWIP_MAX_UDP_PCBS 16 #define CONFIG_ESPTOOLPY_BAUD 921600 @@ -78,31 +105,46 @@ #define CONFIG_MBEDTLS_RC4_DISABLED 1 #define CONFIG_FATFS_LFN_STACK 1 #define CONFIG_CONSOLE_UART_NUM 0 +#define CONFIG_ARDUINO_EVENT_RUNNING_CORE 1 #define CONFIG_ESP32_APPTRACE_LOCK_ENABLE 1 +#define CONFIG_PTHREAD_STACK_MIN 768 #define CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_RC 1 #define CONFIG_TCP_OVERSIZE_MSS 1 #define CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS 1 #define CONFIG_CONSOLE_UART_DEFAULT 1 +#define CONFIG_A2DP_SOURCE_TASK_STACK_SIZE 2048 #define CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN 16384 #define CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS 4 #define CONFIG_ESPTOOLPY_FLASHSIZE_DETECT 1 #define CONFIG_AUTOSTART_ARDUINO 1 +#define CONFIG_ARDUINO_RUNNING_CORE 1 +#define CONFIG_PPP_CHAP_SUPPORT 1 #define CONFIG_LOG_DEFAULT_LEVEL_ERROR 1 #define CONFIG_TIMER_TASK_STACK_SIZE 4096 #define CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE 1 +#define CONFIG_SPIRAM_BANKSWITCH_ENABLE 1 #define CONFIG_MBEDTLS_X509_CRL_PARSE_C 1 +#define CONFIG_HTTPD_PURGE_BUF_LEN 32 +#define CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR 1 +#define CONFIG_MB_SERIAL_TASK_STACK_SIZE 2048 +#define CONFIG_MBEDTLS_PSK_MODES 1 +#define CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO 1 #define CONFIG_LWIP_DHCPS_LEASE_UNIT 60 #define CONFIG_SPIFFS_USE_MAGIC 1 +#define CONFIG_OV7725_SUPPORT 1 #define CONFIG_TCPIP_TASK_STACK_SIZE 2560 #define CONFIG_BLUEDROID_PINNED_TO_CORE_0 1 #define CONFIG_FATFS_CODEPAGE_850 1 #define CONFIG_TASK_WDT 1 +#define CONFIG_MTMN_LITE_QUANT 1 #define CONFIG_MAIN_TASK_STACK_SIZE 4096 #define CONFIG_SPIFFS_PAGE_CHECK 1 +#define CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0 1 #define CONFIG_LWIP_MAX_ACTIVE_TCP 16 #define CONFIG_TASK_WDT_TIMEOUT_S 5 #define CONFIG_INT_WDT_TIMEOUT_MS 300 -#define CONFIG_ESP32_RTC_XTAL_BOOTSTRAP_CYCLES 100 +#define CONFIG_SCCB_HARDWARE_I2C 1 +#define CONFIG_ARDUINO_EVENT_RUN_CORE1 1 #define CONFIG_ESPTOOLPY_FLASHMODE "dio" #define CONFIG_BTC_TASK_STACK_SIZE 8192 #define CONFIG_BLUEDROID_ENABLED 1 @@ -110,50 +152,87 @@ #define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA 1 #define CONFIG_ESPTOOLPY_BEFORE "default_reset" #define CONFIG_ADC2_DISABLE_DAC 1 +#define CONFIG_HFP_ENABLE 1 +#define CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_NUM 100 +#define CONFIG_ESP32_REV_MIN_0 1 #define CONFIG_LOG_DEFAULT_LEVEL 1 #define CONFIG_TIMER_QUEUE_LENGTH 10 +#define CONFIG_ESP32_REV_MIN 0 +#define CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT 1 +#define CONFIG_GATTS_SEND_SERVICE_CHANGE_MODE 0 #define CONFIG_MAKE_WARN_UNDEFINED_VARIABLES 1 #define CONFIG_FATFS_TIMEOUT_MS 10000 -#define CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM 0 +#define CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM 32 +#define CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS 1 #define CONFIG_MBEDTLS_CCM_C 1 +#define CONFIG_SPI_MASTER_ISR_IN_IRAM 1 +#define CONFIG_ARDUHAL_PARTITION_SCHEME "default" #define CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER 20 #define CONFIG_ESP32_RTC_CLK_CAL_CYCLES 1024 #define CONFIG_ESP32_WIFI_TX_BA_WIN 6 #define CONFIG_ESP32_WIFI_NVS_ENABLED 1 +#define CONFIG_MDNS_MAX_SERVICES 10 #define CONFIG_ULP_COPROC_ENABLED 1 +#define CONFIG_HFP_AUDIO_DATA_PATH_PCM 1 +#define CONFIG_EMAC_CHECK_LINK_PERIOD_MS 2000 +#define CONFIG_BTDM_LPCLK_SEL_MAIN_XTAL 1 #define CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED 1 #define CONFIG_LIBSODIUM_USE_MBEDTLS_SHA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_PSK 1 #define CONFIG_DMA_RX_BUF_NUM 10 #define CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_PSK 1 #define CONFIG_TCP_SYNMAXRTX 6 #define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA 1 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF 0 #define CONFIG_HEAP_POISONING_LIGHT 1 #define CONFIG_PYTHON "python" +#define CONFIG_SPIRAM_BANKSWITCH_RESERVE 8 #define CONFIG_MBEDTLS_ECP_NIST_OPTIM 1 #define CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 1 #define CONFIG_ESPTOOLPY_COMPRESSED 1 #define CONFIG_PARTITION_TABLE_FILENAME "partitions_singleapp.csv" +#define CONFIG_MB_CONTROLLER_STACK_SIZE 4096 #define CONFIG_TCP_SND_BUF_DEFAULT 5744 +#define CONFIG_GARP_TMR_INTERVAL 60 #define CONFIG_LWIP_DHCP_MAX_NTP_SERVERS 1 #define CONFIG_TCP_MSL 60000 #define CONFIG_MBEDTLS_SSL_PROTO_TLS1_1 1 #define CONFIG_LWIP_SO_REUSE_RXTOALL 1 +#define CONFIG_MB_CONTROLLER_NOTIFY_TIMEOUT 20 +#define CONFIG_ESP32_WIFI_MGMT_SBUF_NUM 32 #define CONFIG_PARTITION_TABLE_SINGLE_APP 1 +#define CONFIG_XTENSA_IMPL 1 +#define CONFIG_ESP32_WIFI_RX_BA_WIN 16 #define CONFIG_MBEDTLS_X509_CSR_PARSE_C 1 #define CONFIG_SPIFFS_USE_MTIME 1 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN 0 +#define CONFIG_LWIP_DHCP_RESTORE_LAST_IP 1 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN 2 +#define CONFIG_PICO_PSRAM_CS_IO 10 +#define CONFIG_EMAC_TASK_STACK_SIZE 3072 +#define CONFIG_MB_QUEUE_LENGTH 20 #define CONFIG_SW_COEXIST_PREFERENCE_VALUE 2 #define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA 1 +#define CONFIG_OV2640_SUPPORT 1 +#define CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_PSK 1 +#define CONFIG_PPP_SUPPORT 1 +#define CONFIG_SPIRAM_SPEED_40M 1 #define CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE 2048 #define CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V 1 #define CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY 2000 #define CONFIG_BROWNOUT_DET_LVL 0 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_SCO_DATA_PATH_PCM 1 #define CONFIG_MBEDTLS_PEM_PARSE_C 1 #define CONFIG_SPIFFS_GC_MAX_RUNS 10 +#define CONFIG_ARDUINO_RUN_CORE1 1 #define CONFIG_ESP32_APPTRACE_DEST_NONE 1 -#define CONFIG_PARTITION_TABLE_CUSTOM_APP_BIN_OFFSET 0x10000 +#define CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC 1 #define CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 1 #define CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_RSA 1 #define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM 32 +#define CONFIG_HTTPD_MAX_URI_LEN 512 #define CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED 1 #define CONFIG_ARDUHAL_ESP_LOG 1 #define CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED 1 @@ -167,40 +246,59 @@ #define CONFIG_ESP32_XTAL_FREQ 0 #define CONFIG_MONITOR_BAUD_115200B 1 #define CONFIG_LOG_BOOTLOADER_LEVEL 0 +#define CONFIG_D2WD_PSRAM_CS_IO 10 #define CONFIG_MBEDTLS_TLS_ENABLED 1 #define CONFIG_LWIP_MAX_RAW_PCBS 16 #define CONFIG_SMP_ENABLE 1 +#define CONFIG_SPIRAM_SIZE -1 #define CONFIG_MBEDTLS_SSL_SESSION_TICKETS 1 #define CONFIG_SPIFFS_MAX_PARTITIONS 3 #define CONFIG_ESP_ERR_TO_NAME_LOOKUP 1 #define CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_0 1 #define CONFIG_MBEDTLS_SSL_RENEGOTIATION 1 #define CONFIG_ESPTOOLPY_BEFORE_RESET 1 +#define CONFIG_MB_EVENT_QUEUE_TIMEOUT 20 #define CONFIG_ESPTOOLPY_BAUD_OTHER_VAL 115200 +#define CONFIG_PPP_MPPE_SUPPORT 1 #define CONFIG_ENABLE_ARDUINO_DEPENDS 1 +#define CONFIG_WARN_WRITE_STRINGS 1 #define CONFIG_SPIFFS_OBJ_NAME_LEN 32 #define CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT 5 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_EFF 2 #define CONFIG_LOG_BOOTLOADER_LEVEL_NONE 1 #define CONFIG_PARTITION_TABLE_MD5 1 #define CONFIG_TCPIP_RECVMBOX_SIZE 32 #define CONFIG_ESP32_DEFAULT_CPU_FREQ_240 1 #define CONFIG_ESP32_XTAL_FREQ_AUTO 1 +#define CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST 1 #define CONFIG_TCP_MAXRTX 12 #define CONFIG_ESPTOOLPY_AFTER "hard_reset" +#define CONFIG_TCPIP_TASK_AFFINITY 0x0 #define CONFIG_LWIP_SO_REUSE 1 +#define CONFIG_ARDUINO_UDP_RUN_CORE1 1 #define CONFIG_DMA_TX_BUF_NUM 10 #define CONFIG_LWIP_MAX_LISTENING_TCP 16 #define CONFIG_FREERTOS_INTERRUPT_BACKTRACE 1 #define CONFIG_WL_SECTOR_SIZE 4096 #define CONFIG_ESP32_DEBUG_OCDAWARE 1 +#define CONFIG_MQTT_TRANSPORT_WEBSOCKET 1 #define CONFIG_TIMER_TASK_PRIORITY 1 +#define CONFIG_PPP_PAP_SUPPORT 1 #define CONFIG_MBEDTLS_TLS_CLIENT 1 #define CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI 1 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_SCO_DATA_PATH_EFF 1 #define CONFIG_BT_ENABLED 1 +#define CONFIG_D0WD_PSRAM_CLK_IO 17 #define CONFIG_SW_COEXIST_PREFERENCE_BALANCE 1 #define CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED 1 #define CONFIG_MONITOR_BAUD 115200 +#define CONFIG_ESP32_DEBUG_STUBS_ENABLE 1 +#define CONFIG_BLE_ESTABLISH_LINK_CONNECTION_TIMEOUT 30 +#define CONFIG_TCPIP_LWIP 1 +#define CONFIG_REDUCE_PHY_TX_POWER 1 +#define CONFIG_BOOTLOADER_WDT_TIME_MS 9000 #define CONFIG_FREERTOS_CORETIMER_0 1 +#define CONFIG_IDF_FIRMWARE_CHIP_ID 0x0000 #define CONFIG_PARTITION_TABLE_CUSTOM_FILENAME "partitions.csv" #define CONFIG_MBEDTLS_HAVE_TIME 1 #define CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY 1 @@ -210,35 +308,57 @@ #define CONFIG_ADC_CAL_EFUSE_VREF_ENABLE 1 #define CONFIG_MBEDTLS_TLS_SERVER 1 #define CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT 1 +#define CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_SUPPORTED 1 #define CONFIG_FREERTOS_ISR_STACKSIZE 1536 +#define CONFIG_SUPPORT_TERMIOS 1 #define CONFIG_CLASSIC_BT_ENABLED 1 #define CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_RSA_PSK 1 #define CONFIG_OPENSSL_ASSERT_DO_NOTHING 1 #define CONFIG_WL_SECTOR_SIZE_4096 1 #define CONFIG_OPTIMIZATION_LEVEL_DEBUG 1 +#define CONFIG_FREERTOS_NO_AFFINITY 0x7FFFFFFF #define CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED 1 +#define CONFIG_MB_TIMER_INDEX 0 +#define CONFIG_SCAN_DUPLICATE_TYPE 0 #define CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED 1 -#define CONFIG_A2DP_SINK_ENABLE 1 #define CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED 1 +#define CONFIG_HFP_CLIENT_ENABLE 1 #define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA 1 +#define CONFIG_SPI_SLAVE_ISR_IN_IRAM 1 #define CONFIG_SYSTEM_EVENT_QUEUE_SIZE 32 #define CONFIG_BT_ACL_CONNECTIONS 4 #define CONFIG_FATFS_MAX_LFN 255 #define CONFIG_ESP32_WIFI_TX_BUFFER_TYPE 1 #define CONFIG_ESPTOOLPY_BAUD_921600B 1 +#define CONFIG_BOOTLOADER_WDT_ENABLE 1 +#define CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED 1 #define CONFIG_LWIP_LOOPBACK_MAX_PBUFS 8 -#define CONFIG_APP_OFFSET 0x10000 #define CONFIG_A2DP_ENABLE 1 +#define CONFIG_MB_TIMER_GROUP 0 #define CONFIG_SPI_FLASH_ROM_DRIVER_PATCH 1 +#define CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE 1 #define CONFIG_SPIFFS_PAGE_SIZE 256 #define CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED 1 +#define CONFIG_ESP32_DPORT_WORKAROUND 1 +#define CONFIG_PPP_MSCHAP_SUPPORT 1 #define CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0 1 #define CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT 2048 #define CONFIG_LWIP_SO_RCVBUF 1 +#define CONFIG_MB_TIMER_PORT_ENABLED 1 +#define CONFIG_DUPLICATE_SCAN_CACHE_SIZE 20 +#define CONFIG_ARDUINO_UDP_RUNNING_CORE 1 #define CONFIG_MONITOR_BAUD_OTHER_VAL 115200 #define CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF 1 #define CONFIG_ESPTOOLPY_PORT "/dev/cu.usbserial-DO00EAB0" #define CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS 1 +#define CONFIG_TASK_WDT_PANIC 1 +#define CONFIG_OV3660_SUPPORT 1 +#define CONFIG_BLE_ADV_REPORT_DISCARD_THRSHOLD 20 #define CONFIG_BLUEDROID_PINNED_TO_CORE 0 +#define CONFIG_BTDM_MODEM_SLEEP_MODE_ORIG 1 #define CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_ERROR 1 +#define CONFIG_ESP32_WIFI_IRAM_OPT 1 #define CONFIG_FATFS_API_ENCODING_ANSI_OEM 1 +#define CONFIG_ARDUINO_IDF_COMMIT "d3e562907" +#define CONFIG_ARDUINO_IDF_BRANCH "release/v3.2" diff --git a/tools/sdk/include/driver/driver/adc.h b/tools/sdk/include/driver/driver/adc.h index e6c6df1a403..b5a9a9848e3 100644 --- a/tools/sdk/include/driver/driver/adc.h +++ b/tools/sdk/include/driver/driver/adc.h @@ -192,6 +192,10 @@ esp_err_t adc1_config_channel_atten(adc1_channel_t channel, adc_atten_t atten); /** * @brief Take an ADC1 reading from a single channel. + * @note 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. * * @note Call adc1_config_width() before the first time this * function is called. @@ -210,6 +214,11 @@ int adc1_get_raw(adc1_channel_t channel); /** @cond */ //Doxygen command to hide deprecated function from API Reference /* + * @note 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. + * * @deprecated This function returns an ADC1 reading but is deprecated due to * a misleading name and has been changed to directly call the new function. * Use the new function adc1_get_raw() instead @@ -288,6 +297,11 @@ void adc1_ulp_enable(); /** * @brief Read Hall Sensor * + * @note 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. + * * @note The Hall Sensor uses channels 0 and 3 of ADC1. Do not configure * these channels for use as ADC channels. * @@ -349,6 +363,11 @@ 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 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. + * * @note 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``. diff --git a/tools/sdk/include/driver/driver/can.h b/tools/sdk/include/driver/driver/can.h new file mode 100644 index 00000000000..af7b66e0b57 --- /dev/null +++ b/tools/sdk/include/driver/driver/can.h @@ -0,0 +1,400 @@ +// 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_CAN_H_ +#define _DRIVER_CAN_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "esp_types.h" +#include "esp_intr.h" +#include "esp_err.h" +#include "gpio.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 CAN_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 = CAN_IO_UNUSED, .bus_off_io = CAN_IO_UNUSED, \ + .tx_queue_len = 5, .rx_queue_len = 5, \ + .alerts_enabled = CAN_ALERT_NONE, .clkout_divider = 0, } + +/** + * @brief Initializer macros for timing configuration structure + * + * The following initializer macros offer commonly found bit rates. + * + * @note These timing values are based on the assumption APB clock is at 80MHz + */ +#define CAN_TIMING_CONFIG_25KBITS() {.brp = 128, .tseg_1 = 16, .tseg_2 = 8, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_50KBITS() {.brp = 80, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_100KBITS() {.brp = 40, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_125KBITS() {.brp = 32, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_250KBITS() {.brp = 16, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_500KBITS() {.brp = 8, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_800KBITS() {.brp = 4, .tseg_1 = 16, .tseg_2 = 8, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_1MBITS() {.brp = 4, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} + +/** + * @brief Initializer macro for filter configuration to accept all IDs + */ +#define CAN_FILTER_CONFIG_ACCEPT_ALL() {.acceptance_code = 0, .acceptance_mask = 0xFFFFFFFF, .single_filter = true} + +/** + * @brief Alert flags + * + * The following flags represents the various kind of alerts available in + * the CAN driver. These flags can be used when configuring/reconfiguring + * alerts, or when calling can_read_alerts(). + * + * @note The CAN_ALERT_AND_LOG flag is not an actual alert, but will configure + * the CAN driver to log to UART when an enabled alert occurs. + */ +#define CAN_ALERT_TX_IDLE 0x0001 /**< Alert(1): No more messages to transmit */ +#define CAN_ALERT_TX_SUCCESS 0x0002 /**< Alert(2): The previous transmission was successful */ +#define CAN_ALERT_BELOW_ERR_WARN 0x0004 /**< Alert(4): Both error counters have dropped below error warning limit */ +#define CAN_ALERT_ERR_ACTIVE 0x0008 /**< Alert(8): CAN controller has become error active */ +#define CAN_ALERT_RECOVERY_IN_PROGRESS 0x0010 /**< Alert(16): CAN controller is undergoing bus recovery */ +#define CAN_ALERT_BUS_RECOVERED 0x0020 /**< Alert(32): CAN controller has successfully completed bus recovery */ +#define CAN_ALERT_ARB_LOST 0x0040 /**< Alert(64): The previous transmission lost arbitration */ +#define CAN_ALERT_ABOVE_ERR_WARN 0x0080 /**< Alert(128): One of the error counters have exceeded the error warning limit */ +#define CAN_ALERT_BUS_ERROR 0x0100 /**< Alert(256): A (Bit, Stuff, CRC, Form, ACK) error has occurred on the bus */ +#define CAN_ALERT_TX_FAILED 0x0200 /**< Alert(512): The previous transmission has failed (for single shot transmission) */ +#define CAN_ALERT_RX_QUEUE_FULL 0x0400 /**< Alert(1024): The RX queue is full causing a frame to be lost */ +#define CAN_ALERT_ERR_PASS 0x0800 /**< Alert(2048): CAN controller has become error passive */ +#define CAN_ALERT_BUS_OFF 0x1000 /**< Alert(4096): Bus-off condition occurred. CAN controller can no longer influence bus */ +#define CAN_ALERT_ALL 0x1FFF /**< Bit mask to enable all alerts during configuration */ +#define CAN_ALERT_NONE 0x0000 /**< Bit mask to disable all alerts during configuration */ +#define CAN_ALERT_AND_LOG 0x2000 /**< Bit mask to enable alerts to also be logged when they occur */ + +/** + * @brief Message flags + * + * The message flags are used to indicate the type of message transmitted/received. + * Some flags also specify the type of transmission. + */ +#define CAN_MSG_FLAG_NONE 0x00 /**< No message flags (Standard Frame Format) */ +#define CAN_MSG_FLAG_EXTD 0x01 /**< Extended Frame Format (29bit ID) */ +#define CAN_MSG_FLAG_RTR 0x02 /**< Message is a Remote Transmit Request */ +#define CAN_MSG_FLAG_SS 0x04 /**< Transmit as a Single Shot Transmission */ +#define CAN_MSG_FLAG_SELF 0x08 /**< Transmit as a Self Reception Request */ +#define CAN_MSG_FLAG_DLC_NON_COMP 0x10 /**< Message's Data length code is larger than 8. This will break compliance with CAN2.0B */ + +/** + * @brief Miscellaneous macros + */ +#define CAN_EXTD_ID_MASK 0x1FFFFFFF /**< Bit mask for 29 bit Extended Frame Format ID */ +#define CAN_STD_ID_MASK 0x7FF /**< Bit mask for 11 bit Standard Frame Format ID */ +#define CAN_MAX_DATA_LEN 8 /**< Maximum number of data bytes in a CAN2.0B frame */ +#define CAN_IO_UNUSED (-1) /**< Marks GPIO as unused in CAN configuration */ +/** @endcond */ + +/* ----------------------- Enum and Struct Definitions ---------------------- */ + +/** + * @brief CAN driver operating modes + */ +typedef enum { + CAN_MODE_NORMAL, /**< Normal operating mode where CAN controller can send/receive/acknowledge messages */ + CAN_MODE_NO_ACK, /**< Transmission does not require acknowledgment. Use this mode for self testing */ + CAN_MODE_LISTEN_ONLY, /**< The CAN controller will not influence the bus (No transmissions or acknowledgments) but can receive messages */ +} can_mode_t; + +/** + * @brief CAN driver states + */ +typedef enum { + CAN_STATE_STOPPED, /**< Stopped state. The CAN controller will not participate in any CAN bus activities */ + CAN_STATE_RUNNING, /**< Running state. The CAN controller can transmit and receive messages */ + CAN_STATE_BUS_OFF, /**< Bus-off state. The CAN controller cannot participate in bus activities until it has recovered */ + CAN_STATE_RECOVERING, /**< Recovering state. The CAN controller is undergoing bus recovery */ +} can_state_t; + +/** + * @brief Structure for general configuration of the CAN driver + * + * @note Macro initializers are available for this structure + */ +typedef struct { + can_mode_t mode; /**< Mode of CAN 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) */ +} can_general_config_t; + +/** + * @brief Structure for bit timing configuration of the CAN driver + * + * @note Macro initializers are available for this structure + */ +typedef struct { + uint8_t brp; /**< Baudrate prescaler (APB clock divider, even number from 2 to 128) */ + uint8_t tseg_1; /**< Timing segment 1 (Number of time quanta, between 1 to 16) */ + uint8_t tseg_2; /**< Timing segment 2 (Number of time quanta, 1 to 8) */ + uint8_t sjw; /**< Synchronization Jump Width (Max time quanta jump for synchronize from 1 to 4) */ + bool triple_sampling; /**< Enables triple sampling when the CAN controller samples a bit */ +} can_timing_config_t; + +/** + * @brief Structure for acceptance filter configuration of the CAN driver (see documentation) + * + * @note Macro initializers are available for this structure + */ +typedef struct { + uint32_t acceptance_code; /**< 32-bit acceptance code */ + uint32_t acceptance_mask; /**< 32-bit acceptance mask */ + bool single_filter; /**< Use Single Filter Mode (see documentation) */ +} can_filter_config_t; + +/** + * @brief Structure to store status information of CAN driver + */ +typedef struct { + can_state_t state; /**< Current state of CAN 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 */ + uint32_t arb_lost_count; /**< Number of instances arbitration was lost */ + uint32_t bus_error_count; /**< Number of instances a bus error has occurred */ +} can_status_info_t; + +/** + * @brief Structure to store a CAN message + * + * @note The flags member is used to control the message type, and transmission + * type (see documentation for message flags) + */ +typedef struct { + uint32_t flags; /**< Bit field of message flags indicates frame/transmission type (see documentation) */ + uint32_t identifier; /**< 11 or 29 bit identifier */ + uint8_t data_length_code; /**< Data length code */ + uint8_t data[CAN_MAX_DATA_LEN]; /**< Data bytes (not relevant in RTR frame) */ +} can_message_t; + +/* ----------------------------- Public API -------------------------------- */ + +/** + * @brief Install CAN driver + * + * This function installs the CAN driver using three configuration structures. + * The required memory is allocated and the CAN 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 CAN driver, call can_driver_uninstall() first + * + * @return + * - ESP_OK: Successfully installed CAN 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 can_driver_install(const can_general_config_t *g_config, const can_timing_config_t *t_config, const can_filter_config_t *f_config); + +/** + * @brief Uninstall the CAN driver + * + * This function uninstalls the CAN 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 CAN driver + * - ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed + */ +esp_err_t can_driver_uninstall(); + +/** + * @brief Start the CAN driver + * + * This function starts the CAN driver, putting the CAN driver into the running + * state. This allows the CAN driver to participate in CAN bus activities such + * as transmitting/receiving messages. The RX queue is reset in this function, + * clearing any unread messages. This function can only be called when the CAN + * driver is in the stopped state. + * + * @return + * - ESP_OK: CAN driver is now running + * - ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed + */ +esp_err_t can_start(); + +/** + * @brief Stop the CAN driver + * + * This function stops the CAN driver, preventing any further message from being + * transmitted or received until can_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 CAN driver is in the running state. + * + * @warning A message currently being transmitted/received on the CAN bus will + * be ceased immediately. This may lead to other CAN nodes interpreting + * the unfinished message as an error. + * + * @return + * - ESP_OK: CAN driver is now Stopped + * - ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed + */ +esp_err_t can_stop(); + +/** + * @brief Transmit a CAN message + * + * This function queues a CAN 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 timesout. 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 CAN 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: CAN driver is not in running state, or is not installed + * - ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions + */ +esp_err_t can_transmit(const can_message_t *message, TickType_t ticks_to_wait); + +/** + * @brief Receive a CAN 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: CAN driver is not installed + */ +esp_err_t can_receive(can_message_t *message, TickType_t ticks_to_wait); + +/** + * @brief Read CAN driver alerts + * + * This function will read the alerts raised by the CAN driver. If no alert has + * been 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: CAN driver is not installed + */ +esp_err_t can_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: CAN driver is not installed + */ +esp_err_t can_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 CAN driver is in + * the bus-off state. Once initiated, the CAN driver will enter the recovering + * state and wait for 128 occurrences of the bus-free signal on the CAN 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: CAN driver is not in the bus-off state, or is not installed + */ +esp_err_t can_initiate_recovery(); + +/** + * @brief Get current status information of the CAN driver + * + * @param[out] status_info Status information + * + * @return + * - ESP_OK: Status information retrieved + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_INVALID_STATE: CAN driver is not installed + */ +esp_err_t can_get_status_info(can_status_info_t *status_info); + +#ifdef __cplusplus +} +#endif + +#endif /*_DRIVER_CAN_H_*/ + diff --git a/tools/sdk/include/driver/driver/gpio.h b/tools/sdk/include/driver/driver/gpio.h index 8246c415ef3..c2231a625b1 100644 --- a/tools/sdk/include/driver/driver/gpio.h +++ b/tools/sdk/include/driver/driver/gpio.h @@ -24,6 +24,7 @@ #include "rom/gpio.h" #include "esp_attr.h" #include "esp_intr_alloc.h" +#include "soc/gpio_periph.h" #ifdef __cplusplus extern "C" { @@ -31,11 +32,11 @@ extern "C" { #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_2 (BIT(2)) /*!< Pin 2 selected @note There are more macros like that up to pin 39, excluding pins 20, 24 and 28..31. - They are not shown here + They are not shown here to reduce redundant information. */ /** @cond */ #define GPIO_SEL_3 (BIT(3)) /*!< Pin 3 selected */ @@ -121,10 +122,8 @@ extern "C" { #define GPIO_MODE_DEF_OD (BIT2) -#define GPIO_PIN_COUNT 40 /** @endcond */ -extern const uint32_t GPIO_PIN_MUX_REG[GPIO_PIN_COUNT]; #define GPIO_IS_VALID_GPIO(gpio_num) ((gpio_num < GPIO_PIN_COUNT && GPIO_PIN_MUX_REG[gpio_num] != 0)) /*!< Check whether it is a valid GPIO number */ #define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) ((GPIO_IS_VALID_GPIO(gpio_num)) && (gpio_num < 34)) /*!< Check whether it can be a valid GPIO number of output mode */ @@ -172,7 +171,7 @@ typedef enum { GPIO_NUM_38 = 38, /*!< GPIO38, input mode only */ GPIO_NUM_39 = 39, /*!< GPIO39, input mode only */ GPIO_NUM_MAX = 40, -/** @endcond */ +/** @endcond */ } gpio_num_t; typedef enum { @@ -248,6 +247,18 @@ typedef intr_handle_t gpio_isr_handle_t; */ 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 @@ -265,6 +276,10 @@ 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. + * 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. + * * @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 @@ -344,27 +359,27 @@ esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode); 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 - */ + * @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 - */ + * @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); /** @@ -389,6 +404,7 @@ esp_err_t gpio_wakeup_disable(gpio_num_t gpio_num); * @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); @@ -446,8 +462,10 @@ esp_err_t gpio_pulldown_dis(gpio_num_t gpio_num); * * @return * - ESP_OK Success - * - ESP_FAIL Operation fail * - 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); @@ -518,6 +536,80 @@ esp_err_t gpio_set_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t streng */ 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 dont'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 inversed, otherwise False. + */ +void gpio_iomux_out(uint8_t gpio_num, int func, bool oen_inv); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/driver/driver/i2c.h b/tools/sdk/include/driver/driver/i2c.h index b7aceb7b131..feb1d78bd63 100644 --- a/tools/sdk/include/driver/driver/i2c.h +++ b/tools/sdk/include/driver/driver/i2c.h @@ -1,540 +1,579 @@ -// 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_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/xtensa_api.h" -#include "freertos/task.h" -#include "freertos/queue.h" -#include "freertos/ringbuf.h" -#include "driver/gpio.h" - -#define I2C_APB_CLK_FREQ APB_CLK_FREQ /*!< I2C source clock is APB clock, 80MHz */ -#define I2C_FIFO_LEN (32) /*!< I2C hardware fifo length */ -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_CMD_RESTART = 0, /*!=0) The number of data bytes that pushed to the I2C slave buffer. - */ -int i2c_slave_write_buffer(i2c_port_t i2c_num, 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 write into 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 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_*/ +// 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_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/xtensa_api.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/ringbuf.h" +#include "driver/gpio.h" + +#define I2C_APB_CLK_FREQ APB_CLK_FREQ /*!< I2C source clock is APB clock, 80MHz */ +#define I2C_FIFO_LEN (32) /*!< I2C hardware fifo length */ +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_CMD_RESTART = 0, /*!=0) The number of data bytes that pushed to the I2C slave buffer. + */ +int i2c_slave_write_buffer(i2c_port_t i2c_num, 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 write into 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/include/driver/driver/i2s.h b/tools/sdk/include/driver/driver/i2s.h old mode 100755 new mode 100644 index 338e6ca3786..1f73e1f5566 --- a/tools/sdk/include/driver/driver/i2s.h +++ b/tools/sdk/include/driver/driver/i2s.h @@ -139,6 +139,7 @@ typedef struct { 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; @@ -263,42 +264,55 @@ 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 + * This function is deprecated. Use 'i2s_write' instead. + * This definition will be removed in a future release. + * + * @return + * - The amount of bytes written, if timeout, the result will be less than the size passed in. + * - ESP_FAIL Parameter error + */ +int i2s_write_bytes(i2s_port_t i2s_num, const void *src, size_t size, TickType_t ticks_to_wait) __attribute__ ((deprecated)); + +/** + * @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 src Source address to write from * - * @param size Size of data in bytes + * @param size Size of data in bytes * - * @param ticks_to_wait TX buffer wait timeout in RTOS ticks. If this + * @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 - * - Number of bytes written, if timeout occurred, bytes written will be less than the size passed. - * - ESP_FAIL Parameter error. + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error */ -int i2s_write_bytes(i2s_port_t i2s_num, const char *src, size_t size, TickType_t ticks_to_wait); +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 i2s_num I2S_NUM_0, I2S_NUM_1 * - * @param src Source address to write from + * @param src Source address to write from * - * @param size Size of data in bytes + * @param size Size of data in bytes * - * @param src_bits Source audio bit + * @param src_bits Source audio bit * - * @param aim_bits Bit wanted, no more than 32, and must be greater than src_bits + * @param aim_bits Bit wanted, no more than 32, and must be greater than src_bits * - * @param ticks_to_wait TX buffer wait timeout in RTOS ticks. If this + * @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 @@ -309,67 +323,80 @@ int i2s_write_bytes(i2s_port_t i2s_num, const char *src, size_t size, TickType_t * configuration (see i2s_config_t). * * @return - * - Number of bytes written, if timeout occurred, bytes written will be less than the size passed. - * - ESP_FAIL Parameter error. + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error */ -int i2s_write_expand(i2s_port_t i2s_num, const char *src, int size, int src_bits, int aim_bits, TickType_t ticks_to_wait); +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 + * This function is deprecated. Use 'i2s_read' instead. + * This definition will be removed in a future release. * - * @param dest Destination address to read into + * @return + * - The amount of bytes read, if timeout, bytes read will be less than the size passed in + * - ESP_FAIL Parameter error + */ +int i2s_read_bytes(i2s_port_t i2s_num, void *dest, size_t size, TickType_t ticks_to_wait) __attribute__ ((deprecated)); + +/** + * @brief Read data from I2S DMA receive buffer + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 * - * @param size Size of data in bytes + * @param dest Destination address to read into * - * @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. + * @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. * - * Format of the data in source buffer is determined by the I2S - * configuration (see i2s_config_t). * @note If the built-in ADC mode is enabled, we should call i2s_adc_start and i2s_adc_stop around the whole reading process, * to prevent the data getting corrupted. * * @return - * - Number of bytes read, if timeout occurred, bytes written will be less than the size passed. - * - ESP_FAIL Parameter error. + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error */ -int i2s_read_bytes(i2s_port_t i2s_num, char* dest, size_t size, TickType_t ticks_to_wait); +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 Push (write) a single sample to the I2S DMA TX buffer. + * @brief Write a single sample to the I2S DMA TX buffer. * - * Size of the sample is determined by the channel_format (mono or stereo)) & bits_per_sample configuration (see i2s_config_t). + * This function is deprecated. Use 'i2s_write' instead. + * This definition will be removed in a future release. * - * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * @param i2s_num I2S_NUM_0, I2S_NUM_1 * - * @param sample Pointer to buffer containing sample to write. Size of buffer (in bytes) = (number of channels) * bits_per_sample / 8. + * @param sample Buffer to read data. Size of buffer (in bytes) = bits_per_sample / 8. * - * @param ticks_to_wait Push timeout in RTOS ticks. If space is not available in the DMA TX buffer within this period, no data is written and function returns 0. + * @param ticks_to_wait Timeout in RTOS ticks. If a sample is not available in the DMA buffer within this period, no data is read and function returns zero. * * @return - * - Number of bytes successfully pushed to DMA buffer, will be either zero or the size of configured sample buffer. - * - ESP_FAIL Parameter error. + * - Number of bytes successfully pushed to DMA buffer, will be either zero or the size of configured sample buffer (in bytes). + * - ESP_FAIL Parameter error */ -int i2s_push_sample(i2s_port_t i2s_num, const char *sample, TickType_t ticks_to_wait); +int i2s_push_sample(i2s_port_t i2s_num, const void *sample, TickType_t ticks_to_wait) __attribute__ ((deprecated)); /** - * @brief Pop (read) a single sample from the I2S DMA RX buffer. + * @brief Read a single sample from the I2S DMA RX buffer. * - * Size of the sample is determined by the channel_format (mono or stereo)) & bits_per_sample configuration (see i2s_config_t). + * This function is deprecated. Use 'i2s_read' instead. + * This definition will be removed in a future release. * - * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * @param i2s_num I2S_NUM_0, I2S_NUM_1 * - * @param sample Buffer sample data will be read into. Size of buffer (in bytes) = (number of channels) * bits_per_sample / 8. + * @param sample Buffer to write data. Size of buffer (in bytes) = bits_per_sample / 8. * - * @param ticks_to_wait Pop timeout in RTOS ticks. If a sample is not available in the DMA buffer within this period, no data is read and function returns zero. + * @param ticks_to_wait Timeout in RTOS ticks. If a sample is not available in the DMA buffer within this period, no data is read and function returns zero. * * @return - * - Number of bytes successfully read from DMA buffer, will be either zero or the size of configured sample buffer. - * - ESP_FAIL Parameter error. + * - Number of bytes successfully read from DMA buffer, will be either zero or the size of configured sample buffer (in bytes). + * - ESP_FAIL Parameter error */ -int i2s_pop_sample(i2s_port_t i2s_num, char *sample, TickType_t ticks_to_wait); - +int i2s_pop_sample(i2s_port_t i2s_num, void *sample, TickType_t ticks_to_wait) __attribute__ ((deprecated)); /** * @brief Set sample rate used for I2S RX and TX. @@ -385,7 +412,6 @@ int i2s_pop_sample(i2s_port_t i2s_num, char *sample, TickType_t ticks_to_wait); * @return * - ESP_OK Success * - ESP_ERR_INVALID_ARG Parameter error - * - ESP_FAIL I2s is not initialized * - ESP_ERR_NO_MEM Out of memory */ esp_err_t i2s_set_sample_rates(i2s_port_t i2s_num, uint32_t rate); @@ -445,7 +471,6 @@ esp_err_t i2s_zero_dma_buffer(i2s_port_t i2s_num); * * @return * - ESP_OK Success - * - ESP_FAIL Not initialized * - ESP_ERR_INVALID_ARG Parameter error * - ESP_ERR_NO_MEM Out of memory */ @@ -454,7 +479,7 @@ esp_err_t i2s_set_clk(i2s_port_t i2s_num, uint32_t rate, i2s_bits_per_sample_t b /** * @brief Set built-in ADC mode for I2S DMA, this function will initialize ADC pad, * and set ADC parameters. - * @param adc_unit SAR ADC unit index + * @param adc_unit SAR ADC unit index * @param adc_channel ADC channel index * @return * - ESP_OK Success @@ -469,10 +494,9 @@ esp_err_t i2s_set_adc_mode(adc_unit_t adc_unit, adc1_channel_t adc_channel); * * @param i2s_num i2s port index * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - * - ESP_ERR_INVALID_STATE driver state error - * - ESP_FAIL Internal driver error + * - 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); @@ -481,9 +505,9 @@ esp_err_t i2s_adc_enable(i2s_port_t i2s_num); * @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_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); diff --git a/tools/sdk/include/driver/driver/ledc.h b/tools/sdk/include/driver/driver/ledc.h index c5250213d6c..6a82c19a2f9 100644 --- a/tools/sdk/include/driver/driver/ledc.h +++ b/tools/sdk/include/driver/driver/ledc.h @@ -27,6 +27,7 @@ extern "C" { #define LEDC_APB_CLK_HZ (APB_CLK_FREQ) #define LEDC_REF_CLK_HZ (1*1000000) #define LEDC_ERR_DUTY (0xFFFFFFFF) +#define LEDC_ERR_VAL (-1) typedef enum { LEDC_HIGH_SPEED_MODE = 0, /*!< LEDC high speed speed_mode */ @@ -42,6 +43,7 @@ typedef enum { 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 { @@ -54,6 +56,7 @@ typedef enum { 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 { @@ -69,12 +72,27 @@ typedef enum { } ledc_channel_t; typedef enum { - LEDC_TIMER_10_BIT = 10, /*!< LEDC PWM duty resolution of 10 bits */ - LEDC_TIMER_11_BIT = 11, /*!< LEDC PWM duty resolution of 11 bits */ - LEDC_TIMER_12_BIT = 12, /*!< LEDC PWM duty resolution of 12 bits */ - LEDC_TIMER_13_BIT = 13, /*!< LEDC PWM duty resolution of 13 bits */ - LEDC_TIMER_14_BIT = 14, /*!< LEDC PWM duty resolution of 14 bits */ - LEDC_TIMER_15_BIT = 15, /*!< LEDC PWM duty resolution of 15 bits */ + 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 */ + 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 */ + LEDC_TIMER_BIT_MAX, } ledc_timer_bit_t; typedef enum { @@ -92,7 +110,8 @@ typedef struct { 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) - 1] */ + 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; /** @@ -137,9 +156,11 @@ esp_err_t ledc_timer_config(const ledc_timer_config_t* timer_conf); /** * @brief LEDC update channel parameters - * Call this function to activate the LEDC updated parameters. - * After ledc_set_duty, ledc_set_fade, we need to call this function to update the settings. - * + * @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 speed_mode, high-speed mode and low-speed mode, * @param channel LEDC channel (0-7), select from ledc_channel_t * @@ -191,12 +212,47 @@ esp_err_t ledc_set_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num, uint32_t uint32_t ledc_get_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num); /** - * @brief LEDC set duty + * @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 speed_mode, high-speed mode and low-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 speed_mode, high-speed mode and low-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) - 1] + * @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 speed_mode, high-speed mode and low-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 @@ -219,20 +275,21 @@ 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. - * - * @param speed_mode Select the LEDC speed_mode, high-speed mode and low-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) - 1] - * @param gradule_direction Set the direction of the gradient - * @param step_num Set the number of the gradient - * @param duty_cyle_num Set how many LEDC tick each time the gradient lasts - * @param duty_scale Set gradient change amplitude + * @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 speed_mode, high-speed mode and low-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_cyle_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 gradule_direction, +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_cyle_num, uint32_t duty_scale); /** @@ -259,7 +316,7 @@ esp_err_t ledc_isr_register(void (*fn)(void*), void * arg, int intr_alloc_flags, * @param speed_mode Select the LEDC speed_mode, high-speed mode and low-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) - 1] + * @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 @@ -319,9 +376,14 @@ esp_err_t ledc_timer_resume(ledc_mode_t speed_mode, uint32_t timer_sel); esp_err_t ledc_bind_channel_timer(ledc_mode_t speed_mode, uint32_t channel, uint32_t timer_idx); /** - * @brief Set LEDC fade function. Should call ledc_fade_func_install() before calling this function. + * @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 speed_mode, high-speed mode and low-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] @@ -334,12 +396,17 @@ esp_err_t ledc_bind_channel_timer(ledc_mode_t speed_mode, uint32_t channel, uint * - 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, int scale, int cycle_num); +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. Should call ledc_fade_func_install() before calling this function. + * @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 speed_mode, high-speed mode and low-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))) @@ -354,8 +421,7 @@ esp_err_t ledc_set_fade_with_step(ledc_mode_t speed_mode, ledc_channel_t channel 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. - * + * @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. * @@ -373,18 +439,70 @@ void ledc_fade_func_uninstall(); /** * @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 speed_mode, high-speed mode and low-speed mode * @param channel LEDC channel number - * @param wait_done Whether to block until fading done. + * @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 wait_done); +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 speed_mode, high-speed mode and low-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 speed_mode, high-speed mode and low-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 speed_mode, high-speed mode and low-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/include/driver/driver/mcpwm.h b/tools/sdk/include/driver/driver/mcpwm.h index 2a4433fce40..301ca41926b 100644 --- a/tools/sdk/include/driver/driver/mcpwm.h +++ b/tools/sdk/include/driver/driver/mcpwm.h @@ -1,709 +1,710 @@ -// 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_MCPWM_H_ -#define _DRIVER_MCPWM_H_ - -#include "esp_err.h" -#include "soc/soc.h" -#include "driver/gpio.h" -#include "driver/periph_ctrl.h" -#include "esp_intr.h" -#include "esp_intr_alloc.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief IO signals for 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 pin to capture hall sell signal to measure time - */ -typedef enum { - MCPWM0A = 0, /*!> 9) & 0xf) @@ -121,6 +132,13 @@ #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) @@ -143,16 +161,19 @@ /* 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) -#define EXT_CSD_CARD_TYPE_F_52M (1 << 1) -#define EXT_CSD_CARD_TYPE_F_52M_1_8V (1 << 2) -#define EXT_CSD_CARD_TYPE_F_52M_1_2V (1 << 3) +#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 */ @@ -364,4 +385,82 @@ static inline uint32_t MMC_RSP_BITS(uint32_t *src, int start, int len) 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 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 SD_IO_CISTPL_NULL 0x00 +#define SD_IO_CISTPL_VERS_1 0x15 +#define SD_IO_CISTPL_MANFID 0x20 +#define SD_IO_CISTPL_FUNCID 0x21 +#define SD_IO_CISTPL_FUNCE 0x22 +#define SD_IO_CISTPL_END 0xff + +/* CISTPL_FUNCID codes */ +#define TPLFID_FUNCTION_SDIO 0x0c + +/* 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/include/driver/driver/sdmmc_host.h b/tools/sdk/include/driver/driver/sdmmc_host.h index c298889ed3c..4d94d03c7cd 100644 --- a/tools/sdk/include/driver/driver/sdmmc_host.h +++ b/tools/sdk/include/driver/driver/sdmmc_host.h @@ -33,16 +33,22 @@ extern "C" { * Uses SDMMC peripheral, with 4-bit mode enabled, and max frequency set to 20MHz */ #define SDMMC_HOST_DEFAULT() {\ - .flags = SDMMC_HOST_FLAG_4BIT, \ + .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, \ } @@ -53,6 +59,12 @@ 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_t) -1) ///< indicates that card detect line is not used @@ -66,6 +78,7 @@ typedef struct { .gpio_cd = SDMMC_SLOT_NO_CD, \ .gpio_wp = SDMMC_SLOT_NO_WP, \ .width = SDMMC_SLOT_WIDTH_DEFAULT, \ + .flags = 0, \ } /** @@ -141,6 +154,16 @@ size_t sdmmc_host_get_slot_width(int slot); */ 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 * @@ -166,6 +189,26 @@ esp_err_t sdmmc_host_set_card_clk(int slot, uint32_t freq_khz); */ 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 * @@ -177,6 +220,23 @@ esp_err_t sdmmc_host_do_transaction(int slot, sdmmc_command_t* cmdinfo); */ esp_err_t sdmmc_host_deinit(); +/** + * @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 diff --git a/tools/sdk/include/driver/driver/sdmmc_types.h b/tools/sdk/include/driver/driver/sdmmc_types.h index cece4174ef7..369a9210f8b 100644 --- a/tools/sdk/include/driver/driver/sdmmc_types.h +++ b/tools/sdk/include/driver/driver/sdmmc_types.h @@ -21,6 +21,7 @@ #include #include #include "esp_err.h" +#include "freertos/FreeRTOS.h" /** * Decoded values from SD card Card Specific Data register @@ -55,6 +56,13 @@ typedef struct { 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 */ @@ -78,6 +86,7 @@ typedef struct { 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 @@ -101,6 +110,9 @@ typedef struct { #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; @@ -117,18 +129,24 @@ typedef struct { #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 */ 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 */ esp_err_t (*deinit)(void); /*!< host function to deinitialize the driver */ + 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; @@ -141,10 +159,17 @@ typedef struct { sdmmc_cid_t cid; /*!< decoded CID (Card IDentification) register value */ 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/include/driver/driver/sdspi_host.h b/tools/sdk/include/driver/driver/sdspi_host.h index 54eba081e90..1b3b67017e1 100644 --- a/tools/sdk/include/driver/driver/sdspi_host.h +++ b/tools/sdk/include/driver/driver/sdspi_host.h @@ -40,9 +40,13 @@ extern "C" { .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 = &sdspi_host_deinit, \ + .io_int_enable = NULL, \ + .io_int_wait = NULL, \ .command_timeout_ms = 0, \ } @@ -70,8 +74,8 @@ typedef struct { .gpio_mosi = GPIO_NUM_15, \ .gpio_sck = GPIO_NUM_14, \ .gpio_cs = GPIO_NUM_13, \ - .gpio_cd = SDMMC_SLOT_NO_CD, \ - .gpio_wp = SDMMC_SLOT_NO_WP, \ + .gpio_cd = SDSPI_SLOT_NO_CD, \ + .gpio_wp = SDSPI_SLOT_NO_WP, \ .dma_channel = 1 \ } diff --git a/tools/sdk/include/driver/driver/spi_common.h b/tools/sdk/include/driver/driver/spi_common.h index 6adcc06a91d..b3a92613616 100644 --- a/tools/sdk/include/driver/driver/spi_common.h +++ b/tools/sdk/include/driver/driver/spi_common.h @@ -1,4 +1,4 @@ -// Copyright 2010-2017 Espressif Systems (Shanghai) PTE LTD +// 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. @@ -19,9 +19,9 @@ #include #include #include "esp_err.h" -#include "soc/spi_struct.h" #include "rom/lldesc.h" - +#include "soc/spi_periph.h" +#include "sdkconfig.h" #ifdef __cplusplus extern "C" @@ -32,6 +32,34 @@ extern "C" //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)) /** * @brief Enum with the three SPI peripherals that are software-accessible in it @@ -46,7 +74,7 @@ typedef enum { * @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 + * 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. @@ -58,6 +86,12 @@ typedef struct { 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; @@ -81,57 +115,89 @@ bool spicommon_periph_free(spi_host_device_t host); /** * @brief Try to claim a SPI DMA channel - * + * * Call this if your driver wants to use SPI with a DMA channnel. - * + * * @param dma_chan channel to claim - * + * * @return True if success; false otherwise. */ bool spicommon_dma_chan_claim(int dma_chan); /** * @brief Return the SPI DMA channel so other driver can claim it, or just to power down DMA. - * + * * @param dma_chan channel to return - * + * * @return True if success; false otherwise. */ bool spicommon_dma_chan_free(int dma_chan); -#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_QUAD (1<<1) ///< Also initialize WP/HD pins, if specified +#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_NATIVE_PINS (1<<1) ///< Check using iomux pins. Or indicates the pins are configured through the IO mux rather than GPIO matrix. +#define SPICOMMON_BUSFLAG_SCLK (1<<2) ///< Check existing of SCLK pin. Or indicates CLK line initialized. +#define SPICOMMON_BUSFLAG_MISO (1<<3) ///< Check existing of MISO pin. Or indicates MISO line initialized. +#define SPICOMMON_BUSFLAG_MOSI (1<<4) ///< Check existing of MOSI pin. Or indicates CLK line initialized. +#define SPICOMMON_BUSFLAG_DUAL (1<<5) ///< Check MOSI and MISO pins can output. Or indicates bus able to work under DIO mode. +#define SPICOMMON_BUSFLAG_WPHD (1<<6) ///< 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. /** * @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 + * the arguments. Depending on the IO-pads requested, the routing is done either using the * IO_mux or using the GPIO matrix. * * @param host SPI peripheral to be routed * @param bus_config Pointer to a spi_bus_config struct detailing the GPIO pins * @param dma_chan DMA-channel (1 or 2) to use, or 0 for no DMA. - * @param flags Combination of SPICOMMON_BUSFLAG_* flags - * @param[out] is_native A value of 'true' will be written to this address if the GPIOs can be - * routed using the IO_mux, 'false' if the GPIO matrix is used. - * @return + * @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_NATIVE_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_NATIVE_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, int dma_chan, int flags, bool *is_native); +esp_err_t spicommon_bus_initialize_io(spi_host_device_t host, const spi_bus_config_t *bus_config, int dma_chan, uint32_t flags, uint32_t *flags_o); /** * @brief Free the IO used by a SPI peripheral + * @deprecated Use spicommon_bus_free_io_cfg instead. * * @param host SPI peripheral to be freed - * @return + * + * @return * - ESP_ERR_INVALID_ARG if parameter is invalid * - ESP_OK on success */ +esp_err_t spicommon_bus_free_io(spi_host_device_t host) __attribute__((deprecated)); -esp_err_t spicommon_bus_free_io(spi_host_device_t host); +/** + * @brief Free the IO used by a SPI peripheral + * + * @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 @@ -148,12 +214,19 @@ void spicommon_cs_initialize(spi_host_device_t host, int cs_io_num, int cs_num, /** * @brief Free a chip select line + * @deprecated Use spicommon_cs_io, which inputs the gpio num rather than the cs id instead. * * @param host SPI peripheral * @param cs_num CS id to free */ -void spicommon_cs_free(spi_host_device_t host, int cs_num); +void spicommon_cs_free(spi_host_device_t host, int cs_num) __attribute__((deprecated)); +/** + * @brief Free a chip select line + * + * @param cs_gpio_num CS gpio num to free + */ +void spicommon_cs_free_io(int cs_gpio_num); /** * @brief Setup a DMA link chain @@ -201,10 +274,10 @@ typedef void(*dmaworkaround_cb_t)(void *arg); * @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 + * 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 diff --git a/tools/sdk/include/driver/driver/spi_master.h b/tools/sdk/include/driver/driver/spi_master.h index 613b8cf7412..46085d6251b 100644 --- a/tools/sdk/include/driver/driver/spi_master.h +++ b/tools/sdk/include/driver/driver/spi_master.h @@ -1,4 +1,4 @@ -// Copyright 2010-2016 Espressif Systems (Shanghai) PTE LTD +// 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. @@ -22,6 +22,19 @@ #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" @@ -35,12 +48,12 @@ extern "C" #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 native 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. - * However in full-duplex mode, dummy bits are not allowed to use and no way to prevent reading data from being 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) +/** 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) typedef struct spi_transaction_t spi_transaction_t; @@ -57,12 +70,35 @@ typedef struct { uint8_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. uint8_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, in Hz + 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. - transaction_cb_t post_cb; ///< Callback to be called after a transmission has completed. This callback is called within interrupt context. + 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; @@ -79,12 +115,18 @@ typedef struct { */ 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). + 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. @@ -119,14 +161,14 @@ typedef struct spi_device_t* spi_device_handle_t; ///< Handle for a device on a * @param host 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 Either channel 1 or 2, or 0 in the case when no DMA is required. Selecting a DMA channel - * for a SPI bus allows transfers on the bus to have sizes only limited by the amount of + * for a SPI bus allows transfers on the bus to have sizes only limited by the amount of * internal memory. Selecting no DMA channel (by passing the value 0) limits the amount of * bytes transfered to a maximum of 32. * - * @warning If a DMA channel is selected, any transmit and receive buffer used should be allocated in + * @warning If a DMA channel is selected, any transmit and receive buffer used should be allocated in * DMA-capable memory. * - * @return + * @return * - ESP_ERR_INVALID_ARG if configuration is invalid * - ESP_ERR_INVALID_STATE if host already is in use * - ESP_ERR_NO_MEM if out of memory @@ -140,7 +182,7 @@ esp_err_t spi_bus_initialize(spi_host_device_t host, const spi_bus_config_t *bus * @warning In order for this to succeed, all devices have to be removed first. * * @param host SPI peripheral to free - * @return + * @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 @@ -160,12 +202,12 @@ esp_err_t spi_bus_free(spi_host_device_t host); * @param host 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 + * @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, const spi_device_interface_config_t *dev_config, spi_device_handle_t *handle); @@ -173,7 +215,7 @@ esp_err_t spi_bus_add_device(spi_host_device_t host, const spi_device_interface_ * @brief Remove a device from the SPI bus * * @param handle Device handle to free - * @return + * @return * - ESP_ERR_INVALID_ARG if parameter is invalid * - ESP_ERR_INVALID_STATE if device already is freed * - ESP_OK on success @@ -182,7 +224,10 @@ esp_err_t spi_bus_remove_device(spi_device_handle_t handle); /** - * @brief Queue a SPI transaction for execution + * @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 @@ -192,26 +237,27 @@ esp_err_t spi_bus_remove_device(spi_device_handle_t handle); * - 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 + * @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 (queued earlier with - * spi_device_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 + * 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 + * @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 + * @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 @@ -220,20 +266,107 @@ esp_err_t spi_device_get_trans_result(spi_device_handle_t handle, spi_transactio /** - * @brief Do a SPI transaction + * @brief Send a SPI transaction, wait for it to complete, and return the result * - * Essentially does the same as spi_device_queue_trans followed by spi_device_get_trans_result. Do - * not use this when there is still a transaction queued that hasn't been finalized - * using spi_device_get_trans_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 + * @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. * @@ -245,6 +378,32 @@ esp_err_t spi_device_transmit(spi_device_handle_t handle, spi_transaction_t *tra */ int spi_cal_clock(int fapb, int hz, int duty_cycle, uint32_t* reg_o); +/** + * @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 } diff --git a/tools/sdk/include/driver/driver/spi_slave.h b/tools/sdk/include/driver/driver/spi_slave.h index 1d5ea340292..546f3b67336 100644 --- a/tools/sdk/include/driver/driver/spi_slave.h +++ b/tools/sdk/include/driver/driver/spi_slave.h @@ -1,4 +1,4 @@ -// Copyright 2010-2017 Espressif Systems (Shanghai) PTE LTD +// 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. @@ -44,8 +44,26 @@ typedef struct { 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 (0-3) - slave_transaction_cb_t post_setup_cb; ///< Callback called after the SPI registers are loaded with new data - slave_transaction_cb_t post_trans_cb; ///< Callback called after a transaction is done + 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; /** diff --git a/tools/sdk/include/driver/driver/touch_pad.h b/tools/sdk/include/driver/driver/touch_pad.h index 9d14fe4e712..21e2e2ec7c4 100644 --- a/tools/sdk/include/driver/driver/touch_pad.h +++ b/tools/sdk/include/driver/driver/touch_pad.h @@ -103,14 +103,17 @@ typedef enum { typedef intr_handle_t touch_isr_handle_t; #define TOUCH_PAD_SLEEP_CYCLE_DEFAULT (0x1000) /*! +#include +#include +#include +#include + +typedef float fptp_t; +typedef uint8_t uc_t; + +typedef enum +{ + DL_SUCCESS = 0, + DL_FAIL = 1, +} dl_error_type; + +typedef enum +{ + PADDING_VALID = 0, + PADDING_SAME = 1, +} dl_padding_type; + +/* + * Matrix for 3d + * @Warning: the sequence of variables is fixed, cannot be modified, otherwise there will be errors in esp_dsp_dot_float + */ +typedef struct +{ + int w; /*!< Width */ + int h; /*!< Height */ + int c; /*!< Channel */ + int n; /*!< Number of filter, input and output must be 1 */ + int stride; /*!< Step between lines */ + fptp_t *item; /*!< Data */ +} dl_matrix3d_t; + +typedef struct +{ + int w; /*!< Width */ + int h; /*!< Height */ + int c; /*!< Channel */ + int n; /*!< Number of filter, input and output must be 1 */ + int stride; /*!< Step between lines */ + uc_t *item; /*!< Data */ +} dl_matrix3du_t; + +typedef struct +{ + int stride_x; + int stride_y; + dl_padding_type padding; +} dl_matrix3d_mobilenet_config_t; + +/* + * @brief Allocate a 3D matrix with float items, the access sequence is NHWC + * + * @param n Number of matrix3d, for filters it is out channels, for others it is 1 + * @param w Width of matrix3d + * @param h Height of matrix3d + * @param c Channel of matrix3d + * @return 3d matrix + */ +dl_matrix3d_t *dl_matrix3d_alloc(int n, int w, int h, int c); + +/* + * @brief Allocate a 3D matrix with 8-bits items, the access sequence is NHWC + * + * @param n Number of matrix3d, for filters it is out channels, for others it is 1 + * @param w Width of matrix3d + * @param h Height of matrix3d + * @param c Channel of matrix3d + * @return 3d matrix + */ +dl_matrix3du_t *dl_matrix3du_alloc(int n, int w, int h, int c); + +/* + * @brief Free a matrix3d + * + * @param m matrix3d with float items + */ +void dl_matrix3d_free(dl_matrix3d_t *m); + +/* + * @brief Free a matrix3d + * + * @param m matrix3d with 8-bits items + */ +void dl_matrix3du_free(dl_matrix3du_t *m); + +/* + * @brief Dot product with a vector and matrix + * + * @param out Space to put the result + * @param in input vector + * @param f filter matrix + */ +void dl_matrix3dff_dot_product(dl_matrix3d_t *out, dl_matrix3d_t *in, dl_matrix3d_t *f); + +/** + * @brief Do a softmax operation on a matrix3d + * + * @param in Input matrix3d + */ +void dl_matrix3d_softmax(dl_matrix3d_t *m); + +/** + * @brief Copy a range of float items from an existing matrix to a preallocated matrix + * + * @param dst The destination slice matrix + * @param src The source matrix to slice + * @param x X-offset of the origin of the returned matrix within the sliced matrix + * @param y Y-offset of the origin of the returned matrix within the sliced matrix + * @param w Width of the resulting matrix + * @param h Height of the resulting matrix + */ +void dl_matrix3d_slice_copy(dl_matrix3d_t *dst, + dl_matrix3d_t *src, + int x, + int y, + int w, + int h); + +/** + * @brief Copy a range of 8-bits items from an existing matrix to a preallocated matrix + * + * @param dst The destination slice matrix + * @param src The source matrix to slice + * @param x X-offset of the origin of the returned matrix within the sliced matrix + * @param y Y-offset of the origin of the returned matrix within the sliced matrix + * @param w Width of the resulting matrix + * @param h Height of the resulting matrix + */ +void dl_matrix3du_slice_copy(dl_matrix3du_t *dst, + dl_matrix3du_t *src, + int x, + int y, + int w, + int h); + +/** + * @brief Do a general CNN layer pass, dimension is (number, width, height, channel) + * + * @param in Input matrix3d + * @param filter Weights of the neurons + * @param bias Bias for the CNN layer + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect + * If ESP_PLATFORM is not defined, this value is not used. Default is 0 + * @return The result of CNN layer + */ +dl_matrix3d_t *dl_matrix3d_conv(dl_matrix3d_t *in, + dl_matrix3d_t *filter, + dl_matrix3d_t *bias, + int stride_x, + int stride_y, + int padding, + int mode); + +/** + * @brief Do a general CNN layer pass, dimension is (number, width, height, channel) + * + * @param in Input matrix3d + * @param filter Weights of the neurons + * @param bias Bias for the CNN layer + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect + * If ESP_PLATFORM is not defined, this value is not used. Default is 0 + * @return The result of CNN layer + */ + +/** + * @brief Do a global average pooling layer pass, dimension is (number, width, height, channel) + * + * @param in Input matrix3d + * + * @return The result of global average pooling layer + */ +dl_matrix3d_t *dl_matrix3d_global_pool(dl_matrix3d_t *in); + +/** + * @brief Do a batch normalization operation, update the input matrix3d: input = input * scale + offset + * + * @param m Input matrix3d + * @param scale scale matrix3d, scale = gamma/((moving_variance+sigma)^(1/2)) + * @param Offset Offset matrix3d, offset = beta-(moving_mean*gamma/((moving_variance+sigma)^(1/2))) + */ +void dl_matrix3d_batch_normalize(dl_matrix3d_t *m, + dl_matrix3d_t *scale, + dl_matrix3d_t *offset); + +/** + * @brief Add a pair of matrix3d item-by-item: res=in_1+in_2 + * + * @param in_1 First Floating point input matrix3d + * @param in_2 Second Floating point input matrix3d + * + * @return Added data + */ +dl_matrix3d_t *dl_matrix3d_add(dl_matrix3d_t *in_1, dl_matrix3d_t *in_2); + +/** + * @brief Concatenate the channels of two matrix3ds into a new matrix3d + * + * @param in_1 First Floating point input matrix3d + * @param in_2 Second Floating point input matrix3d + * + * @return A newly allocated matrix3d with as avlues in_1|in_2 + */ +dl_matrix3d_t *dl_matrix3d_concat(dl_matrix3d_t *in_1, dl_matrix3d_t *in_2); + +/** + * @brief Concatenate the channels of four matrix3ds into a new matrix3d + * + * @param in_1 First Floating point input matrix3d + * @param in_2 Second Floating point input matrix3d + * @param in_3 Third Floating point input matrix3d + * @param in_4 Fourth Floating point input matrix3d + * + * @return A newly allocated matrix3d with as avlues in_1|in_2|in_3|in_4 + */ +dl_matrix3d_t *dl_matrix3d_concat_4(dl_matrix3d_t *in_1, + dl_matrix3d_t *in_2, + dl_matrix3d_t *in_3, + dl_matrix3d_t *in_4); + +/** + * @brief Concatenate the channels of eight matrix3ds into a new matrix3d + * + * @param in_1 First Floating point input matrix3d + * @param in_2 Second Floating point input matrix3d + * @param in_3 Third Floating point input matrix3d + * @param in_4 Fourth Floating point input matrix3d + * @param in_5 Fifth Floating point input matrix3d + * @param in_6 Sixth Floating point input matrix3d + * @param in_7 Seventh Floating point input matrix3d + * @param in_8 eighth Floating point input matrix3d + * + * @return A newly allocated matrix3d with as avlues in_1|in_2|in_3|in_4|in_5|in_6|in_7|in_8 + */ +dl_matrix3d_t *dl_matrix3d_concat_8(dl_matrix3d_t *in_1, + dl_matrix3d_t *in_2, + dl_matrix3d_t *in_3, + dl_matrix3d_t *in_4, + dl_matrix3d_t *in_5, + dl_matrix3d_t *in_6, + dl_matrix3d_t *in_7, + dl_matrix3d_t *in_8); + +/** + * @brief Do a mobilefacenet block forward, dimension is (number, width, height, channel) + * + * @param in Input matrix3d + * @param pw Weights of the pointwise conv layer + * @param pw_bn_scale The scale params of the batch_normalize layer after the pointwise conv layer + * @param pw_bn_offset The offset params of the batch_normalize layer after the pointwise conv layer + * @param dw Weights of the depthwise conv layer + * @param dw_bn_scale The scale params of the batch_normalize layer after the depthwise conv layer + * @param dw_bn_offset The offset params of the batch_normalize layer after the depthwise conv layer + * @param pw_linear Weights of the pointwise linear conv layer + * @param pw_linear_bn_scale The scale params of the batch_normalize layer after the pointwise linear conv layer + * @param pw_linear_bn_offset The offset params of the batch_normalize layer after the pointwise linear conv layer + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect + * If ESP_PLATFORM is not defined, this value is not used. Default is 0 + * @return The result of a mobilefacenet block + */ +dl_matrix3d_t *dl_matrix3d_mobilefaceblock(dl_matrix3d_t *in, + dl_matrix3d_t *pw, + dl_matrix3d_t *pw_bn_scale, + dl_matrix3d_t *pw_bn_offset, + dl_matrix3d_t *dw, + dl_matrix3d_t *dw_bn_scale, + dl_matrix3d_t *dw_bn_offset, + dl_matrix3d_t *pw_linear, + dl_matrix3d_t *pw_linear_bn_scale, + dl_matrix3d_t *pw_linear_bn_offset, + int stride_x, + int stride_y, + int padding, + int mode, + int shortcut); + +/** + * @brief Do a mobilefacenet block forward with 1x1 split conv, dimension is (number, width, height, channel) + * + * @param in Input matrix3d + * @param pw_1 Weights of the pointwise conv layer 1 + * @param pw_2 Weights of the pointwise conv layer 2 + * @param pw_bn_scale The scale params of the batch_normalize layer after the pointwise conv layer + * @param pw_bn_offset The offset params of the batch_normalize layer after the pointwise conv layer + * @param dw Weights of the depthwise conv layer + * @param dw_bn_scale The scale params of the batch_normalize layer after the depthwise conv layer + * @param dw_bn_offset The offset params of the batch_normalize layer after the depthwise conv layer + * @param pw_linear_1 Weights of the pointwise linear conv layer 1 + * @param pw_linear_2 Weights of the pointwise linear conv layer 2 + * @param pw_linear_bn_scale The scale params of the batch_normalize layer after the pointwise linear conv layer + * @param pw_linear_bn_offset The offset params of the batch_normalize layer after the pointwise linear conv layer + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect + * If ESP_PLATFORM is not defined, this value is not used. Default is 0 + * @return The result of a mobilefacenet block + */ +dl_matrix3d_t *dl_matrix3d_mobilefaceblock_split(dl_matrix3d_t *in, + dl_matrix3d_t *pw_1, + dl_matrix3d_t *pw_2, + dl_matrix3d_t *pw_bn_scale, + dl_matrix3d_t *pw_bn_offset, + dl_matrix3d_t *dw, + dl_matrix3d_t *dw_bn_scale, + dl_matrix3d_t *dw_bn_offset, + dl_matrix3d_t *pw_linear_1, + dl_matrix3d_t *pw_linear_2, + dl_matrix3d_t *pw_linear_bn_scale, + dl_matrix3d_t *pw_linear_bn_offset, + int stride_x, + int stride_y, + int padding, + int mode, + int shortcut); + +void dl_matrix3d_init_bias(dl_matrix3d_t *out, dl_matrix3d_t *bias); + +void dl_matrix3d_multiply(dl_matrix3d_t *out, dl_matrix3d_t *in1, dl_matrix3d_t *in2); + +// +// Activation +// + +/** + * @brief Do a standard relu operation, update the input matrix3d + * + * @param m Floating point input matrix3d + */ +void dl_matrix3d_relu(dl_matrix3d_t *m); + +/** + * @brief Do a relu (Rectifier Linear Unit) operation, update the input matrix3d + * + * @param in Floating point input matrix3d + * @param clip If value is higher than this, it will be clipped to this value + */ +void dl_matrix3d_relu_clip(dl_matrix3d_t *m, fptp_t clip); + +/** + * @brief Do a Prelu (Rectifier Linear Unit) operation, update the input matrix3d + * + * @param in Floating point input matrix3d + * @param alpha If value is less than zero, it will be updated by multiplying this factor + */ +void dl_matrix3d_p_relu(dl_matrix3d_t *in, dl_matrix3d_t *alpha); + +/** + * @brief Do a leaky relu (Rectifier Linear Unit) operation, update the input matrix3d + * + * @param in Floating point input matrix3d + * @param alpha If value is less than zero, it will be updated by multiplying this factor + */ +void dl_matrix3d_leaky_relu(dl_matrix3d_t *m, fptp_t alpha); + +// +// Conv 1x1 +// +void dl_matrix3dff_conv_1x1(dl_matrix3d_t *out, + dl_matrix3d_t *in, + dl_matrix3d_t *filter); + +void dl_matrix3dff_conv_1x1_with_bias(dl_matrix3d_t *out, + dl_matrix3d_t *in, + dl_matrix3d_t *filter, + dl_matrix3d_t *bias); + +void dl_matrix3duf_conv_1x1(dl_matrix3d_t *out, + dl_matrix3du_t *in, + dl_matrix3d_t *filter); + +void dl_matrix3duf_conv_1x1_with_bias(dl_matrix3d_t *out, + dl_matrix3du_t *in, + dl_matrix3d_t *filter, + dl_matrix3d_t *bias); + +// +// Conv 3x3 +// +void dl_matrix3dff_conv_3x3_op(dl_matrix3d_t *out, + dl_matrix3d_t *in, + dl_matrix3d_t *f, + int step_x, + int step_y); + +dl_matrix3d_t *dl_matrix3dff_conv_3x3(dl_matrix3d_t *in, + dl_matrix3d_t *filter, + dl_matrix3d_t *bias, + int stride_x, + int stride_y, + dl_padding_type padding); + +// +// Conv Common +// + +dl_matrix3d_t *dl_matrix3duf_conv_common(dl_matrix3du_t *in, + dl_matrix3d_t *filter, + dl_matrix3d_t *bias, + int stride_x, + int stride_y, + dl_padding_type padding); + +// +// Depthwise 3x3 +// + +dl_matrix3d_t *dl_matrix3dff_depthwise_conv_3x3(dl_matrix3d_t *in, + dl_matrix3d_t *filter, + int stride_x, + int stride_y, + int padding); + +dl_matrix3d_t *dl_matrix3duf_depthwise_conv_3x3(dl_matrix3du_t *in, + dl_matrix3d_t *filter, + int stride_x, + int stride_y, + int padding); + +void dl_matrix3dff_depthwise_conv_3x3_op(dl_matrix3d_t *out, + dl_matrix3d_t *in, + dl_matrix3d_t *f, + int step_x, + int step_y); + +// +// Depthwise Common +// + +/** + * @brief Do a depthwise CNN layer pass, dimension is (number, width, height, channel) + * + * @param in Input matrix3d + * @param filter Weights of the neurons + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect + * If ESP_PLATFORM is not defined, this value is not used. Default is 0 + * @return The result of depthwise CNN layer + */ +dl_matrix3d_t *dl_matrix3dff_depthwise_conv_common(dl_matrix3d_t *in, + dl_matrix3d_t *filter, + int stride_x, + int stride_y, + dl_padding_type padding); + +// +// FC +// +/** + * @brief Do a general fully connected layer pass, dimension is (number, width, height, channel) + * + * @param in Input matrix3d, size is (1, w, 1, 1) + * @param filter Weights of the neurons, size is (1, w, h, 1) + * @param bias Bias for the fc layer, size is (1, 1, 1, h) + * @return The result of fc layer, size is (1, 1, 1, h) + */ +void dl_matrix3dff_fc(dl_matrix3d_t *out, + dl_matrix3d_t *in, + dl_matrix3d_t *filter); + +void dl_matrix3dff_fc_with_bias(dl_matrix3d_t *out, + dl_matrix3d_t *in, + dl_matrix3d_t *filter, + dl_matrix3d_t *bias); + +// +// Mobilenet +// + +/** + * @brief Do a mobilenet block forward, dimension is (number, width, height, channel) + * + * @param in Input matrix3d + * @param filter Weights of the neurons + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect + * If ESP_PLATFORM is not defined, this value is not used. Default is 0 + * @return The result of depthwise CNN layer + */ +dl_matrix3d_t *dl_matrix3dff_mobilenet(dl_matrix3d_t *in, + dl_matrix3d_t *dilate_filter, + dl_matrix3d_t *dilate_prelu, + dl_matrix3d_t *depthwise_filter, + dl_matrix3d_t *depthwise_prelu, + dl_matrix3d_t *compress_filter, + dl_matrix3d_t *bias, + dl_matrix3d_mobilenet_config_t config); + +/** + * @brief Do a mobilenet block forward, dimension is (number, width, height, channel) + * + * @param in Input matrix3du + * @param filter Weights of the neurons + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect + * If ESP_PLATFORM is not defined, this value is not used. Default is 0 + * @return The result of depthwise CNN layer + */ +dl_matrix3d_t *dl_matrix3duf_mobilenet(dl_matrix3du_t *in, + dl_matrix3d_t *dilate_filter, + dl_matrix3d_t *dilate_prelu, + dl_matrix3d_t *depthwise_filter, + dl_matrix3d_t *depthwise_prelu, + dl_matrix3d_t *compress_filter, + dl_matrix3d_t *bias, + dl_matrix3d_mobilenet_config_t config); diff --git a/tools/sdk/include/esp-face/dl_lib_matrix3dq.h b/tools/sdk/include/esp-face/dl_lib_matrix3dq.h new file mode 100644 index 00000000000..57e5e92c22e --- /dev/null +++ b/tools/sdk/include/esp-face/dl_lib_matrix3dq.h @@ -0,0 +1,779 @@ +#pragma once +#include "dl_lib_matrix3d.h" + +typedef int16_t qtp_t; + +/** + * Matrix for input, filter, and output + * @Warning: the sequence of variables is fixed, cannot be modified, otherwise there will be errors in + * some handwrite xtensa instruction functions + */ +typedef struct +{ + /******* fix start *******/ + int w; /*!< Width */ + int h; /*!< Height */ + int c; /*!< Channel */ + int n; /*!< Number of filter, input and output must be 1 */ + int stride; /*!< Step between lines */ + int exponent; /*!< Exponent for quantization */ + qtp_t *item; /*!< Data */ + /******* fix end *******/ +} dl_matrix3dq_t; + +#ifndef DL_QTP_SHIFT +#define DL_QTP_SHIFT 15 +#define DL_ITMQ(m, x, y) m->itemq[(y) + (x)*m->stride] +#define DL_QTP_RANGE ((1 << DL_QTP_SHIFT) - 1) +#define DL_QTP_MAX 32767 +#define DL_QTP_MIN -32768 + +#define DL_QTP_EXP_NA 255 //non-applicable exponent because matrix is null + +#define DL_SHIFT_AUTO 32 +#endif + +/** + * Implementation of matrix relative operations + */ +typedef enum +{ + DL_C_IMPL = 0, /*!< ANSI C */ + DL_XTENSA_IMPL = 1 /*!< Handwrite xtensa instruction */ +} dl_conv_mode; + + +/** + * Configuration of mobilenet operation + */ +typedef struct +{ + int stride_x; /*!< Strides of width */ + int stride_y; /*!< Strides of height */ + dl_padding_type padding; /*!< Padding type */ + dl_conv_mode mode; /*!< Implementation mode */ + int dilate_exponent; /*!< Exponent of dilation filter */ + int depthwise_exponent; /*!< Exponent of depthwise filter */ + int compress_exponent; /*!< Exponent of compress filter */ +} dl_matrix3dq_mobilenet_config_t; + +// +// Utility +// + +/* + * @brief Allocate a 3d quantised matrix + * + * @param n Number of filters, for input and output, should be 1 + * @param w Width of matrix + * @param h Height of matrix + * @param c Channel of matrix + * @param e Exponent of matrix data + * @return 3d quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dq_alloc(int n, int w, int h, int c, int e); + +/* + * @brief Free a 3d quantized matrix + * + * @param m 3d quantised matrix + */ +void dl_matrix3dq_free(dl_matrix3dq_t *m); + +/** + * @brief Copy a range of items from an existing matrix to a preallocated matrix + * + * @param dst The resulting slice matrix + * @param src Old matrix to slice. + * @param x X-offset of the origin of the returned matrix within the sliced matrix + * @param y Y-offset of the origin of the returned matrix within the sliced matrix + * @param w Width of the resulting matrix + * @param h Height of the resulting matrix + */ +void dl_matrix3dq_slice_copy(dl_matrix3dq_t *dst, dl_matrix3dq_t *src, int x, int y, int w, int h); + +/** + * @brief Transform a fixed point matrix to a float point matrix + * + * @param m Quantized matrix + * @return Float point matrix + */ +dl_matrix3d_t *dl_matrix3d_from_matrixq(dl_matrix3dq_t *m); + +/** + * @brief Transform a float point matrix to a fixed point matrix with pre-defined exponent + * + * @param m Float point matrix + * @param exponent Exponent for resulting matrix + * @return Fixed point matrix + */ +dl_matrix3dq_t *dl_matrixq_from_matrix3d_qmf(dl_matrix3d_t *m, int exponent); + +/** + * @brief Transform a float point matrix to a fixed point matrix. The exponent is defined by the distribution of the input matrix. + * + * @param m Float point matrix + * @return Fixed point matrix + */ +dl_matrix3dq_t *dl_matrixq_from_matrix3d(dl_matrix3d_t *m); + +qtp_t dl_matrix3dq_quant_range_exceeded_checking(int64_t value, char *location); + +/** + * @brief Reform a quantized matrix with exponent + * + * @param out Preallocated resulting matrix + * @param in Input matrix + * @param exponent Exponent for resulting matrix + */ +void dl_matrix3dq_shift_exponent(dl_matrix3dq_t *out, dl_matrix3dq_t *in, int exponent); + +/** + * @brief Do batch normalization for a quantized matrix + * + * @param m Input and output quantized matrix, data will be updated + * @param scale Scale of batch-norm + * @param offset Offset of batch-norm + */ +void dl_matrix3dq_batch_normalize(dl_matrix3dq_t *m, dl_matrix3dq_t *scale, dl_matrix3dq_t *offset); + +/** + * @brief Add two quantized matrix with a pre-defined exponent + * + * @param in_1 Adder 1 + * @param in_2 Adder 2 + * @param exponent Exponent for resulting matrix + * @return Result of accumulation of two matrix + */ +dl_matrix3dq_t *dl_matrix3dq_add(dl_matrix3dq_t *in_1, dl_matrix3dq_t *in_2, int exponent); + +// +// Activation +// +/** + * @brief Do relu for a quantized matrix + * + * @param in Input and output quantized matrix, data will be updated + */ +void dl_matrix3dq_relu(dl_matrix3dq_t *in); + +/** + * @brief Do relu with clips for a quantized matrix + * + * @param in Input and output quantized matrix, data will be updated + * @param clip Float point value to limit the maximum data + */ +void dl_matrix3dq_relu_clip(dl_matrix3dq_t *in, fptp_t clip); + +/** + * @brief Do leaky relu for a quantized matrix + * + * @param in Input and output quantized matrix, data will be updated + * @param alpha Float point value to multiply for those less than zero + * @param clip Float point value to limit the maximum data + */ +void dl_matrix3dq_leaky_relu(dl_matrix3dq_t *in, fptp_t alpha, fptp_t clip); + +/** + * @brief Do prelu for a quantized matrix + * + * @param in Input and output quantized matrix, data will be updated + * @param alpha Quantized matrix to multiply for those less than zero + */ +void dl_matrix3dq_p_relu(dl_matrix3dq_t *in, dl_matrix3dq_t *alpha); + +// +// Concat +// +/** + * @brief Concatenate two quantized matrix in channel + * + * @param in_1 Quantized matrix to be concatenated + * @param in_2 Quantized matrix to be concatenated + * @return Quantized matrix with the same width and height of in_1 and in_2, and with the sum of channel number of in_1 and in_2 + */ +dl_matrix3dq_t *dl_matrix3dq_concat(dl_matrix3dq_t *in_1, + dl_matrix3dq_t *in_2); + +/** + * @brief Concatenate four quantized matrix in channel + * + * @param in_1 Quantized matrix to be concatenated + * @param in_2 Quantized matrix to be concatenated + * @param in_3 Quantized matrix to be concatenated + * @param in_4 Quantized matrix to be concatenated + * @return Quantized matrix with the same width and height of all inputs, and with the sum of channel number of all inputs + */ +dl_matrix3dq_t *dl_matrix3dq_concat_4(dl_matrix3dq_t *in_1, + dl_matrix3dq_t *in_2, + dl_matrix3dq_t *in_3, + dl_matrix3dq_t *in_4); + +/** + * @brief Concatenate four quantized matrix in channel + * + * @param in_1 Quantized matrix to be concatenated + * @param in_2 Quantized matrix to be concatenated + * @param in_3 Quantized matrix to be concatenated + * @param in_4 Quantized matrix to be concatenated + * @param in_5 Quantized matrix to be concatenated + * @param in_6 Quantized matrix to be concatenated + * @param in_7 Quantized matrix to be concatenated + * @param in_8 Quantized matrix to be concatenated + * @return Quantized matrix with the same width and height of all inputs, and with the sum of channel number of all inputs + */ +dl_matrix3dq_t *dl_matrix3dq_concat_8(dl_matrix3dq_t *in_1, + dl_matrix3dq_t *in_2, + dl_matrix3dq_t *in_3, + dl_matrix3dq_t *in_4, + dl_matrix3dq_t *in_5, + dl_matrix3dq_t *in_6, + dl_matrix3dq_t *in_7, + dl_matrix3dq_t *in_8); + +// +// Conv 1x1 +// +/** + * @brief Do 1x1 convolution with a quantized matrix + * + * @param out Preallocated quantized matrix, size (1, w, h, n) + * @param in Input matrix, size (1, w, h, c) + * @param filter 1x1 filter, size (n, 1, 1, c) + * @param mode Implementation mode + */ +void dl_matrix3dqq_conv_1x1(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_conv_mode mode); + +/** + * @brief Do 1x1 convolution with a quantized matrix, with relu activation + * + * @param out Preallocated quantized matrix, size (1, w, h, n) + * @param in Input matrix, size (1, w, h, c) + * @param filter 1x1 filter, size (n, 1, 1, c) + * @param mode Implementation mode + */ +void dl_matrix3dqq_conv_1x1_with_relu(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_conv_mode mode); + +/** + * @brief Do 1x1 convolution with a quantized matrix, with bias adding + * + * @param out Preallocated quantized matrix, size (1, w, h, n) + * @param in Input matrix, size (1, w, h, c) + * @param filter 1x1 filter, size (n, 1, 1, c) + * @param bias Bias, size (1, 1, 1, n) + * @param mode Implementation mode + * @param name Layer name to debug + */ +void dl_matrix3dqq_conv_1x1_with_bias(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *bias, + dl_conv_mode mode, + char *name); + +/** + * @brief Do 1x1 convolution with a quantized matrix, with bias adding and relu activation + * + * @param out Preallocated quantized matrix, size (1, w, h, n) + * @param in Input matrix, size (1, w, h, c) + * @param filter 1x1 filter, size (n, 1, 1, c) + * @param bias Bias, size (1, 1, 1, n) + * @param mode Implementation mode + */ +void dl_matrix3dqq_conv_1x1_with_bias_relu(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *bias, + dl_conv_mode mode); + +void dl_matrix3dqq_conv_1x1_with_prelu(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *prelu, + dl_conv_mode mode); + +/** + * @brief Do 1x1 convolution with an 8-bit fixed point matrix + * + * @param out Preallocated quantized matrix, size (1, w, h, n) + * @param in Input matrix, size (1, w, h, c) + * @param filter 1x1 filter, size (n, 1, 1, c) + * @param mode Implementation mode + */ +void dl_matrix3duq_conv_1x1(dl_matrix3dq_t *out, + dl_matrix3du_t *in, + dl_matrix3dq_t *filter, + dl_conv_mode mode); + +/** + * @brief Do 1x1 convolution with an 8-bit fixed point matrix, with bias adding + * + * @param out Preallocated quantized matrix, size (1, w, h, n) + * @param in Input matrix, size (1, w, h, c) + * @param filter 1x1 filter, size (n, 1, 1, c) + * @param bias Bias, size (1, 1, 1, n) + * @param mode Implementation mode + */ +void dl_matrix3duq_conv_1x1_with_bias(dl_matrix3dq_t *out, + dl_matrix3du_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *bias, + dl_conv_mode mode); + +// +// Conv 3x3 +// +/** + * @brief Do 3x3 convolution basic operation with a quantized matrix + * + * @param out Preallocated quantized matrix + * @param in Input matrix, size (1, w, h, c) + * @param filter 3x3 filter, size (n, 3, 3, c) + * @param stride_x Stride of width + * @param stride_y Stride of height + */ +void dl_matrix3dqq_conv_3x3_op(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + int stride_x, + int stride_y); + +/** + * @brief Do 3x3 convolution with a quantized matrix + * + * @param in Input matrix, size (1, w, h, c) + * @param filter 3x3 filter, size (n, 3, 3, c) + * @param stride_x Stride of width + * @param stride_y Stride of height + * @param padding Padding type, 0: valid, 1: same + * @param exponent Exponent for resulting matrix + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dqq_conv_3x3(dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent); + +/** + * @brief Do 3x3 convolution with a quantized matrix, with bias adding + * + * @param in Input matrix, size (1, w, h, c) + * @param filter 3x3 filter, size (n, 3, 3, c) + * @param bias Bias, size (1, 1, 1, n) + * @param stride_x Stride of width + * @param stride_y Stride of height + * @param padding Padding type, 0: valid, 1: same + * @param exponent Exponent for resulting matrix + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dqq_conv_3x3_with_bias(dl_matrix3dq_t *in, + dl_matrix3dq_t *f, + dl_matrix3dq_t *bias, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent, + int relu); + +dl_matrix3dq_t *dl_matrix3duq_conv_3x3_with_bias(dl_matrix3du_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *bias, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent, + char *name); + +dl_matrix3dq_t *dl_matrix3duq_conv_3x3_with_bias_prelu(dl_matrix3du_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *bias, + dl_matrix3dq_t *prelu, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent, + char *name); + +// +// Conv common +// + +/** + * @brief Do a general convolution layer pass, size is (number, width, height, channel) + * + * @param in Input image + * @param filter Weights of the neurons + * @param bias Bias for the CNN layer. + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect. + * If ESP_PLATFORM is not defined, this value is not used. + * @return The result of CNN layer. + */ +dl_matrix3dq_t *dl_matrix3dqq_conv_common(dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *bias, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent, + dl_conv_mode mode); + +/** + * @brief Do a general convolution layer pass for an 8-bit fixed point matrix, size is (number, width, height, channel) + * + * @param in Input image + * @param filter Weights of the neurons + * @param bias Bias for the CNN layer. + * @param stride_x The step length of the convolution window in x(width) direction + * @param stride_y The step length of the convolution window in y(height) direction + * @param padding One of VALID or SAME + * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect. + * If ESP_PLATFORM is not defined, this value is not used. + * @return The result of CNN layer. + */ +dl_matrix3dq_t *dl_matrix3duq_conv_common(dl_matrix3du_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *bias, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent, + dl_conv_mode mode); + +// +// Depthwise 3x3 +// +/** + * @brief Do 3x3 depthwise convolution with an 8-bit fixed point matrix + * + * @param in Input matrix, size (1, w, h, c) + * @param filter 3x3 filter, size (1, 3, 3, c) + * @param stride_x Stride of width + * @param stride_y Stride of height + * @param padding Padding type, 0: valid, 1: same + * @param exponent Exponent for resulting matrix + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3duq_depthwise_conv_3x3(dl_matrix3du_t *in, + dl_matrix3dq_t *filter, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent); + +/** + * @brief Do 3x3 depthwise convolution with a quantized matrix + * + * @param in Input matrix, size (1, w, h, c) + * @param filter 3x3 filter, size (1, 3, 3, c) + * @param stride_x Stride of width + * @param stride_y Stride of height + * @param padding Padding type, 0: valid, 1: same + * @param exponent Exponent for resulting matrix + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dqq_depthwise_conv_3x3(dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent); + +#if CONFIG_DEVELOPING_CODE +dl_matrix3dq_t *dl_matrix3dqq_depthwise_conv_3x3_2(dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent); + +dl_matrix3dq_t *dl_matrix3dqq_depthwise_conv_3x3_3(dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent); +#endif + +/** + * @brief Do 3x3 depthwise convolution with a quantized matrix, with bias adding + * + * @param in Input matrix, size (1, w, h, c) + * @param filter 3x3 filter, size (1, 3, 3, c) + * @param bias Bias, size (1, 1, 1, c) + * @param stride_x Stride of width + * @param stride_y Stride of height + * @param padding Padding type, 0: valid, 1: same + * @param exponent Exponent for resulting matrix + * @param relu Whether to use relu activation + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dqq_depthwise_conv_3x3_with_bias(dl_matrix3dq_t *in, + dl_matrix3dq_t *f, + dl_matrix3dq_t *bias, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent, + int relu); + +/** + * @brief Do 3x3 depthwise convolution with a quantized matrix, with bias adding and stride 1 + * + * @param in Input matrix, size (1, w, h, c) + * @param filter 3x3 filter, size (1, 3, 3, c) + * @param bias Bias, size (1, 1, 1, n) + * @param padding Padding type, 0: valid, 1: same + * @param exponent Exponent for resulting matrix + * @param relu Whether to use relu activation + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dqq_depthwise_conv_3x3s1_with_bias(dl_matrix3dq_t *in, + dl_matrix3dq_t *f, + dl_matrix3dq_t *bias, + dl_padding_type padding, + int exponent, + int relu); + +dl_matrix3dq_t *dl_matrix3dqq_depthwise_conv_3x3_with_prelu(dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *prelu, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent); + + +// +// Depthwise Common +// +#if CONFIG_DEVELOPING_CODE +dl_matrix3dq_t *dl_matrix3dqq_depthwise_conv_common(dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent, + dl_conv_mode mode); + +dl_matrix3dq_t *dl_matrix3duq_depthwise_conv_common(dl_matrix3du_t *in, + dl_matrix3dq_t *filter, + int stride_x, + int stride_y, + dl_padding_type padding, + int exponent, + dl_conv_mode mode); +#endif + +// +// Dot Product +// + +void dl_matrix3dqq_dot_product(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_conv_mode mode); + +// +// FC +// +/** + * @brief Do fully connected layer forward. + * + * @param out Preallocated resulting matrix, size (1, 1, 1, h) + * @param in Input matrix, size (1, 1, 1, w) + * @param filter Filter matrix, size (1, w, h, 1) + * @param mode Implementation mode + */ +void dl_matrix3dqq_fc(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_conv_mode mode); + +/** + * @brief Do fully connected layer forward, with bias adding + * + * @param out Preallocated resulting matrix, size (1, 1, 1, h) + * @param in Input matrix, size (1, 1, 1, w) + * @param filter Filter matrix, size (1, w, h, 1) + * @param bias Bias matrix, size (1, 1, 1, h) + * @param mode Implementation mode + */ +void dl_matrix3dqq_fc_with_bias(dl_matrix3dq_t *out, + dl_matrix3dq_t *in, + dl_matrix3dq_t *filter, + dl_matrix3dq_t *bias, + dl_conv_mode mode, + char *name); + +// +// Mobilefaceblock +// +/** + * @brief Do mobilefacenet process with splited pointwise 1x1 convolution, the process sequence is 1x1 pointwise->bn->relu->3x3 depthwise->bn->relu->1x1 pointwise->bn + * + * @param in Input matrix, size (1, w, h, c) + * @param pw_1 Pointwise 1x1 filter, size (n1/2, 1, 1, c) + * @param pw_2 Pointwise 1x1 filter, size (n1/2, 1, 1, c) + * @param pw_bias Pointwise bias, size (1, 1, 1, n1) + * @param dw Depthwise 3x3 filter, size (1, 3, 3, n1) + * @param dw_bias Depthwise bias, size (1, 1, 1, n1) + * @param pw_linear_1 Pointwise 1x1 filter, size (n2/2, 1, 1, n1) + * @param pw_linear_2 Pointwise 1x1 filter, size (n2/2, 1, 1, n1) + * @param pw_linear_bias Pointwise bias, size (1, 1, 1, n2) + * @param pw_exponent Exponent for pointwise resulting matrix + * @param dw_exponent Exponent for depthwise resulting matrix + * @param pw_linear_exponent Exponent for pointwise resulting matrix + * @param stride_x Stride of width + * @param stride_y Stride of height + * @param padding Padding type, 0: valid, 1: same + * @param mode Implementation mode + * @param shortcut Whether has a shortcut at pointwise linear + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dqq_mobilefaceblock_split(dl_matrix3dq_t *in, + dl_matrix3dq_t *pw_1, + dl_matrix3dq_t *pw_2, + dl_matrix3dq_t *pw_bias, + dl_matrix3dq_t *dw, + dl_matrix3dq_t *dw_bias, + dl_matrix3dq_t *pw_linear_1, + dl_matrix3dq_t *pw_linear_2, + dl_matrix3dq_t *pw_linear_bias, + int pw_exponent, + int dw_exponent, + int pw_linear_exponent, + int stride_x, + int stride_y, + dl_padding_type padding, + dl_conv_mode mode, + int shortcut); + +/** + * @brief Do mobilefacenet process, the process sequence is 1x1 pointwise->bn->relu->3x3 depthwise->bn->relu->1x1 pointwise->bn + * + * @param in Input matrix, size (1, w, h, c) + * @param pw Pointwise 1x1 filter, size (n1, 1, 1, c) + * @param pw_bias Pointwise bias, size (1, 1, 1, n1) + * @param dw Depthwise 3x3 filter, size (1, 3, 3, n1) + * @param dw_bias Depthwise bias, size (1, 1, 1, n1) + * @param pw_linear Pointwise 1x1 filter, size (n2, 1, 1, n1) + * @param pw_linear_bias Pointwise bias, size (1, 1, 1, n2) + * @param pw_exponent Exponent for pointwise resulting matrix + * @param dw_exponent Exponent for depthwise resulting matrix + * @param pw_linear_exponent Exponent for pointwise resulting matrix + * @param stride_x Stride of width + * @param stride_y Stride of height + * @param padding Padding type, 0: valid, 1: same + * @param mode Implementation mode + * @param shortcut Whether has a shortcut at pointwise linear + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dqq_mobilefaceblock(dl_matrix3dq_t *in, + dl_matrix3dq_t *pw, + dl_matrix3dq_t *pw_bias, + dl_matrix3dq_t *dw, + dl_matrix3dq_t *dw_bias, + dl_matrix3dq_t *pw_linear, + dl_matrix3dq_t *pw_linear_bias, + int pw_exponent, + int dw_exponent, + int pw_linear_exponent, + int stride_x, + int stride_y, + dl_padding_type padding, + dl_conv_mode mode, + int shortcut); + +// +// Mobilenet +// + +/** + * @brief Do mobilenet process, the process sequence is 1x1 dilated->prelu->3x3 depthwise->prelu->1x1 compress->bias + * + * @param in Input matrix, size (1, w, h, c) + * @param dilate Pointwise 1x1 filter, size (n1, 1, 1, c) + * @param dilate_prelu Pointwise prelu, size (1, 1, 1, n1) + * @param depthwise Depthwise 3x3 filter, size (1, 3, 3, n1) + * @param depthwise_prelu Depthwise prelu, size (1, 1, 1, n1) + * @param compress Pointwise 1x1 filter, size (n2, 1, 1, n1) + * @param bias Pointwise bias, size (1, 1, 1, n2) + * @param config Mobilenet configuration + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3dqq_mobilenet(dl_matrix3dq_t *in, + dl_matrix3dq_t *dilate, + dl_matrix3dq_t *dilate_prelu, + dl_matrix3dq_t *depthwise, + dl_matrix3dq_t *depth_prelu, + dl_matrix3dq_t *compress, + dl_matrix3dq_t *bias, + dl_matrix3dq_mobilenet_config_t config, + char *name); + +/** + * @brief Do mobilenet process, the process sequence is 1x1 dilated->prelu->3x3 depthwise->prelu->1x1 compress->bias + * + * @param in Input matrix, 8-bit fixed point, size (1, w, h, c) + * @param dilate Pointwise 1x1 filter, size (n1, 1, 1, c) + * @param dilate_prelu Pointwise prelu, size (1, 1, 1, n1) + * @param depthwise Depthwise 3x3 filter, size (1, 3, 3, n1) + * @param depthwise_prelu Depthwise prelu, size (1, 1, 1, n1) + * @param compress Pointwise 1x1 filter, size (n2, 1, 1, n1) + * @param bias Pointwise bias, size (1, 1, 1, n2) + * @param config Mobilenet configuration + * @return Resulting quantized matrix + */ +dl_matrix3dq_t *dl_matrix3duq_mobilenet(dl_matrix3du_t *in, + dl_matrix3dq_t *dilate, + dl_matrix3dq_t *dilate_prelu, + dl_matrix3dq_t *depthwise, + dl_matrix3dq_t *depth_prelu, + dl_matrix3dq_t *compress, + dl_matrix3dq_t *bias, + dl_matrix3dq_mobilenet_config_t config, + char *name); + +// +// Padding +// + +dl_error_type dl_matrix3dqq_padding(dl_matrix3dq_t **padded_in, + dl_matrix3dq_t **out, + dl_matrix3dq_t *in, + int out_c, + int stride_x, + int stride_y, + int padding, + int exponent); + +dl_error_type dl_matrix3duq_padding(dl_matrix3du_t **padded_in, + dl_matrix3dq_t **out, + dl_matrix3du_t *in, + int out_c, + int stride_x, + int stride_y, + int padding, + int exponent); + +// +// Pooling +// +/** + * @brief Calculate average value of a feature map + * + * @param in Input matrix, size (1, w, h, c) + * @return Resulting matrix, size (1, 1, 1, c) + */ +dl_matrix3dq_t *dl_matrix3dq_global_pool(dl_matrix3dq_t *in); diff --git a/tools/sdk/include/esp-face/fd_forward.h b/tools/sdk/include/esp-face/fd_forward.h new file mode 100644 index 00000000000..12db168f659 --- /dev/null +++ b/tools/sdk/include/esp-face/fd_forward.h @@ -0,0 +1,98 @@ +/* + * ESPRESSIF MIT License + * + * Copyright (c) 2018 + * + * Permission is hereby granted for use on ESPRESSIF SYSTEMS products only, in which case, + * it is 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. + * + */ +#pragma once + +#if __cplusplus +extern "C" +{ +#endif + +#include "image_util.h" +#include "dl_lib_matrix3d.h" +#include "mtmn.h" + + typedef enum + { + FAST = 0, + NORMAL = 1, + } mtmn_resize_type; + + typedef struct + { + float score; /// score threshold for filter candidates by score + float nms; /// nms threshold for nms process + int candidate_number; /// candidate number limitation for each net + } threshold_config_t; + + typedef struct + { + int w; /// net width + int h; /// net height + threshold_config_t threshold; /// threshold of net + } net_config_t; + + typedef struct + { + float min_face; /// The minimum size of a detectable face + float pyramid; /// The scale of the gradient scaling for the input images + int pyramid_times; /// The pyramid resizing times + threshold_config_t p_threshold; /// The thresholds for P-Net. For details, see the definition of threshold_config_t + threshold_config_t r_threshold; /// The thresholds for R-Net. For details, see the definition of threshold_config_t + threshold_config_t o_threshold; /// The thresholds for O-Net. For details, see the definition of threshold_config_t + mtmn_resize_type type; /// The image resize type. 'pyramid' will lose efficacy, when 'type'==FAST. + } mtmn_config_t; + + static inline mtmn_config_t mtmn_init_config() + { + mtmn_config_t mtmn_config; + mtmn_config.type = FAST; + mtmn_config.min_face = 80; + mtmn_config.pyramid = 0.707; + mtmn_config.pyramid_times = 4; + mtmn_config.p_threshold.score = 0.6; + mtmn_config.p_threshold.nms = 0.7; + mtmn_config.p_threshold.candidate_number = 20; + mtmn_config.r_threshold.score = 0.7; + mtmn_config.r_threshold.nms = 0.7; + mtmn_config.r_threshold.candidate_number = 10; + mtmn_config.o_threshold.score = 0.7; + mtmn_config.o_threshold.nms = 0.7; + mtmn_config.o_threshold.candidate_number = 1; + + return mtmn_config; + } + + /** + * @brief Do MTMN face detection, return box and landmark infomation. + * + * @param image_matrix Image matrix, rgb888 format + * @param config Configuration of MTMN i.e. score threshold, nms threshold, candidate number threshold, pyramid, min face size + * @return box_array_t* A list of boxes and score. + */ + box_array_t *face_detect(dl_matrix3du_t *image_matrix, + mtmn_config_t *config); + +#if __cplusplus +} +#endif diff --git a/tools/sdk/include/esp-face/fr_flash.h b/tools/sdk/include/esp-face/fr_flash.h new file mode 100644 index 00000000000..b21cea03060 --- /dev/null +++ b/tools/sdk/include/esp-face/fr_flash.h @@ -0,0 +1,52 @@ +#pragma once + +#if __cplusplus +extern "C" +{ +#endif + +#include "fr_forward.h" + +#define FR_FLASH_TYPE 32 +#define FR_FLASH_SUBTYPE 32 +#define FR_FLASH_PARTITION_NAME "fr" +#define FR_FLASH_INFO_FLAG 12138 + + /** + * @brief Produce face id according to the input aligned face, and save it to dest_id and flash. + * + * @param l Face id list + * @param aligned_face An aligned face + * @return -2 Flash partition not found + * @return 0 Enrollment finish + * @return >=1 The left piece of aligned faces should be input + */ + int8_t enroll_face_id_to_flash(face_id_list *l, + dl_matrix3du_t *aligned_face); + + int8_t enroll_face_id_to_flash_with_name(face_id_name_list *l, + dl_matrix3d_t *new_id, + char *name); + /** + * @brief Read the enrolled face IDs from the flash. + * + * @param l Face id list + * @return int8_t The number of IDs remaining in flash + */ + int8_t read_face_id_from_flash(face_id_list *l); + + int8_t read_face_id_from_flash_with_name(face_id_name_list *l); + + /** + * @brief Delete the enrolled face IDs in the flash. + * + * @param l Face id list + * @return int8_t The number of IDs remaining in flash + */ + int8_t delete_face_id_in_flash(face_id_list *l); + int8_t delete_face_id_in_flash_with_name(face_id_name_list *l, char *name); + void delete_face_all_in_flash_with_name(face_id_name_list *l); + +#if __cplusplus +} +#endif diff --git a/tools/sdk/include/esp-face/fr_forward.h b/tools/sdk/include/esp-face/fr_forward.h new file mode 100644 index 00000000000..a6db0a1b324 --- /dev/null +++ b/tools/sdk/include/esp-face/fr_forward.h @@ -0,0 +1,146 @@ +#pragma once + +#if __cplusplus +extern "C" +{ +#endif + +#include "image_util.h" +#include "dl_lib_matrix3d.h" +#include "frmn.h" + +#define FACE_WIDTH 56 +#define FACE_HEIGHT 56 +#define FACE_ID_SIZE 512 +#define FACE_REC_THRESHOLD 0.5 + +#define LEFT_EYE_X 0 +#define LEFT_EYE_Y 1 +#define RIGHT_EYE_X 6 +#define RIGHT_EYE_Y 7 +#define NOSE_X 4 +#define NOSE_Y 5 + +#define EYE_DIST_SET 16.5f +#define NOSE_EYE_RATIO_THRES_MIN 0.49f +#define NOSE_EYE_RATIO_THRES_MAX 2.04f + +/** + * @brief HTTP Client events data + */ +#define ENROLL_NAME_LEN 16 + typedef struct tag_face_id_node + { + struct tag_face_id_node *next; + char id_name[ENROLL_NAME_LEN]; + dl_matrix3d_t *id_vec; + } face_id_node; + + typedef struct + { + face_id_node *head; /*!< head pointer of the id list */ + face_id_node *tail; /*!< tail pointer of the id list */ + uint8_t count; /*!< number of enrolled ids */ + uint8_t confirm_times; /*!< images needed for one enrolling */ + } face_id_name_list; + + typedef struct + { + uint8_t head; /*!< head index of the id list */ + uint8_t tail; /*!< tail index of the id list */ + uint8_t count; /*!< number of enrolled ids */ + uint8_t size; /*!< max len of id list */ + uint8_t confirm_times; /*!< images needed for one enrolling */ + dl_matrix3d_t **id_list; /*!< stores face id vectors */ + } face_id_list; + + /** + * @brief Initialize face id list + * + * @param l Face id list + * @param size Size of list, one list contains one vector + * @param confirm_times Enroll times for one id + * @return dl_matrix3du_t* Size: 1xFACE_WIDTHxFACE_HEIGHTx3 + */ + void face_id_init(face_id_list *l, uint8_t size, uint8_t confirm_times); + void face_id_name_init(face_id_name_list *l, uint8_t size, uint8_t confirm_times); + + /** + * @brief Alloc memory for aligned face. + * + * @return dl_matrix3du_t* Size: 1xFACE_WIDTHxFACE_HEIGHTx3 + */ + dl_matrix3du_t *aligned_face_alloc(); + + /** + * @brief Align detected face to average face according to landmark + * + * @param onet_boxes Output of MTMN with box and landmark + * @param src Image matrix, rgb888 format + * @param dest Output image + * @return ESP_OK Input face is good for recognition + * @return ESP_FAIL Input face is not good for recognition + */ + int8_t align_face(box_array_t *onet_boxes, + dl_matrix3du_t *src, + dl_matrix3du_t *dest); + + int8_t align_face2(fptp_t *landmark, + dl_matrix3du_t *src, + dl_matrix3du_t *dest); + + /** + * @brief Run the face recognition model to get the face feature + * + * @param aligned_face A 56x56x3 image, the variable need to do align_face first + * @return face_id A 512 vector, size (1, 1, 1, 512) + */ + dl_matrix3d_t *get_face_id(dl_matrix3du_t *aligned_face); + + /** + * @brief Add src_id to dest_id + * + * @param dest_id + * @param src_id + */ + void add_face_id(dl_matrix3d_t *dest_id, + dl_matrix3d_t *src_id); + + /** + * @brief Match face with the id_list, and return matched_id. + * + * @param algined_face An aligned face + * @param id_list An ID list + * @return int8_t Matched face id + */ + int8_t recognize_face(face_id_list *l, dl_matrix3du_t *algined_face); + + face_id_node *recognize_face_with_name(face_id_name_list *l, dl_matrix3d_t *face_id); + /** + * @brief Produce face id according to the input aligned face, and save it to dest_id. + * + * @param l face id list + * @param aligned_face An aligned face + * @param enroll_confirm_times Confirm times for each face id enrollment + * @return -1 Wrong input enroll_confirm_times + * @return 0 Enrollment finish + * @return >=1 The left piece of aligned faces should be input + */ + int8_t enroll_face(face_id_list *l, dl_matrix3du_t *aligned_face); + + int8_t enroll_face_with_name(face_id_name_list *l, + dl_matrix3d_t *new_id, + char *name); + + /** + * @brief Alloc memory for aligned face. + * + * @param l face id list + * @return uint8_t left count + */ + uint8_t delete_face(face_id_list *l); + int8_t delete_face_with_name(face_id_name_list *l, char *name); + void delete_face_all_with_name(face_id_name_list *l); +#if __cplusplus +} +#endif diff --git a/tools/sdk/include/esp-face/frmn.h b/tools/sdk/include/esp-face/frmn.h new file mode 100644 index 00000000000..171f69ad885 --- /dev/null +++ b/tools/sdk/include/esp-face/frmn.h @@ -0,0 +1,57 @@ +#pragma once + +#if __cplusplus +extern "C" +{ +#endif + +#include "dl_lib_matrix3d.h" +#include "dl_lib_matrix3dq.h" + + /** + * @brief Forward the face recognition process with frmn model. Calculate in float. + * + * @param in Image matrix, rgb888 format, size is 56x56, normalized + * @return dl_matrix3d_t* Face ID feature vector, size is 512 + */ + dl_matrix3d_t *frmn(dl_matrix3d_t *in); + + /** + * @brief Forward the face recognition process with frmn model. Calculate in quantization. + * + * @param in Image matrix, rgb888 format, size is 56x56, normalized + * @param mode 0: C implement; 1: handwrite xtensa instruction implement + * @return Face ID feature vector, size is 512 + */ + dl_matrix3dq_t *frmn_q(dl_matrix3dq_t *in, dl_conv_mode mode); + + /** + * @brief Forward the face recognition process with frmn2 model. Calculate in quantization. + * + * @param in Image matrix, rgb888 format, size is 56x56, normalized + * @param mode 0: C implement; 1: handwrite xtensa instruction implement + * @return Face ID feature vector, size is 512 + */ + dl_matrix3dq_t *frmn2_q(dl_matrix3dq_t *in, dl_conv_mode mode); + + /** + * @brief Forward the face recognition process with frmn2p model. Calculate in quantization. + * + * @param in Image matrix, rgb888 format, size is 56x56, normalized + * @param mode 0: C implement; 1: handwrite xtensa instruction implement + * @return Face ID feature vector, size is 512 + */ + dl_matrix3dq_t *frmn2p_q(dl_matrix3dq_t *in, dl_conv_mode mode); + + /** + * @brief Forward the face recognition process with frmn2c model. Calculate in quantization. + * + * @param in Image matrix, rgb888 format, size is 56x56, normalized + * @param mode 0: C implement; 1: handwrite xtensa instruction implement + * @return Face ID feature vector, size is 512 + */ + dl_matrix3dq_t *frmn2c_q(dl_matrix3dq_t *in, dl_conv_mode mode); + +#if __cplusplus +} +#endif diff --git a/tools/sdk/include/esp-face/image_util.h b/tools/sdk/include/esp-face/image_util.h new file mode 100644 index 00000000000..961a12299d1 --- /dev/null +++ b/tools/sdk/include/esp-face/image_util.h @@ -0,0 +1,310 @@ +/* + * ESPRESSIF MIT License + * + * Copyright (c) 2018 + * + * Permission is hereby granted for use on ESPRESSIF SYSTEMS products only, in which case, + * it is 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. + * + */ +#pragma once +#ifdef __cplusplus +extern "C" +{ +#endif +#include +#include +#include "mtmn.h" + +#define MAX_VALID_COUNT_PER_IMAGE (30) + +#define DL_IMAGE_MIN(A, B) ((A) < (B) ? (A) : (B)) +#define DL_IMAGE_MAX(A, B) ((A) < (B) ? (B) : (A)) + +#define IMAGE_WIDTH 320 +#define IMAGE_HEIGHT 240 + +#define RGB565_MASK_RED 0xF800 +#define RGB565_MASK_GREEN 0x07E0 +#define RGB565_MASK_BLUE 0x001F + + typedef enum + { + BINARY, + } en_threshold_mode; + typedef struct + { + fptp_t landmark_p[10]; + } landmark_t; + + typedef struct + { + fptp_t box_p[4]; + } box_t; + + typedef struct tag_box_list + { + fptp_t *score; + box_t *box; + landmark_t *landmark; + int len; + } box_array_t; + + typedef struct tag_image_box + { + struct tag_image_box *next; + fptp_t score; + box_t box; + box_t offset; + landmark_t landmark; + } image_box_t; + + typedef struct tag_image_list + { + image_box_t *head; + image_box_t *origin_head; + int len; + } image_list_t; + + static inline void image_get_width_and_height(box_t *box, float *w, float *h) + { + *w = box->box_p[2] - box->box_p[0] + 1; + *h = box->box_p[3] - box->box_p[1] + 1; + } + + static inline void image_get_area(box_t *box, float *area) + { + float w, h; + image_get_width_and_height(box, &w, &h); + *area = w * h; + } + + static inline void image_calibrate_by_offset(image_list_t *image_list) + { + for (image_box_t *head = image_list->head; head; head = head->next) + { + float w, h; + image_get_width_and_height(&(head->box), &w, &h); + head->box.box_p[0] = DL_IMAGE_MAX(0, head->box.box_p[0] + head->offset.box_p[0] * w); + head->box.box_p[1] = DL_IMAGE_MAX(0, head->box.box_p[1] + head->offset.box_p[1] * w); + head->box.box_p[2] += head->offset.box_p[2] * w; + if (head->box.box_p[2] > IMAGE_WIDTH) + { + head->box.box_p[2] = IMAGE_WIDTH - 1; + head->box.box_p[0] = IMAGE_WIDTH - w; + } + head->box.box_p[3] += head->offset.box_p[3] * h; + if (head->box.box_p[3] > IMAGE_HEIGHT) + { + head->box.box_p[3] = IMAGE_HEIGHT - 1; + head->box.box_p[1] = IMAGE_HEIGHT - h; + } + } + } + + static inline void image_landmark_calibrate(image_list_t *image_list) + { + for (image_box_t *head = image_list->head; head; head = head->next) + { + float w, h; + image_get_width_and_height(&(head->box), &w, &h); + head->landmark.landmark_p[0] = head->box.box_p[0] + head->landmark.landmark_p[0] * w; + head->landmark.landmark_p[1] = head->box.box_p[1] + head->landmark.landmark_p[1] * h; + + head->landmark.landmark_p[2] = head->box.box_p[0] + head->landmark.landmark_p[2] * w; + head->landmark.landmark_p[3] = head->box.box_p[1] + head->landmark.landmark_p[3] * h; + + head->landmark.landmark_p[4] = head->box.box_p[0] + head->landmark.landmark_p[4] * w; + head->landmark.landmark_p[5] = head->box.box_p[1] + head->landmark.landmark_p[5] * h; + + head->landmark.landmark_p[6] = head->box.box_p[0] + head->landmark.landmark_p[6] * w; + head->landmark.landmark_p[7] = head->box.box_p[1] + head->landmark.landmark_p[7] * h; + + head->landmark.landmark_p[8] = head->box.box_p[0] + head->landmark.landmark_p[8] * w; + head->landmark.landmark_p[9] = head->box.box_p[1] + head->landmark.landmark_p[9] * h; + } + } + + static inline void image_rect2sqr(box_array_t *boxes, int width, int height) + { + for (int i = 0; i < boxes->len; i++) + { + box_t *box = &(boxes->box[i]); + + int x1 = round(box->box_p[0]); + int y1 = round(box->box_p[1]); + int x2 = round(box->box_p[2]); + int y2 = round(box->box_p[3]); + + int w = x2 - x1 + 1; + int h = y2 - y1 + 1; + int l = DL_IMAGE_MAX(w, h); + + box->box_p[0] = round(DL_IMAGE_MAX(0, x1) + 0.5 * (w - l)); + box->box_p[1] = round(DL_IMAGE_MAX(0, y1) + 0.5 * (h - l)); + + box->box_p[2] = box->box_p[0] + l - 1; + if (box->box_p[2] > width) + { + box->box_p[2] = width - 1; + box->box_p[0] = width - l; + } + box->box_p[3] = box->box_p[1] + l - 1; + if (box->box_p[3] > height) + { + box->box_p[3] = height - 1; + box->box_p[1] = height - l; + } + } + } + + static inline void rgb565_to_888(uint16_t in, uint8_t *dst) + { /*{{{*/ + dst[0] = (in & RGB565_MASK_BLUE) << 3; // blue + dst[1] = (in & RGB565_MASK_GREEN) >> 3; // green + dst[2] = (in & RGB565_MASK_RED) >> 8; // red + } /*}}}*/ + + static inline void rgb888_to_565(uint16_t *in, uint8_t r, uint8_t g, uint8_t b) + { /*{{{*/ + uint16_t rgb565 = 0; + rgb565 = ((r >> 3) << 11); + rgb565 |= ((g >> 2) << 5); + rgb565 |= (b >> 3); + *in = rgb565; + } /*}}}*/ + + /** + * @brief + * + * @param score + * @param offset + * @param width + * @param height + * @param p_net_size + * @param score_threshold + * @param scale + * @return image_list_t* + */ + image_list_t *image_get_valid_boxes(fptp_t *score, + fptp_t *offset, + int width, + int height, + int p_net_size, + fptp_t score_threshold, + fptp_t scale); + /** + * @brief + * + * @param image_sorted_list + * @param insert_list + */ + void image_sort_insert_by_score(image_list_t *image_sorted_list, const image_list_t *insert_list); + + /** + * @brief + * + * @param image_list + * @param nms_threshold + * @param same_area + */ + void image_nms_process(image_list_t *image_list, fptp_t nms_threshold, int same_area); + + /** + * @brief + * + * @param dimage + * @param dw + * @param dh + * @param dc + * @param simage + * @param sw + * @param sc + */ + void image_zoom_in_twice(uint8_t *dimage, + int dw, + int dh, + int dc, + uint8_t *simage, + int sw, + int sc); + + /** + * @brief + * + * @param dst_image + * @param src_image + * @param dst_w + * @param dst_h + * @param dst_c + * @param src_w + * @param src_h + */ + void image_resize_linear(uint8_t *dst_image, uint8_t *src_image, int dst_w, int dst_h, int dst_c, int src_w, int src_h); + + /** + * @brief + * + * @param corp_image + * @param src_image + * @param rotate_angle + * @param ratio + * @param center + */ + void image_cropper(uint8_t *corp_image, uint8_t *src_image, int dst_w, int dst_h, int dst_c, int src_w, int src_h, float rotate_angle, float ratio, float *center); + + /** + * @brief + * + * @param m + * @param bmp + * @param count + */ + void transform_input_image(uint8_t *m, uint16_t *bmp, int count); + + /** + * @brief + * + * @param bmp + * @param m + * @param count + */ + void transform_output_image(uint16_t *bmp, uint8_t *m, int count); + + /** + * @brief + * + * @param buf + * @param boxes + * @param width + */ + void draw_rectangle_rgb565(uint16_t *buf, box_array_t *boxes, int width); + + /** + * @brief + * + * @param buf + * @param boxes + * @param width + */ + void draw_rectangle_rgb888(uint8_t *buf, box_array_t *boxes, int width); + void image_abs_diff(uint8_t *dst, uint8_t *src1, uint8_t *src2, int count); + void image_threshold(uint8_t *dst, uint8_t *src, int threshold, int value, int count, en_threshold_mode mode); + void image_erode(uint8_t *dst, uint8_t *src, int src_w, int src_h, int src_c); +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/esp-face/mtmn.h b/tools/sdk/include/esp-face/mtmn.h new file mode 100644 index 00000000000..609a82ea488 --- /dev/null +++ b/tools/sdk/include/esp-face/mtmn.h @@ -0,0 +1,142 @@ +/* + * ESPRESSIF MIT License + * + * Copyright (c) 2018 + * + * Permission is hereby granted for use on ESPRESSIF SYSTEMS products only, in which case, + * it is 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. + * + */ +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif +#include "dl_lib_matrix3d.h" +#include "dl_lib_matrix3dq.h" + + /** + * Detection results with MTMN. + * + */ + typedef struct + { + dl_matrix3d_t *category; /*!< Classification result after softmax, channel is 2 */ + dl_matrix3d_t *offset; /*!< Bounding box offset of 2 points: top-left and bottom-right, channel is 4 */ + dl_matrix3d_t *landmark; /*!< Offsets of 5 landmarks: + * - Left eye + * - Mouth leftside + * - Nose + * - Right eye + * - Mouth rightside + * + * channel is 10 + * */ + } mtmn_net_t; + + + /** + * @brief Free a mtmn_net_t + * + * @param p A mtmn_net_t pointer + * + */ + + void mtmn_net_t_free(mtmn_net_t *p); + + /** + * @brief Forward the pnet process, coarse detection. Calculate in float. + * + * @param in Image matrix, rgb888 format, size is 320x240 + * @return Scores for every pixel, and box offset with respect. + */ + mtmn_net_t *pnet_lite_f(dl_matrix3du_t *in); + + /** + * @brief Forward the rnet process, fine determine the boxes from pnet. Calculate in float. + * + * @param in Image matrix, rgb888 format + * @param threshold Score threshold to detect human face + * @return Scores for every box, and box offset with respect. + */ + mtmn_net_t *rnet_lite_f_with_score_verify(dl_matrix3du_t *in, float threshold); + + /** + * @brief Forward the onet process, fine determine the boxes from rnet. Calculate in float. + * + * @param in Image matrix, rgb888 format + * @param threshold Score threshold to detect human face + * @return Scores for every box, box offset, and landmark with respect. + */ + mtmn_net_t *onet_lite_f_with_score_verify(dl_matrix3du_t *in, float threshold); + + /** + * @brief Forward the pnet process, coarse detection. Calculate in quantization. + * + * @param in Image matrix, rgb888 format, size is 320x240 + * @return Scores for every pixel, and box offset with respect. + */ + mtmn_net_t *pnet_lite_q(dl_matrix3du_t *in, dl_conv_mode mode); + + /** + * @brief Forward the rnet process, fine determine the boxes from pnet. Calculate in quantization. + * + * @param in Image matrix, rgb888 format + * @param threshold Score threshold to detect human face + * @return Scores for every box, and box offset with respect. + */ + mtmn_net_t *rnet_lite_q_with_score_verify(dl_matrix3du_t *in, float threshold, dl_conv_mode mode); + + /** + * @brief Forward the onet process, fine determine the boxes from rnet. Calculate in quantization. + * + * @param in Image matrix, rgb888 format + * @param threshold Score threshold to detect human face + * @return Scores for every box, box offset, and landmark with respect. + */ + mtmn_net_t *onet_lite_q_with_score_verify(dl_matrix3du_t *in, float threshold, dl_conv_mode mode); + + /** + * @brief Forward the pnet process, coarse detection. Calculate in quantization. + * + * @param in Image matrix, rgb888 format, size is 320x240 + * @return Scores for every pixel, and box offset with respect. + */ + mtmn_net_t *pnet_heavy_q(dl_matrix3du_t *in, dl_conv_mode mode); + + /** + * @brief Forward the rnet process, fine determine the boxes from pnet. Calculate in quantization. + * + * @param in Image matrix, rgb888 format + * @param threshold Score threshold to detect human face + * @return Scores for every box, and box offset with respect. + */ + mtmn_net_t *rnet_heavy_q_with_score_verify(dl_matrix3du_t *in, float threshold, dl_conv_mode mode); + + /** + * @brief Forward the onet process, fine determine the boxes from rnet. Calculate in quantization. + * + * @param in Image matrix, rgb888 format + * @param threshold Score threshold to detect human face + * @return Scores for every box, box offset, and landmark with respect. + */ + mtmn_net_t *onet_heavy_q_with_score_verify(dl_matrix3du_t *in, float threshold, dl_conv_mode mode); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/esp-tls/esp_tls.h b/tools/sdk/include/esp-tls/esp_tls.h new file mode 100644 index 00000000000..15830d5a3cc --- /dev/null +++ b/tools/sdk/include/esp-tls/esp_tls.h @@ -0,0 +1,306 @@ +// 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 "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" + +#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; + +/** + * @brief ESP-TLS configuration parameters + */ +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: + "\x02h2" + - where the first '2' is the length of the protocol and + - the subsequent 'h2' is the protocol name */ + + const unsigned char *cacert_pem_buf; /*!< Certificate Authority's certificate in a buffer */ + + unsigned int cacert_pem_bytes; /*!< Size of Certificate Authority certificate + pointed to by cacert_pem_buf */ + + const unsigned char *clientcert_pem_buf;/*!< Client certificate in a buffer */ + + unsigned int clientcert_pem_bytes; /*!< Size of client certificate pointed to by + clientcert_pem_buf */ + + const unsigned char *clientkey_pem_buf; /*!< Client key in a buffer */ + + unsigned int clientkey_pem_bytes; /*!< Size of client key pointed to by + clientkey_pem_buf */ + + 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 */ + + 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. */ +} esp_tls_cfg_t; + +/** + * @brief ESP-TLS Connection Handle + */ +typedef struct esp_tls { + 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 */ + + 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 */ +} esp_tls_t; + +/** + * @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. + * @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); + +/** + * @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. The underlying + * connection was closed. + * - <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 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. + */ +void esp_tls_conn_delete(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 + */ +size_t esp_tls_get_bytes_avail(esp_tls_t *tls); + +/** + * @brief Create a global CA store with the buffer provided in cfg. + * + * This function should be called if the application wants to use the same CA store for + * multiple connections. 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 creating global CA store 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 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(); + +/** + * @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(); + + +#ifdef __cplusplus +} +#endif + +#endif /* ! _ESP_TLS_H_ */ diff --git a/tools/sdk/include/esp32-camera/esp_camera.h b/tools/sdk/include/esp32-camera/esp_camera.h new file mode 100755 index 00000000000..071b986fa5a --- /dev/null +++ b/tools/sdk/include/esp32-camera/esp_camera.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. +/* + * Example Use + * + static camera_config_t camera_example_config = { + .pin_pwdn = PIN_PWDN, + .pin_reset = PIN_RESET, + .pin_xclk = PIN_XCLK, + .pin_sscb_sda = PIN_SIOD, + .pin_sscb_scl = PIN_SIOC, + .pin_d7 = PIN_D7, + .pin_d6 = PIN_D6, + .pin_d5 = PIN_D5, + .pin_d4 = PIN_D4, + .pin_d3 = PIN_D3, + .pin_d2 = PIN_D2, + .pin_d1 = PIN_D1, + .pin_d0 = PIN_D0, + .pin_vsync = PIN_VSYNC, + .pin_href = PIN_HREF, + .pin_pclk = PIN_PCLK, + + .xclk_freq_hz = 20000000, + .ledc_timer = LEDC_TIMER_0, + .ledc_channel = LEDC_CHANNEL_0, + .pixel_format = PIXFORMAT_JPEG, + .frame_size = FRAMESIZE_SVGA, + .jpeg_quality = 10, + .fb_count = 2 + }; + + esp_err_t camera_example_init(){ + return esp_camera_init(&camera_example_config); + } + + esp_err_t camera_example_capture(){ + //capture a frame + camera_fb_t * fb = esp_camera_fb_get(); + if (!fb) { + ESP_LOGE(TAG, "Frame buffer could not be acquired"); + return ESP_FAIL; + } + + //replace this with your own function + display_image(fb->width, fb->height, fb->pixformat, fb->buf, fb->len); + + //return the frame buffer back to be reused + esp_camera_fb_return(fb); + + return ESP_OK; + } +*/ + +#pragma once + +#include "esp_err.h" +#include "driver/ledc.h" +#include "sensor.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Configuration structure for camera initialization + */ +typedef struct { + int pin_pwdn; /*!< GPIO pin for camera power down line */ + int pin_reset; /*!< GPIO pin for camera reset line */ + int pin_xclk; /*!< GPIO pin for camera XCLK line */ + int pin_sscb_sda; /*!< GPIO pin for camera SDA line */ + int pin_sscb_scl; /*!< GPIO pin for camera SCL line */ + int pin_d7; /*!< GPIO pin for camera D7 line */ + int pin_d6; /*!< GPIO pin for camera D6 line */ + int pin_d5; /*!< GPIO pin for camera D5 line */ + int pin_d4; /*!< GPIO pin for camera D4 line */ + int pin_d3; /*!< GPIO pin for camera D3 line */ + int pin_d2; /*!< GPIO pin for camera D2 line */ + int pin_d1; /*!< GPIO pin for camera D1 line */ + int pin_d0; /*!< GPIO pin for camera D0 line */ + int pin_vsync; /*!< GPIO pin for camera VSYNC line */ + int pin_href; /*!< GPIO pin for camera HREF line */ + int pin_pclk; /*!< GPIO pin for camera PCLK line */ + + int xclk_freq_hz; /*!< Frequency of XCLK signal, in Hz. Either 20KHz or 10KHz for OV2640 double FPS (Experimental) */ + + ledc_timer_t ledc_timer; /*!< LEDC timer to be used for generating XCLK */ + ledc_channel_t ledc_channel; /*!< LEDC channel to be used for generating XCLK */ + + pixformat_t pixel_format; /*!< Format of the pixel data: PIXFORMAT_ + YUV422|GRAYSCALE|RGB565|JPEG */ + framesize_t frame_size; /*!< Size of the output image: FRAMESIZE_ + QVGA|CIF|VGA|SVGA|XGA|SXGA|UXGA */ + + int jpeg_quality; /*!< Quality of JPEG output. 0-63 lower means higher quality */ + size_t fb_count; /*!< Number of frame buffers to be allocated. If more than one, then each frame will be acquired (double speed) */ +} camera_config_t; + +/** + * @brief Data structure of camera frame buffer + */ +typedef struct { + uint8_t * buf; /*!< Pointer to the pixel data */ + size_t len; /*!< Length of the buffer in bytes */ + size_t width; /*!< Width of the buffer in pixels */ + size_t height; /*!< Height of the buffer in pixels */ + pixformat_t format; /*!< Format of the pixel data */ +} camera_fb_t; + +#define ESP_ERR_CAMERA_BASE 0x20000 +#define ESP_ERR_CAMERA_NOT_DETECTED (ESP_ERR_CAMERA_BASE + 1) +#define ESP_ERR_CAMERA_FAILED_TO_SET_FRAME_SIZE (ESP_ERR_CAMERA_BASE + 2) +#define ESP_ERR_CAMERA_FAILED_TO_SET_OUT_FORMAT (ESP_ERR_CAMERA_BASE + 3) +#define ESP_ERR_CAMERA_NOT_SUPPORTED (ESP_ERR_CAMERA_BASE + 4) + +/** + * @brief Initialize the camera driver + * + * @note call camera_probe before calling this function + * + * This function detects and configures camera over I2C interface, + * allocates framebuffer and DMA buffers, + * initializes parallel I2S input, and sets up DMA descriptors. + * + * Currently this function can only be called once and there is + * no way to de-initialize this module. + * + * @param config Camera configuration parameters + * + * @return ESP_OK on success + */ +esp_err_t esp_camera_init(const camera_config_t* config); + +/** + * @brief Deinitialize the camera driver + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if the driver hasn't been initialized yet + */ +esp_err_t esp_camera_deinit(); + +/** + * @brief Obtain pointer to a frame buffer. + * + * @return pointer to the frame buffer + */ +camera_fb_t* esp_camera_fb_get(); + +/** + * @brief Return the frame buffer to be reused again. + * + * @param fb Pointer to the frame buffer + */ +void esp_camera_fb_return(camera_fb_t * fb); + +/** + * @brief Get a pointer to the image sensor control structure + * + * @return pointer to the sensor + */ +sensor_t * esp_camera_sensor_get(); + + +#ifdef __cplusplus +} +#endif + +#include "img_converters.h" + diff --git a/tools/sdk/include/esp32-camera/esp_jpg_decode.h b/tools/sdk/include/esp32-camera/esp_jpg_decode.h new file mode 100644 index 00000000000..f13536edf4d --- /dev/null +++ b/tools/sdk/include/esp32-camera/esp_jpg_decode.h @@ -0,0 +1,43 @@ +// 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_JPG_DECODE_H_ +#define _ESP_JPG_DECODE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include "esp_err.h" + +typedef enum { + JPG_SCALE_NONE, + JPG_SCALE_2X, + JPG_SCALE_4X, + JPG_SCALE_8X, + JPG_SCALE_MAX = JPG_SCALE_8X +} jpg_scale_t; + +typedef size_t (* jpg_reader_cb)(void * arg, size_t index, uint8_t *buf, size_t len); +typedef bool (* jpg_writer_cb)(void * arg, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint8_t *data); + +esp_err_t esp_jpg_decode(size_t len, jpg_scale_t scale, jpg_reader_cb reader, jpg_writer_cb writer, void * arg); + +#ifdef __cplusplus +} +#endif + +#endif /* _ESP_JPG_DECODE_H_ */ diff --git a/tools/sdk/include/esp32-camera/img_converters.h b/tools/sdk/include/esp32-camera/img_converters.h new file mode 100644 index 00000000000..2b83c4d6f42 --- /dev/null +++ b/tools/sdk/include/esp32-camera/img_converters.h @@ -0,0 +1,126 @@ +// 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 _IMG_CONVERTERS_H_ +#define _IMG_CONVERTERS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include "esp_camera.h" + +typedef size_t (* jpg_out_cb)(void * arg, size_t index, const void* data, size_t len); + +/** + * @brief Convert image buffer to JPEG + * + * @param src Source buffer in RGB565, RGB888, YUYV or GRAYSCALE format + * @param src_len Length in bytes of the source buffer + * @param width Width in pixels of the source image + * @param height Height in pixels of the source image + * @param format Format of the source image + * @param quality JPEG quality of the resulting image + * @param cp Callback to be called to write the bytes of the output JPEG + * @param arg Pointer to be passed to the callback + * + * @return true on success + */ +bool fmt2jpg_cb(uint8_t *src, size_t src_len, uint16_t width, uint16_t height, pixformat_t format, uint8_t quality, jpg_out_cb cb, void * arg); + +/** + * @brief Convert camera frame buffer to JPEG + * + * @param fb Source camera frame buffer + * @param quality JPEG quality of the resulting image + * @param cp Callback to be called to write the bytes of the output JPEG + * @param arg Pointer to be passed to the callback + * + * @return true on success + */ +bool frame2jpg_cb(camera_fb_t * fb, uint8_t quality, jpg_out_cb cb, void * arg); + +/** + * @brief Convert image buffer to JPEG buffer + * + * @param src Source buffer in RGB565, RGB888, YUYV or GRAYSCALE format + * @param src_len Length in bytes of the source buffer + * @param width Width in pixels of the source image + * @param height Height in pixels of the source image + * @param format Format of the source image + * @param quality JPEG quality of the resulting image + * @param out Pointer to be populated with the address of the resulting buffer + * @param out_len Pointer to be populated with the length of the output buffer + * + * @return true on success + */ +bool fmt2jpg(uint8_t *src, size_t src_len, uint16_t width, uint16_t height, pixformat_t format, uint8_t quality, uint8_t ** out, size_t * out_len); + +/** + * @brief Convert camera frame buffer to JPEG buffer + * + * @param fb Source camera frame buffer + * @param quality JPEG quality of the resulting image + * @param out Pointer to be populated with the address of the resulting buffer + * @param out_len Pointer to be populated with the length of the output buffer + * + * @return true on success + */ +bool frame2jpg(camera_fb_t * fb, uint8_t quality, uint8_t ** out, size_t * out_len); + +/** + * @brief Convert image buffer to BMP buffer + * + * @param src Source buffer in JPEG, RGB565, RGB888, YUYV or GRAYSCALE format + * @param src_len Length in bytes of the source buffer + * @param width Width in pixels of the source image + * @param height Height in pixels of the source image + * @param format Format of the source image + * @param out Pointer to be populated with the address of the resulting buffer + * @param out_len Pointer to be populated with the length of the output buffer + * + * @return true on success + */ +bool fmt2bmp(uint8_t *src, size_t src_len, uint16_t width, uint16_t height, pixformat_t format, uint8_t ** out, size_t * out_len); + +/** + * @brief Convert camera frame buffer to BMP buffer + * + * @param fb Source camera frame buffer + * @param out Pointer to be populated with the address of the resulting buffer + * @param out_len Pointer to be populated with the length of the output buffer + * + * @return true on success + */ +bool frame2bmp(camera_fb_t * fb, uint8_t ** out, size_t * out_len); + +/** + * @brief Convert image buffer to RGB888 buffer (used for face detection) + * + * @param src Source buffer in JPEG, RGB565, RGB888, YUYV or GRAYSCALE format + * @param src_len Length in bytes of the source buffer + * @param format Format of the source image + * @param rgb_buf Pointer to the output buffer (width * height * 3) + * + * @return true on success + */ +bool fmt2rgb888(const uint8_t *src_buf, size_t src_len, pixformat_t format, uint8_t * rgb_buf); + +#ifdef __cplusplus +} +#endif + +#endif /* _IMG_CONVERTERS_H_ */ diff --git a/tools/sdk/include/esp32-camera/sensor.h b/tools/sdk/include/esp32-camera/sensor.h new file mode 100755 index 00000000000..fc7786498e2 --- /dev/null +++ b/tools/sdk/include/esp32-camera/sensor.h @@ -0,0 +1,138 @@ +/* + * This file is part of the OpenMV project. + * Copyright (c) 2013/2014 Ibrahim Abdelkader + * This work is licensed under the MIT license, see the file LICENSE for details. + * + * Sensor abstraction layer. + * + */ +#ifndef __SENSOR_H__ +#define __SENSOR_H__ +#include + +#define OV9650_PID (0x96) +#define OV2640_PID (0x26) +#define OV7725_PID (0x77) +#define OV3660_PID (0x36) + +typedef enum { + PIXFORMAT_RGB565, // 2BPP/RGB565 + PIXFORMAT_YUV422, // 2BPP/YUV422 + PIXFORMAT_GRAYSCALE, // 1BPP/GRAYSCALE + PIXFORMAT_JPEG, // JPEG/COMPRESSED + PIXFORMAT_RGB888, // 3BPP/RGB888 + PIXFORMAT_RAW, // RAW + PIXFORMAT_RGB444, // 3BP2P/RGB444 + PIXFORMAT_RGB555, // 3BP2P/RGB555 +} pixformat_t; + +typedef enum { + FRAMESIZE_QQVGA, // 160x120 + FRAMESIZE_QQVGA2, // 128x160 + FRAMESIZE_QCIF, // 176x144 + FRAMESIZE_HQVGA, // 240x176 + FRAMESIZE_QVGA, // 320x240 + FRAMESIZE_CIF, // 400x296 + FRAMESIZE_VGA, // 640x480 + FRAMESIZE_SVGA, // 800x600 + FRAMESIZE_XGA, // 1024x768 + FRAMESIZE_SXGA, // 1280x1024 + FRAMESIZE_UXGA, // 1600x1200 + FRAMESIZE_QXGA, // 2048*1536 + FRAMESIZE_INVALID +} framesize_t; + +typedef enum { + GAINCEILING_2X, + GAINCEILING_4X, + GAINCEILING_8X, + GAINCEILING_16X, + GAINCEILING_32X, + GAINCEILING_64X, + GAINCEILING_128X, +} gainceiling_t; + +typedef struct { + uint8_t MIDH; + uint8_t MIDL; + uint8_t PID; + uint8_t VER; +} sensor_id_t; + +typedef struct { + framesize_t framesize;//0 - 10 + uint8_t quality;//0 - 63 + int8_t brightness;//-2 - 2 + int8_t contrast;//-2 - 2 + int8_t saturation;//-2 - 2 + int8_t sharpness;//-2 - 2 + uint8_t denoise; + uint8_t special_effect;//0 - 6 + uint8_t wb_mode;//0 - 4 + uint8_t awb; + uint8_t awb_gain; + uint8_t aec; + uint8_t aec2; + int8_t ae_level;//-2 - 2 + uint16_t aec_value;//0 - 1200 + uint8_t agc; + uint8_t agc_gain;//0 - 30 + uint8_t gainceiling;//0 - 6 + uint8_t bpc; + uint8_t wpc; + uint8_t raw_gma; + uint8_t lenc; + uint8_t hmirror; + uint8_t vflip; + uint8_t dcw; + uint8_t colorbar; +} camera_status_t; + +typedef struct _sensor sensor_t; +typedef struct _sensor { + sensor_id_t id; // Sensor ID. + uint8_t slv_addr; // Sensor I2C slave address. + pixformat_t pixformat; + camera_status_t status; + int xclk_freq_hz; + + // Sensor function pointers + int (*init_status) (sensor_t *sensor); + int (*reset) (sensor_t *sensor); + int (*set_pixformat) (sensor_t *sensor, pixformat_t pixformat); + int (*set_framesize) (sensor_t *sensor, framesize_t framesize); + int (*set_contrast) (sensor_t *sensor, int level); + int (*set_brightness) (sensor_t *sensor, int level); + int (*set_saturation) (sensor_t *sensor, int level); + int (*set_sharpness) (sensor_t *sensor, int level); + int (*set_denoise) (sensor_t *sensor, int level); + int (*set_gainceiling) (sensor_t *sensor, gainceiling_t gainceiling); + int (*set_quality) (sensor_t *sensor, int quality); + int (*set_colorbar) (sensor_t *sensor, int enable); + int (*set_whitebal) (sensor_t *sensor, int enable); + int (*set_gain_ctrl) (sensor_t *sensor, int enable); + int (*set_exposure_ctrl) (sensor_t *sensor, int enable); + int (*set_hmirror) (sensor_t *sensor, int enable); + int (*set_vflip) (sensor_t *sensor, int enable); + + int (*set_aec2) (sensor_t *sensor, int enable); + int (*set_awb_gain) (sensor_t *sensor, int enable); + int (*set_agc_gain) (sensor_t *sensor, int gain); + int (*set_aec_value) (sensor_t *sensor, int gain); + + int (*set_special_effect) (sensor_t *sensor, int effect); + int (*set_wb_mode) (sensor_t *sensor, int mode); + int (*set_ae_level) (sensor_t *sensor, int level); + + int (*set_dcw) (sensor_t *sensor, int enable); + int (*set_bpc) (sensor_t *sensor, int enable); + int (*set_wpc) (sensor_t *sensor, int enable); + + int (*set_raw_gma) (sensor_t *sensor, int enable); + int (*set_lenc) (sensor_t *sensor, int enable); +} sensor_t; + +// Resolution table (in camera.c) +extern const int resolution[][2]; + +#endif /* __SENSOR_H__ */ diff --git a/tools/sdk/include/esp32/esp32/pm.h b/tools/sdk/include/esp32/esp32/pm.h index a7cbf0eac71..f64045fb31b 100644 --- a/tools/sdk/include/esp32/esp32/pm.h +++ b/tools/sdk/include/esp32/esp32/pm.h @@ -31,8 +31,10 @@ extern "C" { * Pass a pointer to this structure as an argument to esp_pm_configure function. */ typedef struct { - rtc_cpu_freq_t max_cpu_freq; /*!< Maximum CPU frequency to use */ - rtc_cpu_freq_t min_cpu_freq; /*!< Minimum CPU frequency to use when no frequency locks are taken */ + rtc_cpu_freq_t max_cpu_freq __attribute__((deprecated)); /*!< Maximum CPU frequency to use. Deprecated, use max_freq_mhz instead. */ + int max_freq_mhz; /*!< Maximum CPU frequency, in MHz */ + rtc_cpu_freq_t min_cpu_freq __attribute__((deprecated)); /*!< Minimum CPU frequency to use when no frequency locks are taken. Deprecated, use min_freq_mhz instead. */ + 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; diff --git a/tools/sdk/include/esp32/esp_attr.h b/tools/sdk/include/esp32/esp_attr.h index a9c3f9a7a33..6d2d5ea84d4 100644 --- a/tools/sdk/include/esp32/esp_attr.h +++ b/tools/sdk/include/esp32/esp_attr.h @@ -39,12 +39,36 @@ // Forces code into RTC fast memory. See "docs/deep-sleep-stub.rst" #define RTC_IRAM_ATTR __attribute__((section(".rtc.text"))) +#if CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY +// Forces bss variable into external memory. " +#define EXT_RAM_ATTR __attribute__((section(".ext_ram.bss"))) +#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 __attribute__((section(".rtc.data"))) -// Forces read-only data into RTC slow memory. See "docs/deep-sleep-stub.rst" +// Forces read-only data into RTC memory. See "docs/deep-sleep-stub.rst" #define RTC_RODATA_ATTR __attribute__((section(".rtc.rodata"))) +// Allows to place data into RTC_SLOW memory. +#define RTC_SLOW_ATTR __attribute__((section(".rtc.force_slow"))) + +// Allows to place data into RTC_FAST memory. +#define RTC_FAST_ATTR __attribute__((section(".rtc.force_fast"))) + +// Forces data into noinit section to avoid initialization after restart. +#define __NOINIT_ATTR __attribute__((section(".noinit"))) + +// 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 __attribute__((section(".rtc_noinit"))) + +// Forces to not inline function +#define NOINLINE_ATTR __attribute__((noinline)) + #endif /* __ESP_ATTR_H__ */ diff --git a/tools/sdk/include/esp32/esp_clk.h b/tools/sdk/include/esp32/esp_clk.h index 6526aa92724..1a91d26f91c 100644 --- a/tools/sdk/include/esp32/esp_clk.h +++ b/tools/sdk/include/esp32/esp_clk.h @@ -62,6 +62,17 @@ int esp_clk_cpu_freq(void); */ int esp_clk_apb_freq(void); +/** + * @brief Return frequency of the main XTAL + * + * Frequency of the main XTAL can be either auto-detected or set at compile + * time (see CONFIG_ESP32_XTAL_FREQ_SEL sdkconfig option). In both cases, this + * function returns the actual value at run time. + * + * @return XTAL frequency, in Hz + */ +int esp_clk_xtal_freq(void); + /** * @brief Read value of RTC counter, converting it to microseconds diff --git a/tools/sdk/include/esp32/esp_coexist_adapter.h b/tools/sdk/include/esp32/esp_coexist_adapter.h new file mode 100644 index 00000000000..f2a38c31e63 --- /dev/null +++ b/tools/sdk/include/esp32/esp_coexist_adapter.h @@ -0,0 +1,59 @@ +// 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 0x00000001 +#define COEX_ADAPTER_MAGIC 0xDEADBEAF + +#define COEX_ADAPTER_FUNCS_TIME_BLOCKING 0xffffffff + +typedef struct { + int32_t _version; + 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); + 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); + int32_t (* _is_in_isr)(void); + void * (* _malloc_internal)(size_t size); + void (* _free)(void *p); + 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); + 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/include/esp32/esp_coexist_internal.h b/tools/sdk/include/esp32/esp_coexist_internal.h new file mode 100644 index 00000000000..1d94d6db796 --- /dev/null +++ b/tools/sdk/include/esp32/esp_coexist_internal.h @@ -0,0 +1,163 @@ +// 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 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 Pause software coexist + * extern function for internal use. + */ +void coex_pause(void); + +/** + * @brief Resume software coexist + * extern function for internal use. + */ +void coex_resume(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 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 Blue tooth requests coexistence. + * + * @param event : blue tooth event + * @param latency : blue tooth will request coexistence after latency + * @param duration : duration for blue tooth to request coexistence + * @return : 0 - success, other - failed + */ +int coex_bt_request(uint32_t event, uint32_t latency, uint32_t duration); + +/** + * @brief Blue tooth release coexistence. + * + * @param event : blue tooth event + * @return : 0 - success, other - failed + */ +int coex_bt_release(uint32_t event); + +/** + * @brief Register callback function for blue tooth. + * + * @param cb : callback function + * @return : 0 - success, other - failed + */ +int coex_register_bt_cb(coex_func_cb_t cb); + +/** + * @brief Lock before reset base band. + * + * @return : lock value + */ +uint32_t coex_bb_reset_lock(void); + +/** + * @brief Unlock after reset base band. + * + * @param restore : lock value + */ +void coex_bb_reset_unlock(uint32_t restore); + +/** + * @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/include/esp32/esp_dbg_stubs.h b/tools/sdk/include/esp32/esp_dbg_stubs.h new file mode 100644 index 00000000000..899dfa56ed8 --- /dev/null +++ b/tools/sdk/include/esp32/esp_dbg_stubs.h @@ -0,0 +1,50 @@ +// 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_ + +#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); + +#endif //ESP_DBG_STUBS_H_ \ No newline at end of file diff --git a/tools/sdk/include/esp32/esp_dport_access.h b/tools/sdk/include/esp32/esp_dport_access.h index 3acf806888b..8ea60c4cdb0 100644 --- a/tools/sdk/include/esp32/esp_dport_access.h +++ b/tools/sdk/include/esp32/esp_dport_access.h @@ -26,17 +26,23 @@ void esp_dport_access_stall_other_cpu_end(void); void esp_dport_access_int_init(void); void esp_dport_access_int_pause(void); void esp_dport_access_int_resume(void); - +void esp_dport_access_read_buffer(uint32_t *buff_out, uint32_t address, uint32_t num_words); +uint32_t esp_dport_access_reg_read(uint32_t reg); +uint32_t esp_dport_access_sequence_reg_read(uint32_t reg); //This routine does not stop the dport routines in any way that is recoverable. Please //only call in case of panic(). void esp_dport_access_int_abort(void); -#if defined(BOOTLOADER_BUILD) || defined(CONFIG_FREERTOS_UNICORE) || !defined(ESP_PLATFORM) +#if defined(BOOTLOADER_BUILD) || !defined(CONFIG_ESP32_DPORT_WORKAROUND) || !defined(ESP_PLATFORM) #define DPORT_STALL_OTHER_CPU_START() #define DPORT_STALL_OTHER_CPU_END() +#define DPORT_INTERRUPT_DISABLE() +#define DPORT_INTERRUPT_RESTORE() #else #define DPORT_STALL_OTHER_CPU_START() esp_dport_access_stall_other_cpu_start() #define DPORT_STALL_OTHER_CPU_END() esp_dport_access_stall_other_cpu_end() +#define DPORT_INTERRUPT_DISABLE() unsigned int intLvl = XTOS_SET_INTLEVEL(CONFIG_ESP32_DPORT_DIS_INTERRUPT_LVL) +#define DPORT_INTERRUPT_RESTORE() XTOS_RESTORE_JUST_INTLEVEL(intLvl) #endif #ifdef __cplusplus diff --git a/tools/sdk/include/esp32/esp_err.h b/tools/sdk/include/esp32/esp_err.h index b38a723bc30..6672f233a19 100644 --- a/tools/sdk/include/esp32/esp_err.h +++ b/tools/sdk/include/esp32/esp_err.h @@ -24,24 +24,23 @@ extern "C" { typedef int32_t 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_OK 0 -#define ESP_FAIL -1 +#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_NO_MEM 0x101 -#define ESP_ERR_INVALID_ARG 0x102 -#define ESP_ERR_INVALID_STATE 0x103 -#define ESP_ERR_INVALID_SIZE 0x104 -#define ESP_ERR_NOT_FOUND 0x105 -#define ESP_ERR_NOT_SUPPORTED 0x106 -#define ESP_ERR_TIMEOUT 0x107 -#define ESP_ERR_INVALID_RESPONSE 0x108 -#define ESP_ERR_INVALID_CRC 0x109 -#define ESP_ERR_INVALID_VERSION 0x10A -#define ESP_ERR_INVALID_MAC 0x10B - -#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_WIFI_BASE 0x3000 /*!< Starting number of WiFi error codes */ +#define ESP_ERR_MESH_BASE 0x4000 /*!< Starting number of MESH error codes */ /** * @brief Returns string for esp_err_t error codes @@ -76,8 +75,12 @@ const char *esp_err_to_name(esp_err_t code); */ 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. @@ -88,6 +91,7 @@ void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const cha #define __ASSERT_FUNC "??" #endif #endif +/** @endcond */ /** * Macro which can be used to check the error code, @@ -101,6 +105,13 @@ void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const cha esp_err_t __err_rc = (x); \ (void) sizeof(__err_rc); \ } while(0); +#elif defined(CONFIG_OPTIMIZATION_ASSERTIONS_SILENT) +#define ESP_ERROR_CHECK(x) do { \ + esp_err_t __err_rc = (x); \ + if (__err_rc != ESP_OK) { \ + abort(); \ + } \ + } while(0); #else #define ESP_ERROR_CHECK(x) do { \ esp_err_t __err_rc = (x); \ @@ -111,6 +122,27 @@ void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const cha } 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 (__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/include/esp32/esp_event.h b/tools/sdk/include/esp32/esp_event.h deleted file mode 100644 index 53c416c29fb..00000000000 --- a/tools/sdk/include/esp32/esp_event.h +++ /dev/null @@ -1,186 +0,0 @@ -// 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_EVENT_H__ -#define __ESP_EVENT_H__ - -#include -#include - -#include "esp_err.h" -#include "esp_wifi_types.h" -#include "tcpip_adapter.h" - -#ifdef __cplusplus -extern "C" { -#endif - -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_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_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_PROBEREQRECVED, /**< Receive probe request packet in soft-AP interface */ - 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 -} 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 - -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 -}system_event_sta_wps_fail_reason_t; -typedef struct { - uint32_t status; /**< status of scanning APs */ - uint8_t number; - uint8_t scan_id; -} system_event_sta_scan_done_t; - -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; -} system_event_sta_connected_t; - -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 */ -} system_event_sta_disconnected_t; - -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 */ -} system_event_sta_authmode_change_t; - -typedef struct { - tcpip_adapter_ip_info_t ip_info; - bool ip_changed; -} system_event_sta_got_ip_t; - -typedef struct { - uint8_t pin_code[8]; /**< PIN code of station in enrollee mode */ -} system_event_sta_wps_er_pin_t; - -typedef struct { - tcpip_adapter_if_t if_index; - tcpip_adapter_ip6_info_t ip6_info; -} system_event_got_ip6_t; - -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 */ -} system_event_ap_staconnected_t; - -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 */ -} system_event_ap_stadisconnected_t; - -typedef struct { - int rssi; /**< Received probe request signal strength */ - uint8_t mac[6]; /**< MAC address of the station which send probe request */ -} system_event_ap_probe_req_rx_t; - -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_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_got_ip6_t got_ip6; /**< ESP32 station or ap or ethernet ipv6 addr state change to preferred */ -} system_event_info_t; - -typedef struct { - system_event_id_t event_id; /**< event ID */ - system_event_info_t event_info; /**< event information */ -} system_event_t; - -typedef esp_err_t (*system_event_handler_t)(system_event_t *event); - -/** - * @brief Send a event to event task - * - * @attention 1. Other task/modules, such as the TCPIP module, can call this API to send an event to event task - * - * @param system_event_t * event : event - * - * @return ESP_OK : succeed - * @return others : fail - */ -esp_err_t esp_event_send(system_event_t *event); - -/** - * @brief Default event handler for system events - * - * 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); - -/** - * @brief Install default event handlers for Ethernet interface - * - */ -void esp_event_set_default_eth_handlers(); - -/** - * @brief Install default event handlers for Wi-Fi interfaces (station and AP) - * - */ -void esp_event_set_default_wifi_handlers(); - -#ifdef __cplusplus -} -#endif - -#endif /* __ESP_EVENT_H__ */ diff --git a/tools/sdk/include/esp32/esp_event_legacy.h b/tools/sdk/include/esp32/esp_event_legacy.h new file mode 100644 index 00000000000..a2518841819 --- /dev/null +++ b/tools/sdk/include/esp32/esp_event_legacy.h @@ -0,0 +1,188 @@ +// 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_EVENT_H__ +#define __ESP_EVENT_H__ + +#include +#include + +#include "esp_err.h" +#include "esp_wifi_types.h" +#include "tcpip_adapter.h" + +#ifdef __cplusplus +extern "C" { +#endif + +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_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_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 +} 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 + +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 +}system_event_sta_wps_fail_reason_t; +typedef struct { + uint32_t status; /**< status of scanning APs */ + uint8_t number; + uint8_t scan_id; +} system_event_sta_scan_done_t; + +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; +} system_event_sta_connected_t; + +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 */ +} system_event_sta_disconnected_t; + +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 */ +} system_event_sta_authmode_change_t; + +typedef struct { + tcpip_adapter_ip_info_t ip_info; + bool ip_changed; +} system_event_sta_got_ip_t; + +typedef struct { + uint8_t pin_code[8]; /**< PIN code of station in enrollee mode */ +} system_event_sta_wps_er_pin_t; + +typedef struct { + tcpip_adapter_if_t if_index; + tcpip_adapter_ip6_info_t ip6_info; +} system_event_got_ip6_t; + +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 */ +} system_event_ap_staconnected_t; + +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 */ +} system_event_ap_stadisconnected_t; + +typedef struct { + int rssi; /**< Received probe request signal strength */ + uint8_t mac[6]; /**< MAC address of the station which send probe request */ +} system_event_ap_probe_req_rx_t; + +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_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_got_ip6_t got_ip6; /**< ESP32 station or ap or ethernet ipv6 addr state change to preferred */ +} system_event_info_t; + +typedef struct { + system_event_id_t event_id; /**< event ID */ + system_event_info_t event_info; /**< event information */ +} system_event_t; + +typedef esp_err_t (*system_event_handler_t)(system_event_t *event); + +/** + * @brief Send a event to event task + * + * @attention 1. Other task/modules, such as the TCPIP module, can call this API to send an event to event task + * + * @param system_event_t * event : event + * + * @return ESP_OK : succeed + * @return others : fail + */ +esp_err_t esp_event_send(system_event_t *event); + +/** + * @brief Default event handler for system events + * + * 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); + +/** + * @brief Install default event handlers for Ethernet interface + * + */ +void esp_event_set_default_eth_handlers(); + +/** + * @brief Install default event handlers for Wi-Fi interfaces (station and AP) + * + */ +void esp_event_set_default_wifi_handlers(); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_EVENT_H__ */ diff --git a/tools/sdk/include/esp32/esp_flash_data_types.h b/tools/sdk/include/esp32/esp_flash_data_types.h index 3e44b2639dc..9a26281b0a8 100644 --- a/tools/sdk/include/esp32/esp_flash_data_types.h +++ b/tools/sdk/include/esp32/esp_flash_data_types.h @@ -21,7 +21,6 @@ extern "C" { #endif -#define ESP_PARTITION_TABLE_ADDR 0x8000 #define ESP_PARTITION_MAGIC 0x50AA #define ESP_PARTITION_MAGIC_MD5 0xEBEB @@ -61,6 +60,7 @@ typedef struct { #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_TYPE_END 0xff #define PART_SUBTYPE_END 0xff diff --git a/tools/sdk/include/esp32/esp_himem.h b/tools/sdk/include/esp32/esp_himem.h new file mode 100644 index 00000000000..099d9260153 --- /dev/null +++ b/tools/sdk/include/esp32/esp_himem.h @@ -0,0 +1,152 @@ +// 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 +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +//Opaque pointers as handles for ram/range data +typedef struct esp_himem_ramdata_t *esp_himem_handle_t; +typedef struct esp_himem_rangedata_t *esp_himem_rangehandle_t; + +//ESP32 MMU block size +#define ESP_HIMEM_BLKSZ (0x8000) + +#define ESP_HIMEM_MAPFLAG_RO 1 /*!< Indicates that a mapping will only be read from. Note that this is unused for now. */ + +/** + * @brief Allocate a block in high memory + * + * @param size Size of the to-be-allocated block, in bytes. Note that this needs to be + * a multiple of the external RAM mmu block size (32K). + * @param[out] handle_out Handle to be returned + * @returns - ESP_OK if succesful + * - ESP_ERR_NO_MEM if out of memory + * - ESP_ERR_INVALID_SIZE if size is not a multiple of 32K + */ +esp_err_t esp_himem_alloc(size_t size, esp_himem_handle_t *handle_out); + + +/** + * @brief Allocate a memory region to map blocks into + * + * This allocates a contiguous CPU memory region that can be used to map blocks + * of physical memory into. + * + * @param size Size of the range to be allocated. Note this needs to be a multiple of + * the external RAM mmu block size (32K). + * @param[out] handle_out Handle to be returned + * @returns - ESP_OK if succesful + * - ESP_ERR_NO_MEM if out of memory or address space + * - ESP_ERR_INVALID_SIZE if size is not a multiple of 32K + */ +esp_err_t esp_himem_alloc_map_range(size_t size, esp_himem_rangehandle_t *handle_out); + +/** + * @brief Map a block of high memory into the CPUs address space + * + * This effectively makes the block available for read/write operations. + * + * @note The region to be mapped needs to have offsets and sizes that are aligned to the + * SPI RAM MMU block size (32K) + * + * @param handle Handle to the block of memory, as given by esp_himem_alloc + * @param range Range handle to map the memory in + * @param ram_offset Offset into the block of physical memory of the block to map + * @param range_offset Offset into the address range where the block will be mapped + * @param len Length of region to map + * @param flags One of ESP_HIMEM_MAPFLAG_* + * @param[out] out_ptr Pointer to variable to store resulting memory pointer in + * @returns - ESP_OK if the memory could be mapped + * - ESP_ERR_INVALID_ARG if offset, range or len aren't MMU-block-aligned (32K) + * - ESP_ERR_INVALID_SIZE if the offsets/lengths don't fit in the allocated memory or range + * - ESP_ERR_INVALID_STATE if a block in the selected ram offset/length is already mapped, or + * if a block in the selected range offset/length already has a mapping. + */ +esp_err_t esp_himem_map(esp_himem_handle_t handle, esp_himem_rangehandle_t range, size_t ram_offset, size_t range_offset, size_t len, int flags, void **out_ptr); + + +/** + * @brief Free a block of physical memory + * + * This clears out the associated handle making the memory available for re-allocation again. + * This will only succeed if none of the memory blocks currently have a mapping. + * + * @param handle Handle to the block of memory, as given by esp_himem_alloc + * @returns - ESP_OK if the memory is succesfully freed + * - ESP_ERR_INVALID_ARG if the handle still is (partially) mapped + */ +esp_err_t esp_himem_free(esp_himem_handle_t handle); + + + +/** + * @brief Free a mapping range + * + * This clears out the associated handle making the range available for re-allocation again. + * This will only succeed if none of the range blocks currently are used for a mapping. + * + * @param handle Handle to the range block, as given by esp_himem_alloc_map_range + * @returns - ESP_OK if the memory is succesfully freed + * - ESP_ERR_INVALID_ARG if the handle still is (partially) mapped to + */ +esp_err_t esp_himem_free_map_range(esp_himem_rangehandle_t handle); + + +/** + * @brief Unmap a region + * + * @param range Range handle + * @param ptr Pointer returned by esp_himem_map + * @param len Length of the block to be unmapped. Must be aligned to the SPI RAM MMU blocksize (32K) + * @returns - ESP_OK if the memory is succesfully unmapped, + * - ESP_ERR_INVALID_ARG if ptr or len are invalid. + */ +esp_err_t esp_himem_unmap(esp_himem_rangehandle_t range, void *ptr, size_t len); + + +/** + * @brief Get total amount of memory under control of himem API + * + * @returns Amount of memory, in bytes + */ +size_t esp_himem_get_phys_size(); + +/** + * @brief Get free amount of memory under control of himem API + * + * @returns Amount of free memory, in bytes + */ +size_t esp_himem_get_free_size(); + + +/** + * @brief Get amount of SPI memory address space needed for bankswitching + * + * @note This is also weakly defined in esp32/spiram.c and returns 0 there, so + * if no other function in this file is used, no memory is reserved. + * + * @returns Amount of reserved area, in bytes + */ +size_t esp_himem_reserved_area_size(); + + +#ifdef __cplusplus +} +#endif + diff --git a/tools/sdk/include/esp32/esp_intr_alloc.h b/tools/sdk/include/esp32/esp_intr_alloc.h index b5420f79817..edc4b9f2df3 100644 --- a/tools/sdk/include/esp32/esp_intr_alloc.h +++ b/tools/sdk/include/esp32/esp_intr_alloc.h @@ -194,18 +194,19 @@ esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusre /** * @brief Disable and free an interrupt. * - * Use an interrupt handle to disable the interrupt and release the resources - * associated with it. + * 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. + * ``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 if handle is invalid, or esp_intr_free runs on another core than - * where the interrupt is allocated on. + * @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); diff --git a/tools/sdk/include/esp32/esp_ipc.h b/tools/sdk/include/esp32/esp_ipc.h index b229cb33777..477b3d0af4e 100644 --- a/tools/sdk/include/esp32/esp_ipc.h +++ b/tools/sdk/include/esp32/esp_ipc.h @@ -33,21 +33,6 @@ typedef void (*esp_ipc_func_t)(void* arg); * These APIs can only be used when FreeRTOS scheduler is running. */ - -/* - * Initialize inter-processor call module. This function is called automatically - * on CPU start and should not be called from the application. - * - * This function start two tasks, one on each CPU. These tasks are started - * with high priority. These tasks are normally inactive, waiting until one of - * the esp_ipc_call_* functions to be used. One of these tasks will be - * woken up to execute the callback provided to esp_ipc_call_nonblocking or - * esp_ipc_call_blocking. - */ -/** @cond */ -void esp_ipc_init(); -/** @endcond */ - /** * @brief Execute a function on the given CPU * diff --git a/tools/sdk/include/esp32/esp_mesh.h b/tools/sdk/include/esp32/esp_mesh.h index 12e2d55d8f3..e52e541ff86 100644 --- a/tools/sdk/include/esp32/esp_mesh.h +++ b/tools/sdk/include/esp32/esp_mesh.h @@ -26,7 +26,7 @@ * | | ...) | (LwIP) | | | | * | |-----------------------------------| |---------------| | * | | | | - * | | WiFi Driver | | + * | | Wi-Fi Driver | | * | |--------------------------------------------------| | * | | | * | | Platform HAL | @@ -36,7 +36,7 @@ * * |---------------| * | | default handler - * | WiFi stack | events |---------------------| + * | Wi-Fi stack | events |---------------------| * | | -------------> | | * |---------------| | | * | event task | @@ -58,27 +58,27 @@ * Mesh Stack * * Mesh event defines almost all system events applications tasks need. - * Mesh event contains WiFi connection states on station interface, children connection states on softAP interface and etc.. + * 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 WiFi station connect states to decide when to send data to its parent, to root or to external IP network; - * (2)Applications could use WiFi softAP states to decide when to send data to its children. + * (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 nodes don't require LwIP stack. But since IDF hasn't supported system without initializing LwIP stack yet, + * 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. + * (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 root is able to access external IP network. - * In application mesh event handler, once a node becomes a root, start DHCP client immediately if DHCP is chosen. + * 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__ @@ -100,9 +100,9 @@ extern "C" { #define MESH_MTU (1500) /**< max transmit unit(in bytes) */ #define MESH_MPS (1472) /**< max payload size(in bytes) */ /** - * @brief mesh error code definition + * @brief Mesh error code definition */ -#define ESP_ERR_MESH_WIFI_NOT_START (ESP_ERR_MESH_BASE + 1) /**< WiFi isn't started */ +#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 */ @@ -120,32 +120,41 @@ extern "C" { #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 WiFi interface error */ +#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 */ /** - * @brief flags used with esp_mesh_send() and esp_mesh_recv() + * @brief Flags bitmap for esp_mesh_send() and esp_mesh_recv() */ -#define MESH_DATA_ENC (0x01) /**< data encrypted(Unimplemented) */ +#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 root having been changed, identify this packet can be dropped by new root */ +#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() + * @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 must have payload */ +#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 */ + /******************************************************* * Enumerations *******************************************************/ /** - * @brief enumerated list of mesh event id + * @brief Enumerated list of mesh event id */ typedef enum { MESH_EVENT_STARTED, /**< mesh is started */ @@ -157,35 +166,47 @@ typedef enum { 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_PARNET_FOUND, /**< no parent found */ + MESH_EVENT_NO_PARENT_FOUND, /**< no parent found */ MESH_EVENT_LAYER_CHANGE, /**< layer changes over the mesh network */ - MESH_EVENT_TODS_STATE, /**< state represents if 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 root */ + 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_GOT_IP, /**< root obtains the IP address. It is posted by LwIP stack automatically */ - MESH_EVENT_ROOT_LOST_IP, /**< root loses the IP address. It is posted by LwIP stack automatically */ - MESH_EVENT_ROOT_ASKED_YIELD, /**< root is asked yield by a more powerful existing root. If self organized is disabled + MESH_EVENT_ROOT_GOT_IP, /**< the root obtains the IP address. It is posted by LwIP stack automatically */ + MESH_EVENT_ROOT_LOST_IP, /**< the root loses the IP address. It is posted by LwIP stack automatically */ + 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_MAX, } mesh_event_id_t; /** - * @brief node type + * @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 node. Has the ability to forward packets over the mesh network */ + MESH_NODE, /**< intermediate device. Has the ability to forward packets over the mesh network */ MESH_LEAF, /**< has no forwarding ability */ } mesh_type_t; /** - * @brief protocol of transmitted application data + * @brief Protocol of transmitted application data */ typedef enum { MESH_PROTO_BIN, /**< binary */ @@ -195,33 +216,38 @@ typedef enum { } mesh_proto_t; /** - * @brief for reliable transmission, mesh stack provides three type of services + * @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_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 + * @brief Vote reason */ typedef enum { - MESH_VOTE_REASON_ROOT_INITIATED = 1, /**< vote is initiated by root */ + 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 + * @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 node 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_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; /******************************************************* @@ -236,7 +262,7 @@ typedef struct { } __attribute__((packed)) mip_t; /** - * @brief mesh address + * @brief Mesh address */ typedef union { uint8_t addr[6]; /**< mac address */ @@ -244,78 +270,86 @@ typedef union { } mesh_addr_t; /** - * @brief channel switch information + * @brief Channel switch information */ typedef struct { uint8_t channel; /**< new channel */ } mesh_event_channel_switch_t; /** - * @brief parent connected information + * @brief Parent connected information */ typedef struct { - system_event_sta_connected_t connected; /**< parent information, same as WiFi event SYSTEM_EVENT_STA_CONNECTED does */ + system_event_sta_connected_t connected; /**< parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does */ uint8_t self_layer; /**< layer */ } mesh_event_connected_t; /** - * @brief no parent found information + * @brief No parent found information */ typedef struct { int scan_times; /**< scan times being through */ } mesh_event_no_parent_found_t; /** - * @brief layer change information + * @brief Layer change information */ typedef struct { uint8_t new_layer; /**< new layer */ } mesh_event_layer_change_t; /** - * @brief the reachability of root to a DS(distribute system) + * @brief The reachability of the root to a DS (distribute system) */ typedef enum { - MESH_TODS_UNREACHABLE, /**< root isn't able to access external IP network */ - MESH_TODS_REACHABLE, /**< root is able to access external IP network */ + 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 root itself */ + 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 IP settings from LwIP stack */ typedef system_event_sta_got_ip_t mesh_event_root_got_ip_t; /** - * @brief root address + * @brief Root address */ typedef mesh_addr_t mesh_event_root_address_t; /** - * @brief parent disconnected information + * @brief Parent disconnected information */ typedef system_event_sta_disconnected_t mesh_event_disconnected_t; /** - * @brief child connected information + * @brief Child connected information */ typedef system_event_ap_staconnected_t mesh_event_child_connected_t; /** - * @brief child disconnected information + * @brief Child disconnected information */ typedef system_event_ap_stadisconnected_t mesh_event_child_disconnected_t; /** - * @brief root switch request information + * @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() */ @@ -323,16 +357,16 @@ typedef struct { } mesh_event_root_switch_req_t; /** - * @brief other powerful root address + * @brief Other powerful root address */ typedef struct { int8_t rssi; /**< rssi with router */ - uint16_t capacity; /**< the number of nodes in its network */ + 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 + * @brief Routing table change */ typedef struct { uint16_t rt_size_new; /**< the new value */ @@ -340,7 +374,33 @@ typedef struct { } mesh_event_routing_table_change_t; /** - * @brief mesh event information + * @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 system_event_sta_connected_t mesh_event_router_switch_t; + +/** + * @brief Mesh event information */ typedef union { mesh_event_channel_switch_t channel_switch; /**< channel switch */ @@ -351,19 +411,24 @@ typedef union { 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, nodes should check this state firstly before trying to send packets to - external IP network. This state indicates right now if root is capable - of sending packets out. If not, nodes had better to wait until this state changes - to be MESH_TODS_REACHABLE. */ + 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_got_ip_t got_ip; /**< root obtains IP address */ 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_info_t; /** - * @brief mesh event + * @brief Mesh event */ typedef struct { mesh_event_id_t id; /**< mesh event id */ @@ -371,14 +436,14 @@ typedef struct { } mesh_event_t; /** - * @brief mesh event callback handler prototype definition + * @brief Mesh event callback handler prototype definition * * @param event mesh_event_t */ typedef void (*mesh_event_cb_t)(mesh_event_t event); /** - * @brief mesh option + * @brief Mesh option */ typedef struct { uint8_t type; /**< option type */ @@ -387,7 +452,7 @@ typedef struct { } __attribute__((packed)) mesh_opt_t; /** - * @brief mesh data for esp_mesh_send() and esp_mesh_recv() + * @brief Mesh data for esp_mesh_send() and esp_mesh_recv() */ typedef struct { uint8_t *data; /**< data */ @@ -397,17 +462,23 @@ typedef struct { } mesh_data_t; /** - * @brief router configuration + * @brief Router configuration */ typedef struct { - uint8_t ssid[32]; /**< SSID */ - uint8_t ssid_len; /**< length of SSID */ - uint8_t bssid[6]; /**< BSSID, if router is hidden, this value is mandatory */ - uint8_t password[64]; /**< password */ + 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 + * @brief Mesh softAP configuration */ typedef struct { uint8_t password[64]; /**< mesh softAP password */ @@ -415,10 +486,12 @@ typedef struct { } mesh_ap_cfg_t; /** - * @brief mesh initialization configuration + * @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_event_cb_t event_cb; /**< mesh event callback */ mesh_addr_t mesh_id; /**< mesh network identification */ mesh_router_t router; /**< router configuration */ @@ -427,27 +500,37 @@ typedef struct { } mesh_cfg_t; /** - * @brief vote + * @brief Vote address configuration */ typedef union { - int attempts; /**< max vote attempts */ - mesh_addr_t rc_addr; /**< root address specified by users for API esp_mesh_waive_root() */ + 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 + * @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_parent_p2p; /**< to parent (P2P) queue */ int to_child; /**< to child queue */ - int to_child_p2p; /**< to child(P2P) 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 + * @brief The number of packets available in the queue waiting to be received by applications */ typedef struct { int toDS; /**< to external DS */ @@ -457,7 +540,7 @@ typedef struct { /******************************************************* * Variable Declaration *******************************************************/ -/* mesh vendor IE crypto callback function */ +/* mesh IE crypto callback function */ extern const mesh_crypto_funcs_t g_wifi_default_mesh_crypto_funcs; /* mesh event callback handler */ @@ -471,11 +554,11 @@ extern mesh_event_cb_t g_mesh_event_cb; * Function Definitions *******************************************************/ /** - * @brief mesh initialization - * Check if WiFi is started. - * Initialize mesh global variables with default values. + * @brief Mesh initialization + * - Check whether Wi-Fi is started. + * - Initialize mesh global variables with default values. * - * @attention This API should be called after WiFi is started. + * @attention This API shall be called after Wi-Fi is started. * * @return * - ESP_OK @@ -484,8 +567,9 @@ extern mesh_event_cb_t g_mesh_event_cb; esp_err_t esp_mesh_init(void); /** - * @brief mesh de-initialization - * Release resources and stop the mesh + * @brief Mesh de-initialization + * + * - Release resources and stop the mesh * * @return * - ESP_OK @@ -494,13 +578,13 @@ esp_err_t esp_mesh_init(void); esp_err_t esp_mesh_deinit(void); /** - * @brief start mesh - * Initialize mesh vendor IE - * Start mesh network management service - * Create TX and RX queues according to the configuration - * Register mesh packets receive callback + * @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 should be called after esp_mesh_init() and esp_mesh_set_config(). + * @attention  This API shall be called after mesh initialization and configuration. * * @return * - ESP_OK @@ -512,15 +596,15 @@ esp_err_t esp_mesh_deinit(void); esp_err_t esp_mesh_start(void); /** - * @brief stop mesh - * Deinitialize mesh vendor 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 WiFi softAP to default settings if WiFi dual mode is enabled + * @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. * * @return * - ESP_OK @@ -529,40 +613,43 @@ esp_err_t esp_mesh_start(void); esp_err_t esp_mesh_stop(void); /** - * @brief send a packet over the mesh network - * Send a packet to any node in the mesh network. - * Send a packet to external IP network. - * - * @attention This API is not reentrant. - * - * @param to the address of the final destination of the packet - * (1)if the packet is to root, just set "to" to NULL and set flag to zero. - * (2)if the packet is outgoing to external IP network such as an IP server address, translate IPv4:PORT known as "to". - * This packet will be delivered to root firstly, then root will forward this packet to the final IP server address. - * @param data pointer to a sending mesh packet - * Should specify the data protocol applications used, binary by default. - * Should specify the transmission tos(type of service), P2P reliable by default. - * @param flag - * (1)used to speed up the route selection - * if the packet is target to an internal node, MESH_DATA_P2P should be set. - * if the packet is outgoing to root or to external IP network, MESH_DATA_TODS should be set. - * if the packet is from root to an internal node, MESH_DATA_FROMDS should be set. - * (2)specify if this API is block or non-block, block by default - * if needs non-block, MESH_DATA_NONBLOCK should be set. - * (3)in the situation of root having been changed, MESH_DATA_DROP identifies this packet can be dropped by new root - * for upstream data to external IP network, we try our best to avoid data loss caused by root having been changed, but - * there is a risk that 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 opt options - * (1)in case of sending a packet to a specified group, MESH_OPT_SEND_GROUP is a good choice. - * In this option, the value field should specify the target receiver addresses in this group. - * (2)root sends a packet to an internal node, this packet is from external IP network in case the receiver node responds - * this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. - * @param opt_count option count - * Currently, this API only takes one option, so opt_count is only supported to be 1. + * @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 @@ -579,24 +666,29 @@ esp_err_t esp_mesh_stop(void); * - ESP_ERR_MESH_DISCARD */ esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, - const int flag, const mesh_opt_t opt[], const int opt_count); + int flag, const mesh_opt_t opt[], int opt_count); /** - * @brief receive a packet targeted to self over the mesh network - * 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. + * @brief Receive a packet targeted to self over the mesh network * - * @param from the address of the original source of the packet - * @param data pointer to the received mesh packet - * Contain the protocol and applications should follow it to parse the data. - * @param timeout_ms wait time if a packet isn't immediately available(0:no wait, portMAX_DELAY:wait forever) - * @param flag - * MESH_DATA_FROMDS represents data from external IP network - * MESH_DATA_TODS represents data directed upward within the mesh network - * @param opt options desired to receive - * MESH_OPT_RECV_DS_ADDR attaches the DS address - * @param opt_count option count desired to receive - * Currently, this API only takes one option, so opt_count is only supported to be 1. + * @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 @@ -609,29 +701,33 @@ 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 root. - * Use esp_mesh_set_xon_qsize() could configure the RX queue size, default:72. 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 root. - * - * @param from the address of the original source of the packet - * @param to the address contains remote IP address and port(IPv4:PORT) - * @param data pointer to the received packet - * Contain the protocol and applications should follow it to parse the data. - * @param timeout_ms wait time if a packet isn't immediately available(0:no wait, portMAX_DELAY:wait forever) - * @param flag - * MESH_DATA_TODS represents data to external IP network - * @param opt options desired to receive - * @param opt_count option count desired to receive + * @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 @@ -645,24 +741,26 @@ esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, int opt_count); /** - * @brief set mesh stack configuration - * Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh vendor 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 root to guarantee nodes in different mesh network could communicate with each other. - * max_connection of mesh softAP is limited by the max number of WiFi softAP supported(max:10). + * @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 should be called between esp_mesh_init() and esp_mesh_start(). + * @attention This API shall be called before mesh is started after mesh is initialized. * - * @param config pointer to mesh stack configuration + * @param[in] config pointer to mesh stack configuration * * @return * - ESP_OK @@ -672,9 +770,9 @@ esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, esp_err_t esp_mesh_set_config(const mesh_cfg_t *config); /** - * @brief get mesh stack configuration + * @brief Get mesh stack configuration * - * @param config pointer to mesh stack configuration + * @param[out] config pointer to mesh stack configuration * * @return * - ESP_OK @@ -683,11 +781,11 @@ esp_err_t esp_mesh_set_config(const mesh_cfg_t *config); esp_err_t esp_mesh_get_config(mesh_cfg_t *config); /** - * @brief set router configuration + * @brief Get router configuration * - * @attention This API should be called between esp_mesh_init() and esp_mesh_start(). + * @attention This API is used to dynamically modify the router configuration after mesh is configured. * - * @param router pointer to router configuration + * @param[in] router pointer to router configuration * * @return * - ESP_OK @@ -696,9 +794,9 @@ esp_err_t esp_mesh_get_config(mesh_cfg_t *config); esp_err_t esp_mesh_set_router(const mesh_router_t *router); /** - * @brief get router configuration + * @brief Get router configuration * - * @param router pointer to router configuration + * @param[out] router pointer to router configuration * * @return * - ESP_OK @@ -707,11 +805,11 @@ esp_err_t esp_mesh_set_router(const mesh_router_t *router); esp_err_t esp_mesh_get_router(mesh_router_t *router); /** - * @brief set mesh network ID + * @brief Set mesh network ID * - * @attention This API should be called between esp_mesh_init() and esp_mesh_start(). + * @attention This API is used to dynamically modify the mesh network ID. * - * @param id pointer to mesh network ID + * @param[in] id pointer to mesh network ID * * @return * - ESP_OK @@ -720,9 +818,9 @@ esp_err_t esp_mesh_get_router(mesh_router_t *router); esp_err_t esp_mesh_set_id(const mesh_addr_t *id); /** - * @brief get mesh network ID + * @brief Get mesh network ID * - * @param id pointer to mesh network ID + * @param[out] id pointer to mesh network ID * * @return * - ESP_OK @@ -731,121 +829,122 @@ esp_err_t esp_mesh_set_id(const mesh_addr_t *id); esp_err_t esp_mesh_get_id(mesh_addr_t *id); /** - * @brief set node type over the mesh network(Unimplemented) + * @brief Designate device type over the mesh network + * - MESH_ROOT: designates the root node for a mesh network + * - MESH_LEAF: designates a device as a standalone Wi-Fi station * - * @param type node type + * @param[in] type device type * * @return * - ESP_OK * - ESP_ERR_MESH_NOT_ALLOWED */ -esp_err_t esp_mesh_set_type(const mesh_type_t type); +esp_err_t esp_mesh_set_type(mesh_type_t type); /** - * @brief get node type over mesh network + * @brief Get device type over mesh network * - * @attention This API should be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. * - * @return mesh type + * @return mesh type * */ mesh_type_t esp_mesh_get_type(void); /** - * @brief set max layer configuration(max:15, default:15) + * @brief Set network max layer value (max:25, default:25) + * - Network max layer limits the max hop count. * - * @attention This API should be called before esp_mesh_start(). + * @attention This API shall be called before mesh is started. * - * @param max_layer max layer value + * @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(const int max_layer); +esp_err_t esp_mesh_set_max_layer(int max_layer); /** - * @brief get max layer configuration + * @brief Get max layer value * - * @return max layer value + * @return max layer value */ int esp_mesh_get_max_layer(void); /** - * @brief set mesh softAP password + * @brief Set mesh softAP password * - * @attention This API should be called before esp_mesh_start(). + * @attention This API shall be called before mesh is started. * - * @param pwd pointer to the password - * @param len password length + * @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, const int len); +esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len); /** - * @brief set mesh softAP authentication mode value + * @brief Set mesh softAP authentication mode * - * @attention This API should be called before esp_mesh_start(). + * @attention This API shall be called before mesh is started. * - * @param authmode authentication mode + * @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(const wifi_auth_mode_t authmode); +esp_err_t esp_mesh_set_ap_authmode(wifi_auth_mode_t authmode); /** - * @brief get mesh softAP authentication mode - * - * @return authentication mode + * @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 + * @brief Set mesh softAP max connection value * - * @attention This API should be called before esp_mesh_start(). + * @attention This API shall be called before mesh is started. * - * @param connections the number of max connections + * @param[in] connections the number of max connections * * @return * - ESP_OK * - ESP_ERR_MESH_ARGUMENT */ -esp_err_t esp_mesh_set_ap_connections(const int connections); +esp_err_t esp_mesh_set_ap_connections(int connections); /** - * @brief get mesh softAP max connection configuration - * - * @return the number of max 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 + * @brief Get current layer value over the mesh network * - * @attention This API should be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. * - * @return layer value + * @return layer value * */ int esp_mesh_get_layer(void); /** - * @brief get parent BSSID + * @brief Get the parent BSSID * - * @attention This API should be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. * - * @param bssid pointer to parent BSSID + * @param[out] bssid pointer to parent BSSID * * @return * - ESP_OK @@ -854,127 +953,139 @@ int esp_mesh_get_layer(void); esp_err_t esp_mesh_get_parent_bssid(mesh_addr_t *bssid); /** - * @brief return if the node is root - * - * @return true/false + * @brief Return whether the device is the root node of the network * + * @return true/false */ bool esp_mesh_is_root(void); /** - * @brief enable/disable mesh networking self-organized, self-organized by default - * if self-organized is disabled, users should set a parent for this node via - * esp_mesh_set_parent()(Unimplemented); + * @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(). * - * @param enable + * @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(const bool enable); +esp_err_t esp_mesh_set_self_organized(bool enable, bool select_parent); /** - * @brief return if mesh networking is self-organized or not - * - * @return true/false + * @brief Return whether enable self-organized networking or not * + * @return true/false */ bool esp_mesh_get_self_organized(void); /** - * @brief root waive itself - * A node is elected to be a root during the networking mostly because it has a strong RSSI with router. - * If such superior conditions change, users could call this API to perform a root switch. + * @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. * - * 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 attempts(at least 10 times), 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 acknowledgement. - * 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. - * So far, root switch is completed with minimal disruption to the whole mesh network. + * Root switch is completed with minimal disruption to the whole mesh network. * - * @attention This API is only called by root. + * @attention This API is only called by the root. * - * @param vote vote configuration - * Specify a desired root address(Unimplemented) - * Attempts should be at least 10 times. - * if "vote" is set NULL, the vote will perform the default 10 times. - * @param reason only accept MESH_VOTE_REASON_ROOT_INITIATED for now + * @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, const int reason); +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 - * During the networking, only obtaining vote percentage reaches this threshold, - * the node could be a root. + * @brief Set vote percentage threshold for approval of being a root + * - During the networking, only obtaining vote percentage reaches this threshold, + * the device could be a root. * - * @attention This API should be called before esp_mesh_start(). + * @attention This API shall be called before mesh is started. * - * @param percentage vote percentage threshold + * @param[in] percentage vote percentage threshold * * @return * - ESP_OK * - ESP_FAIL */ -esp_err_t esp_mesh_set_vote_percentage(const float percentage); +esp_err_t esp_mesh_set_vote_percentage(float percentage); /** - * @brief get vote percentage threshold for approval of being a root + * @brief Get vote percentage threshold for approval of being a root * - * @return percentage threshold + * @return percentage threshold */ float esp_mesh_get_vote_percentage(void); /** - * @brief set mesh softAP associate expired time - * 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. + * @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 seconds + * @param[in] seconds the expired time * * @return * - ESP_OK * - ESP_FAIL */ -esp_err_t esp_mesh_set_ap_assoc_expire(const int seconds); +esp_err_t esp_mesh_set_ap_assoc_expire(int seconds); /** - * @brief get mesh softAP associate expired time + * @brief Get mesh softAP associate expired time * - * @return seconds + * @return seconds */ int esp_mesh_get_ap_assoc_expire(void); /** - * @brief get total number of nodes over the mesh network(including root) + * @brief Get total number of devices in current network (including the root) * - * @attention The returned value might be incorrect when the network is changing. + * @attention The returned value might be incorrect when the network is changing. ** - * @return total number of nodes(including root) + * @return total number of devices (including the root) */ int esp_mesh_get_total_node_num(void); /** - * @brief get the number of nodes in routing table(including self) + * @brief Get the number of devices in this device's sub-network (including self) * - * @return the number of nodes in routing table(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(including itself) + * @brief Get routing table of this device's sub-network (including itself) * - * @param mac pointer to routing table - * @param len routing table size(in bytes) - * @param size pointer to the number of nodes in routing table(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 @@ -983,22 +1094,22 @@ int esp_mesh_get_routing_table_size(void); 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 + * @brief Post the toDS state to the mesh stack * - * @attention This API is only for root. + * @attention This API is only for the root. * - * @param reachable this state represents if root is able to access external IP network + * @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(const bool reachable); +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 + * @brief Return the number of packets pending in the queue waiting to be sent by the mesh stack * - * @param pending pointer to the TX pending + * @param[out] pending pointer to the TX pending * * @return * - ESP_OK @@ -1007,9 +1118,9 @@ esp_err_t esp_mesh_post_toDS_state(const bool reachable); 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 + * @brief Return the number of packets available in the queue waiting to be received by applications * - * @param pending pointer to the RX pending + * @param[out] pending pointer to the RX pending * * @return * - ESP_OK @@ -1018,21 +1129,21 @@ esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending); 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 + * @brief Return the number of packets could be accepted from the specified address * - * @param addr self address or an associate children address - * @param xseqno_in sequence number of the last received packet 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 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 queue size + * @brief Set the number of queue * - * @attention This API should be called before esp_mesh_start(). + * @attention This API shall be called before mesh is started. * - * @param qsize default:72(min:36, max:105) + * @param[in] qsize default:32 (min:16) * * @return * - ESP_OK @@ -1041,80 +1152,87 @@ int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in); esp_err_t esp_mesh_set_xon_qsize(int qsize); /** - * @brief get queue size + * @brief Get queue size * - * @return qsize + * @return the number of queue */ int esp_mesh_get_xon_qsize(void); /** - * @brief set if allow more than one root existing in one network + * @brief Set whether allow more than one root existing in one network * - * @param allowed allow or not + * @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(const bool allowed); +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 + * @brief Set group ID addresses * - * @param addr pointer to new addresses - * @param num number of 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, const int num); +esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num); /** - * @brief delete group ID addresses + * @brief Delete group ID addresses * - * @param addr pointer to deleted address - * @param num number of 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, const int num); +esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, int num); /** - * @brief get the number of group ID addresses + * @brief Get the number of group ID addresses * - * @return 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 + * @brief Get group ID addresses * - * @param addr pointer to group address - * @param num number of 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, const int num); +esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num); /** - * @brief check if the specified group address is my group + * @brief Check whether the specified group address is my group * - * @return true/false + * @return true/false */ bool esp_mesh_is_my_group(const mesh_addr_t *addr); /** - * @brief set mesh network capacity + * @brief Set mesh network capacity (max:1000, default:300) * - * @attention This API should be called before esp_mesh_start(). + * @attention This API shall be called before mesh is started. * - * @param num mesh network capacity + * @param[in] num mesh network capacity * * @return * - ESP_OK @@ -1124,53 +1242,54 @@ bool esp_mesh_is_my_group(const mesh_addr_t *addr); esp_err_t esp_mesh_set_capacity_num(int num); /** - * @brief get mesh network capacity + * @brief Get mesh network capacity * - * @return mesh network capacity + * @return mesh network capacity */ int esp_mesh_get_capacity_num(void); /** - * @brief set mesh ie crypto functions + * @brief Set mesh IE crypto functions * - * @param crypto_funcs crypto functions for mesh ie + * @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 + * @brief Set mesh IE crypto key * - * @attention This API should be called before esp_mesh_start(). + * @attention This API can be called at any time after mesh is initialized. * - * @param key crypto key - * @param len the present implementation only supports 32 + * @param[in] key ASCII crypto key + * @param[in] len length in bytes, range:8~64 * * @return * - ESP_OK - * - ESP_ERR_MESH_NOT_ALLOWED * - ESP_MESH_ERR_ARGUMENT */ -esp_err_t esp_mesh_set_ie_crypto_key(const uint8_t *key, int len); +esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len); /** - * @brief get mesh ie crypto key + * @brief Get mesh IE crypto key * - * @param key crypto key - * @param len the present implementation only supports 32 + * @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(uint8_t *key, int len); +esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len); /** - * @brief set delay time before starting root healing + * @brief Set delay time before starting root healing * - * @param delay_ms delay time in milliseconds + * @param[in] delay_ms delay time in milliseconds * * @return * - ESP_OK @@ -1178,22 +1297,194 @@ esp_err_t esp_mesh_get_ie_crypto_key(uint8_t *key, int len); esp_err_t esp_mesh_set_root_healing_delay(int delay_ms); /** - * @brief get delay time before starting root healing + * @brief Get delay time before network starts root healing * - * @return delay time in milliseconds + * @return delay time in milliseconds */ int esp_mesh_get_root_healing_delay(void); /** - * @brief set mesh event callback + * @brief Set mesh event callback * - * @param event_cb mesh event call back + * @param[in] event_cb mesh event call back * * @return * - ESP_OK */ esp_err_t esp_mesh_set_event_cb(const mesh_event_cb_t event_cb); +/** + * @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 + * - 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); #ifdef __cplusplus } diff --git a/tools/sdk/include/esp32/esp_mesh_internal.h b/tools/sdk/include/esp32/esp_mesh_internal.h index 19273ba06da..e061c457725 100644 --- a/tools/sdk/include/esp32/esp_mesh_internal.h +++ b/tools/sdk/include/esp32/esp_mesh_internal.h @@ -34,28 +34,75 @@ extern "C" { *******************************************************/ typedef struct { int scan; /**< minimum scan times before being a root, default:10 */ - int vote; /**< max vote times in self-healing, default:10000 */ + int vote; /**< max vote times in self-healing, default:1000 */ int fail; /**< parent selection fail times, if the scan times reach this value, - will disconnect with associated children and join self-healing. default:60 */ - int monitor_ie; /**< acceptable times of parent ie change before update self ie, default:3 */ + 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, - will switch to a better parent */ - int cnx_rssi; /* RSSI threshold for keeping a good connection with parent */ - int select_rssi; /* RSSI threshold for parent selection, should be a value greater than switch_rssi */ - int switch_rssi; /* RSSI threshold for action to reselect a better parent */ + 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; + /******************************************************* * Function Definitions *******************************************************/ /** - * @brief set mesh softAP beacon interval + * @brief Set mesh softAP beacon interval * - * @param interval beacon interval(ms) (100ms ~ 60000ms) + * @param[in] interval beacon interval (msecs) (100 msecs ~ 60000 msecs) * * @return * - ESP_OK @@ -65,9 +112,9 @@ typedef struct { esp_err_t esp_mesh_set_beacon_interval(int interval_ms); /** - * @brief get mesh softAP beacon interval + * @brief Get mesh softAP beacon interval * - * @param interval beacon interval(ms) + * @param[out] interval beacon interval (msecs) * * @return * - ESP_OK @@ -75,9 +122,9 @@ esp_err_t esp_mesh_set_beacon_interval(int interval_ms); esp_err_t esp_mesh_get_beacon_interval(int *interval_ms); /** - * @brief set attempts for mesh self-organized networking + * @brief Set attempts for mesh self-organized networking * - * @param attempts + * @param[in] attempts * * @return * - ESP_OK @@ -86,40 +133,77 @@ esp_err_t esp_mesh_get_beacon_interval(int *interval_ms); esp_err_t esp_mesh_set_attempts(mesh_attempts_t *attempts); /** - * @brief get attempts for mesh self-organized networking + * @brief Get attempts for mesh self-organized networking * - * @param attempts + * @param[out] attempts * * @return * - ESP_OK - * - ESP_FAIL + * - ESP_ERR_MESH_ARGUMENT */ esp_err_t esp_mesh_get_attempts(mesh_attempts_t *attempts); /** - * @brief set parameters for parent switch + * @brief Set parameters for parent switch * - * @param paras parameters for parent switch + * @param[in] paras parameters for parent switch * * @return * - ESP_OK - * - ESP_FAIL + * - ESP_ERR_MESH_ARGUMENT */ esp_err_t esp_mesh_set_switch_parent_paras(mesh_switch_parent_t *paras); /** - * @brief get parameters for parent switch + * @brief Get parameters for parent switch * - * @param paras parameters for parent switch + * @param[out] paras parameters for parent switch * * @return * - ESP_OK - * - ESP_FAIL + * - ESP_ERR_MESH_ARGUMENT */ esp_err_t esp_mesh_get_switch_parent_paras(mesh_switch_parent_t *paras); /** - * @brief print the number of txQ waiting + * @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 @@ -128,7 +212,7 @@ esp_err_t esp_mesh_get_switch_parent_paras(mesh_switch_parent_t *paras); esp_err_t esp_mesh_print_txQ_waiting(void); /** - * @brief print the number of rxQ waiting + * @brief Print the number of rxQ waiting * * @return * - ESP_OK @@ -137,9 +221,9 @@ esp_err_t esp_mesh_print_txQ_waiting(void); esp_err_t esp_mesh_print_rxQ_waiting(void); /** - * @brief set passive scan time + * @brief Set passive scan time * - * @param interval_ms passive scan time(ms) + * @param[in] interval_ms passive scan time (msecs) * * @return * - ESP_OK @@ -149,12 +233,35 @@ esp_err_t esp_mesh_print_rxQ_waiting(void); esp_err_t esp_mesh_set_passive_scan_time(int time_ms); /** - * @brief get passive scan time + * @brief Get passive scan time * - * @return interval_ms passive scan time(ms) + * @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); #ifdef __cplusplus } diff --git a/tools/sdk/include/esp32/esp_panic.h b/tools/sdk/include/esp32/esp_panic.h index 4e0630a2458..b9e192f0462 100644 --- a/tools/sdk/include/esp32/esp_panic.h +++ b/tools/sdk/include/esp32/esp_panic.h @@ -61,12 +61,6 @@ esp_err_t esp_set_watchpoint(int no, void *adr, int size, int flags); */ void esp_clear_watchpoint(int no); - -/** - * @brief Stops panic WDT - */ -void esp_panic_wdt_stop(void); - /** * @brief Checks stack pointer */ diff --git a/tools/sdk/include/esp32/esp_phy_init.h b/tools/sdk/include/esp32/esp_phy_init.h index 75cb8fb58e7..2dfb7447da4 100644 --- a/tools/sdk/include/esp32/esp_phy_init.h +++ b/tools/sdk/include/esp32/esp_phy_init.h @@ -37,7 +37,9 @@ typedef struct { * @brief Opaque PHY calibration data */ typedef struct { - uint8_t opaque[1904]; /*!< calibration data */ + 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 { @@ -56,6 +58,7 @@ typedef enum{ MODEM_WIFI_STATION_MODULE, //!< Wi-Fi Station used MODEM_WIFI_SOFTAP_MODULE, //!< Wi-Fi SoftAP used MODEM_WIFI_SNIFFER_MODULE, //!< Wi-Fi Sniffer used + MODEM_WIFI_NULL_MODULE, //!< Wi-Fi Null mode used MODEM_USER_MODULE, //!< User used MODEM_MODULE_COUNT //!< Number of items }modem_sleep_module_t; @@ -71,7 +74,8 @@ typedef enum{ */ #define MODEM_WIFI_MASK ((1< #include +#include #include "esp_err.h" +typedef enum { + ESP_SPIRAM_SIZE_16MBITS = 0, /*!< SPI RAM size is 16 MBits */ + ESP_SPIRAM_SIZE_32MBITS = 1, /*!< SPI RAM size is 32 MBits */ + ESP_SPIRAM_SIZE_64MBITS = 2, /*!< SPI RAM size is 64 MBits */ + ESP_SPIRAM_SIZE_INVALID, /*!< SPI RAM size is invalid */ +} esp_spiram_size_t; + +/** + * @brief get SPI RAM size + * @return + * - ESP_SPIRAM_SIZE_INVALID if SPI RAM not enabled or not valid + * - SPI RAM size + */ +esp_spiram_size_t esp_spiram_get_chip_size(); + /** * @brief Initialize spiram interface/hardware. Normally called from cpu_start.c. * @@ -41,7 +57,7 @@ void esp_spiram_init_cache(); /** * @brief Memory test for SPI RAM. Should be called after SPI RAM is initialized and - * (in case of a dual-core system) the app CPU is online. This test overwrites the + * (in case of a dual-core system) the app CPU is online. This test overwrites the * memory with crap, so do not call after e.g. the heap allocator has stored important * stuff in SPI RAM. * @@ -87,4 +103,14 @@ void esp_spiram_writeback_cache(); esp_err_t esp_spiram_reserve_dma_pool(size_t size); +/** + * @brief If SPI RAM(PSRAM) has been initialized + * + * @return + * - true SPI RAM has been initialized successfully + * - false SPI RAM hasn't been initialized or initialized failed + */ +bool esp_spiram_is_initialized(void); + + #endif diff --git a/tools/sdk/include/esp32/esp_system.h b/tools/sdk/include/esp32/esp_system.h index 0d57d84d842..05214c8f57b 100644 --- a/tools/sdk/include/esp32/esp_system.h +++ b/tools/sdk/include/esp32/esp_system.h @@ -31,12 +31,32 @@ typedef enum { ESP_MAC_ETH, } esp_mac_type_t; +/** @cond */ #define TWO_UNIVERSAL_MAC_ADDR 2 #define FOUR_UNIVERSAL_MAC_ADDR 4 #define UNIVERSAL_MAC_ADDR_NUM CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS +/** @endcond */ /** - * @attention application don't need to call this function anymore. It do nothing and will + * @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; + +/** @cond */ +/** + * @attention Applications don't need to call this function anymore. It does nothing and will * be removed in future version. */ void system_init(void) __attribute__ ((deprecated)); @@ -48,13 +68,18 @@ void system_init(void) __attribute__ ((deprecated)); * This name will be removed in a future release. */ void system_restore(void) __attribute__ ((deprecated)); +/** @endcond */ +/** + * 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 a - * systematic shutdown of the chip. + * This function allows you to register a handler that gets invoked before + * the application is restarted using esp_restart function. */ esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle); @@ -68,17 +93,7 @@ esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle); */ void esp_restart(void) __attribute__ ((noreturn)); -/** - * @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() __attribute__ ((noreturn)); - +/** @cond */ /** * @brief Restart system. * @@ -86,7 +101,15 @@ void esp_restart_noos() __attribute__ ((noreturn)); * This name will be removed in a future release. */ void system_restart(void) __attribute__ ((deprecated, noreturn)); +/** @endcond */ +/** + * @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); + +/** @cond */ /** * @brief Get system time, unit: microsecond. * @@ -94,6 +117,7 @@ void system_restart(void) __attribute__ ((deprecated, noreturn)); * This definition will be removed in a future release. */ uint32_t system_get_time(void) __attribute__ ((deprecated)); +/** @endcond */ /** * @brief Get the size of available heap. @@ -105,6 +129,7 @@ uint32_t system_get_time(void) __attribute__ ((deprecated)); */ uint32_t esp_get_free_heap_size(void); +/** @cond */ /** * @brief Get the size of available heap. * @@ -114,6 +139,7 @@ uint32_t esp_get_free_heap_size(void); * @return Available heap size, in bytes. */ uint32_t system_get_free_heap_size(void) __attribute__ ((deprecated)); +/** @endcond */ /** * @brief Get the minimum heap that has ever been available @@ -125,18 +151,31 @@ 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 secure + * 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. * - * When the app is running without an RF subsystem enabled, it should be considered a PRNG. To help improve this - * situation, the RNG is pre-seeded with entropy while the IDF bootloader is running. However no new entropy is - * available during the window of time between when the bootloader exits and an RF subsystem starts. It may be possible - * to discern a non-random pattern in a very large amount of output captured during this window of time. + * 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. @@ -187,6 +226,7 @@ esp_err_t esp_efuse_mac_get_custom(uint8_t *mac); */ esp_err_t esp_efuse_mac_get_default(uint8_t *mac); +/** @cond */ /** * @brief Read hardware MAC address from efuse. * @@ -209,6 +249,7 @@ esp_err_t esp_efuse_read_mac(uint8_t *mac) __attribute__ ((deprecated)); * @return ESP_OK on success */ esp_err_t system_efuse_read_mac(uint8_t *mac) __attribute__ ((deprecated)); +/** @endcond */ /** * @brief Read base MAC address and set MAC address of the interface. @@ -240,6 +281,7 @@ esp_err_t esp_read_mac(uint8_t* mac, esp_mac_type_t type); */ esp_err_t esp_derive_local_mac(uint8_t* local_mac, const uint8_t* universal_mac); +/** @cond */ /** * Get SDK version * @@ -248,6 +290,7 @@ esp_err_t esp_derive_local_mac(uint8_t* local_mac, const uint8_t* universal_mac) * @return constant string "master" */ const char* system_get_sdk_version(void) __attribute__ ((deprecated)); +/** @endcond */ /** * Get IDF version @@ -264,13 +307,11 @@ typedef enum { CHIP_ESP32 = 1, //!< ESP32 } esp_chip_model_t; -/** - * Chip feature flags, used in esp_chip_info_t - */ -#define CHIP_FEATURE_EMB_FLASH BIT(0) -#define CHIP_FEATURE_WIFI_BGN BIT(1) -#define CHIP_FEATURE_BLE BIT(4) -#define CHIP_FEATURE_BT BIT(5) +/* 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 diff --git a/tools/sdk/include/esp32/esp_task.h b/tools/sdk/include/esp32/esp_task.h index 2f01e610164..754014b5511 100644 --- a/tools/sdk/include/esp32/esp_task.h +++ b/tools/sdk/include/esp32/esp_task.h @@ -27,6 +27,7 @@ #define _ESP_TASK_H_ #include "sdkconfig.h" +#include "freertos/FreeRTOSConfig.h" #define ESP_TASK_PRIO_MAX (configMAX_PRIORITIES) #define ESP_TASK_PRIO_MIN (0) diff --git a/tools/sdk/include/esp32/esp_timer.h b/tools/sdk/include/esp32/esp_timer.h index 07e23721405..ff5c13ab4c1 100644 --- a/tools/sdk/include/esp32/esp_timer.h +++ b/tools/sdk/include/esp32/esp_timer.h @@ -189,6 +189,13 @@ esp_err_t esp_timer_delete(esp_timer_handle_t timer); */ int64_t esp_timer_get_time(); +/** + * @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(); + /** * @brief Dump the list of timers to a stream * diff --git a/tools/sdk/include/esp32/esp_types.h b/tools/sdk/include/esp32/esp_types.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/esp_wifi.h b/tools/sdk/include/esp32/esp_wifi.h old mode 100755 new mode 100644 index beb36e27090..57014b8d9a2 --- a/tools/sdk/include/esp32/esp_wifi.h +++ b/tools/sdk/include/esp32/esp_wifi.h @@ -59,14 +59,10 @@ #include #include -#include "freertos/FreeRTOS.h" -#include "freertos/queue.h" -#include "rom/queue.h" -#include "sdkconfig.h" #include "esp_err.h" #include "esp_wifi_types.h" -#include "esp_wifi_crypto_types.h" #include "esp_event.h" +#include "esp_private/esp_wifi_private.h" #ifdef __cplusplus extern "C" { @@ -88,23 +84,32 @@ extern "C" { #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) /*!< Invalod WiFi state when init/deinit is called */ +#define ESP_ERR_WIFI_STOP_STATE (ESP_ERR_WIFI_BASE + 20) /*!< Returned when WiFi is stopping */ + /** * @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 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 nvs_enable; /**< WiFi NVS flash enable flag */ int nano_enable; /**< Nano option for printf/scan family enable flag */ int tx_ba_win; /**< WiFi Block Ack TX window size */ 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 */ int magic; /**< WiFi init magic number, it should be the last field */ } wifi_init_config_t; @@ -120,6 +125,12 @@ typedef struct { #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 @@ -160,20 +171,43 @@ extern const wpa_crypto_funcs_t g_wifi_default_wpa_crypto_funcs; #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 + #define WIFI_INIT_CONFIG_DEFAULT() { \ .event_handler = &esp_event_send, \ + .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,\ + .csi_enable = WIFI_CSI_ENABLED,\ .ampdu_rx_enable = WIFI_AMPDU_RX_ENABLED,\ .ampdu_tx_enable = WIFI_AMPDU_TX_ENABLED,\ .nvs_enable = WIFI_NVS_ENABLED,\ .nano_enable = WIFI_NANO_FORMAT_ENABLED,\ .tx_ba_win = WIFI_DEFAULT_TX_BA_WIN,\ .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, \ .magic = WIFI_INIT_CONFIG_MAGIC\ }; @@ -204,7 +238,9 @@ esp_err_t esp_wifi_init(const wifi_init_config_t *config); * * @attention 1. This API should be called if you want to remove WiFi driver from the system * - * @return ESP_OK: succeed + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_deinit(void); @@ -284,7 +320,13 @@ esp_err_t esp_wifi_restore(void); * * @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 @@ -347,6 +389,7 @@ esp_err_t esp_wifi_deauth_sta(uint16_t aid); * - 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); @@ -397,6 +440,9 @@ esp_err_t esp_wifi_scan_get_ap_records(uint16_t *number, wifi_ap_record_t *ap_re * @brief Get information of AP which the ESP32 station is associated with * * @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 @@ -406,24 +452,24 @@ esp_err_t esp_wifi_scan_get_ap_records(uint16_t *number, wifi_ap_record_t *ap_re esp_err_t esp_wifi_sta_get_ap_info(wifi_ap_record_t *ap_info); /** - * @brief Set current power save type + * @brief Set current WiFi power save type * - * @attention Default power save type is WIFI_PS_NONE. + * @attention Default power save type is WIFI_PS_MIN_MODEM. * * @param type power save type * - * @return ESP_ERR_NOT_SUPPORTED: not supported yet + * @return ESP_OK: succeed */ esp_err_t esp_wifi_set_ps(wifi_ps_type_t type); /** - * @brief Get current power save type + * @brief Get current WiFi power save type * - * @attention Default power save type is WIFI_PS_NONE. + * @attention Default power save type is WIFI_PS_MIN_MODEM. * * @param[out] type: store current power save type * - * @return ESP_ERR_NOT_SUPPORTED: not supported yet + * @return ESP_OK: succeed */ esp_err_t esp_wifi_get_ps(wifi_ps_type_t *type); @@ -534,7 +580,7 @@ esp_err_t esp_wifi_get_channel(uint8_t *primary, wifi_second_chan_t *second); * 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="USA", .schan=1, .nchan=11} in the example. + * {.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. @@ -671,6 +717,31 @@ esp_err_t esp_wifi_set_promiscuous_filter(const wifi_promiscuous_filter_t *filte */ 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 * @@ -714,6 +785,9 @@ esp_err_t esp_wifi_get_config(wifi_interface_t interface, wifi_config_t *conf); * @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 @@ -751,7 +825,7 @@ esp_err_t esp_wifi_set_storage(wifi_storage_t storage); * - ESP_ERR_WIFI_MODE: WiFi internal error, the station/soft-AP control block is invalid * - others: refer to error code in esp_err.h */ -esp_err_t esp_wifi_set_auto_connect(bool en); +esp_err_t esp_wifi_set_auto_connect(bool en) __attribute__ ((deprecated)); /** * @brief Get the auto connect flag @@ -763,7 +837,17 @@ esp_err_t esp_wifi_set_auto_connect(bool en); * - 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_auto_connect(bool *en); +esp_err_t esp_wifi_get_auto_connect(bool *en) __attribute__ ((deprecated)); + +/** + * @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 @@ -783,16 +867,6 @@ esp_err_t esp_wifi_get_auto_connect(bool *en); */ 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 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 Register Vendor-Specific Information Element monitoring callback. * @@ -806,60 +880,22 @@ typedef void (*esp_vendor_ie_cb_t) (void *ctx, wifi_vendor_ie_type_t type, const esp_err_t esp_wifi_set_vendor_ie_cb(esp_vendor_ie_cb_t cb, void *ctx); /** - * @brief Set maximum WiFi transmiting power - * - * @attention WiFi transmiting power is divided to six levels in phy init data. - * Level0 represents highest transmiting power and level5 represents lowest - * transmiting power. Packets of different rates are transmitted in - * different powers according to the configuration in phy init data. - * This API only sets maximum WiFi transmiting power. If this API is called, - * the transmiting power of every packet will be less than or equal to the - * value set by this API. If this API is not called, the value of maximum - * transmitting power set in phy_init_data.bin or menuconfig (depend on - * whether to use phy init data in partition or not) will be used. Default - * value is level0. Values passed in power are mapped to transmit power - * levels as follows: - * - [78, 127]: level0 - * - [76, 77]: level1 - * - [74, 75]: level2 - * - [68, 73]: level3 - * - [60, 67]: level4 - * - [52, 59]: level5 - * - [44, 51]: level5 - 2dBm - * - [34, 43]: level5 - 4.5dBm - * - [28, 33]: level5 - 6dBm - * - [20, 27]: level5 - 8dBm - * - [8, 19]: level5 - 11dBm - * - [-128, 7]: level5 - 14dBm + * @brief Set maximum WiFi transmitting power * - * @param power Maximum WiFi transmiting power. + * @param power Maximum WiFi transmitting power, unit is 0.25dBm, range is [40, 82] corresponding to 10dBm - 20.5dBm here. * * @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_NOT_ARG: invalid argument */ esp_err_t esp_wifi_set_max_tx_power(int8_t power); /** * @brief Get maximum WiFi transmiting power * - * @attention This API gets maximum WiFi transmiting power. Values got - * from power are mapped to transmit power levels as follows: - * - 78: 19.5dBm - * - 76: 19dBm - * - 74: 18.5dBm - * - 68: 17dBm - * - 60: 15dBm - * - 52: 13dBm - * - 44: 11dBm - * - 34: 8.5dBm - * - 28: 7dBm - * - 20: 5dBm - * - 8: 2dBm - * - -4: -1dBm - * - * @param power Maximum WiFi transmiting power. + * @param power Maximum WiFi transmitting power, unit is 0.25dBm. * * @return * - ESP_OK: succeed @@ -869,6 +905,164 @@ esp_err_t esp_wifi_set_max_tx_power(int8_t power); */ 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); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/esp32/esp_wifi_crypto_types.h b/tools/sdk/include/esp32/esp_wifi_crypto_types.h index c97682daf09..e1e2a51a131 100644 --- a/tools/sdk/include/esp32/esp_wifi_crypto_types.h +++ b/tools/sdk/include/esp32/esp_wifi_crypto_types.h @@ -27,6 +27,8 @@ extern "C" { #endif +#define ESP_WIFI_CRYPTO_VERSION 0x00000001 + /* * Enumeration for hash operations. * When WPA2 is connecting, this enum is used to @@ -80,7 +82,7 @@ typedef esp_crypto_hash_t * (*esp_crypto_hash_init_t)(esp_crypto_hash_alg_t alg, * @param len Length of the buffer. * */ -typedef void * (*esp_crypto_hash_update_t)(esp_crypto_hash_t *ctx, const unsigned char *data, int len); +typedef void (*esp_crypto_hash_update_t)(esp_crypto_hash_t *ctx, const unsigned char *data, int len); /** * @brief The crypto callback function used in wpa enterprise hash operation when connect. @@ -95,7 +97,7 @@ typedef void * (*esp_crypto_hash_update_t)(esp_crypto_hash_t *ctx, const unsigne * or -2 on other failures (including failed crypto_hash_update() operations) * */ -typedef int * (*esp_crypto_hash_finish_t)(esp_crypto_hash_t *ctx, unsigned char *hash, int *len); +typedef int (*esp_crypto_hash_finish_t)(esp_crypto_hash_t *ctx, unsigned char *hash, int *len); /** * @brief The AES callback function when do WPS connect. @@ -105,7 +107,7 @@ typedef int * (*esp_crypto_hash_finish_t)(esp_crypto_hash_t *ctx, unsigned char * @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); +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. @@ -116,7 +118,7 @@ typedef int * (*esp_aes_128_encrypt_t)(const unsigned char *key, const unsigned * @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); +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. @@ -127,7 +129,7 @@ typedef int * (*esp_aes_128_decrypt_t)(const unsigned char *key, const unsigned * @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); +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. @@ -138,7 +140,7 @@ typedef int * (*esp_aes_wrap_t)(const unsigned char *kek, int n, const unsigned * @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); +typedef int (*esp_aes_unwrap_t)(const unsigned char *kek, int n, const unsigned char *cipher, unsigned char *plain); /** * @brief The crypto callback function used in wpa enterprise cipher operation when connect. @@ -162,7 +164,7 @@ typedef esp_crypto_cipher_t * (*esp_crypto_cipher_init_t)(esp_crypto_cipher_alg_ * @param len Length of the plaintext. * */ -typedef int * (*esp_crypto_cipher_encrypt_t)(esp_crypto_cipher_t *ctx, +typedef int (*esp_crypto_cipher_encrypt_t)(esp_crypto_cipher_t *ctx, const unsigned char *plain, unsigned char *crypt, int len); /** * @brief The crypto callback function used in wpa enterprise cipher operation when connect. @@ -174,7 +176,7 @@ typedef int * (*esp_crypto_cipher_encrypt_t)(esp_crypto_cipher_t *ctx, * @param len Length of the cipher text. * */ -typedef int * (*esp_crypto_cipher_decrypt_t)(esp_crypto_cipher_t *ctx, +typedef int (*esp_crypto_cipher_decrypt_t)(esp_crypto_cipher_t *ctx, const unsigned char *crypt, unsigned char *plain, int len); /** * @brief The crypto callback function used in wpa enterprise cipher operation when connect. @@ -183,7 +185,7 @@ typedef int * (*esp_crypto_cipher_decrypt_t)(esp_crypto_cipher_t *ctx, * @param ctx Context pointer from esp_crypto_cipher_init_t callback function. * */ -typedef void * (*esp_crypto_cipher_deinit_t)(esp_crypto_cipher_t *ctx); +typedef void (*esp_crypto_cipher_deinit_t)(esp_crypto_cipher_t *ctx); /** * @brief The SHA256 callback function when do WPS connect. @@ -195,7 +197,7 @@ typedef void * (*esp_crypto_cipher_deinit_t)(esp_crypto_cipher_t *ctx); * @param mac Buffer for the hash (20 bytes). * */ -typedef void * (*esp_hmac_sha256_t)(const unsigned char *key, int key_len, const unsigned char *data, +typedef void (*esp_hmac_sha256_t)(const unsigned char *key, int key_len, const unsigned char *data, int data_len, unsigned char *mac); /** @@ -209,7 +211,7 @@ typedef void * (*esp_hmac_sha256_t)(const unsigned char *key, int key_len, const * @param mac Buffer for the hash (32 bytes). * */ -typedef void * (*esp_hmac_sha256_vector_t)(const unsigned char *key, int key_len, int num_elem, +typedef void (*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); /** @@ -224,7 +226,7 @@ typedef void * (*esp_hmac_sha256_vector_t)(const unsigned char *key, int key_len * @param buf_len Number of bytes of key to generate. * */ -typedef void * (*esp_sha256_prf_t)(const unsigned char *key, int key_len, const char *label, +typedef void (*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); /** @@ -233,10 +235,10 @@ typedef void * (*esp_sha256_prf_t)(const unsigned char *key, int key_len, const * @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. + * @paramac Buffer for the hash. * */ -typedef int * (*esp_sha256_vector_t)(int num_elem, const unsigned char *addr[], const int *len, +typedef int (*esp_sha256_vector_t)(int num_elem, const unsigned char *addr[], const int *len, unsigned char *mac); /** @@ -253,20 +255,471 @@ typedef int * (*esp_sha256_vector_t)(int num_elem, const unsigned char *addr[], * @param result_len Result length (max buffer size on input, real len on output). * */ -typedef int * (*esp_crypto_mod_exp_t)(const unsigned char *base, int base_len, +typedef int (*esp_crypto_mod_exp_t)(const unsigned char *base, int base_len, const unsigned char *power, int power_len, const unsigned char *modulus, int modulus_len, unsigned char *result, unsigned int *result_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 Initialize TLS library + * + * @conf: Configuration data for TLS library + * Returns: Context data to be used as tls_ctx in calls to other functions, + * or %NULL on failure. + * + * Called once during program startup and once for each RSN pre-authentication + * session. In other words, there can be two concurrent TLS contexts. If global + * library initialization is needed (i.e., one that is shared between both + * authentication types), the TLS library wrapper should maintain a reference + * counter and do global initialization only when moving from 0 to 1 reference. + */ +typedef void * (*esp_tls_init_t)(void); + +/** + * @brief Deinitialize TLS library + * + * @tls_ctx: TLS context data from tls_init() + * + * Called once during program shutdown and once for each RSN pre-authentication + * session. If global library deinitialization is needed (i.e., one that is + * shared between both authentication types), the TLS library wrapper should + * maintain a reference counter and do global deinitialization only when moving + * from 1 to 0 references. + */ +typedef void (*esp_tls_deinit_t)(void *tls_ctx); + +/** + * @brief Add certificate and private key for connect + + * @sm: eap state machine + * + * Returns: 0 for success, -1 state machine didn't exist, -2 short of certificate or key + */ +typedef int (*esp_eap_peer_blob_init_t)(void *sm); + +/** + * @brief delete the certificate and private + * + * @sm: eap state machine + * + */ +typedef void (*esp_eap_peer_blob_deinit_t)(void *sm); + +/** + * @brief Initialize the eap state machine + * + * @sm: eap state machine + * @private_key_passwd: the start address of private_key_passwd + * @private_key_passwd_len: length of private_key_password + * + * Returns: 0 is success, -1 state machine didn't exist, -2 short of parameters + * + */ +typedef int (*esp_eap_peer_config_init_t)(void *sm, unsigned char *private_key_passwd,int private_key_passwd_len); + +/** + * @brief Deinit the eap state machine + * + * @sm: eap state machine + * + */ +typedef void (*esp_eap_peer_config_deinit_t)(void *sm); + +/** + * @brief Register the eap method + * + * Note: ESP32 only support PEAP/TTLS/TLS three eap methods now. + * + */ +typedef int (*esp_eap_peer_register_methods_t)(void); + +/** + * @brief remove the eap method + * + * Note: ESP32 only support PEAP/TTLS/TLS three eap methods now. + * + */ +typedef void (*esp_eap_peer_unregister_methods_t)(void); + +/** + * @brief remove the eap method before build new connect + * + * @sm: eap state machine + * @txt: not used now + */ +typedef void (*esp_eap_deinit_prev_method_t)(void *sm, const char *txt); + +/** + * @brief Get EAP method based on type number + * + * @vendor: EAP Vendor-Id (0 = IETF) + * @method: EAP type number + * Returns: Pointer to EAP method or %NULL if not found + */ +typedef const void * (*esp_eap_peer_get_eap_method_t)(int vendor, int method); + +/** + * @brief Abort EAP authentication + * + * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init() + * + * Release system resources that have been allocated for the authentication + * session without fully deinitializing the EAP state machine. + */ +typedef void (*esp_eap_sm_abort_t)(void *sm); + +/** + * @brief Build EAP-NAK for the current network + * + * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init() + * @type: EAP type of the fail reason + * @id: EAP identifier for the packet + * + * This function allocates and builds a nak packet for the + * current network. The caller is responsible for freeing the returned data. + */ +typedef void * (*esp_eap_sm_build_nak_t)(void *sm, int type, unsigned char id); + +/** + * @brief Build EAP-Identity/Response for the current network + * + * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init() + * @id: EAP identifier for the packet + * @encrypted: Whether the packet is for encrypted tunnel (EAP phase 2) + * Returns: Pointer to the allocated EAP-Identity/Response packet or %NULL on + * failure + * + * This function allocates and builds an EAP-Identity/Response packet for the + * current network. The caller is responsible for freeing the returned data. + */ +typedef void * (*esp_eap_sm_build_identity_resp_t)(void *sm, unsigned char id, int encrypted); + +/** + * @brief Allocate a buffer for an EAP message + * + * @vendor: Vendor-Id (0 = IETF) + * @type: EAP type + * @payload_len: Payload length in bytes (data after Type) + * @code: Message Code (EAP_CODE_*) + * @identifier: Identifier + * Returns: Pointer to the allocated message buffer or %NULL on error + * + * This function can be used to allocate a buffer for an EAP message and fill + * in the EAP header. This function is automatically using expanded EAP header + * if the selected Vendor-Id is not IETF. In other words, most EAP methods do + * not need to separately select which header type to use when using this + * function to allocate the message buffers. The returned buffer has room for + * payload_len bytes and has the EAP header and Type field already filled in. + */ +typedef void * (*esp_eap_msg_alloc_t)(int vendor, int type, unsigned int payload_len, + unsigned char code, unsigned char identifier); + +/** + * @brief get the enrollee mac address + * @mac_addr: instore the mac address of enrollee + * @uuid: Universally Unique Identifer of the enrollee + * + */ +typedef void (*esp_uuid_gen_mac_addr_t)(const unsigned char *mac_addr, unsigned char *uuid); + +/** + * @brief free the message after finish DH + * + */ +typedef void (*esp_dh5_free_t)(void *ctx); + +/** + * @brief Build WPS IE for (Re)Association Request + * + * @req_type: Value for Request Type attribute + * Returns: WPS IE or %NULL on failure + * + * The caller is responsible for freeing the buffer. + */ +typedef void * (*esp_wps_build_assoc_req_ie_t)(int req_type); + +/** + * @brief Build WPS IE for (Re)Association Response + * + * Returns: WPS IE or %NULL on failure + * + * The caller is responsible for freeing the buffer. + */ +typedef void * (*esp_wps_build_assoc_resp_ie_t)(void); + +/** + * @brief Build WPS IE for Probe Request + * + * @pw_id: Password ID (DEV_PW_PUSHBUTTON for active PBC and DEV_PW_DEFAULT for + * most other use cases) + * @dev: Device attributes + * @uuid: Own UUID + * @req_type: Value for Request Type attribute + * @num_req_dev_types: Number of requested device types + * @req_dev_types: Requested device types (8 * num_req_dev_types octets) or + * %NULL if none + * Returns: WPS IE or %NULL on failure + * + * The caller is responsible for freeing the buffer. + */ +typedef void * (*esp_wps_build_probe_req_ie_t)(uint16_t pw_id, void *dev, const unsigned char *uuid, + int req_type, unsigned int num_req_dev_types, const unsigned char *req_dev_types); + +/** + * @brief build public key for exchange in M1 + * + * + */ +typedef int (*esp_wps_build_public_key_t)(void *wps, void *msg, int mode); + + +/** + * @brief get the wps information in exchange password + * + * + */ +typedef void * (*esp_wps_enrollee_get_msg_t)(void *wps, void *op_code); + +/** + * @brief deal with the wps information in exchange password + * + * + */ +typedef int (*esp_wps_enrollee_process_msg_t)(void *wps, int op_code, const void *msg); + +/** + * @brief Generate a random PIN + * + * Returns: Eight digit PIN (i.e., including the checksum digit) + */ +typedef unsigned int (*esp_wps_generate_pin_t)(void); + +/** + * @brief Check whether WPS IE indicates active PIN + * + * @msg: WPS IE contents from Beacon or Probe Response frame + * Returns: 1 if PIN Registrar is active, 0 if not + */ +typedef int (*esp_wps_is_selected_pin_registrar_t)(const void *msg, unsigned char *bssid); + +/** + * @brief Check whether WPS IE indicates active PBC + * + * @msg: WPS IE contents from Beacon or Probe Response frame + * Returns: 1 if PBC Registrar is active, 0 if not + */ +typedef int (*esp_wps_is_selected_pbc_registrar_t)(const void *msg, unsigned char *bssid); + + + /** * @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; }wpa_crypto_funcs_t; /** @@ -275,12 +728,26 @@ typedef struct { * hardware. */ typedef struct{ + uint32_t size; + uint32_t version; esp_aes_128_encrypt_t aes_128_encrypt; /**< function used to process message when do WPS */ esp_aes_128_decrypt_t aes_128_decrypt; /**< function used to process message when do WPS */ esp_crypto_mod_exp_t crypto_mod_exp; /**< function used to calculate public key and private key */ esp_hmac_sha256_t hmac_sha256; /**< function used to get attribute */ esp_hmac_sha256_vector_t hmac_sha256_vector; /**< function used to process message when do WPS */ esp_sha256_vector_t sha256_vector; /**< function used to process message when do WPS */ + esp_uuid_gen_mac_addr_t uuid_gen_mac_addr; + esp_dh5_free_t dh5_free; + esp_wps_build_assoc_req_ie_t wps_build_assoc_req_ie; + esp_wps_build_assoc_resp_ie_t wps_build_assoc_resp_ie; + esp_wps_build_probe_req_ie_t wps_build_probe_req_ie; + esp_wps_build_public_key_t wps_build_public_key; + esp_wps_enrollee_get_msg_t wps_enrollee_get_msg; + esp_wps_enrollee_process_msg_t wps_enrollee_process_msg; + esp_wps_generate_pin_t wps_generate_pin; + esp_wps_is_selected_pin_registrar_t wps_is_selected_pin_registrar; + esp_wps_is_selected_pbc_registrar_t wps_is_selected_pbc_registrar; + esp_eap_msg_alloc_t eap_msg_alloc; }wps_crypto_funcs_t; /** @@ -289,6 +756,8 @@ typedef struct{ * hardware. */ typedef struct { + uint32_t size; + uint32_t version; esp_crypto_hash_init_t crypto_hash_init; /**< function used to initialize a crypto_hash structure when use TLSV1 */ esp_crypto_hash_update_t crypto_hash_update; /**< function used to calculate hash data when use TLSV1 */ esp_crypto_hash_finish_t crypto_hash_finish; /**< function used to finish the hash calculate when use TLSV1 */ @@ -298,6 +767,20 @@ typedef struct { esp_crypto_cipher_deinit_t crypto_cipher_deinit; /**< function used to free context when use TLSV1 */ esp_crypto_mod_exp_t crypto_mod_exp; /**< function used to do key exchange when use TLSV1 */ esp_sha256_vector_t sha256_vector; /**< function used to do X.509v3 certificate parsing and processing */ + esp_tls_init_t tls_init; + esp_tls_deinit_t tls_deinit; + esp_eap_peer_blob_init_t eap_peer_blob_init; + esp_eap_peer_blob_deinit_t eap_peer_blob_deinit; + esp_eap_peer_config_init_t eap_peer_config_init; + esp_eap_peer_config_deinit_t eap_peer_config_deinit; + esp_eap_peer_register_methods_t eap_peer_register_methods; + esp_eap_peer_unregister_methods_t eap_peer_unregister_methods; + esp_eap_deinit_prev_method_t eap_deinit_prev_method; + esp_eap_peer_get_eap_method_t eap_peer_get_eap_method; + esp_eap_sm_abort_t eap_sm_abort; + esp_eap_sm_build_nak_t eap_sm_build_nak; + esp_eap_sm_build_identity_resp_t eap_sm_build_identity_resp; + esp_eap_msg_alloc_t eap_msg_alloc; } wpa2_crypto_funcs_t; /** diff --git a/tools/sdk/include/esp32/esp_wifi_internal.h b/tools/sdk/include/esp32/esp_wifi_internal.h index 2fc138b737e..d41b099db60 100644 --- a/tools/sdk/include/esp32/esp_wifi_internal.h +++ b/tools/sdk/include/esp32/esp_wifi_internal.h @@ -35,11 +35,17 @@ #include "esp_err.h" #include "esp_wifi_types.h" #include "esp_event.h" +#include "esp_wifi.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 Initialize Wi-Fi Driver * Alloc resource for WiFi driver, such as WiFi control structure, RX/TX buffer, @@ -81,7 +87,7 @@ void esp_wifi_internal_free_rx_buffer(void* buffer); * * @param wifi_interface_t wifi_if : wifi interface id * @param void *buffer : the buffer to be tansmit - * @param u16_t len : the length of buffer + * @param uint16_t len : the length of buffer * * @return * - ERR_OK : Successfully transmit the buffer to wifi driver @@ -89,7 +95,7 @@ void esp_wifi_internal_free_rx_buffer(void* buffer); * - ERR_IF : WiFi driver error * - ERR_ARG : Invalid argument */ -int esp_wifi_internal_tx(wifi_interface_t wifi_if, void *buffer, u16_t len); +int esp_wifi_internal_tx(wifi_interface_t wifi_if, void *buffer, uint16_t len); /** * @brief The WiFi RX callback function @@ -121,6 +127,70 @@ esp_err_t esp_wifi_internal_reg_rxcb(wifi_interface_t ifx, wifi_rxcb_t fn); */ 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 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 * @@ -156,6 +226,36 @@ void *wifi_realloc( void *ptr, size_t size ); */ 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 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); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/esp32/esp_wifi_os_adapter.h b/tools/sdk/include/esp32/esp_wifi_os_adapter.h new file mode 100644 index 00000000000..165caa6edc5 --- /dev/null +++ b/tools/sdk/include/esp32/esp_wifi_os_adapter.h @@ -0,0 +1,135 @@ +// 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 0x00000002 +#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; + void (*_set_isr)(int32_t n, void *f, void *arg); + void (*_ints_on)(uint32_t mask); + void (*_ints_off)(uint32_t mask); + 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, int32_t clear_on_exit, int32_t 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)(uint32_t size); + void (* _free)(void *p); + 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); + int32_t (* _phy_rf_deinit)(uint32_t module); + void (* _phy_load_cal_and_init)(uint32_t module); + int32_t (* _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 (* _periph_module_enable)(uint32_t periph); + void (* _periph_module_disable)(uint32_t periph); + int64_t (* _esp_timer_get_time)(void); + int32_t (* _nvs_set_i8)(uint32_t handle, const char* key, int8_t value); + int32_t (* _nvs_get_i8)(uint32_t handle, const char* key, int8_t* out_value); + int32_t (* _nvs_set_u8)(uint32_t handle, const char* key, uint8_t value); + int32_t (* _nvs_get_u8)(uint32_t handle, const char* key, uint8_t* out_value); + int32_t (* _nvs_set_u16)(uint32_t handle, const char* key, uint16_t value); + int32_t (* _nvs_get_u16)(uint32_t handle, const char* key, uint16_t* out_value); + int32_t (* _nvs_open)(const char* name, uint32_t open_mode, uint32_t *out_handle); + void (* _nvs_close)(uint32_t handle); + int32_t (* _nvs_commit)(uint32_t handle); + int32_t (* _nvs_set_blob)(uint32_t handle, const char* key, const void* value, size_t length); + int32_t (* _nvs_get_blob)(uint32_t handle, const char* key, void* out_value, size_t* length); + int32_t (* _nvs_erase_key)(uint32_t handle, const char* key); + int32_t (* _get_random)(uint8_t *buf, size_t len); + int32_t (* _get_time)(void *t); + unsigned long (* _random)(void); + void (* _log_write)(uint32_t level, const char* tag, const char* format, ...); + 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)(int32_t queue_len, int32_t item_size); + void (* _wifi_delete_queue)(void * queue); + int32_t (* _modem_sleep_enter)(uint32_t module); + int32_t (* _modem_sleep_exit)(uint32_t module); + int32_t (* _modem_sleep_register)(uint32_t module); + int32_t (* _modem_sleep_deregister)(uint32_t module); + void (* _sc_ack_send)(void *param); + void (* _sc_ack_send_stop)(void); + uint32_t (* _coex_status_get)(void); + int32_t (* _coex_wifi_request)(uint32_t event, uint32_t latency, uint32_t duration); + int32_t (* _coex_wifi_release)(uint32_t event); + 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/include/esp32/esp_wifi_types.h b/tools/sdk/include/esp32/esp_wifi_types.h old mode 100755 new mode 100644 index 63be8ba9bd1..3f6eccde0be --- a/tools/sdk/include/esp32/esp_wifi_types.h +++ b/tools/sdk/include/esp32/esp_wifi_types.h @@ -18,9 +18,8 @@ #include #include -#include "rom/queue.h" #include "esp_err.h" -#include "esp_interface.h" +#include "esp_private/esp_wifi_types_private.h" #ifdef __cplusplus extern "C" { @@ -49,6 +48,7 @@ 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; @@ -92,12 +92,13 @@ typedef enum { WIFI_REASON_AUTH_FAIL = 202, WIFI_REASON_ASSOC_FAIL = 203, WIFI_REASON_HANDSHAKE_TIMEOUT = 204, + WIFI_REASON_CONNECTION_FAIL = 205, } 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 second channel is above the primary channel */ - WIFI_SECOND_CHAN_BELOW, /**< the channel width is HT40 and the second channel is below the primary channel */ + 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 { @@ -139,22 +140,34 @@ typedef enum { WIFI_CIPHER_TYPE_UNKNOWN, /**< the cipher type is unknown */ } wifi_cipher_type_t; -/** @brief Description of an WiFi AP */ +/** + * @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; /**< second 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 reserved:27; /**< bit: 5..31 reserved */ + wifi_country_t country; /**< country information of AP */ } wifi_ap_record_t; typedef enum { @@ -173,12 +186,16 @@ typedef struct { wifi_auth_mode_t authmode; /**< The weakest authmode to accept in the fast scan mode */ }wifi_fast_scan_threshold_t; +typedef wifi_fast_scan_threshold_t wifi_scan_threshold_t; /**< wifi_fast_scan_threshold_t only used in fast scan mode once, now it enabled in all channel scan, the wifi_fast_scan_threshold_t will be remove in version 4.0 */ + typedef enum { WIFI_PS_NONE, /**< No power save */ - WIFI_PS_MIN_MODEM, /**< Minimum modem power save. In this mode, station wakes up to receive beacon every DTIM period */ - WIFI_PS_MAX_MODEM, /**< Maximum modem power save. In this mode, station wakes up to receive beacon every listen interval */ + 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_PS_MODEM WIFI_PS_MIN_MODEM /**< @deprecated Use WIFI_PS_MIN_MODEM or WIFI_PS_MAX_MODEM instead */ + #define WIFI_PROTOCOL_11B 1 #define WIFI_PROTOCOL_11G 2 #define WIFI_PROTOCOL_11N 4 @@ -209,9 +226,9 @@ typedef struct { 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 in maximum power save mode, units: beacon interval */ + 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_fast_scan_threshold_t threshold; /**< When scan_method is set to WIFI_FAST_SCAN, 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_scan_threshold_t threshold; /**< When scan_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_sta_config_t; /** @brief Configuration data for ESP32 AP or STA. @@ -228,6 +245,12 @@ typedef union { /** @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 */ @@ -283,31 +306,33 @@ typedef struct { /** @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; /**< signal intensity of packet */ - unsigned rate:5; /**< data rate */ - unsigned :1; /**< reserve */ - unsigned sig_mode:2; /**< 0:is not 11n packet; 1:is 11n packet */ - unsigned :16; /**< reserve */ - unsigned mcs:7; /**< if is 11n packet, shows the modulation(range from 0 to 76) */ - unsigned cwb:1; /**< if is 11n packet, shows if is HT40 packet or not */ - unsigned :16; /**< reserve */ - unsigned smoothing:1; /**< reserve */ - unsigned not_sounding:1; /**< reserve */ - unsigned :1; /**< reserve */ - unsigned aggregation:1; /**< Aggregation */ - unsigned stbc:2; /**< STBC */ - unsigned fec_coding:1; /**< Flag is set for 11n packets which are LDPC */ - unsigned sgi:1; /**< SGI */ - unsigned noise_floor:8; /**< noise floor */ - unsigned ampdu_cnt:8; /**< ampdu cnt */ - unsigned channel:4; /**< which channel this packet in */ - unsigned :12; /**< reserve */ - unsigned timestamp:32; /**< timestamp */ - unsigned :32; /**< reserve */ - unsigned :32; /**< reserve */ - unsigned sig_len:12; /**< length of packet */ - unsigned :12; /**< reserve */ - unsigned rx_state:8; /**< rx state */ + 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; /**< reserve */ + unsigned sig_mode:2; /**< 0: non HT(11bg) packet; 1: HT(11n) packet; 3: VHT(11ac) packet */ + unsigned :16; /**< reserve */ + 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; /**< reserve */ + unsigned smoothing:1; /**< reserve */ + unsigned not_sounding:1; /**< reserve */ + unsigned :1; /**< reserve */ + 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 */ + signed noise_floor:8; /**< noise floor of Radio Frequency Module(RF). unit: 0.25dBm*/ + 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; /**< reserve */ + 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; /**< reserve */ + unsigned :31; /**< reserve */ + unsigned ant:1; /**< antenna number from which this packet is received. 0: WiFi antenna 0; 1: WiFi antenna 1 */ + unsigned sig_len:12; /**< length of packet including Frame Check Sequence(FCS) */ + unsigned :12; /**< reserve */ + 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. @@ -325,6 +350,7 @@ typedef struct { */ 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; @@ -332,16 +358,167 @@ typedef enum { #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_DATA (1<<1) /**< filter the packets with type of WIFI_PKT_DATA */ -#define WIFI_PROMIS_FILTER_MASK_MISC (1<<2) /**< filter the packets with type of WIFI_PKT_MISC */ -#define WIFI_PROMIS_FILTER_MASK_DATA_MPDU (1<<3) /**< filter the MPDU which is a kind of WIFI_PKT_DATA */ -#define WIFI_PROMIS_FILTER_MASK_DATA_AMPDU (1<<4) /**< filter the AMPDU which is a kind of WIFI_PKT_DATA */ +#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_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 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; + +/** + * @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 diff --git a/tools/sdk/include/esp32/esp_wpa2.h b/tools/sdk/include/esp32/esp_wpa2.h index fa73dbe2870..1b2dfa51038 100644 --- a/tools/sdk/include/esp32/esp_wpa2.h +++ b/tools/sdk/include/esp32/esp_wpa2.h @@ -15,6 +15,8 @@ #ifndef ESP_WPA2_H #define ESP_WPA2_H +#include + #include "esp_err.h" #include "esp_wifi_crypto_types.h" @@ -121,7 +123,7 @@ void esp_wifi_sta_wpa2_ent_clear_password(void); * @attention 1. The API only passes the parameter password to the global pointer variable in wpa2 enterprise module. * @attention 2. The new password is used to substitute the old password when eap-mschapv2 failure request message with error code ERROR_PASSWD_EXPIRED is received. * - * @param password: point to address where stores the password; + * @param new_password: point to address where stores the password; * @param len: length of password * * @return @@ -130,7 +132,7 @@ void esp_wifi_sta_wpa2_ent_clear_password(void); * - ESP_ERR_NO_MEM: fail(internal memory malloc fail) */ -esp_err_t esp_wifi_sta_wpa2_ent_set_new_password(const unsigned char *password, int len); +esp_err_t esp_wifi_sta_wpa2_ent_set_new_password(const unsigned char *new_password, int len); /** * @brief Clear new password for MSCHAPv2 method.. @@ -144,12 +146,12 @@ void esp_wifi_sta_wpa2_ent_clear_new_password(void); * @attention 2. The ca_cert should be zero terminated. * * @param ca_cert: point to address where stores the CA certificate; - * @param len: length of ca_cert + * @param ca_cert_len: length of ca_cert * * @return * - ESP_OK: succeed */ -esp_err_t esp_wifi_sta_wpa2_ent_set_ca_cert(const unsigned char *ca_cert, int len); +esp_err_t esp_wifi_sta_wpa2_ent_set_ca_cert(const unsigned char *ca_cert, int ca_cert_len); /** * @brief Clear CA certificate for PEAP/TTLS method. diff --git a/tools/sdk/include/esp32/esp_wps.h b/tools/sdk/include/esp32/esp_wps.h index efe37bd028d..9bd61cc3af1 100644 --- a/tools/sdk/include/esp32/esp_wps.h +++ b/tools/sdk/include/esp32/esp_wps.h @@ -56,14 +56,33 @@ typedef enum wps_type { extern const wps_crypto_funcs_t g_wifi_default_wps_crypto_funcs; +#define WPS_MAX_MANUFACTURER_LEN 65 +#define WPS_MAX_MODEL_NUMBER_LEN 33 +#define WPS_MAX_MODEL_NAME_LEN 33 +#define WPS_MAX_DEVICE_NAME_LEN 33 + +typedef struct { + char manufacturer[WPS_MAX_MANUFACTURER_LEN]; /*!< Manufacturer, null-terminated string. The default manufcturer is used if the string is empty */ + char model_number[WPS_MAX_MODEL_NUMBER_LEN]; /*!< Model number, null-terminated string. The default model number is used if the string is empty */ + char model_name[WPS_MAX_MODEL_NAME_LEN]; /*!< Model name, null-terminated string. The default model name is used if the string is empty */ + char device_name[WPS_MAX_DEVICE_NAME_LEN]; /*!< Device name, null-terminated string. The default device name is used if the string is empty */ +} wps_factory_information_t; + typedef struct { wps_type_t wps_type; const wps_crypto_funcs_t *crypto_funcs; -}esp_wps_config_t; + wps_factory_information_t factory_info; +} esp_wps_config_t; #define WPS_CONFIG_INIT_DEFAULT(type) { \ .wps_type = type, \ .crypto_funcs = &g_wifi_default_wps_crypto_funcs, \ + .factory_info = { \ + .manufacturer = "ESPRESSIF", \ + .model_number = "ESP32", \ + .model_name = "ESPRESSIF IOT", \ + .device_name = "ESP STATION", \ + } \ } /** diff --git a/tools/sdk/include/esp32/hwcrypto/aes.h b/tools/sdk/include/esp32/hwcrypto/aes.h index 0bcd1f490ca..5a3fd24fe03 100644 --- a/tools/sdk/include/esp32/hwcrypto/aes.h +++ b/tools/sdk/include/esp32/hwcrypto/aes.h @@ -41,16 +41,25 @@ extern "C" { /** * \brief AES context structure * - * \note buf is able to hold 32 extra bytes, which can be used: - * - for alignment purposes if VIA padlock is used, and/or - * - to simplify key expansion in the 256-bit case by - * generating an extra round key */ typedef struct { uint8_t key_bytes; + volatile uint8_t key_in_hardware; /* This variable is used for fault injection checks, so marked volatile to avoid optimisation */ uint8_t key[32]; } esp_aes_context; +/** + * \brief The AES XTS context-type definition. + */ +typedef struct +{ + esp_aes_context crypt; /*!< The AES context to use for AES block + encryption or decryption. */ + esp_aes_context tweak; /*!< The AES context used for tweak + computation. */ +} esp_aes_xts_context; + + /** * \brief Lock access to AES hardware unit * @@ -86,6 +95,23 @@ void esp_aes_init( esp_aes_context *ctx ); */ void esp_aes_free( esp_aes_context *ctx ); +/** + * \brief This function initializes the specified AES XTS context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The AES XTS context to initialize. + */ +void esp_aes_xts_init( esp_aes_xts_context *ctx ); + +/** + * \brief This function releases and clears the specified AES XTS context. + * + * \param ctx The AES XTS context to clear. + */ +void esp_aes_xts_free( esp_aes_xts_context *ctx ); + /** * \brief AES set key schedule (encryption or decryption) * @@ -233,6 +259,42 @@ int esp_aes_crypt_ctr( esp_aes_context *ctx, const unsigned char *input, unsigned char *output ); +/** + * \brief This function prepares an XTS context for encryption and + * sets the encryption key. + * + * \param ctx The AES XTS context to which the key should be bound. + * \param key The encryption key. This is comprised of the XTS key1 + * concatenated with the XTS key2. + * \param keybits The size of \p key passed in bits. Valid options are: + *
  • 256 bits (each of key1 and key2 is a 128-bit key)
  • + *
  • 512 bits (each of key1 and key2 is a 256-bit key)
+ * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int esp_aes_xts_setkey_enc( esp_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function prepares an XTS context for decryption and + * sets the decryption key. + * + * \param ctx The AES XTS context to which the key should be bound. + * \param key The decryption key. This is comprised of the XTS key1 + * concatenated with the XTS key2. + * \param keybits The size of \p key passed in bits. Valid options are: + *
  • 256 bits (each of key1 and key2 is a 128-bit key)
  • + *
  • 512 bits (each of key1 and key2 is a 256-bit key)
+ * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int esp_aes_xts_setkey_dec( esp_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits ); + /** * \brief Internal AES block encryption function @@ -243,7 +305,10 @@ int esp_aes_crypt_ctr( esp_aes_context *ctx, * \param input Plaintext block * \param output Output (ciphertext) block */ -void esp_aes_encrypt( esp_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); +int esp_internal_aes_encrypt( esp_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); + +/** Deprecated, see esp_aes_internal_encrypt */ +void esp_aes_encrypt( esp_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) __attribute__((deprecated)); /** * \brief Internal AES block decryption function @@ -254,7 +319,10 @@ void esp_aes_encrypt( esp_aes_context *ctx, const unsigned char input[16], unsig * \param input Ciphertext block * \param output Output (plaintext) block */ -void esp_aes_decrypt( esp_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); +int esp_internal_aes_decrypt( esp_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); + +/** Deprecated, see esp_aes_internal_decrypt */ +void esp_aes_decrypt( esp_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) __attribute__((deprecated)); #ifdef __cplusplus } diff --git a/tools/sdk/include/esp32/hwcrypto/sha.h b/tools/sdk/include/esp32/hwcrypto/sha.h index 921f597fdd7..516de6c1272 100644 --- a/tools/sdk/include/esp32/hwcrypto/sha.h +++ b/tools/sdk/include/esp32/hwcrypto/sha.h @@ -166,6 +166,8 @@ void esp_sha_unlock_engine(esp_sha_type sha_type); * while it is in use by the SHA engine. Caller should use esp_sha_wait_idle() * to ensure the SHA engine is not reading from the memory block in hardware. * + * @note This function enters a critical section. Do not block while holding this lock. + * * @note You do not need to lock the memory block before calling esp_sha_block() or esp_sha_read_digest_state(), these functions handle memory block locking internally. * * Call esp_sha_unlock_memory_block() when done. @@ -177,6 +179,8 @@ void esp_sha_lock_memory_block(void); * * Caller should have already locked a SHA engine before calling this function. * + * This function releases the critical section entered by esp_sha_lock_memory_block(). + * * Call following esp_sha_lock_memory_block(). */ void esp_sha_unlock_memory_block(void); diff --git a/tools/sdk/include/esp32/rom/cache.h b/tools/sdk/include/esp32/rom/cache.h index 72aa33aaab0..4b923e669d7 100644 --- a/tools/sdk/include/esp32/rom/cache.h +++ b/tools/sdk/include/esp32/rom/cache.h @@ -83,6 +83,9 @@ static inline unsigned int IRAM_ATTR cache_flash_mmu_set(int cpu_no, int pid, un * @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. @@ -106,18 +109,7 @@ static inline unsigned int IRAM_ATTR cache_flash_mmu_set(int cpu_no, int pid, un * 4 : mmu table to be written is out of range * 5 : vaddr is out of range */ -static inline unsigned int IRAM_ATTR cache_sram_mmu_set(int cpu_no, int pid, unsigned int vaddr, unsigned int paddr, int psize, int num) -{ - extern unsigned int cache_sram_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_sram_mmu_set_rom(cpu_no, pid, vaddr, paddr, psize, num); - DPORT_STALL_OTHER_CPU_END(); - - return ret; -} +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. diff --git a/tools/sdk/include/esp32/rom/ets_sys.h b/tools/sdk/include/esp32/rom/ets_sys.h index 0f972f2c338..6e27b38beb3 100644 --- a/tools/sdk/include/esp32/rom/ets_sys.h +++ b/tools/sdk/include/esp32/rom/ets_sys.h @@ -301,6 +301,15 @@ typedef struct _ETSTIMER_ { */ 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. diff --git a/tools/sdk/include/esp32/rom/gpio.h b/tools/sdk/include/esp32/rom/gpio.h index bd1777c60b3..f98d6cf2dd0 100644 --- a/tools/sdk/include/esp32/rom/gpio.h +++ b/tools/sdk/include/esp32/rom/gpio.h @@ -20,6 +20,7 @@ #include "esp_attr.h" #include "soc/gpio_reg.h" +#include "soc/gpio_pins.h" #ifdef __cplusplus extern "C" { @@ -35,11 +36,13 @@ extern "C" { #define GPIO_REG_READ(reg) READ_PERI_REG(reg) #define GPIO_REG_WRITE(reg, val) WRITE_PERI_REG(reg, val) -#define GPIO_PIN_COUNT 40 #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))) @@ -57,8 +60,8 @@ typedef enum { #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)) +#define GPIO_DIS_OUTPUT(gpio_no) ((gpio_no < 32) ? gpio_output_set(0,0,0, 1<>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); diff --git a/tools/sdk/include/esp32/rom/libc_stubs.h b/tools/sdk/include/esp32/rom/libc_stubs.h index 0c1876e5856..90c0b446886 100644 --- a/tools/sdk/include/esp32/rom/libc_stubs.h +++ b/tools/sdk/include/esp32/rom/libc_stubs.h @@ -51,7 +51,7 @@ struct syscall_stub_table 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); + 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 *); diff --git a/tools/sdk/include/esp32/rom/md5_hash.h b/tools/sdk/include/esp32/rom/md5_hash.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/rom/queue.h b/tools/sdk/include/esp32/rom/queue.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/rom/rtc.h b/tools/sdk/include/esp32/rom/rtc.h index 3161fb27484..6d9d297746a 100644 --- a/tools/sdk/include/esp32/rom/rtc.h +++ b/tools/sdk/include/esp32/rom/rtc.h @@ -55,7 +55,7 @@ extern "C" { * 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_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 @@ -68,8 +68,10 @@ extern "C" { #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, ///xtensa/board.h - using a -I directive passed to the compiler. */ - -#error "Unspecified board. Missing -I directive to select supported Xtensa board, usually -I XTENSA_TOOLS_ROOT/xtensa-elf/include/xtensa/ (XTENSA_TOOLS_ROOT is root of Xtensa Tools install, see xt-run --show-config=xttools)" - -/* - * Copyright (c) 2013 Tensilica 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. - */ - diff --git a/tools/sdk/include/esp32/xtensa/c6x-compat.h b/tools/sdk/include/esp32/xtensa/c6x-compat.h deleted file mode 100755 index 4b17987ea95..00000000000 --- a/tools/sdk/include/esp32/xtensa/c6x-compat.h +++ /dev/null @@ -1,1758 +0,0 @@ -/* - * Copyright (c) 2006-2010 Tensilica Inc. 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. - */ - -#ifndef __C6X_COMPAT__H -#define __C6X_COMPAT__H - -/* Unimplemented functions _gmpy, _gmpy4, _xormpy, _lssub, _cmpy, _cmpyr, - _cmpyr1, _ddotpl2r, _ddotph2r */ - - -typedef long long C6X_COMPAT_LONG40; - - -#define _memd8(a) (*((double*)(a))) -#define _memd8_const(a) (*((const double*)(a))) - -#define _amemd8(a) (*((double*)(a))) -#define _amemd8_const(a) (*((const double*)(a))) - -#define _mem8(a) (*((unsigned long long*)(a))) -#define _mem8_const(a) (*((const unsigned long long*)(a))) - -#define _mem4(a) (*((unsigned*)(a))) -#define _mem4_const(a) (*((const unsigned*)(a))) -#define _amem4_const(a) (*((const unsigned*)(a))) - -/* NOTE: To emulate a C6X properly you should define global variables - for your Xtensa with these names. Some of the emulation routines - will set these values. */ - -extern int _carry; -extern int _overflow; - -// Utility routines - - -#define TESTBIT(x,n) (((x) >> (n)) & 1) - -#define NSA_BITS 32 - -static inline unsigned int norm_shift_amt_U_and_non_U(int is_signed, int inp) { -int j=0, k=0; -int x=inp; -if (is_signed) { - /* Invert signed val if negative */ - x= TESTBIT(x,(NSA_BITS-1))? ~x: x; - x= (x&1)|(x<<1); /* Shift up to return count-1 */ - if (x ==0) - return NSA_BITS-1; - } - if (x ==0) - return NSA_BITS; - /* Now count leading zeros */ - for (j=0, k=NSA_BITS-1; k>=0; j++, k--) { - if (TESTBIT(x,k)) - return j; - } - return NSA_BITS; -} - - - -static inline long long -orig_L40_set( long long L40_var1) { - long long L40_var_out; - - L40_var_out = L40_var1 & 0x000000ffffffffffLL; - - if( L40_var1 & 0x8000000000LL) - L40_var_out = L40_var_out | 0xffffff0000000000LL; - - return( L40_var_out); -} - - - -static inline signed long long -util_saturate_n_no_state(signed long long t, int n) -{ - signed long long maxv, minv; - maxv = (1LL << (n-1)) - 1; - minv = (-1LL << (n-1)); - if (t > maxv) { - t = maxv; - } else if (t < minv) { - t = minv; - } - return t; -} - - -static inline signed long long -util_saturate_n_sgn(signed long long t, int n) -{ - signed long long result; - signed long long maxv, minv; - maxv = (1LL << (n-1)) - 1; - minv = (-1LL << (n-1)); - if (t > 0) { - result = maxv; - _overflow = 1; - } else if (t < 0) { - result = minv; - _overflow = 1; - } else { - result = 0; - } - return result; -} - - - - -/* well-behaved signed shift right (left on negative) with - saturation */ -static inline signed long long -util_shift_right_saturate_n(signed long long t, int shval, int n) -{ - /* n should be <= 62 */ - long long result; - - signed long long mask; - int actual_shift = shval; - long long shft = actual_shift > 0 ? actual_shift : -actual_shift; - - if (t == 0 || actual_shift == 0) - return t; - - if (actual_shift >= n) { - return (t < 0) ? -1 : 0; - } - if (actual_shift <= -n) { - return util_saturate_n_sgn(t, n); - } - if (actual_shift > 0) { - return t >> actual_shift; - } - /* actual_shift < 0. Check for saturation after shift. */ - mask = (-1LL << (n-shft-1)); - if (t > 0 && ((mask & t) != 0)) { - return util_saturate_n_sgn(t, n); - } - if (t < 0 && ((mask & t) != mask)) { - return util_saturate_n_sgn(t, n); - } - result = t << shft; - - return result; -} - - -/* Implemented c6x standard C compatibility functions (alphabetical - order) */ - - -static inline int _abs(int src1) { - if ((unsigned) src1 == (unsigned) 0x80000000) { - return 0x7fffffff; - } - return abs(src1); -} - - -static inline int _abs2(int src1) { - short s1[2],r[2]; - int result; - *((int*)s1) = src1; - if ((unsigned short) s1[1] == (unsigned short) 0x8000) r[1] = 0x7fff; - else r[1] = abs(s1[1]); - if ((unsigned short) s1[0] == (unsigned short) 0x8000) r[0] = 0x7fff; - else r[0] = abs(s1[0]); - result = *(int*)r; - return result; - } - - - - -static inline int _add2(int src1, int src2) { - short s1[2], s2[2], r[2]; - int result; - *((int*)s1) = src1; - *((int*)s2) = src2; - r[0] = s1[0] + s2[0]; - r[1] = s1[1] + s2[1]; - result = *(int*)r; - return result; -} - -static inline int _add4(int src1, int src2) { - char c1[4], c2[4], r[4]; - int result; - *((int*)c1) = src1; - *((int*)c2) = src2; - r[0] = c1[0] + c2[0]; - r[1] = c1[1] + c2[1]; - r[2] = c1[2] + c2[2]; - r[3] = c1[3] + c2[3]; - result = *(int*)r; - return result; -} - - - -static inline long long _addsub(unsigned int src1, unsigned int src2) -{ - - int res_lo; - int res_hi; - - res_hi = src1+src2; - res_lo = src1-src2; - return (((unsigned long long) res_hi) << 32) | ((unsigned int) res_lo) ; -} - - -static inline long long _addsub2(unsigned int src1, unsigned int src2) -{ - short s1[2], s2[2], ra[2], rs[2]; - int res_lo; - int res_hi; - - *((int*)s1) = src1; - *((int*)s2) = src2; - ra[0] = s1[0] + s2[0]; - ra[1] = s1[1] + s2[1]; - rs[0] = s1[0] - s2[0]; - rs[1] = s1[1] - s2[1]; - - res_hi = *(int*)ra; - res_lo = *(int*)rs; - return (((unsigned long long) res_hi) << 32) | ((unsigned int) res_lo) ; -} - - -static inline int _avg2(int src1, int src2) { - int low = (((int)1 + (short) src1 + (short) src2) >> 1) & 0XFFFF; - int high1 = src1 >> 16; - int high2 = src2 >> 16; - int high = ((high1 + high2 + 1) >> 1)<< 16; - return high | low; -} - - - -static inline unsigned int _avgu4(unsigned int src1, unsigned int src2) { -unsigned int res0 = ((src1 & 0xFF) + (src2 & 0xFF) + 1) >> 1; - unsigned int res1 = (((src1 & 0xFF00) >> 8) + ((src2 & 0xFF00) >> 8) + 1) >> 1; - unsigned int res2 = (((src1 & 0xFF0000) >> 16) + ((src2 & 0xFF0000) >> 16) + 1) >> 1; - unsigned int res3 = (((src1 & 0xFF000000) >> 24) + ((src2 & 0xFF000000) >> 24) + 1) >> 1; - return (res3 << 24) | (res2 << 16) | (res1 << 8) | res0; -} - - -static inline int TEN_popc (unsigned char b) -{ - int i, result = 0; - for (i = 0; i < 8; i++){ - if (b & 0x1) - result++; - b >>= 1; - } - return result; -} - -static inline unsigned int _bitc4(unsigned int src1) -{ - unsigned int res0 = TEN_popc(src1 & 0xFF); - unsigned int res1 = TEN_popc((src1 & 0xFF00) >> 8); - unsigned int res2 = TEN_popc((src1 & 0xFF0000) >> 16); - unsigned int res3 = TEN_popc((src1 & 0xFF000000) >> 24); - return (res3 << 24) | (res2 << 16) | (res1 << 8) | res0; -} - -static inline unsigned int _bitr(unsigned int src) { - int i; - unsigned r = 0; - for (i = 0; i< 32; ++i) { - r = r | (((src >> i) & 1)<<(31-i)); - } - return r; -} - - -static inline unsigned int _clr(unsigned int src2, int csta, int cstb) -{ - csta &= 0x1f; - cstb &= 0x1f; - if (csta > cstb) - return src2; - else { - unsigned int mask = (((1 << (cstb - csta)) << 1) - 1) << csta; - return src2 & (~mask); - } -} - -static inline unsigned int _clrr(unsigned int src2, int src1) -{ - unsigned int csta = (src1 >> 5) & 0x1f; - unsigned int cstb = src1 & 0x1f; - if (csta > cstb) - return src2; - else { - unsigned int mask = (((1 << (cstb - csta)) << 1) - 1) << csta; - return src2 & (~mask); - } -} - - - - -static inline int _cmpeq2(int src1, int src2) { - short s1[2], s2[2]; - int r0, r1; - int result; - *((int*)s1) = src1; - *((int*)s2) = src2; - r0 = s1[0] == s2[0] ? 1 : 0; - r1 = s1[1] == s2[1] ? 1 : 0; - result = (r1 << 1) | r0; - return result; -} - -static inline int _cmpeq4(int src1, int src2) { - char s1[4], s2[4]; - int r0, r1, r2, r3; - int result; - *((int*)s1) = src1; - *((int*)s2) = src2; - r0 = s1[0] == s2[0] ? 1 : 0; - r1 = s1[1] == s2[1] ? 1 : 0; - r2 = s1[2] == s2[2] ? 1 : 0; - r3 = s1[3] == s2[3] ? 1 : 0; - result = (r3 << 3) | (r2 << 2) | (r1 << 1) | r0; - return result; -} - - -static inline int _cmpgt2(int src1, int src2) { - short s1[2], s2[2]; - int r1, r0; - int result; - *((int*)s1) = src1; - *((int*)s2) = src2; - r0 = s1[0] > s2[0] ? 1 : 0; - r1 = s1[1] > s2[1] ? 1 : 0; - result = (r1<<1) | r0; - return result; -} - - -static inline unsigned int _cmpgtu4(unsigned int src1, unsigned int src2) { - unsigned int s1_0 = (src1 & 0xFF); - unsigned int s1_1 = (src1 & 0xFF00) >> 8; - unsigned int s1_2 = (src1 & 0xFF0000) >> 16; - unsigned int s1_3 = (src1 & 0xFF000000) >> 24; - - unsigned int s2_0 = (src2 & 0xFF); - unsigned int s2_1 = (src2 & 0xFF00) >> 8; - unsigned int s2_2 = (src2 & 0xFF0000) >> 16; - unsigned int s2_3 = (src2 & 0xFF000000) >> 24; - - unsigned int result = 0; - - if (s1_0 > s2_0) - result |= 0x1; - - if (s1_1 > s2_1) - result |= 0x2; - - if (s1_2 > s2_2) - result |= 0x4; - - if (s1_3 > s2_3) - result |= 0x8; - - return result; -} - - - - -static inline long long _ddotp4(unsigned int src1, unsigned int src2) { - unsigned int res0, res1; - short s1_0 = (src1 & 0xffff); - short s1_1 = (src1 & 0xfff0000) >> 16; - - unsigned short s2_0 = (src2 & 0xff); - unsigned short s2_1 = (src2 & 0xff00) >> 8; - unsigned short s2_2 = (src2 & 0xff0000) >> 16; - unsigned short s2_3 = (src2 & 0xff000000) >> 24; - - res0 = ((int)s1_0) * s2_0 + ((int)s1_1) * s2_1; - res1 = ((int)s1_0) * s2_2 + ((int)s1_1) * s2_3; - - return (res1 << 16) | res0; -} - - -static inline long long _ddotph2(long long src1_o_src1_e, unsigned int src2) -{ - - unsigned int src1_o = src1_o_src1_e >> 32; - unsigned int src1_e = src1_o_src1_e & 0xFFFFFFFF; - short ls1_o = src1_o & 0XFFFF; - short hs1_o = src1_o >> 16; -// short ls1_e = src1_e & 0XFFFF; - short hs1_e = src1_e >> 16; - short ls2 = src2 & 0XFFFF; - short hs2 = src2 >> 16; - - unsigned long long res_hi = ls2 * ls1_o + hs2 * hs1_o; - unsigned int res_lo = ls1_o * hs2 + hs1_e * ls2; - return (res_hi << 32) | res_lo; -} - - -static inline long long _ddotpl2(long long src1_o_src1_e, unsigned int src2) -{ - unsigned int src1_o = src1_o_src1_e >> 32; - unsigned int src1_e = src1_o_src1_e & 0xFFFFFFFF; - short ls1_o = src1_o & 0XFFFF; -// short hs1_o = src1_o >> 16; - short ls1_e = src1_e & 0XFFFF; - short hs1_e = src1_e >> 16; - short ls2 = src2 & 0XFFFF; - short hs2 = src2 >> 16; - - unsigned long long res_hi = ls2 * hs1_e + hs2 * ls1_o; - unsigned res_lo = hs1_e * hs2 + ls1_e * ls2; - return (res_hi << 32) | res_lo; -} - - -static inline unsigned int _deal(unsigned int src) -{ - int i; - unsigned short lo = 0, hi = 0; - for (i = 0; i < 32; i+= 2) { - lo >>= 1; - lo |= (src & 0x1) << 15; - src >>= 1; - hi >>= 1; - hi |= (src & 0x1) << 15; - src >>= 1; - } - return (hi << 16) | lo; -} - - -static inline long long _dmv(unsigned int src1, unsigned int src2) -{ - return (((long long) src1) << 32) | src2; -} - - -static inline int _dotpn2(int src1, int src2) { -short int s1_h = src1>>16; - short int s1_l = src1; - short int s2_h = src2>>16; - short int s2_l = src2; - return s1_h * s2_h - s1_l * s2_l; -} - - -static inline int _dotp2(int src1, int src2) { - short int s1_h = src1>>16; - short int s1_l = src1; - short int s2_h = src2>>16; - short int s2_l = src2; - return s1_h * s2_h + s1_l * s2_l; -} - - - -static inline int _dotpnrsu2(int src1, unsigned int src2) -{ - short ls1 = src1 & 0XFFFF; - unsigned short ls2 = src2 & 0XFFFF; - short hs1 = src1 >> 16; - unsigned short hs2 = src2 >> 16; - - int result = (((long long) (int)(hs1 * hs2)) - ((long long) (int)(ls1 * ls2)) + (1 << 15)) >> 16; - return result; -} - - - -static inline int _dotprsu2(int src1, unsigned int src2) { - short ls1 = src1 & 0XFFFF; - unsigned short ls2 = (src2 & 0XFFFF); - short hs1 = src1 >> 16; - unsigned short hs2 = (src2 >> 16); - - int result = (((long long) (int) (ls1 * ls2)) + ((long long) (int) (hs1 * hs2)) + (1LL << 15)) >> 16; - return result; -} - - - - - - - -static inline int _dotpsu4(int src1, unsigned int src2) { - int result; - signed char s1_0 = (src1 & 0xff); - signed char s1_1 = (src1 & 0xff00) >> 8; - signed char s1_2 = (src1 & 0xff0000) >> 16; - signed char s1_3 = (src1 & 0xff000000) >> 24; - - unsigned int s2_0 = (src2 & 0xff); - unsigned int s2_1 = (src2 & 0xff00) >> 8; - unsigned int s2_2 = (src2 & 0xff0000) >> 16; - unsigned int s2_3 = (src2 & 0xff000000) >> 24; - - result = s1_0 * s2_0 + s1_1 * s2_1 + s1_2 * s2_2 + s1_3 * s2_3; - return result; -} - - -static inline unsigned int _dotpu4(unsigned int src1, unsigned int src2) { - unsigned char v1_0 = src1 & 0xff; - unsigned char v1_1 = (src1>>8) & 0xff; - unsigned char v1_2 = (src1>>16) & 0xff; - unsigned char v1_3 = (src1>>24) & 0xff; - - unsigned char v2_0 = src2 & 0xff; - unsigned char v2_1 = (src2>>8) & 0xff; - unsigned char v2_2 = (src2>>16) & 0xff; - unsigned char v2_3 = (src2>>24) & 0xff; - - unsigned v = v1_0 * v2_0 + v1_1 * v2_1 + v1_2 * v2_2 + v1_3 * v2_3; - return v; -} - - -static inline long long _dpack2(unsigned int src1, unsigned int src2){ -unsigned short s1[2], s2[2]; -*((int*)s1) = src1; -*((int*)s2) = src2; -return ((unsigned long long) s1[1] << 48) | ((unsigned long long) s2[1] << 32) | ((unsigned long long) s1[0] << 16) | ((unsigned long long) s2[0]); -} - - -static inline long long _dpackx2(unsigned int src1, unsigned int src2){ -unsigned short s1[2], s2[2]; -*((int*)s1) = src1; -*((int*)s2) = src2; -return ((unsigned long long) s2[0] << 48) | ((unsigned long long) s1[1] << 32) | ((unsigned long long) s1[0] << 16) | ((unsigned long long) s2[1]); -} - -static inline int _ext(int src2, unsigned int csta, unsigned int cstb) -{ - return (src2 << csta) >> cstb; -} - -static inline int _extr(int src2, int src1) -{ - unsigned int csta = (src1 >> 5) & 0x1f; - unsigned int cstb = src1 & 0x1f; - return (src2 << csta) >> cstb; -} - -static inline unsigned int _extu(unsigned int src2, unsigned int csta, unsigned int cstb) -{ - return (src2 << csta) >> cstb; -} - -static inline unsigned int _extur(unsigned int src2, int src1) -{ - unsigned int csta = (src1 >> 5) & 0x1f; - unsigned int cstb = src1 & 0x1f; - return (src2 << csta) >> cstb; -} - - -static inline unsigned long long _hi(double src) { - unsigned long long v; - *(double*)&v = src; - return v>>32; -} - -static inline unsigned int _hill (long long src) -{ - return (unsigned int) (src >> 32); -} - - - -static inline double _itod(unsigned hi, unsigned lo) { - double v; - unsigned long long ll = ((((unsigned long long)(hi))<<32) | (unsigned long long)((unsigned)lo)); - *((unsigned long long *)&v) = ll; - return v; -} - - -static inline long long _itoll(unsigned int src2, unsigned int src1) -{ - return (((long long) src2) << 32) | src1; -} - - -static inline C6X_COMPAT_LONG40 _labs(C6X_COMPAT_LONG40 src2) -{ - long long maxv = (1LL << (40 -1)) - 1; - long long minv = (-1LL << (40 - 1)); - C6X_COMPAT_LONG40 lres = orig_L40_set(src2); - - lres = lres < 0 ? -lres : lres; - if (lres > maxv) lres = maxv; - else if (lres < minv) lres = minv; - - return lres; -} - - -static inline C6X_COMPAT_LONG40 _ldotp2(int src1, int src2) { -return (C6X_COMPAT_LONG40) _dotp2(src1, src2); -} - - -static inline unsigned int _lmbd(unsigned int src1, unsigned int src2) -{ - return norm_shift_amt_U_and_non_U(0,(((int) (src1 << 31)) >> 31) ^ (~src2)); -} - - -static inline unsigned int _lnorm(C6X_COMPAT_LONG40 src2) { -if (src2 == 0) - return 39; - else { - int hi = (int)(src2 >> 32); - int lo = (int)src2; - - - long long temp = (unsigned long long)(unsigned)lo | (unsigned long long)hi << 32; - temp = orig_L40_set(temp); - - if (temp == 0) return 0; - int cnt = 0; - while (((temp >> 39) & 1) == ((temp >> 38) & 1)) { - temp <<= 1; - cnt++; - } - return cnt; - } -} - - -static inline unsigned long long _lo(double src) { - unsigned long long v; - *(double*)&v = src; - return v; -} - - -static inline unsigned int _loll (long long src) -{ - return (unsigned int) src; -} - - -static inline C6X_COMPAT_LONG40 _lsadd(int src1, C6X_COMPAT_LONG40 src2) -{ - long long maxv = (1LL << (40 -1)) - 1; - long long minv = (-1LL << (40 - 1)); - int hi = (int)(src2 >> 32); - int lo = (int)src2; - long long src2_int = (unsigned long long)(unsigned)lo | (unsigned long long)hi << 32; - - - long long src2_int2 = orig_L40_set(src2_int); - - long long res = src1 + src2_int2; - - if (res > maxv) { - res = maxv; - _overflow = 1; - } - else if (res < minv) { - res = minv; - _overflow = 1; - } - - long long res2 = orig_L40_set(res); - - res2 = (signed char)(res2 >> 32); - - C6X_COMPAT_LONG40 lres = (((C6X_COMPAT_LONG40) res2) << 32) | ((unsigned int)res); - return lres; -} - - - -static inline int _max2 (int src1, int src2) { - short s1[2], s2[2], r[2]; - int result; - *((int*)s1) = src1; - *((int*)s2) = src2; - r[0] = s1[0] > s2[0] ? s1[0] : s2[0]; - r[1] = s1[1] > s2[1] ? s1[1] : s2[1]; - result = *(int*)r; - return result; -} - - - - - - -static inline unsigned int _maxu4(unsigned int src1, unsigned int src2) { - unsigned int res0, res1, res2, res3; - unsigned int s1_0 = res0 = (src1 & 0xFF); - unsigned int s1_1 = res1 = (src1 & 0xFF00) >> 8; - unsigned int s1_2 = res2 = (src1 & 0xFF0000) >> 16; - unsigned int s1_3 = res3 = (src1 & 0xFF000000) >> 24; - - unsigned int s2_0 = (src2 & 0xFF); - unsigned int s2_1 = (src2 & 0xFF00) >> 8; - unsigned int s2_2 = (src2 & 0xFF0000) >> 16; - unsigned int s2_3 = (src2 & 0xFF000000) >> 24; - -// unsigned int res = 0; - - if (s1_0 < s2_0) - res0 = s2_0; - - if (s1_1 < s2_1) - res1 = s2_1; - - if (s1_2 < s2_2) - res2 = s2_2; - - if (s1_3 < s2_3) - res3 = s2_3; - - return (res3 << 24) | (res2 << 16) | (res1 << 8) | res0; - - -} - -static inline int _min2(int src1, int src2) { - short s1[2], s2[2], r[2]; - int result; - *((int*)s1) = src1; - *((int*)s2) = src2; - r[0] = s1[0] < s2[0] ? s1[0] : s2[0]; - r[1] = s1[1] < s2[1] ? s1[1] : s2[1]; - result = *(int*)r; - return result; -} - - -static inline unsigned int _minu4(unsigned int src1, unsigned int src2) { -unsigned int res0, res1, res2, res3; - unsigned int s1_0 = res0 = (src1 & 0xFF); - unsigned int s1_1 = res1 = (src1 & 0xFF00) >> 8; - unsigned int s1_2 = res2 = (src1 & 0xFF0000) >> 16; - unsigned int s1_3 = res3 = (src1 & 0xFF000000) >> 24; - - unsigned int s2_0 = (src2 & 0xFF); - unsigned int s2_1 = (src2 & 0xFF00) >> 8; - unsigned int s2_2 = (src2 & 0xFF0000) >> 16; - unsigned int s2_3 = (src2 & 0xFF000000) >> 24; - -// unsigned int res = 0; - - if (s1_0 > s2_0) - res0 = s2_0; - - if (s1_1 > s2_1) - res1 = s2_1; - - if (s1_2 > s2_2) - res2 = s2_2; - - if (s1_3 > s2_3) - res3 = s2_3; - - return (res3 << 24) | (res2 << 16) | (res1 << 8) | res0; -} - - -static inline int _mpy(int src1, int src2) { -return (short) src1 * (short) src2; -} - - -static inline int _mpyh(int src1, int src2) { -return (short) (src1 >> 16) * (short) (src2 >> 16); -} - - -static inline long long _mpyhill (int src1, int src2) -{ - short s1 = src1 >> 16; - return ((long long) src2) * s1; -} - -static inline int _mpyhir(int src1, int src2) -{ - short s1 = src1 >> 16; - long long result = ((long long) src2) * s1 + (1 << 14); - result >>= 15; - return result; -} - - -static inline int _mpyhl(int src1, int src2) { -return (short) (src1 >> 16) * (short) (src2); -} - -static inline unsigned int _mpyhlu(unsigned int src1, unsigned int src2) { -return (unsigned short) (src1 >> 16) * (unsigned short) (src2); -} - -static inline int _mpyhslu(int src1, unsigned int src2) { -return (short) (src1 >> 16) * (unsigned short) src2; -} - - -static inline int _mpyhsu(int src1, unsigned int src2) { -return (short) (src1 >>16) * (unsigned short) (src2 >>16); -} - - -static inline unsigned int _mpyhu(unsigned int src1, unsigned int src2) { -return (unsigned short) (src1 >>16) * (unsigned short) (src2 >> 16); -} - - -static inline int _mpyhuls(unsigned int src1, int src2) { -return (unsigned short) (src1 >>16) * (signed short) (src2); -} - - -static inline int _mpyhus(unsigned int src1, int src2) { -return (unsigned short) (src1 >> 16) * (short) (src2 >>16); -} - - - -static inline long long _mpyidll (int src1, int src2) -{ - return (long long) src1 * src2; -} - - -static inline int _mpylh(int src1, int src2) { -return (signed short) (src1 & 0xffff) * (signed short) (src2 >> 16); -} - -static inline unsigned int _mpylhu(unsigned int src1, unsigned int src2) { -return (unsigned short) src1 * (unsigned short) (src2 >> 16); -} - - -static inline long long _mpylill (int src1, int src2) -{ - return ((long long) src2) * ((short)src1); -} - - - -static inline int _mpylir(int src1, int src2) -{ - short s1 = src1; - long long result = ((long long) src2) * s1 + (1 << 14); - result >>= 15; - return result; -} - - -static inline int _mpylshu(int src1, unsigned int src2) { -return (short) src1 * (unsigned short) (src2 >> 16); -} - - -static inline int _mpyluhs(unsigned int src1, int src2) { -return (unsigned short) src1 * (short) (src2 >> 16); -} - - - -static inline int _mpysu(int src1, unsigned int src2) { -return (short) src1 * (unsigned short) src2; -} - - - -static inline long long _mpysu4ll (int src1, unsigned int src2) { - unsigned short res0, res1, res2, res3; - signed char s1_0 = (src1 & 0xff); - signed char s1_1 = (src1 & 0xff00) >> 8; - signed char s1_2 = (src1 & 0xff0000) >> 16; - signed char s1_3 = (src1 & 0xff000000) >> 24; - - unsigned short s2_0 = (src2 & 0xff); - unsigned short s2_1 = (src2 & 0xff00) >> 8; - unsigned short s2_2 = (src2 & 0xff0000) >> 16; - unsigned short s2_3 = (src2 & 0xff000000) >> 24; - - res0 = s1_0 * s2_0; - res1 = s1_1 * s2_1; - res2 = s1_2 * s2_2; - res3 = s1_3 * s2_3; - - return (((unsigned long long) res3) << 48) - | (((unsigned long long) res2) << 32) - | (((unsigned long long) res1) << 16) - | res0; -} - -static inline unsigned int _mpyu(unsigned int src1, unsigned int src2) { - unsigned v = (unsigned short)src1 * (unsigned short)src2; - return v; -} - -static inline int _mpyus(unsigned int src1, int src2) { -return (unsigned short) src1 * (short) src2; -} - -static inline long long _mpyu4ll (unsigned int src1, unsigned int src2) { - unsigned short res0, res1, res2, res3; - unsigned char s1_0 = (src1 & 0xff); - unsigned char s1_1 = (src1 & 0xff00) >> 8; - unsigned char s1_2 = (src1 & 0xff0000) >> 16; - unsigned char s1_3 = (src1 & 0xff000000) >> 24; - - unsigned short s2_0 = (src2 & 0xff); - unsigned short s2_1 = (src2 & 0xff00) >> 8; - unsigned short s2_2 = (src2 & 0xff0000) >> 16; - unsigned short s2_3 = (src2 & 0xff000000) >> 24; - - res0 = s1_0 * s2_0; - res1 = s1_1 * s2_1; - res2 = s1_2 * s2_2; - res3 = s1_3 * s2_3; - - return (((unsigned long long) res3) << 48) - | (((unsigned long long) res2) << 32) - | (((unsigned long long) res1) << 16) - | res0; -} - - -static inline long long _mpy2ir(unsigned int src1, unsigned int src2) -{ - if ((src1 == 0x8000) && (src2 == 0x80000000)) { - _overflow = 1; - return 0; - } - else { - short ls1 = src1 & 0xffff; - short hs1 = src1 >> 16; - unsigned long long hi = (((long long) hs1) * (int) src2 + (1 << 14)) >> 15; - unsigned long long lo = ((((long long) ls1) * (int) src2 + (1 << 14)) >> 15) & 0xFFFFFFFF; - return (hi << 32) | lo; - } -} - - -static inline long long _mpy2ll (int src1, int src2) { - short ls1 = src1 & 0xffff; - short hs1 = src1 >> 16; - short ls2 = src2 & 0xffff; - short hs2 = src2 >> 16; - - unsigned long long hi = hs1 * hs2; - unsigned long long lo = (ls1 * ls2) & 0xFFFFFFFF; - - return (hi << 32) | lo; - -} - - -static inline int _mpy32(int src1, int src2) -{ - return src1 * src2; -} - - -static inline long long _mpy32ll(int src1, int src2) -{ - return ((long long) src1) * src2; -} - -static inline long long _mpy32su(int src1, unsigned int src2) -{ - return ((long long) src1) * ((int) src2); -} - -static inline long long _mpy32u(unsigned int src1, unsigned int src2) -{ - return ((long long) ((int) src1)) * ((long long) ((int) src2)); -} - -static inline long long _mpy32us(unsigned int src1, int src2) -{ - return ((int) src1) * ((long long) src2); -} - -static inline int _mvd (int src2) -{ - return src2; -} - - -static inline unsigned int _norm(int src2) -{ - return norm_shift_amt_U_and_non_U(1,src2); -} - - -static inline unsigned int _pack2 (unsigned int src1, unsigned int src2) { - short s1[2], s2[2], r[2]; - int result; - *((int*)s1) = src1; - *((int*)s2) = src2; - r[0] = s2[0]; - r[1] = s1[0]; - result = *(int*)r; - return result; -} - - -static inline int _packh2 (unsigned int src1, unsigned int src2) { - unsigned v0 = src1 & 0xffff0000; - unsigned v1 = src2 >> 16; - unsigned v = v0|v1; - return v; - -} - -static inline unsigned int _packh4 (unsigned int src1, unsigned int src2) { - unsigned v3 = (src1 >> 24) & 0xff; - unsigned v2 = (src1 >> 8) & 0xff; - unsigned v1 = (src2 >> 24) & 0xff; - unsigned v0 = (src2 >> 8) & 0xff; - unsigned v = (v3<<24) | (v2<<16) | (v1 << 8) | v0; - return v; -} - -static inline unsigned int _packhl2 (unsigned int src1, unsigned int src2) { - unsigned v0 = src1 & 0xffff0000; - unsigned v1 = src2 & 0x0000ffff; - unsigned v = v0|v1; - return v; -} - -static inline unsigned int _packlh2 (unsigned int src1, unsigned int src2) { - unsigned v0 = src1 << 16; - unsigned v1 = (src2 >> 16) & 0xffff; - unsigned v = v0|v1; - return v; -} - - - - -static inline unsigned int _packl4 (unsigned int src1, unsigned int src2) { - unsigned v3 = (src1 >> 16) & 0xff; - unsigned v2 = (src1) & 0xff; - unsigned v1 = (src2 >> 16) & 0xff; - unsigned v0 = (src2) & 0xff; - unsigned v = (v3<<24) | (v2<<16) | (v1 << 8) | v0; - return v; -} - - - - -static inline unsigned int _rpack2 (unsigned int src1, unsigned int src2) { -int s1 = (int) src1; -int s2 = (int) src2; -s1 = util_shift_right_saturate_n (s1, -1, 32); -s2 = util_shift_right_saturate_n (s2, -1, 32); -return (unsigned int) (s1 & 0xffff0000) | (unsigned int) ((s2 & 0xffff0000) >>16); -} - - -static inline unsigned int _rotl (unsigned int src1, unsigned int src2) -{ - src2 &= 0x1f; - return (src1 << src2) | (src1 >> (32 - src2)); -} - - -static inline int _sadd(int src1, int src2) { -signed long long res; -signed long long maxv, minv; -maxv = (1LL << (32-1)) - 1; -minv = (-1LL << (32-1)); -res = (long long) src1 + (long long) src2; -if (res > maxv) { - res = maxv; - _overflow = 1; - } -else if (res < minv ) { - res = minv; - _overflow = 1; - } -return (int) res; -} - -static inline long long _saddsub(unsigned int src1, unsigned int src2) { -int radd; -signed long long rsub; - -signed long long maxv, minv; -maxv = (1LL << (32-1)) - 1; -minv = (-1LL << (32-1)); - -radd = (int) src1 + (int) src2; - -// saturate on subtract, not add - - -rsub = (long long) ((int) src1) - (long long) ((int) src2); -if (rsub > maxv) { - rsub = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (rsub < minv ) { - rsub = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } - -return (((unsigned long long) radd) << 32) | ( rsub & 0x00000000ffffffff ) ; -} - - - -static inline long long _saddsub2(unsigned int src1, unsigned int src2) { -signed int radd[2]; -signed int rsub[2]; -signed short s1[2], s2[2]; - -signed int maxv, minv; -maxv = (1L << (16-1)) - 1; -minv = (-1L << (16-1)); - -*((int*)s1) = src1; -*((int*)s2) = src2; - -radd[0] = (int) s1[0] + (int) s2[0]; -radd[1] = (int) s1[1] + (int) s2[1]; - -rsub[0] = (int) s1[0] - (int) s2[0]; -rsub[1] = (int) s1[1] - (int) s2[1]; - -if (radd[0] > maxv) { - radd[0] = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (radd[0] < minv ) { - radd[0] = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } - -if (radd[1] > maxv) { - radd[1] = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (radd[1] < minv ) { - radd[1] = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } - - -if (rsub[0] > maxv) { - rsub[0] = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (rsub[0] < minv ) { - rsub[0] = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } - -if (rsub[1] > maxv) { - rsub[1] = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (rsub[1] < minv ) { - rsub[1] = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } - - -return ((((unsigned long long) radd[1]) & 0x000000000000ffff) << 48) | - ((((unsigned long long) radd[0]) & 0x000000000000ffff) << 32) | - ((((unsigned long long) rsub[1]) & 0x000000000000ffff) << 16) | - ((((unsigned long long) rsub[0]) & 0x000000000000ffff)); -} - - - -static inline int _sadd2(int src1, int src2) { -signed short s1[2], s2[2]; -signed int r[2], maxv, minv; - -maxv = (1L << (16-1)) - 1; -minv = (-1L << (16-1)); - - -*((int*)s1) = src1; -*((int*)s2) = src2; - -r[0] = (int) s1[0] + (int) s2[0]; -r[1] = (int) s1[1] + (int) s2[1]; - -if (r[0] > maxv) { - r[0] = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (r[0] < minv ) { - r[0] = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -if (r[1] > maxv) { - r[1] = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (r[1] < minv ) { - r[1] = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } - -return ((r[1] & 0xffff) << 16 ) | (r[0] & 0xffff) ; -} - - -static inline int _saddus2(unsigned int src1, int src2) { -int res0, res1; - unsigned int s1_0 = (src1 & 0xffff); - unsigned int s1_1 = (src1 & 0xffff0000) >> 16; - - short s2_0 = (src2 & 0xffff); - short s2_1 = (src2 & 0xffff0000) >> 16; - - res0 = s1_0 + s2_0; - res1 = s1_1 + s2_1; - - if (res0 >= 0x10000) - res0 = 0xffff; - else if (res0 < 0) - res0 = 0; - - if (res1 >= 0x10000) - res1 = 0xffff; - else if (res1 < 0) - res1 = 0; - - return (res1 << 16) | res0; -} - - -static inline unsigned int _saddu4(unsigned int src1, unsigned int src2) { -unsigned int res0, res1, res2, res3; - unsigned int s1_0 = (src1 & 0xff); - unsigned int s1_1 = (src1 & 0xff00) >> 8; - unsigned int s1_2 = (src1 & 0xff0000) >> 16; - unsigned int s1_3 = (src1 & 0xff000000) >> 24; - - unsigned int s2_0 = (src2 & 0xff); - unsigned int s2_1 = (src2 & 0xff00) >> 8; - unsigned int s2_2 = (src2 & 0xff0000) >> 16; - unsigned int s2_3 = (src2 & 0xff000000) >> 24; - - res0 = s1_0 + s2_0; - res1 = s1_1 + s2_1; - res2 = s1_2 + s2_2; - res3 = s1_3 + s2_3; - - if (res0 >= 0x100) - res0 = 0xff; - - if (res1 >= 0x100) - res1 = 0xff; - - if (res2 >= 0x100) - res2 = 0xff; - - if (res3 >= 0x100) - res3 = 0xff; - - return (res3 << 24) | (res2 << 16) | (res1 << 8) | res0; - -} - - - -static inline int _sat(C6X_COMPAT_LONG40 src2) -{ - long long maxv = (1LL << (32-1)) - 1; - long long minv = (-1LL << (32-1)); - - int hi = (int)(src2 >> 32); - int lo = (int)src2; - long long temp = (unsigned long long)(unsigned)lo | (unsigned long long)hi << 32; - temp = orig_L40_set(temp); - - if (temp > maxv) { - temp = maxv; - _overflow = 1; - } - else if (temp < minv) { - temp = minv; - _overflow = 1; - } - return (int) temp; -} - -static inline unsigned int _set(unsigned int src2, unsigned int csta, unsigned int cstb) -{ - csta &= 0x1f; - cstb &= 0x1f; - if (csta > cstb) - return src2; - else { - unsigned int mask = (((1 << (cstb - csta)) << 1) - 1) << csta; - return src2 | mask; - } -} - -static inline unsigned int _setr(unsigned int src2, int src1) -{ - unsigned int csta = (src1 >> 5) & 0x1f; - unsigned int cstb = src1 & 0x1f; - if (csta > cstb) - return src2; - else { - unsigned int mask = (((1 << (cstb - csta)) << 1) - 1) << csta; - return src2 | mask; - } -} - - -static inline unsigned int _shfl (unsigned int src2) -{ - unsigned short lo = src2; - unsigned short hi = src2 >> 16; - unsigned int result = 0; - int i; - for (i = 0; i < 32; i+= 2) { - result >>= 1; - result |= (lo & 0x1) << 31; - lo >>= 1; - result >>= 1; - result |= (hi & 0x1) << 31; - hi >>= 1; - } - return result; -} - -static inline long long _shfl3 (unsigned int src1, unsigned int src2) -{ - unsigned short lo = src2; - unsigned short hi = src1 >> 16; - unsigned short mid = src1; - unsigned long long result = 0; - int i; - for (i = 0; i < 32; i+= 2) { - result >>= 1; - result |= ((unsigned long long) (lo & 0x1)) << 47; - lo >>= 1; - result >>= 1; - result |= ((unsigned long long) (mid & 0x1)) << 47; - mid >>= 1; - result >>= 1; - result |= ((unsigned long long) (hi & 0x1)) << 47; - hi >>= 1; - } - return result; -} - - - -static inline unsigned int _shlmb (unsigned int src1, unsigned int src2) -{ - return (src2 << 8) | (src1 >> 24); -} - -static inline unsigned int _shrmb (unsigned int src1, unsigned int src2) -{ - return (src2 >> 8) | (src1 << 24); -} - - -static inline unsigned int _shru2 (unsigned int src1, unsigned int src2) { -unsigned short hs1 = src1 >> 16; - unsigned short ls1 = src1 & 0xFFFF; - hs1 >>= src2; - ls1 >>= src2; - return (hs1 << 16) | ls1; -} - - -static inline int _shr2 (int src1, unsigned int src2) { - short s1[2], result[2]; - *((int*)s1) = src1; - src2 = src2 & 31; - result[0] = (int)s1[0] >> src2; - result[1] = (int)s1[1] >> src2; - - return *(int*)result; -} - - -static inline int _smpy (int src1, int src2) { -unsigned long long result; -result = (((short) src1 * (short) src2) << 1); - -if ((result & 0xffffffff) == 0x80000000){ - result = 0x7fffffff; - _overflow = 1; - } -return (int) (result); -} - -static inline int _smpyh (int src1, int src2) { -unsigned long long result; -result = ((short) (src1 >> 16) * (short) (src2 >> 16)) << 1; -if ((result & 0xffffffff) == 0x80000000){ - result = 0x7fffffff; - _overflow = 1; - } -return (int) (result); -} - -static inline int _smpyhl (int src1, int src2) { -unsigned long long result; -result = ((short) (src1 >> 16) * (short) (src2)) << 1; -if ((result & 0xffffffff) == 0x80000000){ - result = 0x7fffffff; - _overflow = 1; - } -return (int) (result); -} - -static inline int _smpylh (int src1, int src2) { -unsigned long long result; -result = ((short) (src1) * (short) (src2 >> 16)) << 1; -if ((result & 0xffffffff) == 0x80000000){ - result = 0x7fffffff; - _overflow = 1; - } -return (int) (result); -} - -static inline long long _smpy2ll (int src1, int src2) { - short ls1 = src1 & 0XFFFF; - short hs1 = src1 >> 16; - short ls2 = src2 & 0XFFFF; - short hs2 = src2 >> 16; - - unsigned long long hi = (hs1 * hs2) << 1; - unsigned long long lo = ((ls1 * ls2) << 1) & 0xFFFFFFFF; - if ((hi & 0xffffffff) == 0x80000000){ - hi = 0x7fffffff; - _overflow = 1; - } - - if ((lo & 0xffffffff) == 0x80000000){ - lo = 0x7fffffff; - _overflow = 1; - } - - return (hi << 32) | lo; -} - - - - -static inline int _smpy32(int src1, int src2) -{ - long long res = (long long) src1 * src2; - res <<= 1; - res >>= 32; - return res; -} - -static inline unsigned char TEN_satu8 (short src) -{ - if (src > 0xff) - return 0xff; - else if (src < 0) - return 0; - else - return src; -} - -static inline int _spack2 (int src1, int src2) { -short s1 = (short) util_saturate_n_no_state(src1,16); -short s2 = (short) util_saturate_n_no_state(src2,16); -return ( (unsigned int) s1 << 16) | (((int) s2) & 0xFFFF); -} - - -static inline unsigned int _spacku4 (int src1, int src2) { - short lolo = src2; - short lohi = src2 >> 16; - short hilo = src1; - short hihi = src1 >> 16; - - lolo = TEN_satu8(lolo); - lohi = TEN_satu8(lohi); - hilo = TEN_satu8(hilo); - hihi = TEN_satu8(hihi); - - return (((unsigned int) hihi) << 24) | (((unsigned int) hilo) << 16) | (lohi << 8) | lolo; -} - - - -static inline int _sshl (int src1, unsigned int src2) { -short local2 = (short)(src2 & 0x7FFF); -return (int) util_shift_right_saturate_n(src1, -local2, 32); -} - - - - -static inline int _sshvl (int src2, int src1) { - short s1; - if (src1 > 31) - s1 = 31; - else if (src1 < -31) - s1 = -31; - else - s1 = src1; - - return (int) util_shift_right_saturate_n(src2, -s1, 32); -} - - - - - -static inline int _sshvr (int src2, int src1) { -short s1; - if (src1 > 31) - s1 = 31; - else if (src1 < -31) - s1 = -31; - else - s1 = src1; - return (int) util_shift_right_saturate_n(src2, s1, 32); -} - - - - -static inline int _ssub(int src1, int src2) { -signed long long res; -signed long long maxv, minv; -maxv = (1LL << (32-1)) - 1; -minv = (-1LL << (32-1)); -res = (long long) src1 - (long long) src2; -if (res > maxv) { - res = maxv; - _overflow = 1; - } -else if (res < minv ) { - res = minv; - _overflow = 1; - } -return (int) res; -} - -static inline int _ssub2(int src1, int src2) { -signed short s1[2], s2[2]; -signed int r[2], maxv, minv; - -maxv = (1L << (16-1)) - 1; -minv = (-1L << (16-1)); - - -*((int*)s1) = src1; -*((int*)s2) = src2; - -r[0] = (int) s1[0] - (int) s2[0]; -r[1] = (int) s1[1] - (int) s2[1]; - -if (r[0] > maxv) { - r[0] = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (r[0] < minv ) { - r[0] = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -if (r[1] > maxv) { - r[1] = maxv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } -else if (r[1] < minv ) { - r[1] = minv; - /* NOTE: TI c6x does NOT set the overflow register even if results saturate */ - /* _overflow = 1; */ - } - -return ((r[1] & 0xffff) << 16 ) | (r[0] & 0xffff) ; -} - - -static inline int _subabs4 (int src1, int src2) { - int res0, res1, res2, res3; - unsigned int s1_0 = (src1 & 0xff); - unsigned int s1_1 = (src1 & 0xff00) >> 8; - unsigned int s1_2 = (src1 & 0xff0000) >> 16; - unsigned int s1_3 = (src1 & 0xff000000) >> 24; - - unsigned int s2_0 = (src2 & 0xff); - unsigned int s2_1 = (src2 & 0xff00) >> 8; - unsigned int s2_2 = (src2 & 0xff0000) >> 16; - unsigned int s2_3 = (src2 & 0xff000000) >> 24; - - res0 = s1_0 - s2_0; - res1 = s1_1 - s2_1; - res2 = s1_2 - s2_2; - res3 = s1_3 - s2_3; - - if (res0 < 0) - res0 = -res0; - - if (res1 < 0) - res1 = -res1; - - if (res2 < 0) - res2 = -res2; - - if (res3 < 0) - res3 = -res3; - - return (res3 << 24) | (res2 << 16) | (res1 << 8) | res0; -} - - -static inline unsigned int _subc (unsigned int src1, unsigned int src2) -{ - if ( src1 >= src2) - return ((src1 - src2) << 1) + 1; - else - return src1 << 1; -} - - - -static inline int _sub2(int src1, int src2) { - short s1[2], s2[2], r[2]; - int result; - *((int*)s1) = src1; - *((int*)s2) = src2; - r[0] = s1[0] - s2[0]; - r[1] = s1[1] - s2[1]; - result = *(int*)r; - return result; -} - - -static inline int _sub4(int src1, int src2) { - char c1[4], c2[4], r[4]; - int result; - *((int*)c1) = src1; - *((int*)c2) = src2; - r[0] = c1[0] - c2[0]; - r[1] = c1[1] - c2[1]; - r[2] = c1[2] - c2[2]; - r[3] = c1[3] - c2[3]; - result = *(int*)r; - return result; -} - - -static inline int _swap4 (unsigned int src1) { - unsigned char v0 = src1; - unsigned char v1 = src1 >> 8; - unsigned char v2 = src1 >> 16; - unsigned char v3 = src1 >> 24; - unsigned v = v0<<8 | v1 | v2<<24 | v3<<16; - return v; -} - -static inline unsigned int _unpkhu4 (unsigned int src1) { - unsigned v0 = src1>>24; - unsigned v1 = (src1>>16) & 0xff; - return (v0<<16) | v1; -} - -static inline unsigned int _unpklu4 (unsigned int src1) { - unsigned v1 = (src1>>8) & 0xff; - unsigned v0 = (src1) & 0xff; - return (v1<<16) | v0; -} - - - - -static inline unsigned int _xpnd2 (unsigned int src1) { - int v0 = (src1 & 0x1) ? 0x0000ffff : 0x00000000; - int v1 = (src1 & 0x2) ? 0xffff0000 : 0x00000000; - return v0|v1; -} - -static inline unsigned int _xpnd4 (unsigned int src1) { - int v0 = (src1 & 0x1) ? 0x000000ff : 0x00000000; - int v1 = (src1 & 0x2) ? 0x0000ff00 : 0x00000000; - int v2 = (src1 & 0x4) ? 0x00ff0000 : 0x00000000; - int v3 = (src1 & 0x8) ? 0xff000000 : 0x00000000; - int r = v0|v1|v2|v3; - return r; -} - - - -// end of Implemented in alphabetical order - - -#endif /* __C6X_COMPAT__H */ diff --git a/tools/sdk/include/esp32/xtensa/cacheasm.h b/tools/sdk/include/esp32/xtensa/cacheasm.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/cacheattrasm.h b/tools/sdk/include/esp32/xtensa/cacheattrasm.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/config/core.h b/tools/sdk/include/esp32/xtensa/config/core.h index 98f1b1961a8..0204757b055 100644 --- a/tools/sdk/include/esp32/xtensa/config/core.h +++ b/tools/sdk/include/esp32/xtensa/config/core.h @@ -1401,5 +1401,16 @@ extern const unsigned int XCJOIN(Xthal_cp_mask_,XCHAL_CP7_IDENT); #define XCHAL_ERRATUM_497 0 #endif +/* + * Erratum 572 (releases TBD, but present in ESP32) + * Disable zero-overhead loop buffer to prevent rare illegal instruction + * exceptions while executing zero-overhead loops. + */ +#if ( XCHAL_HAVE_LOOPS && XCHAL_LOOP_BUFFER_SIZE != 0 ) +#define XCHAL_ERRATUM_572 1 +#else +#define XCHAL_ERRATUM_572 0 +#endif + #endif /*XTENSA_CONFIG_CORE_H*/ diff --git a/tools/sdk/include/esp32/xtensa/core-macros.h b/tools/sdk/include/esp32/xtensa/core-macros.h old mode 100755 new mode 100644 index c8f7e347627..37c48921a4f --- a/tools/sdk/include/esp32/xtensa/core-macros.h +++ b/tools/sdk/include/esp32/xtensa/core-macros.h @@ -335,7 +335,7 @@ __asm__ __volatile__("wsr.intenable %0" :: "a"(__intenable):"memory"); \ } while(0) # define XTHAL_GET_INTERRUPT() ({ int __interrupt; \ - __asm__("rsr.interrupt %0" : "=a"(__interrupt)); \ + __asm__ __volatile__("rsr.interrupt %0" : "=a"(__interrupt)); \ __interrupt; }) # define XTHAL_SET_INTSET(v) do { int __interrupt = (int)(v); \ __asm__ __volatile__("wsr.intset %0" :: "a"(__interrupt):"memory"); \ @@ -344,7 +344,7 @@ __asm__ __volatile__("wsr.intclear %0" :: "a"(__interrupt):"memory"); \ } while(0) # define XTHAL_GET_CCOUNT() ({ int __ccount; \ - __asm__("rsr.ccount %0" : "=a"(__ccount)); \ + __asm__ __volatile__("rsr.ccount %0" : "=a"(__ccount)); \ __ccount; }) # define XTHAL_SET_CCOUNT(v) do { int __ccount = (int)(v); \ __asm__ __volatile__("wsr.ccount %0" :: "a"(__ccount):"memory"); \ diff --git a/tools/sdk/include/esp32/xtensa/coreasm.h b/tools/sdk/include/esp32/xtensa/coreasm.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/corebits.h b/tools/sdk/include/esp32/xtensa/corebits.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/debugfs.h b/tools/sdk/include/esp32/xtensa/debugfs.h deleted file mode 100755 index eba7b438cd3..00000000000 --- a/tools/sdk/include/esp32/xtensa/debugfs.h +++ /dev/null @@ -1,93 +0,0 @@ -/* Xtensa Debug-FileSystem definitions */ - -/* - * Copyright (c) 2005-2009 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -#ifndef __DEBUGFS_H__ -#define __DEBUGFS_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include - -int xt_dbfs_open(const char *pathname, int flags, mode_t mode); -int xt_dbfs_ftruncate(int fd, off_t length); -int xt_dbfs_truncate(const char * filename, off_t length); -int xt_dbfs_creat(const char *pathname, mode_t mode); -int xt_dbfs_errno(void); -int xt_dbfs_lseek(int fd, off_t offset, int whence); -ssize_t xt_dbfs_write(int fd, const void * buf, size_t bytes); - ssize_t xt_dbfs_open_append_close(const char * filename, int align, - const void * buf, size_t bytes); -ssize_t xt_dbfs_read(int fd, void * buf, size_t bytes); -int xt_dbfs_close(int fd); -int xt_dbfs_unlink(const char *pathname); - -/* By default, this function is a wrapper around sbrk, and follows - sbrk semantics: - - On success, it returns increment bytes of memory allocated from - system memory. - - On failure, it returns 0xFFFFFFFF - - - If you want to use a method of allocating memory other than sbrk, - implement xt_dbfs_sbrk in your own sources, and the linker will - automatically use that copy. -*/ -void * xt_dbfs_sbrk(int increment); - - - -#ifdef REPLACE_FS_WITH_DBFS -#define open xt_dbfs_open -#define close xt_dbfs_close -#define creat xt_dbfs_creat -#define lseek xt_dbfs_lseek -#define write xt_dbfs_write -#define read xt_dbfs_read -#define close xt_dbfs_close -#define unlink xt_dbfs_unlink - -#define rmdir NOT_IMPLEMENTED_IN_DBFS -#define opendir NOT_IMPLEMENTED_IN_DBFS -#define closedir NOT_IMPLEMENTED_IN_DBFS -#define dirfs NOT_IMPLEMENTED_IN_DBFS -#define readdir NOT_IMPLEMENTED_IN_DBFS -#define scandir NOT_IMPLEMENTED_IN_DBFS -#define seekdir NOT_IMPLEMENTED_IN_DBFS -#define telldir NOT_IMPLEMENTED_IN_DBFS - -#define fcntl NOT_IMPLEMENTED_IN_DBFS -#define dup2 NOT_IMPLEMENTED_IN_DBFS -#define dup NOT_IMPLEMENTED_IN_DBFS -#define flock NOT_IMPLEMENTED_IN_DBFS -#define lockf NOT_IMPLEMENTED_IN_DBFS -#define link NOT_IMPLEMENTED_IN_DBFS -#define stat NOT_IMPLEMENTED_IN_DBFS -#define fstat NOT_IMPLEMENTED_IN_DBFS -#define lstat NOT_IMPLEMENTED_IN_DBFS -#define chmod NOT_IMPLEMENTED_IN_DBFS -#define fchmod NOT_IMPLEMENTED_IN_DBFS -#define chmown NOT_IMPLEMENTED_IN_DBFS -#define lchown NOT_IMPLEMENTED_IN_DBFS -#define fchown NOT_IMPLEMENTED_IN_DBFS - -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/esp32/xtensa/feedback.h b/tools/sdk/include/esp32/xtensa/feedback.h deleted file mode 100755 index aecb7453332..00000000000 --- a/tools/sdk/include/esp32/xtensa/feedback.h +++ /dev/null @@ -1,45 +0,0 @@ - -/* - * Copyright (c) 2013 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -#ifndef __XT_FEEDBACK_INCLUDED__ -#define __XT_FEEDBACK_INCLUDED__ - -#ifdef __cplusplus -extern "C" { -#endif - -/* xt_feedback_save_and_reset - - Save and reset the accumulated feedback data. -*/ -extern void xt_feedback_save_and_reset(void); - -/* xt_feedback_enable - - Turn on feedback accumulation. Ordinarily, feedback accumulation is on - by default. If you turn it off using xt_feedback_disable, You can turn - it on again via this function. -*/ -extern void xt_feedback_enable (void); - -/* xt_feedback_disable - - Turn off feedback accumulation. If you don't want to gather feedback for a - portion of your code, use this function and then xt_feedback_enable when - you want to start again. -*/ -extern void xt_feedback_disable (void); - -#ifdef __cplusplus -} -#endif - -#endif /* __XT_FEEDBACK_INCLUDED__ */ - diff --git a/tools/sdk/include/esp32/xtensa/gdbio.h b/tools/sdk/include/esp32/xtensa/gdbio.h deleted file mode 100755 index 784a8629788..00000000000 --- a/tools/sdk/include/esp32/xtensa/gdbio.h +++ /dev/null @@ -1,80 +0,0 @@ -/* Xtensa Debug-FileSystem definitions - * - * Copyright (c) 2006-2009 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -#ifndef __DEBUGFS_H__ -#define __DEBUGFS_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include -#include - - int _gdbio_open_r(void * ptr, const char *pathname, int flags, mode_t mode); - int _gdbio_creat_r(void * ptr, const char *pathname, mode_t mode); - int _gdbio_lseek_r(void * ptr, int fd, off_t offset, int whence); - ssize_t _gdbio_write_r(void * ptr, int fd, const void * buf, size_t bytes); - ssize_t _gdbio_read_r(void * ptr, int fd, void * buf, size_t bytes); - int _gdbio_close_r(void * ptr, int fd); - int _gdbio_unlink_r(void * ptr, const char * pathname); - - static inline - int gdbio_open(const char *pathname, int flags, mode_t mode) { - return _gdbio_open_r(&errno, pathname, flags, mode); - } - static inline int - gdbio_creat(const char *pathname, mode_t mode) { - return _gdbio_open_r(&errno, pathname, O_CREAT|O_WRONLY|O_TRUNC, mode); - } - static inline int - gdbio_errno(void) { - return errno; - } - static inline int - gdbio_lseek(int fd, off_t offset, int whence) { - return _gdbio_lseek_r(&errno, fd, offset, whence); - } - static inline - ssize_t gdbio_write(int fd, const void * buf, size_t bytes) { - return _gdbio_write_r(&errno, fd, buf, bytes); - } - static inline - ssize_t gdbio_read(int fd, void * buf, size_t bytes) { - return _gdbio_read_r(&errno, fd, buf, bytes); - } - static inline int - gdbio_close(int fd) { - return _gdbio_close_r(&errno, fd); - } - static inline int - gdbio_unlink(const char * pathname) { - return _gdbio_unlink_r(&errno, pathname); - } - -#ifdef REPLACE_FS_WITH_GDBIO -#define open gdbio_open -#define close gdbio_close -#define creat gdbio_creat -#define lseek gdbio_lseek -#define write gdbio_write -#define read gdbio_read -#define close gdbio_close -#define unlink gdbio_unlink - -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/esp32/xtensa/hal.h b/tools/sdk/include/esp32/xtensa/hal.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/jtag-xtensa.h b/tools/sdk/include/esp32/xtensa/jtag-xtensa.h deleted file mode 100755 index 45ac1caa40f..00000000000 --- a/tools/sdk/include/esp32/xtensa/jtag-xtensa.h +++ /dev/null @@ -1,99 +0,0 @@ -/* Copyright (c) 2011-2012 Tensilica Inc. ALL RIGHTS RESERVED. -// These coded instructions, statements, and computer programs are the -// copyrighted works and confidential proprietary information of Tensilica Inc. -// They may not be modified, copied, reproduced, distributed, or disclosed to -// third parties in any manner, medium, or form, in whole or in part, without -// the prior written consent of Tensilica Inc. -*/ - -#ifndef _JTAG_XTENSA_H_ -#define _JTAG_XTENSA_H_ - - -/* ---------------- JTAG registers ------------------ */ - -/* -- ER and later JTAG registers */ -typedef enum { - regIR, - regBypass, - regNAR, - regNDR, - regIdcode, - regPWRCTL, - regPWRSTAT, - regJtagMAX, -} xtensaJtagReg; - -/* -- pre-ER JTAG registers */ -typedef enum { - regOldIR, - regOldBypass, - regOldDIRW, - regOldDIR, - regOldDDR, - regOldDOSR, - regOldESR, - regOldDCR, - regOldTraxNDR, - regOldTraxNAR, - regOldMAX -} xtensaOldJtagReg; - - -/* ---------------- JTAG Instructions ------------------ */ - -/* -- pre-ER JTAG instructions */ -typedef enum { - ji_EnableOCD = 0x11, - ji_DebugInt, - ji_RetDebugInt, // TBD: remove - ji_DisRetOCD, // TBD: remove - ji_ExecuteDI, - ji_LoadDI, - ji_ScanDDR, - ji_ReadDOSR, - ji_ScanDCR, - ji_LoadWDI, - ji_TRAX = 0x1c, - ji_BYPASS = 0x1f, -} xtensaJtagInstruction; - -typedef enum { - OCDNormalMode, - OCDRunMode, - OCDHaltMode, - OCDStepMode -} xtensaMode; - -typedef struct { - xtensaMode mode; - int DRsel; - XTMP_core core; - XTMP_tap tap; - int core_num; - jtagReg_t *jtagRegs; - void *dap; // used for ARM DAP only - bool isBig; - int dir_array_option; // used by pre-ER devices only - // for testing, below - FIXME - delete later - int ocdReg; - unsigned int wr_data; - XTMP_event start_OCD_trans; - bool data_cycle; - bool data_pending; -} coreSlaveData_t; - - -enum OCD_ACCESS_TYPE{ - NEXUS_ACCESS, - CS_ACCESS, -}; - -// pre-ER Xtensa initializiation -EXTERN XTMP_deviceStatus -XTMP_jtagCoreSlaveEX(XTMP_component component, XTMP_jtagSlave slave, void* mydata); - -extern char *OCDrd; -extern char *OCDwr; - -#endif diff --git a/tools/sdk/include/esp32/xtensa/lcd-splc780d-4bitmode-board.h b/tools/sdk/include/esp32/xtensa/lcd-splc780d-4bitmode-board.h deleted file mode 100755 index f4db5885829..00000000000 --- a/tools/sdk/include/esp32/xtensa/lcd-splc780d-4bitmode-board.h +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* -Copyright (c) 2009-2013 by Tensilica Inc. ALL RIGHTS RESERVED. -These coded instructions, statements, and computer programs are the -copyrighted works and confidential proprietary information of Tensilica Inc. -They may not be modified, copied, reproduced, distributed, or disclosed to -third parties in any manner, medium, or form, in whole or in part, without -the prior written consent of Tensilica Inc. --------------------------------------------------------------------------------- - -lcd-splc780d-4bitmode-board.h Board-specific LCD info for these boards: - Avnet AV110 (XT-AV110) - Xilinx ML605 (XT-ML605) - Xilinx KC705 (XT-KC705) - -Interface between board-independent driver and board-specific header. - -This is used by a board-independent SPLC780D LCD controller (4 bit mode) -driver to obtain board-specific information about LCD displays on the board, -such as the controller register base address and spacing (a function of how -the address lines are connected on the board) and length of the visible window -of the display (a function of the LCD panel the controller drives). -The driver doesnot refer directly to the board-specific header, which therefore is not -constrained to use macro names consistent with other boards. - -!! Must not contain any board-specific macro names (only controller specific) !! - -Included at compile-time via an include path specific to the board. - -The listed boards contain a single MYTech MOC-16216B-B display driven by -a Sunplus SPLC870D controller. - -*******************************************************************************/ - -#ifndef _LCD_SPLC780D_4BIT_BOARD_H -#define _LCD_SPLC780D_4BIT_BOARD_H - -#include /* Board info */ - - -/* Base address of the controller's registers. */ -#ifdef SPLC780D_4BIT_VADDR -#define SPLC780D_4BIT_REGBASE SPLC780D_4BIT_VADDR -#endif - -/* -The controller's registers are connected at word addresses on these boards. -Each byte-wide register appears as the least-significant-byte (LSB) of the -word regardless of the endianness of the processor (so if using word accesses -then endianness doesn't matter). -*/ -#define SPLC780D_4BIT_REGSPACING 4 -typedef unsigned splc780d_4bit_reg_t; - -/* Include generic information shared by all boards that use this device. */ -#include - - -/* Display limits of the LCD panel. */ -#define DISPLAY_VISIBLE_LEN 16 /* length (chars) of visible window */ - -#endif /* _LCD_SPLC780D_4BIT_BOARD_H */ - diff --git a/tools/sdk/include/esp32/xtensa/lcd-splc780d-4bitmode.h b/tools/sdk/include/esp32/xtensa/lcd-splc780d-4bitmode.h deleted file mode 100755 index 0a214bb400f..00000000000 --- a/tools/sdk/include/esp32/xtensa/lcd-splc780d-4bitmode.h +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - -Copyright (c) 2009-2010 by Tensilica Inc. ALL RIGHTS RESERVED. -These coded instructions, statements, and computer programs are the -copyrighted works and confidential proprietary information of Tensilica Inc. -They may not be modified, copied, reproduced, distributed, or disclosed to -third parties in any manner, medium, or form, in whole or in part, without -the prior written consent of Tensilica Inc. --------------------------------------------------------------------------------- - -lcd-SPLC780D-4bitmode.h Generic definitions for Sunplus SPLC780D LCD Controller -operating in 4 bit mode. - -This is used by board-support-packages with one or more LCD displays that use -a SPLC780D controller in 4 bit mode. A BSP provides a base address for each -instance of an SPLC780D LCD controller on the board. - -Note that LCD display operation is almost totally independent of the LCD -display, depending almost entirely on the controller. However the display -may limit the number of characters of the controller's RAM buffer that are -actually visible at one time. The length of the display's visible window -is not specifified in this controller-specific header, but comes to the -driver from the board-specific "display.h" header. - -*******************************************************************************/ - -#ifndef _LCD_SPLC780D_4BIT_H_ -#define _LCD_SPLC780D_4BIT_H_ - - -/* Offsets to controller registers from base. */ -#define SPLC780D_4BIT_INST 0 -#define SPLC780D_4BIT_DATA (SPLC780D_4BIT_INST + SPLC780D_4BIT_REGSPACING) - - -#define SPLC780D_4BIT_INST_INIT1 0xFF /* First command in - init sequence */ -#define SPLC780D_4BIT_INST_INIT2 0x30 /* Second command in - init sequence, - issued 3 times */ -#define SPLC780D_4BIT_INST_INIT3 0x20 /* Third and last command - in init sequence */ -#define SPLC780D_4BIT_INST_CLEAR 0x01 /* clear (blank) display) */ -#define SPLC780D_4BIT_INST_SET_MODE 0x28 /* Set LCD mode. Supported - setting is 4 bit data - length, 2 lines, 5*8 */ -#define SPLC780D_4BIT_INST_DSPLY_ON 0x0C /* Set Display ON */ -#define SPLC780D_4BIT_INST_CRSR_INC 0x06 /* Set cursor moving direction - as increment */ - -#define SPLC780D_4BIT_LINET_ADDR 0x80 /* clear (blank) display) */ -#define SPLC780D_4BIT_LINEB_ADDR 0xC0 /* clear (blank) display) */ - -#ifndef __ASSEMBLER__ - -/* C interface to controller registers. */ -struct splc780d_4bit_s { - splc780d_4bit_reg_t inst; /* instruction register */ - splc780d_4bit_reg_t data; /* data register */ -}; - -typedef volatile struct splc780d_4bit_s splc780d_4bit_t; - -/* -Prototypes of high level driver functions. -*/ - -/* Write an instruction byte to LCD, result in two back to back writes since the - * LCD is hooked up in 4 bit mode*/ -extern void lcd_write_inst_byte(splc780d_4bit_t *lcd, unsigned char inst); - -/* Write a data byte to LCD, result in two back to back writes since the - * LCD is hooked up in 4 bit mode*/ -extern void lcd_write_data_byte(splc780d_4bit_t *lcd, unsigned char data); - -/* -Initialize the display with default settings. -*/ -extern void splc780d_4bit_init_default(splc780d_4bit_t *lcd); - -/* -Write a single character at a given position (chars from left, starting at 0). -Wait long enough afterward for the controller to be ready for more input. -Positions beyond the end of the display are ignored. -*/ -extern void splc780d_4bit_write_char(splc780d_4bit_t *lcd, unsigned pos, const char c); - -/* -Write a string to the display starting at the left (position 0). -Blank-pad to or truncate at the end of the display (overwrites any previous -string so don't need to blank the display first). -Wait long enough after each char for the controller to be ready for more input. -*/ -extern void splc780d_4bit_write_string(splc780d_4bit_t *lcd, const char *s); - -/* -Blank (clear) the entire display. -Wait long enough afterward for the controller to be ready for more input. -*/ -extern void splc780d_4bit_blank(splc780d_4bit_t *lcd); - -#endif /* __ASSEMBLER__ */ - -#endif /* _LCD_SPLC780D_4BIT_H_ */ - diff --git a/tools/sdk/include/esp32/xtensa/lcd-splc780d.h b/tools/sdk/include/esp32/xtensa/lcd-splc780d.h deleted file mode 100755 index 4e878e90532..00000000000 --- a/tools/sdk/include/esp32/xtensa/lcd-splc780d.h +++ /dev/null @@ -1,151 +0,0 @@ -/******************************************************************************* - -Copyright (c) 2006-2007 by Tensilica Inc. ALL RIGHTS RESERVED. -These coded instructions, statements, and computer programs are the -copyrighted works and confidential proprietary information of Tensilica Inc. -They may not be modified, copied, reproduced, distributed, or disclosed to -third parties in any manner, medium, or form, in whole or in part, without -the prior written consent of Tensilica Inc. --------------------------------------------------------------------------------- - -lcd-SPLC780D.h Generic definitions for Sunplus SPLC780D LCD Controller - -This is used by board-support-packages with one or more LCD displays that use -a SPLC780D controller. A BSP provides a base address for each instance of an -SPLC780D LCD controller on the board. - -Note that LCD display operation is almost totally independent of the LCD -display, depending almost entirely on the controller. However the display -may limit the number of characters of the controller's RAM buffer that are -actually visible at one time. The length of the display's visible window -is not specifified in this controller-specific header, but comes to the -driver from the board-specific "display.h" header. - -*******************************************************************************/ - -#ifndef _LCD_SPLC780D_H_ -#define _LCD_SPLC780D_H_ - - -/* Offsets to controller registers from base. */ -#define SPLC780D_INST 0 -#define SPLC780D_DATA (SPLC780D_INST + SPLC780D_REGSPACING) - -/* -Bit fields and their values in the instruction register. -These fields are NOT orthogonal - they overlap! -Thus only one field may be written at a time, determined by the -most-significant 1 bit in the pattern (the field selector). -All less significant bits are part of the value of the selected field. -The fields and their values are grouped together to emphasize this format. -Field selector macro names end in '_' (implying something more needs -to be ORed) and the value macros are indented. The pattern written to a -bitfield is a bitwise OR of a field selector and one or more values, eg. - (SPLC780D_INST_ON_ | SPLC780D_INST_ON_DISPLAY | SPLC780D_INST_ON_CURSOR) -A single bit field (eg. SPCL780D_INST_HOME) need not have a value. - -NOTE: Controller requires a software delay after writing to the control -or data registers. For the data register it is 38us. For the control -register it is 38us for most bit fields, with the following exceptions: - SPLC780D_FUNC_ 100us. - SPLC780D_INST_CLEAR, SPLC780D_INST_HOME 1520us. -For more details and reset timing, see the SUNPLUS SPLC780D data sheet. -*/ - -#define SPLC780D_INST_CLEAR_ 0x1 /* clear (blank) display) */ - -#define SPLC780D_INST_HOME_ 0x2 /* home cursor and shift pos */ - -#define SPLC780D_INST_ENTRY_ 0x4 /* combine *ENTRY_* flags below */ -#define SPLC780D_INST_ENTRY_SHIFT 0x1 /* display shift on entry / not */ -#define SPLC780D_INST_ENTRY_INCR 0x2 /* cursor incr / decr */ -#define SPLC780D_INST_ENTRY_DECR 0 /* cursor incr / decr */ - -#define SPLC780D_INST_ON_ 0x8 /* combine *ON_* flags below */ -#define SPLC780D_INST_ON_DISPLAY 0x4 /* display on / off */ -#define SPLC780D_INST_ON_CURSOR 0x2 /* cursor on / off */ -#define SPLC780D_INST_ON_BLINK 0x1 /* blink on / off */ - -#define SPLC780D_INST_SHIFT_ 0x10 /* combine *SHIFT_* flags below */ -#define SPLC780D_INST_SHIFT_DISP 0x8 /* shift display / move cursor */ -#define SPLC780D_INST_SHIFT_CURS 0 /* shift display / move cursor */ -#define SPLC780D_INST_SHIFT_RIGHT 0x4 /* shift right / left */ -#define SPLC780D_INST_SHIFT_LEFT 0 /* shift right / left */ - -#define SPLC780D_INST_FUNC_ 0x20 /* combine *FUNC_* flags below */ -#define SPLC780D_INST_FUNC_8BIT 0x10 /* data length 8 bit / 4 bit */ -#define SPLC780D_INST_FUNC_4BIT 0 /* data length 8 bit / 4 bit */ -#define SPLC780D_INST_FUNC_2LINE 0x08 /* display lines 2 / 1 */ -#define SPLC780D_INST_FUNC_1LINE 0 /* display lines 2 / 1 */ -#define SPLC780D_INST_FUNC_F5x10 0x04 /* character font 5x10 / 5x8 */ -#define SPLC780D_INST_FUNC_F5x8 0 /* character font 5x10 / 5x8 */ - /* font must be 5x8 for 2 lines */ -#define SPLC780D_INST_CGEN_ 0x40 /* set char generator address */ -#define SPLC780D_INST_CGEN_ADDR 0x3F /* to address in this field */ -#define SPLC780D_INST_DRAM_ 0x80 /* set display data RAM address */ -#define SPLC780D_INST_DRAM_ADDR 0x7F /* to address in this field */ -#define SPLC780D_INST_DRAM_LINE2 0x40 /* address offset to line 2 */ -/* Controller limits */ -#define SPLC780D_RAMLEN_1LINE 0x50 /* length of line in RAM (1 line) */ -#define SPLC780D_RAMLEN_2LINE 0x28 /* length of line in RAM (2 line) */ - - -#ifndef __ASSEMBLER__ - -/* C interface to controller registers. */ -struct splc780d_s { - splc780d_reg_t inst; /* instruction register */ - splc780d_reg_t data; /* data register */ -}; - -typedef volatile struct splc780d_s splc780d_t; - -/* -Prototypes of high level driver functions. -*/ - -/* -Initialize the display with the FUNC_, ENTRY_ and ON_ fields as specified in -terms of the values above. The splc780d_init_default() macro is an example. -*/ -extern void splc780d_init(splc780d_t *lcd, - unsigned func, unsigned entry, unsigned on); - -/* -Initialize the display to default mode: 8-bit interface, 2 line, 5x8 font, -increment cursor on entry, display on (cursor and blinking off). -*/ -#define splc780d_init_default(lcd) \ - splc780d_init( lcd, \ - SPLC780D_INST_FUNC_8BIT \ - | SPLC780D_INST_FUNC_2LINE \ - | SPLC780D_INST_FUNC_F5x8, \ - SPLC780D_INST_ENTRY_INCR, \ - SPLC780D_INST_ON_DISPLAY \ - ) - -/* -Write a single character at a given position (chars from left, starting at 0). -Wait long enough afterward for the controller to be ready for more input. -Positions beyond the end of the display are ignored. -*/ -extern void splc780d_write_char(splc780d_t *lcd, unsigned pos, const char c); - -/* -Write a string to the display starting at the left (position 0). -Blank-pad to or truncate at the end of the display (overwrites any previous -string so don't need to blank the display first). -Wait long enough after each char for the controller to be ready for more input. -*/ -extern void splc780d_write_string(splc780d_t *lcd, const char *s); - -/* -Blank (clear) the entire display. -Wait long enough afterward for the controller to be ready for more input. -*/ -extern void splc780d_blank(splc780d_t *lcd); - -#endif /* __ASSEMBLER__ */ - -#endif /* _LCD_SPLC780D_H_ */ - diff --git a/tools/sdk/include/esp32/xtensa/overlay.h b/tools/sdk/include/esp32/xtensa/overlay.h deleted file mode 100755 index e959cf512fb..00000000000 --- a/tools/sdk/include/esp32/xtensa/overlay.h +++ /dev/null @@ -1,184 +0,0 @@ -// overlay.h -- Overlay manager header file -// $Id$ - -// Copyright (c) 2013 Tensilica 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. - - -#ifndef OVERLAY_H -#define OVERLAY_H - - -#include - - -#ifdef __cplusplus -extern "C" { -#endif - -// Define this to turn off overlay support -#ifdef XT_DISABLE_OVERLAYS - -#define OVERLAY(n) -#define DECLARE_OVERLAY(n) - -#define xt_overlay_map(ov_id) -#define xt_overlay_map_async(ov_id) 0 -#define xt_overlay_map_in_progress() 0 -#define xt_overlay_get_id() 0 -#define xt_overlay_get_state(pc) 0 -#define xt_overlay_check_map(pc,ps,ovstate,sp) 0 - -#else - -// Shorthand for convenience and portability. -#define OVERLAY(n) __attribute__((overlay(n))) - -// Structure of the overlay table required by gdb and the overlay -// manager. Should not be accessed by user code unless overriding -// the load process. -struct ovly_table { - void * vma; // The overlay's mapped address. - unsigned int size; // The size of the overlay, in bytes. - void * lma; // The overlay's load address. - unsigned int mapped; // Non-zero if overlay is currently mapped; zero otherwise. -}; - -// Constructed by the linker. Required for gdb and for the overlay -// manager. Should not be accessed by user code unless overriding -// the load process. -extern struct ovly_table _ovly_table[]; - -// Functions. -void xt_overlay_map(int ov_id); -int xt_overlay_map_async(int ov_id); -int xt_overlay_map_in_progress(void); -unsigned int xt_overlay_get_state(unsigned int pc); -unsigned int xt_overlay_check_map(unsigned int * pc, unsigned int * ps, - unsigned int ovstate, unsigned int sp); -int xt_overlay_start_map(void * dst, void * src, unsigned int len, int ov_id); -int xt_overlay_is_mapping(int ov_id); -void xt_overlay_fatal_error(int ov_id); - - -// Returns the current overlay ID. If no overlay is mapped or an overlay -// is in the middle of being mapped, returns -1. Inlined to avoid calling -// out of overlay (wastes cycles, can end up reading wrong ID on interrupt -// activity). -// -static inline int xt_overlay_get_id(void) -{ -#pragma always_inline -extern short _mapping_id; -extern short _ovly_id; - - int ret; - unsigned int flags = XTOS_SET_INTLEVEL(15); - - if (_mapping_id >= 0) { - ret = -1; - } - else { - ret = _ovly_id; - } - - XTOS_RESTORE_INTLEVEL(flags); - return ret; -} - - -// The following macros are used to declare numbered overlays and generate -// the corresponding call stubs. Use as follows: -// -// DECLARE_OVERLAY(n) -// -// See documentation for more details. - -//#include - -// At this time overlays are not supported without windowing. -#if defined(__XTENSA_WINDOWED_ABI__) - -#define xstr(x) str(x) -#define str(x) #x - -// At entry, register a8 holds the return address and a9 holds the target -// function address. This stub saves a8 on the stack at (SP - 20) which -// is the only location that is safe for us to use. Then it allocates 32 -// bytes on the stack for working storage, loads the overlay number into -// a8, and jumps to the common handler. The common handler will make sure -// that the called function is loaded into memory before calling it. -// NOTE: we are using the stack area normally reserved for nested functions. -// This means nested functions cannot be used when overlays are in use. - -#define CALL_IN(num) \ - asm(".section .gnu.linkonce.t.overlay.call." xstr(num) ".text, \"ax\"\n" \ - ".global _overlay_call_in_" xstr(num) "_\n" \ - ".align 4\n" \ - "_overlay_call_in_" xstr(num) "_:\n" \ - "s32e a8, a1, -20\n" \ - "addi a8, a1, -32\n" \ - "movsp a1, a8\n" \ - "movi a8, " xstr(num) "\n" \ - "j _overlay_call_in_common\n" \ - ".size _overlay_call_in_" xstr(num) "_, . - _overlay_call_in_" xstr(num) "_\n"); - -// The call-out stub first calls the target function, then loads the overlay -// number into register a14 and jumps to the common handler. The handler will -// make sure that the caller function is present in memory before returning. -// Note that registers a10-a13 may contain return values so must be preserved. -// -// Because we came here via a call4, the return address is in a4, and the top -// 2 bits are set to the window increment. We'll restore the top 2 bits of -// the return address from the called function's address, assuming that both -// are in the same 1 GB segment. For now this is always true. - -#define CALL_OUT(num) \ - asm(".section .gnu.linkonce.t.overlay.call." xstr(num) ".text, \"ax\"\n" \ - ".global _overlay_call_out_" xstr(num) "_\n" \ - ".align 4\n" \ - "_overlay_call_out_" xstr(num) "_:\n" \ - "slli a4, a4, 2\n" \ - "srli a4, a4, 2\n" \ - "extui a8, a9, 30, 2\n" \ - "slli a8, a8, 30\n" \ - "or a4, a4, a8\n" \ - "callx8 a9\n" \ - "movi a14, " xstr(num) "\n" \ - "j _overlay_call_out_common\n" \ - ".size _overlay_call_out_" xstr(num) "_, . - _overlay_call_out_" xstr(num) "_\n"); - -// Generate a call-in and a call-out stub for each overlay. - -#define DECLARE_OVERLAY(num) \ - CALL_IN(num) \ - CALL_OUT(num) - -#endif // defined(__XTENSA_WINDOWED_ABI__) - -#endif // XT_DISABLE_OVERLAYS - -#ifdef __cplusplus -} -#endif - -#endif // OVERLAY_H - diff --git a/tools/sdk/include/esp32/xtensa/overlay_os_asm.h b/tools/sdk/include/esp32/xtensa/overlay_os_asm.h deleted file mode 100755 index 4adc044e6a6..00000000000 --- a/tools/sdk/include/esp32/xtensa/overlay_os_asm.h +++ /dev/null @@ -1,140 +0,0 @@ -// overlay_os_asm.h -- Overlay manager assembly macros for OS use. -// $Id$ - -// Copyright (c) 2013 Tensilica 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. - - -#ifndef OVERLAY_OS_ASM_H -#define OVERLAY_OS_ASM_H - -// The macros in here are intended to be used by RTOS task switch code -// to check overlay status. Such code is usually in assembly and cannot -// call C code without penalty. For C code usage, it is best to use the -// corresponding C functions from the library. - - -// Inline assembly version of xt_overlay_get_state(). The arguments are -// three AR registers (a0-a15): -// -// "pcreg" - should contain the outgoing task's PC, i.e. the point at -// which the task got interrupted. The return value is also -// returned in this register. -// "sr1/2" - Scratch registers. These must be distinct from "pcreg". -// -// The return value is a 32-bit result that should be saved with the -// task context and passed as-is to xt_overlay_check_map. - - .macro _xt_overlay_get_state pcreg sr1 sr2 - - movi \sr1, _mapping_id - movi \sr2, _ovly_id - l16si \sr1, \sr1, 0 - l16ui \sr2, \sr2, 0 - slli \sr1, \sr1, 16 - or \pcreg, \sr1, \sr2 - - .endm - - -// Inline assembly version of xt_overlay_check_map(). It requires 5 AR -// registers (a0-a15) as arguments. -// -// "pcreg" - should contain the interrupted task's PC, i.e. the point -// at which the task got interrupted. This will be adjusted -// if required. -// "psreg" - should contain the interrupted task's PS. This will be -// adjusted if required. -// "ovreg" - should contain the overlay state on entry. Contents may -// be clobbered. -// "spreg" - should contain the tasks stack pointer on entry. -// "sr1" - Scratch register. Must be distinct from any of the above. -// -// The return values are "pcreg" and "psreg" and these must be used -// to update the task's PC and PS. -// Note that this macro may store data below the "spreg" pointer. If -// it does, then it will also disable interrupts via the PS, so that -// the task resumes with all interrupts disabled (to avoid corrupting -// this data). -// -// (SP - 24) Overlay ID to restore -// (SP - 28) Task PC -// (SP - 32) Task PS - - .macro _xt_overlay_check_map pcreg psreg ovreg spreg sr1 - -// There are four cases to deal with: -// -// _ovly_id = -1, _mapping_id = -1 -// No overlay is mapped or mapping, nothing to do. -// -// _ovly_id >= 0, _mapping_id = -1 -// An overlay was mapped, check PC to see if we need a restore. -// -// _ovly_id = -1, _mapping_id >= 0 -// An overlay is being mapped. Either it belongs to this task, which -// implies that the PC is in the mapping function, or it does not -// belong to this task. Either way there is nothing to do. -// -// _ovly_id >= 0, _mapping_id >= 0 -// Illegal, cannot happen by design. Don't need to handle this. -// -// So, the logic is to check _ovly_id first. If this is >= 0, then -// we check the task PC. If the PC is in the regions of interest then -// we'll patch the return PC to invoke xt_overlay_restore. - -.L1: - extui \sr1, \ovreg, 0, 16 // Extract _ovly_id - bbsi.l \sr1, 15, .Lno // If -1 then we're done - mov \ovreg, \sr1 // Restore this one - -// Next check the PC to see if it falls within the ranges of interest. - -.L2: - movi \sr1, _overlay_vma // Is PC < VMA range ? - bltu \pcreg, \sr1, .L3 - movi \sr1, _overlay_vma_end // Is PC > VMA range ? - bgeu \pcreg, \sr1, .L3 - j .L4 // PC is in VMA range -.L3: - movi \sr1, _overlay_call_stubs_start // Is PC < call stubs range ? - bltu \pcreg, \sr1, .Lno - movi \sr1, _overlay_call_stubs_end // Is PC > call stubs range ? - bgeu \pcreg, \sr1, .Lno - -// If we get here then a restore is needed. Save the overlay ID, PC and PS. -// Return modified PC and PS so that xt_overlay_restore() will execute in -// the context of the task when resumed. Note that the OS resumption code -// may expect PS.EXCM to be set so we leave it as is in the return value. - -.L4: - s32e \ovreg, \spreg, -24 // Save overlay ID - s32e \pcreg, \spreg, -28 // Save task PC - s32e \psreg, \spreg, -32 // Save task PS - movi \pcreg, xt_overlay_restore // Adjust resumption PC - movi \sr1, 15 - or \psreg, \psreg, \sr1 // Set intlevel to highest -.Lno: - - .endm - -#endif // OVERLAY_OS_ASM_H - diff --git a/tools/sdk/include/esp32/xtensa/sim.h b/tools/sdk/include/esp32/xtensa/sim.h deleted file mode 100755 index e02087c5c07..00000000000 --- a/tools/sdk/include/esp32/xtensa/sim.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 2004-2006 by Tensilica Inc. ALL RIGHTS RESERVED. -/ These coded instructions, statements, and computer programs are the -/ copyrighted works and confidential proprietary information of Tensilica Inc. -/ They may not be modified, copied, reproduced, distributed, or disclosed to -/ third parties in any manner, medium, or form, in whole or in part, without -/ the prior written consent of Tensilica Inc. -*/ - -/* sim.h - * - * Definitions and prototypes for specific ISS SIMCALLs - * (ie. outside the standard C library). - */ - -#ifndef _INC_SIM_H_ -#define _INC_SIM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* Shortcuts for enabling/disabling profiling in the Xtensa ISS */ -extern void xt_iss_profile_enable(void); -extern void xt_iss_profile_disable(void); - -/* Shortcut for setting the trace level in the Xtensa ISS */ -extern void xt_iss_trace_level(unsigned level); - -/* Generic interface for passing client commands in the Xtensa ISS: - * returns 0 on success, -1 on failure. - */ -extern int xt_iss_client_command(const char *client, const char *command); - -/* Interface for switching simulation modes in the Xtensa ISS: - * returns 0 on success, -1 on failure. - */ -#define XT_ISS_CYCLE_ACCURATE 0 -#define XT_ISS_FUNCTIONAL 1 -extern int xt_iss_switch_mode(int mode); - - -/* Interface for waiting on a system synchronization event */ -extern void xt_iss_event_wait(unsigned event_id); - -/* Interface for firing a system synchronization event */ -extern void xt_iss_event_fire(unsigned event_id); - -/* Interface for invoking a user simcall action, - * which can be registered in XTMP or XTSC. - */ -extern int xt_iss_simcall(int arg1, int arg2, int arg3, - int arg4, int arg5, int arg6); - - -#ifdef __cplusplus -} -#endif - -#endif /*_INC_SIM_H_*/ - diff --git a/tools/sdk/include/esp32/xtensa/simboard.h b/tools/sdk/include/esp32/xtensa/simboard.h deleted file mode 100755 index 980b0b75963..00000000000 --- a/tools/sdk/include/esp32/xtensa/simboard.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2001 Tensilica 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. - */ - -/* simboard.h - Xtensa ISS "Board" specific definitions */ - -#ifndef _INC_SIMBOARD_H_ -#define _INC_SIMBOARD_H_ - -#include -#include - - -/* - * Device addresses. - */ - -/* System ROM: */ -#define XTBOARD_ROM_SIZE XSHAL_ROM_SIZE -#ifdef XSHAL_ROM_VADDR -#define XTBOARD_ROM_VADDR XSHAL_ROM_VADDR -#endif -#ifdef XSHAL_ROM_PADDR -#define XTBOARD_ROM_PADDR XSHAL_ROM_PADDR -#endif - -/* System RAM: */ -#define XTBOARD_RAM_SIZE XSHAL_RAM_SIZE -#ifdef XSHAL_RAM_VADDR -#define XTBOARD_RAM_VADDR XSHAL_RAM_VADDR -#endif -#ifdef XSHAL_RAM_PADDR -#define XTBOARD_RAM_PADDR XSHAL_RAM_PADDR -#endif - - -/* - * Things that depend on device addresses. - */ - -#define XTBOARD_CACHEATTR_WRITEBACK XSHAL_ISS_CACHEATTR_WRITEBACK -#define XTBOARD_CACHEATTR_WRITEALLOC XSHAL_ISS_CACHEATTR_WRITEALLOC -#define XTBOARD_CACHEATTR_WRITETHRU XSHAL_ISS_CACHEATTR_WRITETHRU -#define XTBOARD_CACHEATTR_BYPASS XSHAL_ISS_CACHEATTR_BYPASS -#define XTBOARD_CACHEATTR_DEFAULT XSHAL_ISS_CACHEATTR_DEFAULT - -#define XTBOARD_BUSINT_PIPE_REGIONS 0 -#define XTBOARD_BUSINT_SDRAM_REGIONS 0 - - -#endif /*_INC_SIMBOARD_H_*/ - diff --git a/tools/sdk/include/esp32/xtensa/simcall-errno.h b/tools/sdk/include/esp32/xtensa/simcall-errno.h deleted file mode 100755 index 445ec901358..00000000000 --- a/tools/sdk/include/esp32/xtensa/simcall-errno.h +++ /dev/null @@ -1,139 +0,0 @@ -/* Error numbers for Xtensa ISS semihosting. */ - -/* Copyright (c) 2003 by Tensilica Inc. ALL RIGHTS RESERVED. - These coded instructions, statements, and computer programs are the - copyrighted works and confidential proprietary information of Tensilica Inc. - They may not be modified, copied, reproduced, distributed, or disclosed to - third parties in any manner, medium, or form, in whole or in part, without - the prior written consent of Tensilica Inc. */ - -#ifndef _SIMCALL_ERRNO_H -#define _SIMCALL_ERRNO_H - -/* Define the error numbers (using the default newlib values) with prefixes - so they can be used in ISS without conflicting with the host values. */ - -#define _SIMC_EPERM 1 -#define _SIMC_ENOENT 2 -#define _SIMC_ESRCH 3 -#define _SIMC_EINTR 4 -#define _SIMC_EIO 5 -#define _SIMC_ENXIO 6 -#define _SIMC_E2BIG 7 -#define _SIMC_ENOEXEC 8 -#define _SIMC_EBADF 9 -#define _SIMC_ECHILD 10 -#define _SIMC_EAGAIN 11 -#define _SIMC_ENOMEM 12 -#define _SIMC_EACCES 13 -#define _SIMC_EFAULT 14 -#define _SIMC_ENOTBLK 15 -#define _SIMC_EBUSY 16 -#define _SIMC_EEXIST 17 -#define _SIMC_EXDEV 18 -#define _SIMC_ENODEV 19 -#define _SIMC_ENOTDIR 20 -#define _SIMC_EISDIR 21 -#define _SIMC_EINVAL 22 -#define _SIMC_ENFILE 23 -#define _SIMC_EMFILE 24 -#define _SIMC_ENOTTY 25 -#define _SIMC_ETXTBSY 26 -#define _SIMC_EFBIG 27 -#define _SIMC_ENOSPC 28 -#define _SIMC_ESPIPE 29 -#define _SIMC_EROFS 30 -#define _SIMC_EMLINK 31 -#define _SIMC_EPIPE 32 -#define _SIMC_EDOM 33 -#define _SIMC_ERANGE 34 -#define _SIMC_ENOMSG 35 -#define _SIMC_EIDRM 36 -#define _SIMC_ECHRNG 37 -#define _SIMC_EL2NSYNC 38 -#define _SIMC_EL3HLT 39 -#define _SIMC_EL3RST 40 -#define _SIMC_ELNRNG 41 -#define _SIMC_EUNATCH 42 -#define _SIMC_ENOCSI 43 -#define _SIMC_EL2HLT 44 -#define _SIMC_EDEADLK 45 -#define _SIMC_ENOLCK 46 -#define _SIMC_EBADE 50 -#define _SIMC_EBADR 51 -#define _SIMC_EXFULL 52 -#define _SIMC_ENOANO 53 -#define _SIMC_EBADRQC 54 -#define _SIMC_EBADSLT 55 -#define _SIMC_EDEADLOCK 56 -#define _SIMC_EBFONT 57 -#define _SIMC_ENOSTR 60 -#define _SIMC_ENODATA 61 -#define _SIMC_ETIME 62 -#define _SIMC_ENOSR 63 -#define _SIMC_ENONET 64 -#define _SIMC_ENOPKG 65 -#define _SIMC_EREMOTE 66 -#define _SIMC_ENOLINK 67 -#define _SIMC_EADV 68 -#define _SIMC_ESRMNT 69 -#define _SIMC_ECOMM 70 -#define _SIMC_EPROTO 71 -#define _SIMC_EMULTIHOP 74 -#define _SIMC_ELBIN 75 -#define _SIMC_EDOTDOT 76 -#define _SIMC_EBADMSG 77 -#define _SIMC_EFTYPE 79 -#define _SIMC_ENOTUNIQ 80 -#define _SIMC_EBADFD 81 -#define _SIMC_EREMCHG 82 -#define _SIMC_ELIBACC 83 -#define _SIMC_ELIBBAD 84 -#define _SIMC_ELIBSCN 85 -#define _SIMC_ELIBMAX 86 -#define _SIMC_ELIBEXEC 87 -#define _SIMC_ENOSYS 88 -#define _SIMC_ENMFILE 89 -#define _SIMC_ENOTEMPTY 90 -#define _SIMC_ENAMETOOLONG 91 -#define _SIMC_ELOOP 92 -#define _SIMC_EOPNOTSUPP 95 -#define _SIMC_EPFNOSUPPORT 96 -#define _SIMC_ECONNRESET 104 -#define _SIMC_ENOBUFS 105 -#define _SIMC_EAFNOSUPPORT 106 -#define _SIMC_EPROTOTYPE 107 -#define _SIMC_ENOTSOCK 108 -#define _SIMC_ENOPROTOOPT 109 -#define _SIMC_ESHUTDOWN 110 -#define _SIMC_ECONNREFUSED 111 -#define _SIMC_EADDRINUSE 112 -#define _SIMC_ECONNABORTED 113 -#define _SIMC_ENETUNREACH 114 -#define _SIMC_ENETDOWN 115 -#define _SIMC_ETIMEDOUT 116 -#define _SIMC_EHOSTDOWN 117 -#define _SIMC_EHOSTUNREACH 118 -#define _SIMC_EINPROGRESS 119 -#define _SIMC_EALREADY 120 -#define _SIMC_EDESTADDRREQ 121 -#define _SIMC_EMSGSIZE 122 -#define _SIMC_EPROTONOSUPPORT 123 -#define _SIMC_ESOCKTNOSUPPORT 124 -#define _SIMC_EADDRNOTAVAIL 125 -#define _SIMC_ENETRESET 126 -#define _SIMC_EISCONN 127 -#define _SIMC_ENOTCONN 128 -#define _SIMC_ETOOMANYREFS 129 -#define _SIMC_EPROCLIM 130 -#define _SIMC_EUSERS 131 -#define _SIMC_EDQUOT 132 -#define _SIMC_ESTALE 133 -#define _SIMC_ENOTSUP 134 -#define _SIMC_ENOMEDIUM 135 -#define _SIMC_ENOSHARE 136 -#define _SIMC_ECASECLASH 137 -#define _SIMC_EILSEQ 138 -#define _SIMC_EOVERFLOW 139 - -#endif /* ! _SIMCALL_ERRNO_H */ diff --git a/tools/sdk/include/esp32/xtensa/simcall-fcntl.h b/tools/sdk/include/esp32/xtensa/simcall-fcntl.h deleted file mode 100755 index 1c03f5595e0..00000000000 --- a/tools/sdk/include/esp32/xtensa/simcall-fcntl.h +++ /dev/null @@ -1,21 +0,0 @@ -/* File control operations for Xtensa ISS semihosting. */ - -/* Copyright (c) 2003 by Tensilica Inc. ALL RIGHTS RESERVED. - These coded instructions, statements, and computer programs are the - copyrighted works and confidential proprietary information of Tensilica Inc. - They may not be modified, copied, reproduced, distributed, or disclosed to - third parties in any manner, medium, or form, in whole or in part, without - the prior written consent of Tensilica Inc. */ - -#ifndef _SIMCALL_FCNTL_H -#define _SIMCALL_FCNTL_H - -#define _SIMC_O_APPEND 0x0008 -#define _SIMC_O_NONBLOCK 0x0080 -#define _SIMC_O_CREAT 0x0100 -#define _SIMC_O_TRUNC 0x0200 -#define _SIMC_O_EXCL 0x0400 -#define _SIMC_O_TEXT 0x4000 -#define _SIMC_O_BINARY 0x8000 - -#endif /* ! _SIMCALL_FCNTL_H */ diff --git a/tools/sdk/include/esp32/xtensa/simcall.h b/tools/sdk/include/esp32/xtensa/simcall.h deleted file mode 100755 index d71959eea71..00000000000 --- a/tools/sdk/include/esp32/xtensa/simcall.h +++ /dev/null @@ -1,189 +0,0 @@ -/* - * simcall.h - Simulator call numbers - * - * Software that runs on a simulated Xtensa processor using - * the instruction set simulator (ISS) can invoke simulator - * services using the SIMCALL instruction. The a2 register - * is set prior to executing SIMCALL to a "simcall number", - * indicating which service to invoke. This file defines the - * simcall numbers defined and/or supported by the Xtensa ISS. - * - * IMPORTANT NOTE: These numbers are highly subject to change! - * - * Copyright (c) 2002-2007 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -#ifndef SIMCALL_INCLUDED -#define SIMCALL_INCLUDED - -/* - * System call like services offered by the simulator host. - * These are modeled after the Linux 2.4 kernel system calls - * for Xtensa processors. However not all system calls and - * not all functionality of a given system call are implemented, - * or necessarily have well defined or equivalent semantics in - * the context of a simulation (as opposed to a Unix kernel). - * - * These services behave largely as if they had been invoked - * as a task in the simulator host's operating system - * (eg. files accessed are those of the simulator host). - * However, these SIMCALLs model a virtual operating system - * so that various definitions, bit assignments etc - * (eg. open mode bits, errno values, etc) are independent - * of the host operating system used to run the simulation. - * Rather these definitions are specific to the Xtensa ISS. - * This way Xtensa ISA code written to use these SIMCALLs - * can (in principle) be simulated on any host. - * - * Up to 6 parameters are passed in registers a3 to a8 - * (note the 6th parameter isn't passed on the stack, - * unlike windowed function calling conventions). - * The return value is in a2. A negative value in the - * range -4096 to -1 indicates a negated error code to be - * reported in errno with a return value of -1, otherwise - * the value in a2 is returned as is. - */ - -/* These #defines need to match what's in Xtensa/OS/vxworks/xtiss/simcalls.c */ - -#define SYS_nop 0 /* n/a - setup; used to flush register windows */ -#define SYS_exit 1 /*x*/ -#define SYS_fork 2 -#define SYS_read 3 /*x*/ -#define SYS_write 4 /*x*/ -#define SYS_open 5 /*x*/ -#define SYS_close 6 /*x*/ -#define SYS_rename 7 /*x 38 - waitpid */ -#define SYS_creat 8 /*x*/ -#define SYS_link 9 /*x (not implemented on WIN32) */ -#define SYS_unlink 10 /*x*/ -#define SYS_execv 11 /* n/a - execve */ -#define SYS_execve 12 /* 11 - chdir */ -#define SYS_pipe 13 /* 42 - time */ -#define SYS_stat 14 /* 106 - mknod */ -#define SYS_chmod 15 -#define SYS_chown 16 /* 202 - lchown */ -#define SYS_utime 17 /* 30 - break */ -#define SYS_wait 18 /* n/a - oldstat */ -#define SYS_lseek 19 /*x*/ -#define SYS_getpid 20 -#define SYS_isatty 21 /* n/a - mount */ -#define SYS_fstat 22 /* 108 - oldumount */ -#define SYS_time 23 /* 13 - setuid */ -#define SYS_gettimeofday 24 /*x 78 - getuid (not implemented on WIN32) */ -#define SYS_times 25 /*X 43 - stime (Xtensa-specific implementation) */ -#define SYS_socket 26 -#define SYS_sendto 27 -#define SYS_recvfrom 28 -#define SYS_select_one 29 /* not compitible select, one file descriptor at the time */ -#define SYS_bind 30 -#define SYS_ioctl 31 - -/* - * Other... - */ -#define SYS_iss_argc 1000 /* returns value of argc */ -#define SYS_iss_argv_size 1001 /* bytes needed for argv & arg strings */ -#define SYS_iss_set_argv 1002 /* saves argv & arg strings at given addr */ - -#define SYS_memset 1004 /* fill a range of memory (fast) */ - -/* - * SIMCALLs for the ferret memory debugger. All are invoked by - * libferret.a ... ( Xtensa/Target-Libs/ferret ) - */ -#define SYS_ferret 1010 -#define SYS_malloc 1011 -#define SYS_free 1012 -#define SYS_more_heap 1013 -#define SYS_no_heap 1014 -#define SYS_enter_ferret 1015 -#define SYS_leave_ferret 1016 - -/* - * SIMCALLs for ISS client commands - */ -#define SYS_profile_enable 1020 -#define SYS_profile_disable 1021 -#define SYS_trace_level 1022 -#define SYS_client_command 1023 - -/* - * SIMCALL for simulation mode switching - */ -#define SYS_sim_mode_switch 1030 - -/* - * SIMCALLs for XTMP/XTSC event notify and core stall - */ -#define SYS_event_fire 1040 -#define SYS_event_stall 1041 - -/* - * SIMCALLs for callbacks registered in XTMP/XTSC - */ -#define SYS_callback_first 100 -#define SYS_callback_last 999 - -/* - * User defined simcall - */ -#define SYS_user_simcall 100 - -#define SYS_xmpa_errinfo 200 -#define SYS_xmpa_proc_status 201 -#define SYS_xmpa_proc_start 202 -#define SYS_xmpa_proc_stop 203 -#define SYS_xmpa_proc_mem_read 204 -#define SYS_xmpa_proc_mem_write 205 -#define SYS_xmpa_proc_mem_fill 206 -#define SYS_xmpa_proc_reg_read 207 -#define SYS_xmpa_proc_reg_write 208 - - -/* - * Extra SIMCALLs for GDB: - */ -#define SYS_gdb_break -1 /* invoked by XTOS on user exceptions if EPC points - to a break.n/break, regardless of cause! */ -#define SYS_xmon_out -2 /* invoked by XMON: ... */ -#define SYS_xmon_in -3 /* invoked by XMON: ... */ -#define SYS_xmon_flush -4 /* invoked by XMON: ... */ -#define SYS_gdb_abort -5 /* invoked by XTOS in _xtos_panic() */ -#define SYS_gdb_illegal_inst -6 /* invoked by XTOS for illegal instructions (too deeply) */ -#define SYS_xmon_init -7 /* invoked by XMON: ... */ -#define SYS_gdb_enter_sktloop -8 /* invoked by XTOS on debug exceptions */ -#define SYS_unhandled_kernel_exc -9 /* invoked by XTOS for unhandled kernel exceptions */ -#define SYS_unhandled_user_exc -10 /* invoked by XTOS for unhandled user exceptions */ -#define SYS_unhandled_double_exc -11 /* invoked by XTOS for unhandled double exceptions */ -#define SYS_unhandled_highpri_interrupt -12 /* invoked by XTOS for unhandled high-priority interrupts */ -#define SYS_xmon_close -13 /* invoked by XMON: ... */ - -/* - * SIMCALLs for vxWorks xtiss BSP: - */ -#define SYS_setup_ppp_pipes -83 -#define SYS_log_msg -84 - -/* - * SYS_select_one specifiers - */ -#define XTISS_SELECT_ONE_READ 1 -#define XTISS_SELECT_ONE_WRITE 2 -#define XTISS_SELECT_ONE_EXCEPT 3 - -/* - * SIMCALL for client calling arbitrary code in a client plug in. - * see clients/xcc_instr to see how this works. - */ - -#define SYS_client 0xC0DECAFE - - - -#endif /* !SIMCALL_INCLUDED */ diff --git a/tools/sdk/include/esp32/xtensa/specreg.h b/tools/sdk/include/esp32/xtensa/specreg.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_DFP_assist.h b/tools/sdk/include/esp32/xtensa/tie/xt_DFP_assist.h deleted file mode 100644 index 4d529ebd3f7..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_DFP_assist.h +++ /dev/null @@ -1,96 +0,0 @@ -/* Definitions for the xt_DFP_assist TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_DFP_assist_HEADER -#define _XTENSA_xt_DFP_assist_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_DFP_assist_F64ITER(unsigned arr /*inout*/, unsigned ars, unsigned art, immediate oper, immediate noshift); -extern unsigned _TIE_xt_DFP_assist_F64RND(unsigned ars, unsigned art, immediate mode); -extern void _TIE_xt_DFP_assist_F64ADDC(unsigned art /*inout*/, unsigned ars, immediate immZ, immediate immC); -extern void _TIE_xt_DFP_assist_F64SUBC(unsigned art /*inout*/, unsigned ars, immediate immZ, immediate immC); -extern unsigned _TIE_xt_DFP_assist_F64SIG(unsigned ars); -extern unsigned _TIE_xt_DFP_assist_F64CMPL(unsigned ars, unsigned art); -extern unsigned _TIE_xt_DFP_assist_F64CMPH(unsigned ars, unsigned art, immediate oper); -extern unsigned _TIE_xt_DFP_assist_F64NORM(unsigned ars, unsigned art, immediate mode); -extern unsigned _TIE_xt_DFP_assist_F64SEXP(unsigned ars, unsigned art); -extern unsigned _TIE_xt_DFP_assist_RF64R(immediate hilo); -extern void _TIE_xt_DFP_assist_WF64R(unsigned ars, unsigned art, immediate hilo); -extern unsigned _TIE_xt_DFP_assist_RUR_F64R_LO(void); -extern unsigned _TIE_xt_DFP_assist_RUR_F64R_HI(void); -extern void _TIE_xt_DFP_assist_WUR_F64R_LO(unsigned art); -extern void _TIE_xt_DFP_assist_WUR_F64R_HI(unsigned art); -extern unsigned _TIE_xt_DFP_assist_RUR_F64S(void); -extern void _TIE_xt_DFP_assist_WUR_F64S(unsigned art); -#define F64ITER _TIE_xt_DFP_assist_F64ITER -#define F64RND _TIE_xt_DFP_assist_F64RND -#define F64ADDC _TIE_xt_DFP_assist_F64ADDC -#define F64SUBC _TIE_xt_DFP_assist_F64SUBC -#define F64SIG _TIE_xt_DFP_assist_F64SIG -#define F64CMPL _TIE_xt_DFP_assist_F64CMPL -#define F64CMPH _TIE_xt_DFP_assist_F64CMPH -#define F64NORM _TIE_xt_DFP_assist_F64NORM -#define F64SEXP _TIE_xt_DFP_assist_F64SEXP -#define RF64R _TIE_xt_DFP_assist_RF64R -#define WF64R _TIE_xt_DFP_assist_WF64R -#define RUR_F64R_LO _TIE_xt_DFP_assist_RUR_F64R_LO -#define RF64R_LO _TIE_xt_DFP_assist_RUR_F64R_LO -#define RUR234 _TIE_xt_DFP_assist_RUR_F64R_LO -#define RUR_F64R_HI _TIE_xt_DFP_assist_RUR_F64R_HI -#define RF64R_HI _TIE_xt_DFP_assist_RUR_F64R_HI -#define RUR235 _TIE_xt_DFP_assist_RUR_F64R_HI -#define WUR_F64R_LO _TIE_xt_DFP_assist_WUR_F64R_LO -#define WF64R_LO _TIE_xt_DFP_assist_WUR_F64R_LO -#define WUR234 _TIE_xt_DFP_assist_WUR_F64R_LO -#define WUR_F64R_HI _TIE_xt_DFP_assist_WUR_F64R_HI -#define WF64R_HI _TIE_xt_DFP_assist_WUR_F64R_HI -#define WUR235 _TIE_xt_DFP_assist_WUR_F64R_HI -#define RUR_F64S _TIE_xt_DFP_assist_RUR_F64S -#define RF64S _TIE_xt_DFP_assist_RUR_F64S -#define RUR236 _TIE_xt_DFP_assist_RUR_F64S -#define WUR_F64S _TIE_xt_DFP_assist_WUR_F64S -#define WF64S _TIE_xt_DFP_assist_WUR_F64S -#define WUR236 _TIE_xt_DFP_assist_WUR_F64S - -#ifndef RUR -#define RUR(NUM) RUR##NUM() -#endif - -#ifndef WUR -#define WUR(VAL, NUM) WUR##NUM(VAL) -#endif - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_DFP_assist_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_FP.h b/tools/sdk/include/esp32/xtensa/tie/xt_FP.h deleted file mode 100644 index 229a108ab79..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_FP.h +++ /dev/null @@ -1,197 +0,0 @@ -/* Definitions for the xt_FP TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_FP_HEADER -#define _XTENSA_xt_FP_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include -#include -typedef float _TIE_xt_FP_xtfloat; -typedef _TIE_xt_FP_xtfloat xtfloat; - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern unsigned _TIE_xt_FP_RUR_FCR(void); -extern void _TIE_xt_FP_WUR_FCR(unsigned v); -extern unsigned _TIE_xt_FP_RUR_FSR(void); -extern void _TIE_xt_FP_WUR_FSR(unsigned v); -extern xtfloat _TIE_xt_FP_xtfloat_loadi(const xtfloat * p, immediate imm8x4); -extern void _TIE_xt_FP_xtfloat_storei(xtfloat t, xtfloat * p, immediate imm8x4); -extern void _TIE_xt_FP_xtfloat_loadip(xtfloat t /*out*/, const xtfloat * p /*inout*/, immediate imm8x4); -extern void _TIE_xt_FP_xtfloat_storeip(xtfloat t, xtfloat * p /*inout*/, immediate imm8x4); -extern xtfloat _TIE_xt_FP_xtfloat_loadx(const xtfloat * p, int imm8x4); -extern void _TIE_xt_FP_xtfloat_storex(xtfloat t, xtfloat * p, int imm8x4); -extern void _TIE_xt_FP_xtfloat_loadxp(xtfloat t /*out*/, const xtfloat * p /*inout*/, int imm8x4); -extern void _TIE_xt_FP_xtfloat_storexp(xtfloat t, xtfloat * p /*inout*/, int imm8x4); -extern xtfloat _TIE_xt_FP_xtfloat_move(xtfloat r); -extern int _TIE_xt_FP_ROUND_S(xtfloat s, immediate t); -extern int _TIE_xt_FP_TRUNC_S(xtfloat s, immediate t); -extern unsigned _TIE_xt_FP_UTRUNC_S(xtfloat s, immediate t); -extern int _TIE_xt_FP_FLOOR_S(xtfloat s, immediate t); -extern int _TIE_xt_FP_CEIL_S(xtfloat s, immediate t); -extern xtfloat _TIE_xt_FP_LSI(const xtfloat * p, immediate imm8x4); -extern void _TIE_xt_FP_SSI(xtfloat t, xtfloat * p, immediate imm8x4); -extern void _TIE_xt_FP_LSIP(xtfloat t /*out*/, const xtfloat * p /*inout*/, immediate imm8x4); -extern void _TIE_xt_FP_SSIP(xtfloat t, xtfloat * p /*inout*/, immediate imm8x4); -extern xtfloat _TIE_xt_FP_LSX(const xtfloat * p, int imm8x4); -extern void _TIE_xt_FP_SSX(xtfloat t, xtfloat * p, int imm8x4); -extern void _TIE_xt_FP_LSXP(xtfloat t /*out*/, const xtfloat * p /*inout*/, int imm8x4); -extern void _TIE_xt_FP_SSXP(xtfloat t, xtfloat * p /*inout*/, int imm8x4); -extern xtfloat _TIE_xt_FP_ABS_S(xtfloat s); -extern xtfloat _TIE_xt_FP_NEG_S(xtfloat s); -extern xtfloat _TIE_xt_FP_MOV_S(xtfloat s); -extern void _TIE_xt_FP_MOVEQZ_S(xtfloat r /*inout*/, xtfloat s, int t); -extern void _TIE_xt_FP_MOVNEZ_S(xtfloat r /*inout*/, xtfloat s, int t); -extern void _TIE_xt_FP_MOVLTZ_S(xtfloat r /*inout*/, xtfloat s, int t); -extern void _TIE_xt_FP_MOVGEZ_S(xtfloat r /*inout*/, xtfloat s, int t); -extern void _TIE_xt_FP_MOVF_S(xtfloat r /*inout*/, xtfloat s, xtbool t); -extern void _TIE_xt_FP_MOVT_S(xtfloat r /*inout*/, xtfloat s, xtbool t); -extern unsigned _TIE_xt_FP_RFR(xtfloat s); -extern xtfloat _TIE_xt_FP_WFR(unsigned s); -extern xtfloat _TIE_xt_FP_FLOAT_S(int s, immediate t); -extern xtfloat _TIE_xt_FP_UFLOAT_S(unsigned s, immediate t); -extern xtbool _TIE_xt_FP_OEQ_S(xtfloat s, xtfloat t); -extern xtbool _TIE_xt_FP_OLE_S(xtfloat s, xtfloat t); -extern xtbool _TIE_xt_FP_OLT_S(xtfloat s, xtfloat t); -extern xtbool _TIE_xt_FP_UEQ_S(xtfloat s, xtfloat t); -extern xtbool _TIE_xt_FP_ULE_S(xtfloat s, xtfloat t); -extern xtbool _TIE_xt_FP_ULT_S(xtfloat s, xtfloat t); -extern xtbool _TIE_xt_FP_UN_S(xtfloat s, xtfloat t); -extern xtfloat _TIE_xt_FP_ADD_S(xtfloat s, xtfloat t); -extern xtfloat _TIE_xt_FP_SUB_S(xtfloat s, xtfloat t); -extern xtfloat _TIE_xt_FP_MUL_S(xtfloat s, xtfloat t); -extern void _TIE_xt_FP_MADD_S(xtfloat r /*inout*/, xtfloat s, xtfloat t); -extern void _TIE_xt_FP_MSUB_S(xtfloat r /*inout*/, xtfloat s, xtfloat t); -extern xtfloat _TIE_xt_FP_RECIP0_S(xtfloat s); -extern xtfloat _TIE_xt_FP_DIV0_S(xtfloat s); -extern xtfloat _TIE_xt_FP_NEXP01_S(xtfloat s); -extern xtfloat _TIE_xt_FP_CONST_S(immediate s); -extern void _TIE_xt_FP_MKDADJ_S(xtfloat r /*inout*/, xtfloat s); -extern xtfloat _TIE_xt_FP_MKSADJ_S(xtfloat s); -extern void _TIE_xt_FP_ADDEXPM_S(xtfloat r /*inout*/, xtfloat s); -extern void _TIE_xt_FP_ADDEXP_S(xtfloat r /*inout*/, xtfloat s); -extern void _TIE_xt_FP_DIVN_S(xtfloat r /*inout*/, xtfloat s, xtfloat t); -extern xtfloat _TIE_xt_FP_RSQRT0_S(xtfloat s); -extern xtfloat _TIE_xt_FP_SQRT0_S(xtfloat s); -extern void _TIE_xt_FP_MADDN_S(xtfloat r /*inout*/, xtfloat s, xtfloat t); -extern xtfloat _TIE_xt_FP_DIV_S(xtfloat s, xtfloat t); -extern xtfloat _TIE_xt_FP_SQRT_S(xtfloat s); -extern xtfloat _TIE_xt_FP_RECIP_S(xtfloat s); -extern xtfloat _TIE_xt_FP_RSQRT_S(xtfloat s); -extern xtfloat _TIE_xt_FP_FSQRT_S(xtfloat s); -#define XT_RUR_FCR _TIE_xt_FP_RUR_FCR -#define RFCR _TIE_xt_FP_RUR_FCR -#define RUR232 _TIE_xt_FP_RUR_FCR -#define XT_WUR_FCR _TIE_xt_FP_WUR_FCR -#define WFCR _TIE_xt_FP_WUR_FCR -#define WUR232 _TIE_xt_FP_WUR_FCR -#define XT_RUR_FSR _TIE_xt_FP_RUR_FSR -#define RFSR _TIE_xt_FP_RUR_FSR -#define RUR233 _TIE_xt_FP_RUR_FSR -#define XT_WUR_FSR _TIE_xt_FP_WUR_FSR -#define WFSR _TIE_xt_FP_WUR_FSR -#define WUR233 _TIE_xt_FP_WUR_FSR -#define XT_xtfloat_loadi _TIE_xt_FP_xtfloat_loadi -#define XT_xtfloat_storei _TIE_xt_FP_xtfloat_storei -#define XT_xtfloat_loadip _TIE_xt_FP_xtfloat_loadip -#define XT_xtfloat_storeip _TIE_xt_FP_xtfloat_storeip -#define XT_xtfloat_loadx _TIE_xt_FP_xtfloat_loadx -#define XT_xtfloat_storex _TIE_xt_FP_xtfloat_storex -#define XT_xtfloat_loadxp _TIE_xt_FP_xtfloat_loadxp -#define XT_xtfloat_storexp _TIE_xt_FP_xtfloat_storexp -#define XT_xtfloat_move _TIE_xt_FP_xtfloat_move -#define XT_ROUND_S _TIE_xt_FP_ROUND_S -#define XT_TRUNC_S _TIE_xt_FP_TRUNC_S -#define XT_UTRUNC_S _TIE_xt_FP_UTRUNC_S -#define XT_FLOOR_S _TIE_xt_FP_FLOOR_S -#define XT_CEIL_S _TIE_xt_FP_CEIL_S -#define XT_LSI _TIE_xt_FP_LSI -#define XT_SSI _TIE_xt_FP_SSI -#define XT_LSIP _TIE_xt_FP_LSIP -#define XT_SSIP _TIE_xt_FP_SSIP -#define XT_LSX _TIE_xt_FP_LSX -#define XT_SSX _TIE_xt_FP_SSX -#define XT_LSXP _TIE_xt_FP_LSXP -#define XT_SSXP _TIE_xt_FP_SSXP -#define XT_ABS_S _TIE_xt_FP_ABS_S -#define XT_NEG_S _TIE_xt_FP_NEG_S -#define XT_MOV_S _TIE_xt_FP_MOV_S -#define XT_MOVEQZ_S _TIE_xt_FP_MOVEQZ_S -#define XT_MOVNEZ_S _TIE_xt_FP_MOVNEZ_S -#define XT_MOVLTZ_S _TIE_xt_FP_MOVLTZ_S -#define XT_MOVGEZ_S _TIE_xt_FP_MOVGEZ_S -#define XT_MOVF_S _TIE_xt_FP_MOVF_S -#define XT_MOVT_S _TIE_xt_FP_MOVT_S -#define XT_RFR _TIE_xt_FP_RFR -#define XT_WFR _TIE_xt_FP_WFR -#define XT_FLOAT_S _TIE_xt_FP_FLOAT_S -#define XT_UFLOAT_S _TIE_xt_FP_UFLOAT_S -#define XT_OEQ_S _TIE_xt_FP_OEQ_S -#define XT_OLE_S _TIE_xt_FP_OLE_S -#define XT_OLT_S _TIE_xt_FP_OLT_S -#define XT_UEQ_S _TIE_xt_FP_UEQ_S -#define XT_ULE_S _TIE_xt_FP_ULE_S -#define XT_ULT_S _TIE_xt_FP_ULT_S -#define XT_UN_S _TIE_xt_FP_UN_S -#define XT_ADD_S _TIE_xt_FP_ADD_S -#define XT_SUB_S _TIE_xt_FP_SUB_S -#define XT_MUL_S _TIE_xt_FP_MUL_S -#define XT_MADD_S _TIE_xt_FP_MADD_S -#define XT_MSUB_S _TIE_xt_FP_MSUB_S -#define XT_RECIP0_S _TIE_xt_FP_RECIP0_S -#define XT_DIV0_S _TIE_xt_FP_DIV0_S -#define XT_NEXP01_S _TIE_xt_FP_NEXP01_S -#define XT_CONST_S _TIE_xt_FP_CONST_S -#define XT_MKDADJ_S _TIE_xt_FP_MKDADJ_S -#define XT_MKSADJ_S _TIE_xt_FP_MKSADJ_S -#define XT_ADDEXPM_S _TIE_xt_FP_ADDEXPM_S -#define XT_ADDEXP_S _TIE_xt_FP_ADDEXP_S -#define XT_DIVN_S _TIE_xt_FP_DIVN_S -#define XT_RSQRT0_S _TIE_xt_FP_RSQRT0_S -#define XT_SQRT0_S _TIE_xt_FP_SQRT0_S -#define XT_MADDN_S _TIE_xt_FP_MADDN_S -#define XT_DIV_S _TIE_xt_FP_DIV_S -#define XT_SQRT_S _TIE_xt_FP_SQRT_S -#define XT_RECIP_S _TIE_xt_FP_RECIP_S -#define XT_RSQRT_S _TIE_xt_FP_RSQRT_S -#define XT_FSQRT_S _TIE_xt_FP_FSQRT_S - -#ifndef RUR -#define RUR(NUM) RUR##NUM() -#endif - -#ifndef WUR -#define WUR(VAL, NUM) WUR##NUM(VAL) -#endif - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_FP_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_MAC16.h b/tools/sdk/include/esp32/xtensa/tie/xt_MAC16.h deleted file mode 100644 index b46a1db7f7a..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_MAC16.h +++ /dev/null @@ -1,239 +0,0 @@ -/* Definitions for the xt_MAC16 TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_MAC16_HEADER -#define _XTENSA_xt_MAC16_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_MAC16_UMUL_AA_HH(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_UMUL_AA_LH(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_UMUL_AA_HL(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_UMUL_AA_LL(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MUL_AA_HH(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MUL_AA_LH(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MUL_AA_HL(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MUL_AA_LL(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MUL_AD_HH(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MUL_AD_LH(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MUL_AD_HL(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MUL_AD_LL(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MUL_DA_HH(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MUL_DA_LH(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MUL_DA_HL(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MUL_DA_LL(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MUL_DD_HH(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MUL_DD_LH(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MUL_DD_HL(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MUL_DD_LL(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MULS_AA_HH(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MULS_AA_LH(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MULS_AA_HL(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MULS_AA_LL(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MULA_AA_HH(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MULA_AA_LH(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MULA_AA_HL(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MULA_AA_LL(unsigned ars, unsigned art); -extern void _TIE_xt_MAC16_MULS_AD_HH(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MULS_AD_LH(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MULS_AD_HL(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MULS_AD_LL(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MULA_AD_HH(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MULA_AD_LH(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MULA_AD_HL(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MULA_AD_LL(unsigned ars, immediate my); -extern void _TIE_xt_MAC16_MULS_DA_HH(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MULS_DA_LH(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MULS_DA_HL(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MULS_DA_LL(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MULA_DA_HH(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MULA_DA_LH(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MULA_DA_HL(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MULA_DA_LL(immediate mx, unsigned art); -extern void _TIE_xt_MAC16_MULS_DD_HH(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MULS_DD_LH(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MULS_DD_HL(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MULS_DD_LL(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MULA_DD_HH(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MULA_DD_LH(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MULA_DD_HL(immediate mx, immediate my); -extern void _TIE_xt_MAC16_MULA_DD_LL(immediate mx, immediate my); -extern unsigned _TIE_xt_MAC16_RSR_M0(void); -extern void _TIE_xt_MAC16_WSR_M0(unsigned art); -extern void _TIE_xt_MAC16_XSR_M0(unsigned art /*inout*/); -extern unsigned _TIE_xt_MAC16_RSR_M1(void); -extern void _TIE_xt_MAC16_WSR_M1(unsigned art); -extern void _TIE_xt_MAC16_XSR_M1(unsigned art /*inout*/); -extern unsigned _TIE_xt_MAC16_RSR_M2(void); -extern void _TIE_xt_MAC16_WSR_M2(unsigned art); -extern void _TIE_xt_MAC16_XSR_M2(unsigned art /*inout*/); -extern unsigned _TIE_xt_MAC16_RSR_M3(void); -extern void _TIE_xt_MAC16_WSR_M3(unsigned art); -extern void _TIE_xt_MAC16_XSR_M3(unsigned art /*inout*/); -extern unsigned _TIE_xt_MAC16_RSR_ACCLO(void); -extern void _TIE_xt_MAC16_WSR_ACCLO(unsigned art); -extern void _TIE_xt_MAC16_XSR_ACCLO(unsigned art /*inout*/); -extern unsigned _TIE_xt_MAC16_RSR_ACCHI(void); -extern void _TIE_xt_MAC16_WSR_ACCHI(unsigned art); -extern void _TIE_xt_MAC16_XSR_ACCHI(unsigned art /*inout*/); -extern void _TIE_xt_MAC16_MULA_DA_LL_LDDEC(immediate w, const short * s /*inout*/, immediate x, int t); -extern void _TIE_xt_MAC16_MULA_DA_LL_LDINC(immediate w, const short * s /*inout*/, immediate x, int t); -extern void _TIE_xt_MAC16_MULA_DA_HL_LDDEC(immediate w, const short * s /*inout*/, immediate x, int t); -extern void _TIE_xt_MAC16_MULA_DA_HL_LDINC(immediate w, const short * s /*inout*/, immediate x, int t); -extern void _TIE_xt_MAC16_MULA_DA_LH_LDDEC(immediate w, const short * s /*inout*/, immediate x, int t); -extern void _TIE_xt_MAC16_MULA_DA_LH_LDINC(immediate w, const short * s /*inout*/, immediate x, int t); -extern void _TIE_xt_MAC16_MULA_DA_HH_LDDEC(immediate w, const short * s /*inout*/, immediate x, int t); -extern void _TIE_xt_MAC16_MULA_DA_HH_LDINC(immediate w, const short * s /*inout*/, immediate x, int t); -extern void _TIE_xt_MAC16_MULA_DD_LL_LDDEC(immediate w, const short * s /*inout*/, immediate x, immediate y); -extern void _TIE_xt_MAC16_MULA_DD_LL_LDINC(immediate w, const short * s /*inout*/, immediate x, immediate y); -extern void _TIE_xt_MAC16_MULA_DD_HL_LDDEC(immediate w, const short * s /*inout*/, immediate x, immediate y); -extern void _TIE_xt_MAC16_MULA_DD_HL_LDINC(immediate w, const short * s /*inout*/, immediate x, immediate y); -extern void _TIE_xt_MAC16_MULA_DD_LH_LDDEC(immediate w, const short * s /*inout*/, immediate x, immediate y); -extern void _TIE_xt_MAC16_MULA_DD_LH_LDINC(immediate w, const short * s /*inout*/, immediate x, immediate y); -extern void _TIE_xt_MAC16_MULA_DD_HH_LDDEC(immediate w, const short * s /*inout*/, immediate x, immediate y); -extern void _TIE_xt_MAC16_MULA_DD_HH_LDINC(immediate w, const short * s /*inout*/, immediate x, immediate y); -extern void _TIE_xt_MAC16_LDDEC(immediate w, const short * p /*inout*/); -extern void _TIE_xt_MAC16_ULDDEC(immediate w, const unsigned short * p /*inout*/); -extern void _TIE_xt_MAC16_SLDDEC(immediate w, const short * p /*inout*/); -extern void _TIE_xt_MAC16_LDINC(immediate w, const short * p /*inout*/); -extern void _TIE_xt_MAC16_ULDINC(immediate w, const unsigned short * p /*inout*/); -extern void _TIE_xt_MAC16_SLDINC(immediate w, const short * p /*inout*/); -extern int _TIE_xt_MAC16_RSR16(void); -extern void _TIE_xt_MAC16_WSR16(int t); -extern void _TIE_xt_MAC16_XSR16(int t /*inout*/); -extern int _TIE_xt_MAC16_RSR17(void); -extern void _TIE_xt_MAC16_WSR17(int t); -extern void _TIE_xt_MAC16_XSR17(int t /*inout*/); -#define XT_UMUL_AA_HH _TIE_xt_MAC16_UMUL_AA_HH -#define XT_UMUL_AA_LH _TIE_xt_MAC16_UMUL_AA_LH -#define XT_UMUL_AA_HL _TIE_xt_MAC16_UMUL_AA_HL -#define XT_UMUL_AA_LL _TIE_xt_MAC16_UMUL_AA_LL -#define XT_MUL_AA_HH _TIE_xt_MAC16_MUL_AA_HH -#define XT_MUL_AA_LH _TIE_xt_MAC16_MUL_AA_LH -#define XT_MUL_AA_HL _TIE_xt_MAC16_MUL_AA_HL -#define XT_MUL_AA_LL _TIE_xt_MAC16_MUL_AA_LL -#define XT_MUL_AD_HH _TIE_xt_MAC16_MUL_AD_HH -#define XT_MUL_AD_LH _TIE_xt_MAC16_MUL_AD_LH -#define XT_MUL_AD_HL _TIE_xt_MAC16_MUL_AD_HL -#define XT_MUL_AD_LL _TIE_xt_MAC16_MUL_AD_LL -#define XT_MUL_DA_HH _TIE_xt_MAC16_MUL_DA_HH -#define XT_MUL_DA_LH _TIE_xt_MAC16_MUL_DA_LH -#define XT_MUL_DA_HL _TIE_xt_MAC16_MUL_DA_HL -#define XT_MUL_DA_LL _TIE_xt_MAC16_MUL_DA_LL -#define XT_MUL_DD_HH _TIE_xt_MAC16_MUL_DD_HH -#define XT_MUL_DD_LH _TIE_xt_MAC16_MUL_DD_LH -#define XT_MUL_DD_HL _TIE_xt_MAC16_MUL_DD_HL -#define XT_MUL_DD_LL _TIE_xt_MAC16_MUL_DD_LL -#define XT_MULS_AA_HH _TIE_xt_MAC16_MULS_AA_HH -#define XT_MULS_AA_LH _TIE_xt_MAC16_MULS_AA_LH -#define XT_MULS_AA_HL _TIE_xt_MAC16_MULS_AA_HL -#define XT_MULS_AA_LL _TIE_xt_MAC16_MULS_AA_LL -#define XT_MULA_AA_HH _TIE_xt_MAC16_MULA_AA_HH -#define XT_MULA_AA_LH _TIE_xt_MAC16_MULA_AA_LH -#define XT_MULA_AA_HL _TIE_xt_MAC16_MULA_AA_HL -#define XT_MULA_AA_LL _TIE_xt_MAC16_MULA_AA_LL -#define XT_MULS_AD_HH _TIE_xt_MAC16_MULS_AD_HH -#define XT_MULS_AD_LH _TIE_xt_MAC16_MULS_AD_LH -#define XT_MULS_AD_HL _TIE_xt_MAC16_MULS_AD_HL -#define XT_MULS_AD_LL _TIE_xt_MAC16_MULS_AD_LL -#define XT_MULA_AD_HH _TIE_xt_MAC16_MULA_AD_HH -#define XT_MULA_AD_LH _TIE_xt_MAC16_MULA_AD_LH -#define XT_MULA_AD_HL _TIE_xt_MAC16_MULA_AD_HL -#define XT_MULA_AD_LL _TIE_xt_MAC16_MULA_AD_LL -#define XT_MULS_DA_HH _TIE_xt_MAC16_MULS_DA_HH -#define XT_MULS_DA_LH _TIE_xt_MAC16_MULS_DA_LH -#define XT_MULS_DA_HL _TIE_xt_MAC16_MULS_DA_HL -#define XT_MULS_DA_LL _TIE_xt_MAC16_MULS_DA_LL -#define XT_MULA_DA_HH _TIE_xt_MAC16_MULA_DA_HH -#define XT_MULA_DA_LH _TIE_xt_MAC16_MULA_DA_LH -#define XT_MULA_DA_HL _TIE_xt_MAC16_MULA_DA_HL -#define XT_MULA_DA_LL _TIE_xt_MAC16_MULA_DA_LL -#define XT_MULS_DD_HH _TIE_xt_MAC16_MULS_DD_HH -#define XT_MULS_DD_LH _TIE_xt_MAC16_MULS_DD_LH -#define XT_MULS_DD_HL _TIE_xt_MAC16_MULS_DD_HL -#define XT_MULS_DD_LL _TIE_xt_MAC16_MULS_DD_LL -#define XT_MULA_DD_HH _TIE_xt_MAC16_MULA_DD_HH -#define XT_MULA_DD_LH _TIE_xt_MAC16_MULA_DD_LH -#define XT_MULA_DD_HL _TIE_xt_MAC16_MULA_DD_HL -#define XT_MULA_DD_LL _TIE_xt_MAC16_MULA_DD_LL -#define XT_RSR_M0 _TIE_xt_MAC16_RSR_M0 -#define XT_WSR_M0 _TIE_xt_MAC16_WSR_M0 -#define XT_XSR_M0 _TIE_xt_MAC16_XSR_M0 -#define XT_RSR_M1 _TIE_xt_MAC16_RSR_M1 -#define XT_WSR_M1 _TIE_xt_MAC16_WSR_M1 -#define XT_XSR_M1 _TIE_xt_MAC16_XSR_M1 -#define XT_RSR_M2 _TIE_xt_MAC16_RSR_M2 -#define XT_WSR_M2 _TIE_xt_MAC16_WSR_M2 -#define XT_XSR_M2 _TIE_xt_MAC16_XSR_M2 -#define XT_RSR_M3 _TIE_xt_MAC16_RSR_M3 -#define XT_WSR_M3 _TIE_xt_MAC16_WSR_M3 -#define XT_XSR_M3 _TIE_xt_MAC16_XSR_M3 -#define XT_RSR_ACCLO _TIE_xt_MAC16_RSR_ACCLO -#define XT_WSR_ACCLO _TIE_xt_MAC16_WSR_ACCLO -#define XT_XSR_ACCLO _TIE_xt_MAC16_XSR_ACCLO -#define XT_RSR_ACCHI _TIE_xt_MAC16_RSR_ACCHI -#define XT_WSR_ACCHI _TIE_xt_MAC16_WSR_ACCHI -#define XT_XSR_ACCHI _TIE_xt_MAC16_XSR_ACCHI -#define XT_MULA_DA_LL_LDDEC _TIE_xt_MAC16_MULA_DA_LL_LDDEC -#define XT_MULA_DA_LL_LDINC _TIE_xt_MAC16_MULA_DA_LL_LDINC -#define XT_MULA_DA_HL_LDDEC _TIE_xt_MAC16_MULA_DA_HL_LDDEC -#define XT_MULA_DA_HL_LDINC _TIE_xt_MAC16_MULA_DA_HL_LDINC -#define XT_MULA_DA_LH_LDDEC _TIE_xt_MAC16_MULA_DA_LH_LDDEC -#define XT_MULA_DA_LH_LDINC _TIE_xt_MAC16_MULA_DA_LH_LDINC -#define XT_MULA_DA_HH_LDDEC _TIE_xt_MAC16_MULA_DA_HH_LDDEC -#define XT_MULA_DA_HH_LDINC _TIE_xt_MAC16_MULA_DA_HH_LDINC -#define XT_MULA_DD_LL_LDDEC _TIE_xt_MAC16_MULA_DD_LL_LDDEC -#define XT_MULA_DD_LL_LDINC _TIE_xt_MAC16_MULA_DD_LL_LDINC -#define XT_MULA_DD_HL_LDDEC _TIE_xt_MAC16_MULA_DD_HL_LDDEC -#define XT_MULA_DD_HL_LDINC _TIE_xt_MAC16_MULA_DD_HL_LDINC -#define XT_MULA_DD_LH_LDDEC _TIE_xt_MAC16_MULA_DD_LH_LDDEC -#define XT_MULA_DD_LH_LDINC _TIE_xt_MAC16_MULA_DD_LH_LDINC -#define XT_MULA_DD_HH_LDDEC _TIE_xt_MAC16_MULA_DD_HH_LDDEC -#define XT_MULA_DD_HH_LDINC _TIE_xt_MAC16_MULA_DD_HH_LDINC -#define XT_LDDEC _TIE_xt_MAC16_LDDEC -#define XT_ULDDEC _TIE_xt_MAC16_ULDDEC -#define XT_SLDDEC _TIE_xt_MAC16_SLDDEC -#define XT_LDINC _TIE_xt_MAC16_LDINC -#define XT_ULDINC _TIE_xt_MAC16_ULDINC -#define XT_SLDINC _TIE_xt_MAC16_SLDINC -#define XT_RSR16 _TIE_xt_MAC16_RSR16 -#define XT_WSR16 _TIE_xt_MAC16_WSR16 -#define XT_XSR16 _TIE_xt_MAC16_XSR16 -#define XT_RSR17 _TIE_xt_MAC16_RSR17 -#define XT_WSR17 _TIE_xt_MAC16_WSR17 -#define XT_XSR17 _TIE_xt_MAC16_XSR17 - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_MAC16_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_MUL32.h b/tools/sdk/include/esp32/xtensa/tie/xt_MUL32.h deleted file mode 100644 index 91b3c3299c2..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_MUL32.h +++ /dev/null @@ -1,24 +0,0 @@ -/* Definitions for the 32-bit Integer Multiply Option. */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2009 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* NOTE: This file exists only for backward compatibility with RB-200X.x - and earlier Xtensa releases. Starting with RC-2009.0 you should use - . */ - -#ifndef _XTENSA_xt_MUL32_HEADER -#define _XTENSA_xt_MUL32_HEADER - -#ifdef __XTENSA__ - -#include - -#endif /* __XTENSA__ */ -#endif /* !_XTENSA_xt_MUL32_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_booleans.h b/tools/sdk/include/esp32/xtensa/tie/xt_booleans.h deleted file mode 100644 index 94b5b468ed8..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_booleans.h +++ /dev/null @@ -1,69 +0,0 @@ -/* Definitions for the xt_booleans TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_booleans_HEADER -#define _XTENSA_xt_booleans_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include -typedef _TIE_xtbool xtbool; -typedef _TIE_xtbool2 xtbool2; -typedef _TIE_xtbool4 xtbool4; -typedef _TIE_xtbool8 xtbool8; -typedef _TIE_xtbool16 xtbool16; - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern xtbool _TIE_xt_booleans_XORB(xtbool bs, xtbool bt); -extern xtbool _TIE_xt_booleans_ORBC(xtbool bs, xtbool bt); -extern xtbool _TIE_xt_booleans_ORB(xtbool bs, xtbool bt); -extern xtbool _TIE_xt_booleans_ANDBC(xtbool bs, xtbool bt); -extern xtbool _TIE_xt_booleans_ANDB(xtbool bs, xtbool bt); -extern xtbool _TIE_xt_booleans_ALL4(xtbool4 bs4); -extern xtbool _TIE_xt_booleans_ANY4(xtbool4 bs4); -extern xtbool _TIE_xt_booleans_ALL8(xtbool8 bs8); -extern xtbool _TIE_xt_booleans_ANY8(xtbool8 bs8); -extern void _TIE_xt_booleans_MOVT(unsigned arr /*inout*/, unsigned ars, xtbool bt); -extern void _TIE_xt_booleans_MOVF(unsigned arr /*inout*/, unsigned ars, xtbool bt); -#define XT_XORB _TIE_xt_booleans_XORB -#define XT_ORBC _TIE_xt_booleans_ORBC -#define XT_ORB _TIE_xt_booleans_ORB -#define XT_ANDBC _TIE_xt_booleans_ANDBC -#define XT_ANDB _TIE_xt_booleans_ANDB -#define XT_ALL4 _TIE_xt_booleans_ALL4 -#define XT_ANY4 _TIE_xt_booleans_ANY4 -#define XT_ALL8 _TIE_xt_booleans_ALL8 -#define XT_ANY8 _TIE_xt_booleans_ANY8 -#define XT_MOVT _TIE_xt_booleans_MOVT -#define XT_MOVF _TIE_xt_booleans_MOVF - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_booleans_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_coprocessors.h b/tools/sdk/include/esp32/xtensa/tie/xt_coprocessors.h deleted file mode 100644 index 27215cf1cdd..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_coprocessors.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Definitions for the xt_coprocessors TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_coprocessors_HEADER -#define _XTENSA_xt_coprocessors_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern unsigned _TIE_xt_coprocessors_RSR_CPENABLE(void); -extern void _TIE_xt_coprocessors_WSR_CPENABLE(unsigned art); -extern void _TIE_xt_coprocessors_XSR_CPENABLE(unsigned art /*inout*/); -#define XT_RSR_CPENABLE _TIE_xt_coprocessors_RSR_CPENABLE -#define XT_WSR_CPENABLE _TIE_xt_coprocessors_WSR_CPENABLE -#define XT_XSR_CPENABLE _TIE_xt_coprocessors_XSR_CPENABLE - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_coprocessors_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_core.h b/tools/sdk/include/esp32/xtensa/tie/xt_core.h deleted file mode 100644 index 469b199e6b4..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_core.h +++ /dev/null @@ -1,395 +0,0 @@ -/* Definitions for the xt_core TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_core_HEADER -#define _XTENSA_xt_core_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_core_ILL(void); -extern void _TIE_xt_core_NOP(void); -extern void _TIE_xt_core_SIMCALL(void); -extern void _TIE_xt_core_MEMW(void); -extern void _TIE_xt_core_EXTW(void); -extern void _TIE_xt_core_ISYNC(void); -extern void _TIE_xt_core_DSYNC(void); -extern void _TIE_xt_core_ESYNC(void); -extern void _TIE_xt_core_RSYNC(void); -extern unsigned _TIE_xt_core_RSR_LBEG(void); -extern void _TIE_xt_core_WSR_LBEG(unsigned art); -extern void _TIE_xt_core_XSR_LBEG(unsigned art /*inout*/); -extern unsigned _TIE_xt_core_RSR_CONFIGID0(void); -extern void _TIE_xt_core_WSR_CONFIGID0(unsigned art); -extern unsigned _TIE_xt_core_RSR_CONFIGID1(void); -extern unsigned _TIE_xt_core_RUR_THREADPTR(void); -extern void _TIE_xt_core_WUR_THREADPTR(unsigned v); -extern unsigned _TIE_xt_core_uint32_loadi(const unsigned * p, immediate o); -extern void _TIE_xt_core_uint32_storei(unsigned c, unsigned * p, immediate o); -extern unsigned _TIE_xt_core_uint32_move(unsigned b); -extern int _TIE_xt_core_ADDI(int s, immediate i); -extern int _TIE_xt_core_OR(int s, int t); -extern int _TIE_xt_core_L32I(const int * p, immediate i); -extern void _TIE_xt_core_S32I(int r, int * p, immediate i); -extern void _TIE_xt_core_S32NB(int r, int * p, immediate i); -extern unsigned char _TIE_xt_core_L8UI(const unsigned char * p, immediate i); -extern void _TIE_xt_core_S8I(signed char r, signed char * p, immediate i); -extern unsigned short _TIE_xt_core_L16UI(const unsigned short * p, immediate i); -extern short _TIE_xt_core_L16SI(const short * p, immediate i); -extern void _TIE_xt_core_S16I(short r, short * p, immediate i); -extern int _TIE_xt_core_ADDMI(int s, immediate i); -extern int _TIE_xt_core_ADD(int s, int t); -extern int _TIE_xt_core_ADDX2(int s, int t); -extern int _TIE_xt_core_ADDX4(int s, int t); -extern int _TIE_xt_core_ADDX8(int s, int t); -extern int _TIE_xt_core_SUB(int s, int t); -extern int _TIE_xt_core_SUBX2(int s, int t); -extern int _TIE_xt_core_SUBX4(int s, int t); -extern int _TIE_xt_core_SUBX8(int s, int t); -extern int _TIE_xt_core_AND(int s, int t); -extern int _TIE_xt_core_XOR(int s, int t); -extern unsigned _TIE_xt_core_EXTUI(unsigned t, immediate i, immediate o); -extern int _TIE_xt_core_MOVI(immediate i); -extern void _TIE_xt_core_MOVEQZ(int r /*inout*/, int s, int t); -extern void _TIE_xt_core_MOVNEZ(int r /*inout*/, int s, int t); -extern void _TIE_xt_core_MOVLTZ(int r /*inout*/, int s, int t); -extern void _TIE_xt_core_MOVGEZ(int r /*inout*/, int s, int t); -extern int _TIE_xt_core_NEG(int t); -extern int _TIE_xt_core_ABS(int t); -extern void _TIE_xt_core_SSR(int s); -extern void _TIE_xt_core_SSL(int s); -extern void _TIE_xt_core_SSA8L(int s); -extern void _TIE_xt_core_SSA8B(int s); -extern void _TIE_xt_core_SSAI(immediate i); -extern int _TIE_xt_core_SLL(int s); -extern int _TIE_xt_core_SRC(int s, int t); -extern unsigned _TIE_xt_core_SRL(unsigned t); -extern int _TIE_xt_core_SRA(int t); -extern int _TIE_xt_core_SLLI(int s, immediate i); -extern int _TIE_xt_core_SRAI(int t, immediate i); -extern unsigned _TIE_xt_core_SRLI(unsigned t, immediate i); -extern int _TIE_xt_core_SSAI_SRC(int src1, int src2, immediate amount); -extern int _TIE_xt_core_SSR_SRC(int src1, int src2, int amount); -extern int _TIE_xt_core_WSR_SAR_SRC(int src1, int src2, int amount); -extern int _TIE_xt_core_SSR_SRA(int src, int amount); -extern unsigned _TIE_xt_core_SSR_SRL(unsigned src, int amount); -extern int _TIE_xt_core_SSL_SLL(int src, int amount); -extern int _TIE_xt_core_RSIL(immediate t); -extern int _TIE_xt_core_RSR_LEND(void); -extern void _TIE_xt_core_WSR_LEND(int t); -extern void _TIE_xt_core_XSR_LEND(int t /*inout*/); -extern int _TIE_xt_core_RSR_LCOUNT(void); -extern void _TIE_xt_core_WSR_LCOUNT(int t); -extern void _TIE_xt_core_XSR_LCOUNT(int t /*inout*/); -extern unsigned _TIE_xt_core_RSR_SAR(void); -extern void _TIE_xt_core_WSR_SAR(unsigned t); -extern void _TIE_xt_core_XSR_SAR(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_MEMCTL(void); -extern void _TIE_xt_core_WSR_MEMCTL(unsigned t); -extern void _TIE_xt_core_XSR_MEMCTL(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_LITBASE(void); -extern void _TIE_xt_core_WSR_LITBASE(unsigned t); -extern void _TIE_xt_core_XSR_LITBASE(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_PS(void); -extern void _TIE_xt_core_WSR_PS(unsigned t); -extern void _TIE_xt_core_XSR_PS(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPC1(void); -extern void _TIE_xt_core_WSR_EPC1(unsigned t); -extern void _TIE_xt_core_XSR_EPC1(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCSAVE1(void); -extern void _TIE_xt_core_WSR_EXCSAVE1(unsigned t); -extern void _TIE_xt_core_XSR_EXCSAVE1(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPC2(void); -extern void _TIE_xt_core_WSR_EPC2(unsigned t); -extern void _TIE_xt_core_XSR_EPC2(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCSAVE2(void); -extern void _TIE_xt_core_WSR_EXCSAVE2(unsigned t); -extern void _TIE_xt_core_XSR_EXCSAVE2(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPC3(void); -extern void _TIE_xt_core_WSR_EPC3(unsigned t); -extern void _TIE_xt_core_XSR_EPC3(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCSAVE3(void); -extern void _TIE_xt_core_WSR_EXCSAVE3(unsigned t); -extern void _TIE_xt_core_XSR_EXCSAVE3(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPC4(void); -extern void _TIE_xt_core_WSR_EPC4(unsigned t); -extern void _TIE_xt_core_XSR_EPC4(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCSAVE4(void); -extern void _TIE_xt_core_WSR_EXCSAVE4(unsigned t); -extern void _TIE_xt_core_XSR_EXCSAVE4(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPC5(void); -extern void _TIE_xt_core_WSR_EPC5(unsigned t); -extern void _TIE_xt_core_XSR_EPC5(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCSAVE5(void); -extern void _TIE_xt_core_WSR_EXCSAVE5(unsigned t); -extern void _TIE_xt_core_XSR_EXCSAVE5(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPC6(void); -extern void _TIE_xt_core_WSR_EPC6(unsigned t); -extern void _TIE_xt_core_XSR_EPC6(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCSAVE6(void); -extern void _TIE_xt_core_WSR_EXCSAVE6(unsigned t); -extern void _TIE_xt_core_XSR_EXCSAVE6(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPC7(void); -extern void _TIE_xt_core_WSR_EPC7(unsigned t); -extern void _TIE_xt_core_XSR_EPC7(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCSAVE7(void); -extern void _TIE_xt_core_WSR_EXCSAVE7(unsigned t); -extern void _TIE_xt_core_XSR_EXCSAVE7(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_VECBASE(void); -extern void _TIE_xt_core_WSR_VECBASE(unsigned t); -extern void _TIE_xt_core_XSR_VECBASE(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPS2(void); -extern void _TIE_xt_core_WSR_EPS2(unsigned t); -extern void _TIE_xt_core_XSR_EPS2(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPS3(void); -extern void _TIE_xt_core_WSR_EPS3(unsigned t); -extern void _TIE_xt_core_XSR_EPS3(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPS4(void); -extern void _TIE_xt_core_WSR_EPS4(unsigned t); -extern void _TIE_xt_core_XSR_EPS4(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPS5(void); -extern void _TIE_xt_core_WSR_EPS5(unsigned t); -extern void _TIE_xt_core_XSR_EPS5(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPS6(void); -extern void _TIE_xt_core_WSR_EPS6(unsigned t); -extern void _TIE_xt_core_XSR_EPS6(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EPS7(void); -extern void _TIE_xt_core_WSR_EPS7(unsigned t); -extern void _TIE_xt_core_XSR_EPS7(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCCAUSE(void); -extern void _TIE_xt_core_WSR_EXCCAUSE(unsigned t); -extern void _TIE_xt_core_XSR_EXCCAUSE(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_EXCVADDR(void); -extern void _TIE_xt_core_WSR_EXCVADDR(unsigned t); -extern void _TIE_xt_core_XSR_EXCVADDR(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_DEPC(void); -extern void _TIE_xt_core_WSR_DEPC(unsigned t); -extern void _TIE_xt_core_XSR_DEPC(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_MISC0(void); -extern void _TIE_xt_core_WSR_MISC0(unsigned t); -extern void _TIE_xt_core_XSR_MISC0(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_MISC1(void); -extern void _TIE_xt_core_WSR_MISC1(unsigned t); -extern void _TIE_xt_core_XSR_MISC1(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_MISC2(void); -extern void _TIE_xt_core_WSR_MISC2(unsigned t); -extern void _TIE_xt_core_XSR_MISC2(unsigned t /*inout*/); -extern unsigned _TIE_xt_core_RSR_MISC3(void); -extern void _TIE_xt_core_WSR_MISC3(unsigned t); -extern void _TIE_xt_core_XSR_MISC3(unsigned t /*inout*/); -extern int _TIE_xt_core_RSR_PRID(void); -#define XT_ILL _TIE_xt_core_ILL -#define XT_NOP _TIE_xt_core_NOP -#define XT_SIMCALL _TIE_xt_core_SIMCALL -#define XT_MEMW _TIE_xt_core_MEMW -#define XT_EXTW _TIE_xt_core_EXTW -#define XT_ISYNC _TIE_xt_core_ISYNC -#define XT_DSYNC _TIE_xt_core_DSYNC -#define XT_ESYNC _TIE_xt_core_ESYNC -#define XT_RSYNC _TIE_xt_core_RSYNC -#define XT_RSR_LBEG _TIE_xt_core_RSR_LBEG -#define XT_WSR_LBEG _TIE_xt_core_WSR_LBEG -#define XT_XSR_LBEG _TIE_xt_core_XSR_LBEG -#define XT_RSR_CONFIGID0 _TIE_xt_core_RSR_CONFIGID0 -#define XT_WSR_CONFIGID0 _TIE_xt_core_WSR_CONFIGID0 -#define XT_RSR_CONFIGID1 _TIE_xt_core_RSR_CONFIGID1 -#define XT_RUR_THREADPTR _TIE_xt_core_RUR_THREADPTR -#define RTHREADPTR _TIE_xt_core_RUR_THREADPTR -#define RUR231 _TIE_xt_core_RUR_THREADPTR -#define XT_WUR_THREADPTR _TIE_xt_core_WUR_THREADPTR -#define WTHREADPTR _TIE_xt_core_WUR_THREADPTR -#define WUR231 _TIE_xt_core_WUR_THREADPTR -#define XT_uint32_loadi _TIE_xt_core_uint32_loadi -#define XT_uint32_storei _TIE_xt_core_uint32_storei -#define XT_uint32_move _TIE_xt_core_uint32_move -#define XT_ADDI _TIE_xt_core_ADDI -#define XT_OR _TIE_xt_core_OR -#define XT_L32I _TIE_xt_core_L32I -#define XT_S32I _TIE_xt_core_S32I -#define XT_S32NB _TIE_xt_core_S32NB -#define XT_L8UI _TIE_xt_core_L8UI -#define XT_S8I _TIE_xt_core_S8I -#define XT_L16UI _TIE_xt_core_L16UI -#define XT_L16SI _TIE_xt_core_L16SI -#define XT_S16I _TIE_xt_core_S16I -#define XT_ADDMI _TIE_xt_core_ADDMI -#define XT_ADD _TIE_xt_core_ADD -#define XT_ADDX2 _TIE_xt_core_ADDX2 -#define XT_ADDX4 _TIE_xt_core_ADDX4 -#define XT_ADDX8 _TIE_xt_core_ADDX8 -#define XT_SUB _TIE_xt_core_SUB -#define XT_SUBX2 _TIE_xt_core_SUBX2 -#define XT_SUBX4 _TIE_xt_core_SUBX4 -#define XT_SUBX8 _TIE_xt_core_SUBX8 -#define XT_AND _TIE_xt_core_AND -#define XT_XOR _TIE_xt_core_XOR -#define XT_EXTUI _TIE_xt_core_EXTUI -#define XT_MOVI _TIE_xt_core_MOVI -#define XT_MOVEQZ _TIE_xt_core_MOVEQZ -#define XT_MOVNEZ _TIE_xt_core_MOVNEZ -#define XT_MOVLTZ _TIE_xt_core_MOVLTZ -#define XT_MOVGEZ _TIE_xt_core_MOVGEZ -#define XT_NEG _TIE_xt_core_NEG -#define XT_ABS _TIE_xt_core_ABS -#define XT_SSR _TIE_xt_core_SSR -#define XT_SSL _TIE_xt_core_SSL -#define XT_SSA8L _TIE_xt_core_SSA8L -#define XT_SSA8B _TIE_xt_core_SSA8B -#define XT_SSAI _TIE_xt_core_SSAI -#define XT_SLL _TIE_xt_core_SLL -#define XT_SRC _TIE_xt_core_SRC -#define XT_SRL _TIE_xt_core_SRL -#define XT_SRA _TIE_xt_core_SRA -#define XT_SLLI _TIE_xt_core_SLLI -#define XT_SRAI _TIE_xt_core_SRAI -#define XT_SRLI _TIE_xt_core_SRLI -#define XT_SSAI_SRC _TIE_xt_core_SSAI_SRC -#define XT_SSR_SRC _TIE_xt_core_SSR_SRC -#define XT_WSR_SAR_SRC _TIE_xt_core_WSR_SAR_SRC -#define XT_SSR_SRA _TIE_xt_core_SSR_SRA -#define XT_SSR_SRL _TIE_xt_core_SSR_SRL -#define XT_SSL_SLL _TIE_xt_core_SSL_SLL -#define XT_RSIL _TIE_xt_core_RSIL -#define XT_RSR_LEND _TIE_xt_core_RSR_LEND -#define XT_WSR_LEND _TIE_xt_core_WSR_LEND -#define XT_XSR_LEND _TIE_xt_core_XSR_LEND -#define XT_RSR_LCOUNT _TIE_xt_core_RSR_LCOUNT -#define XT_WSR_LCOUNT _TIE_xt_core_WSR_LCOUNT -#define XT_XSR_LCOUNT _TIE_xt_core_XSR_LCOUNT -#define XT_RSR_SAR _TIE_xt_core_RSR_SAR -#define XT_WSR_SAR _TIE_xt_core_WSR_SAR -#define XT_XSR_SAR _TIE_xt_core_XSR_SAR -#define XT_RSR_MEMCTL _TIE_xt_core_RSR_MEMCTL -#define XT_WSR_MEMCTL _TIE_xt_core_WSR_MEMCTL -#define XT_XSR_MEMCTL _TIE_xt_core_XSR_MEMCTL -#define XT_RSR_LITBASE _TIE_xt_core_RSR_LITBASE -#define XT_WSR_LITBASE _TIE_xt_core_WSR_LITBASE -#define XT_XSR_LITBASE _TIE_xt_core_XSR_LITBASE -#define XT_RSR_PS _TIE_xt_core_RSR_PS -#define XT_WSR_PS _TIE_xt_core_WSR_PS -#define XT_XSR_PS _TIE_xt_core_XSR_PS -#define XT_RSR_EPC1 _TIE_xt_core_RSR_EPC1 -#define XT_WSR_EPC1 _TIE_xt_core_WSR_EPC1 -#define XT_XSR_EPC1 _TIE_xt_core_XSR_EPC1 -#define XT_RSR_EXCSAVE1 _TIE_xt_core_RSR_EXCSAVE1 -#define XT_WSR_EXCSAVE1 _TIE_xt_core_WSR_EXCSAVE1 -#define XT_XSR_EXCSAVE1 _TIE_xt_core_XSR_EXCSAVE1 -#define XT_RSR_EPC2 _TIE_xt_core_RSR_EPC2 -#define XT_WSR_EPC2 _TIE_xt_core_WSR_EPC2 -#define XT_XSR_EPC2 _TIE_xt_core_XSR_EPC2 -#define XT_RSR_EXCSAVE2 _TIE_xt_core_RSR_EXCSAVE2 -#define XT_WSR_EXCSAVE2 _TIE_xt_core_WSR_EXCSAVE2 -#define XT_XSR_EXCSAVE2 _TIE_xt_core_XSR_EXCSAVE2 -#define XT_RSR_EPC3 _TIE_xt_core_RSR_EPC3 -#define XT_WSR_EPC3 _TIE_xt_core_WSR_EPC3 -#define XT_XSR_EPC3 _TIE_xt_core_XSR_EPC3 -#define XT_RSR_EXCSAVE3 _TIE_xt_core_RSR_EXCSAVE3 -#define XT_WSR_EXCSAVE3 _TIE_xt_core_WSR_EXCSAVE3 -#define XT_XSR_EXCSAVE3 _TIE_xt_core_XSR_EXCSAVE3 -#define XT_RSR_EPC4 _TIE_xt_core_RSR_EPC4 -#define XT_WSR_EPC4 _TIE_xt_core_WSR_EPC4 -#define XT_XSR_EPC4 _TIE_xt_core_XSR_EPC4 -#define XT_RSR_EXCSAVE4 _TIE_xt_core_RSR_EXCSAVE4 -#define XT_WSR_EXCSAVE4 _TIE_xt_core_WSR_EXCSAVE4 -#define XT_XSR_EXCSAVE4 _TIE_xt_core_XSR_EXCSAVE4 -#define XT_RSR_EPC5 _TIE_xt_core_RSR_EPC5 -#define XT_WSR_EPC5 _TIE_xt_core_WSR_EPC5 -#define XT_XSR_EPC5 _TIE_xt_core_XSR_EPC5 -#define XT_RSR_EXCSAVE5 _TIE_xt_core_RSR_EXCSAVE5 -#define XT_WSR_EXCSAVE5 _TIE_xt_core_WSR_EXCSAVE5 -#define XT_XSR_EXCSAVE5 _TIE_xt_core_XSR_EXCSAVE5 -#define XT_RSR_EPC6 _TIE_xt_core_RSR_EPC6 -#define XT_WSR_EPC6 _TIE_xt_core_WSR_EPC6 -#define XT_XSR_EPC6 _TIE_xt_core_XSR_EPC6 -#define XT_RSR_EXCSAVE6 _TIE_xt_core_RSR_EXCSAVE6 -#define XT_WSR_EXCSAVE6 _TIE_xt_core_WSR_EXCSAVE6 -#define XT_XSR_EXCSAVE6 _TIE_xt_core_XSR_EXCSAVE6 -#define XT_RSR_EPC7 _TIE_xt_core_RSR_EPC7 -#define XT_WSR_EPC7 _TIE_xt_core_WSR_EPC7 -#define XT_XSR_EPC7 _TIE_xt_core_XSR_EPC7 -#define XT_RSR_EXCSAVE7 _TIE_xt_core_RSR_EXCSAVE7 -#define XT_WSR_EXCSAVE7 _TIE_xt_core_WSR_EXCSAVE7 -#define XT_XSR_EXCSAVE7 _TIE_xt_core_XSR_EXCSAVE7 -#define XT_RSR_VECBASE _TIE_xt_core_RSR_VECBASE -#define XT_WSR_VECBASE _TIE_xt_core_WSR_VECBASE -#define XT_XSR_VECBASE _TIE_xt_core_XSR_VECBASE -#define XT_RSR_EPS2 _TIE_xt_core_RSR_EPS2 -#define XT_WSR_EPS2 _TIE_xt_core_WSR_EPS2 -#define XT_XSR_EPS2 _TIE_xt_core_XSR_EPS2 -#define XT_RSR_EPS3 _TIE_xt_core_RSR_EPS3 -#define XT_WSR_EPS3 _TIE_xt_core_WSR_EPS3 -#define XT_XSR_EPS3 _TIE_xt_core_XSR_EPS3 -#define XT_RSR_EPS4 _TIE_xt_core_RSR_EPS4 -#define XT_WSR_EPS4 _TIE_xt_core_WSR_EPS4 -#define XT_XSR_EPS4 _TIE_xt_core_XSR_EPS4 -#define XT_RSR_EPS5 _TIE_xt_core_RSR_EPS5 -#define XT_WSR_EPS5 _TIE_xt_core_WSR_EPS5 -#define XT_XSR_EPS5 _TIE_xt_core_XSR_EPS5 -#define XT_RSR_EPS6 _TIE_xt_core_RSR_EPS6 -#define XT_WSR_EPS6 _TIE_xt_core_WSR_EPS6 -#define XT_XSR_EPS6 _TIE_xt_core_XSR_EPS6 -#define XT_RSR_EPS7 _TIE_xt_core_RSR_EPS7 -#define XT_WSR_EPS7 _TIE_xt_core_WSR_EPS7 -#define XT_XSR_EPS7 _TIE_xt_core_XSR_EPS7 -#define XT_RSR_EXCCAUSE _TIE_xt_core_RSR_EXCCAUSE -#define XT_WSR_EXCCAUSE _TIE_xt_core_WSR_EXCCAUSE -#define XT_XSR_EXCCAUSE _TIE_xt_core_XSR_EXCCAUSE -#define XT_RSR_EXCVADDR _TIE_xt_core_RSR_EXCVADDR -#define XT_WSR_EXCVADDR _TIE_xt_core_WSR_EXCVADDR -#define XT_XSR_EXCVADDR _TIE_xt_core_XSR_EXCVADDR -#define XT_RSR_DEPC _TIE_xt_core_RSR_DEPC -#define XT_WSR_DEPC _TIE_xt_core_WSR_DEPC -#define XT_XSR_DEPC _TIE_xt_core_XSR_DEPC -#define XT_RSR_MISC0 _TIE_xt_core_RSR_MISC0 -#define XT_WSR_MISC0 _TIE_xt_core_WSR_MISC0 -#define XT_XSR_MISC0 _TIE_xt_core_XSR_MISC0 -#define XT_RSR_MISC1 _TIE_xt_core_RSR_MISC1 -#define XT_WSR_MISC1 _TIE_xt_core_WSR_MISC1 -#define XT_XSR_MISC1 _TIE_xt_core_XSR_MISC1 -#define XT_RSR_MISC2 _TIE_xt_core_RSR_MISC2 -#define XT_WSR_MISC2 _TIE_xt_core_WSR_MISC2 -#define XT_XSR_MISC2 _TIE_xt_core_XSR_MISC2 -#define XT_RSR_MISC3 _TIE_xt_core_RSR_MISC3 -#define XT_WSR_MISC3 _TIE_xt_core_WSR_MISC3 -#define XT_XSR_MISC3 _TIE_xt_core_XSR_MISC3 -#define XT_RSR_PRID _TIE_xt_core_RSR_PRID - -#ifndef RUR -#define RUR(NUM) RUR##NUM() -#endif - -#ifndef WUR -#define WUR(VAL, NUM) WUR##NUM(VAL) -#endif - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_core_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_debug.h b/tools/sdk/include/esp32/xtensa/tie/xt_debug.h deleted file mode 100644 index 676fd33c782..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_debug.h +++ /dev/null @@ -1,116 +0,0 @@ -/* Definitions for the xt_debug TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_debug_HEADER -#define _XTENSA_xt_debug_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_debug_BREAK(immediate imms, immediate immt); -extern void _TIE_xt_debug_BREAK_N(immediate imms); -extern unsigned _TIE_xt_debug_RSR_DBREAKA0(void); -extern void _TIE_xt_debug_WSR_DBREAKA0(unsigned art); -extern void _TIE_xt_debug_XSR_DBREAKA0(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_DBREAKC0(void); -extern void _TIE_xt_debug_WSR_DBREAKC0(unsigned art); -extern void _TIE_xt_debug_XSR_DBREAKC0(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_DBREAKA1(void); -extern void _TIE_xt_debug_WSR_DBREAKA1(unsigned art); -extern void _TIE_xt_debug_XSR_DBREAKA1(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_DBREAKC1(void); -extern void _TIE_xt_debug_WSR_DBREAKC1(unsigned art); -extern void _TIE_xt_debug_XSR_DBREAKC1(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_IBREAKA0(void); -extern void _TIE_xt_debug_WSR_IBREAKA0(unsigned art); -extern void _TIE_xt_debug_XSR_IBREAKA0(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_IBREAKA1(void); -extern void _TIE_xt_debug_WSR_IBREAKA1(unsigned art); -extern void _TIE_xt_debug_XSR_IBREAKA1(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_IBREAKENABLE(void); -extern void _TIE_xt_debug_WSR_IBREAKENABLE(unsigned art); -extern void _TIE_xt_debug_XSR_IBREAKENABLE(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_DEBUGCAUSE(void); -extern void _TIE_xt_debug_WSR_DEBUGCAUSE(unsigned art); -extern void _TIE_xt_debug_XSR_DEBUGCAUSE(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_ICOUNT(void); -extern void _TIE_xt_debug_WSR_ICOUNT(unsigned art); -extern void _TIE_xt_debug_XSR_ICOUNT(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_ICOUNTLEVEL(void); -extern void _TIE_xt_debug_WSR_ICOUNTLEVEL(unsigned art); -extern void _TIE_xt_debug_XSR_ICOUNTLEVEL(unsigned art /*inout*/); -extern unsigned _TIE_xt_debug_RSR_DDR(void); -extern void _TIE_xt_debug_WSR_DDR(unsigned art); -extern void _TIE_xt_debug_XSR_DDR(unsigned art /*inout*/); -extern void _TIE_xt_debug_LDDR32_P(const void * ars /*inout*/); -extern void _TIE_xt_debug_SDDR32_P(void * ars /*inout*/); -#define XT_BREAK _TIE_xt_debug_BREAK -#define XT_BREAK_N _TIE_xt_debug_BREAK_N -#define XT_RSR_DBREAKA0 _TIE_xt_debug_RSR_DBREAKA0 -#define XT_WSR_DBREAKA0 _TIE_xt_debug_WSR_DBREAKA0 -#define XT_XSR_DBREAKA0 _TIE_xt_debug_XSR_DBREAKA0 -#define XT_RSR_DBREAKC0 _TIE_xt_debug_RSR_DBREAKC0 -#define XT_WSR_DBREAKC0 _TIE_xt_debug_WSR_DBREAKC0 -#define XT_XSR_DBREAKC0 _TIE_xt_debug_XSR_DBREAKC0 -#define XT_RSR_DBREAKA1 _TIE_xt_debug_RSR_DBREAKA1 -#define XT_WSR_DBREAKA1 _TIE_xt_debug_WSR_DBREAKA1 -#define XT_XSR_DBREAKA1 _TIE_xt_debug_XSR_DBREAKA1 -#define XT_RSR_DBREAKC1 _TIE_xt_debug_RSR_DBREAKC1 -#define XT_WSR_DBREAKC1 _TIE_xt_debug_WSR_DBREAKC1 -#define XT_XSR_DBREAKC1 _TIE_xt_debug_XSR_DBREAKC1 -#define XT_RSR_IBREAKA0 _TIE_xt_debug_RSR_IBREAKA0 -#define XT_WSR_IBREAKA0 _TIE_xt_debug_WSR_IBREAKA0 -#define XT_XSR_IBREAKA0 _TIE_xt_debug_XSR_IBREAKA0 -#define XT_RSR_IBREAKA1 _TIE_xt_debug_RSR_IBREAKA1 -#define XT_WSR_IBREAKA1 _TIE_xt_debug_WSR_IBREAKA1 -#define XT_XSR_IBREAKA1 _TIE_xt_debug_XSR_IBREAKA1 -#define XT_RSR_IBREAKENABLE _TIE_xt_debug_RSR_IBREAKENABLE -#define XT_WSR_IBREAKENABLE _TIE_xt_debug_WSR_IBREAKENABLE -#define XT_XSR_IBREAKENABLE _TIE_xt_debug_XSR_IBREAKENABLE -#define XT_RSR_DEBUGCAUSE _TIE_xt_debug_RSR_DEBUGCAUSE -#define XT_WSR_DEBUGCAUSE _TIE_xt_debug_WSR_DEBUGCAUSE -#define XT_XSR_DEBUGCAUSE _TIE_xt_debug_XSR_DEBUGCAUSE -#define XT_RSR_ICOUNT _TIE_xt_debug_RSR_ICOUNT -#define XT_WSR_ICOUNT _TIE_xt_debug_WSR_ICOUNT -#define XT_XSR_ICOUNT _TIE_xt_debug_XSR_ICOUNT -#define XT_RSR_ICOUNTLEVEL _TIE_xt_debug_RSR_ICOUNTLEVEL -#define XT_WSR_ICOUNTLEVEL _TIE_xt_debug_WSR_ICOUNTLEVEL -#define XT_XSR_ICOUNTLEVEL _TIE_xt_debug_XSR_ICOUNTLEVEL -#define XT_RSR_DDR _TIE_xt_debug_RSR_DDR -#define XT_WSR_DDR _TIE_xt_debug_WSR_DDR -#define XT_XSR_DDR _TIE_xt_debug_XSR_DDR -#define XT_LDDR32_P _TIE_xt_debug_LDDR32_P -#define XT_SDDR32_P _TIE_xt_debug_SDDR32_P - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_debug_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_density.h b/tools/sdk/include/esp32/xtensa/tie/xt_density.h deleted file mode 100644 index da5c51ccf05..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_density.h +++ /dev/null @@ -1,58 +0,0 @@ -/* Definitions for the xt_density TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_density_HEADER -#define _XTENSA_xt_density_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_density_ILL_N(void); -extern void _TIE_xt_density_NOP_N(void); -extern int _TIE_xt_density_L32I_N(const int * p, immediate i); -extern void _TIE_xt_density_S32I_N(int t, int * p, immediate i); -extern int _TIE_xt_density_ADD_N(int s, int t); -extern int _TIE_xt_density_ADDI_N(int s, immediate i); -extern int _TIE_xt_density_MOV_N(int s); -extern int _TIE_xt_density_MOVI_N(immediate i); -#define XT_ILL_N _TIE_xt_density_ILL_N -#define XT_NOP_N _TIE_xt_density_NOP_N -#define XT_L32I_N _TIE_xt_density_L32I_N -#define XT_S32I_N _TIE_xt_density_S32I_N -#define XT_ADD_N _TIE_xt_density_ADD_N -#define XT_ADDI_N _TIE_xt_density_ADDI_N -#define XT_MOV_N _TIE_xt_density_MOV_N -#define XT_MOVI_N _TIE_xt_density_MOVI_N - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_density_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_exceptions.h b/tools/sdk/include/esp32/xtensa/tie/xt_exceptions.h deleted file mode 100644 index 64fb3930790..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_exceptions.h +++ /dev/null @@ -1,45 +0,0 @@ -/* Definitions for the xt_exceptions TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_exceptions_HEADER -#define _XTENSA_xt_exceptions_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_exceptions_EXCW(void); -extern void _TIE_xt_exceptions_SYSCALL(void); -#define XT_EXCW _TIE_xt_exceptions_EXCW -#define XT_SYSCALL _TIE_xt_exceptions_SYSCALL - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_exceptions_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_externalregisters.h b/tools/sdk/include/esp32/xtensa/tie/xt_externalregisters.h deleted file mode 100644 index 3196527c2f6..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_externalregisters.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Definitions for the xt_externalregisters TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_externalregisters_HEADER -#define _XTENSA_xt_externalregisters_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern unsigned _TIE_xt_externalregisters_RER(unsigned ars); -extern void _TIE_xt_externalregisters_WER(unsigned art, unsigned ars); -#define XT_RER _TIE_xt_externalregisters_RER -#define XT_WER _TIE_xt_externalregisters_WER - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_externalregisters_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_integerdivide.h b/tools/sdk/include/esp32/xtensa/tie/xt_integerdivide.h deleted file mode 100644 index 9fbe9615b7b..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_integerdivide.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Definitions for the xt_integerdivide TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_integerdivide_HEADER -#define _XTENSA_xt_integerdivide_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern unsigned _TIE_xt_integerdivide_REMS(unsigned ars, unsigned art); -extern unsigned _TIE_xt_integerdivide_REMU(unsigned ars, unsigned art); -extern unsigned _TIE_xt_integerdivide_QUOS(unsigned ars, unsigned art); -extern unsigned _TIE_xt_integerdivide_QUOU(unsigned ars, unsigned art); -#define XT_REMS _TIE_xt_integerdivide_REMS -#define XT_REMU _TIE_xt_integerdivide_REMU -#define XT_QUOS _TIE_xt_integerdivide_QUOS -#define XT_QUOU _TIE_xt_integerdivide_QUOU - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_integerdivide_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_interrupt.h b/tools/sdk/include/esp32/xtensa/tie/xt_interrupt.h deleted file mode 100644 index b20c94f47ac..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_interrupt.h +++ /dev/null @@ -1,56 +0,0 @@ -/* Definitions for the xt_interrupt TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_interrupt_HEADER -#define _XTENSA_xt_interrupt_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_interrupt_WAITI(immediate s); -extern unsigned _TIE_xt_interrupt_RSR_INTERRUPT(void); -extern void _TIE_xt_interrupt_WSR_INTSET(unsigned art); -extern void _TIE_xt_interrupt_WSR_INTCLEAR(unsigned art); -extern unsigned _TIE_xt_interrupt_RSR_INTENABLE(void); -extern void _TIE_xt_interrupt_WSR_INTENABLE(unsigned art); -extern void _TIE_xt_interrupt_XSR_INTENABLE(unsigned art /*inout*/); -#define XT_WAITI _TIE_xt_interrupt_WAITI -#define XT_RSR_INTERRUPT _TIE_xt_interrupt_RSR_INTERRUPT -#define XT_WSR_INTSET _TIE_xt_interrupt_WSR_INTSET -#define XT_WSR_INTCLEAR _TIE_xt_interrupt_WSR_INTCLEAR -#define XT_RSR_INTENABLE _TIE_xt_interrupt_RSR_INTENABLE -#define XT_WSR_INTENABLE _TIE_xt_interrupt_WSR_INTENABLE -#define XT_XSR_INTENABLE _TIE_xt_interrupt_XSR_INTENABLE - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_interrupt_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_ioports.h b/tools/sdk/include/esp32/xtensa/tie/xt_ioports.h deleted file mode 100644 index 0253bea4cf6..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_ioports.h +++ /dev/null @@ -1,66 +0,0 @@ -/* Definitions for the xt_ioports TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_ioports_HEADER -#define _XTENSA_xt_ioports_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern unsigned _TIE_xt_ioports_READ_IMPWIRE(void); -extern void _TIE_xt_ioports_SETB_EXPSTATE(immediate bitindex); -extern void _TIE_xt_ioports_CLRB_EXPSTATE(immediate bitindex); -extern void _TIE_xt_ioports_WRMSK_EXPSTATE(unsigned art, unsigned ars); -extern unsigned _TIE_xt_ioports_RUR_EXPSTATE(void); -extern void _TIE_xt_ioports_WUR_EXPSTATE(unsigned v); -#define READ_IMPWIRE _TIE_xt_ioports_READ_IMPWIRE -#define SETB_EXPSTATE _TIE_xt_ioports_SETB_EXPSTATE -#define CLRB_EXPSTATE _TIE_xt_ioports_CLRB_EXPSTATE -#define WRMSK_EXPSTATE _TIE_xt_ioports_WRMSK_EXPSTATE -#define RUR_EXPSTATE _TIE_xt_ioports_RUR_EXPSTATE -#define REXPSTATE _TIE_xt_ioports_RUR_EXPSTATE -#define RUR230 _TIE_xt_ioports_RUR_EXPSTATE -#define WUR_EXPSTATE _TIE_xt_ioports_WUR_EXPSTATE -#define WEXPSTATE _TIE_xt_ioports_WUR_EXPSTATE -#define WUR230 _TIE_xt_ioports_WUR_EXPSTATE - -#ifndef RUR -#define RUR(NUM) RUR##NUM() -#endif - -#ifndef WUR -#define WUR(VAL, NUM) WUR##NUM(VAL) -#endif - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_ioports_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_misc.h b/tools/sdk/include/esp32/xtensa/tie/xt_misc.h deleted file mode 100644 index a0b36f4e5d4..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_misc.h +++ /dev/null @@ -1,58 +0,0 @@ -/* Definitions for the xt_misc TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_misc_HEADER -#define _XTENSA_xt_misc_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern int _TIE_xt_misc_CLAMPS(int s, immediate i); -extern int _TIE_xt_misc_MIN(int s, int t); -extern int _TIE_xt_misc_MAX(int s, int t); -extern unsigned _TIE_xt_misc_MINU(unsigned s, unsigned t); -extern unsigned _TIE_xt_misc_MAXU(unsigned s, unsigned t); -extern int _TIE_xt_misc_NSA(int s); -extern unsigned _TIE_xt_misc_NSAU(unsigned s); -extern int _TIE_xt_misc_SEXT(int s, immediate i); -#define XT_CLAMPS _TIE_xt_misc_CLAMPS -#define XT_MIN _TIE_xt_misc_MIN -#define XT_MAX _TIE_xt_misc_MAX -#define XT_MINU _TIE_xt_misc_MINU -#define XT_MAXU _TIE_xt_misc_MAXU -#define XT_NSA _TIE_xt_misc_NSA -#define XT_NSAU _TIE_xt_misc_NSAU -#define XT_SEXT _TIE_xt_misc_SEXT - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_misc_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_mmu.h b/tools/sdk/include/esp32/xtensa/tie/xt_mmu.h deleted file mode 100644 index ce786c0fea4..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_mmu.h +++ /dev/null @@ -1,62 +0,0 @@ -/* Definitions for the xt_mmu TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_mmu_HEADER -#define _XTENSA_xt_mmu_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_mmu_IDTLB(unsigned ars); -extern unsigned _TIE_xt_mmu_RDTLB1(unsigned ars); -extern unsigned _TIE_xt_mmu_RDTLB0(unsigned ars); -extern unsigned _TIE_xt_mmu_PDTLB(unsigned ars); -extern void _TIE_xt_mmu_WDTLB(unsigned art, unsigned ars); -extern void _TIE_xt_mmu_IITLB(unsigned ars); -extern unsigned _TIE_xt_mmu_RITLB1(unsigned ars); -extern unsigned _TIE_xt_mmu_RITLB0(unsigned ars); -extern unsigned _TIE_xt_mmu_PITLB(unsigned ars); -extern void _TIE_xt_mmu_WITLB(unsigned art, unsigned ars); -#define XT_IDTLB _TIE_xt_mmu_IDTLB -#define XT_RDTLB1 _TIE_xt_mmu_RDTLB1 -#define XT_RDTLB0 _TIE_xt_mmu_RDTLB0 -#define XT_PDTLB _TIE_xt_mmu_PDTLB -#define XT_WDTLB _TIE_xt_mmu_WDTLB -#define XT_IITLB _TIE_xt_mmu_IITLB -#define XT_RITLB1 _TIE_xt_mmu_RITLB1 -#define XT_RITLB0 _TIE_xt_mmu_RITLB0 -#define XT_PITLB _TIE_xt_mmu_PITLB -#define XT_WITLB _TIE_xt_mmu_WITLB - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_mmu_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_mul.h b/tools/sdk/include/esp32/xtensa/tie/xt_mul.h deleted file mode 100644 index e20862069d0..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_mul.h +++ /dev/null @@ -1,52 +0,0 @@ -/* Definitions for the xt_mul TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_mul_HEADER -#define _XTENSA_xt_mul_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern int _TIE_xt_mul_MUL16S(short s, short t); -extern unsigned _TIE_xt_mul_MUL16U(unsigned short s, unsigned short t); -extern int _TIE_xt_mul_MULL(int s, int t); -extern unsigned _TIE_xt_mul_MULUH(unsigned s, unsigned t); -extern int _TIE_xt_mul_MULSH(int s, int t); -#define XT_MUL16S _TIE_xt_mul_MUL16S -#define XT_MUL16U _TIE_xt_mul_MUL16U -#define XT_MULL _TIE_xt_mul_MULL -#define XT_MULUH _TIE_xt_mul_MULUH -#define XT_MULSH _TIE_xt_mul_MULSH - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_mul_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_regwin.h b/tools/sdk/include/esp32/xtensa/tie/xt_regwin.h deleted file mode 100644 index 7bce471a03b..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_regwin.h +++ /dev/null @@ -1,64 +0,0 @@ -/* Definitions for the xt_regwin TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_regwin_HEADER -#define _XTENSA_xt_regwin_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_regwin_ENTRY(unsigned ars /*inout*/, immediate uimm12x8); -extern void _TIE_xt_regwin_ROTW(immediate simm4); -extern int _TIE_xt_regwin_MOVSP(int s); -extern int _TIE_xt_regwin_L32E(const int * s, immediate o); -extern void _TIE_xt_regwin_S32E(int t, int * s, immediate o); -extern unsigned _TIE_xt_regwin_RSR_WINDOWBASE(void); -extern void _TIE_xt_regwin_WSR_WINDOWBASE(unsigned t); -extern void _TIE_xt_regwin_XSR_WINDOWBASE(unsigned t /*inout*/); -extern unsigned _TIE_xt_regwin_RSR_WINDOWSTART(void); -extern void _TIE_xt_regwin_WSR_WINDOWSTART(unsigned t); -extern void _TIE_xt_regwin_XSR_WINDOWSTART(unsigned t /*inout*/); -#define XT_ENTRY _TIE_xt_regwin_ENTRY -#define XT_ROTW _TIE_xt_regwin_ROTW -#define XT_MOVSP _TIE_xt_regwin_MOVSP -#define XT_L32E _TIE_xt_regwin_L32E -#define XT_S32E _TIE_xt_regwin_S32E -#define XT_RSR_WINDOWBASE _TIE_xt_regwin_RSR_WINDOWBASE -#define XT_WSR_WINDOWBASE _TIE_xt_regwin_WSR_WINDOWBASE -#define XT_XSR_WINDOWBASE _TIE_xt_regwin_XSR_WINDOWBASE -#define XT_RSR_WINDOWSTART _TIE_xt_regwin_RSR_WINDOWSTART -#define XT_WSR_WINDOWSTART _TIE_xt_regwin_WSR_WINDOWSTART -#define XT_XSR_WINDOWSTART _TIE_xt_regwin_XSR_WINDOWSTART - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_regwin_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_scmpr.h b/tools/sdk/include/esp32/xtensa/tie/xt_scmpr.h deleted file mode 100644 index 337c7762ebc..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_scmpr.h +++ /dev/null @@ -1,22 +0,0 @@ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_scmpr_h_HEADER -#define _XTENSA_xt_scmpr_h_HEADER - - -/* Header includes start */ - - -/* Header includes end */ - -#endif /* !_XTENSA_xt_scmpr_h_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_sync.h b/tools/sdk/include/esp32/xtensa/tie/xt_sync.h deleted file mode 100644 index 9323dfe4b88..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_sync.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Definitions for the xt_sync TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_sync_HEADER -#define _XTENSA_xt_sync_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern unsigned _TIE_xt_sync_RSR_SCOMPARE1(void); -extern void _TIE_xt_sync_WSR_SCOMPARE1(unsigned art); -extern void _TIE_xt_sync_XSR_SCOMPARE1(unsigned art /*inout*/); -extern unsigned _TIE_xt_sync_RSR_ATOMCTL(void); -extern void _TIE_xt_sync_WSR_ATOMCTL(unsigned art); -extern void _TIE_xt_sync_XSR_ATOMCTL(unsigned art /*inout*/); -extern unsigned _TIE_xt_sync_L32AI(const unsigned * p, immediate o); -extern void _TIE_xt_sync_S32RI(unsigned c, unsigned * p, immediate o); -extern void _TIE_xt_sync_S32C1I(unsigned c /*inout*/, const unsigned * p, immediate o); -#define XT_RSR_SCOMPARE1 _TIE_xt_sync_RSR_SCOMPARE1 -#define XT_WSR_SCOMPARE1 _TIE_xt_sync_WSR_SCOMPARE1 -#define XT_XSR_SCOMPARE1 _TIE_xt_sync_XSR_SCOMPARE1 -#define XT_RSR_ATOMCTL _TIE_xt_sync_RSR_ATOMCTL -#define XT_WSR_ATOMCTL _TIE_xt_sync_WSR_ATOMCTL -#define XT_XSR_ATOMCTL _TIE_xt_sync_XSR_ATOMCTL -#define XT_L32AI _TIE_xt_sync_L32AI -#define XT_S32RI _TIE_xt_sync_S32RI -#define XT_S32C1I _TIE_xt_sync_S32C1I - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_sync_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_timer.h b/tools/sdk/include/esp32/xtensa/tie/xt_timer.h deleted file mode 100644 index 64db45c1a44..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_timer.h +++ /dev/null @@ -1,66 +0,0 @@ -/* Definitions for the xt_timer TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_timer_HEADER -#define _XTENSA_xt_timer_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern unsigned _TIE_xt_timer_RSR_CCOUNT(void); -extern void _TIE_xt_timer_WSR_CCOUNT(unsigned art); -extern void _TIE_xt_timer_XSR_CCOUNT(unsigned art /*inout*/); -extern unsigned _TIE_xt_timer_RSR_CCOMPARE0(void); -extern void _TIE_xt_timer_WSR_CCOMPARE0(unsigned art); -extern void _TIE_xt_timer_XSR_CCOMPARE0(unsigned art /*inout*/); -extern unsigned _TIE_xt_timer_RSR_CCOMPARE1(void); -extern void _TIE_xt_timer_WSR_CCOMPARE1(unsigned art); -extern void _TIE_xt_timer_XSR_CCOMPARE1(unsigned art /*inout*/); -extern unsigned _TIE_xt_timer_RSR_CCOMPARE2(void); -extern void _TIE_xt_timer_WSR_CCOMPARE2(unsigned art); -extern void _TIE_xt_timer_XSR_CCOMPARE2(unsigned art /*inout*/); -#define XT_RSR_CCOUNT _TIE_xt_timer_RSR_CCOUNT -#define XT_WSR_CCOUNT _TIE_xt_timer_WSR_CCOUNT -#define XT_XSR_CCOUNT _TIE_xt_timer_XSR_CCOUNT -#define XT_RSR_CCOMPARE0 _TIE_xt_timer_RSR_CCOMPARE0 -#define XT_WSR_CCOMPARE0 _TIE_xt_timer_WSR_CCOMPARE0 -#define XT_XSR_CCOMPARE0 _TIE_xt_timer_XSR_CCOMPARE0 -#define XT_RSR_CCOMPARE1 _TIE_xt_timer_RSR_CCOMPARE1 -#define XT_WSR_CCOMPARE1 _TIE_xt_timer_WSR_CCOMPARE1 -#define XT_XSR_CCOMPARE1 _TIE_xt_timer_XSR_CCOMPARE1 -#define XT_RSR_CCOMPARE2 _TIE_xt_timer_RSR_CCOMPARE2 -#define XT_WSR_CCOMPARE2 _TIE_xt_timer_WSR_CCOMPARE2 -#define XT_XSR_CCOMPARE2 _TIE_xt_timer_XSR_CCOMPARE2 - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_timer_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/tie/xt_trace.h b/tools/sdk/include/esp32/xtensa/tie/xt_trace.h deleted file mode 100644 index 8d8d07fa48d..00000000000 --- a/tools/sdk/include/esp32/xtensa/tie/xt_trace.h +++ /dev/null @@ -1,44 +0,0 @@ -/* Definitions for the xt_trace TIE package */ - -/* - * Customer ID=11657; Build=0x5fe96; Copyright (c) 2004-2010 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -/* Do not modify. This is automatically generated.*/ - -#ifndef _XTENSA_xt_trace_HEADER -#define _XTENSA_xt_trace_HEADER - -#ifdef __XTENSA__ -#ifdef __XCC__ - -#include - -/* - * The following prototypes describe intrinsic functions - * corresponding to TIE instructions. Some TIE instructions - * may produce multiple results (designated as "out" operands - * in the iclass section) or may have operands used as both - * inputs and outputs (designated as "inout"). However, the C - * and C++ languages do not provide syntax that can express - * the in/out/inout constraints of TIE intrinsics. - * Nevertheless, the compiler understands these constraints - * and will check that the intrinsic functions are used - * correctly. To improve the readability of these prototypes, - * the "out" and "inout" parameters are marked accordingly - * with comments. - */ - -extern void _TIE_xt_trace_WSR_MMID(unsigned art); -#define XT_WSR_MMID _TIE_xt_trace_WSR_MMID - -#endif /* __XCC__ */ - -#endif /* __XTENSA__ */ - -#endif /* !_XTENSA_xt_trace_HEADER */ diff --git a/tools/sdk/include/esp32/xtensa/trax-api.h b/tools/sdk/include/esp32/xtensa/trax-api.h deleted file mode 100755 index aa1584359bc..00000000000 --- a/tools/sdk/include/esp32/xtensa/trax-api.h +++ /dev/null @@ -1,93 +0,0 @@ -/* Misc TRAX API function definitions. - - Copyright (c) 2007-2012 Tensilica 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. */ - -#ifndef _TRAX_API_H_ -#define _TRAX_API_H_ - -#include -#include -#include "tpack.h" -#include "traxreg.h" - -#include "xdm-regs.h" - -/* Flags for trax_stop(): */ -#define TRAX_STOP_HALT 0x0001 /* halt immediately, don't wait for post-stop-trigger capture */ -#define TRAX_STOP_QUIET 0x0002 /* don't display informative messages */ - - -/* - * Describes a TRAX channel (based on tpack). - */ -typedef struct { - tpack_channel chan; /* channel structure header */ - /* Per TRAX unit information: */ - int trax_version; /* TRAX_ID_VER(id), one of TRAX_VER_xxx macros */ - unsigned long trax_tram_size; /* size of trace RAM in bytes */ - int trax_erratum10; /* set if TRAX 1.0 erratum workarounds needed */ - int trax_erratum20; /* set if TRAX 2.0 erratum workaround needed (PR 22161)*/ - int trax_erratum20_size; - int trax_has_busy; /* has trace-busy feature */ - int trax_has_atb; /* has ATB feature */ - /*FIXME: add various features: coresight regs (don't call it that), APB, ATB, TRAM, ... */ -} trax_channel; - - -/* Prototypes: */ - -/* TRAX Protocol API: */ -extern int trax_read_register(tpack_channel *tchan, int regno, unsigned *value); -extern int trax_write_register(tpack_channel *tchan, int regno, unsigned value); -extern int trax_read_memory(tpack_channel *tchan, int address, int size, unsigned char *pdata); -extern int trax_fill_memory(tpack_channel *tchan, int address, int size, tpack_u32 pattern); -extern int trax_enumerate_devices(tpack_channel *tchan, int * buf, int * size); - -/* TRAX Network API: */ -extern unsigned long trax_ram_size(tpack_channel *traxchan); -extern unsigned long trax_ram_size_addr(tpack_channel *traxchan); -extern int trax_create_tracefile(tpack_channel *traxchan, int size, unsigned char * data, - char *filename, int hflags, const char *toolver); -extern int trax_memaccess_safe(tpack_channel *traxchan, const char *what); -extern int trax_start(tpack_channel *traxchan, int flags); -extern int trax_stop(tpack_channel *traxchan, int flags); -extern int trax_halt(tpack_channel *traxchan, int flags); -extern int trax_save(tpack_channel *traxchan, char *filename, int flags, const char *toolver, int erratum); - -/* TRAX Misc API (no network dependencies): */ -int trax_fixed_hw(unsigned * regs); -extern int trax_display_id(unsigned id, const char *prefix); -extern int trax_display_summary(unsigned id, - unsigned status, - unsigned control, - unsigned address, - unsigned delay, - unsigned trigger, - unsigned match, - unsigned startaddr, - unsigned endaddr, - const char *prefix); - -/* Other: */ - -#endif /* _TRAX_API_H_ */ - diff --git a/tools/sdk/include/esp32/xtensa/trax-core-config.h b/tools/sdk/include/esp32/xtensa/trax-core-config.h deleted file mode 100755 index 42a03334aa1..00000000000 --- a/tools/sdk/include/esp32/xtensa/trax-core-config.h +++ /dev/null @@ -1,144 +0,0 @@ -/* Definitions for Xtensa processor config info needed for TRAX. - - Copyright (c) 2005-2011 Tensilica 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. */ - -#ifndef TRAX_CORE_CONFIG_H -#define TRAX_CORE_CONFIG_H - -#include "xtensa-params.h" - -/* - * Vector Enumerations. - */ - -/* These must match the LX2.0 and later traceport spec: */ -#define VEC_NO_VECTOR 0 -#define VEC_FIRST VEC_RESET /* first valid vector */ -#define VEC_RESET 1 -#define VEC_DEBUG 2 -#define VEC_NMI 3 -#define VEC_USER 4 -#define VEC_KERNEL 5 -#define VEC_DOUBLE 6 -#define VEC_MEMERR 7 -#define VEC_RESERVED8 8 -#define VEC_RESERVED9 9 -#define VEC_WINO4 10 -#define VEC_WINU4 11 -#define VEC_WINO8 12 -#define VEC_WINU8 13 -#define VEC_WINO12 14 -#define VEC_WINU12 15 -#define VEC_INTLEVEL2 16 -#define VEC_INTLEVEL3 17 -#define VEC_INTLEVEL4 18 -#define VEC_INTLEVEL5 19 -#define VEC_INTLEVEL6 20 -/* These are internal, i.e. don't appear like this on traceport: */ -#define VEC_DEBUG_OCD 21 -#define VEC_UNKNOWN 22 -/* Enumerations 23 through 31 are also reserved, but putting */ -/* placeholders here seems wasteful and unnecessary. */ -#define VEC_COUNT 23 - -/* Other branch (change-of-PC-flow) type encodings; - * if PC changes due to an exception or interrupt vector, - * one of the VEC_* values above is used, otherwise - * (or if it's unknown whether it's due to an exception/interrupt) - * one of the following is used: */ - -#define BRANCH_IS_VEC(n) ((n) < VEC_COUNT) /* is known to be except/interrupt? */ -#define BRANCH_OR_VEC 24 /* unknown type of branch (branch/exception/interrupt/etc) */ -#define BRANCH_UNKNOWN 25 /* unknown type of branch (anything but except/interrupt) */ -#define BRANCH_UNKNOWN_ERR 26 /* like BRANCH_UNKNOWN with known error (non-branch instr) */ -#define BRANCH_LOOPBACK 28 /* zero-overhead loopback (from LEND to LBEG) */ -#define BRANCH_CONDTAKEN 29 /* conditional branch taken (or LOOP{NEZ,GTZ} loop skip) */ -#define BRANCH_JUMP 30 /* jump (unconditional branch, i.e. J or JX) */ -#define BRANCH_IS_CALL(n) (((n) & ~3) == 32) /* is a function call? */ -#define BRANCH_CALL0 32 /* non-windowed function call (CALL0, CALLX0) */ -#define BRANCH_CALL4 33 /* windowed function call (CALL4, CALLX4) */ -#define BRANCH_CALL8 34 /* windowed function call (CALL8, CALLX8) */ -#define BRANCH_CALL12 35 /* windowed function call (CALL12, CALLX12) */ -#define BRANCH_IS_RETURN(n) ((n) >= 36) /* is any kind of return? */ -#define BRANCH_IS_CALLRETURN(n) (((n) & ~1) == 36) /* is a function return? */ -#define BRANCH_RET 36 /* non-windowed function return (RET or RET.N) */ -#define BRANCH_RETW 37 /* windowed function return (RETW or RETW.N) */ -#define BRANCH_IS_EIRETURN(n) ((n) >= 38) /* is an except/inter. return? */ -#define BRANCH_RFE 38 /* RFE or RFUE */ -#define BRANCH_RFDE 39 /* RFDE */ -#define BRANCH_RFWO 40 /* RFWO */ -#define BRANCH_RFWU 41 /* RFWU */ -#define BRANCH_RFI_2 42 /* RFI 2 */ -#define BRANCH_RFI_3 43 /* RFI 3 */ -#define BRANCH_RFI_4 44 /* RFI 4 */ -#define BRANCH_RFI_5 45 /* RFI 5 */ -#define BRANCH_RFI_6 46 /* RFI 6 */ -#define BRANCH_RFI_NMI 47 /* RFI NMILEVEL */ -#define BRANCH_RFI_DEBUG 48 /* RFI DEBUGLEVEL */ -#define BRANCH_RFME 49 /* RFME */ -#define BRANCH_COUNT 50 /* (number of defined BRANCH_xxx values) */ - - - -typedef struct { - unsigned vaddr; - unsigned vaddr2; /* for static vectors only (reloc vectors option) */ - int is_configured; -} trax_vector_t; - - -/* - * This structure describes those portion of a Tensilica processor's - * configuration that are useful for trace. - */ -typedef struct { - char ** isa_dlls; - char * core_name; /* (XPG core name, not necessarily same as XTENSA_CORE) */ - int big_endian; /* 0 = little-endian, 1 = big-endian */ - int has_loops; /* 1 = zero overhead loops configured */ - int has_autorefill; /* 1 = TLB autorefill (MMU) configured */ - unsigned max_instr_size; /* in bytes (eg. 3, 4, 8, ...) */ - unsigned int_level_max; /* number of interrupt levels configured (without NMI) */ - int debug_level; /* debug intlevel, 0 if debug not configured */ - int nmi_level; /* NMI intlevel, 0 if NMI not configured */ - unsigned targethw_min; /* min. targeted hardware version (XTENSA_HWVERSION_) */ - unsigned targethw_max; /* max. targeted hardware version (XTENSA_HWVERSION_) */ - int reloc_vectors; /* 0 = fixed vectors, 1 = relocatable vectors */ - int statvec_select; /* 0 = stat vec base 0, 1 = stat vec base 1 (SW default) */ - int vecbase_align; /* number of bits to align VECBASE (32 - bits in VECBASE) */ - unsigned statvec_base0; /* static vector base 0 */ - unsigned statvec_base1; /* static vector base 1 */ - unsigned vecbase_reset; /* reset value of VECBASE */ - trax_vector_t vectors[VEC_COUNT]; /* all vectors... */ -} trax_core_config_t; - - -/* Globals: */ -//extern const char * const trax_vector_short_names[/*VEC_COUNT*/]; // nobody uses this one -extern const char * const trax_vector_names[/*VEC_COUNT*/]; - -/* Prototypes: */ -extern int trax_read_params (trax_core_config_t *c, xtensa_params p); -extern int trax_vector_from_address(trax_core_config_t *config, unsigned long vaddr, unsigned long *vecbases); - -#endif /* TRAX_CORE_CONFIG_H */ - diff --git a/tools/sdk/include/esp32/xtensa/trax-proto.h b/tools/sdk/include/esp32/xtensa/trax-proto.h deleted file mode 100755 index 41d5c9fd769..00000000000 --- a/tools/sdk/include/esp32/xtensa/trax-proto.h +++ /dev/null @@ -1,91 +0,0 @@ -/* This file contains functions that are hidden from the user. These are - * protocol specific functions used to read and write TRAX registers - * and the trace memory - */ - -/* - * Copyright (c) 2012-2013 Tensilica 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. - */ -#ifndef _TRAX_PROTO_H -#define _TRAX_PROTO_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Function to read register - * - * regno : The register number to be read (not ERI addressed) - * data : Location where the read value is kept - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_read_register_eri (int regno, unsigned *data); - -/* Function to write a value into a register - * - * regno : The register number to be written (not ERI addressed) - * value : The value to be written at that register location - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_write_register_eri (int regno, unsigned value); - -/* Function to read memory - * - * address : Address of the TraceRAM memory, each location has a word - * len : Amount of memory in bytes, to be read - * data : buffer in which the read memory is stored - * final_address: Next address to be read in the following call to this - * function (trace save mechanism) - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_read_memory_eri (unsigned address, int len, int *data, - unsigned *final_address); - -/* Function to write a value to the memory address - * - * address : Address of the TraceRAM memory - * value : The value to be written inside that location - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_write_memory_eri (int address, unsigned value); - -/* Function to write to a subfield of the register. - * Called by set and show parameter functions. - * - * regno : Register number - * regmask : Mask in order to toggle appropriate bits - * value : Value to be written in the masked location - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_write_register_field_eri (int regno, unsigned regmask, - unsigned value); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/esp32/xtensa/trax-util.h b/tools/sdk/include/esp32/xtensa/trax-util.h deleted file mode 100755 index 123ac366dfb..00000000000 --- a/tools/sdk/include/esp32/xtensa/trax-util.h +++ /dev/null @@ -1,63 +0,0 @@ -/* This file contains utility functions that can be used for polling TRAX - * or executing higher level save functionality - * It assumes that print subroutines and file I/O routines are available - * on the system - */ - -/* - * Copyright (c) 2012-2013 Tensilica 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. - */ - -#ifndef _TRAX_UTIL_H -#define _TRAX_UTIL_H - - -#ifdef __cplusplus -extern "C" { -#endif - -/* User can use this function if he wants to generate a tracefile output. - * Internally it calls trax_get_trace in a loop until it realizes that - * the entire trace has been read. - * - * context : pointer to structure which contains information about the - * current TRAX session - * filename : user specified output trace file name. If the file does not - * exist, it would create the new file, else would append to it - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_save (trax_context *context, char *filename); - -/* Displays a brief machine readable status. - * - * context : pointer to structure which contains information about the - * current TRAX session - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_poll (trax_context *context); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/esp32/xtensa/trax.h b/tools/sdk/include/esp32/xtensa/trax.h deleted file mode 100755 index 47049c51d21..00000000000 --- a/tools/sdk/include/esp32/xtensa/trax.h +++ /dev/null @@ -1,409 +0,0 @@ -/* Header file for TRAX control Library */ - -/* - * Copyright (c) 2012-2013 Tensilica 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. - */ - -#ifndef _TRAX_H -#define _TRAX_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define TRAX_STOP_HALT 0x0001 -#define TRAX_STOP_QUIET 0x0002 - -/* Flag values to indicate if the user wanted to reverse the pcstop - * parameters */ -#define TRAX_PCSTOP_REVERSE 0x0001 -#define TRAX_PCSTOP_NO_REVERSE 0x0000 - -/* Indicating whether postsize should be in terms of bytes, instructions - * or percentage of trace size captured */ -#define TRAX_POSTSIZE_BYTES 0x0000 -#define TRAX_POSTSIZE_INSTR 0x0001 -#define TRAX_POSTSIZE_PERCENT 0x0002 - -/* Size of the header inside the trace file */ -#define TRAX_HEADER_SIZE 256 - -/* Minimum size between start and end addresses */ -#define TRAX_MIN_TRACEMEM 64 - -/* For basic debugging */ -#define DEBUG 0 - -#include - -#define ffs(i) __builtin_ffs(i) - -/* Data structures */ - -/* Represents the context of the TRAX unit and the current TRAX session. - * To be used by set and show function calls to set and show appropriate - * parameters of appropriate TRAX unit. - */ - -typedef struct { - int trax_version; /* TRAX PC version information */ - unsigned long trax_tram_size; /* If trace RAM is present,size of it */ - int hflags; /* Flags that can be used to debug, - print info, etc. */ - int address_read_last; /* During saving of the trace, this - indicates the address from which - the current trace reading must - resume */ - unsigned long bytes_read; /* bytes read uptil now */ - unsigned long total_memlen; /* Total bytes to be read based on the - trace collected in the trace RAM */ - bool get_trace_started; /* indicates that the first chunk of - bytes (which include the header) has - been read */ -} trax_context; - - -/* -----------------------TRAX Initialization ------------------------------*/ - -/* Initializing the trax context. Reads registers and sets values for version, - * trace RAM size, total memory length, etc. Most of the other values are - * initialized to their default case. - * - * context : pointer to structure which contains information about the - * current TRAX session - * - * returns : 0 if successful, -1 if unsuccessful, -2 if ram_size if - * incorrect - */ -int trax_context_init_eri (trax_context *context); - -/* -----------------Starting/Stopping TRAX session -------------------------*/ - -/* Start tracing with current parameter setting. If tracing is already in - * progress, an error is reported. Otherwise, tracing starts and any unsaved - * contents of the TraceRAM is discarded - * - * context : pointer to structure which contains information about the - * current TRAX session - * returns : 0 if successful, 1 if trace is already active, - * -1 if unsuccessful - */ -int trax_start (trax_context *context); - -/* This command initiates a stop trigger or halts a trace session based of the - * value of the flag parameter passed. In case stop trigger is initiated, any - * selected post-stop-trigger capture proceeds normally. - * If trace capture was not in progress, or a stop was already triggered, the - * return value indicates appropriately. - * - * context : pointer to structure which contains information about the - * current TRAX session - * flags : To differentiate between stopping trace without any - * post-size-trigger capture (trax_halt) or with that. - * A zero value would stop the trace based on trigger and a - * value of one would halt it - * - * returns : 0 if successful, 1 if already stopped, -1 if unsuccessful - */ -int trax_stop_halt (trax_context *context, int flags); - -/* Resets the TRAX parameters to their default values which would internally - * involve resetting the TRAX registers. To invoke another trace session or - * reset the current tracing mechanism, this function needs to be called as - * it resets parameters of the context that deal with tracing information - * - * context : pointer to structure which contains information about the - * current TRAX session - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_reset (trax_context *context); - -/* ---------------Set/Get several TRAX parameters --------------------------*/ - -/* Sets the start address and end address (word aligned) of the trace in the - * TraceRAM. Care must be taken to ensure that the difference between the - * start and the end addresses is atleast TRAX_MIN_TRACEMEM bytes. If not, - * the values are reset to default, which is 0 for startaddr and - * traceRAM_words -1 for endaddr - * - * context : pointer to structure which contains information about the - * current TRAX session - * startaddr : value to which the start address must be set. Can be - * any value between 0 - (traceRAM_words - 1) - * endaddr : value to which the end address must be set. Can be any value - * between 0 - (traceRAM_words - 1) - * - * returns : 0 if successful, -1 if unsuccessful, -2 if the difference - * between the start and end addresses is less than - * TRAX_MIN_TRACEMEM bytes or if they are passed incorrect - * values, -3 if memory shared option is not configured, in - * which case, start and end addresses are set to default - * values instead of those passed by the user - */ -int trax_set_ram_boundaries (trax_context *context, unsigned startaddr, - unsigned endaddr); - -/* Shows the start address and end address(word aligned) of the trace in the - * TraceRAM. If incorrect, the startaddress and the endaddress values are - * set to default, i.e. 0 for startaddr and traceRAM_words - 1 for endaddr - * - * context : pointer to structure which contains information about the - * current TRAX session - * startaddr : pointer to value which will contain the start address - * endaddr : pointer to value which will contain the end address - * - * returns : 0 if successful, -1 if unsuccessful - * - */ -int trax_get_ram_boundaries (trax_context *context, unsigned *startaddr, - unsigned *endaddr); - -/* Selects stop trigger via cross-trigger input - * - * context : pointer to structure which contains information about the - * current TRAX session - * value : 0 = off (reset value), 1 = on - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_set_ctistop (trax_context *context, unsigned value); - -/* Shows if stop-trigger via cross-trigger input is off or on - * - * context : pointer to structure which contains information about the - * current TRAX session - * returns : 0 if off, 1 if on, -1 if unsuccessful - */ -int trax_get_ctistop (trax_context *context); - -/* Selects stop trigger via processor-trigger input - * - * context : pointer to structure which contains information about the - * current TRAX session - * value : 0 = off (reset value), 1 = on - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_set_ptistop (trax_context *context, unsigned value); - -/* Shows if stop trigger visa processor-trigger input is off or on - * - * context : pointer to structure which contains information about the - * current TRAX session - * returns : 0 if off, 1 if on, -1 if unsuccessful - */ -int trax_get_ptistop (trax_context *context); - -/* Reports cross trigger output state - * - * context : pointer to structure which contains information about the - * current TRAX session - * returns : 0 if CTO bit is reset, 1 if CTO bit is set - */ -int trax_get_cto (trax_context *context); - -/* Reports processor trigger output state - * - * context : pointer to structure which contains information about the - * current TRAX session - * returns : 0 if PTO bit is reset, 1 if PTO bit is set - */ -int trax_get_pto (trax_context *context); - -/* Selects condition that asserts cross trigger output - * - * context : pointer to structure which contains information about the - * current TRAX session - * option : 0 = off(reset value)/1 = ontrig/2 = onhalt - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_set_ctowhen (trax_context *context, int option); - -/* Shows condition that asserted cross trigger output. It can be - * any of: ontrig or onhalt or even off - * - * context : pointer to structure which contains information about the - * current TRAX session - * - * returns : 0 if off, 1 if ontrig, 2 if onhalt, -1 if unsuccessful - */ -int trax_get_ctowhen (trax_context *context); - -/* Selects condition that asserts processor trigger output - * - * context : pointer to structure which contains information about the - * current TRAX session - * option : 0 = off(reset value)/1 = ontrig/2 = onhalt - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_set_ptowhen (trax_context *context, int option); - - -/* Shows condition that asserted processor trigger output. It can be - * any of: ontrig or onhalt or even off - * - * context : pointer to structure which contains information about the - * current TRAX session - * returns : 0 if off, 1 if ontrig, 2 if onhalt, -1 if unsuccessful - */ -int trax_get_ptowhen (trax_context *context); - -/* Selects the trace synchronization message period. - * If ATEN enabled, we cannot allow syncper to be off, set it to reset value. - * Also, if no trace RAM, and ATEN enabled, set syncper to be reset value - * i.e. 256. A value of 1 i.e. on indicates that internally the message - * frequency is set to an optimal value. This option should be preferred - * if the user is not sure what message frequency option to set for the - * trace session. - * - * context : pointer to structure which contains information about the - * current TRAX session - * option : 0 = off, 1 = on, -1 = auto, 8, 16, 32, 64, 128, - * 256 (reset value) - * - * returns : 0 if successful, -1 if unsuccessful, -2 if incorrect - * arguments - */ -int trax_set_syncper (trax_context *context, int option); - -/* Shows trace synchronization message period. Can be one of: - * off, on, auto, 8, 16, 32, 64, 128, 256 (reset value) - * - * context : pointer to structure which contains information about the - * current TRAX session - * returns : value of sync period, 0 if off, -1 if unsuccessful - */ -int trax_get_syncper (trax_context *context); - -/* Selects stop trigger via PC match. Specifies the address or - * address range to match against program counter. Trace stops when the - * processor executes an instruction matching the specified address - * or range. - * - * context : pointer to structure which contains information about the - * current TRAX session - * index : indicates the number of stop trigger (currently there is - * only one i.e. index = 0) - * startaddress : start range of the address at which the stop trigger - * should be activated - * enaddress : end range of the address at which the stop trigger should - * be activated - * flags : If non-zero, this inverts the range. i.e. trace stops - * when the processor executes an instruction that does not - * match the specified address or range - * - * returns : 0 if successful, -1 if unsuccessful, -2 if incorrect - * arguments (unaligned) - * - * Note : For the current version of TRAX library, the endaddress and - * startaddress can differ by at most 31 bytes and the total - * range i.e. (endaddress - startaddress + 1) has to be a power - * of two - */ -int trax_set_pcstop (trax_context *context, int index, unsigned long startaddress, - unsigned long endaddress, int flags); - -/* Shows the stop trigger via PC match - * - * context : pointer to structure which contains information about the - * current TRAX session - * index : container of information about the number of stop triggers - * startaddress : container of start range of stop trigger - * endaddress : container of end range of stop trigger - * flags : container of information whcih indicates whether the - * pc stop range is inverted or not. - * - * returns : 0 if successful, -1 if unsuccessful - */ -int trax_get_pcstop (trax_context *context, int *index, - unsigned long *startaddress, - unsigned long *endaddress, int *flags); - -/* This function is used to set the amount of trace to be captured past - * the stop trigger. - * - * context : pointer to structure which contains information about the - * current TRAX session - * count_unit : contains the count of units (instructions or bytes) to be - * captured post trigger. If 0, it implies that this is off - * unit : unit of measuring the count. 0 is bytes, 1 is instructions - * 2 is percentage of trace - * - * returns : 0 if successful, -1 if unsuccessful, -2 if incorrect - * arguments - * - */ -int trax_set_postsize (trax_context *context, int count_unit, int unit); - -/* This function shows the amount of TraceRAM in terms of the number of - * instructions or bytes, captured post the stop trigger - * - * context : pointer to structure which contains information about the - * current TRAX session - * count_unit : will contain the count of units(instructions or bytes) post - * trigger - * unit : will contain information about the events that are counted - * 0 implies that the traceRAM words consumed are counted and - * 1 implies that the target processor instructions executed and - * excpetions/interrupts taken are counted - * - * returns : 0 if postsize was got successfully, -1 if unsuccessful - */ -int trax_get_postsize (trax_context *context, int *count_unit, int *unit); - -/* -------------------------- TRAX save routines ---------------------------*/ - -/* This function should be called by the user to return a chunk of - * bytes in buf. It can be a lower layer function of save, or can be - * called by the user explicitly. If bytes_actually_read contains a 0 - * after a call to this function has been made, it implies that the entire - * trace has been read successfully. - * - * context : pointer to structure which contains information about - * the current TRAX session - * buf : Buffer that is allocated by the user, all the trace - * data read would be put in this buffer, which can then - * be used to generate a tracefile. - * The first TRAX_HEADER_SIZE of the buffer will always - * contain the header information. - * bytes_to_be_read : Indicates the bytes the user wants to read. The first - * invocation would need this parameter to be - * TRAX_HEADER_SIZE at least. - * - * returns : bytes actually read during the call to this function. - * 0 implies that all the bytes in the trace have been - * read, -1 if unsuccessful read/write of - * registers or memory, -2 if trace was active while - * this function was called, -3 if user enters - * bytes_to_be_read < TRAX_HEADER_SIZE in the first - * pass - */ -int trax_get_trace (trax_context *context, void *buf, - int bytes_to_be_read); -#ifdef __cplusplus -} -#endif - -#endif /* _TRAX_H */ diff --git a/tools/sdk/include/esp32/xtensa/traxfile.h b/tools/sdk/include/esp32/xtensa/traxfile.h deleted file mode 100755 index 4afc926a507..00000000000 --- a/tools/sdk/include/esp32/xtensa/traxfile.h +++ /dev/null @@ -1,62 +0,0 @@ -/* TRAX file header definition. - - Copyright (c) 2007-2012 Tensilica 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. */ - - -#define TRAX_FHEAD_MAGIC "TRAXdmp" -#define TRAX_FHEAD_VERSION 1 - -/* Header flags: */ -#define TRAX_FHEADF_OCD_ENABLED 0x00000001 /* set if OCD was enabled while capturing trace */ -#define TRAX_FHEADF_TESTDUMP 0x00000002 /* set if is a test file - (from 'memsave' instead of 'save') */ -#define TRAX_FHEADF_OCD_ENABLED_WHILE_EXIT 0x00000004 /* set if OCD was enabled while capturing trace and - we were exiting the OCD mode */ - -/* Header at the start of a TRAX dump file. */ -typedef struct { - char magic[8]; /* 00: "TRAXdmp\0" (TRAX_FHEAD_MAGIC) */ - char endianness; /* 08: 0=little-endian, 1=big-endian */ - char version; /* 09: TRAX_FHEAD_VERSION */ - char reserved0[2]; /* 0A: ... */ - unsigned filesize; /* 0C: size of the trace file, including this header */ - unsigned trace_ofs; /* 10: start of trace output, byte offset from start of header */ - unsigned trace_size; /* 14: size of trace output in bytes */ - unsigned dumptime; /* 18: date/time of capture save (secs since 1970-01-01), 0 if unknown */ - unsigned flags; /* 1C: misc flags (TRAX_FHEAD_F_xxx) */ - char username[16]; /* 20: user doing the capture/save (up to 15 chars) */ - char toolver[24]; /* 30: tool + version used for capture/save (up to 23 chars) */ - char reserved2[40]; /* 48: (reserved - could be hostname used for dump (up to 39 chars)) */ - unsigned configid[2]; /* 70: processor ConfigID values, 0 if unknown */ - unsigned ts_freq; /* 78: timestamp frequency, 0 if not specified */ - unsigned reserved3; /* 7C: (reserved) */ - unsigned id; /* 80: TRAX registers at time of save (0 if not read) */ - unsigned control; - unsigned status; - unsigned reserved4; /* Data register (should not be read) */ - unsigned address; - unsigned trigger; - unsigned match; - unsigned delay; - unsigned trax_regs[24]; /*100: (total size) -- dummy allocation (FIXME) */ -} trax_file_header; - diff --git a/tools/sdk/include/esp32/xtensa/traxreg.h b/tools/sdk/include/esp32/xtensa/traxreg.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/uart-16550-board.h b/tools/sdk/include/esp32/xtensa/uart-16550-board.h deleted file mode 100755 index 8ef8af16374..00000000000 --- a/tools/sdk/include/esp32/xtensa/uart-16550-board.h +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* -Copyright (c) 2006-2013 by Tensilica Inc. ALL RIGHTS RESERVED. -These coded instructions, statements, and computer programs are the -copyrighted works and confidential proprietary information of Tensilica Inc. -They may not be modified, copied, reproduced, distributed, or disclosed to -third parties in any manner, medium, or form, in whole or in part, without -the prior written consent of Tensilica Inc. --------------------------------------------------------------------------------- - -uart-16550-board.h Board-specific UART info on these boards: - Avnet AV60 (XT-AV60) - Avnet AV110 (XT-AV110) - Avnet AV200 (XT-AV200) - Xilinx ML605 (XT-ML605) - Xilinx KC705 (XT-KC705) - -Interface between board-independent driver and board-specific header. - -This is used by a board-independent 16550 UART driver to obtain board-specific -information about 1 instance of the 16550 UART on the board, such as the device -register base address and spacing (a function of how the address lines are -connected on the board) and the frequency of the UART clock. The driver does -not refer directly to the board-specific header, which therefore is not -constrained to use macro names consistent with other boards. - -!! Must not contain any board-specific macro names (only UART specific). !! - -Included at compile-time via an include path specific to the board. - -These boards contain a single 16550 UART implemented on the FPGA. -Their clock frequency comes from the board's core clock (not its own crystal) -which depends on the core config so is not a constant. Obtained via the BSP. - -*******************************************************************************/ - -#ifndef _UART_16550_BOARD_H -#define _UART_16550_BOARD_H - -#include /* BSP API */ -#include /* Board info */ - - -/* Base address of UART's registers. */ -#ifdef UART16550_VADDR -#define UART_16550_REGBASE UART16550_VADDR -#endif - -/* -The UART's registers are connected at word addresses on these boards. -Each byte-wide register appears as the least-significant-byte (LSB) of the -word regardless of the endianness of the processor. -*/ -#define UART_16550_REGSPACING 4 -typedef unsigned uart16550_reg_t; - -/* UART Clock Frequency in Hz */ -#define UART_16550_XTAL_FREQ xtbsp_clock_freq_hz() - -/* UART Interrupt Number */ -#ifdef UART16550_INTNUM -#define UART_16550_INTNUM UART16550_INTNUM -#endif - - -/* Include generic information shared by all boards that use this device. */ -#include - -#endif /* _UART_16550_BOARD_H */ - diff --git a/tools/sdk/include/esp32/xtensa/uart-16550.h b/tools/sdk/include/esp32/xtensa/uart-16550.h deleted file mode 100755 index c551c64c137..00000000000 --- a/tools/sdk/include/esp32/xtensa/uart-16550.h +++ /dev/null @@ -1,152 +0,0 @@ -/******************************************************************************* - - Copyright (c) 2006-2007 Tensilica 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. - --------------------------------------------------------------------------------- - -uart-16550.h Generic definitions for National Semiconductor 16550 UART - -This is used by board-support-packages with one or more 16550 compatible UARTs. -A BSP provides a base address for each instance of a 16550 UART on the board. - -Note that a 16552 DUART (Dual UART) is simply two instances of a 16550 UART. - -*******************************************************************************/ - -#ifndef _UART_16550_H_ -#define _UART_16550_H_ - -/* C interface to UART registers. */ -struct uart_dev_s { - union { - uart16550_reg_t rxb; /* DLAB=0: receive buffer, read-only */ - uart16550_reg_t txb; /* DLAB=0: transmit buffer, write-only */ - uart16550_reg_t dll; /* DLAB=1: divisor, LS byte latch */ - } w0; - union { - uart16550_reg_t ier; /* DLAB=0: interrupt-enable register */ - uart16550_reg_t dlm; /* DLAB=1: divisor, MS byte latch */ - } w1; - - union { - uart16550_reg_t isr; /* DLAB=0: interrupt status register, read-only */ - uart16550_reg_t fcr; /* DLAB=0: FIFO control register, write-only */ - uart16550_reg_t afr; /* DLAB=1: alternate function register */ - } w2; - - uart16550_reg_t lcr; /* line control-register, write-only */ - uart16550_reg_t mcr; /* modem control-regsiter, write-only */ - uart16550_reg_t lsr; /* line status register, read-only */ - uart16550_reg_t msr; /* modem status register, read-only */ - uart16550_reg_t scr; /* scratch regsiter, read/write */ -}; - - -#define _RXB(u) ((u)->w0.rxb) -#define _TXB(u) ((u)->w0.txb) -#define _DLL(u) ((u)->w0.dll) -#define _IER(u) ((u)->w1.ier) -#define _DLM(u) ((u)->w1.dlm) -#define _ISR(u) ((u)->w2.isr) -#define _FCR(u) ((u)->w2.fcr) -#define _AFR(u) ((u)->w2.afr) -#define _LCR(u) ((u)->lcr) -#define _MCR(u) ((u)->mcr) -#define _LSR(u) ((u)->lsr) -#define _MSR(u) ((u)->msr) -#define _SCR(u) ((u)->scr) - -typedef volatile struct uart_dev_s uart_dev_t; - -/* IER bits */ -#define RCVR_DATA_REG_INTENABLE 0x01 -#define XMIT_HOLD_REG_INTENABLE 0x02 -#define RCVR_STATUS_INTENABLE 0x04 -#define MODEM_STATUS_INTENABLE 0x08 - -/* FCR bits */ -#define _FIFO_ENABLE 0x01 -#define RCVR_FIFO_RESET 0x02 -#define XMIT_FIFO_RESET 0x04 -#define DMA_MODE_SELECT 0x08 -#define RCVR_TRIGGER_LSB 0x40 -#define RCVR_TRIGGER_MSB 0x80 - -/* AFR bits */ -#define AFR_CONC_WRITE 0x01 -#define AFR_BAUDOUT_SEL 0x02 -#define AFR_RXRDY_SEL 0x04 - -/* ISR bits */ -#define INT_STATUS(r) ((r)&1) -#define INT_PRIORITY(r) (((r)>>1)&0x7) - -/* LCR bits */ -#define WORD_LENGTH(n) (((n)-5)&0x3) -#define STOP_BIT_ENABLE 0x04 -#define PARITY_ENABLE 0x08 -#define EVEN_PARITY 0x10 -#define FORCE_PARITY 0x20 -#define XMIT_BREAK 0x40 -#define DLAB_ENABLE 0x80 - -/* MCR bits */ -#define _DTR 0x01 -#define _RTS 0x02 -#define _OP1 0x04 -#define _OP2 0x08 -#define LOOP_BACK 0x10 - -/* LSR Bits */ -#define RCVR_DATA_READY 0x01 -#define OVERRUN_ERROR 0x02 -#define PARITY_ERROR 0x04 -#define FRAMING_ERROR 0x08 -#define BREAK_INTERRUPT 0x10 -#define XMIT_HOLD_EMPTY 0x20 -#define XMIT_EMPTY 0x40 -#define FIFO_ERROR 0x80 -#define RCVR_READY(u) (_LSR(u)&RCVR_DATA_READY) -#define XMIT_READY(u) (_LSR(u)&XMIT_HOLD_EMPTY) - -/* MSR bits */ -#define _RDR 0x01 -#define DELTA_DSR 0x02 -#define DELTA_RI 0x04 -#define DELTA_CD 0x08 -#define _CTS 0x10 -#define _DSR 0x20 -#define _RI 0x40 -#define _CD 0x80 - - -/* Compute 16-bit divisor for baudrate generator, with rounding: */ -#define UART_DIVISOR(clock,baud) (((clock)/16 + (baud)/2)/(baud)) - -/* Prototypes of driver functions */ -extern void uart16550_init( uart_dev_t *u, unsigned baud, unsigned ndata, - unsigned parity, unsigned nstop ); -extern void uart16550_out( uart_dev_t *u, char c ); -extern char uart16550_in( uart_dev_t *u ); -extern unsigned uart16550_measure_sys_clk( uart_dev_t *u ); - -#endif /* _UART_16550_H_ */ diff --git a/tools/sdk/include/esp32/xtensa/udma.h b/tools/sdk/include/esp32/xtensa/udma.h deleted file mode 100755 index a5feb777018..00000000000 --- a/tools/sdk/include/esp32/xtensa/udma.h +++ /dev/null @@ -1,276 +0,0 @@ -/* Customer ID=11656; Build=0x5f626; Copyright (c) 2005-2014 by Cadence Design Systems, Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of - * Cadence Design Systems, Inc. They may not be modified, copied, reproduced, - * distributed, or disclosed to third parties in any manner, medium, or form, - * in whole or in part, without the prior written consent of Cadence Design - * Systems Inc. - */ -#ifndef __UDMA_H__ -#define __UDMA_H__ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Size of the uDMA descriptor */ -#define UDMA_DESC_STRUCT_SIZE 32 - -/* Request attribute is a bit vector passed to the udma functions - udma_copy, - * udma_2d_copy, udma_add_descs. - * Bit 0 : 1 - trigger an interrupt when done, else do nothing - * Bit 1 : 0 - retry the failed request; abort after programmer specified - * number of retries. Defaults to abort with no retries. - * 1 - abort the failed request (after retries) and all pending requests - */ -#define UDMA_DONE_INTERRUPT 0x1 -#define UDMA_ERROR_ABORT 0x0 -#define UDMA_ERROR_ABORT_ALL 0x2 - -/* Enum representing various udma error conditions, udma status, and - * return values - */ -typedef enum { - UDMA_OK = 0, - UDMA_ERROR_QUEUE_FULL = 1, - UDMA_ERROR_BAD_DESC = 2, - UDMA_ERROR_DRAM_CROSSING = 3, - UDMA_ERROR_PIF_ADDR_BUS = 4, - UDMA_ERROR_PIF_DATA_BUS = 5, - UDMA_REQ_PENDING = 6, - UDMA_REQ_DONE = 7, - UDMA_ERROR_BAD_REQUEST = 8, - UDMA_ERROR_INVALID_ARG = 11, - UDMA_ERROR_INIT = 12, - UDMA_ERROR_INTERNAL = -1 -} udma_status_t; - -#ifndef __UDMA_INTERNAL_H__ -/* Opaque structure describing a uDMA descriptor */ -struct udma_desc_struct { - char _[UDMA_DESC_STRUCT_SIZE]; -} __attribute__ ((aligned (UDMA_DESC_STRUCT_SIZE))); -#endif - -typedef struct udma_desc_struct udma_desc_t; - -/* Initialize the udma control structure, the uDMA registers with - * the descriptor queue addresses, and the uDMA sync and error interrupt - * handler. This function needs to be invoked prior to using the uDMA. - * - * xmp_udma_sync_intr : Processor interrupt number to flag udma done - * xmp_udma_error_intr : Processor interrupt number to flag udma error - * - * Returns UDMA_ERROR_INIT if there was an error during initialization else - * returns UDMA_OK. - */ -extern udma_status_t -udma_init(uint32_t xmp_udma_sync_intr, uint32_t xmp_udma_error_intr); - -/* Performs a copy of a linear block of size bytes from the src - * to the dest address. If the call returns UDMA_OK, status is set to - * UDMA_REQ_PENDING or UDMA_REQ_DONE. If there is a dma error, the error code, - * which could be one of UDMA_ERROR_BAD_DESC, UDMA_ERROR_DRAM_CROSSING, - * UDMA_ERROR_PIF_ADDR_BUS, UDMA_ERROR_PIF_DATA_BUS is returned in the status. - * Status is set to UDMA_REQ_DONE if the dma completes normally. - * On completion, the callback function is invoked with the callback_data - * and status as parameters. Note, the callback is always invoked even if - * there is a dma error. - * - * src : src address of the copy - * dest : dest address of the copy - * size : number of bytes to copy - * callback_data : optional data to be passed to callback_func - * callback_func : optional callback after copy is done - * request_attr : attribute defining how to process this request - * (see description of the request attribute in top of udma.h) - * status : track status of the copy; this gets also passed - * as the second argument to the callback_func - * - * Returns UDMA_ERROR_QUEUE_FULL if no more requests can be added, else - * returns UDMA_OK. - */ -extern udma_status_t -udma_copy(void *dest, - void *src, - size_t size, - void *callback_data, - void (*callback_func)(void *, udma_status_t *status), - uint32_t request_attr, - udma_status_t *status); - -/* Performs a copy of a 2D block of data from the src to the dest - * address. If the call returns UDMA_OK, status is set to UDMA_REQ_PENDING or - * UDMA_REQ_DONE. If there is a dma error, the error code, - * which could be one of UDMA_ERROR_BAD_DESC, UDMA_ERROR_DRAM_CROSSING, - * UDMA_ERROR_PIF_ADDR_BUS, UDMA_ERROR_PIF_DATA_BUS is returned in the status. - * Status is set to UDMA_REQ_DONE if the dma completes normally. - * On completion, the callback function is invoked with the callback_data - * and status as parameters. Note, the callback is always invoked even if - * there is a dma error. - * - * src : src address of the copy - * dest : dest address of the copy - * row_size : number of bytes per row to copy - * num_rows : number of rows to copy - * src_pitch : src pitch - * dest_pitch : dest pitch - * callback_data : optional data to be passed to callback_func - * callback_func : optional callback after copy is done - * request_attr : attribute defining how to process this request - * (see description of the request attribute in top of udma.h) - * status : track status of the copy; this gets also passed - * as the second argument to the callback_func - * - * Returns UDMA_ERROR_QUEUE_FULL if no more requests can be added, else - * returns UDMA_OK. - */ -extern udma_status_t -udma_2d_copy(void *dest, - void *src, - size_t row_size, - uint32_t num_rows, - uint32_t src_pitch, - uint32_t dest_pitch, - void *callback_data, - void (*callback_func)(void *, udma_status_t *status), - uint32_t request_attr, - udma_status_t *status); - -/* Process requests that are done. Any callbacks associated - * with the completed requests gets invoked. If there are any errors, - * the error request is (and any pending request based on the request attribute) - * cancelled and the error code is returned in the status associated with - * all such cancelled requests. Callbacks associated with the cancelled - * requests are also invoked. If all requests terminate normally, the status - * of the completed requests are set to UDMA_REQ_DONE. - * - * Returns void - */ -extern void -udma_process_requests(); - -/* Sets the udma max PIF block size - * - * max_block_size : max block size to be set - * - * Returns UDMA_ERROR_INVALID_ARG if block_size is > 3, else returns UDMA_OK - */ -udma_status_t -udma_set_max_block_size(uint32_t block_size); - -/* Sets the udma max outstanding PIF requests - * - * max_outstanding : max outstanding PIF requests - * - * Returns UDMA_ERROR_INVALID_ARG if max_outstanding is not between 1 and 16 - * else returns UDMA_OK - */ -udma_status_t -udma_set_max_outstanding(uint32_t max_outstanding); - -/* Initialize a uDMA descriptor using the copy parameters. The descriptor - * is then queued separately using udma_add_desc - * - * src : src address of the copy - * dest : dest address of the copy - * row_size : number of bytes per row to copy - * num_rows : number of rows to copy - * src_pitch : src pitch - * dest_pitch : dest pitch - * notify_with_interrupt : If 1, interrupt when dma is done with this descriptor - * if 0, do nothing, else undefined - * - * Returns void - */ -extern void -udma_set_desc(void *src, - void *dest, - size_t row_size, - uint32_t num_rows, - uint32_t src_pitch, - uint32_t dest_pitch, - uint32_t notify_with_interrupt, - udma_desc_t *desc); - -/* Add multiple uDMA descriptors to the descriptor queue. If the call returns - * UDMA_OK, the status is set to UDMA_REQ_PENDING or UDMA_REQ_DONE. - * If there is a dma error, the error code, which could be one of - * UDMA_ERROR_BAD_DESC, UDMA_ERROR_DRAM_CROSSING, UDMA_ERROR_PIF_ADDR_BUS, - * UDMA_ERROR_PIF_DATA_BUS is returned in the status. Status is set - * to UDMA_REQ_DONE, if the dma completes normally. - * On completion, the callback function is invoked with the callback_data - * and status as parameters. Note, the callback is always invoked even if - * there is a dma error. - * - * desc : descriptors to be added - * num_desc : number of descriptors to be added - * callback_data : optional data to be passed to callback_func - * callback_func : optional callback after copy is done - * request_attr : attribute defining how to process this request - * (see description of the request attribute in top of udma.h) - * Note, bit 0 (for enabling interrupt) is ignored in this call. - * To interrupt on dma completion, set the - * notify_with_interrupt parameter when creating descriptors - * using udma_set_desc. - * status : track status of the copy; this gets also passed - * as the second argument to the callback_func - * - * Returns UDMA_ERROR_QUEUE_FULL if no more descriptors can be added, - * UDMA_ERROR_INVALID_ARG if num_descs == 0, else return UDMA_OK - */ -udma_status_t -udma_add_descs(udma_desc_t *descs, - uint32_t num_descs, - void *callback_data, - void (*callback_func)(void *, udma_status_t *status), - uint32_t request_attr, - udma_status_t *status); - -/* Wait for udma copy request to complete. Could spin wait or goto waiti - * based on the sleep_wait parameter. Once the request is done, the callback - * associated with this request and any prior completed requests are handled. - * Error code, if any, is returned in the status s, else s is set to - * UDMA_REQ_DONE. - * - * s : status to wait for - * sleep_wait : sleep wait if true, else spin waits - * - * Returns void - */ -extern void -udma_wait_request(volatile udma_status_t *s, uint32_t sleep_wait); - -/* Inlined function to set the src, dest address of the descriptor - * - * src : src address of the uDMA - * dest : dest address of the uDMA - * desc : descriptor to be modified - * - * Returns void - */ -void static inline -udma_set_desc_addrs(void *src, void *dest, udma_desc_t *desc) { - uint32_t *d = (uint32_t *)desc; - *d = (uintptr_t)src; - *(d+1) = (uintptr_t)dest; -} - -/* Sets the number of retries for a failed dma request - * - * max_retries : max number of retries - * - * Sets the max number of retries for a failed dma request. The default is 0, - * i.e, no retries - */ -void -udma_set_max_retries(uint32_t max_retries); - -#ifdef __cplusplus -} -#endif - -#endif /* __UDMA_H__ */ diff --git a/tools/sdk/include/esp32/xtensa/xdm-regs.h b/tools/sdk/include/esp32/xtensa/xdm-regs.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/xmon.h b/tools/sdk/include/esp32/xtensa/xmon.h deleted file mode 100755 index 12a757a2c10..00000000000 --- a/tools/sdk/include/esp32/xtensa/xmon.h +++ /dev/null @@ -1,97 +0,0 @@ -/* xmon.h - XMON definitions - * - * $Id: //depot/rel/Eaglenest/Xtensa/OS/xmon/xmon.h#3 $ - * - * Copyright (c) 2001-2013 Tensilica 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. - */ - -#ifndef __H_XMON -#define __H_XMON - -/* Default GDB packet size */ -#define GDB_PKT_SIZE 4096 - -/*XMON signals */ -#define XMON_SIGINT 2 /*target was interrupted */ -#define XMON_SIGILL 4 /*illegal instruction */ -#define XMON_SIGTRAP 5 /*general exception */ -#define XMON_SIGSEGV 11 /*page faults */ - - -/* Type of log message from XMON to the application */ -typedef enum { - XMON_LOG, - XMON_TRACE, - XMON_ERR, - XMON_APP, - XMON_GDB -} xmon_log_t; - -/* Return value type for xmon_proc() (see below) */ -typedef enum { - XMON_GDB_PEND, - XMON_GDB_PKT, - XMON_NOT_GDB -} xmon_gdb_pkt_t; - -#ifdef _cplusplus -extern "C" { -#endif - -/* - * THE FOLLOWING ROUTINES ARE USED BY USER - */ -extern int _xmon_init(char* gdbBuf, int gdbPktSize, - void(*xlog)(xmon_log_t type, const char* str)); -//Initialize GDB communication and logging to the main app. -//For the logging to work, xlog function needs to be provided. -//gdbBuf - pointer to a buffer XMON can use to comm. with GDB -//gdbPktSize - Size of the allocated buffer for GDB communication. -//xlog - logger handle. - - -extern void _xmon_close(void); -//Main application can detach from xmon at any time - - -extern xmon_gdb_pkt_t _xmon_proc(char); -// Give character to XMON to check if GDB message -// Application is supposed to accumulate all the -// character in case the recognition fails and chars -// have to be sent to the original handler -// Return: XMON_GDB_PEND - send me more chars -// XMON_GDB_PKT - GDB message confirmed, C) not -// XMON_NOT_GDB - not GDB message - - -/* - * THE FOLLOWING ROUTINES NEED TO BE PROVIDED BY USER - */ -extern int _xmon_in(); // wait for character from GDB -extern void _xmon_out(char); // output a character to GDB -extern int _xmon_flush(void); // flush output characters - -#ifdef _cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/esp32/xtensa/xmp-library.h b/tools/sdk/include/esp32/xtensa/xmp-library.h deleted file mode 100755 index 624272077c4..00000000000 --- a/tools/sdk/include/esp32/xtensa/xmp-library.h +++ /dev/null @@ -1,789 +0,0 @@ -/* Customer ID=11656; Build=0x5f626; Copyright (c) 2008-2009 by Tensilica Inc. ALL RIGHTS RESERVED. - These coded instructions, statements, and computer programs are the - copyrighted works and confidential proprietary information of Tensilica Inc. - They may not be modified, copied, reproduced, distributed, or disclosed to - third parties in any manner, medium, or form, in whole or in part, without - the prior written consent of Tensilica Inc. */ - -#ifndef _XMP_LIBRARY_H -#define _XMP_LIBRARY_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include -#if XCHAL_HAVE_RELEASE_SYNC -#include -#endif -#if XCHAL_HAVE_EXTERN_REGS -#include -#endif -#include -#include - -#include "xtensa/system/mpsystem.h" - -/* - W A R N I N G: - - xmp library clients should treat all data structures in this file - as opaque. They are only public to enable users to declare them - statically. -*/ - - -/* ------------------------------------------------------------------------- - When using XMP on cache-incoherent systems, these macros are helpful - to ensure that you are not reading stale data, and to ensure that - the data you write makes it all the way back to main memory. - */ - -#if !XCHAL_DCACHE_IS_COHERENT -#define XMP_WRITE_BACK_ELEMENT(x) xthal_dcache_region_writeback((void *)x, sizeof(*x)) -#define XMP_INVALIDATE_ELEMENT(x) xthal_dcache_region_invalidate((void *)x, sizeof(*x)) -#define XMP_WRITE_BACK_INVALIDATE_ELEMENT(x) xthal_dcache_region_writeback_inv((void *)x, sizeof(*x)) -#define XMP_WRITE_BACK_ARRAY(x) xthal_dcache_region_writeback((void *)x, sizeof(x)) -#define XMP_INVALIDATE_ARRAY(x) xthal_dcache_region_invalidate((void *)x, sizeof(x)) -#define XMP_WRITE_BACK_INVALIDATE_ARRAY(x) xthal_dcache_region_writeback_inv((void *)x, sizeof(x)) -#define XMP_WRITE_BACK_ARRAY_ELEMENTS(x, num_elements) xthal_dcache_region_writeback((void *)x, sizeof(*x) * num_elements) -#define XMP_INVALIDATE_ARRAY_ELEMENTS(x, num_elements) xthal_dcache_region_invalidate((void *)x, sizeof(*x) * num_elements) -#define XMP_WRITE_BACK_INVALIDATE_ARRAY_ELEMENTS(x, num_elements) xthal_dcache_region_writeback_inv((void *)x, sizeof(*x) * num_elements) -#else -#define XMP_WRITE_BACK_ELEMENT(x) -#define XMP_INVALIDATE_ELEMENT(x) -#define XMP_WRITE_BACK_INVALIDATE_ELEMENT(x) -#define XMP_WRITE_BACK_ARRAY(x) -#define XMP_INVALIDATE_ARRAY(x) -#define XMP_WRITE_BACK_INVALIDATE_ARRAY(x) -#define XMP_WRITE_BACK_ARRAY_ELEMENTS(x, num_elements) -#define XMP_INVALIDATE_ARRAY_ELEMENTS(x, num_elements) -#define XMP_WRITE_BACK_INVALIDATE_ARRAY_ELEMENTS(x, num_elements) -#endif - -/* ------------------------------------------------------------------------- - Initialization, error codes, constants and house-keeping - - Every core should call xmp_init with the number of cores in the - system. - - xmp_init should be called before you use any global synchronization - primitive or shared data. - - Further, before you use a dynamically allocated synchronization - primitives, you need to both initialize it by calling the - xmp_*_init function, and you need to have called xmp_init, which - sets up interrupt handlers and interrupt routing. - - The second parameter sets the interprocessor interrupt - routing. Passing zero instructs the library to use the default - routing, which will be suitable for most users. - -*/ - -extern void xmp_init (int num_cores, unsigned int interrupt_routing); - - -/* If you want finer-grained control than that provided by xmp_init, - you can the functions below individually--however, this is more - inconvenient and requires greater understanding of the library's - internals. Don't use them directly unless you have a good reason. -*/ - -extern void xmp_unpack_shared (void); -extern void xmp_route_interrupts (unsigned int routing); - -#if XCHAL_HAVE_MP_INTERRUPTS -extern void xmp_enable_ipi_interrupts (void); - -/* Turn off certain things enabled by xmp_init */ -extern void xmp_disable_ipi_interrupts (void); -#endif - -extern void xmp_end (void); - -/* Only valid after xmp_init. */ -extern int xmp_num_cores (void); - -/* How many cycles should a core wait before rechecking a - synchronization variable? Higher values will reduce memory - transactions, but will also result in higher latency in returning - from synchronization. -*/ -extern void xmp_spin_wait_set_cycles (unsigned int limit); - -/* If you would prefer to provide your own spin wait function, - to go to sleep, etc. Declare a function of this type, then call - this function. */ -typedef void (*xmp_spin_wait_function_t)(void); -extern void xmp_spin_wait_set_function (xmp_spin_wait_function_t func); -extern void xmp_spin(void); - -#define XMP_NO_OWNER 0x07 -#define XMP_MUTEX_DESTROYED 0xFE -#define XMP_ERROR_FATAL 0xFD - -#define XMP_MAX_CORES 0x4 - - -static inline unsigned int xmp_prid (void) -{ -#if XCHAL_HAVE_PRID - return XT_RSR_PRID() & 0xFF; -#else - return 0; -#endif -} - - -/* ------------------------------------------------------------------------- - Tracing - - A core must set a trace_file if it wants any synchronization - tracing to occur. Sharing file descriptors among cores is very - messy, so don't do it. This, unfortunately, means that two cores - contending for a mutex are not able to trace to the same file. - - Any object (except the atomic integer) can have tracing off or on. -*/ - -extern void xmp_set_trace_file (FILE * file); -extern void xmp_trace (const char * fmt, ...); - - -/* ------------------------------------------------------------------------- - Memory Allocation Functions. - - These do what you would expect, only from shared memory instead of - private memory. -*/ - -#if XCHAL_DCACHE_IS_COHERENT -extern void * xmp_malloc (size_t size); -extern void * xmp_calloc (size_t nmemb, size_t size); -extern void xmp_free (void * ptr); -#endif -extern void * xmp_sbrk(int size); - -/* ------------------------------------------------------------------------- - xmp_atomic_int_t - - The most basic synchronization primitive in the xmp library. - Atomic ints are sharable among processors, and even interrupt - levels on the same processor. However, their semantics are fairly - rudimentary. All other primitives are based on these, therefore, - changing this implementation affects all other primitives. - -*/ - -typedef unsigned int xmp_atomic_int_t; - -static inline xmp_atomic_int_t -xmp_coherent_l32ai(xmp_atomic_int_t * address) -{ - XMP_INVALIDATE_ELEMENT (address); - return XT_L32AI(address, 0); -} - -static inline void -xmp_coherent_s32ri(xmp_atomic_int_t value, xmp_atomic_int_t * address) -{ - XT_S32RI (value, address, 0); - XMP_WRITE_BACK_ELEMENT (address); -} - -#define XMP_ATOMIC_INT_INITIALIZER(value) (value) - -/* xmp_atomic_int_init - Initialize an int prior to use - - Nonsynchronizing, Nonblocking - - Usage: - value - initial value - integer - points to an uninitialized integer - - On exit: - initialized to given value - - Errors: none -*/ - -static inline void -xmp_atomic_int_init (xmp_atomic_int_t * integer, int value) -{ - xmp_coherent_s32ri (value, integer); -} - - -/* xmp_atomic_int_value - Read the value - - Nonsynchronizing, Nonblocking - - Usage: - integer - points to an int - - Returns: - the value -*/ - -static inline int -xmp_atomic_int_value (xmp_atomic_int_t * integer) -{ - return xmp_coherent_l32ai (integer); -} - - -/* xmp_atomic_int_conditional_increment - Conditionally increment integer - - Synchronizing, nonblocking - - Usage: - integer - points to an initialized integer - amount - how much to increment - prev - believed value of the integer - eg: prev = xmp_atomic_int_value (integer); - success = xmp_atomic_int_increment (integer, 1, prev); - - Returns: current value of integer - user should check if it matches - the previous value of the integer. If it does, then the update - was successful. - -*/ - -#define USE_ASSEMBLY_IMPLEMENTATION 0 - -static inline int -xmp_atomic_int_conditional_increment (xmp_atomic_int_t * integer, int amount, int prev) -{ - int val; - int saved; - -#if USE_ASSEMBLY_IMPLEMENTATION - /* %0 = prev - %1 = saved - %2 = atomic integer pointer - %3 = amount - */ - - asm volatile ("wsr.scompare1 %0\n" - "mov %1, %0\n" - "add %0, %0, %3\n" - "s32c1i %0, %2, 0\n" - : "+&a" (prev), "+&a"(saved) : "a" (integer), "a" (amount)); - - return prev; - -#else - - XT_WSR_SCOMPARE1 (prev); - val = prev + amount; - saved = val; - XT_S32C1I (val, integer, 0); - - return val; -#endif -} - - -/* xmp_atomic_int_increment - Increment integer - - Synchronizing, blocking - - Usage: - integer - points to an initialized integer - amount - how much to increment - - Returns: new value of integer - -*/ - -static inline int -xmp_atomic_int_increment (xmp_atomic_int_t * integer, int amount) -{ - int val; - int saved; -#if USE_ASSEMBLY_IMPLEMENTATION - /* %0 = val - %1 = saved - %2 = atomic integer pointer - %3 = amount - */ - - asm volatile ("l32ai %0, %2, 0\n" - "1:\n" - "wsr.scompare1 %0\n" - "mov %1, %0\n" - "add %0, %0, %3\n" - "s32c1i %0, %2, 0\n" - "bne %0, %1, 1b\n" - : "+&a" (val), "+&a"(saved) : "a" (integer), "a" (amount)); -#else - /* Accurately naming "val" is tricky. Sometimes it will be what we - want to be the new value, but sometimes it contains the value - that is currently at the location. */ - - /* Load location's current value */ - val = xmp_coherent_l32ai (integer); - - do { - XT_WSR_SCOMPARE1 (val); - saved = val; - /* Change it to what we would like to store there--"new_val" */ - val = val + amount; - /* Possibly store new_val, but reload location's current value no - matter what. */ - XT_S32C1I (val, integer, 0); - if (val != saved) - xmp_spin(); - } while (val != saved); - -#endif - return val + amount; -} - - -/* xmp_atomic_int_conditional_set - Set the value of an atomic integer - - Synchronizing, nonblocking - - Usage: - integer - points to an initialized integer - from - believed value of the integer - eg: prev = xmp_atomic_int_value (integer); - success = xmp_atomic_int_conditional_set (integer, 1, prev); - to - new value - - Returns: current value of integer - user should check if it matches - the previous value of the integer. If it does, then the update - was successful. - -*/ - -static inline int -xmp_atomic_int_conditional_set (xmp_atomic_int_t * integer, int from, int to) -{ - int val; - - /* Don't even try to update if the integer's value isn't what we - think it should be. This prevents acquiring this cache-line for - writing and therefore prevents bus transactions when various - cores contend. */ - val = xmp_coherent_l32ai(integer); - if (val == from) { - XT_WSR_SCOMPARE1 (from); - val = to; - /* Possibly store to, but reload location's current value no - matter what. */ - XT_S32C1I (val, integer, 0); - } - return val; -} - - -/* Macros to implement trivial spin locks. These are very primitive, but - can be useful when you don't need the higher-overhead synchronization. - - To use an xmp_atomic_int_t as a trivial spin lock, you should - initialize it to zero first. -*/ - -#define XMP_SIMPLE_SPINLOCK_ACQUIRE(atomic_int_ptr) \ - { while (xmp_atomic_int_conditional_set (atomic_int_ptr, 0, xmp_prid() + 1) != 0) \ - xmp_spin(); } -#define XMP_SIMPLE_SPINLOCK_RELEASE(atomic_int_ptr) \ - { while (xmp_atomic_int_conditional_set (atomic_int_ptr, xmp_prid() + 1, 0) != xmp_prid() + 1) \ - xmp_spin(); } - -#define XMP_SIMPLE_SPINLOCK_OWNER(atomic_int_ptr) (xmp_atomic_int_value(atomic_int_ptr) - 1) - - -/* ------------------------------------------------------------------------- - xmp_mutex_t - An even higher-level data structure to enforce - mutual exclusion between cores. A core which waits on a mutex might - sleep with a waiti and be interrupted by an interrupt. - - Mutexes can be normal or recursive. For a normal mutex, a core - attempting to acquire a mutex it already holds will result in - deadlock. For a recursive mutex, a core will succeed in acquiring a - mutex it already holds, and must release it as many times as it - acquired it. - - Mutexes are not sharable between interrupt levels--because - ownership is tracked by core, not thread. - - Like all xmp data structures, an object of type xmp_mutex_t - should be treated by the programmer as opaque. They are only - public in this header file to allow them to be declared statically. - - For configurations with 16-byte cache lines, this has the most - frequently used and changed data in the first line. - -*/ - -#if XCHAL_DCACHE_IS_COHERENT -typedef struct xmp_mutex_t { - xmp_atomic_int_t qlock; - unsigned int qhead; - unsigned int qtail; - unsigned char queue[XMP_MAX_CORES]; - unsigned short held; - - unsigned char owner; - unsigned char recursive : 1; - unsigned char trace : 1; - unsigned char system : 1; - unsigned char unused : 5; - const char * name; -} xmp_mutex_t __attribute__ ((aligned (XMP_MAX_DCACHE_LINESIZE))); - - -#define XMP_MUTEX_INITIALIZER(name) \ - { 0, 0, -1, {XMP_NO_OWNER, XMP_NO_OWNER, XMP_NO_OWNER, XMP_NO_OWNER}, \ - 0, XMP_NO_OWNER, XMP_MUTEX_FLAG_NORMAL, 0, 0, 0, name } - -#define XMP_RECURSIVE_MUTEX_INITIALIZER(name) \ - { 0, 0, -1, {XMP_NO_OWNER, XMP_NO_OWNER, XMP_NO_OWNER, XMP_NO_OWNER}, \ - 0, XMP_NO_OWNER, XMP_MUTEX_FLAG_RECURSIVE, 0, 0, 0, name } - -#define XMP_MUTEX_FLAG_NORMAL 0 -#define XMP_MUTEX_FLAG_RECURSIVE 1 - -#define XMP_MUTEX_ACQUIRE_FAILED -1 -#define XMP_MUTEX_ERROR_DESTROY_OWNED -2 -#define XMP_MUTEX_ERROR_NOT_OWNED -3 -#define XMP_MUTEX_ERROR_ALREADY_OWNED -4 - -/* - xmp_mutex_init - - Nonsynchronizing - Nonblocking - - Usage: - mutex - points to an uninitialized mutex - name - name if you want one, NULL if not. - recursive - use recursive semantices - - Returns - zero on success (always succeeds) - -*/ - -extern int xmp_mutex_init (xmp_mutex_t * mutex, - const char * name, - unsigned int recursive); - -/* - int xmp_mutex_destroy (xmp_mutex_t * mutex); - - Synchronizing - will fail if mutex is held by anyone -- including - current processor - Nonblocking - - Usage: - mutex - points to a mutex - - Returns - zero on success - non-zero if mutex is held -*/ - -extern int xmp_mutex_destroy (xmp_mutex_t * mutex); - - -/* - xmp_mutex_lock -- Synchronizing - xmp_mutex_trylock - - Usage: - mutex - points to a mutex - - Returns - zero on success -*/ - -extern int xmp_mutex_lock (xmp_mutex_t * mutex); -extern int xmp_mutex_trylock (xmp_mutex_t * mutex); - - -/* - xmp_mutex_unlock - - Synchronizing - Nonblocking - - Usage: - mutex - points to a mutex - - Returns - zero on success - mutex is released - non-zero on failure - mutex is owned by another core - - prid of processor that does own it - note that by the time this function - returns, the owner of the core may - have changed. -*/ - -extern int xmp_mutex_unlock (xmp_mutex_t * mutex); - - -/* - xmp_mutex_name - - Nonsynchronizing - Nonblocking - - Usage: - mutex - points to a mutex - - Returns the name of the given mutex, which may be NULL. - -*/ - -const char * xmp_mutex_name (const xmp_mutex_t * mutex); - - -/* - xmp_mutex_trace_on - xmp_mutex_trace_off - - Nonsynchronizing - Nonblocking - - Turn off and on tracing for the mutex. - - These functions are only present in the debug version of the library. -*/ - -extern void xmp_mutex_trace_on (xmp_mutex_t * mutex); -extern void xmp_mutex_trace_off (xmp_mutex_t * mutex); - - -/* ------------------------------------------------------------------------- - xmp_condition_t - - Condition Variables following Mesa semantics. - - Condition variables are not sharable among interrupt levels. - -*/ - - -typedef struct xmp_condition_t { - unsigned int qhead; - unsigned int qtail; - unsigned char queue[XMP_MAX_CORES]; - unsigned int waiting[XMP_MAX_CORES]; - - unsigned char trace : 1; - unsigned char unused : 7; - const char * name; -} xmp_condition_t __attribute__ ((aligned (XMP_MAX_DCACHE_LINESIZE))); - - -#define XMP_CONDITION_INITIALIZER(name) \ - { 0, -1, {XMP_NO_OWNER, XMP_NO_OWNER, XMP_NO_OWNER, XMP_NO_OWNER}, \ - {0, 0, 0, 0}, 0, 0, name} - - -/* xmp_condition_init - Initialize a condition variable - - Nonsynchronizing, Nonblocking - - Usage: - condition - pointer to an xmp_condition_t - - On exit: - condition initialized - - Errors: none -*/ - -extern int xmp_condition_init (xmp_condition_t * condition, - const char * name); -extern int xmp_condition_destroy (xmp_condition_t * condition); - - -/* xmp_condition_wait - Wait for a condition variable - - Synchronizing, blocking - - Usage: - condition - pointer to an xmp_condition_t - mutex - pointer to an xmp_mutex_t already acquired by the calling - process - - Errors: if the mutex isn't held by this core -*/ - -extern int xmp_condition_wait (xmp_condition_t * condition, - xmp_mutex_t * mutex); - -/* xmp_condition_signal - - - Signal the first (if any) core waiting on a condition variable - - You must hold the mutex you passed to xmp_condition_wait before - calling this function. - - Synchronizing, nonblocking - - Usage: - condition - pointer to an xmp_condition_t - - Errors: none -*/ - -extern int xmp_condition_signal (xmp_condition_t * condition); - - -/* xmp_condition_broadcast - - - Signal all cores waiting on a condition variable - - Synchronizing, nonblocking - - You must hold the mutex you passed to xmp_condition_wait before - calling this function. - - Usage: - condition - pointer to an xmp_condition_t - - Errors: none -*/ - -extern int xmp_condition_broadcast (xmp_condition_t * condition); - - -static inline const char * xmp_condition_name (const xmp_condition_t * condition) -{ - return condition->name; -} - -/* - xmp_condition_trace_on - xmp_condition_trace_off - - Nonsynchronizing - Nonblocking - - Turn off and on statistics and tracing for the condition. For - tracing you must also set a trace file for the core. - - These functions are only present in the debug-version of the library. -*/ - -extern void xmp_condition_trace_on (xmp_condition_t * condition); -extern void xmp_condition_trace_off (xmp_condition_t * condition); - -#endif /* XCHAL_DCACHE_IS_COHERENT */ - -/* ------------------------------------------------------------------------- - xmp_barrier_t - - Classic barriers that stop any core from continuing until a - specified number of cores reach that point. Once the barrier allows - cores through, the barrier is reset and will stop cores from - progressing again. - - Barriers are not sharable among interrupt levels. - -*/ - - -typedef struct xmp_barrier_t -{ - xmp_atomic_int_t count; - xmp_atomic_int_t state; - xmp_atomic_int_t sleeping; - unsigned short num_cores; - unsigned short trace : 1; - unsigned short system : 1; - const char * name; -} xmp_barrier_t __attribute__ ((aligned (XMP_MAX_DCACHE_LINESIZE))); - -#define XMP_BARRIER_INITIALIZER(number, name) \ - { 0, 0, 0, number, 0, 0, name } - - -/* xmp_barrier_init - Initialize a barrier - - Nonsynchronizing, Nonblocking - - Usage: - barrier - pointer to an xmp_barrier_t - num_cores - number of cores needed to arrive at the - barrier before any are allowed through - On exit: - barrier initialized - - Always returns zero. - - Errors: none -*/ - -extern int xmp_barrier_init (xmp_barrier_t * barrier, int num_cores, - const char * name); - - -/* xmp_barrier_wait - Wait on a barrier - - Nonsynchronizing, Nonblocking - - Usage: - barrier - pointer to an xmp_barrier_t - On exit: - Enough cores (as determined at the barrier's initialization) - have reached the barrier. - - Errors: none -*/ - -extern int xmp_barrier_wait (xmp_barrier_t * barrier); - - -static inline const char * xmp_barrier_name (const xmp_barrier_t * barrier) -{ - return barrier->name; -} - - -/* - xmp_barrier_trace_on - xmp_barrier_trace_off - - Nonsynchronizing - Nonblocking - - Turn on and off tracing for the barrier. For - tracing you must also set a trace file for the core. - - These functions are only present in the debug-version of the library. -*/ - -extern void xmp_barrier_trace_on (xmp_barrier_t * barrier); -extern void xmp_barrier_trace_off (xmp_barrier_t * barrier); - - -/* ------------------------------------------------------------------------- - Portions of the library that are internal, but belong here for - convenience. -*/ - -extern xmp_atomic_int_t _ResetSync; - -static inline void -xmp_initial_sync (int num_cores) -{ - xmp_atomic_int_increment (&_ResetSync, 1); - while (xmp_coherent_l32ai (&_ResetSync) != num_cores) - xmp_spin (); -} - -#ifdef __cplusplus -} -#endif - -#endif /* _XMP_LIBRARY_H */ diff --git a/tools/sdk/include/esp32/xtensa/xos.h b/tools/sdk/include/esp32/xtensa/xos.h deleted file mode 100755 index 883a9c975ab..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos.h +++ /dev/null @@ -1,524 +0,0 @@ -/** @file */ - -// xos.h - XOS API interface and data structures visible to user code. - -// 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. - - -#ifndef __XOS_H__ -#define __XOS_H__ - -#ifdef __cplusplus -extern "C" { -#endif - - -#include "xos_types.h" - -#include -#if XCHAL_HAVE_INTERRUPTS -#include -#include -#endif - -#include "xos_common.h" -#include "xos_errors.h" -#include "xos_regaccess.h" - - -//----------------------------------------------------------------------------- -// Convert x into a literal string. -//----------------------------------------------------------------------------- -#define _XOS_STR(x) __XOS_STR(x) -#define __XOS_STR(x) #x - - -//----------------------------------------------------------------------------- -// XOS version. -//----------------------------------------------------------------------------- -#define XOS_VERSION_MAJOR 1 -#define XOS_VERSION_MINOR 10 -#define XOS_VERSION_STRING "1.10" ///< XOS version string. - - -//----------------------------------------------------------------------------- -// Runtime error handling. -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -/// -/// Reports a fatal error and halts XOS operation, i.e. halts the system. This -/// function will call a user-registered error handler (if one has been set) -/// and then halt the system. The user handler may do system-specific things -/// such as record the error reason in nonvolatile memory etc. -/// -/// \param errcode Error code. May be any user defined value < 0. -/// Values >=0 are reserved for use by the system. -/// -/// \param errmsg Optional text string describing the error. -/// -/// \return This function does not return. -/// -//----------------------------------------------------------------------------- -void -xos_fatal_error(int32_t errcode, const char * errmsg); - - -#if XOS_DEBUG - -// Do not call directly. -void -xos_assert(const char * file, int32_t line); - -//----------------------------------------------------------------------------- -/// -/// Check condition and fail if condition expression is false. -/// In debug builds, an assertion failure will cause a fatal error to be -/// reported. In non-debug builds, assertions are compiled out. -/// -/// NOTE: Remember that any code in XOS_ASSERT() statements gets compiled out -/// for non-debug builds. -/// -//----------------------------------------------------------------------------- - -#define XOS_ASSERT(expr) if ((expr) == 0) xos_assert(__FILE__, __LINE__) - -#else - -#define XOS_ASSERT(expr) - -#endif - - -//----------------------------------------------------------------------------- -/// -/// Interrupt handler function pointer type. -/// -//----------------------------------------------------------------------------- -typedef void (XosIntFunc)(void * arg); - -//----------------------------------------------------------------------------- -/// -/// Print handler function pointer type. -/// -//----------------------------------------------------------------------------- -typedef int32_t (XosPrintFunc)(void * arg, const char * fmt, ...); - -//----------------------------------------------------------------------------- -/// -/// Fatal error handler function pointer type. -/// -//----------------------------------------------------------------------------- -typedef void (XosFatalErrFunc)(int32_t errcode, const char * errmsg); - -//----------------------------------------------------------------------------- -/// -/// Exception handler function pointer type. -/// -//----------------------------------------------------------------------------- -typedef void (XosExcHandlerFunc)(XosExcFrame * frame); - - -//----------------------------------------------------------------------------- -/// -/// Install a user defined exception handler for the specified exception type. -/// This will override the default XOS exception handler. The handler is a C -/// function that is passed one parameter -- a pointer to the exception frame. -/// The exception frame is allocated on the stack of the thread that caused the -/// exception, and contains saved state and exception information. For details -/// of the exception frame see the structure XosExcFrame. -/// -/// \param exc Exception type (number) to override. The exception -/// numbers are enumerated in . -/// -/// \param handler Pointer to handler function to be installed. -/// To revert to the default handler, pass NULL. -/// -/// \return Returns a pointer to previous handler installed, if any. -/// -//----------------------------------------------------------------------------- -XosExcHandlerFunc * -xos_register_exception_handler(int32_t exc, XosExcHandlerFunc * handler); - - -//----------------------------------------------------------------------------- -/// -/// Install a user defined fatal error handler. This function will be called if -/// a fatal error is reported either by user code or by XOS itself. It will be -/// passed the same arguments that are passed to xos_fatal_error(). -/// -/// The handler need not return. It should make minimal assumptions about the -/// state of the system. In particular, it should not assume that further XOS -/// system calls will succeed. -/// -/// \param handler Pointer to handler function to be installed. -/// -/// \return Returns a pointer to previous handler installed, if any. -/// -//----------------------------------------------------------------------------- -XosFatalErrFunc * -xos_register_fatal_error_handler(XosFatalErrFunc * handler); - - -#ifdef _XOS_INCLUDE_INTERNAL_ -# include "xos_internal.h" -#endif - - -#include "xos_thread.h" -#include "xos_timer.h" -#include "xos_cond.h" -#include "xos_event.h" -#include "xos_mutex.h" -#include "xos_msgq.h" -#include "xos_semaphore.h" -#include "xos_stopwatch.h" - - -//----------------------------------------------------------------------------- -/// -/// Register a handler function to call when interrupt "num" occurs. -/// -/// For level-triggered and timer interrupts, the handler function will have -/// to clear the source of the interrupt before returning, to avoid infinitely -/// retaking the interrupt. Edge-triggered and software interrupts are -/// automatically cleared by the OS interrupt dispatcher (see xos_handlers.S). -/// -/// \param num Xtensa internal interrupt number (0..31). To -/// refer to a specific external interrupt number -/// (BInterrupt pin), use HAL macro XCHAL_EXTINTx_NUM -/// where 'x' is the external number. -/// -/// \param handler Pointer to handler function. -/// -/// \param arg Argument passed to handler. -/// -/// \return Returns XOS_OK if successful, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_register_interrupt_handler(int32_t num, XosIntFunc * handler, void * arg); - - -//----------------------------------------------------------------------------- -/// -/// Unregister a handler function for interrupt "num". If no handler was -/// installed, this function will have no effect. -/// -/// \param num Xtensa internal interrupt number (0..31). To -/// refer to a specific external interrupt number -/// (BInterrupt pin), use HAL macro XCHAL_EXTINTx_NUM -/// where 'x' is the external number. -/// -/// \return Returns XOS_OK if successful, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_unregister_interrupt_handler(int32_t num); - - -//----------------------------------------------------------------------------- -/// -/// Register a high priority interrupt handler for interrupt level "level". -/// -/// Unlike low and medium priority interrupt handlers, high priority handlers -/// are not installed for a specific interrupt number, but for an interrupt -/// level. The level must be above XCHAL_EXCM_LEVEL. The handler function must -/// be written in assembly since C handlers are not supported for levels above -/// XCHAL_EXCM_LEVEL. The handler function must preserve all registers except -/// a0, and must return to the dispatcher via a "ret" instruction, not "rfi". -/// -/// NOTE: This method of dispatch takes a few cycles of overhead. If you wish -/// to save even these cycles, then you can define your own dispatch function -/// to override the built-in dispatcher. See xos_handlers.S for more details. -/// -/// \param level The interrupt level to be handled. -/// -/// \param handler Pointer to handler function. -/// -/// \return Returns XOS_OK if successful, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_register_hp_interrupt_handler(int32_t level, void * handler); - - -//----------------------------------------------------------------------------- -/// -/// Enable a specific interrupt, by interrupt number. -/// The state (enabled vs. disabled) of individual interrupts is global, i.e. -/// not associated with any specific thread. Depending on system options and -/// implementation, this state may be stored in one of two ways: -/// - directly in the INTENABLE register, or -/// - in a global variable (this is generally the case when INTENABLE is used -/// not just to control what interrupts are enabled globally, but also for -/// software interrupt prioritization within an interrupt level, effectively -/// providing finer grained levels; in this case XOS takes care to update -/// INTENABLE whenever either the global enabled-state variable or the -/// per-thread fine-grained-level variable change). -/// Thus it is best to never access the INTENABLE register directly. -/// -/// To modify thread-specific interrupt priority level, use one of: -/// - xos_set_int_pri_level() -/// - xos_restore_int_pri_level() -/// - xos_disable_interrupts() -/// - xos_restore_interrupts() -/// -/// NOTE: To refer to a specific external interrupt number (BInterrupt pin), -/// use HAL macro XCHAL_EXTINTx_NUM where 'x' is the external interrupt -/// number. For example, to enable external interrupt 3 (BInterrupt[3]), -/// you can use: -/// -/// xos_interrupt_enable( XCHAL_EXTINT3_NUM ); -/// -/// \param intnum Interrupt number to enable. Must range between 0-31. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -void -xos_interrupt_enable(uint32_t intnum); - - -//----------------------------------------------------------------------------- -/// -/// Disable a specific individual interrupt, by interrupt number. -/// -/// This is the counterpart to xos_interrupt_enable(). See the description -/// of xos_interrupt_enable() for further comments and notes. -/// -/// \param intnum Interrupt number to disable. Must range between 0-31. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -void -xos_interrupt_disable(uint32_t intnum); - - -//----------------------------------------------------------------------------- -/// -/// Get the CPU's current interrupt priority level. Interrupts at or below this -/// priority level are blocked. -/// -/// \return Returns the current IPL, ranging from 0 to XCHAL_NUM_INTLEVELS. -/// -//----------------------------------------------------------------------------- -static inline uint32_t -xos_get_int_pri_level(void) -{ -#if XCHAL_HAVE_INTERRUPTS - return XT_RSR_PS() & 0xF; -#else - return 0; -#endif -} - - -//----------------------------------------------------------------------------- -/// -/// Set the CPU's interrupt priority level to the specified level, but only if -/// the current IPL is below the one requested. This function will never cause -/// the interrupt priority level to be lowered from the current level. -/// Call this function to block interrupts at or below the specified priority -/// level. -/// -/// When setting the IPL temporarily (such as in a critical section), call -/// xos_set_int_pri_level(), execute the critical code section, and then call -/// xos_restore_int_pri_level(). -/// -/// The interrupt priority level is part of the thread context, so it is saved -/// and restored across context switches. To enable and disable individual -/// interrupts globally, use the functions xos_interrupt_enable() and -/// xos_interrupt_disable() instead. -/// -/// NOTE: It is usually not required to disable interrupts at a level higher -/// than that of the highest priority interrupt that interacts with the OS -/// (i.e. calls into XOS such that threads may be woken / blocked / -/// reprioritized / switched, or otherwise access XOS data structures). -/// In XOS, that maximum level is XOS_MAX_OS_INTLEVEL, which defaults to -/// XCHAL_EXCM_LEVEL. This may be modified by editing xos_params.h and -/// rebuilding XOS. -/// -/// \param level The new interrupt priority level (IPL). -/// -/// \return Returns a value that can be used to restore the previous -/// priority level by calling xos_restore_int_pri_level(). This -/// value should be treated as opaque by application code, and -/// should be passed unchanged to the restore function. -/// -//----------------------------------------------------------------------------- -__attribute__((always_inline)) -static inline uint32_t -xos_set_int_pri_level(uint32_t level) -{ -#if XCHAL_HAVE_INTERRUPTS -#pragma no_reorder - uint32_t ps = XT_RSR_PS(); - - if (level > (ps & 0xF)) { - level = (ps & ~0xF) | level; - XT_WSR_PS(level); - XT_RSYNC(); - } - - return ps; -#else - return 0; -#endif -} - - -//----------------------------------------------------------------------------- -/// -/// Restores the CPU to a previously saved interrupt priority level. This level -/// must have been obtained by calling xos_set_int_pri_level(). -/// -/// \param oldval Return value from xos_set_int_pri_level(). -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -__attribute__((always_inline)) -static inline void -xos_restore_int_pri_level(const uint32_t oldval) -{ -#if XCHAL_HAVE_INTERRUPTS -#pragma no_reorder - XT_WSR_PS(oldval); - XT_RSYNC(); -#else - // Nothing -#endif -} - - -//----------------------------------------------------------------------------- -/// -/// Disable all interrupts that can interact directly with the OS. This is a -/// convenience function, shorthand for setting the IPL to XOS_MAX_OS_INTLEVEL. -/// -/// Returns: A value that can be used to restore the previous priority level -/// by calling xos_restore_interrupts(). This value should be treated as -/// opaque by application code, and should be passed unchanged to the restore -/// function. -/// -//----------------------------------------------------------------------------- -static inline uint32_t -xos_disable_interrupts(void) -{ - return xos_set_int_pri_level(XOS_MAX_OS_INTLEVEL); -} - - -//----------------------------------------------------------------------------- -/// -/// Restore the CPU's previously saved interrupt status. This is a convenience -/// function, the counterpart to xos_disable_interrupts(). -/// -/// \return rval Return value from xos_disable_interrupts(). -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -static inline void -xos_restore_interrupts(uint32_t rval) -{ - xos_restore_int_pri_level(rval); -} - - -#ifdef _XOS_INCLUDE_INTERNAL_ - -//----------------------------------------------------------------------------- -// Enter an OS critical section, i.e. get exclusive access to OS critical -// state and data structures. Code that manipulates the state of OS objects -// or modifies internal OS state must call this function first, to ensure -// that it has exclusive access. On a single-core system, this is equivalent -// to blocking all interrupts that can interact directly with the OS, i.e. -// all interrupts at or below XOS_MAX_OS_INTLEVEL. In a multi-core system -// this is likely to be implemented differently to achieve the same effect. -// -// Returns: A value that is to be used to restore the state of the CPU when -// exiting the critical section. This must be treated as opaque and passed -// unmodified to xos_critical_exit(). -// -// NOTE: This function is meant for use in OS code, not in applications. -//----------------------------------------------------------------------------- -__attribute__((always_inline)) -static inline uint32_t -xos_critical_enter(void) -{ -#if XCHAL_HAVE_INTERRUPTS - // This function cannot be called by high-level interrupt handlers, - // i.e. it can never be called with intlevel > XOS_MAX_OS_INTLEVEL. - // So, we do not need to check current intlevel because we will not - // ever be lowering it by setting it to XOS_MAX_OS_INTLEVEL. - // NOTE: sync after RSIL not needed. - return XT_RSIL(XOS_MAX_OS_INTLEVEL); -#else - return 0; -#endif -} - - -//----------------------------------------------------------------------------- -// Exit an OS critical section and restore CPU state. See the documentation -// for xos_critical_enter(). -// -// cflags Return value from xos_critical_enter(). -// Must be treated as an opaque value. -// -// Returns: Nothing. -// -// NOTE: This function is meant for use in OS code, not in applications. -//----------------------------------------------------------------------------- -__attribute__((always_inline)) -static inline void -xos_critical_exit(uint32_t cflags) -{ - xos_restore_int_pri_level(cflags); -} - -#endif // _XOS_INCLUDE_INTERNAL_ - - -// This file uses things defined above -#include "xos_syslog.h" - - -// Misc - -//----------------------------------------------------------------------------- -// Helper function to list all threads in system. Useful for debug. -//----------------------------------------------------------------------------- -void -xos_display_threads(void * arg, XosPrintFunc * print_fn); - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_common.h b/tools/sdk/include/esp32/xtensa/xos_common.h deleted file mode 100755 index 647cb7f457a..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_common.h +++ /dev/null @@ -1,362 +0,0 @@ - -// xos_common.h - Macros and definitions common to C and assembly code. - -// 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. - - -#ifndef __XOS_COMMON_H__ -#define __XOS_COMMON_H__ - -#ifdef __cplusplus -extern "C" { -#endif - - -#include -#include -#include - -#include "xos_params.h" - - -//----------------------------------------------------------------------------- -// Macros that help define structures for both C and assembler. -// These are somewhat different from the XTOS version in xtruntime-frames.h. -//----------------------------------------------------------------------------- -#if defined(_ASMLANGUAGE) || defined(__ASSEMBLER__) - -#define STRUCT_BEGIN .pushsection .text; .struct 0 -#define STRUCT_FIELD(ctype,size,asname,name) asname: .space size -#define STRUCT_AFIELD(ctype,size,asname,name,n) asname: .space (size)*(n) -#define STRUCT_END(sname) sname##Size:; .popsection - -#else - -#define STRUCT_BEGIN typedef struct { -#define STRUCT_FIELD(ctype,size,asname,name) ctype name; -#define STRUCT_AFIELD(ctype,size,asname,name,n) ctype name[n]; -#define STRUCT_END(sname) } sname; - -#endif //_ASMLANGUAGE || __ASSEMBLER__ - - -//----------------------------------------------------------------------------- -// Offsets relative to xos_globals. -//----------------------------------------------------------------------------- -#define XOS_INTLEVEL_MASK 0 // offset to the level mask -#define XOS_INTENABLE_MASK 4 // offset to the enable mask -#define XOS_CURR_THREADPTR 8 // offset to the current thread ptr -#define XOS_NEXT_THREADPTR 12 // offset to the next thread ptr -#define XOS_INTERRUPT_TABLE 16 // offset to the interrupt table - - -//----------------------------------------------------------------------------- -// Offsets for xos_interrupt_table[] entries. -//----------------------------------------------------------------------------- -#define XOS_INTTAB_HANDLER (XOS_INTERRUPT_TABLE+0) // ofs to interrupt handler -#define XOS_INTTAB_ARG (XOS_INTERRUPT_TABLE+4) // ofs to interrupt handler arg -#define XOS_INTTAB_PS (XOS_INTERRUPT_TABLE+8) // (hwpri) PS for interrupt level -#define XOS_INTTAB_LEVEL (XOS_INTERRUPT_TABLE+8) // (swpri) interrupt level (1..7) -#define XOS_INTTAB_PRI (XOS_INTERRUPT_TABLE+9) // (swpri) interrupt priority (0..255) -#define XOS_INTTAB_PRIMASK (XOS_INTERRUPT_TABLE+12) // (swpri) mask of higher pri. interrupts - - -//----------------------------------------------------------------------------- -// Exception/interrupt stack frame layout for a pre-empted thread -// tcb->resume_fn == &xos_resume_preempted_thread). -// Pointed to by thread->esf. Located just below thread's current stack ptr. -// Thread's a1 == thread->esf + XosExcFrameSize. -// NOTE: exception frame size is a multiple of 16. -//----------------------------------------------------------------------------- -STRUCT_BEGIN -STRUCT_AFIELD(long,4,FRAME_AREG,areg, 12) // a4-a15 (offsets 0 thru 44) - // (a1 is computed, a0,a2-a3 are in s32e range of a1) -//#if XCHAL_HAVE_LOOPS -STRUCT_FIELD (long,4,FRAME_LBEG,lbeg) -STRUCT_FIELD (long,4,FRAME_LEND,lend) -STRUCT_FIELD (long,4,FRAME_LCOUNT,lcount) -//#endif -//#if XCHAL_HAVE_MAC16 -STRUCT_FIELD (long,4,FRAME_ACCLO,acclo) -STRUCT_FIELD (char,1,FRAME_ACCHI,acchi) -//#endif -STRUCT_FIELD (char,1,FRAME_SAR,sar) -STRUCT_FIELD (short,2,FRAME_PAD0,pad0) // unused -STRUCT_FIELD (long,4,FRAME_EXCCAUSE,exccause) -STRUCT_FIELD (long,4,FRAME_EXCVADDR,excvaddr) -STRUCT_FIELD (long,4,FRAME_PAD1,pad1) // unused -- pad to make multiple of 16 bytes -STRUCT_FIELD (long,4,FRAME_PAD2,pad2) -STRUCT_FIELD (long,4,FRAME_PS,ps) // (XOS_FRAME_SIZE-44) in S32E range of end -STRUCT_FIELD (long,4,FRAME_PC,pc) // (XOS_FRAME_SIZE-40) in S32E range of end -STRUCT_FIELD (long,4,FRAME_A0,a0) -STRUCT_FIELD (long,4,FRAME_A2,a2) // (XOS_FRAME_SIZE-32) in S32E range of end -STRUCT_FIELD (long,4,FRAME_A3,a3) // (XOS_FRAME_SIZE-28) in S32E range of end -STRUCT_FIELD (long,4,FRAME_LEVELMASK,levelmask) // -STRUCT_FIELD (long,4,FRAME_NESTCHAIN,nestchain) // nested C function call chain ptr -// Caller's a0-a3 save area below SP. These fields MUST be the last ones in the -// struct so that they are guaranteed to be just under the original SP (before -// we allocate the exception frame). -STRUCT_AFIELD (long,4,FRAME_CWINSAVE,cwinsave, 4) // (XOS_FRAME_SIZE-16) -STRUCT_END(XosExcFrame) // NOTE: exception frame size is 128 - -#define FRAME_AR(x) (FRAME_AREG + x*4 - 16) - -#if defined(_ASMLANGUAGE) || defined(__ASSEMBLER__) -#define XOS_FRAME_SIZE XosExcFrameSize -#else -#define XOS_FRAME_SIZE sizeof(XosExcFrame) -#endif - - -//----------------------------------------------------------------------------- -// Stack frame layout for a cooperatively switched out thread -// (tcb->resume_fn == &xos_resume_cooperative_thread). -// Pointed to by thread->esf. This is a function frame. -// Thread's a1 == thread->esf. -//----------------------------------------------------------------------------- -STRUCT_BEGIN -STRUCT_FIELD (long,4,CFRAME_A0,a0) // return PC -STRUCT_FIELD (long,4,CFRAME_LEVELMASK,levelmask) -STRUCT_FIELD (long,4,CFRAME_PS,ps) -#ifdef __XTENSA_CALL0_ABI__ -STRUCT_FIELD (long,4,CFRAME_PAD0,pad0) -STRUCT_AFIELD(long,4,CFRAME_AREG,areg,4) // callee-saved regs a12-a15 -#endif -STRUCT_END(XosCoopFrame) - - -//----------------------------------------------------------------------------- -// Offsets into thread control block (must match xos_thread.h !!) -//----------------------------------------------------------------------------- -#define TCB_RESUME_FN 12 // ptr to thread resume asm sequence -#define TCB_STACK_ESF 16 // saved stack ptr (actually, ptr to ESF) -#define TCB_TIE_SAVE 20 // ptr to TIE save area -#define TCB_RETVALUE 24 // ptr to xos_block return value -#define TCB_STACK_END 36 // ptr to end of stack (thread's initial stack ptr) -#define TCB_STARTUP_ENTRY 40 // ptr to thread entry function -#define TCB_STARTUP_ARG 44 // ptr to thread entry function's arg -#define TCB_READY 48 // thread ready state (1 byte) -#define TCB_CLIB_PTR 108 // thread C lib context pointer - -#define TCB_RESUME_CCOUNT 116 // cycle count at last resume -#define TCB_CYCLE_COUNT 120 // number of cycles consumed -#define TCB_NORMAL_RESUMES 128 // number of cooperative/restart thread resumes -#define TCB_PREEMPT_RESUMES 132 // number of pre-emptive thread resumes - - -//----------------------------------------------------------------------------- -// Coprocessor state handling: -// The coprocessor state save area is allocated on the thread stack. The stack -// must be sized appropriately. Threads that do not use coprocessors need not -// allocate the storage area. -// -// Along with the save area for each coprocessor, two bitmasks with flags per -// coprocessor (laid out as in the CPENABLE reg) help manage context switching -// coprocessors as efficiently as possible: -// -// XT_CPENABLE -// The contents of a non-running thread's CPENABLE register. -// It represents the coprocessors owned (and whose state is still needed) -// by the thread. When a thread is preempted, its CPENABLE is saved here. -// When a thread solicits a context switch, its CPENABLE is cleared - the -// compiler has saved the (caller-saved) coprocessor state if needed. -// When a non-running thread loses ownership of a CP, its bit is cleared. -// When a thread runs, it's XT_CPENABLE is loaded into the CPENABLE reg. -// Avoids coprocessor exceptions when no change of ownership is needed. -// -// XT_CPSTORED -// A bitmask with the same layout as CPENABLE, a bit per coprocessor. -// Indicates whether the state of each coprocessor is saved in the state -// save area. When a thread enters the kernel, only the state of coprocs -// still enabled in CPENABLE is saved. When the coprocessor exception -// handler assigns ownership of a coprocessor to a thread, it restores -// the saved state only if this bit is set, and clears this bit. -// -// XT_CP_CS_ST -// A bitmask with the same layout as CPENABLE, a bit per co-processor. -// Indicates whether callee-saved state is saved in the state save area. -// Callee-saved state is saved by itself on a solicited context switch, -// and restored when needed by the coprocessor exception handler. -// Unsolicited switches will cause the entire coprocessor to be saved -// when necessary. -// -// XT_NCP_ASA -// Pointer to aligned save area for non-CP state. This is always filled -// in, even if there is no non-CP state to be saved. If there is no state -// to be saved then no space is actually allocated and this pointer is -// not used. -// -// XT_CP_ASA -// Pointer to aligned save area for coprocessor state. This is filled in -// only if coprocessor state is to be saved for the thread. Allows it to be -// aligned more than the overall save area (which might be stack-aligned -// or TCB-aligned). Especially relevant for Xtensa cores configured with a -// very large data path that requires alignment greater than 16 bytes (ABI -// stack alignment). -//----------------------------------------------------------------------------- - -#define ALIGNUP(n, val) (((val) + (n)-1) & -(n)) - -// Offsets of each coprocessor save area within the 'aligned save area'. -// The non-CP TIE state save area is at offset 0, so that it does not -// move around if some or all coprocessors are not to be saved. - -#define XT_NCP_SA 0 -#define XT_CP0_SA ALIGNUP(XCHAL_CP0_SA_ALIGN, XT_NCP_SA + XCHAL_NCP_SA_SIZE) -#define XT_CP1_SA ALIGNUP(XCHAL_CP1_SA_ALIGN, XT_CP0_SA + XCHAL_CP0_SA_SIZE) -#define XT_CP2_SA ALIGNUP(XCHAL_CP2_SA_ALIGN, XT_CP1_SA + XCHAL_CP1_SA_SIZE) -#define XT_CP3_SA ALIGNUP(XCHAL_CP3_SA_ALIGN, XT_CP2_SA + XCHAL_CP2_SA_SIZE) -#define XT_CP4_SA ALIGNUP(XCHAL_CP4_SA_ALIGN, XT_CP3_SA + XCHAL_CP3_SA_SIZE) -#define XT_CP5_SA ALIGNUP(XCHAL_CP5_SA_ALIGN, XT_CP4_SA + XCHAL_CP4_SA_SIZE) -#define XT_CP6_SA ALIGNUP(XCHAL_CP6_SA_ALIGN, XT_CP5_SA + XCHAL_CP5_SA_SIZE) -#define XT_CP7_SA ALIGNUP(XCHAL_CP7_SA_ALIGN, XT_CP6_SA + XCHAL_CP6_SA_SIZE) - -#define XT_TOT_SA_SIZE ALIGNUP(16, XT_CP7_SA + XCHAL_CP7_SA_SIZE) -#define XT_NCP_SA_SIZE XCHAL_NCP_SA_SIZE - -// Offsets within the overall save area - -#define XT_CPENABLE 0 // (2 bytes) coprocessors active for this thread -#define XT_CPSTORED 2 // (2 bytes) coprocessors saved for this thread -#define XT_CP_CS_ST 4 // (2 bytes) coprocessor callee-saved regs for this thread -#define XT_NCP_ASA 8 // (4 bytes) ptr to aligned save area for nonCP state -#define XT_CP_ASA 12 // (4 bytes) ptr to aligned save area for CP state - -// Overall size allows for dynamic alignment, make sure multiple of 4 bytes. -// XT_CP_SIZE - total space needed for all coprocessors + nonCP state + hdr -// XT_NCP_SIZE - total space needed for nonCP state + hdr - -#define XT_CP_SIZE ALIGNUP(4, (16 + XT_TOT_SA_SIZE + XCHAL_TOTAL_SA_ALIGN)) -#define XT_NCP_SIZE ALIGNUP(4, (16 + XT_NCP_SA_SIZE + XCHAL_TOTAL_SA_ALIGN)) - - -//----------------------------------------------------------------------------- -// Stack size computation. -// -// XOS_STACK_MIN_SIZE -// The minimum recommended stack size for any XOS thread. If you want to -// use a stack size smaller than this, you will have to verify that the -// smaller size will work under all operating conditions. -// -// XOS_STACK_MIN_SIZE_NO_CP -// The minimum recommended atack size for threads that will not use any -// coprocessor resources. No coprocessor state will be saved/restored -// for these threads. Non-CP TIE state will still be saved/restored. -// These threads must be created with the flag XOS_THREAD_NO_CP. -// -// XOS_STACK_EXTRA -// The amount of stack space used by the system to: -// - save coprocessor state -// - save non-coprocessor TIE state -// - allocate an interrupt/exception frame -// -// XOS_STACK_EXTRA_NO_CP -// The amount of stack space used by the system to: -// - save non-coprocessor TIE state -// - allocate an interrupt/exception frame -//----------------------------------------------------------------------------- - -#define XOS_STACK_EXTRA (XOS_FRAME_SIZE + XT_CP_SIZE) -#define XOS_STACK_EXTRA_NO_CP (XOS_FRAME_SIZE + XT_NCP_SIZE) - -#ifdef __XTENSA_CALL0_ABI__ -#define XOS_STACK_MIN_SIZE (XOS_STACK_EXTRA + 0x180) -#define XOS_STACK_MIN_SIZE_NO_CP (XOS_STACK_EXTRA_NO_CP + 0x180) -#else -#define XOS_STACK_MIN_SIZE (XOS_STACK_EXTRA + 0x200) -#define XOS_STACK_MIN_SIZE_NO_CP (XOS_STACK_EXTRA_NO_CP + 0x200) -#endif - - -//----------------------------------------------------------------------------- -// Items related to C library thread safety. -//----------------------------------------------------------------------------- -#if XOS_OPT_THREAD_SAFE_CLIB - -#if XSHAL_CLIB == XTHAL_CLIB_XCLIB - #if !defined(_ASMLANGUAGE) && !defined(__ASSEMBLER__) - #include - #endif - #define CLIB_THREAD_STRUCT struct _reent xclib_reent - #define GLOBAL_CLIB_PTR _reent_ptr -#elif XSHAL_CLIB == XTHAL_CLIB_NEWLIB - #if !defined(_ASMLANGUAGE) && !defined(__ASSEMBLER__) - #include - #endif - #define CLIB_THREAD_STRUCT struct _reent newlib_reent - #define GLOBAL_CLIB_PTR _impure_ptr -#else - #error The selected C runtime library is not thread safe. -#endif - -#endif // XOS_OPT_THREAD_SAFE_CLIB - - -//----------------------------------------------------------------------------- -// Check (MAX_OS_INTLEVEL,EXCM_LEVEL) -//----------------------------------------------------------------------------- -#if XOS_MAX_OS_INTLEVEL >= XCHAL_EXCM_LEVEL -# define XOS_MAX_OSEXCM_LEVEL XOS_MAX_OS_INTLEVEL -#else -# warning "XOS_MAX_OS_INTLEVEL was set below XCHAL_EXCM_LEVEL: this was never tested" -# define XOS_MAX_OSEXCM_LEVEL XCHAL_EXCM_LEVEL -#endif - - -//----------------------------------------------------------------------------- -// Detect if in interrupt context. -//----------------------------------------------------------------------------- -#if XCHAL_HAVE_INTERRUPTS -#define INTERRUPT_CONTEXT ((XT_RSR_PS() & PS_UM) == 0) -#else -#define INTERRUPT_CONTEXT 0 -#endif - - -//----------------------------------------------------------------------------- -// Xtensa tools version. -//----------------------------------------------------------------------------- -#if defined __XCC__ -#define XTTOOLS_VERSION (__XCC__ + __XCC_MINOR__) -#else -#define XTTOOLS_VERSION (0) -#endif - - -//----------------------------------------------------------------------------- -// Erratum workarounds. -//----------------------------------------------------------------------------- - -// Erratum 487 fix is available in version RF.3 onwards and RG.2 onwards. -#if ((__XCC__ == 11000) && (__XCC_MINOR__ >= 3)) || (XTTOOLS_VERSION >= 12002) -#define HWERR_487_FIX hw_erratum_487_fix -#else -#define HWERR_487_FIX -#endif - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_COMMON_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_cond.h b/tools/sdk/include/esp32/xtensa/xos_cond.h deleted file mode 100755 index 8116947d331..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_cond.h +++ /dev/null @@ -1,145 +0,0 @@ -/** @file */ - -// xos_cond.h - XOS condition variables API interface and data structures. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - -#ifndef __XOS_COND_H__ -#define __XOS_COND_H__ - -#include "xos_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -//----------------------------------------------------------------------------- -// -// Function pointer type for condition callbacks (defined in xos_thread.h) -// -// typedef int32_t (XosCondFunc)(void * arg, int32_t sig_value, XosThread * thread); -// -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -/// -/// Condition object. -/// -//----------------------------------------------------------------------------- -typedef struct XosCond { - XosThreadQueue queue; ///< Queue of waiters. -#if XOS_COND_DEBUG - uint32_t sig; // Signature indicates valid object. -#endif -} XosCond; - - -//----------------------------------------------------------------------------- -/// -/// Initialize a condition object before first use. The object must be -/// allocated by the caller. -/// -/// \param cond Pointer to condition object. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -void -xos_cond_create(XosCond * cond); - - -//----------------------------------------------------------------------------- -/// -/// Destroy a condition object. Must have been previously created by calling -/// xos_cond_create(). -/// -/// \param cond Pointer to condition object. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -void -xos_cond_delete(XosCond * cond); - - -//----------------------------------------------------------------------------- -/// -/// Wait on a condition: block until the condition is satisfied. The condition -/// is satisfied when xos_cond_signal() is called on this condition *and* the -/// condition callback function returns non-zero. If there is no callback -/// function, then the condition is automatically satisfied. -/// -/// The condition structure must have been initialized before first use by -/// calling xos_cond_create(). -/// -/// \param cond Pointer to condition object. -/// -/// \param cond_fn Pointer to a function, called by xos_cond_signal(), -/// that should return non-zero if this thread is to -/// be resumed. The function is invoked as: -/// `(*cond_fn)(cond_arg, sig_value)`. -/// -/// \param cond_arg Argument passed to cond_fn. -/// -/// \return Returns the value passed to xos_cond_signal(). -/// -//----------------------------------------------------------------------------- -int32_t -xos_cond_wait(XosCond * cond, XosCondFunc * cond_fn, void * cond_arg); - - -//----------------------------------------------------------------------------- -/// -/// Trigger the condition: wake all threads waiting on the condition, if their -/// condition function evaluates to true (non-zero). If there is no condition -/// function for a thread then it is automatically awakened. -/// -/// The condition structure must have been initialized before first use by -/// calling xos_cond_create(). -/// -/// \param cond Pointer to condition object. -/// -/// \param sig_value Value passed to all waiters, returned by -/// xos_cond_wait(). -/// -/// \return Returns the number of waiting threads that were resumed. -/// -/// NOTE: Signaling a condition that has no waiters has no effect on it, and -/// the signal is not remembered. Any thread that waits on it later must be -/// woken by another call to xos_cond_signal(). -/// -//----------------------------------------------------------------------------- -int32_t -xos_cond_signal(XosCond * cond, int32_t sig_value); - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_COND_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_errors.h b/tools/sdk/include/esp32/xtensa/xos_errors.h deleted file mode 100755 index 790cdde3bd3..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_errors.h +++ /dev/null @@ -1,107 +0,0 @@ -/** @file */ - -// xos_errors.h - XOS error codes. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - - -#ifndef __XOS_ERRORS_H__ -#define __XOS_ERRORS_H__ - -#include "xos_types.h" - - -#define _XOS_ERR_FIRST (-65536) -#define _XOS_ERR_LAST (-1) - - -//----------------------------------------------------------------------------- -/// -/// List of XOS error codes. All error codes are negative integers, except for -/// XOS_OK which is zero. -/// XOS error codes occupy the range from -65536 up to -1. -/// The function IS_XOS_ERRCODE() can be used to check if a value lies within -/// the error code range. -/// -//----------------------------------------------------------------------------- -typedef enum xos_err_t { - XOS_OK = 0, - - XOS_ERR_NOT_FOUND = _XOS_ERR_FIRST, ///< Object not found - XOS_ERR_INVALID_PARAMETER, ///< Function parameter is invalid - XOS_ERR_LIMIT, ///< Limit exceeded - XOS_ERR_NOT_OWNED, ///< Object not owned by caller - XOS_ERR_MUTEX_LOCKED, ///< Mutex is already locked - XOS_ERR_MUTEX_NOT_OWNED, ///< Mutex not owned by caller - XOS_ERR_MUTEX_ALREADY_OWNED, ///< Mutex already owned by caller - XOS_ERR_MUTEX_DELETE, ///< Mutex being waited on has been deleted - XOS_ERR_COND_DELETE, ///< Condition being waited on has been deleted - XOS_ERR_SEM_DELETE, ///< Semaphore being waited on has been deleted - XOS_ERR_SEM_BUSY, ///< Semaphore is not available - XOS_ERR_EVENT_DELETE, ///< Event being waited on has been deleted - XOS_ERR_MSGQ_FULL, ///< Message queue is full - XOS_ERR_MSGQ_EMPTY, ///< Message queue is empty - XOS_ERR_MSGQ_DELETE, ///< Message queue being waited on has been deleted - XOS_ERR_TIMER_DELETE, ///< Timer being waited on has been deleted - XOS_ERR_CONTAINER_NOT_RTC, ///< Containing thread not of RTC type - XOS_ERR_CONTAINER_NOT_SAME_PRI, ///< Containing thread not at same priority - XOS_ERR_STACK_TOO_SMALL, ///< Thread stack is too small - XOS_ERR_CONTAINER_ILLEGAL, ///< Illegal container thread - XOS_ERR_ILLEGAL_OPERATION, ///< This operation is not allowed - XOS_ERR_THREAD_EXITED, ///< The thread has already exited - XOS_ERR_NO_TIMER, ///< No suitable timer found - XOS_ERR_FEATURE_NOT_PRESENT, ///< This feature is disabled or not implemented - XOS_ERR_TIMEOUT, ///< Wait timed out - - XOS_ERR_UNHANDLED_INTERRUPT, ///< No handler for interrupt - XOS_ERR_UNHANDLED_EXCEPTION, ///< No handler for exception - XOS_ERR_INTERRUPT_CONTEXT, ///< Operation is illegal in interrupt context - XOS_ERR_THREAD_BLOCKED, ///< Thread already blocked - XOS_ERR_ASSERT_FAILED, ///< Runtime assertion failure - XOS_ERR_CLIB_ERR, ///< Error in C library thread safety module - XOS_ERR_INTERNAL_ERROR, ///< XOS internal error - - XOS_ERR_LAST = _XOS_ERR_LAST, -} xos_err_t; - - -//----------------------------------------------------------------------------- -/// -/// Check if a value is a valid XOS error code. -/// -/// \param val Value to check -/// -/// \return Returns nonzero if 'val' is in the XOS error code range. -/// -//----------------------------------------------------------------------------- -static inline int32_t -IS_XOS_ERRCODE(xos_err_t val) -{ - return ((val >= _XOS_ERR_FIRST) && (val <= _XOS_ERR_LAST)); -} - - -#endif // __XOS_ERRORS_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_event.h b/tools/sdk/include/esp32/xtensa/xos_event.h deleted file mode 100755 index 43219a2478d..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_event.h +++ /dev/null @@ -1,281 +0,0 @@ -/** @file */ - -// xos_event.h - XOS Event API interface and data structures. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - -#ifndef __XOS_EVENT_H__ -#define __XOS_EVENT_H__ - -#include "xos_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -//----------------------------------------------------------------------------- -// Defines. -//----------------------------------------------------------------------------- -#define XOS_EVENT_BITS_ALL 0xFFFFFFFF -#define XOS_EVENT_BITS_NONE 0 - - -//----------------------------------------------------------------------------- -// Event flags. -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -/// -/// Event object. -/// -//----------------------------------------------------------------------------- -typedef struct XosEvent { - XosThreadQueue waitq; ///< Queue of waiters. - uint32_t bits; ///< Event bits - uint32_t mask; ///< Specifies which bits are valid - uint16_t flags; ///< Properties. - uint16_t pad; ///< Padding -#if XOS_EVENT_DEBUG - uint32_t sig; // Valid signature indicates inited. -#endif -} XosEvent; - - -//----------------------------------------------------------------------------- -/// -/// Initialize an event object before first use. -/// -/// \param event Pointer to event object. -/// -/// \param mask Mask of active bits. Only these bits can be signaled. -/// -/// \param flags Creation flags (currently ignored, should be zero). -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -void -xos_event_create(XosEvent * event, uint32_t mask, uint32_t flags); - - -//----------------------------------------------------------------------------- -/// -/// Destroy an event object. Must have been previously created by calling -/// xos_event_create(). -/// -/// \param event Pointer to event object. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -void -xos_event_delete(XosEvent * event); - - -//----------------------------------------------------------------------------- -/// -/// Set the specified bits in the specified event. Propagates the bit states -/// to all waiting threads and wakes them if needed. -/// -/// \param event Pointer to event object. -/// -/// \param bits Mask of bits to set. Bits not set in the mask -/// will not be modified by this call. To set all -/// the bits in the event, use the constant -/// XOS_EVENT_BITS_ALL. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_set(XosEvent * event, uint32_t bits); - - -//----------------------------------------------------------------------------- -/// -/// Clear the specified bits in the specified event. Propagates the bit states -/// to all waiting threads and wakes them if needed. -/// -/// \param event Pointer to event object. -/// -/// \param bits Mask of bits to clear. Every bit that is set in -/// the mask will be cleared from the event. Bits -/// not set in the mask will not be modified by this -/// call. To clear all the bits in an event use the -/// constant XOS_EVENT_BITS_ALL. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_clear(XosEvent * event, uint32_t bits); - - -//----------------------------------------------------------------------------- -/// -/// Clear and set the specified bits in the specified event. The two steps are -/// combined into one update, so this is faster than calling xos_event_clear() -/// and xos_event_set() separately. Only one update is sent out to waiting -/// threads. -/// -/// \param event Pointer to event object. -/// -/// \param clr_bits Mask of bits to clear. The clear operation -/// happens before the set operation. -/// -/// \param set_bits Mask of bits to set. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_clear_and_set(XosEvent * event, uint32_t clr_bits, uint32_t set_bits); - - -//----------------------------------------------------------------------------- -/// -/// Get the current state of the event object. This is a snapshot of the state -/// of the event at this time. -/// -/// \param event Pointer to event object. -/// -/// \param pstate Pointer to a uint32_t variable where the state -/// will be returned. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_get(XosEvent * event, uint32_t * pstate); - - -//----------------------------------------------------------------------------- -/// -/// Wait until all the specified bits in the wait mask become set in the given -/// event object. -/// -/// \param event Pointer to event object. -/// -/// \param bits Mask of bits to test. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_wait_all(XosEvent * event, uint32_t bits); - - -//----------------------------------------------------------------------------- -/// -/// Wait until all the specified bits in the wait mask become set in the given -/// event object, or the timeout expires. -/// -/// \param event Pointer to event object. -/// -/// \param bits Mask of bits to test. -/// -/// \param to_cycles Timeout in cycles. Convert from time to cycles -/// using the helper functions provided in xos_timer. -/// A value of zero indicates no timeout. -/// -/// \return Returns XOS_OK on success, XOS_ERR_TIMEOUT on timeout, else -/// error code. -/// -/// NOTE: If XOS_OPT_WAIT_TIMEOUT is not enabled, then the timeout value is -/// ignored, and no timeout will occur. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_wait_all_timeout(XosEvent * event, uint32_t bits, uint64_t to_cycles); - - -//----------------------------------------------------------------------------- -/// -/// Wait until any of the specified bits in the wait mask become set in the -/// given event object. -/// -/// \param event Pointer to event object. -/// -/// \param bits Mask of bits to test. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_wait_any(XosEvent * event, uint32_t bits); - - -//----------------------------------------------------------------------------- -/// -/// Wait until any of the specified bits in the wait mask become set in the -/// event object, or the timeout expires. -/// -/// \param event Pointer to event object. -/// -/// \param bits Mask of bits to test. -/// -/// \param to_cycles Timeout in cycles. Convert from time to cycles -/// using the helper functions provided in xos_timer. -/// A value of zero indicates no timeout. -/// -/// \return Returns XOS_OK on success, XOS_ERR_TIMEOUT on timeout, else -/// error code. -/// -/// NOTE: If XOS_OPT_WAIT_TIMEOUT is not enabled, then the timeout value is -/// ignored, and no timeout will occur. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_wait_any_timeout(XosEvent * event, uint32_t bits, uint64_t to_cycles); - - -//----------------------------------------------------------------------------- -/// -/// Atomically set a specified group of bits, then wait for another specified -/// group of bits to become set. -/// -/// \param event Pointer to event object. -/// -/// \param set_bits Group of bits to set. -/// -/// \param wait_bits Group of bits to wait on. All the bits in the -/// group will have to get set before the wait is -/// satisfied. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_event_set_and_wait(XosEvent * event, uint32_t set_bits, uint32_t wait_bits); - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_EVENT_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_internal.h b/tools/sdk/include/esp32/xtensa/xos_internal.h deleted file mode 100755 index 5b8c8b46620..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_internal.h +++ /dev/null @@ -1,120 +0,0 @@ - -// 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. - - -#ifndef __XOS_INTERNAL_H__ -#define __XOS_INTERNAL_H__ - -#if !defined(__XOS_H__) || !defined(_XOS_INCLUDE_INTERNAL_) - #error "xos_internal.h must be included by defining _XOS_INCLUDE_INTERNAL_ before including xos.h" -#endif - -#include -#include "xos_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -// Use this macro to suppress compiler warnings for unused variables. - -#define UNUSED(x) (void)(x) - - -#if XOS_DEBUG - -#include -#include -# define DPRINTF printf - -#else - -# define DPRINTF(x...) do {} while(0) - -#endif - - -//----------------------------------------------------------------------------- -// Internal flags for thread creation. -//----------------------------------------------------------------------------- -#define XOS_THREAD_FAKE 0x8000 // Don't allocate stack (init and idle threads). - - -//----------------------------------------------------------------------------- -// Interrupt handler table entry. This structure defines one entry in the XOS -// interrupt handler table. -//----------------------------------------------------------------------------- -typedef struct XosIntEntry { - XosIntFunc * handler; // Pointer to handler function. - void * arg; // Argument passed to handler function. -#if XOS_OPT_INTERRUPT_SWPRI - unsigned char level; // Interrupt level. - unsigned char priority; // Interrupt priority. - short reserved; // Reserved. - unsigned int primask; // Mask of interrupts at higher priority. -#else - unsigned int ps; // Value of PS when running the handler. -#endif -} XosIntEntry; - - -//----------------------------------------------------------------------------- -// Extern variables. -//----------------------------------------------------------------------------- -extern unsigned xos_intlevel_mask; -extern unsigned xos_intenable_mask; -extern XosIntEntry xos_interrupt_table[XCHAL_NUM_INTERRUPTS]; - -extern uint32_t xos_clock_freq; -extern uint32_t xos_tick_period; -extern uint64_t xos_system_ticks; -extern uint64_t xos_system_cycles; -extern uint32_t xos_num_ctx_switches; - - -/* - -One thing I noticed is different between my initial idea of stack -assignments to RTC threads, when comparing to interrupts, is that I -expected each RTC thread priority to have its own stack, whereas -interrupts of different priorities share an interrupt stack. - -It's not really a difference in memory usage, because when assigning -multiple priorities to a stack, you have to add-up worst-case for -all priorities. One possible functional difference is that with -separate stacks per priority, it's possible to dynamically change -the priority of an RTC thread (while it's running). Not sure how -valuable that might be -- changing priority is useful with priority -inheritance, to avoid priority inversion, but I don't know how often -an RTC thread might acquire a lock (it couldn't block on acquiring a -lock in the usual sense -- it could get queued waiting and be restarted -when it becomes available, or use try_lock instead of lock). - -*/ - -#ifdef __cplusplus -} -#endif - -#endif /* __XOS_INTERNAL_H__ */ - diff --git a/tools/sdk/include/esp32/xtensa/xos_msgq.h b/tools/sdk/include/esp32/xtensa/xos_msgq.h deleted file mode 100755 index 30b9aa9032d..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_msgq.h +++ /dev/null @@ -1,278 +0,0 @@ -/** @file */ - -// xos_msgq.h - XOS Message Queue API and data structures. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - - -#ifndef __XOS_MSGQ_H__ -#define __XOS_MSGQ_H__ - -#include "xos_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -//----------------------------------------------------------------------------- -// XosMsgQueue is a multi-writer multi-reader message queue implementation. -// It is completely thread-safe and can be used by interrupt handlers. -// Interrupt handlers are guaranteed not to block when trying to send or -// receive a message. Messages are copied into the queue. The queue contains -// storage for a fixed number of messages defined at queue creation time. -// Messages must be a multiple of 4 bytes long (padded if necessary) and the -// message buffers must be 4-byte aligned. -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -// Message Queue flags. -//----------------------------------------------------------------------------- -#define XOS_MSGQ_WAIT_PRIORITY 0x0000 ///< Wake waiters in priority order (default) -#define XOS_MSGQ_WAIT_FIFO 0x0001 ///< Wake waiters in FIFO order -#define XOS_MSGQ_FULL 0x0002 // Queue is full -#define XOS_MSGQ_DELETED 0x8000 // Queue is deleted - - -//----------------------------------------------------------------------------- -/// -/// XosMsgQueue object. -/// -//----------------------------------------------------------------------------- -typedef struct XosMsgQueue { - uint16_t flags; ///< queue flags - uint16_t count; ///< # of messages queue can hold - uint32_t msize; ///< message size in bytes - uint16_t head; ///< write pointer - uint16_t tail; ///< read pointer - XosThreadQueue readq; ///< reader wait queue - XosThreadQueue writeq; ///< writer wait queue -#if XOS_MSGQ_DEBUG - uint32_t sig; // debug signature -#endif -#if XOS_OPT_MSGQ_STATS - uint32_t num_send; ///< # of messages put to queue - uint32_t num_recv; ///< # of messages taken from queue - uint32_t num_send_blks; ///< # of times thread blocked on send - uint32_t num_recv_blks; ///< # of times thread blocked on recv -#endif - uint32_t msg[1]; ///< first word of message buffer -} XosMsgQueue; - - -//----------------------------------------------------------------------------- -/// -/// Use these macros to statically or dynamically allocate a message queue. -/// XOS_MSGQ_ALLOC allocates a static queue, while XOS_MSGQ_SIZE can be used -/// to allocate memory via malloc() etc. -/// -/// Static: this allocates a queue named "testq", containing 10 messages, -/// each 16 bytes long. -/// -/// XOS_MSGQ_ALLOC(testq, 10, 16); -/// -/// Dynamic: this allocates a queue named "testq", containing 10 messages, -/// each 16 bytes long. -/// -/// XosMsgQueue * testq = malloc( XOS_MSGQ_SIZE(10, 16) ); -/// -/// \param name The queue name, i.e. the name of the pointer -/// to the queue. Used as the queue handle in -/// queue API calls. -/// -/// \param num Number of messages to allocate in queue. Must be > 0. -/// -/// \param size Message size in bytes. Must be > 0 and multiple of 4. -/// -//----------------------------------------------------------------------------- - -#define XOS_MSGQ_ALLOC(name, num, size) \ - static uint8_t name ## _buf[ sizeof(XosMsgQueue) + ((num) * (size)) ]; \ - XosMsgQueue * name = (XosMsgQueue *) name ## _buf; - -#define XOS_MSGQ_SIZE(num, size) \ - (sizeof(XosMsgQueue) + ((num) * (size))) - - -//----------------------------------------------------------------------------- -/// -/// Create the message queue object. Memory for the queue must be allocated by -/// the caller, either statically or via dynamic allocation. See the macros -/// XOS_MSGQ_ALLOC and XOS_MSGQ_SIZE for examples. -/// -/// \param msgq Handle (pointer) to message queue. -/// -/// \param num Number of messages allocated in queue. Must be > 0. -/// -/// \param size Message size in bytes. Must be > 0 and multiple of 4. -/// -/// \param flags Queue flags: -/// - XOS_MSGQ_WAIT_FIFO - blocked threads will be -/// woken in FIFO order. -/// - XOS_MSGQ_WAIT_PRIORITY - blocked threads will -/// be woken in priority order (default). -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_msgq_create(XosMsgQueue * msgq, uint16_t num, uint32_t size, uint16_t flags); - - -//----------------------------------------------------------------------------- -/// -/// Destroys the specified queue. Any waiting threads are unblocked with an -/// error return. Any messages in the queue will be lost. -/// -/// \param msgq Pointer to message queue. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_msgq_delete(XosMsgQueue * msgq); - - -//----------------------------------------------------------------------------- -/// -/// Put a message into the queue. The message contents are copied into the next -/// available message slot. If no space is available, this function will block -/// if called from a thread, but will return immediately if called from an -/// interrupt handler. -/// -/// \param msgq Pointer to message queue. -/// -/// \param msg Pointer to message buffer. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_msgq_put(XosMsgQueue * msgq, const uint32_t * msg); - - -//----------------------------------------------------------------------------- -/// -/// Put a message into the queue. The message contents are copied into the next -/// available message slot. If no space is available, this function will block -/// if called from a thread, but will return immediately if called from an -/// interrupt handler. The thread will be unblocked when space frees up in the -/// queue or the timeout expires. -/// -/// \param msgq Pointer to message queue. -/// -/// \param msg Pointer to message buffer. -/// -/// \param to_cycles Timeout in cycles. Convert from time to cycles -/// using the helper functions provided in xos_timer. -/// A value of zero indicates no timeout. -/// -/// \return Returns XOS_OK on success, XOS_ERR_TIMEOUT on timeout, else error code. -/// -/// NOTE: If XOS_OPT_WAIT_TIMEOUT is not enabled, then the timeout value is -/// ignored, and no timeout will occur. -/// -//----------------------------------------------------------------------------- -int32_t -xos_msgq_put_timeout(XosMsgQueue * msgq, const uint32_t * msg, uint64_t to_cycles); - - -//----------------------------------------------------------------------------- -/// -/// Get a message from the queue. The message contents are copied into the -/// buffer that must be provided. If no message is available, this function -/// will block if called from a thread, but will return immediately if called -/// from an interrupt handler. -/// -/// \param msgq Pointer to message queue. -/// -/// \param msg Pointer to message buffer. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_msgq_get(XosMsgQueue * msgq, uint32_t * msg); - - -//----------------------------------------------------------------------------- -/// -/// Get a message from the queue. The message contents are copied into the -/// buffer that must be provided. If no message is available, this function -/// will block if called from a thread, but will return immediately if called -/// from an interrupt handler. The thread will be unblocked when a message -/// arrives in the queue or the timeout expires. -/// -/// \param msgq Pointer to message queue. -/// -/// \param msg Pointer to message buffer. -/// -/// \param to_cycles Timeout in cycles. Convert from time to cycles -/// using the helper functions provided in xos_timer. -/// A value of zero indicates no timeout. -/// -/// \return Returns XOS_OK on success, XOS_ERR_TIMEOUT on timeout, else error code. -/// -/// NOTE: If XOS_OPT_WAIT_TIMEOUT is not enabled, then the timeout value is -/// ignored, and no timeout will occur. -/// -//----------------------------------------------------------------------------- -int32_t -xos_msgq_get_timeout(XosMsgQueue * msgq, uint32_t * msg, uint64_t to_cycles); - - -//----------------------------------------------------------------------------- -/// -/// Check if the queue is empty. -/// -/// \param msgq Pointer to message queue. -/// -/// \return Returns nonzero if queue is empty, zero if queue is not empty. -/// -//----------------------------------------------------------------------------- -int32_t -xos_msgq_empty(XosMsgQueue * msgq); - - -//----------------------------------------------------------------------------- -/// -/// Check if the queue is full. -/// -/// \param msgq Pointer to message queue. -/// -/// \return Returns nonzero if queue is full, zero if queue is not full. -/// -//----------------------------------------------------------------------------- -int32_t -xos_msgq_full(XosMsgQueue * msgq); - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_MSGQ_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_mutex.h b/tools/sdk/include/esp32/xtensa/xos_mutex.h deleted file mode 100755 index 9df5f9750b6..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_mutex.h +++ /dev/null @@ -1,205 +0,0 @@ -/** @file */ - -// xos_mutex.h - XOS Mutex API interface and data structures. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - -#ifndef __XOS_MUTEX_H__ -#define __XOS_MUTEX_H__ - -#include "xos_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -//----------------------------------------------------------------------------- -// Mutex flags. -//----------------------------------------------------------------------------- -#define XOS_MUTEX_WAIT_PRIORITY 0x0000 ///< Wake waiters in priority order (default) -#define XOS_MUTEX_WAIT_FIFO 0x0001 ///< Wake waiters in FIFO order -#define XOS_MUTEX_PRIORITY_CLG 0x0004 // Use priority ceiling -#define XOS_MUTEX_PRIORITY_INV 0x0008 // Protect against priority inversion - - -//----------------------------------------------------------------------------- -/// -/// XosMutex object. -/// -//----------------------------------------------------------------------------- -typedef struct XosMutex { - XosThread * owner; ///< Owning thread (null if unlocked). - XosThreadQueue waitq; ///< Queue of waiters. - uint32_t flags; ///< Properties. - uint32_t priority; - int32_t lock_count; ///< For recursive locking. -#if XOS_MUTEX_DEBUG - uint32_t sig; // Valid signature indicates inited. -#endif -} XosMutex; - - -//----------------------------------------------------------------------------- -/// -/// Initialize a mutex object before first use. -/// -/// \param mutex Pointer to mutex object. -/// -/// \param flags Creation flags: -/// - XOS_MUTEX_WAIT_FIFO -- Queue waiting threads -/// in fifo order. -/// - XOS_MUTEX_WAIT_PRIORITY -- Queue waiting threads -/// by priority. This is the default. -/// - XOS_MUTEX_PRIORITY_CLG -- Use specified priority -/// value as the mutex's priority ceiling. If the -/// owning thread has a priority lower than the mutex's -/// priority, then the thread will have its priority -/// raised to the higher value as long as it owns the -/// mutex. -/// - XOS_MUTEX_PRIORITY_INV -- Protect against priority -/// inversion. If there is a waiting thread with a -/// higher priority than the current owner thread, -/// then the owner thread's priority is raised to the -/// higher value for as long as it owns the mutex. -/// -/// \param priority Mutex's priority ceiling. This is used only if the -/// XOS_MUTEX_PRIORITY_CLG flag is set. -/// -/// \return Returns XOS_OK on success, else error code. -/// -/// NOTE: XOS_MUTEX_PRIORITY_CLG and XOS_MUTEX_PRIORITY_INV are NOT supported -/// in the current release. They will be supported in a future release. -/// -//----------------------------------------------------------------------------- -int32_t -xos_mutex_create(XosMutex * mutex, uint32_t flags, uint8_t priority); - - -//----------------------------------------------------------------------------- -/// -/// Destroy a mutex object. Must have been previously initialized by calling -/// xos_mutex_create(). -/// -/// \param mutex Pointer to mutex object. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_mutex_delete(XosMutex * mutex); - - -//----------------------------------------------------------------------------- -/// -/// Take ownership of the mutex: block until the mutex is owned. -/// The mutex must have been initialized. -/// -/// \param mutex Pointer to mutex object. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_mutex_lock(XosMutex * mutex); - - -//----------------------------------------------------------------------------- -/// -/// Take ownership of the mutex: block until the mutex is owned or the timeout -/// expires. The mutex must have been initialized. -/// -/// \param mutex Pointer to mutex object. -/// -/// \param to_cycles Timeout in cycles. Convert from time to cycles -/// using the helper functions provided in xos_timer. -/// A value of zero indicates no timeout. -/// -/// \return Returns XOS_OK on success, XOS_ERR_TIMEOUT on timeout, else error code. -/// -/// NOTE: If XOS_OPT_WAIT_TIMEOUT is not enabled, then the timeout value is -/// ignored, and no timeout will occur. -/// -//----------------------------------------------------------------------------- -int32_t -xos_mutex_lock_timeout(XosMutex * mutex, uint64_t to_cycles); - - -//----------------------------------------------------------------------------- -/// -/// Release ownership of the mutex. The mutex must have been initialized and -/// must be owned by the calling thread. -/// -/// \param mutex Pointer to mutex object. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_mutex_unlock(XosMutex * mutex); - - -//----------------------------------------------------------------------------- -/// -/// Try to take ownership of the mutex, but do not block if the mutex is taken. -/// Return immediately. The mutex must have been initialized. -/// -/// \param mutex Pointer to mutex object. -/// -/// \return Returns XOS_OK on success (mutex owned), else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_mutex_trylock(XosMutex * mutex); - - -//----------------------------------------------------------------------------- -/// -/// Return the state of the mutex (locked or unlocked) but do not attempt to -/// take ownership. The mutex must have been initialized. -/// -/// \param mutex Pointer to mutex object. -/// -/// \return Returns 0 if the mutex is unlocked, 1 if it is locked, -1 on error. -/// -//----------------------------------------------------------------------------- -static inline int32_t -xos_mutex_test(XosMutex * mutex) -{ - XOS_ASSERT(mutex); - - if (mutex != XOS_NULL) { - return (mutex->owner != XOS_NULL) ? 1 : 0; - } - return -1; -} - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_MUTEX_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_params.h b/tools/sdk/include/esp32/xtensa/xos_params.h deleted file mode 100755 index 3fca11f21a0..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_params.h +++ /dev/null @@ -1,276 +0,0 @@ -/** @file */ - -// xos_params.h - user-settable compile time parameters for XOS. - -// 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. - - -#ifndef __XOS_PARAMS_H__ -#define __XOS_PARAMS_H__ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -//----------------------------------------------------------------------------- -/// -/// Number of thread priority levels. At this time XOS supports a maximum of -/// 32 priority levels (0 - 31). -/// -//----------------------------------------------------------------------------- -#ifndef XOS_NUM_PRIORITY -#define XOS_NUM_PRIORITY 16 // Default is 16 -#endif - - -//----------------------------------------------------------------------------- -/// -/// Debug flags - Set to 1 to enable debug mode (and more verbose operation). -/// Can be set individually, or define XOS_DEBUG_ALL to enable all of them. -/// -/// - XOS_DEBUG -- Generic OS debug -/// - XOS_COND_DEBUG -- Condition objects debug -/// - XOS_EVENT_DEBUG -- Event objects debug -/// - XOS_MSGQ_DEBUG -- Message queue debug -/// - XOS_MUTEX_DEBUG -- Mutex objects debug -/// - XOS_SEM_DEBUG -- Semaphore objects debug -/// - XOS_THREAD_DEBUG -- Thread module debug -/// - XOS_TIMER_DEBUG -- Timer module debug -/// -/// WARNING: Enabling one or more of these flags will affect system performance -/// and timing. -/// -/// NOTE: Not all of these have been fully implemented. -/// -//----------------------------------------------------------------------------- -#if defined XOS_DEBUG_ALL - -#define XOS_DEBUG 1 -#define XOS_THREAD_DEBUG 1 -#define XOS_TIMER_DEBUG 1 -#define XOS_COND_DEBUG 1 -#define XOS_MUTEX_DEBUG 1 -#define XOS_SEM_DEBUG 1 -#define XOS_EVENT_DEBUG 1 -#define XOS_MSGQ_DEBUG 1 - -#else - -#ifndef XOS_DEBUG -#define XOS_DEBUG 0 -#endif -#ifndef XOS_THREAD_DEBUG -#define XOS_THREAD_DEBUG 0 -#endif -#ifndef XOS_TIMER_DEBUG -#define XOS_TIMER_DEBUG 0 -#endif -#ifndef XOS_COND_DEBUG -#define XOS_COND_DEBUG 0 -#endif -#ifndef XOS_MUTEX_DEBUG -#define XOS_MUTEX_DEBUG 0 -#endif -#ifndef XOS_SEM_DEBUG -#define XOS_SEM_DEBUG 0 -#endif -#ifndef XOS_EVENT_DEBUG -#define XOS_EVENT_DEBUG 0 -#endif -#ifndef XOS_MSGQ_DEBUG -#define XOS_MSGQ_DEBUG 0 -#endif - -#endif - - -//----------------------------------------------------------------------------- -/// -/// Set this option to 1 to enable runtime statistics collection for XOS. -/// NOTE: Enabling this option does have some impact on runtime performance -/// and OS footprint. -/// -//----------------------------------------------------------------------------- -#ifndef XOS_OPT_STATS -#define XOS_OPT_STATS 1 -#endif - - -//----------------------------------------------------------------------------- -/// -/// Set this option to 1 to enable statistics tracking for message queues. -/// enabling this will cause message queue objects to increase in size, and add -/// some overhead to message queue processing. -/// -//----------------------------------------------------------------------------- -#ifndef XOS_OPT_MSGQ_STATS -#define XOS_OPT_MSGQ_STATS 0 -#endif - - -//----------------------------------------------------------------------------- -/// -/// Size of interrupt stack in bytes. Shared by all interrupt handlers. Must be -/// sized to handle worst case nested interrupts. This is also used by the idle -/// thread so must exist even if interrupts are not configured. -/// -//----------------------------------------------------------------------------- -#ifndef XOS_INT_STACK_SIZE -#if XCHAL_HAVE_INTERRUPTS -#define XOS_INT_STACK_SIZE 8192 -#else -#define XOS_INT_STACK_SIZE 32 -#endif -#endif - - -//----------------------------------------------------------------------------- -/// -/// Default maximum interrupt level at which XOS primitives may be called. -/// It is the level at which interrupts are disabled by default. -/// See also description of xos_set_int_pri_level(). -/// -//----------------------------------------------------------------------------- -#ifndef XOS_MAX_OS_INTLEVEL -#define XOS_MAX_OS_INTLEVEL XCHAL_EXCM_LEVEL -#endif - - -//----------------------------------------------------------------------------- -/// -/// Set this to 1 to enable stack checking. The stack is filled with a pattern -/// on thread creation, and the stack is checked at certain times during system -/// operation. -/// WARNING: Enabling this option can have some impact on runtime performance. -/// -//----------------------------------------------------------------------------- -#ifndef XOS_OPT_STACK_CHECK -#if XOS_DEBUG -#define XOS_OPT_STACK_CHECK 1 -#else -#define XOS_OPT_STACK_CHECK 0 -#endif -#endif - - -//----------------------------------------------------------------------------- -/// -/// Set XOS_CLOCK_FREQ to the system clock frequency if this is known ahead of -/// time. Otherwise, call xos_set_clock_freq() to set it at run time. -/// -//----------------------------------------------------------------------------- -#ifndef XOS_CLOCK_FREQ -#define XOS_CLOCK_FREQ 1000000 -#endif -#define XOS_DEFAULT_CLOCK_FREQ XOS_CLOCK_FREQ - - -//----------------------------------------------------------------------------- -/// -/// Set this option to 1 to enable software prioritization of interrupts. The -/// priority scheme applied is that a higher interrupt number at the same level -/// will have higher priority. -/// -//----------------------------------------------------------------------------- -#ifndef XOS_OPT_INTERRUPT_SWPRI -#define XOS_OPT_INTERRUPT_SWPRI 1 -#endif - - -//----------------------------------------------------------------------------- -/// -/// Set this option to 1 to use the thread-safe version of the C runtime library. -/// You may need to enable this if you call C library functions from multiple -/// threads -- see the documentation for the relevant C library to determine if -/// this is necessary. This option increases the size of the TCB. -/// NOTE: At this time only the newlib and xclib libraries are supported for -/// thread safety. -/// -//----------------------------------------------------------------------------- -#include - -#ifndef XOS_OPT_THREAD_SAFE_CLIB - -#if XSHAL_CLIB == XTHAL_CLIB_XCLIB -#define XOS_OPT_THREAD_SAFE_CLIB 1 -#elif XSHAL_CLIB == XTHAL_CLIB_NEWLIB -#define XOS_OPT_THREAD_SAFE_CLIB 1 -#else -#define XOS_OPT_THREAD_SAFE_CLIB 0 -#endif - -#endif - - -//----------------------------------------------------------------------------- -/// -/// Set this option to 1 to enable the wait timeout feature. This allows waits -/// on waitable objects to expire after a specified timeout. -/// -//----------------------------------------------------------------------------- -#ifndef XOS_OPT_WAIT_TIMEOUT -#define XOS_OPT_WAIT_TIMEOUT 1 -#endif - - -//----------------------------------------------------------------------------- -/// -/// Set this option to 1 to enable threads waiting on timer objects. If this -/// feature is not used, turning it off will make timer objects smaller, and -/// reduce the time taken by timer expiry processing (by a small amount). -/// -//----------------------------------------------------------------------------- -#ifndef XOS_OPT_TIMER_WAIT -#define XOS_OPT_TIMER_WAIT 1 -#endif - - -//----------------------------------------------------------------------------- -/// -/// Set this option to 1 to enable time-slicing between multiple threads at the -/// same priority. If this option is enabled then on every timer tick the timer -/// handler will switch out the current thread if there is another ready thread -/// at the same priority, and allow the latter thread to run. Execution will be -/// round robin switched among all the threads at the same priority. -/// -/// Currently the time slice interval is fixed to be one timer tick. -/// -/// This feature is most useful if fixed duration timer ticks are used. -/// If dynamic ticking is enabled, then time slicing will work unpredictably -/// because the interval between ticks will vary. In some cases it may be -/// better to turn time slicing off. -/// -//----------------------------------------------------------------------------- -#ifndef XOS_OPT_TIME_SLICE -#define XOS_OPT_TIME_SLICE 1 -#endif - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_PARAMS_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_regaccess.h b/tools/sdk/include/esp32/xtensa/xos_regaccess.h deleted file mode 100755 index 1fea5ddc287..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_regaccess.h +++ /dev/null @@ -1,201 +0,0 @@ - -// xos_regaccess.h - Access routines for various processor special registers. - -// 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. - -#ifndef __REGACCESS_H__ -#define __REGACCESS_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "xos_types.h" - -#include - -#if defined (__XCC__) -#if XCHAL_HAVE_CCOUNT -#include -#endif -#endif - - -//----------------------------------------------------------------------------- -// Read CCOUNT register. -//----------------------------------------------------------------------------- -static __inline__ uint32_t xos_get_ccount(void) -{ -#if XCHAL_HAVE_CCOUNT - -#if defined (__XCC__) - return XT_RSR_CCOUNT(); -#else - uint32_t ccount; - - __asm__ __volatile__ ( "rsr %0, ccount" : "=a" (ccount) ); - return ccount; -#endif - -#else - - return 0; - -#endif -} - - -//----------------------------------------------------------------------------- -// Read CCOMPARE0 -//----------------------------------------------------------------------------- -static __inline__ uint32_t xos_get_ccompare0(void) -{ -#if XCHAL_HAVE_CCOUNT - -#if defined (__XCC__) - return XT_RSR_CCOMPARE0(); -#else - uint32_t ccompare0; - - __asm__ __volatile__ ( "rsr %0, ccompare0" : "=a" (ccompare0)); - return ccompare0; -#endif - -#else - - return 0; - -#endif -} - - -//----------------------------------------------------------------------------- -// Read CCOMPARE1 -//----------------------------------------------------------------------------- -#if (XCHAL_NUM_TIMERS > 1) -static __inline__ uint32_t xos_get_ccompare1(void) -{ -#if defined (__XCC__) - return XT_RSR_CCOMPARE1(); -#else - uint32_t ccompare1; - - __asm__ __volatile__ ( "rsr %0, ccompare1" : "=a" (ccompare1)); - return ccompare1; -#endif -} -#endif - - -//----------------------------------------------------------------------------- -// Read CCOMPARE2 -//----------------------------------------------------------------------------- -#if (XCHAL_NUM_TIMERS > 2) -static __inline__ uint32_t xos_get_ccompare2(void) -{ -#if defined (__XCC__) - return XT_RSR_CCOMPARE2(); -#else - uint32_t ccompare2; - - __asm__ __volatile__ ( "rsr %0, ccompare2" : "=a" (ccompare2)); - return ccompare2; -#endif -} -#endif - - -//----------------------------------------------------------------------------- -// Write CCOMPARE0 -//----------------------------------------------------------------------------- -static __inline__ void xos_set_ccompare0(uint32_t val) -{ -#if XCHAL_HAVE_CCOUNT - -#if defined (__XCC__) - XT_WSR_CCOMPARE0(val); - XT_ISYNC(); -#else - __asm__ __volatile__ ( - "wsr %0, ccompare0\n" - "isync" - : - : "a" (val) - ); -#endif - -#else - - // Empty - -#endif -} - - -//----------------------------------------------------------------------------- -// Write CCOMPARE1 -//----------------------------------------------------------------------------- -#if (XCHAL_NUM_TIMERS > 1) -static __inline__ void xos_set_ccompare1(uint32_t val) -{ -#if defined (__XCC__) - XT_WSR_CCOMPARE1(val); - XT_ISYNC(); -#else - __asm__ __volatile__ ( - "wsr %0, ccompare1\n" - "isync" - : - : "a" (val) - ); -#endif -} -#endif - - -//----------------------------------------------------------------------------- -// Write CCOMPARE2 -//----------------------------------------------------------------------------- -#if (XCHAL_NUM_TIMERS > 2) -static __inline__ void xos_set_ccompare2(uint32_t val) -{ -#if defined (__XCC__) - XT_WSR_CCOMPARE2(val); - XT_ISYNC(); -#else - __asm__ __volatile__ ( - "wsr %0, ccompare2\n" - "isync" - : - : "a" (val) - ); -#endif -} -#endif - - -#ifdef __cplusplus -} -#endif - -#endif // __REGACCESS_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_semaphore.h b/tools/sdk/include/esp32/xtensa/xos_semaphore.h deleted file mode 100755 index 42b7914ef06..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_semaphore.h +++ /dev/null @@ -1,190 +0,0 @@ -/** @file */ - -// xos_semaphore.h - XOS Semaphore API interface and data structures. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - -#ifndef __XOS_SEMAPHORE_H__ -#define __XOS_SEMAPHORE_H__ - -#include "xos_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -//----------------------------------------------------------------------------- -// Semaphore flags. -//----------------------------------------------------------------------------- -#define XOS_SEM_WAIT_PRIORITY 0x0000 ///< Wake waiters in priority order (default) -#define XOS_SEM_WAIT_FIFO 0x0001 ///< Wake waiters in FIFO order -#define XOS_SEM_PRIORITY_INV 0x0004 // Protect against priority inversion - - -//----------------------------------------------------------------------------- -/// -/// XosSem object. -/// -//----------------------------------------------------------------------------- -typedef struct XosSem { - uint32_t count; ///< Current count - XosThreadQueue waitq; ///< Queue of waiters. - uint32_t flags; ///< Properties. -#if XOS_SEM_DEBUG - uint32_t sig; // Valid signature indicates inited. -#endif -} XosSem; - - -//----------------------------------------------------------------------------- -/// -/// Initialize a semaphore object before first use. -/// -/// \param sem Pointer to semaphore object. -/// -/// \param flags Creation flags: -/// - XOS_SEM_WAIT_FIFO -- queue waiting threads in -/// fifo order. -/// - XOS_SEM_WAIT_PRIORITY -- queue waiting threads -/// by priority. This is the default. -/// - XOS_SEM_PRIORITY_INV -- protect against priority -/// inversion. -/// -/// \param initial_count Initial count for semaphore on creation. -/// -/// \return Returns XOS_OK on success, else error code. -/// -/// NOTE: XOS_SEM_PRIORITY_INV is NOT supported in the current release. It will -/// be supported in a future release. -/// -//----------------------------------------------------------------------------- -int32_t -xos_sem_create(XosSem * sem, uint32_t flags, uint32_t initial_count); - - -//----------------------------------------------------------------------------- -/// -/// Destroy a semaphore object. Must have been previously created by calling -/// xos_sem_create(). -/// -/// \param sem Pointer to semaphore object. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_sem_delete(XosSem * sem); - - -//----------------------------------------------------------------------------- -/// -/// Decrement the semaphore count: block until the decrement is possible. -/// The semaphore must have been initialized. -/// -/// \param sem Pointer to semaphore object. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_sem_get(XosSem * sem); - - -//----------------------------------------------------------------------------- -/// -/// Decrement the semaphore count: block until the decrement is possible or -/// the timeout expires. The semaphore must have been initialized. -/// -/// \param sem Pointer to semaphore object. -/// -/// \param to_cycles Timeout in cycles. Convert from time to cycles -/// using the helper functions provided in xos_timer. -/// A value of zero indicates no timeout. -/// -/// \return Returns XOS_OK on success, XOS_ERR_TIMEOUT on timeout, else error code. -/// -/// NOTE: If XOS_OPT_WAIT_TIMEOUT is not enabled, then the timeout value is -/// ignored, and no timeout will occur. -/// -//----------------------------------------------------------------------------- -int32_t -xos_sem_get_timeout(XosSem * sem, uint64_t to_cycles); - - -//----------------------------------------------------------------------------- -/// -/// Increment the semaphore count. The semaphore must have been initialized. -/// Remember that this action may wake up a waiting thread, and if that thread -/// is higher priority then there will be an immediate context switch. -/// -/// \param sem Pointer to semaphore object. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_sem_put(XosSem * sem); - - -//----------------------------------------------------------------------------- -/// -/// Try to decrement the semaphore, but do not block if the semaphore count is -/// zero. Return immediately. The semaphore must have been initialized. -/// -/// \param sem Pointer to semaphore object. -/// -/// \return Returns XOS_OK on success (semaphore decremented), else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_sem_tryget(XosSem * sem); - - -//----------------------------------------------------------------------------- -/// -/// Return the count of the semaphore but do not attempt to decrement it. -/// The semaphore must have been initialized. -/// -/// \param sem Pointer to semaphore object. -/// -/// \return Returns semaphore count, -1 on error. -/// -//----------------------------------------------------------------------------- -static inline int32_t -xos_sem_test(XosSem * sem) -{ - XOS_ASSERT(sem); - - return sem ? sem->count : -1; -} - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_SEMAPHORE_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_stopwatch.h b/tools/sdk/include/esp32/xtensa/xos_stopwatch.h deleted file mode 100755 index bf71cc388be..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_stopwatch.h +++ /dev/null @@ -1,175 +0,0 @@ -/** @file */ - -// xos_stopwatch.h - XOS Stopwatch objects and related API. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - - -#ifndef __XOS_STOPWATCH_H__ -#define __XOS_STOPWATCH_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "xos_types.h" -#include "xos_params.h" - - -//----------------------------------------------------------------------------- -// A stopwatch object can be used to track elapsed time and accumulate total -// elapsed time over multiple execution periods. The stopwatch records the -// time whenever its start function is called, and stops recording the time -// when the stop function is called and updates its cumulative time counter. -// The stopwatch keeps time in cycles. This can be converted to seconds etc. -// by using the XOS conversion calls such as xos_cycles_to_secs(). -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -/// -/// XosStopwatch object. -/// -//----------------------------------------------------------------------------- -typedef struct XosStopwatch { - uint64_t total; ///< Total accumulated cycle count - uint64_t start; ///< Starting system cycle count - uint16_t active; ///< Active flag (nonzero when active) -} XosStopwatch; - - -//----------------------------------------------------------------------------- -/// -/// Initialize a stopwatch object. -/// -/// \param sw Pointer to a stopwatch object. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -static inline void -xos_stopwatch_init(XosStopwatch * sw) -{ - sw->total = 0; - sw->start = 0; - sw->active = 0; -} - - -//----------------------------------------------------------------------------- -/// -/// Start a stopwatch. Starts cycle counting. -/// Note that this does not necessarily start counting from zero. The current -/// run (start-to-stop interval) will just get added to the accumulated count -/// in the stopwatch if any. -/// To reset the accumulated count, use xos_stopwatch_clear(). -/// -/// \param sw Pointer to a stopwatch object. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -static inline void -xos_stopwatch_start(XosStopwatch * sw) -{ - XOS_ASSERT(!sw->active); - sw->active = 1; - sw->start = xos_get_system_cycles(); -} - - -//----------------------------------------------------------------------------- -/// -/// Stop a stopwatch. Stops cycle counting and updates total. -/// -/// \param sw Pointer to a stopwatch object. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -static inline void -xos_stopwatch_stop(XosStopwatch * sw) -{ - XOS_ASSERT(sw->active); - sw->active = 0; - sw->total += xos_get_system_cycles() - sw->start; -} - - -//----------------------------------------------------------------------------- -/// -/// Get stopwatch accumulated count. -/// -/// \param sw Pointer to a stopwatch object. -/// -/// \return Returns the accumulated count. -/// -//----------------------------------------------------------------------------- -static inline uint64_t -xos_stopwatch_count(XosStopwatch * sw) -{ - return sw->total; -} - - -//----------------------------------------------------------------------------- -/// -/// Get elapsed time since stopwatch was started. If not started, returns zero. -/// -/// \param sw Pointer to a stopwatch object. -/// -/// \return Returns elapsed time in cycles. -/// -//----------------------------------------------------------------------------- -static inline uint64_t -xos_stopwatch_elapsed(XosStopwatch * sw) -{ - return sw->active ? xos_get_system_cycles() - sw->start : 0; -} - - -//----------------------------------------------------------------------------- -/// -/// Clears a stopwatch. Resets the accumulated count to zero, and deactivates -/// it if active. -/// -/// \param sw Pointer to a stopwatch object. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -static inline void -xos_stopwatch_clear(XosStopwatch * sw) -{ - xos_stopwatch_init(sw); -} - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_STOPWATCH_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_syslog.h b/tools/sdk/include/esp32/xtensa/xos_syslog.h deleted file mode 100755 index be56968fcea..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_syslog.h +++ /dev/null @@ -1,330 +0,0 @@ -/** @file */ - -// xos_syslog.h - XOS Event logging module. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - - -#ifndef __XOS_SYSLOG_H__ -#define __XOS_SYSLOG_H__ - -#include "xos_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -//----------------------------------------------------------------------------- -// The XOS system log is an array of fixed size entries. The size of the log -// is determined by the application, and memory for the log must be provided -// at init time. Every time the log function is called, an entry is made in -// the log and the next pointer advanced. When the log is full, it will wrap -// around and start overwriting the oldest entries. -// Logging can be done from C/C++ code as well as assembly code, and at any -// interrupt level, even from high level interrupt handlers. -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -// Defines. -//----------------------------------------------------------------------------- -#define XOS_SYSLOG_ENABLED 0x0001 - - -///---------------------------------------------------------------------------- -/// -/// Use this macro to compute how much memory to allocate for the syslog. -/// -///---------------------------------------------------------------------------- -#define XOS_SYSLOG_SIZE(num_entries) \ - ( sizeof(XosSysLog) + ((num_entries - 1) * sizeof(XosSysLogEntry)) ) - - -///---------------------------------------------------------------------------- -/// -/// System log entry structure. -/// -///---------------------------------------------------------------------------- -typedef struct XosSysLogEntry { - uint32_t timestamp; ///< Timestamp in clock cycles - uint32_t param1; ///< User defined value - uint32_t param2; ///< User defined value - struct XosSysLogEntry * next; ///< Link to next entry -} XosSysLogEntry; - - -///---------------------------------------------------------------------------- -/// -/// System log structure. -/// -///---------------------------------------------------------------------------- -typedef struct XosSysLog { - uint16_t flags; ///< Flags - uint16_t size; ///< Number of entries - XosSysLogEntry * next; ///< Next write position - XosSysLogEntry entries[1]; ///< First entry -} XosSysLog; - - -//----------------------------------------------------------------------------- -// Pointer to syslog area. -//----------------------------------------------------------------------------- -extern XosSysLog * xos_syslog; - - -//---------------------------------------------------------------------------- -/// -/// Initialize the syslog. Initializing the log also enables it. The system -/// log always wraps around when full and overwrites the oldest entries. -/// -/// \param log_mem Pointer to allocated memory for the log. -/// -/// \param num_entries The number of entries that the log can contain. -/// -/// \return Returns nothing. -/// -//---------------------------------------------------------------------------- -static inline void -xos_syslog_init(void * log_mem, uint16_t num_entries) -{ - uint16_t i; - - xos_syslog = (XosSysLog *) log_mem; - xos_syslog->size = num_entries; - xos_syslog->next = xos_syslog->entries; - - for (i = 0; i < num_entries - 1; i++) { - xos_syslog->entries[i].next = &(xos_syslog->entries[i+1]); - xos_syslog->entries[i].timestamp = 0; - } - xos_syslog->entries[i].next = xos_syslog->entries; - xos_syslog->entries[i].timestamp = 0; - - xos_syslog->flags = XOS_SYSLOG_ENABLED; -} - - -///---------------------------------------------------------------------------- -/// -/// Reset the syslog. All entries made up to now are abandoned and the write -/// pointer is set to the first entry location. -/// -/// No parameters. -/// -/// \return Returns nothing. -/// -///---------------------------------------------------------------------------- -static inline void -xos_syslog_clear() -{ -#if XCHAL_HAVE_INTERRUPTS - uint32_t ps = XT_RSIL(XCHAL_NUM_INTLEVELS); -#endif - - xos_syslog_init(xos_syslog, xos_syslog->size); -#if XCHAL_HAVE_INTERRUPTS - xos_restore_int_pri_level(ps); -#endif -} - - -///---------------------------------------------------------------------------- -/// -/// Enable logging to the syslog. This function needs to be called only if -/// logging had been previously disabled via xos_syslog_disable(), since -/// initializing the syslog automatically enables it. -/// -/// No parameters. -/// -/// \return Returns nothing. -/// -///---------------------------------------------------------------------------- -static inline void -xos_syslog_enable() -{ -#if XCHAL_HAVE_INTERRUPTS - uint32_t ps = XT_RSIL(XCHAL_NUM_INTLEVELS); -#endif - - xos_syslog->flags |= XOS_SYSLOG_ENABLED; -#if XCHAL_HAVE_INTERRUPTS - xos_restore_int_pri_level(ps); -#endif -} - - -///---------------------------------------------------------------------------- -/// -/// Disable logging to the syslog. It is sometimes useful to disable logging -/// while the log is being examined or dumped. -/// -/// No parameters. -/// -/// \return Returns nothing. -/// -///---------------------------------------------------------------------------- -static inline void -xos_syslog_disable() -{ -#if XCHAL_HAVE_INTERRUPTS - uint32_t ps = XT_RSIL(XCHAL_NUM_INTLEVELS); -#endif - xos_syslog->flags &= ~XOS_SYSLOG_ENABLED; -#if XCHAL_HAVE_INTERRUPTS - xos_restore_int_pri_level(ps); -#endif -} - - -///---------------------------------------------------------------------------- -/// -/// Write an entry into the syslog. This function does disable all interrupts -/// since logging can be done from interrupt handlers as well. It will write -/// into the log only if the log exists and is enabled. -/// -/// \param param1 User defined value. -/// -/// \param param2 User defined value. -/// -/// \return Returns nothing. -/// -///---------------------------------------------------------------------------- -static inline void -xos_syslog_write(uint32_t param1, uint32_t param2) -{ - if (xos_syslog != XOS_NULL) { -#if XCHAL_HAVE_INTERRUPTS - uint32_t ps = XT_RSIL(XCHAL_NUM_INTLEVELS); -#endif - - if ((xos_syslog->flags & XOS_SYSLOG_ENABLED) != 0) { - XosSysLogEntry * next = xos_syslog->next; - - next->timestamp = xos_get_ccount(); - next->param1 = param1; - next->param2 = param2; - - xos_syslog->next = next->next; - } - -#if XCHAL_HAVE_INTERRUPTS - xos_restore_int_pri_level(ps); -#endif - } -} - - -///---------------------------------------------------------------------------- -/// -/// Read the first (oldest) entry in the syslog. Will return an error if the -/// log has not been created or is empty. Storage to copy the entry must be -/// provided by the caller. -/// -/// \param entry Pointer to storage where the entry data will be -/// copied. This pointer must be passed to -/// xos_syslog_get_next(). -/// -/// \return Returns XOS_OK on success, else error code. -/// -///---------------------------------------------------------------------------- -static inline int32_t -xos_syslog_get_first(XosSysLogEntry * entry) -{ - if (xos_syslog == XOS_NULL) { - return XOS_ERR_NOT_FOUND; - } - - if (entry != XOS_NULL) { -#if XCHAL_HAVE_INTERRUPTS - uint32_t ps = XT_RSIL(XCHAL_NUM_INTLEVELS); -#endif - XosSysLogEntry * next = xos_syslog->next; - - // 'next' should be pointing to the next entry to be overwritten, if we - // have wrapped. This means it is the oldest entry. However if this entry - // has a zero timestamp then we have not wrapped, in which case we must - // look at the first entry in the list. - if (next->timestamp == 0) { - next = xos_syslog->entries; - } - - *entry = *next; -#if XCHAL_HAVE_INTERRUPTS - xos_restore_int_pri_level(ps); -#endif - return entry->timestamp ? XOS_OK : XOS_ERR_NOT_FOUND; - } - - return XOS_ERR_INVALID_PARAMETER; -} - - -///---------------------------------------------------------------------------- -/// -/// Get the next sequential entry from the syslog. This function must be called -/// only after xos_syslog_get_first() has been called. -/// -/// \param entry Pointer to storage where entry data will be copied. -/// Must be the same pointer that was passed in the call -/// to xos_syslog_get_first(), as it is used to keep track -/// of the current position. -/// -/// \return Returns XOS_OK on success, else error code. -/// -///---------------------------------------------------------------------------- -static inline int32_t -xos_syslog_get_next(XosSysLogEntry * entry) -{ - if (entry != XOS_NULL) { -#if XCHAL_HAVE_INTERRUPTS - uint32_t ps = XT_RSIL(XCHAL_NUM_INTLEVELS); -#endif - XosSysLogEntry * next = entry->next; - int32_t ret = XOS_OK; - - // Make sure we're not pointing past the last entry. - if ((next != XOS_NULL) && (next != xos_syslog->next) && (next->timestamp != 0)) { - *entry = *next; - } - else { - ret = XOS_ERR_NOT_FOUND; - } -#if XCHAL_HAVE_INTERRUPTS - xos_restore_int_pri_level(ps); -#endif - return ret; - } - - return XOS_ERR_INVALID_PARAMETER; -} - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_SYSLOG_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_thread.h b/tools/sdk/include/esp32/xtensa/xos_thread.h deleted file mode 100755 index 8bc5077eca5..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_thread.h +++ /dev/null @@ -1,1086 +0,0 @@ -/** @file */ - -// xos_thread.h - XOS Thread API interface and data structures. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - - -#ifndef __XOS_THREAD_H__ -#define __XOS_THREAD_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "xos_types.h" -#include "xos_params.h" - - -//----------------------------------------------------------------------------- -// Number of thread priority levels. -//----------------------------------------------------------------------------- -#ifndef XOS_NUM_PRIORITY -#error "XOS_NUM_PRIORITY must be defined (in xos_params.h)." -#endif -#if XOS_NUM_PRIORITY > 32 -#error "The number of thread priority levels (XOS_NUM_PRIORITY) must be <= 32." -#endif -#define XOS_MAX_PRIORITY (XOS_NUM_PRIORITY) - - -//----------------------------------------------------------------------------- -// Macro for thread self pointer. -//----------------------------------------------------------------------------- -#define XOS_THREAD_SELF (xos_thread_id()) - - -//----------------------------------------------------------------------------- -/// -/// Thread entry function pointer type. -/// -//----------------------------------------------------------------------------- -typedef int32_t (XosThreadFunc)(void * arg, int32_t wake_value); - - -//----------------------------------------------------------------------------- -// Thread switcher function signature. -//----------------------------------------------------------------------------- -typedef struct XosThread XosThread; -typedef int32_t (XosSwitchFunc)(XosThread *); - - -//----------------------------------------------------------------------------- -/// -/// Condition evaluation callback function pointer type. -/// -//----------------------------------------------------------------------------- -typedef int32_t (XosCondFunc)(void * arg, int32_t sig_value, XosThread * thread); - - -//----------------------------------------------------------------------------- -/// -/// Thread exit handler function pointer type. -/// -//----------------------------------------------------------------------------- -typedef int32_t (XosThdExitFunc)(int32_t exitcode); - - -//----------------------------------------------------------------------------- -// Thread queue structure. Used to implement the ready queues as well -// as the wait queues. -//----------------------------------------------------------------------------- -typedef struct XosThreadQueue { - XosThread * head; // Pointer to first thread in queue, or 0 if none. - XosThread ** tail; // Pointer to last thread's r_next pointer, or - // to "head" if none. -} XosThreadQueue; - - -//----------------------------------------------------------------------------- -// Stack frame for a thread that is not running. That is, it has either -// been preempted or has yielded. -//----------------------------------------------------------------------------- -typedef union XosFrame { - XosExcFrame e; // resume_fn == &xos_resume_preempted_thread - XosCoopFrame c; // resume_fn == &xos_resume_cooperative_thread - // nothing for resume_fn == &xos_resume_idle_thread - // nothing for resume_fn == &xos_resume_by_restart -} XosFrame; - - -//----------------------------------------------------------------------------- -// Thread Control Block. Tracks the state and control information associated -// with a thread. -// -// IMPORTANT: keep this in sync with TCB_*** offsets in xos_common.h . -//----------------------------------------------------------------------------- -struct XosThread { - XosThread * r_next; // 00 Next thread in queue (eg. ready queue of - // its priority, or some queue of blocked threads) - // Should be NULL if not in any queue. - - XosThread ** r_pprev; // 04 Points to previous queue entry's r_next - // pointer (i.e. to itself), or to queue head - // if first in queue. NULL if not in any queue. - - XosThread * all_next; // 08 Next in list of all threads. - - void * resume_fn; // 12 Pointer to the routine to be called to - // resume this thread. On entry to such code: - // a2 == xos_curr_threadptr (thread being resumed) - // a3 == &xos_globals - - XosFrame * esf; // 16 Pointer to saved exception stack frame, - // just below thread's current stack pointer. - // For RTC threads, this is valid only while the - // thread is preempted, not when it is blocked. - - void * tie_save; // 20 TIE state save area. May be NULL if there - // is not TIE state saved for this thread. - - int32_t wake_value; // 24 Value returned from block call (by wake call) - // (for RTC: pass this to start function??) - - XosSwitchFunc * switch_fn; // 28 Pointer to a function that - // can be called from within this thread, to save - // this thread's state and switch to a specified - // other thread. Returns wake value. - - void * stack_base; // 32 Base of stack as specified by thread creator. - - void * stack_end; // 36 End of stack (adjusted for TIE state save area - // if any). - - XosThreadFunc * entry; // 40 Pointer to thread entry function. Used for - // RTC thread restart. - - void * arg; // 44 Argument value passed to entry function. - - bool ready; // 48 Set when thread is ready to run, and is in - // its priority queue (i.e. r_pprev is set when - // this flag is set). - - bool in_exit; // Exit flag, nonzero when in exit processing. - - int8_t priority; // Thread priority, 0 .. (XOS_MAX_PRI - 1). Higher - // numbers have higher priority. This must only be - // changed when thread is not ready, or by calling - // xos_thread_set_priority(). - - int8_t preempt_pri; // This thread's preemption blocking priority. - // (preempt_pri >= priority). A thread's priority - // must be higher than another's preempt_pri to be - // able to preempt it. Note that preempt_pri can - // change during runtime e.g. due to priority - // inheritance. - - uint32_t flags; // 52 Thread creation flags. - - const char * name; // 56 Thread name (mainly for debug). - - const char * block_cause; // 60 Reason for blocking. Valid only when thread - // not ready (r_pprev == 0). - - XosThread * container; // 64 Thread whose stack will be used to run - // this thread. Valid for RTC threads only, else NULL. - - XosThdExitFunc * exit_func; // 68 Thread exit handler function pointer. - - XosThreadQueue exit_waiters; // 72 Queue of threads waiting for this one to exit. - - XosThreadQueue * wq_ptr; // 80 If this thread is in a wait queue, this - // points to the queue. Must be NULL when - // thread not in a queue. - - XosCondFunc * cond_fn; // 84 Condition function. Valid only while thread - // is blocked on condition. - - void * cond_arg; // 88 Argument to be passed to condition function. - - uint16_t cp_mask; // 92 Mask of coprocessors used. - uint16_t cp_saved; // 94 Mask of coprocessors saved. - - uint32_t event_bits; // 96 event bits - uint32_t event_mask; // 100 event bit mask - uint32_t event_flags; // 104 event flags - - void * clib_ptr; // 108 Pointer to C lib context struct. - - uint32_t sig; // 112 Signature of valid TCB - - uint32_t resume_ccount; // 116 cycle count at resume - uint64_t cycle_count; // 120 number of cycles consumed (approx). - // NOTE: must be 8-byte aligned - uint32_t normal_resumes; // 128 Number of non-preemptive resumptions. - uint32_t preempt_resumes;// 132 Number of preemptive resumptions. - -#if XOS_OPT_THREAD_SAFE_CLIB - CLIB_THREAD_STRUCT; // C library context area. -#endif -}; - - -//----------------------------------------------------------------------------- -// User-visible flags for xos_thread_create(). -//----------------------------------------------------------------------------- -#define XOS_THREAD_SUSPEND 0x0001 ///< Create suspended instead of ready -#define XOS_THREAD_RTC 0x0002 ///< Run-to-completion thread -#define XOS_THREAD_NO_CP 0x0004 ///< Thread does not use coprocessors - - -//----------------------------------------------------------------------------- -// Flags used by thread creation extra parameters. -//----------------------------------------------------------------------------- -#define XOS_TP_COPROC_MASK 0x0001 -#define XOS_TP_PREEMPT_PRI 0x0002 -#define XOS_TP_EXIT_HANDLER 0x0004 - - -//----------------------------------------------------------------------------- -// Thread creation extra parameters. -//----------------------------------------------------------------------------- -typedef struct XosThreadParm { - uint32_t parms_mask; // Combination of XOS_TP_xxx flags indicating - // which parameters are valid. - - uint16_t cp_mask; // Mask of coprocessors the thread can access. - - uint32_t preempt_pri; // Initial preemption blocking priority. Can be - // changed later via xos_thread_set_priority(). - - XosThdExitFunc * handler; // Exit handler function. - -} XosThreadParm; - - -//----------------------------------------------------------------------------- -// Wrapper struct for RTC (run to completion) thread. -//----------------------------------------------------------------------------- -typedef struct XosRtcThread { - struct XosThread thread; -} XosRtcThread; - - -//----------------------------------------------------------------------------- -// External variables. -//----------------------------------------------------------------------------- -extern XosThread * xos_curr_threadptr; // Current active thread -extern XosThread * xos_next_threadptr; // Next ready thread -extern XosThread * xos_all_threads; // List of all threads - - -//----------------------------------------------------------------------------- -/// -/// Set thread creation parameter: the group of coprocessors that this thread -/// will use. This must be set during thread creation, and cannot be changed -/// after the thread has been created. Defining this allows reduction of -/// memory usage (for CP state saving) in some circumstances, and can also -/// speed up the context switch time. -/// -/// NOTE: Support for this is not currently implemented. If a thread uses -/// any coprocessor, space for all coprocessors must be reserved. -/// -/// \param parms Thread creation parameter structure. Must be -/// allocated by the caller. -/// -/// \param cp_mask Bitmask of coprocessors thread is allowed to -/// use. Bit 0 for coprocessor 0, etc. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -static inline void -xos_threadp_set_cp_mask(XosThreadParm * parms, uint16_t cp_mask) -{ - if (parms != XOS_NULL) { - parms->parms_mask |= XOS_TP_COPROC_MASK; - parms->cp_mask = cp_mask; - } -} - - -//----------------------------------------------------------------------------- -/// -/// Set thread creation parameter: thread pre-emption priority. -/// -/// \param parms Thread creation parameter structure. Must be -/// allocated by caller. -/// -/// \param preempt_pri Thread pre-emption blocking priority. -/// From 0 .. XOS_NUM_PRIORITY - 1. -/// Must be greater or equal to the thread priority -/// (if not, is automatically set to thread priority). -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -static inline void -xos_threadp_set_preemption_priority(XosThreadParm * parms, int8_t preempt_pri) -{ - if (parms != XOS_NULL) { - parms->parms_mask |= XOS_TP_PREEMPT_PRI; - parms->preempt_pri = preempt_pri; - } -} - - -//----------------------------------------------------------------------------- -/// -/// Set thread creation parameter: thread exit handler. -/// -/// \param parms Thread creation parameter structure. Must be -/// allocated by caller. -/// -/// \param handler Exit handler function. -/// -/// \return Returns nothing. -//----------------------------------------------------------------------------- -static inline void -xos_threadp_set_exit_handler(XosThreadParm * parms, XosThdExitFunc * handler) -{ - if (parms != XOS_NULL) { - parms->parms_mask |= XOS_TP_EXIT_HANDLER; - parms->handler = handler; - } -} - - -//----------------------------------------------------------------------------- -/// -/// Create a new thread. If the thread is not created suspended, then it will -/// be made ready as soon as it is created, and will immediately run if it is -/// the highest priority non-blocked thread in the system. -/// -/// \param thread Pointer to the thread descriptor (an otherwise -/// unused XosThread structure, usually allocated -/// by the caller for the lifetime of the thread, -/// for example as a global variable). -/// -/// \param container Pointer to separate thread acting as "container" -/// for this one. At the moment, this is only meaningful -/// for run-to-completion (RTC) threads (identified with -/// the XOS_THREAD_RTC flag), in which case the container -/// must have the same priority and also be an RTC thread. -/// (The priority restriction may be lifted in a future -/// implementation, with appropriate constraints on dynamic -/// reprioritization of the created thread). -/// -/// \param entry Thread entry function, takes one argument. -/// -/// \param arg Argument "void*" that is passed to the thread function. -/// -/// \param name Unique name of the thread, for debug/display purposes. -/// This string must be valid for the lifetime of the thread -/// (only a pointer to it is stored in the thread control block). -/// Typically consists of identifier chars with no spaces. -/// -/// \param stack Base of initial stack for the thread, allocated by the -/// caller. Need not be aligned (initial stack pointer will be -/// computed and aligned from given stack base and size). -/// Required argument, except for run-to-completion threads -/// when container is non-NULL, in which case the container's -/// stack is used and this argument must be NULL. -/// -/// \param stack_size Size of the stack, in bytes. -/// NOTE: stack should be at least XOS_STACK_EXTRA bytes plus -/// whatever the thread actually needs if the thread will use -/// coprocessors/TIE state. If the thread will not touch the -/// coprocessors, then it should be XOS_STACK_EXTRA_NO_CP -/// plus whatever the thread actually needs. -/// Recommended minimum stack sizes are defined by the constants -/// XOS_STACK_MIN_SIZE and XOS_STACK_MIN_SIZE_NO_CP. -/// -/// For run-to-completion threads where container is non-NULL, -/// stack_size specifies the minimum stack size required for -/// the thread; it should be smaller or equal to the container's -/// stack. -/// -/// \param priority Initial thread priority. From 0 .. XOS_MAX_PRI - 1. -/// Higher numbers are higher priority. -/// -/// \param parms Pointer to extra parameters structure, or 0 if none given. -/// Use xos_thread_p_***() functions to set parameters in the -/// structure. -/// -/// \param flags Option flags: -/// - XOS_THREAD_SUSPEND -- Leave thread suspended instead of -/// making it ready. The thread can be made ready to run later -/// by calling xos_thread_resume(). -/// - XOS_THREAD_RTC -- Run-to-completion thread. -/// - XOS_THREAD_NO_CP -- Thread does not use coprocessors. -/// No coprocessor state will be saved for this thread. -/// Threads that have this flag set will not allocate any -/// storage for saving coprocessor state and so can have -/// smaller stacks. -/// -/// NOTE: xos_start_main() calls xos_thread_create() to convert main() into the 'main' -/// thread. -/// -/// \return Returns XOS_OK if successful, error code otherwise. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_create(XosThread * thread, - XosThread * container, - XosThreadFunc * entry, - void * arg, - const char * name, - void * stack, - uint32_t stack_size, - int32_t priority, - XosThreadParm * parms, - uint32_t flags ); - - -//----------------------------------------------------------------------------- -/// -/// Remove thread and free up all resources. Thread must have exited already. -/// After this call returns, all resources allocated to the thread (e.g. TCB, -/// stack space, etc.) can be reused. -/// -/// \param thread Handle of thread to be deleted. -/// -/// \return Returns XOS_OK on success, else error code. -/// -/// NOTE: A thread cannot call this on itself. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_delete(XosThread * thread); - - -//----------------------------------------------------------------------------- -/// -/// Force the thread to terminate. The thread execution is aborted, but exit -/// processing will still happen, i.e. the exit handler (if any) will be run. -/// After termination, any other threads waiting on this thread are notified. -/// This function cannot be called on the current thread. -/// -/// \param thread Handle of thread to be aborted. -/// -/// \param exitcode Exit code returned to any waiting threads. -/// -/// \return Returns XOS_OK on success, else error code. -/// -/// NOTE: If the thread is blocked waiting for something, the wait is aborted -/// and the thread is made ready. -/// NOTE: The thread is not guaranteed to have exited when this call returns. -/// It will be made ready and set up for exit processing, but when the exit -/// processing will actually happen depends on the state of the system and -/// the priority of the thread being aborted. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_abort(XosThread * thread, int32_t exitcode); - - -//----------------------------------------------------------------------------- -/// -/// Exit the current thread. The exit handler (if any) will be run before the -/// thread terminates. -/// -/// \param exitcode Exit code to be returned to any waiting threads. -/// -/// \return This function does not return. -/// -/// NOTE: This is automatically called if the thread returns from its entry -/// function. The entry function's return value will be passed as the exit -/// code. -/// -//----------------------------------------------------------------------------- -void -xos_thread_exit(int32_t exitcode); - - -//----------------------------------------------------------------------------- -/// -/// Wait until the specified thread exits and get its exit code. If the thread -/// has exited already, an error will be returned. -/// -/// \param thread The thread to wait for. Cannot be "self", i.e. -/// one cannot wait on one's own exit. -/// -/// \param p_exitcode If not null, the exit code will be returned here. -/// -/// \return Returns XOS_OK on sucess, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_join(XosThread * thread, int32_t * p_exitcode); - - -//----------------------------------------------------------------------------- -/// -/// Yield the CPU to the next thread in line. The calling thread remains ready -/// and is placed at the tail of the ready queue at its current priority level. -/// If there are no threads at the same priority level that are ready to run, -/// then this call will return immediately. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -void -xos_thread_yield(); - - -//----------------------------------------------------------------------------- -/// -/// Suspend the specified thread. The thread will remain suspended until -/// xos_thread_resume() has been called on it. If the thread is already blocked -/// on some other condition, then this function will return an error. -/// -/// \param thread Handle of thread being suspended. A thread can -/// use the special handle XOS_THREAD_SELF to suspend -/// itself. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_suspend(XosThread * thread); - - -//----------------------------------------------------------------------------- -/// -/// Resume a suspended thread. If the thread is not suspended or is blocked on -/// some other condition then this function will do nothing. Otherwise, it will -/// be made ready, and this can cause an immediate context switch if the thread -/// is at a higher priority than the calling thread. -/// -/// \param thread Handle of thread being resumed. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_resume(XosThread * thread); - - -//----------------------------------------------------------------------------- -/// -/// Get the priority of the specified thread. This returns the priority of the -/// queried thread at this instant, however this can change at any time due to -/// other activity in the system. -/// -/// \param thread Handle of thread being queried. A thread can use -/// the special handle XOS_THREAD_SELF to query itself. -/// -/// \return Returns the thread's current priority, or -1 if the thread handle -/// is not valid. -/// -//----------------------------------------------------------------------------- -static inline int32_t -xos_thread_get_priority(XosThread * thread) -{ - XOS_ASSERT(thread); - return thread ? thread->priority : -1; -} - - -//----------------------------------------------------------------------------- -/// -/// Set the priority of the specified thread. The thread must exist. -/// -/// \param thread Handle of thread being affected. A thread can -/// use the special handle XOS_THREAD_SELF to specify -/// itself. -/// -/// \param priority The new priority level to be set. -/// -/// \return Returns XOS_OK on success, else error code. -/// -/// NOTE: Calling this function can result in a scheduler activation, and the -/// caller may be suspended as a result. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_set_priority(XosThread * thread, int32_t priority); - - -//----------------------------------------------------------------------------- -/// -/// Return the name of the specified thread. -/// -/// \param thread Handle of thread being queried. A thread can use -/// the special handle XOS_THREAD_SELF to specify -/// itself. -/// -/// \return Returns a pointer to the name string if available, else NULL. -/// -//----------------------------------------------------------------------------- -static inline const char * -xos_thread_get_name(XosThread * thread) -{ - XOS_ASSERT(thread); - return thread ? thread->name : 0; -} - - -//----------------------------------------------------------------------------- -/// -/// Set the name of the specified thread. -/// -/// \param thread Handle of thread whose name is to be set. A thread -/// can use the special handle XOS_THREAD_SELF to specify -/// itself. -/// -/// \param name Pointer to the new name string. The string is not -/// copied, only the pointer is saved. So the string -/// must be persistent for the life of the thread. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -static inline int32_t -xos_thread_set_name(XosThread * thread, const char * name) -{ - XOS_ASSERT(thread); - if (thread != XOS_NULL) { - thread->name = name; - return XOS_OK; - } - - return XOS_ERR_INVALID_PARAMETER; -} - - -//----------------------------------------------------------------------------- -/// -/// Set an exit handler for the specified thread. The exit handler is run when -/// the thread terminates, either by calling xos_thread_exit() or by returning -/// from its entry function. It will also be called if the thread is being -/// terminated due to e.g. an unhandled exception. -/// -/// The handler must be a function defined as e.g.: -/// -/// int32_t exit_handler(int32_t exitcode); -/// -/// The exit handler runs in the context of the exiting thread, and can call -/// system services. It is provided with a single parameter which is the -/// thread's exit code (the exit code may be set to an error code if the -/// thread is being terminated due to an error or exception). The handler -/// must return a value which will be set as the thread's exit code. -/// -/// \param thread Handle of the thread for which the handler is -/// to be installed. A thread can use the special -/// handle XOS_THREAD_SELF to specify itself. -/// -/// \param func Pointer to exit handler function. To clear an -/// existing handler, pass NULL as the pointer. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_set_exit_handler(XosThread * thread, XosThdExitFunc * func); - - -//----------------------------------------------------------------------------- -/// -/// Return the ID (handle) of the current thread. -/// -/// \return Returns the handle of the current thread. This handle can be -/// used in all XOS system calls. -/// -/// NOTE: If called from interrupt context, returns the handle of the thread -/// that was preempted. -/// -//----------------------------------------------------------------------------- -static inline XosThread * -xos_thread_id() -{ - return xos_curr_threadptr; -} - - -//----------------------------------------------------------------------------- -/// -/// Return the coprocessor mask for the specified thread. -/// -/// \param thread Handle of thread being queried. -/// -/// \return Returns the mask for the specified thread if available, else 0. -/// -//----------------------------------------------------------------------------- -static inline uint16_t -xos_thread_cp_mask(XosThread * thread) -{ - XOS_ASSERT(thread); - return thread ? thread->cp_mask : 0; -} - - -//----------------------------------------------------------------------------- -/// -/// Return the wake value for the specified thread. -/// -/// \return thread Handle of thread being queried. -/// -/// \return Returns The last set wake value. There is no way to detect what -/// action set the wake value and when. -/// -//----------------------------------------------------------------------------- -static inline int32_t -xos_thread_get_wake_value(XosThread * thread) -{ - XOS_ASSERT(thread); - return thread ? thread->wake_value : 0; -} - - -//----------------------------------------------------------------------------- -/// -/// Return the current value of the event bits for the current thread. -/// This function takes no parameters. -/// -/// \return Returns the current value of the event bits. The event bits -/// are set when the thread is woken from an event wait. They will -/// not change while the thread is running. There is no way to -/// determine when the event bits were last updated. -/// -//----------------------------------------------------------------------------- -static inline uint32_t -xos_thread_get_event_bits(void) -{ - XosThread * thread = xos_thread_id(); - return thread ? thread->event_bits : 0; -} - - -//----------------------------------------------------------------------------- -/// -/// Enum values for thread state. -/// -//----------------------------------------------------------------------------- -typedef enum xos_thread_state_t { - XOS_THREAD_STATE_INVALID = 0, ///< Invalid thread - XOS_THREAD_STATE_BLOCKED, ///< Thread is blocked - XOS_THREAD_STATE_READY, ///< Thread is ready to run - XOS_THREAD_STATE_RUNNING, ///< Thread is running - XOS_THREAD_STATE_EXITED, ///< Thread has exited -} xos_thread_state_t; - - -//----------------------------------------------------------------------------- -/// -/// Return the state of the specified thread. -/// -/// \param thread Handle of thread being queried. -/// -/// \return Returns one of the following values: -/// - XOS_THREAD_STATE_RUNNING -- The thread is currently running. -/// - XOS_THREAD_STATE_READY -- The thread is ready to run. -/// - XOS_THREAD_STATE_BLOCKED -- The thread is blocked on something. -/// - XOS_THREAD_STATE_INVALID -- The thread handle is invalid. -/// - XOS_THREAD_STATE_EXITED -- The thread has exited. -/// -//----------------------------------------------------------------------------- -xos_thread_state_t -xos_thread_get_state(XosThread * thread); - - -//----------------------------------------------------------------------------- -/// -/// Disable thread preemption. Prevents context switching to another thread. -/// However, interrupt handlers will still continue to be run. Multiple calls -/// will nest, and the same number of calls to xos_preemption_enable() will be -/// required to re-enable preemption. If the calling thread yields the CPU or -/// exits without enabling preemption, it will cause a system halt. -/// If the calling thread encounters a fatal error, preemption will be enabled -/// during fatal error handling. -/// -/// \return Returns the new value of preemption disable flag after this call. -/// -/// NOTE: Cannot be called from interrupt context. -/// -//----------------------------------------------------------------------------- -uint32_t -xos_preemption_disable(void); - - -//----------------------------------------------------------------------------- -/// -/// Enable thread preemption. Has no effect if preemption was already enabled. -/// Otherwise, it decrements the value of the preemption disable flag and if -/// the value goes to zero, enables preemption. -/// -/// \return Returns the new value of preemption disable flag after this call. -/// -/// NOTE: If scheduling gets enabled, it may cause an immediate context switch -/// if higher priority threads are ready. -/// -//----------------------------------------------------------------------------- -uint32_t -xos_preemption_enable(void); - - -//----------------------------------------------------------------------------- -/// -/// Initialize XOS thread support and start scheduler. -/// -/// Must be called from main() before calling any other thread function. -/// This function initializes thread support, creates the idle thread, and -/// starts the scheduler. It does not return to its caller. This means that -/// at least one user thread must be created before calling xos_start(). -/// Otherwise, the scheduler will run the idle thread since it will be the -/// only thread in the system, and no other thread can be created. -/// -/// NOTE: This function does not initialize timer/tick support. For timer -/// services to be available xos_start_system_timer() must be called. -/// -/// NOTE: xos_start() and xos_start_main() are exclusive, both cannot be -/// called within the same application. -/// -/// \param flags Currently unused (pass 0). -/// -/// \return Does not return. -/// -//----------------------------------------------------------------------------- -void -xos_start(uint32_t flags); - - -//----------------------------------------------------------------------------- -/// -/// Initialize XOS thread support and create init (main) thread. -/// -/// Must be called from main() before calling any other thread function. -/// This function converts the caller into the 'main' or 'init' thread, and -/// returns to the caller after completing initialization. -/// -/// NOTE: This function does not initialize timer/tick support. For timer -/// services to be available xos_start_system_timer() must be called. -/// -/// NOTE: xos_start_main() and xos_start() are exclusive, both cannot be -/// called within the same application. -/// -/// \param name Name of main thread (see xos_thread_create()). -/// -/// \param priority Initial priority of main thread. -/// -/// \param flags Currently unused (pass 0). -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -void -xos_start_main(const char * name, int8_t priority, uint32_t flags); - - -//----------------------------------------------------------------------------- -/// -/// Per-thread stats structure. -/// Note that the CPU use % is approximate, both because of cycle counting -/// and because of integer division. So all the threads' CPU % will not add -/// up to exactly 100%. -/// -//----------------------------------------------------------------------------- -typedef struct XosThreadStats { - XosThread * thread; ///< Thread handle (or pseudo-handle) - uint32_t cpu_pct; ///< CPU use % for this thread - uint32_t normal_switches; ///< Number of non-preemptive switches. - uint32_t preempt_switches; ///< Number of preemptive switches. - uint64_t cycle_count; ///< Number of cycles consumed. -} XosThreadStats; - - -//----------------------------------------------------------------------------- -// Thread pseudo-handles. -//----------------------------------------------------------------------------- -#define XOS_THD_STATS_IDLE ((XosThread *) 1) -#define XOS_THD_STATS_INTR ((XosThread *) 2) - - -//----------------------------------------------------------------------------- -/// -/// Get the thread statistics for the specified thread. Statistics are only -/// available if XOS_OPT_STATS has been enabled. Otherwise, the function -/// will return XOS_OK, but the structure contents will be undefined. -/// -/// \param thread Handle of thread being queried. The following -/// special pseudo-handles can be used: -/// - XOS_THD_STATS_IDLE -- stats for idle thread -/// - XOS_THD_STATS_INTR -- stats for interrupt processing -/// -/// \param stats Pointer to XosThreadStats struct to be filled in. -/// -/// \return Returns XOS_OK on success, else error code. -/// -/// NOTE: Can be called from interrupt context. -/// NOTE: This call will not fill in the "thread" and "cpu_pct" fields in the -/// "stats" structure. The thread handle is already known, and calculating the -/// CPU loading can take quite a bit of time so is not done here. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_get_stats(XosThread * thread, XosThreadStats * stats); - - -//----------------------------------------------------------------------------- -/// -/// Get CPU loading statistics for the system. This function computes the CPU -/// percentage use for all threads in the system (including the idle thread and -/// the 'interrupt thread' (interrupt context). It also returns the cycle count -/// and number of context switches for each thread. -/// Statistics are only available if XOS_OPT_STATS has been enabled. -/// Otherwise, the function will return XOS_OK, but the structure contents will -/// be undefined. -/// -/// IMPORTANT: The entry for interrupt context does not contain a real thread -/// handle. It uses the pseudo-handle XOS_THD_STATS_INTR to indicate that this -/// entry reports interrupt statistics. This pseudo-handle cannot be used for -/// any other thread operations or queries. -/// -/// NOTE: This function disables interrupts while traversing the thread list. -/// It does not leave interrupts disabled during the computations, as that can -/// take a fair amount of time. -/// -/// \param stats Pointer to an array of XosThreadStats structures. -/// The array must be large enough to accommodate all -/// threads in the system. -/// -/// \param size The number of elements available in the array. If -/// this is smaller than the number of threads plus one -/// (for the interrupt context) then XOS_ERR_INVALID_PARAMETER -/// will be returned and '*size' will be set to the -/// minimum number of elements required. On a successful -/// return, '*size' is set to the number of elements -/// actually filled in. -/// -/// \param reset If nonzero, then thread stats counters are reset -/// after reading. This is useful if you want to track -/// the stats so as to get a better idea of current -/// system loading. E.g. calling this function once a -/// second with 'reset' nonzero will provide CPU load -/// information for the last second on each call. -/// -/// \return Returns XOS_OK on success, else error code. In particular, -/// XOS_ERR_INVALID_PARAMETER will be returned if the output buffer -/// is too small. -/// -//----------------------------------------------------------------------------- -int32_t -xos_get_cpu_load(XosThreadStats * stats, int32_t * size, int32_t reset); - - -#ifdef _XOS_INCLUDE_INTERNAL_ - -// Signature of valid thread object -#define XOS_THREAD_SIG 0x54485244 - - -// Extern functions -void -xos_init(void); - -bool -xos_init_done(void); - -bool -xos_started(void); - -int32_t -xos_schedule(XosThread * curr_thread); - -void -xos_q_remove(XosThreadQueue * queue, XosThread * thread); - -XosThread * -xos_q_pop(XosThreadQueue * queue); - -int32_t -xos_wake_queue(XosThreadQueue * queue, const char * expected_cause, int32_t wake_value); - -// Well known block causes -extern const char * const xos_blkon_idle; // (for idle thread only) -extern const char * const xos_blkon_suspend; -extern const char * const xos_blkon_delay; -extern const char * const xos_blkon_exited; -extern const char * const xos_blkon_join; -extern const char * const xos_blkon_event; -extern const char * const xos_blkon_condition; -extern const char * const xos_blkon_mutex; -extern const char * const xos_blkon_sem; -extern const char * const xos_blkon_msgq; - - -//----------------------------------------------------------------------------- -// Blocks the current active thread. -// -// Currently, this can be called from an interrupt handler to block the thread -// that was interrupted. Note that in interrupt context the current thread can -// already be in the blocked state, due to a previous call to this function. -// Can be called with interrupts enabled. -// -// block_cause Reason for blocking. -// -// block_queue Queue on to which this thread should be pushed once it -// is blocked. Can be NULL. -// -// must_schedule If nonzero, then forces a scheduling operation to pick -// the next thread to run, even if there are ready threads -// at the same priority level as the blocked thread. -// -// use_priority If nonzero, then the blocked thread will be queued in -// priority order in the specified block queue. If zero, -// the thread is queued in FIFO order. If no queue has -// been specified, this parameter is ignored. -// -// Returns: The value passed by xos_thread_wake(). -//----------------------------------------------------------------------------- -int32_t -xos_block(const char * block_cause, - XosThreadQueue * block_queue, - int32_t must_schedule, - int32_t use_priority); - - -//----------------------------------------------------------------------------- -// Unblocks the specified blocked thread and puts it at the tail end of its -// ready queue. Schedules it if it is higher priority than the current thread. -// No effect if the thread is not blocked with the specified cause. -// -// thread The thread to wake up (make ready). -// -// expected_cause The expected block cause of the thread. Thread will be -// woken only if its block cause matches this cause, or if -// expected_cause is zero. -// -// wake_value The value to be passed to the woken thread as a return -// value from xos_thread_block(). -// -// Returns: nothing. -// -// The target thread can be woken at a different priority by changing its -// priority while the thread is blocked. -// Can be called with interrupts enabled. Can be called in interrupt context. -//----------------------------------------------------------------------------- -void -xos_thread_wake(XosThread * thread, const char * expected_cause, int32_t wakevalue); - - -//----------------------------------------------------------------------------- -// Function to init C library per-thread and reentrancy support. -//----------------------------------------------------------------------------- -#if XOS_OPT_THREAD_SAFE_CLIB -void -xos_clib_init(void); - -void -xos_clib_thread_init(XosThread * thread); - -void -xos_clib_thread_cleanup(XosThread * thread); -#endif - -#endif - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_THREAD_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_timer.h b/tools/sdk/include/esp32/xtensa/xos_timer.h deleted file mode 100755 index 0d89a21929e..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_timer.h +++ /dev/null @@ -1,592 +0,0 @@ -/** @file */ - -// xos_timer.h - XOS Timer API interface and data structures. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - - -#ifndef __XOS_TIMER_H__ -#define __XOS_TIMER_H__ - -#include "xos_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -//----------------------------------------------------------------------------- -/// -/// Function pointer type for timer callbacks. -/// -//----------------------------------------------------------------------------- -typedef void (XosTimerFunc)(void * arg); - - -//----------------------------------------------------------------------------- -/// -/// Timer event structure. Used to track pending timer events. -/// -//----------------------------------------------------------------------------- -typedef struct XosTimer { - struct XosTimer * next; ///< Pointer to next event in list. - uint64_t when; ///< Time (clock cycles) at which to trigger. - uint64_t delta; ///< Delta for next re-trigger, 0 if none. - XosTimerFunc * fn; ///< Function to call when timer expires. - void * arg; ///< Argument to pass to called function. - bool active; ///< Set if active (in some list of events). -#if XOS_OPT_TIMER_WAIT - XosThreadQueue waitq; ///< Queue of threads waiting on this timer. -#endif -#if XOS_TIMER_DEBUG - uint32_t signature; -#endif -} XosTimer; - - -//----------------------------------------------------------------------------- -// Extern declarations. -//----------------------------------------------------------------------------- - -// System clock frequency in cycles per second. -extern uint32_t xos_clock_freq; - - -///@{ -//----------------------------------------------------------------------------- -// Functions to convert from clock cycles to time units and vice versa. -// -// Note that these are integer conversions so for example a cycle count of less -// than one second will convert to zero seconds. -//----------------------------------------------------------------------------- - -/// Converts CPU cycles to time in seconds. -/// -/// \param cycles Number of CPU cycles. -/// -/// \return Equivalent number of seconds (truncated to integer). -static inline uint64_t -xos_cycles_to_secs(uint64_t cycles) -{ - return cycles / xos_clock_freq; -} - -/// Converts CPU cycles to time in milliseconds. -/// -/// \param cycles Number of CPU cycles. -/// -/// \return Equivalent number of milliseconds (truncated to integer). -static inline uint64_t -xos_cycles_to_msecs(uint64_t cycles) -{ - return (cycles * 1000) / xos_clock_freq; -} - -/// Converts CPU cycles to time in microseconds. -/// -/// \param cycles Number of CPU cycles. -/// -/// \return Equivalent number of microseconds (truncated to integer). -static inline uint64_t -xos_cycles_to_usecs(uint64_t cycles) -{ - return (cycles * 1000000) / xos_clock_freq; -} - -/// Converts time in seconds to CPU cycle count. -/// -/// \param secs Number of seconds. -/// -/// \return Equivalent number of CPU cycles. -static inline uint64_t -xos_secs_to_cycles(uint64_t secs) -{ - return secs * xos_clock_freq; -} - -/// Converts time in milliseconds to CPU cycle count. -/// -/// \param msecs Number of milliseconds. -/// -/// \return Equivalent number of CPU cycles. -static inline uint64_t -xos_msecs_to_cycles(uint64_t msecs) -{ - return (msecs * xos_clock_freq) / 1000; -} - -/// Converts time in microseconds to CPU cycle count. -/// -/// \param usecs Number of microseconds. -/// -/// \return Equivalent number of CPU cycles. -static inline uint64_t -xos_usecs_to_cycles(uint64_t usecs) -{ - return (usecs * xos_clock_freq) / 1000000; -} -///@} - - -//----------------------------------------------------------------------------- -/// -/// Set system clock frequency. This is expected to be set only once, and only -/// if the clock frequency is not known at compile time. -/// -/// \param freq Frequency in cycles per second. -/// -/// \return Returns nothing. -/// -//----------------------------------------------------------------------------- -static inline void -xos_set_clock_freq(uint32_t freq) -{ - xos_clock_freq = freq; -} - - -//----------------------------------------------------------------------------- -/// -/// Get current system clock frequency. -/// -/// \return Returns current system clock frequency in cycles per second. -/// -//----------------------------------------------------------------------------- -static inline uint32_t -xos_get_clock_freq() -{ - return xos_clock_freq; -} - - -//----------------------------------------------------------------------------- -/// -/// Initialize timer support and start the system timer. -/// This function must be called before calling any other timer function. -/// -/// NOTE: The smaller the tick period, the more precisely delays can be -/// specified using timers. However, we also need to make the tick period -/// large enough to allow time both to execute the tick timer interrupt handler -/// and for the application to make reasonable forward progress. If tick_period -/// is too small, the timer interrupt may re-trigger before the timer interrupt -/// handler has returned to the application, thus keeping the processor busy in -/// constantly executing the timer interrupt handler without leaving any cycles -/// for the application. Or, the application might get some cycles but only a -/// fraction of what is spent in the timer interrupt handler, thus severely -/// impacting application performance. -/// -/// The exact number of cycles needed to execute the timer interrupt handler -/// is not specified here. It depends on many factors (e.g. use of caches, -/// various processor configuration options, etc) and can vary by orders of -/// magnitude. Also note that the time to execute this handler is variable: -/// when timers expire upon a given tick timer interrupt, their respective -/// timer handler functions are called from within the interrupt handler. -/// -/// \param timer_num Which Xtensa timer to use (0..2). This timer -/// must exist and be configured at level 1 or at a -/// medium-priority interrupt level (<=EXCM_LEVEL). -/// If 'timer_num' is -1, then this function will -/// automatically choose the highest priority timer -/// that is suitable for use. This value will be -/// passed to xos_system_timer_select(). -/// -/// \param tick_period Number of clock (CCOUNT) cycles between ticks. -/// Must range between 0 and UINT32_MAX. -/// Zero is used to specify dynamic tick (tickless) -/// mode. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_start_system_timer(int32_t timer_num, uint32_t tick_period); - - -//----------------------------------------------------------------------------- -/// -/// Get the timer number of the system timer. Useful mainly when XOS has been -/// allowed to choose its own timer via xos_start_system_timer(). Not valid if -/// called before the system timer has been started. -/// -/// \return Returns one of XOS_SYS_TIMER_0, XOS_SYS_TIMER_1, XOS_SYS_TIMER_2 -/// or XOS_SYS_TIMER_EXTERNAL, or XOS_SYS_TIMER_NONE. -/// -//----------------------------------------------------------------------------- -int32_t -xos_get_system_timer_num(void); - - -//----------------------------------------------------------------------------- -/// -/// Initialize timer object. -/// -/// \param timer Pointer to timer event structure. -/// -/// \return Returns nothing. -/// -/// NOTE: This function should not be called on a timer object once it has -/// been activated. -/// -//----------------------------------------------------------------------------- -void xos_timer_init(XosTimer * timer); - - -//----------------------------------------------------------------------------- -// Flags for xos_timer_start(). -//----------------------------------------------------------------------------- -#define XOS_TIMER_DELTA 0x0000 -#define XOS_TIMER_PERIODIC 0x0001 -#define XOS_TIMER_ABSOLUTE 0x0002 -#define XOS_TIMER_FROM_NOW 0x0000 -#define XOS_TIMER_FROM_LAST 0x0010 - - -//----------------------------------------------------------------------------- -/// -/// Start the timer, and when the timer expires, call the specified function -/// (invoke (*fn)(arg)). If the timer is periodic, it will be automatically -/// restarted when it expires. -/// -/// The specified timer event structure must have been initialized before -/// first use by calling xos_timer_init(). -/// -/// The callback function will be called in an interrupt context. Hence it is -/// NOT safe to use any coprocessors in the function, including the FPU. If a -/// coprocessor must be used, then its state must be saved and restored across -/// its use. -/// -/// NOTE: If you are using the timer only to wait on (via xos_timer_wait()) -/// then it is not necessary to specify a callback function. You should pass -/// NULL for the callback function and zero for the callback argument. -/// -/// \param timer Pointer to timer event structure. Must have been -/// initialized. May be active or not. -/// -/// \param when When to call the function (see flags). -/// -/// \param flags Set of option flags XOS_TIMER_* \n -/// The following flags are mutually exclusive: -/// - XOS_TIMER_DELTA -- when is number of cycles from -/// [see below] (default) -/// - XOS_TIMER_PERIODIC -- when is number of cycles -/// from [see below], and timer continually -/// re-triggers at that interval -/// - XOS_TIMER_ABSOLUTE -- when is absolute value of -/// cycle count \n -/// \n -/// The following flags are mutually exclusive: -/// - XOS_TIMER_FROM_NOW -- *DELTA and *PERIODIC are -/// relative to now (default) -/// - XOS_TIMER_FROM_LAST -- *DELTA and *PERIODIC are -/// relative to the timer event's last specified expiry -/// time (usually in the future if active, in the past -/// if not, absolute 0 if was never activated). -/// -/// \param func Function to call (called in timer interrupt context). -/// This argument is optional. Specify NULL if no function -/// is to be called. -/// -/// \param arg Argument passed to callback function. Only relevant if -/// 'func' is not NULL. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_timer_start(XosTimer * timer, - uint64_t when, - uint32_t flags, - XosTimerFunc * func, - void * arg); - - -//----------------------------------------------------------------------------- -/// -/// Stop the timer and remove it from the list of active timers. Has no effect -/// if the timer is not active. Any waiting threads are woken up. -/// -/// The timer structure must have been initialized at least once, else its -/// contents are undefined and can lead to unpredictable results. -/// -/// \param timer Pointer to timer object. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_timer_stop(XosTimer * timer); - - -//----------------------------------------------------------------------------- -/// -/// Reset and restart the timer. -/// -/// The timer is reset to go off at time "when" from now. If the timer was not -/// active, it will be activated. If the timer was active, it will be restarted. -/// If the timer is periodic, the period will be set to "when". -/// The timer object must have been initialized at some point before this call. -/// -/// \param timer Pointer to timer object. -/// -/// \param when Number of cycles from now that the timer will expire. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_timer_restart(XosTimer * timer, uint64_t when); - - -//----------------------------------------------------------------------------- -/// -/// Check if the timer is active. The timer is active if it has been started -/// and not yet expired or canceled. -/// -/// \param timer Pointer to timer object. -/// -/// \return Returns non-zero if the timer is active, else zero. -/// -//----------------------------------------------------------------------------- -static inline int32_t -xos_timer_is_active(XosTimer * timer) -{ - return timer ? timer->active : 0; -} - - -//----------------------------------------------------------------------------- -/// -/// Get the repeat period for a periodic timer. For a one-shot timer this will -/// return zero. The period is reported in system clock cycles. -/// -/// \param timer Pointer to timer object. -/// -/// \return Returns period in cycles, or zero for non-periodic timers. -/// -//----------------------------------------------------------------------------- -static inline uint64_t -xos_timer_get_period(XosTimer * timer) -{ - return timer ? timer->delta : 0; -} - - -//----------------------------------------------------------------------------- -/// -/// Set the repeat period for a periodic timer. The period must be specified -/// in system clock cycles. -/// -/// If the timer is active, the change in period does not take effect until -/// the timer expires at least once after this call. -/// Note that setting a period of zero will effectively turn a periodic timer -/// into a one-shot timer. Similarly, a one-shot timer can be turned into a -/// periodic timer. -/// -/// \param timer Pointer to timer object. -/// -/// \param period Repeat period in system clock cycles. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_timer_set_period(XosTimer * timer, uint64_t period); - - -//----------------------------------------------------------------------------- -/// -/// Get the current system cycle count. This accounts for the periodic rollover -/// of the 32-bit CCOUNT cycle counter and returns a 64-bit value. -/// -/// \return Returns the current system cycle count. -/// -//----------------------------------------------------------------------------- -static inline uint64_t -xos_get_system_cycles(void) -{ - extern uint64_t xos_system_cycles; - extern uint32_t xos_last_ccount; - - // xos_last_ccount was updated when xos_system_cycles was last updated. - // We need to add in the number of cycles elapsed since then. - return xos_system_cycles + (xos_get_ccount() - xos_last_ccount); -} - - -//----------------------------------------------------------------------------- -/// -/// Put calling thread to sleep for at least the specified number of cycles. -/// The actual number of cycles spent sleeping may be larger depending upon -/// the granularity of the system timer. Once the specified time has elapsed -/// the thread will be woken and made ready. -/// -/// \param cycles Number of system clock cycles to sleep. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_thread_sleep(uint64_t cycles); - - -//----------------------------------------------------------------------------- -/// -/// Put calling thread to sleep for at least the specified number of msec. -/// The actual amount of time spent sleeping may be larger depending upon -/// the granularity of the system timer. Once the specified time has elapsed -/// the thread will be woken and made ready. -/// -/// \return msecs The number of milliseconds to sleep. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -static inline int32_t -xos_thread_sleep_msec(uint64_t msecs) -{ - return xos_thread_sleep(xos_msecs_to_cycles(msecs)); -} - - -//----------------------------------------------------------------------------- -/// -/// Put calling thread to sleep for at least the specified number of usec. -/// The actual amount of time spent sleeping may be larger depending upon -/// the granularity of the system timer. Once the specified time has elapsed -/// the thread will be woken and made ready. -/// -/// \return usecs The number of microseconds to sleep. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -static inline int32_t -xos_thread_sleep_usec(uint64_t usecs) -{ - return xos_thread_sleep(xos_usecs_to_cycles(usecs)); -} - - -//----------------------------------------------------------------------------- -/// -/// Wait on a timer until it expires or is cancelled. The calling thread will -/// be blocked. The timer must be active. -/// NOTE: This operation is only available if XOS_OPT_TIMER_WAIT is set -/// to 1 in the configuration options. -/// -/// \param timer Pointer to timer object. -/// -/// \return Returns XOS_OK on normal timeout, else an error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_timer_wait(XosTimer * timer); - - -//----------------------------------------------------------------------------- -// System timer control interface. -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -// Defines for system timer ID. -//----------------------------------------------------------------------------- -#define XOS_SYS_TIMER_0 0 ///< Internal timer 0 -#define XOS_SYS_TIMER_1 1 ///< Internal timer 1 -#define XOS_SYS_TIMER_2 2 ///< Internal timer 2 -#define XOS_SYS_TIMER_EXTERNAL -2 ///< External timer -#define XOS_SYS_TIMER_NONE -1 ///< No system timer selected - - -//----------------------------------------------------------------------------- -/// -/// This function handles XOS timer tick processing. It must be called by the -/// timer interrupt handler on every timer interrupt. This function computes -/// the time to the next tick and sets it up by calling xos_system_timer_set(). -/// -//----------------------------------------------------------------------------- -void -xos_tick_handler(void); - - -//----------------------------------------------------------------------------- -/// -/// Selects the timer to use. The selection may be one of the internal timers -/// or an external timer. The default implementation selects an internal timer. -/// This function can be overridden to provide custom timer processing or to -/// support an external timer. -/// -/// \param timer_num The internal timer number to select (0-2) or -/// -1 to auto-select a timer. This parameter can -/// be ignored by custom implementations that use -/// an external timer. -/// -/// \param psel Pointer to a location where the selected timer -/// ID must be returned. The timer ID must be one -/// of XOS_SYS_TIMER_0, XOS_SYS_TIMER_1, XOS_SYS_TIMER_2 -/// or XOS_SYS_TIMER_EXTERNAL. -/// -/// \return Returns XOS_OK on success, else error code. -/// -//----------------------------------------------------------------------------- -int32_t -xos_system_timer_select(int32_t timer_num, int32_t *psel); - - -//----------------------------------------------------------------------------- -/// -/// Starts the system timer and sets up the first interrupt. This function can -/// be overridden to provide custom timer processing or to support an external -/// timer. -/// -/// \param cycles The number of CPU cycles from now when the -/// first interrupt must occur. -/// -//----------------------------------------------------------------------------- -void -xos_system_timer_init(uint32_t cycles); - - -//----------------------------------------------------------------------------- -/// -/// Sets the next trigger value of the system timer. The parameter 'cycles' is -/// the number of CPU cycles from now when the interrupt must occur. -/// This function can be overridden to provide custom timer processing or to -/// support an external timer. -/// -/// \param cycles The number of CPU cycles from now when the -/// next interrupt must occur. -/// -//----------------------------------------------------------------------------- -void -xos_system_timer_set(uint32_t cycles); - - -#ifdef __cplusplus -} -#endif - -#endif // __XOS_TIMER_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xos_types.h b/tools/sdk/include/esp32/xtensa/xos_types.h deleted file mode 100755 index a913b94a231..00000000000 --- a/tools/sdk/include/esp32/xtensa/xos_types.h +++ /dev/null @@ -1,75 +0,0 @@ -/** @file */ -// xos_types.h - XOS type definitions. - -// 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. - -// NOTE: Do not include this file directly in your application. Including -// xos.h will automatically include this file. - - -#ifndef __XOS_TYPES_H__ -#define __XOS_TYPES_H__ - -#if !defined(_ASMLANGUAGE) && !defined(__ASSEMBLER__) - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -//----------------------------------------------------------------------------- -// The following are defined here because of the variations in the C libraries -// that we need to work with. -// - Not all of them have stdbool.h -// - Not all of them define NULL as (void *)0 -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -/// -/// XOS define for NULL value. This makes the NULL value independent of the -/// C library (not all of them define NULL the same way). -/// -//----------------------------------------------------------------------------- -#define XOS_NULL ((void *)0) - - -//----------------------------------------------------------------------------- -/// -/// XOS definition of 'bool' type. Some C libraries do not support stdbool.h. -/// -//----------------------------------------------------------------------------- -#ifndef bool -#define bool int8_t -#define false 0 ///< XOS definition of 'false' -#define true 1 ///< XOS definition of 'true' -#endif - -#ifdef __cplusplus -} -#endif - -#endif // !defined(_ASMLANGUAGE) && !defined(__ASSEMBLER__) - -#endif // __XOS_TYPES_H__ - diff --git a/tools/sdk/include/esp32/xtensa/xt_perf_consts.h b/tools/sdk/include/esp32/xtensa/xt_perf_consts.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/xt_perfmon.h b/tools/sdk/include/esp32/xtensa/xt_perfmon.h deleted file mode 100755 index 959052b164d..00000000000 --- a/tools/sdk/include/esp32/xtensa/xt_perfmon.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Customer ID=11656; Build=0x5f626; Copyright (c) 2012 by Tensilica Inc. 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. - */ - -#ifndef __XT_PERFMON_H__ -#define __XT_PERFMON_H__ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef int counter_id_t; - -/* xt_perf_init - - Initialize the performance monitor library. Ordinarily, this - function is called automatically via the .init section. If your - environment does not support the .init section, you will need to - call this function from your code. -*/ - -extern void xt_perf_init(void); - -/* xt_perf_enable - - Turn on the performance monitor. Ordinarily, counting is off by - default. If you turn off performance monitor using xt_perf_disable or - by call to a function that disables performance monitor, you can turn - it on again via this function. -*/ - -extern void xt_perf_enable(void); - -/* xt_perf_disable - - Turn off the performance monitor. If you want to suspend counting - events for a portion of your code, use this function and then call - xt_perf_enable when you want to start again. -*/ - -extern void xt_perf_disable(void); - -/* xt_perf_clear - - Disable performance monitor and clear all initialized hardware counters. - All counter ids are invalid after call to this function and all hardware - counters available for initialization. -*/ - -extern void xt_perf_clear (void); - -/* xt_perf_counters_num - - Returns number of free hardware performance counters. After call to xt_perf_clear - all counters are free and available for initialization. With each successful - xt_perf_init_counter/xt_perf_init_event call this number is decreasing until - no free counters available. -*/ - -extern int xt_perf_counters_num (void); - -/* xt_perf_init_counter32 - - Setup 32 bit performance counter. This function disables performance monitor - if it was enabled. - - Returns zero based counter id on success or negative value if failed. - This function may fail if there is insufficient number of free hardware - counters or function arguments are invalid. - - The counter id returned on success can be used with xt_perf_reset_counter - and xt_perf_counter32 functions. - - - events group, one of XTPERF_CNT constants defined in - xt_perf_consts.h; - - events mask for selected group. Mask bit fields for each - selector defined with XTPERF_MASK prefix in xt_perf_consts.h; - - specifies interrupt levels at which to count events; - if trace_level is greater or equal to zero events are - counted only at interrupt levels below or equal to - trace_level; if trace_level is negative events are - counted only at (-trace_level) interrupt level or higher. -*/ - - -extern counter_id_t xt_perf_init_counter32 ( unsigned int selector, - unsigned int mask, - int trace_level); - -/* xt_perf_init_counter64 - - Setup 64 bit performance counter. Library emulates 64 bit counters by handling - profiling interrupt and recording overflows of 32 bit hardware counters. - This function disables performance monitor if it was enabled. - - Returns zero based counter id on success or negative value if failed. - This function may fail if there is insufficient number of free hardware - counters or function arguments are invalid. - - The counter id returned on success can be used with xt_perf_reset_counter - and xt_perf_counter64 functions. - - - events group, one of XTPERF_CNT constants defined in - xt_perf_consts.h; - - events mask for selected group. Mask bit fields for each - selector defined with XTPERF_MASK prefix in xt_perf_consts.h; - - specifies interrupt levels at which to count events; - if trace_level is greater or equal to zero events are - counted only at interrupt levels below or equal to - trace_level; if trace_level is negative events are - counted only at (-trace_level) interrupt level or higher. -*/ - -extern counter_id_t xt_perf_init_counter64 ( unsigned int selector, - unsigned int mask, - int trace_level); - -/* xt_perf_reset_counter - - Reset counter value to 0. - Returns zero on success or non zero if failed. -*/ - -extern int xt_perf_reset_counter (counter_id_t counter_id); - -/* xt_perf_counter32 - - Read 32 bit counter value. - - Returns zero if counter id is not valid. -*/ - -extern unsigned int xt_perf_counter32 (counter_id_t counter_id); - -/* xt_perf_counter64 - - Read 64 bit counter value. - - Counter must be initialized using xt_perf_init_counter64 function. - - Returns zero if counter id is not valid. -*/ - -extern unsigned long long xt_perf_counter64 (counter_id_t counter_id); - - /* xt_perf_overflow32 - - Read overflow flag of 32 bit counter. This flag is dropped when - counter initialized or reset. Once counter overflows and wraps - around the flag is set and stays set until counter reset. - - Returns negative value if counter id is invalid, zero if counter - not overflowed, positive if in overflowed state. - */ - -extern int xt_perf_overflow32 (counter_id_t counter_id); - -#ifdef __cplusplus -} -#endif - -#endif /* __XT_PERFMON_H__ */ diff --git a/tools/sdk/include/esp32/xtensa/xt_profiling.h b/tools/sdk/include/esp32/xtensa/xt_profiling.h deleted file mode 100755 index 650713a4595..00000000000 --- a/tools/sdk/include/esp32/xtensa/xt_profiling.h +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Customer ID=11656; Build=0x5f626; Copyright (c) 2005-2012 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -#ifndef __XT_PROFILER_H__ -#define __XT_PROFILER_H__ - -#include - -#if XCHAL_NUM_PERF_COUNTERS -/* Performance monitor counters constants */ -#include - -#endif /* XCHAL_NUM_PERF_COUNTERS */ - - -#ifdef __cplusplus -extern "C" { -#endif - -/* This file defines an interface that allows a program being profiled - to control when and how it is profiled, whether it is running under - the instruction set simulator or under the hardware profiler. - - Both ISS and HWP implement this interface, although in different - ways. Both also do the right thing if you don't call any of these - functions. -*/ - - -/* -xt_profile_init - - ISS: a no op. - - HWP: Initialize the profiler. Ordinarily, this function is called - automatically via the .init section. If your environment does not - support the .init section, you will need to call this function - by hand. -*/ -extern void xt_profile_init(void); - -/* -xt_profile_add_memory - - ISS: a no op. - - HWP: - Makes "buf_size" bytes at "buf" available to the hardware profiler. - This buffer should be initialized to zeros prior to this call. - - The hardware profiler has already estimated the amount of memory it needs, - but under certain circumstances may still run out of memory. If so, you can - provide more memory with this routine. - -*/ -extern void xt_profile_add_memory(void * buf, unsigned int buf_size); - - -/* xt_profile_enable - - Turn on the profiler. Ordinarily, profiling is on by default. - If you turn off profiling using xt_profile_disable, You can turn - it on again via this function. -*/ -extern void xt_profile_enable(void); - -/* xt_profile_disable - - Turn off the profiler. If you don't want to profile a portion of your code, - use this function and then xt_profile_enable when you want to start again. -*/ -extern void xt_profile_disable(void); - -/* xt_profile_save_and_reset - - Save and reset the profiler's data. - If there were errors, either during profiling or while attempting to - write the data, no data will be written and this function will - return non-zero. - -*/ -extern int xt_profile_save_and_reset(void); - -/* xt_profile_get_frequency - - ISS: always returns 1. - - HWP: - Returns the number of cycles between samples for timer based profiler. - In performance counters based profiler always returns 1. -*/ -extern unsigned int xt_profile_get_frequency(void); - -/* xt_profile_set_frequency - - ISS: a no op. - - HWP: - Set the number of cycles between samples for timer based profiler. - Ignored in performance counters based profiler. - - sample frequency is the number of cycles to wait between samples. It should - be a multiple of 1024. - - If you set the sample frequency to a different value than was passed in xt_profile_init, - then the labels in the output will reflect the later frequency, even though some samples may - have been taken at the earlier frequency. Typically this does not make a significant difference - in the results if this function is called early enough. -*/ -extern void xt_profile_set_frequency(unsigned int sample_frequency); - -/* xt_profile_num_errors - - ISS: always returns 0 - - HWP: - Returns the number of errors that occured while taking samples. Typically these - are out of memory errors and you need to pass a bigger buffer to - xt_profile_add_memory -*/ -extern int xt_profile_num_errors(void); - - -#if XCHAL_NUM_PERF_COUNTERS - - -/* xt_profile_randomize - - ISS: not available - - HWP: Available in performance monitor based profiler. - - Turns on or off sampling period randomization mode. Period randomization - helps to avoid aliasing problems when code being profiled is highly periodic. - Profiler maintains same average sampling period but individual sampling - steps may vary. - Period randomization is turned off by default. - - - non zero turns randomization on, - zero turns randomization off. -*/ - -extern void xt_profile_randomization(int value); - -/* xt_profile_config_clear - - ISS: not available - - HWP: Available in performance monitor based profiler. - - Stops profiling if it was enabled and clears performance counters - parameters. Accumulated profile data stays in memory and will be - saved when xt_profile_save_and_reset is called or at program exit. - Number of configured performance counters is zero after this - function call. -*/ - -extern void xt_profile_config_clear(void); - - -/* xt_profile_config_num - - ISS: not available - - HWP: Available in performance monitor based profiler. - - Returns number of free performance counters. -*/ - -extern int xt_profile_config_num(void); - - -/* xt_profile_config_counter error codes -*/ - -#define XTPROF_ERR_OUT_OF_MEM -1 -#define XTPROF_ERR_INVALID_ARGS -2 -#define XTPROF_ERR_NOT_ENOUGH_COUNTERS -3 -#define XTPROF_ERR_DEFUNCT -4 - -/* xt_profile_config_counter - - ISS: not available - - HWP: Available in performance monitor based profiler. - - Allocating and initializing one or more performance counter for sampling. - Even though event may require multiple performance counters allocated the - profile data for event is merged and dumped into single gmon file. - This function disables profiling if it was enabled. - - Returns 0 on success, non zero if failed: - XTPROF_ERR_OUT_OF_MEM - memory allocation failed; - XTPROF_ERR_INVALID_ARGS - invalid function parameters; - XTPROF_ERR_NOT_ENOUGH_COUNTERS - not enough free performance counters available; - XTPROF_ERR_DEFUNCT - profiling is disabled because of previous errors - (xt_profile_num_errors() is non zero) - - - events group, one of XTPERF_CNT constants defined in xt_perf_consts.h - - events mask for selected group. Mask bit fields for each - selector defined with XTPERF_MASK prefix in xt_perf_consts.h - - specifies interrupt levels at which to take samples; - if trace_level is greater or equal to zero samples are - taken only at interrupt levels below or equal to - trace_level; if trace_level is negative samples are taken - only at (-trace_level) interrupt level or higher. - - sampling period; 1 - record every event, 2 - record every - other event and so on; - Please note - there is overhead associated with events recording, - high frequency events may produce incorrect profile when period - is too small. -*/ - -extern int xt_profile_config_counter ( unsigned int selector, - unsigned int mask, - int trace_level, - unsigned int period); - - - -#endif /* XCHAL_NUM_PERF_COUNTERS */ - -#ifdef __cplusplus -} -#endif - -#endif /* __XT_PROFILER_H__ */ diff --git a/tools/sdk/include/esp32/xtensa/xt_reftb.h b/tools/sdk/include/esp32/xtensa/xt_reftb.h deleted file mode 100755 index 358c39f7408..00000000000 --- a/tools/sdk/include/esp32/xtensa/xt_reftb.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Customer ID=11656; Build=0x5f626; Copyright (c) 2009-2013 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of - * Tensilica Inc. They may be adapted and modified by bona fide - * purchasers for internal use, but neither the original nor any - * adapted or modified version may be disclosed or distributed to - * third parties in any manner, medium, or form, in whole or in part, - * without the prior written consent of Tensilica Inc. - * - * This software and its derivatives are to be executed solely on - * products incorporating a Tensilica processor. - */ - -// Utility routines for returning pass/fail status in HW simulations - -#ifndef XT_REF_TESTBENCH_H -#define XT_REF_TESTBENCH_H 1 - -#ifdef __cplusplus -extern "C" { -#endif - -// Exit routines for HW simulation -extern int diag_pass(); -extern int diag_fail(); - -// Set exit status for HW simulation -int set_diag_status(int stat); - -// Setup for user power toggling -extern int setup_power_toggle(); - -// Return exit status location -extern unsigned int* testbench_exit_location(); -// Return power toggle location -extern unsigned int* testbench_power_toggle_location(); - - -// Change exit status location -// You must also change the plusarg "+DVMagicExit" sent to the HW simulator -// or change the argument "--exit_location" sent to the ISS -extern unsigned int* set_testbench_exit_location(unsigned int*); -// Change power toggle location -// You must also change the plusarg "+DVPowerLoc" sent to the HW simulator -extern unsigned int* set_testbench_power_toggle_location(unsigned int*); - -// Exit routines with status message -// -static inline -int pass(const char *msg) -{ - return diag_pass(); -} - -static inline -int fail(const char *msg) -{ - return diag_fail(); -} - -#define POWER_TOGGLE_ON 1 -#define POWER_TOGGLE_OFF 0 - -// Routine to turn on and off power toggle -// Does a magic write that Monitors.v intercepts and appropriately turns -// SAIF dumping on and offf -// -extern volatile unsigned int *_reftb_power_toggle; - -__attribute__ ((always_inline)) -static inline -int set_power_toggle(int val) -{ -#ifdef __XTENSA__ - *_reftb_power_toggle = val; -#endif - return val; -} - -#ifdef __cplusplus -} -#endif - -#endif // XT_REF_TESTBENCH_H - diff --git a/tools/sdk/include/esp32/xtensa/xtav110.h b/tools/sdk/include/esp32/xtensa/xtav110.h deleted file mode 100755 index 23421f0b745..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtav110.h +++ /dev/null @@ -1,313 +0,0 @@ -/* Copyright (c) 2007-2013 by Tensilica Inc. ALL RIGHTS RESERVED. -/ These coded instructions, statements, and computer programs are the -/ copyrighted works and confidential proprietary information of Tensilica Inc. -/ They may not be modified, copied, reproduced, distributed, or disclosed to -/ third parties in any manner, medium, or form, in whole or in part, without -/ the prior written consent of Tensilica Inc. -*/ - -/* xtav110.h - Xtensa Avnet LX110 (XT-AV110) board specific definitions */ - -#ifndef _INC_XTAV110_H_ -#define _INC_XTAV110_H_ - -#include -#include - -#define XTBOARD_NAME "XT-AV110" - - -/* - * Default assignment of XTAV110 devices to external interrupts. - */ - -/* Ethernet interrupt: */ -#ifdef XCHAL_EXTINT1_NUM -#define ETHERNET_INTNUM XCHAL_EXTINT1_NUM -#define ETHERNET_INTLEVEL XCHAL_EXTINT1_LEVEL -#define ETHERNET_INTMASK XCHAL_EXTINT1_MASK -#else -#define ETHERNET_INTMASK 0 -#endif - -/* UART interrupt: */ -#ifdef XCHAL_EXTINT0_NUM -#define UART16550_INTNUM XCHAL_EXTINT0_NUM -#define UART16550_INTLEVEL XCHAL_EXTINT0_LEVEL -#define UART16550_INTMASK XCHAL_EXTINT0_MASK -#else -#define UART16550_INTMASK 0 -#endif - -/* Audio output interrupt (I2S transmitter FIFO): */ -#ifdef XCHAL_EXTINT2_NUM -#define AUDIO_I2S_OUT_INTNUM XCHAL_EXTINT2_NUM -#define AUDIO_I2S_OUT_INTLEVEL XCHAL_EXTINT2_LEVEL -#define AUDIO_I2S_OUT_INTMASK XCHAL_EXTINT2_MASK -#else -#define AUDIO_I2S_OUT_INTMASK 0 -#endif - -/* Audio input interrupt (I2S receiver FIFO): */ -#ifdef XCHAL_EXTINT3_NUM -#define AUDIO_I2S_IN_INTNUM XCHAL_EXTINT3_NUM -#define AUDIO_I2S_IN_INTLEVEL XCHAL_EXTINT3_LEVEL -#define AUDIO_I2S_IN_INTMASK XCHAL_EXTINT3_MASK -#else -#define AUDIO_I2S_IN_INTMASK 0 -#endif - -/* I2C interrupt */ -#ifdef XCHAL_EXTINT4_NUM -#define I2C_INTNUM XCHAL_EXTINT4_NUM -#define I2C_INTLEVEL XCHAL_EXTINT4_LEVEL -#define I2C_INTMASK XCHAL_EXTINT4_MASK -#else -#define I2C_INTMASK 0 -#endif - -/* USB interrupt */ -#ifdef XCHAL_EXTINT5_NUM -#define USB_INTNUM XCHAL_EXTINT5_NUM -#define USB_INTLEVEL XCHAL_EXTINT5_LEVEL -#define USB_INTMASK XCHAL_EXTINT5_MASK -#else -#define USB_INTMASK 0 -#endif - -/* - * Device addresses. - * - * Note: for endianness-independence, use 32-bit loads and stores for all - * register accesses to Ethernet, UART and LED devices. Undefined bits - * may need to be masked out if needed when reading if the actual register - * size is smaller than 32 bits. - * - * Note: XTAV110 bus byte lanes are defined in terms of msbyte and lsbyte - * relative to the processor. So 32-bit registers are accessed consistently - * from both big and little endian processors. However, this means byte - * sequences are not consistent between big and little endian processors. - * This is fine for RAM, and for ROM if ROM is created for a specific - * processor (and thus has correct byte sequences). However this may be - * unexpected for Flash, which might contain a file-system that one wants - * to use for multiple processor configurations (eg. the Flash might contain - * the Ethernet card's address, endianness-independent application data, etc). - * That is, byte sequences written in Flash by a core of a given endianness - * will be byte-swapped when seen by a core of the other endianness. - * Someone implementing an endianness-independent Flash file system will - * likely handle this byte-swapping issue in the Flash driver software. - */ - -#define XTBOARD_FLASH_MAXSIZE 0x1000000 /* 16 MB */ - -#ifdef XSHAL_IOBLOCK_BYPASS_PADDR - -/* Flash Memory: */ -# define XTBOARD_FLASH_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x08000000) - -/* FPGA registers: */ -# define XTBOARD_FPGAREGS_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D020000) - -/* Ethernet controller/transceiver SONIC SN83934: */ -# define ETHERNET_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D030000) - - -/* UART National-Semi PC16550D: */ -# define UART16550_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D050000) - -/* I2S transmitter */ -# define AUDIO_I2S_OUT_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D080000) - -/* I2S receiver */ -# define AUDIO_I2S_IN_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D088000) - -/* I2C master */ -# define I2C_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D090000) - -/* SPI controller */ -# define SPI_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D0A0000) - -/* Display controller Sunplus SPLC780D, 4bit mode, - * LCD Display MYTech MOC-16216B-B: */ -# define SPLC780D_4BIT_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D0C0000) - -/* USB Controller */ -# define USB_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D0D0000) - -/* Ethernet buffer: */ -# define ETHERNET_BUFFER_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D800000) - -#endif /* XSHAL_IOBLOCK_BYPASS_PADDR */ - -/* These devices might be accessed cached: */ -#ifdef XSHAL_IOBLOCK_CACHED_PADDR -# define XTBOARD_FLASH_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x08000000) -# define ETHERNET_BUFFER_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x0D800000) -#endif /* XSHAL_IOBLOCK_CACHED_PADDR */ - - -/*** Same thing over again, this time with virtual addresses: ***/ - -#ifdef XSHAL_IOBLOCK_BYPASS_VADDR - -/* Flash Memory: */ -# define XTBOARD_FLASH_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x08000000) - -/* FPGA registers: */ -# define XTBOARD_FPGAREGS_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D020000) - -/* Ethernet controller/transceiver SONIC SN83934: */ -# define ETHERNET_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D030000) - - -/* UART National-Semi PC16550D: */ -# define UART16550_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D050000) - -/* I2S transmitter */ -# define AUDIO_I2S_OUT_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D080000) - -/* I2S receiver */ -# define AUDIO_I2S_IN_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D088000) - -/* I2C master */ -# define I2C_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D090000) - -/* SPI controller */ -# define SPI_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D0A0000) - -/* Display controller Sunplus SPLC780D, 4bit mode, - * LCD Display MYTech MOC-16216B-B: */ -# define SPLC780D_4BIT_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D0C0000) - -/* USB Controller */ -# define USB_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D0D0000) - -/* Ethernet buffer: */ -# define ETHERNET_BUFFER_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D800000) - -#endif /* XSHAL_IOBLOCK_BYPASS_VADDR */ - -/* These devices might be accessed cached: */ -#ifdef XSHAL_IOBLOCK_CACHED_VADDR -# define XTBOARD_FLASH_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x08000000) -# define ETHERNET_BUFFER_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x0D800000) -#endif /* XSHAL_IOBLOCK_CACHED_VADDR */ - - -/* System ROM: */ -#define XTBOARD_ROM_SIZE XSHAL_ROM_SIZE -#ifdef XSHAL_ROM_VADDR -#define XTBOARD_ROM_VADDR XSHAL_ROM_VADDR -#endif -#ifdef XSHAL_ROM_PADDR -#define XTBOARD_ROM_PADDR XSHAL_ROM_PADDR -#endif - -/* System RAM: */ -#define XTBOARD_RAM_SIZE XSHAL_RAM_SIZE -#ifdef XSHAL_RAM_VADDR -#define XTBOARD_RAM_VADDR XSHAL_RAM_VADDR -#endif -#ifdef XSHAL_RAM_PADDR -#define XTBOARD_RAM_PADDR XSHAL_RAM_PADDR -#endif -#define XTBOARD_RAM_BYPASS_VADDR XSHAL_RAM_BYPASS_VADDR -#define XTBOARD_RAM_BYPASS_PADDR XSHAL_RAM_BYPASS_PADDR - - - -/* - * Things that depend on device addresses. - */ - - -#define XTBOARD_CACHEATTR_WRITEBACK XSHAL_XT2000_CACHEATTR_WRITEBACK -#define XTBOARD_CACHEATTR_WRITEALLOC XSHAL_XT2000_CACHEATTR_WRITEALLOC -#define XTBOARD_CACHEATTR_WRITETHRU XSHAL_XT2000_CACHEATTR_WRITETHRU -#define XTBOARD_CACHEATTR_BYPASS XSHAL_XT2000_CACHEATTR_BYPASS -#define XTBOARD_CACHEATTR_DEFAULT XSHAL_XT2000_CACHEATTR_DEFAULT - -#define XTBOARD_BUSINT_PIPE_REGIONS XSHAL_XT2000_PIPE_REGIONS -#define XTBOARD_BUSINT_SDRAM_REGIONS XSHAL_XT2000_SDRAM_REGIONS - - -/* - * FPGA registers. - * All these registers are normally accessed using 32-bit loads/stores. - */ - -/* Register offsets: */ -#define XTBOARD_DATECD_OFS 0x00 /* date code (read-only) */ -#define XTBOARD_CLKFRQ_OFS 0x04 /* clock frequency Hz (read-only) */ -#define XTBOARD_SYSLED_OFS 0x08 /* LEDs */ -#define XTBOARD_DIPSW_OFS 0x0C /* DIP switch bits (read-only) */ -#define XTBOARD_SWRST_OFS 0x10 /* software reset */ - -/* Physical register addresses: */ -#ifdef XTBOARD_FPGAREGS_PADDR -#define XTBOARD_DATECD_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_DATECD_OFS) -#define XTBOARD_CLKFRQ_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_CLKFRQ_OFS) -#define XTBOARD_SYSLED_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_SYSLED_OFS) -#define XTBOARD_DIPSW_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_DIPSW_OFS) -#define XTBOARD_SWRST_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_SWRST_OFS) -#endif - -/* Virtual register addresses: */ -#ifdef XTBOARD_FPGAREGS_VADDR -#define XTBOARD_DATECD_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_DATECD_OFS) -#define XTBOARD_CLKFRQ_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_CLKFRQ_OFS) -#define XTBOARD_SYSLED_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_SYSLED_OFS) -#define XTBOARD_DIPSW_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_DIPSW_OFS) -#define XTBOARD_SWRST_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_SWRST_OFS) -/* Register access (for C code): */ -#define XTBOARD_DATECD_REG (*(volatile unsigned*) XTBOARD_DATECD_VADDR) -#define XTBOARD_CLKFRQ_REG (*(volatile unsigned*) XTBOARD_CLKFRQ_VADDR) -#define XTBOARD_SYSLED_REG (*(volatile unsigned*) XTBOARD_SYSLED_VADDR) -#define XTBOARD_DIPSW_REG (*(volatile unsigned*) XTBOARD_DIPSW_VADDR) -#define XTBOARD_SWRST_REG (*(volatile unsigned*) XTBOARD_SWRST_VADDR) -#endif - -/* DATECD (date code; when core was built) bit fields: */ -/* BCD-coded month (01..12): */ -#define XTBOARD_DATECD_MONTH_SHIFT 24 -#define XTBOARD_DATECD_MONTH_BITS 8 -#define XTBOARD_DATECD_MONTH_MASK 0xFF000000 -/* BCD-coded day (01..31): */ -#define XTBOARD_DATECD_DAY_SHIFT 16 -#define XTBOARD_DATECD_DAY_BITS 8 -#define XTBOARD_DATECD_DAY_MASK 0x00FF0000 -/* BCD-coded year (2001..9999): */ -#define XTBOARD_DATECD_YEAR_SHIFT 0 -#define XTBOARD_DATECD_YEAR_BITS 16 -#define XTBOARD_DATECD_YEAR_MASK 0x0000FFFF - -/* SYSLED (system LED) bit fields: */ - -/* LED control bits (off=0, on=1): */ -#define XTBOARD_SYSLED_USER_SHIFT 0 -#define XTBOARD_SYSLED_USER_BITS 2 -#define XTBOARD_SYSLED_USER_MASK 0x00000003 - -/* DIP Switch SW5 (left=sw1=lsb=bit0, right=sw4=msb=bit3; off=0, on=1): */ -/* DIP switch bit fields (bit2/sw3 is reserved and presently unused): */ -#define XTBOARD_DIPSW_USER_SHIFT 0 /* labeled 1-2 (1=lsb) */ -#define XTBOARD_DIPSW_USER_BITS 2 -#define XTBOARD_DIPSW_USER_MASK 0x00000003 -#define XTBOARD_DIPSW_BOOT_SHIFT 3 /* labeled 8 (msb) */ -#define XTBOARD_DIPSW_BOOT_BITS 1 -#define XTBOARD_DIPSW_BOOT_MASK 0x00000008 -/* Boot settings: bit3/sw4, off=0, on=1 (this switch controls hardware): */ -#define XTBOARD_DIPSW_BOOT_RAM (0< - diff --git a/tools/sdk/include/esp32/xtensa/xtav200.h b/tools/sdk/include/esp32/xtensa/xtav200.h deleted file mode 100755 index f3d837efa68..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtav200.h +++ /dev/null @@ -1,280 +0,0 @@ -/* Copyright (c) 2007-2013 by Tensilica Inc. ALL RIGHTS RESERVED. -/ These coded instructions, statements, and computer programs are the -/ copyrighted works and confidential proprietary information of Tensilica Inc. -/ They may not be modified, copied, reproduced, distributed, or disclosed to -/ third parties in any manner, medium, or form, in whole or in part, without -/ the prior written consent of Tensilica Inc. -*/ - -/* xtav200.h - Xtensa Avnet LX200 (XT-AV200) board specific definitions */ - -#ifndef _INC_XTAV200_H_ -#define _INC_XTAV200_H_ - -#include -#include - -#define XTBOARD_NAME "XT-AV200" - - -/* - * Default assignment of XTAV200 devices to external interrupts. - */ - -/* Ethernet interrupt: */ -#ifdef XCHAL_EXTINT1_NUM -#define ETHERNET_INTNUM XCHAL_EXTINT1_NUM -#define ETHERNET_INTLEVEL XCHAL_EXTINT1_LEVEL -#define ETHERNET_INTMASK XCHAL_EXTINT1_MASK -#else -#define ETHERNET_INTMASK 0 -#endif - -/* UART interrupt: */ -#ifdef XCHAL_EXTINT0_NUM -#define UART16550_INTNUM XCHAL_EXTINT0_NUM -#define UART16550_INTLEVEL XCHAL_EXTINT0_LEVEL -#define UART16550_INTMASK XCHAL_EXTINT0_MASK -#else -#define UART16550_INTMASK 0 -#endif - -/* Audio output interrupt (I2S FIFO underrun): */ -#ifdef XCHAL_EXTINT2_NUM -#define AUDIO_INTNUM XCHAL_EXTINT2_NUM -#define AUDIO_INTLEVEL XCHAL_EXTINT2_LEVEL -#define AUDIO_INTMASK XCHAL_EXTINT2_MASK -#else -#define AUDIO_INTMASK 0 -#endif - -/* Audio output (I2S FIFO level) interrupt: */ -#ifdef XCHAL_EXTINT3_NUM -#define AUDIO_I2SLVL_INTNUM XCHAL_EXTINT3_NUM -#define AUDIO_I2SLVL_INTLEVEL XCHAL_EXTINT3_LEVEL -#define AUDIO_I2SLVL_INTMASK XCHAL_EXTINT3_MASK -#else -#define AUDIO_I2SLVL_INTMASK 0 -#endif - -/* Audio input (ADC FIFO level) interrupt: */ -#ifdef XCHAL_EXTINT4_NUM -#define AUDIO_ADCLVL_INTNUM XCHAL_EXTINT4_NUM -#define AUDIO_ADCLVL_INTLEVEL XCHAL_EXTINT4_LEVEL -#define AUDIO_ADCLVL_INTMASK XCHAL_EXTINT4_MASK -#else -#define AUDIO_ADCLVL_INTMASK 0 -#endif - - -/* - * Device addresses. - * - * Note: for endianness-independence, use 32-bit loads and stores for all - * register accesses to Ethernet, UART and LED devices. Undefined bits - * may need to be masked out if needed when reading if the actual register - * size is smaller than 32 bits. - * - * Note: XTAV200 bus byte lanes are defined in terms of msbyte and lsbyte - * relative to the processor. So 32-bit registers are accessed consistently - * from both big and little endian processors. However, this means byte - * sequences are not consistent between big and little endian processors. - * This is fine for RAM, and for ROM if ROM is created for a specific - * processor (and thus has correct byte sequences). However this may be - * unexpected for Flash, which might contain a file-system that one wants - * to use for multiple processor configurations (eg. the Flash might contain - * the Ethernet card's address, endianness-independent application data, etc). - * That is, byte sequences written in Flash by a core of a given endianness - * will be byte-swapped when seen by a core of the other endianness. - * Someone implementing an endianness-independent Flash file system will - * likely handle this byte-swapping issue in the Flash driver software. - */ - -#define XTBOARD_FLASH_MAXSIZE 0x1000000 /* 16 MB */ - -#ifdef XSHAL_IOBLOCK_BYPASS_PADDR - -/* Flash Memory: */ -# define XTBOARD_FLASH_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x08000000) - -/* FPGA registers: */ -# define XTBOARD_FPGAREGS_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D020000) - -/* Ethernet controller/transceiver SONIC SN83934: */ -# define ETHERNET_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D030000) - -/* UART National-Semi PC16550D: */ -# define UART16550_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D050000) - -/* TI 320AIC23/28-TSSOP Stereo Audio Codec: */ -# define AUDIO_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D070000) - -/* Boot 128K Sram address: */ -# define BOOT_SRAM_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D400000) - -/* Ethernet buffer: */ -# define ETHERNET_BUFFER_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D800000) - -#endif /* XSHAL_IOBLOCK_BYPASS_PADDR */ - -/* These devices might be accessed cached: */ -#ifdef XSHAL_IOBLOCK_CACHED_PADDR -# define XTBOARD_FLASH_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x08000000) -# define ETHERNET_BUFFER_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x0D800000) -# define BOOT_SRAM_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x0D400000) -#endif /* XSHAL_IOBLOCK_CACHED_PADDR */ - - -/*** Same thing over again, this time with virtual addresses: ***/ - -#ifdef XSHAL_IOBLOCK_BYPASS_VADDR - -/* Flash Memory: */ -# define XTBOARD_FLASH_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x08000000) - -/* FPGA registers: */ -# define XTBOARD_FPGAREGS_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D020000) - -/* Ethernet controller/transceiver SONIC SN83934: */ -# define ETHERNET_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D030000) - -/* UART National-Semi PC16550D: */ -# define UART16550_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D050000) - -/* TI 320AIC23/28-TSSOP Stereo Audio Codec: */ -# define AUDIO_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D070000) - -/* 128K Sram address: */ -# define BOOT_SRAM_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D400000) - -/* Ethernet buffer: */ -# define ETHERNET_BUFFER_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D800000) - -#endif /* XSHAL_IOBLOCK_BYPASS_VADDR */ - -/* These devices might be accessed cached: */ -#ifdef XSHAL_IOBLOCK_CACHED_VADDR -# define XTBOARD_FLASH_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x08000000) -# define AUDIO_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x0D070000) -# define ETHERNET_BUFFER_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x0D800000) -# define BOOT_SRAM_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x0D400000) -#endif /* XSHAL_IOBLOCK_CACHED_VADDR */ - - -/* System ROM: */ -#define XTBOARD_ROM_SIZE XSHAL_ROM_SIZE -#ifdef XSHAL_ROM_VADDR -#define XTBOARD_ROM_VADDR XSHAL_ROM_VADDR -#endif -#ifdef XSHAL_ROM_PADDR -#define XTBOARD_ROM_PADDR XSHAL_ROM_PADDR -#endif - -/* System RAM: */ -#define XTBOARD_RAM_SIZE XSHAL_RAM_SIZE -#ifdef XSHAL_RAM_VADDR -#define XTBOARD_RAM_VADDR XSHAL_RAM_VADDR -#endif -#ifdef XSHAL_RAM_PADDR -#define XTBOARD_RAM_PADDR XSHAL_RAM_PADDR -#endif -#define XTBOARD_RAM_BYPASS_VADDR XSHAL_RAM_BYPASS_VADDR -#define XTBOARD_RAM_BYPASS_PADDR XSHAL_RAM_BYPASS_PADDR - - - -/* - * Things that depend on device addresses. - */ - - -#define XTBOARD_CACHEATTR_WRITEBACK XSHAL_XT2000_CACHEATTR_WRITEBACK -#define XTBOARD_CACHEATTR_WRITEALLOC XSHAL_XT2000_CACHEATTR_WRITEALLOC -#define XTBOARD_CACHEATTR_WRITETHRU XSHAL_XT2000_CACHEATTR_WRITETHRU -#define XTBOARD_CACHEATTR_BYPASS XSHAL_XT2000_CACHEATTR_BYPASS -#define XTBOARD_CACHEATTR_DEFAULT XSHAL_XT2000_CACHEATTR_DEFAULT - -#define XTBOARD_BUSINT_PIPE_REGIONS XSHAL_XT2000_PIPE_REGIONS -#define XTBOARD_BUSINT_SDRAM_REGIONS XSHAL_XT2000_SDRAM_REGIONS - - -/* - * FPGA registers. - * All these registers are normally accessed using 32-bit loads/stores. - */ - -/* Register offsets: */ -#define XTBOARD_DATECD_OFS 0x00 /* date code (read-only) */ -#define XTBOARD_CLKFRQ_OFS 0x04 /* clock frequency Hz (read-only) */ -#define XTBOARD_SYSLED_OFS 0x08 /* LEDs */ -#define XTBOARD_DIPSW_OFS 0x0C /* DIP switch bits (read-only) */ -#define XTBOARD_SWRST_OFS 0x10 /* software reset */ - -/* Physical register addresses: */ -#ifdef XTBOARD_FPGAREGS_PADDR -#define XTBOARD_DATECD_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_DATECD_OFS) -#define XTBOARD_CLKFRQ_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_CLKFRQ_OFS) -#define XTBOARD_SYSLED_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_SYSLED_OFS) -#define XTBOARD_DIPSW_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_DIPSW_OFS) -#define XTBOARD_SWRST_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_SWRST_OFS) -#endif - -/* Virtual register addresses: */ -#ifdef XTBOARD_FPGAREGS_VADDR -#define XTBOARD_DATECD_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_DATECD_OFS) -#define XTBOARD_CLKFRQ_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_CLKFRQ_OFS) -#define XTBOARD_SYSLED_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_SYSLED_OFS) -#define XTBOARD_DIPSW_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_DIPSW_OFS) -#define XTBOARD_SWRST_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_SWRST_OFS) -/* Register access (for C code): */ -#define XTBOARD_DATECD_REG (*(volatile unsigned*) XTBOARD_DATECD_VADDR) -#define XTBOARD_CLKFRQ_REG (*(volatile unsigned*) XTBOARD_CLKFRQ_VADDR) -#define XTBOARD_SYSLED_REG (*(volatile unsigned*) XTBOARD_SYSLED_VADDR) -#define XTBOARD_DIPSW_REG (*(volatile unsigned*) XTBOARD_DIPSW_VADDR) -#define XTBOARD_SWRST_REG (*(volatile unsigned*) XTBOARD_SWRST_VADDR) -#endif - -/* DATECD (date code; when core was built) bit fields: */ -/* BCD-coded month (01..12): */ -#define XTBOARD_DATECD_MONTH_SHIFT 24 -#define XTBOARD_DATECD_MONTH_BITS 8 -#define XTBOARD_DATECD_MONTH_MASK 0xFF000000 -/* BCD-coded day (01..31): */ -#define XTBOARD_DATECD_DAY_SHIFT 16 -#define XTBOARD_DATECD_DAY_BITS 8 -#define XTBOARD_DATECD_DAY_MASK 0x00FF0000 -/* BCD-coded year (2001..9999): */ -#define XTBOARD_DATECD_YEAR_SHIFT 0 -#define XTBOARD_DATECD_YEAR_BITS 16 -#define XTBOARD_DATECD_YEAR_MASK 0x0000FFFF - -/* SYSLED (system LED) bit fields: */ - -/* LED control bits (off=0, on=1): */ -#define XTBOARD_SYSLED_USER_SHIFT 0 -#define XTBOARD_SYSLED_USER_BITS 4 -#define XTBOARD_SYSLED_USER_MASK 0x0000000F - -/* DIP Switch (left=sw1=lsb=bit0, right=sw8=msb=bit7; off=0, on=1): */ -/* DIP switch bit fields (bit6/sw7 is reserved and presently unused): */ -#define XTBOARD_DIPSW_USER_SHIFT 0 /* labeled 1-6 (1=lsb) */ -#define XTBOARD_DIPSW_USER_BITS 6 -#define XTBOARD_DIPSW_USER_MASK 0x0000003F -#define XTBOARD_DIPSW_BOOT_SHIFT 7 /* labeled 8 (msb) */ -#define XTBOARD_DIPSW_BOOT_BITS 1 -#define XTBOARD_DIPSW_BOOT_MASK 0x00000080 -/* Boot settings: bit7/sw8, off=0, on=1 (this switch controls hardware): */ -#define XTBOARD_DIPSW_BOOT_RAM (0< - diff --git a/tools/sdk/include/esp32/xtensa/xtav60.h b/tools/sdk/include/esp32/xtensa/xtav60.h deleted file mode 100755 index d7c8e3aed85..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtav60.h +++ /dev/null @@ -1,241 +0,0 @@ -/* Copyright (c) 2002-2013 by Tensilica Inc. ALL RIGHTS RESERVED. -/ These coded instructions, statements, and computer programs are the -/ copyrighted works and confidential proprietary information of Tensilica Inc. -/ They may not be modified, copied, reproduced, distributed, or disclosed to -/ third parties in any manner, medium, or form, in whole or in part, without -/ the prior written consent of Tensilica Inc. -*/ - -/* xtav60.h - Xtensa Avnet LX60 (XT-AV60) board specific definitions */ - -#ifndef _INC_XTAV60_H_ -#define _INC_XTAV60_H_ - -#include -#include - -#define XTBOARD_NAME "XT-AV60" - - -/* - * Default assignment of XTAV60 devices to external interrupts. - */ - -/* Ethernet interrupt: */ -#ifdef XCHAL_EXTINT1_NUM -#define ETHERNET_INTNUM XCHAL_EXTINT1_NUM -#define ETHERNET_INTLEVEL XCHAL_EXTINT1_LEVEL -#define ETHERNET_INTMASK XCHAL_EXTINT1_MASK -#else -#define ETHERNET_INTMASK 0 -#endif - -/* UART interrupt: */ -#ifdef XCHAL_EXTINT0_NUM -#define UART16550_INTNUM XCHAL_EXTINT0_NUM -#define UART16550_INTLEVEL XCHAL_EXTINT0_LEVEL -#define UART16550_INTMASK XCHAL_EXTINT0_MASK -#else -#define UART16550_INTMASK 0 -#endif - -/* - * Device addresses. - * - * Note: for endianness-independence, use 32-bit loads and stores for all - * register accesses to Ethernet, UART and LED devices. Undefined bits - * may need to be masked out if needed when reading if the actual register - * size is smaller than 32 bits. - * - * Note: XTAV60 bus byte lanes are defined in terms of msbyte and lsbyte - * relative to the processor. So 32-bit registers are accessed consistently - * from both big and little endian processors. However, this means byte - * sequences are not consistent between big and little endian processors. - * This is fine for RAM, and for ROM if ROM is created for a specific - * processor (and thus has correct byte sequences). However this may be - * unexpected for Flash, which might contain a file-system that one wants - * to use for multiple processor configurations (eg. the Flash might contain - * the Ethernet card's address, endianness-independent application data, etc). - * That is, byte sequences written in Flash by a core of a given endianness - * will be byte-swapped when seen by a core of the other endianness. - * Someone implementing an endianness-independent Flash file system will - * likely handle this byte-swapping issue in the Flash driver software. - */ - -#define XTBOARD_FLASH_MAXSIZE 0x400000 /* 4 MB */ - -#ifdef XSHAL_IOBLOCK_BYPASS_PADDR - -/* Flash Memory: */ -# define XTBOARD_FLASH_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x08000000) - -/* FPGA registers: */ -# define XTBOARD_FPGAREGS_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D020000) - -/* Ethernet controller/transceiver SONIC SN83934: */ -# define ETHERNET_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D030000) -# define ETHERNET_CONTROLLER_PADDR ETHERNET_PADDR /* legacy macro */ - -/* Display controller Sunplus SPLC780D, LCD Display MYTech MOC-16216B-B: */ -# define SPLC780D_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D040000) - -/* UART National-Semi PC16550D: */ -# define UART16550_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D050000) - -/* Boot 128K Sram address: */ -# define BOOT_SRAM_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D400000) - -/* Ethernet buffer: */ -# define ETHERNET_BUFFER_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D800000) - -#endif /* XSHAL_IOBLOCK_BYPASS_PADDR */ - -/* These devices might be accessed cached: */ -#ifdef XSHAL_IOBLOCK_CACHED_PADDR -# define XTBOARD_FLASH_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x08000000) -# define ETHERNET_BUFFER_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x0D800000) -# define BOOT_SRAM_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x0D400000) -#endif /* XSHAL_IOBLOCK_CACHED_PADDR */ - - -/*** Same thing over again, this time with virtual addresses: ***/ - -#ifdef XSHAL_IOBLOCK_BYPASS_VADDR - -/* Flash Memory: */ -# define XTBOARD_FLASH_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x08000000) - -/* FPGA registers: */ -# define XTBOARD_FPGAREGS_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D020000) - -/* Ethernet controller/transceiver SONIC SN83934: */ -# define ETHERNET_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D030000) - -/* Display controller Sunplus SPLC780D, LCD Display MYTech MOC-16216B-B: */ -# define SPLC780D_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D040000) - -/* UART National-Semi PC16550D: */ -# define UART16550_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D050000) - -/* 128K Sram address: */ -# define BOOT_SRAM_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D400000) - -/* Ethernet buffer: */ -# define ETHERNET_BUFFER_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D800000) - -#endif /* XSHAL_IOBLOCK_BYPASS_VADDR */ - -/* These devices might be accessed cached: */ -#ifdef XSHAL_IOBLOCK_CACHED_VADDR -# define XTBOARD_FLASH_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x08000000) -# define ETHERNET_BUFFER_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x0D800000) -# define BOOT_SRAM_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x0D400000) -#endif /* XSHAL_IOBLOCK_CACHED_VADDR */ - - -/* System ROM: */ -#define XTBOARD_ROM_SIZE XSHAL_ROM_SIZE -#ifdef XSHAL_ROM_VADDR -#define XTBOARD_ROM_VADDR XSHAL_ROM_VADDR -#endif -#ifdef XSHAL_ROM_PADDR -#define XTBOARD_ROM_PADDR XSHAL_ROM_PADDR -#endif - -/* System RAM: */ -#define XTBOARD_RAM_SIZE XSHAL_RAM_SIZE -#ifdef XSHAL_RAM_VADDR -#define XTBOARD_RAM_VADDR XSHAL_RAM_VADDR -#endif -#ifdef XSHAL_RAM_PADDR -#define XTBOARD_RAM_PADDR XSHAL_RAM_PADDR -#endif -#define XTBOARD_RAM_BYPASS_VADDR XSHAL_RAM_BYPASS_VADDR -#define XTBOARD_RAM_BYPASS_PADDR XSHAL_RAM_BYPASS_PADDR - - - -/* - * Things that depend on device addresses. - */ - - -#define XTBOARD_CACHEATTR_WRITEBACK XSHAL_XT2000_CACHEATTR_WRITEBACK -#define XTBOARD_CACHEATTR_WRITEALLOC XSHAL_XT2000_CACHEATTR_WRITEALLOC -#define XTBOARD_CACHEATTR_WRITETHRU XSHAL_XT2000_CACHEATTR_WRITETHRU -#define XTBOARD_CACHEATTR_BYPASS XSHAL_XT2000_CACHEATTR_BYPASS -#define XTBOARD_CACHEATTR_DEFAULT XSHAL_XT2000_CACHEATTR_DEFAULT - -#define XTBOARD_BUSINT_PIPE_REGIONS XSHAL_XT2000_PIPE_REGIONS -#define XTBOARD_BUSINT_SDRAM_REGIONS XSHAL_XT2000_SDRAM_REGIONS - - -/* - * FPGA registers. - * All these registers are normally accessed using 32-bit loads/stores. - */ - -/* Register offsets: */ -#define XTBOARD_DATECD_OFS 0x00 /* date code (read-only) */ -#define XTBOARD_CLKFRQ_OFS 0x04 /* clock frequency Hz (read-only) */ -#define XTBOARD_DIPSW_OFS 0x0C /* DIP switch bits (read-only) */ -#define XTBOARD_SWRST_OFS 0x10 /* software reset */ - -/* Physical register addresses: */ -#ifdef XTBOARD_FPGAREGS_PADDR -#define XTBOARD_DATECD_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_DATECD_OFS) -#define XTBOARD_CLKFRQ_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_CLKFRQ_OFS) -#define XTBOARD_DIPSW_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_DIPSW_OFS) -#define XTBOARD_SWRST_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_SWRST_OFS) -#endif - -/* Virtual register addresses: */ -#ifdef XTBOARD_FPGAREGS_VADDR -#define XTBOARD_DATECD_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_DATECD_OFS) -#define XTBOARD_CLKFRQ_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_CLKFRQ_OFS) -#define XTBOARD_DIPSW_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_DIPSW_OFS) -#define XTBOARD_SWRST_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_SWRST_OFS) -/* Register access (for C code): */ -#define XTBOARD_DATECD_REG (*(volatile unsigned*) XTBOARD_DATECD_VADDR) -#define XTBOARD_CLKFRQ_REG (*(volatile unsigned*) XTBOARD_CLKFRQ_VADDR) -#define XTBOARD_DIPSW_REG (*(volatile unsigned*) XTBOARD_DIPSW_VADDR) -#define XTBOARD_SWRST_REG (*(volatile unsigned*) XTBOARD_SWRST_VADDR) -#endif - -/* DATECD (date code; when core was built) bit fields: */ -/* BCD-coded month (01..12): */ -#define XTBOARD_DATECD_MONTH_SHIFT 24 -#define XTBOARD_DATECD_MONTH_BITS 8 -#define XTBOARD_DATECD_MONTH_MASK 0xFF000000 -/* BCD-coded day (01..31): */ -#define XTBOARD_DATECD_DAY_SHIFT 16 -#define XTBOARD_DATECD_DAY_BITS 8 -#define XTBOARD_DATECD_DAY_MASK 0x00FF0000 -/* BCD-coded year (2001..9999): */ -#define XTBOARD_DATECD_YEAR_SHIFT 0 -#define XTBOARD_DATECD_YEAR_BITS 16 -#define XTBOARD_DATECD_YEAR_MASK 0x0000FFFF - -/* DIP Switch (left=sw1=lsb=bit0, right=sw8=msb=bit7; off=0, on=1): */ -/* DIP switch bit fields (bit6/sw7 is reserved and presently unused): */ -#define XTBOARD_DIPSW_USER_SHIFT 0 /* labeled 1-6 (1=lsb) */ -#define XTBOARD_DIPSW_USER_BITS 6 -#define XTBOARD_DIPSW_USER_MASK 0x0000003F -#define XTBOARD_DIPSW_BOOT_SHIFT 7 /* labeled 8 (msb) */ -#define XTBOARD_DIPSW_BOOT_BITS 1 -#define XTBOARD_DIPSW_BOOT_MASK 0x00000080 -/* Boot settings: bit7/sw8, off=0, on=1 (this switch controls hardware): */ -#define XTBOARD_DIPSW_BOOT_RAM (0< - diff --git a/tools/sdk/include/esp32/xtensa/xtav60/xtensa/lcd-splc780d-board.h b/tools/sdk/include/esp32/xtensa/xtav60/xtensa/lcd-splc780d-board.h deleted file mode 100755 index 629a32581ad..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtav60/xtensa/lcd-splc780d-board.h +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - -Copyright (c) 2006-2007 by Tensilica Inc. ALL RIGHTS RESERVED. -These coded instructions, statements, and computer programs are the -copyrighted works and confidential proprietary information of Tensilica Inc. -They may not be modified, copied, reproduced, distributed, or disclosed to -third parties in any manner, medium, or form, in whole or in part, without -the prior written consent of Tensilica Inc. --------------------------------------------------------------------------------- - -lcd-splc780d-board.h Board-specific LCD info on Avnet AV60 (XT-AV60) board. - -Interface between board-independent driver and board-specific header. - -This is used by a board-independent SPLC780D LCD controller driver to obtain -board-specific information about LCD displays on the board, such as the -controller register base address and spacing (a function of how the address -lines are connected on the board) and length of the visible window of the -display (a function of the LCD panel the controller drives). The driver does -not refer directly to the board-specific header, which therefore is not -constrained to use macro names consistent with other boards. - -!! Must not contain any board-specific macro names (only controller specific) !! - -Included at compile-time via an include path specific to the board. - -The XT-AV60 board contains a single MYTech MOC-16216B-B display driven by -a Sunplus SPLC870D controller. - -*******************************************************************************/ - -#ifndef _LCD_SPLC780D_BOARD_H -#define _LCD_SPLC780D_BOARD_H - -#include /* Board info */ - - -/* Base address of the controller's registers. */ -#ifdef SPLC780D_VADDR -#define SPLC780D_REGBASE SPLC780D_VADDR -#endif - -/* -The controller's registers are connected at word addresses on the XT-AV60. -Each byte-wide register appears as the least-significant-byte (LSB) of the -word regardless of the endianness of the processor (so if using word accesses -then endianness doesn't matter). -*/ -#define SPLC780D_REGSPACING 4 -typedef unsigned splc780d_reg_t; - -/* Include generic information shared by all boards that use this device. */ -#include - - -/* Display limits of the LCD panel. */ -#define DISPLAY_VISIBLE_LEN 16 /* length (chars) of visible window */ - -#endif /* _LCD_SPLC780D_BOARD_H */ - diff --git a/tools/sdk/include/esp32/xtensa/xtbsp.h b/tools/sdk/include/esp32/xtensa/xtbsp.h deleted file mode 100755 index 62356dd8688..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtbsp.h +++ /dev/null @@ -1,269 +0,0 @@ -/******************************************************************************* - - Copyright (c) 2006-2009 Tensilica 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. - --------------------------------------------------------------------------------- - -xtbsp.h Xtensa Board Support Package API - -This API defines a minimal set of board-support functions that every supported -Xtensa board is expected to provide in the board-support-package (BSP) library -associated with the board-specific LSP. Only basic board functions are provided -in this board-independent API. API functions not applicable to a board must be -stubbed in its BSP library. More complex operations must use a board-specific -interface. Functions are grouped by type of peripheral device. - -*******************************************************************************/ - -#ifndef _XTBSP_H_ -#define _XTBSP_H_ - - -#ifdef __cplusplus -extern "C" { -#endif - - -/******************************************************************************* -BOARD INITIALIZATION. -The board with all its devices is initialized by xtbsp_board_init(). -Individual devices represented by this API can be reinitialized at any -time by calling their inidividual device init functions (grouped with -other device functions). This might be useful to (say) change the baud -rate of the UART. -*/ - - -/* -Initialize the board. Must call before any other API function. -Iniitializes BSP, board in general, and all devices on the board. -*/ -extern void xtbsp_board_init(void); - - -/******************************************************************************* -BOARD CHARACTERISTICS and CONVENIENCE FUNCTIONS. -Board support functions not associated with a particular peripheral device. -*/ - -/* -Return a short string representing the type of board. -If the board has a display, the string must fit on a single line. -*/ -extern const char * xtbsp_board_name(void); - -/* -Hardware reset the entire board (if possible). Does not return if successful. -If this function returns, it is stubbed out or not possible with this board. -*/ -extern void xtbsp_board_reset(void); - -/* -Return the clock frequency in Hertz. May be constant or computed. -*/ -extern unsigned xtbsp_clock_freq_hz(void); - -/* -Return the clock period in picoseconds. May be constant or computed. -*/ -extern unsigned xtbsp_clock_period_ps(void); - -/* -Spin (at least) a number of cycles per the processor's CCOUNT register. -Unlike a s/w delay loop, the duration is not affected by compiler -optimization or interrupts completed within the delay period. -If the processor doesn't have CCOUNT, a s/w delay loop is used to obtain -a rough approximation of the cycle count. -*/ -extern void xtbsp_delay_cycles(unsigned cycles); - -/* -Spin at least a number of nanoseconds (approximate and err in the high side). -BSP implementation should do this efficiently, avoiding integer overflow or -excessive loss of precision, run-time division or floating point. -Function implementation (vs. macro) allows BSP to optimize for the clock -frequency by pre-computing (or using constant) scale factors. -*/ -extern void xtbsp_delay_ns(unsigned ns); - - -/******************************************************************************* -C LIBRARY SUPPORT. -These functions are called by the C library libgloss interface. -Their names are predetermined apart from this BSP API. -*/ - -/* -Initialize the board. Called by C library initialization code. -Usually simply calls xtbsp_board_init(). -*/ -extern void board_init(void); - -/* -(Wait for and) Input a single byte from the default character I/O -device. Return -1 if there is no input device. -This device is usually a UART and this function calls xtbsp_uart_getchar(). -On some boards (eg.) it might be a directly connected keyboard. -*/ -extern int inbyte(void); - -/* -Output a single char to the default character I/O device (and wait -until it's been taken). -This device is usually a UART and this function calls xtbsp_uart_putchar(). -On some boards (eg.) it might be a directly connected bit-mapped screen. -*/ -extern void outbyte(int c); - - -/******************************************************************************* -UART (SERIAL I/O). -Supports a single UART in a simple polling mode and provides control of -receiver and transmitter data interrupts (client must provide handler). -Provides a mapping to processor interrupt number which can be used with -the HAL to control processor interrupt enable (INTENABLE) etc. -*/ - -/* Bitmasks to identify UART interrupts. */ -typedef enum xtbsp_uart_int { - xtbsp_uart_int_rx = 1<<0, - xtbsp_uart_int_tx = 1<<1, - /* mask of all valid interrupt bits */ - xtbsp_uart_int_all = (1<<2)-1 -} xtbsp_uart_int; - -/* -Return non-zero if the board has a UART. -*/ -extern int xtbsp_uart_exists(void); - -/* -Initialize the UART: - parity = 0 (none), 1 (odd), or 2 (even). - nstop = 1 or 2 (stop bits). - ndata = 7 or 8 (data bits). -Disables all UART interrupts. -Returns non-zero if failed (perhaps due to unsupported parameter values). -Must call before any of the following functions. -*/ -extern int xtbsp_uart_init(unsigned baud, unsigned ndata, - unsigned parity, unsigned nstop); -#define xtbsp_uart_init_default() xtbsp_uart_init(38400, 8, 0, 1) - -/* -(Wait for and) Input a single char from the UART. -Any pending xtbsp_uart_int_rx interrupt is cleared. -*/ -extern char xtbsp_uart_getchar(void); - -/* -(Wait for transmitter ready and) Output a single char to the UART. -Any pending xtbsp_uart_int_tx interrupt is cleared. -*/ -extern void xtbsp_uart_putchar(const char c); - -/* -Return true (non-zero) if a character has been received and is ready -to be input by xtbsp_uart_getchar() without waiting, else return 0. -*/ -extern int xtbsp_uart_get_isready(void); - -/* -Return non-zero if a character may be output by xtbsp_uart_putchar() -without waiting, else return 0. -Any pending xtbsp_uart_int_tx interrupt is cleared. -*/ -extern int xtbsp_uart_put_isready(void); - -/* -Return the enable status of all UART interrupts represented by this API, -that is those with bits defined in type xtbsp_uart_int (1 bit = enabled). -This is the enable status at the device, not the processor's INTENABLE. -*/ -extern xtbsp_uart_int xtbsp_uart_int_enable_status(void); - -/* -Enable selected UART interrupts at the device. -*/ -extern void xtbsp_uart_int_enable(const xtbsp_uart_int mask); - -/* -Disable selected UART interrupts at the device. -*/ -extern void xtbsp_uart_int_disable(const xtbsp_uart_int mask); - -/* -Return the interrupt number (0..31) to which the selected UART interrupt -is connected. May be used with the link-time HAL to obtain more information, -eg. Xthal_intlevel_mask[xtbsp_uart_int_number(xtbsp_uart_int_rx)] -This information can be used to control the processor's INTENABLE, etc. -Result is -1 if not connected, undefined if mask has more than 1 bit set. -*/ -extern int xtbsp_uart_int_number(const xtbsp_uart_int mask); - - -/******************************************************************************* -DISPLAY. -Supports a single display that can render a series of ASCII characters. -Functions are provided to perform generic display tasks such as display -a string, display character by character, or blank the display. -Chars are 7-bit printable ASCII. Strings are C style NUL \0 terminated. -These functions busy-wait for any required timing delays so the caller does -not have to deal with timing. Some displays require long delays which in -some client applications warrant a board and RTOS specific approach to -driving the display, however that is beyond the scope of this API. -*/ - -/* -Return non-zero if board has a display. -*/ -extern int xtbsp_display_exists(void); - -/* -Initialize the display. Must call before any of the following functions. -*/ -extern void xtbsp_display_init(void); - -/* -Display a single char at position pos (0 is leftmost). Other positions are -left untouched. Positions beyond the width of the display are ignored. -*/ -extern void xtbsp_display_char(unsigned pos, const char c); - -/* -Display a string. Blank-pad to or truncate at the end of the display -(overwrites any previous string so don't need to blank display first). -*/ -extern void xtbsp_display_string(const char *s); - -/* -Blank (clear) the entire display. -*/ -extern void xtbsp_display_blank(void); - - - -#ifdef __cplusplus -} -#endif - -#endif /* _XTBSP_H_ */ diff --git a/tools/sdk/include/esp32/xtensa/xtensa-libdb-macros.h b/tools/sdk/include/esp32/xtensa/xtensa-libdb-macros.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/xtensa-versions.h b/tools/sdk/include/esp32/xtensa/xtensa-versions.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/xtensa-xer.h b/tools/sdk/include/esp32/xtensa/xtensa-xer.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/xtkc705.h b/tools/sdk/include/esp32/xtensa/xtkc705.h deleted file mode 100755 index 831c15d541f..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtkc705.h +++ /dev/null @@ -1,14 +0,0 @@ -/* Copyright (c) 2006-2013 by Tensilica Inc. ALL RIGHTS RESERVED. -/ These coded instructions, statements, and computer programs are the -/ copyrighted works and confidential proprietary information of Tensilica Inc. -/ They may not be modified, copied, reproduced, distributed, or disclosed to -/ third parties in any manner, medium, or form, in whole or in part, without -/ the prior written consent of Tensilica Inc. -*/ - -/* xtkc705.h - Xtensa Xilinx KC705 (XT-KC705) board specific definitions */ - -/* 99.9% same as ML605, just indicate we're KC705 and include ML605 header: */ -#define XTBOARD_IS_KC705 1 -#include - diff --git a/tools/sdk/include/esp32/xtensa/xtkc705/xtensa/board.h b/tools/sdk/include/esp32/xtensa/xtkc705/xtensa/board.h deleted file mode 100755 index 5d2d8348021..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtkc705/xtensa/board.h +++ /dev/null @@ -1,13 +0,0 @@ -/* - * board.h - Include board-specific definitions - * - * Copyright (c) 2013 by Tensilica Inc. ALL RIGHTS RESERVED. - * These coded instructions, statements, and computer programs are the - * copyrighted works and confidential proprietary information of Tensilica Inc. - * They may not be modified, copied, reproduced, distributed, or disclosed to - * third parties in any manner, medium, or form, in whole or in part, without - * the prior written consent of Tensilica Inc. - */ - -#include - diff --git a/tools/sdk/include/esp32/xtensa/xtload-api.h b/tools/sdk/include/esp32/xtensa/xtload-api.h deleted file mode 100755 index 4e2297f5108..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtload-api.h +++ /dev/null @@ -1,77 +0,0 @@ -/* Customer ID=11656; Build=0x5f626; Copyright (c) 2003-2012 Tensilica Inc. ALL RIGHTS RESERVED. - These coded instructions, statements, and computer programs are the - copyrighted works and confidential proprietary information of Tensilica Inc. - They may not be modified, copied, reproduced, distributed, or disclosed to - third parties in any manner, medium, or form, in whole or in part, without - the prior written consent of Tensilica Inc. */ - -#ifndef _XTLOAD_API_H -#define _XTLOAD_API_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define XTENSA_BYTES_PER_WORD 4 -#define XLOAD_ALL_CORES -1 - -typedef int core_number_t; -typedef uint32_t xtload_address_t; -typedef uint32_t xtload_word_count_t; -typedef uint32_t * xtload_word_ptr_t; - -/* These functions correspond one-to-one with xt-load script - commands. See the documentation for xt-load for their usage. - - There are however, several higher-level script commands--such as - load-elf-file--which don't have direct analogues here. These - "missing" commands are essentially just macros that result in - several of these commands below. Note that you can execute several - of these commands, then the results of a script, or vice-versa. - */ - -void xtload_bootloader_wake (void); -void xtload_bootloader_sleep (void); -void xtload_bootloader_done (void); -void xtload_bootloader_not_done (void); -void xtload_reset_and_cont (core_number_t core); -void xtload_stall_and_reset (core_number_t core); -#define xtload_reset_and_stall xtload_stall_and_reset -void xtload_stall_and_target (core_number_t core); -void xtload_ignore_and_stall (core_number_t core); -void xtload_ignore_and_cont (core_number_t core); -#define xtload_ignore_and_continue xtload_ignore_and_cont -void xtload_read_words (xtload_address_t addr, xtload_word_count_t count); -void xtload_zero_words (xtload_address_t addr, xtload_word_count_t count); -void xtload_write_words (int swap, xtload_address_t addr, - xtload_word_ptr_t ptr, xtload_word_count_t count); -void xtload_setup_write_words (xtload_address_t addr, xtload_word_count_t count); -void xtload_read_register (core_number_t core); - -/* *I M P O R T A N T* - - The bootloader API calls this function whenever it outputs a word - to the bootloader hardware chain. - - Because the API has no information about how the bootloader - hardware is connected to the host hardware, the user must - implement this function to write a word to the bootloader's register. - - A user's implementation might write the bytes to an Xtensa queue or - to a memory-mapped register. - - For example, xt-load uses this API just like any other client. Its - implementation of this function simply writes this word to an - output file. -*/ - -void xtload_user_output_word (uint32_t word); - -#ifdef __cplusplus -} -#endif - -#endif /* _XTLOAD_API_H */ - diff --git a/tools/sdk/include/esp32/xtensa/xtml605.h b/tools/sdk/include/esp32/xtensa/xtml605.h deleted file mode 100755 index 5f54d700d18..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtml605.h +++ /dev/null @@ -1,338 +0,0 @@ -/* Copyright (c) 2007-2013 by Tensilica Inc. ALL RIGHTS RESERVED. -/ These coded instructions, statements, and computer programs are the -/ copyrighted works and confidential proprietary information of Tensilica Inc. -/ They may not be modified, copied, reproduced, distributed, or disclosed to -/ third parties in any manner, medium, or form, in whole or in part, without -/ the prior written consent of Tensilica Inc. -*/ - -/* xtml605.h - Xtensa Xilinx ML605 (XT-ML605) board specific definitions */ -/* xtkc705.h - Also includes this, for the Xilinx KC705 (XT-KC705). */ - -#ifndef _INC_ML605_H_ -#define _INC_ML605_H_ - -#include -#include - -#if XTBOARD_IS_KC705 -#define XTBOARD_NAME "XT-KC705" -#else -#define XTBOARD_NAME "XT-ML605" -#endif - - -/* - * Default assignment of ML605 devices to external interrupts. - */ - -/* Ethernet interrupt: */ -#ifdef XCHAL_EXTINT1_NUM -#define ETHERNET_INTNUM XCHAL_EXTINT1_NUM -#define ETHERNET_INTLEVEL XCHAL_EXTINT1_LEVEL -#define ETHERNET_INTMASK XCHAL_EXTINT1_MASK -#else -#define ETHERNET_INTMASK 0 -#endif - -/* UART interrupt: */ -#ifdef XCHAL_EXTINT0_NUM -#define UART16550_INTNUM XCHAL_EXTINT0_NUM -#define UART16550_INTLEVEL XCHAL_EXTINT0_LEVEL -#define UART16550_INTMASK XCHAL_EXTINT0_MASK -#else -#define UART16550_INTMASK 0 -#endif - -/* Audio output interrupt (I2S transmitter FIFO): */ -#ifdef XCHAL_EXTINT2_NUM -#define AUDIO_I2S_OUT_INTNUM XCHAL_EXTINT2_NUM -#define AUDIO_I2S_OUT_INTLEVEL XCHAL_EXTINT2_LEVEL -#define AUDIO_I2S_OUT_INTMASK XCHAL_EXTINT2_MASK -#else -#define AUDIO_I2S_OUT_INTMASK 0 -#endif - -/* Audio input interrupt (I2S receiver FIFO): */ -#ifdef XCHAL_EXTINT3_NUM -#define AUDIO_I2S_IN_INTNUM XCHAL_EXTINT3_NUM -#define AUDIO_I2S_IN_INTLEVEL XCHAL_EXTINT3_LEVEL -#define AUDIO_I2S_IN_INTMASK XCHAL_EXTINT3_MASK -#else -#define AUDIO_I2S_IN_INTMASK 0 -#endif - -/* I2C interrupt */ -#ifdef XCHAL_EXTINT4_NUM -#define I2C_INTNUM XCHAL_EXTINT4_NUM -#define I2C_INTLEVEL XCHAL_EXTINT4_LEVEL -#define I2C_INTMASK XCHAL_EXTINT4_MASK -#else -#define I2C_INTMASK 0 -#endif - -/* USB interrupt */ -#ifdef XCHAL_EXTINT5_NUM -#define USB_INTNUM XCHAL_EXTINT5_NUM -#define USB_INTLEVEL XCHAL_EXTINT5_LEVEL -#define USB_INTMASK XCHAL_EXTINT5_MASK -#else -#define USB_INTMASK 0 -#endif - -/* - * Device addresses. - * - * Note: for endianness-independence, use 32-bit loads and stores for all - * register accesses to Ethernet, UART and LED devices. Undefined bits - * may need to be masked out if needed when reading if the actual register - * size is smaller than 32 bits. - * - * Note: ML605 bus byte lanes are defined in terms of msbyte and lsbyte - * relative to the processor. So 32-bit registers are accessed consistently - * from both big and little endian processors. However, this means byte - * sequences are not consistent between big and little endian processors. - * This is fine for RAM, and for ROM if ROM is created for a specific - * processor (and thus has correct byte sequences). However this may be - * unexpected for Flash, which might contain a file-system that one wants - * to use for multiple processor configurations (eg. the Flash might contain - * the Ethernet card's address, endianness-independent application data, etc). - * That is, byte sequences written in Flash by a core of a given endianness - * will be byte-swapped when seen by a core of the other endianness. - * Someone implementing an endianness-independent Flash file system will - * likely handle this byte-swapping issue in the Flash driver software. - */ - -#define ML605_FLASH_MAXSIZE 0x01000000 /* 16 MB */ -#define ML605_FLASH_IOBLOCK_OFS 0x08000000 - -#define KC705_FLASH_MAXSIZE 0x08000000 /* 128 MB */ -#define KC705_FLASH_IOBLOCK_OFS 0x00000000 - -#if XTBOARD_IS_KC705 -#define XTBOARD_FLASH_MAXSIZE KC705_FLASH_MAXSIZE -#define XTBOARD_FLASH_IO_OFS KC705_FLASH_IOBLOCK_OFS -#else -#define XTBOARD_FLASH_MAXSIZE ML605_FLASH_MAXSIZE -#define XTBOARD_FLASH_IO_OFS ML605_FLASH_IOBLOCK_OFS -#endif - -#ifdef XSHAL_IOBLOCK_BYPASS_PADDR - -/* Flash Memory: */ -# define XTBOARD_FLASH_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+XTBOARD_FLASH_IO_OFS) - -/* FPGA registers: */ -# define XTBOARD_FPGAREGS_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D020000) - -/* Ethernet controller/transceiver SONIC SN83934: */ -# define ETHERNET_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D030000) - - -/* UART National-Semi PC16550D: */ -# define UART16550_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D050000) - -/* I2S transmitter */ -# define AUDIO_I2S_OUT_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D080000) - -/* I2S receiver */ -# define AUDIO_I2S_IN_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D088000) - -/* I2C master */ -# define I2C_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D090000) - -/* SPI controller */ -# define SPI_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D0A0000) - -/* Display controller Sunplus SPLC780D, 4bit mode, - * LCD Display MYTech MOC-16216B-B: */ -# define SPLC780D_4BIT_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D0C0000) - -/* USB Controller */ -# define USB_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D0D0000) - -/* Ethernet buffer: */ -# define ETHERNET_BUFFER_PADDR (XSHAL_IOBLOCK_BYPASS_PADDR+0x0D800000) - -#endif /* XSHAL_IOBLOCK_BYPASS_PADDR */ - -/* These devices might be accessed cached: */ -#ifdef XSHAL_IOBLOCK_CACHED_PADDR -# define XTBOARD_FLASH_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+XTBOARD_FLASH_IO_OFS) -# define ETHERNET_BUFFER_CACHED_PADDR (XSHAL_IOBLOCK_CACHED_PADDR+0x0D800000) -#endif /* XSHAL_IOBLOCK_CACHED_PADDR */ - - -/*** Same thing over again, this time with virtual addresses: ***/ - -#ifdef XSHAL_IOBLOCK_BYPASS_VADDR - -/* Flash Memory: */ -# define XTBOARD_FLASH_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+XTBOARD_FLASH_IO_OFS) - -/* FPGA registers: */ -# define XTBOARD_FPGAREGS_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D020000) - -/* Ethernet controller/transceiver SONIC SN83934: */ -# define ETHERNET_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D030000) - - -/* UART National-Semi PC16550D: */ -# define UART16550_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D050000) - -/* I2S transmitter */ -# define AUDIO_I2S_OUT_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D080000) - -/* I2S receiver */ -# define AUDIO_I2S_IN_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D088000) - -/* I2C master */ -# define I2C_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D090000) - -/* SPI controller */ -# define SPI_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D0A0000) - -/* Display controller Sunplus SPLC780D, 4bit mode, - * LCD Display MYTech MOC-16216B-B: */ -# define SPLC780D_4BIT_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D0C0000) - -/* USB Controller */ -# define USB_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D0D0000) - -/* Ethernet buffer: */ -# define ETHERNET_BUFFER_VADDR (XSHAL_IOBLOCK_BYPASS_VADDR+0x0D800000) - -#endif /* XSHAL_IOBLOCK_BYPASS_VADDR */ - -/* These devices might be accessed cached: */ -#ifdef XSHAL_IOBLOCK_CACHED_VADDR -# define XTBOARD_FLASH_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+XTBOARD_FLASH_IO_OFS) -# define ETHERNET_BUFFER_CACHED_VADDR (XSHAL_IOBLOCK_CACHED_VADDR+0x0D800000) -#endif /* XSHAL_IOBLOCK_CACHED_VADDR */ - - -/* System ROM: */ -#define XTBOARD_ROM_SIZE XSHAL_ROM_SIZE -#ifdef XSHAL_ROM_VADDR -#define XTBOARD_ROM_VADDR XSHAL_ROM_VADDR -#endif -#ifdef XSHAL_ROM_PADDR -#define XTBOARD_ROM_PADDR XSHAL_ROM_PADDR -#endif - -/* System RAM: */ -#define XTBOARD_RAM_SIZE XSHAL_RAM_SIZE -#ifdef XSHAL_RAM_VADDR -#define XTBOARD_RAM_VADDR XSHAL_RAM_VADDR -#endif -#ifdef XSHAL_RAM_PADDR -#define XTBOARD_RAM_PADDR XSHAL_RAM_PADDR -#endif -#define XTBOARD_RAM_BYPASS_VADDR XSHAL_RAM_BYPASS_VADDR -#define XTBOARD_RAM_BYPASS_PADDR XSHAL_RAM_BYPASS_PADDR - - - -/* - * Things that depend on device addresses. - */ - - -#define XTBOARD_CACHEATTR_WRITEBACK XSHAL_XT2000_CACHEATTR_WRITEBACK -#define XTBOARD_CACHEATTR_WRITEALLOC XSHAL_XT2000_CACHEATTR_WRITEALLOC -#define XTBOARD_CACHEATTR_WRITETHRU XSHAL_XT2000_CACHEATTR_WRITETHRU -#define XTBOARD_CACHEATTR_BYPASS XSHAL_XT2000_CACHEATTR_BYPASS -#define XTBOARD_CACHEATTR_DEFAULT XSHAL_XT2000_CACHEATTR_DEFAULT - -#define XTBOARD_BUSINT_PIPE_REGIONS XSHAL_XT2000_PIPE_REGIONS -#define XTBOARD_BUSINT_SDRAM_REGIONS XSHAL_XT2000_SDRAM_REGIONS - - -/* - * FPGA registers. - * All these registers are normally accessed using 32-bit loads/stores. - */ - -/* Register offsets: */ -#define XTBOARD_DATECD_OFS 0x00 /* date code (read-only) */ -#define XTBOARD_CLKFRQ_OFS 0x04 /* clock frequency Hz (read-only) */ -#define XTBOARD_SYSLED_OFS 0x08 /* LEDs */ -#define XTBOARD_DIPSW_OFS 0x0C /* DIP switch bits (read-only) */ -#define XTBOARD_SWRST_OFS 0x10 /* software reset */ - -/* Physical register addresses: */ -#ifdef XTBOARD_FPGAREGS_PADDR -#define XTBOARD_DATECD_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_DATECD_OFS) -#define XTBOARD_CLKFRQ_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_CLKFRQ_OFS) -#define XTBOARD_SYSLED_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_SYSLED_OFS) -#define XTBOARD_DIPSW_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_DIPSW_OFS) -#define XTBOARD_SWRST_PADDR (XTBOARD_FPGAREGS_PADDR+XTBOARD_SWRST_OFS) -#endif - -/* Virtual register addresses: */ -#ifdef XTBOARD_FPGAREGS_VADDR -#define XTBOARD_DATECD_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_DATECD_OFS) -#define XTBOARD_CLKFRQ_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_CLKFRQ_OFS) -#define XTBOARD_SYSLED_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_SYSLED_OFS) -#define XTBOARD_DIPSW_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_DIPSW_OFS) -#define XTBOARD_SWRST_VADDR (XTBOARD_FPGAREGS_VADDR+XTBOARD_SWRST_OFS) -/* Register access (for C code): */ -#define XTBOARD_DATECD_REG (*(volatile unsigned*) XTBOARD_DATECD_VADDR) -#define XTBOARD_CLKFRQ_REG (*(volatile unsigned*) XTBOARD_CLKFRQ_VADDR) -#define XTBOARD_SYSLED_REG (*(volatile unsigned*) XTBOARD_SYSLED_VADDR) -#define XTBOARD_DIPSW_REG (*(volatile unsigned*) XTBOARD_DIPSW_VADDR) -#define XTBOARD_SWRST_REG (*(volatile unsigned*) XTBOARD_SWRST_VADDR) -#endif - -/* DATECD (date code; when core was built) bit fields: */ -/* BCD-coded month (01..12): */ -#define XTBOARD_DATECD_MONTH_SHIFT 24 -#define XTBOARD_DATECD_MONTH_BITS 8 -#define XTBOARD_DATECD_MONTH_MASK 0xFF000000 -/* BCD-coded day (01..31): */ -#define XTBOARD_DATECD_DAY_SHIFT 16 -#define XTBOARD_DATECD_DAY_BITS 8 -#define XTBOARD_DATECD_DAY_MASK 0x00FF0000 -/* BCD-coded year (2001..9999): */ -#define XTBOARD_DATECD_YEAR_SHIFT 0 -#define XTBOARD_DATECD_YEAR_BITS 16 -#define XTBOARD_DATECD_YEAR_MASK 0x0000FFFF - -/* SYSLED (system LED) bit fields: */ - -/* LED control bits (off=0, on=1): */ -#define XTBOARD_SYSLED_USER_SHIFT 0 -#define XTBOARD_SYSLED_USER_BITS 2 -#define XTBOARD_SYSLED_USER_MASK 0x00000003 - -/* DIP Switch SW? (left=sw1=lsb=bit0, right=sw4=msb=bit3; off=0, on=1): */ -/* DIP switch bit fields (bit2/sw3 is reserved and presently unused): */ -#if XTBOARD_IS_KC705 -#define XTBOARD_DIPSW_USER_SHIFT 0 -#define XTBOARD_DIPSW_USER_BITS 2 -#define XTBOARD_DIPSW_USER_MASK 0x00000003 -#define XTBOARD_DIPSW_BOOT_SHIFT 3 -#define XTBOARD_DIPSW_BOOT_BITS 1 -#define XTBOARD_DIPSW_BOOT_MASK 0x00000008 -#else /* ML605: */ -#define XTBOARD_DIPSW_USER_SHIFT 0 -#define XTBOARD_DIPSW_USER_BITS 6 -#define XTBOARD_DIPSW_USER_MASK 0x0000003F -#define XTBOARD_DIPSW_BOOT_SHIFT 7 -#define XTBOARD_DIPSW_BOOT_BITS 1 -#define XTBOARD_DIPSW_BOOT_MASK 0x00000080 -#endif /*ML605*/ -#define XTBOARD_DIPSW_BOOT_RAM (0< - diff --git a/tools/sdk/include/esp32/xtensa/xtruntime-core-state.h b/tools/sdk/include/esp32/xtensa/xtruntime-core-state.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/xtruntime-frames.h b/tools/sdk/include/esp32/xtensa/xtruntime-frames.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/xtruntime.h b/tools/sdk/include/esp32/xtensa/xtruntime.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/esp32/xtensa/xtutil.h b/tools/sdk/include/esp32/xtensa/xtutil.h deleted file mode 100755 index fb05c370577..00000000000 --- a/tools/sdk/include/esp32/xtensa/xtutil.h +++ /dev/null @@ -1,61 +0,0 @@ - -/* $Id$ */ -/*******************************************************************************/ -/* Copyright (c) 2001-2013 by Tensilica Inc. ALL RIGHTS RESERVED. */ -/* These coded instructions, statements, and computer programs are the */ -/* copyrighted works and confidential proprietary information of Tensilica Inc.*/ -/* They may not be modified, copied, reproduced, distributed, or disclosed to */ -/* third parties in any manner, medium, or form, in whole or in part, without */ -/* the prior written consent of Tensilica Inc. */ -/*******************************************************************************/ - -#ifndef XTUTIL_H -#define XTUTIL_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -extern int xt_putchar(int c); -extern int xt_puts(const char * s); -extern void xt_putn(unsigned n); -extern int xt_atoi(const char * s); -extern int xt_printf(const char *fmt, ...); -extern int xt_sprintf(char * buf, const char * fmt, ...); - -typedef int xt_output_fn(int *, int, const void *, int); -extern xt_output_fn * xt_set_output_fn(xt_output_fn * fn); - -#ifdef XTUTIL_LIB - -// Only defined if building library - -typedef void (xt_outbuf_fn)(void *, char *, int); - -extern int xt_vprintf(xt_outbuf_fn * out, void * outarg, const char * fmt, va_list ap); - -#else - -// Only defined if building application and overriding - -#ifndef XTUTIL_NO_OVERRIDE - -#define putchar xt_putchar -#define puts xt_puts -#define putn xt_putn -#define atoi xt_atoi -#define printf xt_printf -#define sprintf xt_sprintf - -#endif // XTUTIL_NO_OVERRIDE - -#endif // XTUTIL_LIB - -#ifdef __cplusplus -} -#endif - -#endif // XTUTIL_H - diff --git a/tools/sdk/include/esp_event/esp_event.h b/tools/sdk/include/esp_event/esp_event.h new file mode 100644 index 00000000000..f095844a72b --- /dev/null +++ b/tools/sdk/include/esp_event/esp_event.h @@ -0,0 +1,336 @@ +// 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(); + +/** + * @brief Delete the default event loop + * + * @return + * - ESP_OK: Success + * - Others: Fail + */ +esp_err_t esp_event_loop_delete_default(); + +/** + * @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. + * + * 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_INVALIG_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. + * + * 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 + * + * @return + * - ESP_OK: Success + * - ESP_ERR_NO_MEM: Cannot allocate memory for the handler + * - ESP_ERR_INVALIG_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 Unregister a handler with the system 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 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_INVALIG_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 with the system event loop. + * + * 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_INVALIG_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 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 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 + * + * @note posting events from an ISR is not supported + * + * @return + * - ESP_OK: Success + * - ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired + * - ESP_ERR_INVALIG_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 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 + * + * @note posting events from an ISR is not supported + * + * @return + * - ESP_OK: Success + * - ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired + * - ESP_ERR_INVALIG_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); + +/** + * @brief Dumps statistics of all event loops. + * + * Dumps event loop info in the format: + * + @verbatim + event loop + event + handler + handler + event + handler + handler + event loop + event + handler + ... + ... + ... + + where: + + event loop + format: address,name rx:total_recieved dr:total_dropped inv:total_number_of_invocations run:total_runtime + where: + address - memory address of the event loop + name - name of the event loop + total_recieved - number of successfully posted events + total_number_of_invocations - total number of handler invocations performed so far + total_runtime - total runtime of all invocations so far + + event + format: base:id proc:total_processed run:total_runtime + where: + base - event base + id - event id + total_processed - number of instances of this event that has been processed + total_runtime - total amount of time in microseconds used for invoking handlers of this event + + handler + format: address inv:total_invoked run:total_runtime + where: + address - address of the handler function + 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_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_ \ No newline at end of file diff --git a/tools/sdk/include/esp_event/esp_event_base.h b/tools/sdk/include/esp_event/esp_event_base.h new file mode 100644 index 00000000000..d2fd3804283 --- /dev/null +++ b/tools/sdk/include/esp_event/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 */ + + +// 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/include/esp_http_client/esp_http_client.h b/tools/sdk/include/esp_http_client/esp_http_client.h new file mode 100644 index 00000000000..18b68b88334 --- /dev/null +++ b/tools/sdk/include/esp_http_client/esp_http_client.h @@ -0,0 +1,397 @@ +// 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" + +#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_HEADER_SENT, /*!< After sending all the headers to the server */ + 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_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 */ + const char *client_cert_pem; /*!< SSL client certification, PEM format as string, if the server requires to verify client */ + const char *client_key_pem; /*!< SSL client key, PEM format as string, if the server requires to verify client */ + 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 redirection number, using default value if zero*/ + 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 buffer size (both send and receive) */ + 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. */ +} esp_http_client_config_t; + + +#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 Set http request method + * + * @param[in] client The esp_http_client handle + * @param[in] method The method + * + * @return ESP_OK + */ +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); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/tools/sdk/include/esp_http_server/esp_http_server.h b/tools/sdk/include/esp_http_server/esp_http_server.h new file mode 100644 index 00000000000..7d4b1a63e02 --- /dev/null +++ b/tools/sdk/include/esp_http_server/esp_http_server.h @@ -0,0 +1,1203 @@ +// 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, \ + .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, \ +} + +#define ESP_ERR_HTTPD_BASE (0x8000) /*!< 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 */ + +/* ************** 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 status + */ +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 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 */ + + /** + * 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() + */ + 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; +} 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; +} 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: 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 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, -1 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 data from the buffer that should be sent out, -1 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); + +/* 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 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 + */ +esp_err_t httpd_resp_send_404(httpd_req_t *r); + +/** + * @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 + */ +esp_err_t httpd_resp_send_408(httpd_req_t *r); + +/** + * @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 + */ +esp_err_t httpd_resp_send_500(httpd_req_t *r); + +/** + * @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); + +/** 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); + +/** 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 + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! _ESP_HTTP_SERVER_H_ */ diff --git a/tools/sdk/include/esp_http_server/http_server.h b/tools/sdk/include/esp_http_server/http_server.h new file mode 100644 index 00000000000..56f73c5b74c --- /dev/null +++ b/tools/sdk/include/esp_http_server/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/include/esp_https_ota/esp_https_ota.h b/tools/sdk/include/esp_https_ota/esp_https_ota.h new file mode 100644 index 00000000000..157195601c7 --- /dev/null +++ b/tools/sdk/include/esp_https_ota/esp_https_ota.h @@ -0,0 +1,45 @@ +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief HTTPS OTA Firmware upgrade. + * + * This function performs HTTPS OTA Firmware upgrade + * + * @param[in] config pointer to esp_http_client_config_t structure. + * + * @note For secure HTTPS updates, the `cert_pem` member of `config` + * structure must be set to the server certificate. + * + * @return + * - ESP_OK: OTA data updated, next reboot will use specified partition. + * - ESP_FAIL: For generic failure. + * - 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); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/esp_ringbuf/freertos/ringbuf.h b/tools/sdk/include/esp_ringbuf/freertos/ringbuf.h new file mode 100644 index 00000000000..de8a3690952 --- /dev/null +++ b/tools/sdk/include/esp_ringbuf/freertos/ringbuf.h @@ -0,0 +1,415 @@ +// 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 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_t; + +/** + * @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, ringbuf_type_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 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 timesout. + * + * @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 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 timesout. + * + * @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 + * + * @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 timesout. + * + * @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 timesout. + * + * @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 + * + * @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 + */ +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 + * + * @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 + * + * @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] 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 *uxItemsWaiting); + +/** + * @brief Debugging function to print the internal pointers in the ring buffer + * + * @param xRingbuffer Ring buffer to show + */ +void xRingbufferPrintInfo(RingbufHandle_t xRingbuffer); + +/* -------------------------------- Deprecated Functions --------------------------- */ + +/** @cond */ //Doxygen command to hide deprecated function from API Reference +/* + * Deprecated as function is not thread safe and does not check if an item is + * actually available for retrieval. Use xRingbufferReceiveSplit() instead for + * thread safe method of retrieve a split item. + */ +bool xRingbufferIsNextItemWrapped(RingbufHandle_t xRingbuffer) __attribute__((deprecated)); + +/* + * Deprecated as queue sets are not meant to be used for writing to buffers. Adding + * the ring buffer write semaphore to a queue set will break queue set usage rules, + * as every read of a semaphore must be preceded by a call to xQueueSelectFromSet(). + * QueueSetWrite no longer supported. + */ +BaseType_t xRingbufferAddToQueueSetWrite(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet) __attribute__((deprecated)); + +/* + * Deprecated as queue sets are not meant to be used for writing to buffers. + * QueueSetWrite no longer supported. + */ +BaseType_t xRingbufferRemoveFromQueueSetWrite(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet) __attribute__((deprecated)); +/** @endcond */ + +#ifdef __cplusplus +} +#endif + +#endif /* FREERTOS_RINGBUF_H */ + diff --git a/tools/sdk/include/ethernet/esp_eth.h b/tools/sdk/include/ethernet/esp_eth.h index f4622d0ee7b..f22cf4f7013 100644 --- a/tools/sdk/include/ethernet/esp_eth.h +++ b/tools/sdk/include/ethernet/esp_eth.h @@ -15,76 +15,95 @@ #ifndef __ESP_ETH_H__ #define __ESP_ETH_H__ -#include -#include -#include "esp_err.h" - #ifdef __cplusplus extern "C" { #endif +#include "esp_types.h" +#include "esp_err.h" + +/** + * @brief Ethernet interface mode + * + */ typedef enum { - ETH_MODE_RMII = 0, - ETH_MODE_MII, + ETH_MODE_RMII = 0, /*!< RMII mode */ + ETH_MODE_MII, /*!< MII mode */ } eth_mode_t; -typedef enum { - ETH_CLOCK_GPIO0_IN = 0, - ETH_CLOCK_GPIO0_OUT = 1, - ETH_CLOCK_GPIO16_OUT = 2, - ETH_CLOCK_GPIO17_OUT = 3 +/** + * @brief Ethernet clock mode + * + */ +typedef enum { + ETH_CLOCK_GPIO0_IN = 0, /*!< RMII clock input to GPIO0 */ + ETH_CLOCK_GPIO0_OUT = 1, /*!< RMII clock output from GPIO0 */ + ETH_CLOCK_GPIO16_OUT = 2, /*!< RMII clock output from GPIO16 */ + ETH_CLOCK_GPIO17_OUT = 3 /*!< RMII clock output from GPIO17 */ } eth_clock_mode_t; +/** + * @brief Ethernet Speed + * + */ typedef enum { - ETH_SPEED_MODE_10M = 0, - ETH_SPEED_MODE_100M, + ETH_SPEED_MODE_10M = 0, /*!< Ethernet speed: 10Mbps */ + ETH_SPEED_MODE_100M, /*!< Ethernet speed: 100Mbps */ } eth_speed_mode_t; +/** + * @brief Ethernet Duplex + * + */ typedef enum { - ETH_MODE_HALFDUPLEX = 0, - ETH_MODE_FULLDUPLEX, + ETH_MODE_HALFDUPLEX = 0, /*!< Ethernet half duplex */ + ETH_MODE_FULLDUPLEX, /*!< Ethernet full duplex */ } eth_duplex_mode_t; +/** + * @brief Ethernet PHY address + * + */ typedef enum { - PHY0 = 0, - PHY1, - PHY2, - PHY3, - PHY4, - PHY5, - PHY6, - PHY7, - PHY8, - PHY9, - PHY10, - PHY11, - PHY12, - PHY13, - PHY14, - PHY15, - PHY16, - PHY17, - PHY18, - PHY19, - PHY20, - PHY21, - PHY22, - PHY23, - PHY24, - PHY25, - PHY26, - PHY27, - PHY28, - PHY29, - PHY30, - PHY31, + PHY0 = 0, /*!< PHY address 0 */ + PHY1, /*!< PHY address 1 */ + PHY2, /*!< PHY address 2 */ + PHY3, /*!< PHY address 3 */ + PHY4, /*!< PHY address 4 */ + PHY5, /*!< PHY address 5 */ + PHY6, /*!< PHY address 6 */ + PHY7, /*!< PHY address 7 */ + PHY8, /*!< PHY address 8 */ + PHY9, /*!< PHY address 9 */ + PHY10, /*!< PHY address 10 */ + PHY11, /*!< PHY address 11 */ + PHY12, /*!< PHY address 12 */ + PHY13, /*!< PHY address 13 */ + PHY14, /*!< PHY address 14 */ + PHY15, /*!< PHY address 15 */ + PHY16, /*!< PHY address 16 */ + PHY17, /*!< PHY address 17 */ + PHY18, /*!< PHY address 18 */ + PHY19, /*!< PHY address 19 */ + PHY20, /*!< PHY address 20 */ + PHY21, /*!< PHY address 21 */ + PHY22, /*!< PHY address 22 */ + PHY23, /*!< PHY address 23 */ + PHY24, /*!< PHY address 24 */ + PHY25, /*!< PHY address 25 */ + PHY26, /*!< PHY address 26 */ + PHY27, /*!< PHY address 27 */ + PHY28, /*!< PHY address 28 */ + PHY29, /*!< PHY address 29 */ + PHY30, /*!< PHY address 30 */ + PHY31 /*!< PHY address 31 */ } eth_phy_base_t; typedef bool (*eth_phy_check_link_func)(void); typedef void (*eth_phy_check_init_func)(void); typedef eth_speed_mode_t (*eth_phy_get_speed_mode_func)(void); typedef eth_duplex_mode_t (*eth_phy_get_duplex_mode_func)(void); -typedef void (*eth_phy_func)(void); +typedef esp_err_t (*eth_phy_func)(void); typedef esp_err_t (*eth_tcpip_input_func)(void *buffer, uint16_t len, void *eb); typedef void (*eth_gpio_config_func)(void); typedef bool (*eth_phy_get_partner_pause_enable_func)(void); @@ -95,27 +114,27 @@ typedef void (*eth_phy_power_enable_func)(bool enable); * */ typedef struct { - eth_phy_base_t phy_addr; /*!< phy base addr (0~31) */ - eth_mode_t mac_mode; /*!< mac mode only support RMII now */ - eth_clock_mode_t clock_mode; /*!< external/internal clock mode selecton */ - eth_tcpip_input_func tcpip_input; /*!< tcpip input func */ - eth_phy_func phy_init; /*!< phy init func */ - eth_phy_check_link_func phy_check_link; /*!< phy check link func */ - eth_phy_check_init_func phy_check_init; /*!< phy check init func */ - eth_phy_get_speed_mode_func phy_get_speed_mode; /*!< phy check init func */ - eth_phy_get_duplex_mode_func phy_get_duplex_mode; /*!< phy check init func */ - eth_gpio_config_func gpio_config; /*!< gpio config func */ - bool flow_ctrl_enable; /*!< flag of flow ctrl enable */ - eth_phy_get_partner_pause_enable_func phy_get_partner_pause_enable; /*!< get partner pause enable */ - eth_phy_power_enable_func phy_power_enable; /*!< enable or disable phy power */ - + eth_phy_base_t phy_addr; /*!< PHY address (0~31) */ + eth_mode_t mac_mode; /*!< MAC mode: only support RMII now */ + eth_clock_mode_t clock_mode; /*!< external/internal clock mode selection */ + eth_tcpip_input_func tcpip_input; /*!< tcpip input func */ + eth_phy_func phy_init; /*!< phy init func */ + eth_phy_check_link_func phy_check_link; /*!< phy check link func */ + eth_phy_check_init_func phy_check_init; /*!< phy check init func */ + eth_phy_get_speed_mode_func phy_get_speed_mode; /*!< phy check init func */ + eth_phy_get_duplex_mode_func phy_get_duplex_mode; /*!< phy check init func */ + eth_gpio_config_func gpio_config; /*!< gpio config func */ + bool flow_ctrl_enable; /*!< flag of flow ctrl enable */ + eth_phy_get_partner_pause_enable_func phy_get_partner_pause_enable; /*!< get partner pause enable */ + eth_phy_power_enable_func phy_power_enable; /*!< enable or disable phy power */ + uint32_t reset_timeout_ms; /*!< timeout value for reset emac */ + bool promiscuous_enable; /*!< set true to enable promiscuous mode */ } eth_config_t; - /** * @brief Init ethernet mac * - * @note config can not be NULL,and phy chip must be suitable to phy init func. + * @note config can not be NULL, and phy chip must be suitable to phy init func. * * @param[in] config mac init data. * @@ -125,6 +144,16 @@ typedef struct { */ esp_err_t esp_eth_init(eth_config_t *config); +/** + * @brief Deinit ethernet mac + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_INVALID_STATE + */ +esp_err_t esp_eth_deinit(void); + /** * @brief Init Ethernet mac driver only * @@ -134,7 +163,7 @@ esp_err_t esp_eth_init(eth_config_t *config); * This function may be called, if you only need to initialize the Ethernet * driver without having to use the network stack on top. * - * @note config can not be NULL,and phy chip must be suitable to phy init func. + * @note config can not be NULL, and phy chip must be suitable to phy init func. * @param[in] config mac init data. * * @return @@ -146,7 +175,7 @@ esp_err_t esp_eth_init_internal(eth_config_t *config); /** * @brief Send packet from tcp/ip to mac * - * @note buf can not be NULL,size must be less than 1580 + * @note buf can not be NULL, size must be less than 1580 * * @param[in] buf: start address of packet data. * @@ -161,7 +190,7 @@ esp_err_t esp_eth_tx(uint8_t *buf, uint16_t size); /** * @brief Enable ethernet interface * - * @note Shout be called after esp_eth_init + * @note Should be called after esp_eth_init * * @return * - ESP_OK @@ -172,7 +201,7 @@ esp_err_t esp_eth_enable(void); /** * @brief Disable ethernet interface * - * @note Shout be called after esp_eth_init + * @note Should be called after esp_eth_init * * @return * - ESP_OK @@ -190,24 +219,24 @@ esp_err_t esp_eth_disable(void); void esp_eth_get_mac(uint8_t mac[6]); /** - * @brief Read phy reg with smi interface. + * @brief Write PHY reg with SMI interface. * - * @note phy base addr must be right. + * @note PHY base addr must be right. * - * @param[in] reg_num: phy reg num. + * @param[in] reg_num: PHY reg num. * - * @param[in] value: value which write to phy reg. + * @param[in] value: value which is written to PHY reg. */ void esp_eth_smi_write(uint32_t reg_num, uint16_t value); /** - * @brief Read phy reg with smi interface. + * @brief Read PHY reg with SMI interface. * - * @note phy base addr must be right. + * @note PHY base addr must be right. * - * @param[in] reg_num: phy reg num. + * @param[in] reg_num: PHY reg num. * - * @return value what read from phy reg + * @return value that is read from PHY reg */ uint16_t esp_eth_smi_read(uint32_t reg_num); @@ -236,41 +265,42 @@ esp_err_t esp_eth_smi_wait_value(uint32_t reg_num, uint16_t value, uint16_t valu * * @return ESP_OK if desired value matches, ESP_ERR_TIMEOUT if timed out. */ -static inline esp_err_t esp_eth_smi_wait_set(uint32_t reg_num, uint16_t value_mask, int timeout_ms) { +static inline esp_err_t esp_eth_smi_wait_set(uint32_t reg_num, uint16_t value_mask, int timeout_ms) +{ return esp_eth_smi_wait_value(reg_num, value_mask, value_mask, timeout_ms); } /** * @brief Free emac rx buf. * - * @note buf can not be null,and it is tcpip input buf. + * @note buf can not be null, and it is tcpip input buf. * - * @param[in] buf: start address of recevie packet data. + * @param[in] buf: start address of received packet data. * */ void esp_eth_free_rx_buf(void *buf); -/** - * @brief Get mac of ethernet interface. - * - * @param[out] mac: store mac of the interface. - * - */ -void esp_eth_get_mac(uint8_t mac[6]); - /** * @brief Set mac of ethernet interface. * - * @note user can call this function after emac_init,and the new mac address will be enabled after emac_enable. + * @note user can call this function after emac_init, and the new mac address will be enabled after emac_enable. * * @param[in] mac: the Mac address. * - * @return + * @return * - ESP_OK: succeed * - ESP_ERR_INVALID_MAC: invalid mac address */ esp_err_t esp_eth_set_mac(const uint8_t mac[6]); +/** + * @brief Get Ethernet link speed + * + * @return eth_speed_mode_t ETH_SPEED_MODE_10M when link speed is 10Mbps + * ETH_SPEED_MODE_100M when link speed is 100Mbps + */ +eth_speed_mode_t esp_eth_get_speed(void); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/ethernet/eth_phy/phy.h b/tools/sdk/include/ethernet/eth_phy/phy.h index 18b8f3f6c97..d38e9819d6d 100644 --- a/tools/sdk/include/ethernet/eth_phy/phy.h +++ b/tools/sdk/include/ethernet/eth_phy/phy.h @@ -20,38 +20,55 @@ extern "C" { #include "esp_eth.h" -/** Common PHY-management functions. - - These are not enough to drive any particular Ethernet PHY, but they provide a common configuration structure and - management functions. -*/ - -/** Configure fixed pins for RMII data interface. - - This configures GPIOs 0, 19, 22, 25, 26, 27 for use with RMII - data interface. These pins cannot be changed, and must be wired to - ethernet functions. +/** + * @brief Common PHY-management functions. + * + * @note These are not enough to drive any particular Ethernet PHY. + * They provide a common configuration structure and management functions. + * + */ - This is not sufficient to fully configure the Ethernet PHY, - MDIO configuration interface pins (such as SMI MDC, MDO, MDI) - must also be configured correctly in the GPIO matrix. -*/ +/** + * @brief Configure fixed pins for RMII data interface. + * + * @note This configures GPIOs 0, 19, 22, 25, 26, 27 for use with RMII data interface. + * These pins cannot be changed, and must be wired to ethernet functions. + * This is not sufficient to fully configure the Ethernet PHY. + * MDIO configuration interface pins (such as SMI MDC, MDO, MDI) must also be configured correctly in the GPIO matrix. + * + */ void phy_rmii_configure_data_interface_pins(void); -/** Configure variable pins for SMI (MDIO) ethernet functions. - - Calling this function along with mii_configure_default_pins() will - fully configure the GPIOs for the ethernet PHY. +/** + * @brief Configure variable pins for SMI ethernet functions. + * + * @param mdc_gpio MDC GPIO Pin number + * @param mdio_gpio MDIO GPIO Pin number + * + * @note Calling this function along with mii_configure_default_pins() will fully configure the GPIOs for the ethernet PHY. */ void phy_rmii_smi_configure_pins(uint8_t mdc_gpio, uint8_t mdio_gpio); - -/** Enable flow control in standard PHY MII register. +/** + * @brief Enable flow control in standard PHY MII register. + * */ void phy_mii_enable_flow_ctrl(void); +/** + * @brief Check Ethernet link status via MII interface + * + * @return true Link is on + * @return false Link is off + */ bool phy_mii_check_link_status(void); +/** + * @brief Check pause frame ability of partner via MII interface + * + * @return true Partner is able to process pause frame + * @return false Partner can not process pause frame + */ bool phy_mii_get_partner_pause_enable(void); #ifdef __cplusplus diff --git a/tools/sdk/include/ethernet/eth_phy/phy_ip101.h b/tools/sdk/include/ethernet/eth_phy/phy_ip101.h new file mode 100644 index 00000000000..d18ef2d0964 --- /dev/null +++ b/tools/sdk/include/ethernet/eth_phy/phy_ip101.h @@ -0,0 +1,75 @@ +// 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 "phy.h" + +/** + * @brief Dump IP101 PHY SMI configuration registers + * + */ +void phy_ip101_dump_registers(); + +/** + * @brief Default IP101 phy_check_init function + * + */ +void phy_ip101_check_phy_init(void); + +/** + * @brief Default IP101 phy_get_speed_mode function + * + * @return eth_speed_mode_t Ethernet speed mode + */ +eth_speed_mode_t phy_ip101_get_speed_mode(void); + +/** + * @brief Default IP101 phy_get_duplex_mode function + * + * @return eth_duplex_mode_t Ethernet duplex mode + */ +eth_duplex_mode_t phy_ip101_get_duplex_mode(void); + +/** + * @brief Default IP101 phy_power_enable function + * + */ +void phy_ip101_power_enable(bool); + +/** + * @brief Default IP101 phy_init function + * + * @return esp_err_t + * - ESP_OK on success + * - ESP_FAIL on error + */ +esp_err_t phy_ip101_init(void); + +/** + * @brief Default IP101 PHY configuration + * + * @note This configuration is not suitable for use as-is, + * it will need to be modified for your particular PHY hardware setup. + * + */ +extern const eth_config_t phy_ip101_default_ethernet_config; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/ethernet/eth_phy/phy_lan8720.h b/tools/sdk/include/ethernet/eth_phy/phy_lan8720.h index 8c579ef5e40..1448f36556c 100644 --- a/tools/sdk/include/ethernet/eth_phy/phy_lan8720.h +++ b/tools/sdk/include/ethernet/eth_phy/phy_lan8720.h @@ -20,45 +20,53 @@ extern "C" { #include "phy.h" - -/** @brief Dump all LAN8720 PHY SMI configuration registers +/** + * @brief Dump LAN8720 PHY SMI configuration registers * - * @note These registers are dumped at 'debug' level, so output - * may not be visible depending on default log levels. */ void phy_lan8720_dump_registers(); -/** @brief Default LAN8720 phy_check_init function. +/** + * @brief Default LAN8720 phy_check_init function + * */ void phy_lan8720_check_phy_init(void); -/** @brief Default LAN8720 phy_get_speed_mode function. +/** + * @brief Default LAN8720 phy_get_speed_mode function + * + * @return eth_speed_mode_t Ethernet speed mode */ eth_speed_mode_t phy_lan8720_get_speed_mode(void); -/** @brief Default LAN8720 phy_get_duplex_mode function. +/** + * @brief Default LAN8720 phy_get_duplex_mode function + * + * @return eth_duplex_mode_t Ethernet duplex mode */ eth_duplex_mode_t phy_lan8720_get_duplex_mode(void); -/** @brief Default LAN8720 phy_power_enable function. - * - * @note This function may need to be replaced with a custom function - * if the PHY has a GPIO to enable power or start a clock. +/** + * @brief Default LAN8720 phy_power_enable function * - * Consult the ethernet example to see how this is done. */ void phy_lan8720_power_enable(bool); -/** @brief Default LAN8720 phy_init function. +/** + * @brief Default LAN8720 phy_init function + * + * @return esp_err_t + * - ESP_OK on success + * - ESP_FAIL on error */ -void phy_lan8720_init(void); +esp_err_t phy_lan8720_init(void); -/** @brief Default LAN8720 PHY configuration +/** + * @brief Default LAN8720 PHY configuration * - * This configuration is not suitable for use as-is, it will need - * to be modified for your particular PHY hardware setup. + * @note This configuration is not suitable for use as-is, + * it will need to be modified for your particular PHY hardware setup. * - * Consult the Ethernet example to see how this is done. */ extern const eth_config_t phy_lan8720_default_ethernet_config; diff --git a/tools/sdk/include/ethernet/eth_phy/phy_reg.h b/tools/sdk/include/ethernet/eth_phy/phy_reg.h index 33c9a064a3a..2a9a141676a 100644 --- a/tools/sdk/include/ethernet/eth_phy/phy_reg.h +++ b/tools/sdk/include/ethernet/eth_phy/phy_reg.h @@ -14,24 +14,41 @@ #pragma once -/* This header contains register/bit masks for the standard - PHY MII registers that should be supported by all PHY models. -*/ - -#define MII_BASIC_MODE_CONTROL_REG (0x0) -#define MII_SOFTWARE_RESET BIT(15) - -#define MII_BASIC_MODE_STATUS_REG (0x1) -#define MII_AUTO_NEGOTIATION_COMPLETE BIT(5) -#define MII_LINK_STATUS BIT(2) - -#define MII_PHY_IDENTIFIER_1_REG (0x2) -#define MII_PHY_IDENTIFIER_2_REG (0x3) - -#define MII_AUTO_NEG_ADVERTISEMENT_REG (0x4) -#define MII_ASM_DIR BIT(11) -#define MII_PAUSE BIT(10) - -#define MII_PHY_LINK_PARTNER_ABILITY_REG (0x5) -#define MII_PARTNER_ASM_DIR BIT(11) -#define MII_PARTNER_PAUSE BIT(10) +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief This header contains register/bit masks for the standard PHY MII registers that should be supported by all PHY models. + * + */ + +#define MII_BASIC_MODE_CONTROL_REG (0x0) +#define MII_SOFTWARE_RESET BIT(15) +#define MII_SPEED_SELECT BIT(13) +#define MII_AUTO_NEGOTIATION_ENABLE BIT(12) +#define MII_POWER_DOWN BIT(11) +#define MII_RESTART_AUTO_NEGOTIATION BIT(9) +#define MII_DUPLEX_MODE BIT(8) + +#define MII_BASIC_MODE_STATUS_REG (0x1) +#define MII_AUTO_NEGOTIATION_COMPLETE BIT(5) +#define MII_LINK_STATUS BIT(2) + +#define MII_PHY_IDENTIFIER_1_REG (0x2) +#define MII_PHY_IDENTIFIER_2_REG (0x3) + +#define MII_AUTO_NEGOTIATION_ADVERTISEMENT_REG (0x4) +#define MII_ASM_DIR BIT(11) +#define MII_PAUSE BIT(10) + +#define MII_PHY_LINK_PARTNER_ABILITY_REG (0x5) +#define MII_PARTNER_ASM_DIR BIT(11) +#define MII_PARTNER_PAUSE BIT(10) + +/******************************legacy*******************************/ +#define MII_AUTO_NEG_ADVERTISEMENT_REG MII_AUTO_NEGOTIATION_ADVERTISEMENT_REG + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/ethernet/eth_phy/phy_tlk110.h b/tools/sdk/include/ethernet/eth_phy/phy_tlk110.h index ff61c322c7a..077f13cece0 100644 --- a/tools/sdk/include/ethernet/eth_phy/phy_tlk110.h +++ b/tools/sdk/include/ethernet/eth_phy/phy_tlk110.h @@ -20,44 +20,53 @@ extern "C" { #include "phy.h" -/** @brief Dump all TLK110 PHY SMI configuration registers +/** + * @brief Dump TLK110 PHY SMI configuration registers * - * @note These registers are dumped at 'debug' level, so output - * may not be visible depending on default log levels. */ void phy_tlk110_dump_registers(); -/** @brief Default TLK110 phy_check_init function. +/** + * @brief Default TLK110 phy_check_init function + * */ void phy_tlk110_check_phy_init(void); -/** @brief Default TLK110 phy_get_speed_mode function. +/** + * @brief Default TLK110 phy_get_speed_mode function + * + * @return eth_speed_mode_t Ethernet speed mode */ eth_speed_mode_t phy_tlk110_get_speed_mode(void); -/** @brief Default TLK110 phy_get_duplex_mode function. +/** + * @brief Default TLK110 phy_get_duplex_mode function + * + * @return eth_duplex_mode_t Ethernet duplex mode */ eth_duplex_mode_t phy_tlk110_get_duplex_mode(void); -/** @brief Default TLK110 phy_power_enable function. +/** + * @brief Default TLK110 phy_power_enable function * - * @note This function may need to be replaced with a custom function - * if the PHY has a GPIO to enable power or start a clock. - * - * Consult the ethernet example to see how this is done. */ void phy_tlk110_power_enable(bool); -/** @brief Default TLK110 phy_init function. +/** + * @brief Default TLK110 phy_init function + * + * @return esp_err_t + * - ESP_OK on success + * - ESP_FAIL on error */ -void phy_tlk110_init(void); +esp_err_t phy_tlk110_init(void); -/** @brief Default TLK110 PHY configuration +/** + * @brief Default TLK110 PHY configuration * - * This configuration is not suitable for use as-is, it will need - * to be modified for your particular PHY hardware setup. + * @note This configuration is not suitable for use as-is, + * it will need to be modified for your particular PHY hardware setup. * - * Consult the Ethernet example to see how this is done. */ extern const eth_config_t phy_tlk110_default_ethernet_config; diff --git a/tools/sdk/include/expat/ascii.h b/tools/sdk/include/expat/ascii.h index d10530b09bd..c3587e57332 100644 --- a/tools/sdk/include/expat/ascii.h +++ b/tools/sdk/include/expat/ascii.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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 diff --git a/tools/sdk/include/expat/asciitab.h b/tools/sdk/include/expat/asciitab.h index 79a15c28ca1..2f59fd92906 100644 --- a/tools/sdk/include/expat/asciitab.h +++ b/tools/sdk/include/expat/asciitab.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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, diff --git a/tools/sdk/include/expat/chardata.h b/tools/sdk/include/expat/chardata.h deleted file mode 100644 index e8dc4ce22c4..00000000000 --- a/tools/sdk/include/expat/chardata.h +++ /dev/null @@ -1,40 +0,0 @@ -/* chardata.h - - Interface to some helper routines used to accumulate and check text - and attribute content. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef XML_CHARDATA_H -#define XML_CHARDATA_H 1 - -#ifndef XML_VERSION -#include "expat.h" /* need XML_Char */ -#endif - - -typedef struct { - int count; /* # of chars, < 0 if not set */ - XML_Char data[1024]; -} CharData; - - -void CharData_Init(CharData *storage); - -void CharData_AppendString(CharData *storage, const char *s); - -void CharData_AppendXMLChars(CharData *storage, const XML_Char *s, int len); - -int CharData_CheckString(CharData *storage, const char *s); - -int CharData_CheckXMLChars(CharData *storage, const XML_Char *s); - - -#endif /* XML_CHARDATA_H */ - -#ifdef __cplusplus -} -#endif diff --git a/tools/sdk/include/expat/expat.h b/tools/sdk/include/expat/expat.h index 086e24b39c5..1f608c02d6f 100644 --- a/tools/sdk/include/expat/expat.h +++ b/tools/sdk/include/expat/expat.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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 @@ -24,7 +52,6 @@ extern "C" { struct XML_ParserStruct; typedef struct XML_ParserStruct *XML_Parser; -/* Should this be defined using stdbool.h when C99 is available? */ typedef unsigned char XML_Bool; #define XML_TRUE ((XML_Bool) 1) #define XML_FALSE ((XML_Bool) 0) @@ -95,7 +122,9 @@ enum XML_Error { /* Added in 2.0. */ XML_ERROR_RESERVED_PREFIX_XML, XML_ERROR_RESERVED_PREFIX_XMLNS, - XML_ERROR_RESERVED_NAMESPACE_URI + XML_ERROR_RESERVED_NAMESPACE_URI, + /* Added in 2.2.1. */ + XML_ERROR_INVALID_ARGUMENT }; enum XML_Content_Type { @@ -706,6 +735,7 @@ XML_UseParserAsHandlerArg(XML_Parser parser); 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); @@ -729,15 +759,16 @@ XML_GetBase(XML_Parser parser); 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. + 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. Each - attribute/value pair counts as 2; thus this correspondds to an - index into the atts array passed to the XML_StartElementHandler. + 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); @@ -901,6 +932,7 @@ enum XML_ParamEntityParsing { 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, @@ -910,6 +942,7 @@ XML_SetParamEntityParsing(XML_Parser parser, 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, @@ -936,6 +969,10 @@ XML_GetErrorCode(XML_Parser parser); 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); @@ -1039,7 +1076,7 @@ XML_GetFeatureList(void); */ #define XML_MAJOR_VERSION 2 #define XML_MINOR_VERSION 2 -#define XML_MICRO_VERSION 0 +#define XML_MICRO_VERSION 5 #ifdef __cplusplus } diff --git a/tools/sdk/include/expat/expat_config.h b/tools/sdk/include/expat/expat_config.h index 207d1a7791d..b6b927a19bb 100644 --- a/tools/sdk/include/expat/expat_config.h +++ b/tools/sdk/include/expat/expat_config.h @@ -3,7 +3,6 @@ /* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */ #define BYTEORDER 1234 - /* Define to 1 if you have the `bcopy' function. */ #define HAVE_BCOPY 1 @@ -15,7 +14,6 @@ /* 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 @@ -52,10 +50,12 @@ /* Define to 1 if you have the header file. */ #define HAVE_UNISTD_H 1 -/* Define to the sub-directory in which libtool stores uninstalled libraries. - */ +/* 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" @@ -63,7 +63,7 @@ #define PACKAGE_NAME "expat" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "expat 2.2.0" +#define PACKAGE_STRING "expat 2.2.5" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "expat" @@ -72,11 +72,14 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "2.2.0" +#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 */ @@ -90,9 +93,6 @@ /* Define to make XML Namespaces functionality available. */ #define XML_NS 1 -/* Define to __FUNCTION__ or "" if `__func__' does not conform to ANSI C. */ -/* #undef __func__ */ - /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */ diff --git a/tools/sdk/include/expat/expat_external.h b/tools/sdk/include/expat/expat_external.h index aa08a2f84c0..629483a91b2 100644 --- a/tools/sdk/include/expat/expat_external.h +++ b/tools/sdk/include/expat/expat_external.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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 @@ -8,7 +36,7 @@ /* External API definitions */ #if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__) -#define XML_USE_MSC_EXTENSIONS 1 +# define XML_USE_MSC_EXTENSIONS 1 #endif /* Expat tries very hard to make the API boundary very specifically @@ -34,11 +62,11 @@ 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 +# 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 @@ -49,41 +77,41 @@ pre-processor and how to specify the same calling convention as the platform's malloc() implementation. */ -#define XMLCALL -#endif +# define XMLCALL +# endif #endif /* not defined XMLCALL */ #if !defined(XML_STATIC) && !defined(XMLIMPORT) -#ifndef XML_BUILDING_EXPAT +# ifndef XML_BUILDING_EXPAT /* using Expat from an application */ -#ifdef XML_USE_MSC_EXTENSIONS -#define XMLIMPORT __declspec(dllimport) -#endif +# ifdef XML_USE_MSC_EXTENSIONS +# define XMLIMPORT __declspec(dllimport) +# endif -#endif +# endif #endif /* not defined XML_STATIC */ #if !defined(XMLIMPORT) && defined(__GNUC__) && (__GNUC__ >= 4) -#define XMLIMPORT __attribute__ ((visibility ("default"))) +# define XMLIMPORT __attribute__ ((visibility ("default"))) #endif /* If we didn't define it above, define it away: */ #ifndef XMLIMPORT -#define XMLIMPORT +# define XMLIMPORT #endif #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)) -#define XML_ATTR_MALLOC __attribute__((__malloc__)) +# define XML_ATTR_MALLOC __attribute__((__malloc__)) #else -#define XML_ATTR_MALLOC +# 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))) +# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) #else -#define XML_ATTR_ALLOC_SIZE(x) +# define XML_ATTR_ALLOC_SIZE(x) #endif #define XMLPARSEAPI(type) XMLIMPORT type XMLCALL @@ -93,30 +121,35 @@ extern "C" { #endif #ifdef XML_UNICODE_WCHAR_T -#define XML_UNICODE +# 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 +# ifdef XML_UNICODE_WCHAR_T typedef wchar_t XML_Char; typedef wchar_t XML_LChar; -#else +# else typedef unsigned short XML_Char; typedef char XML_LChar; -#endif /* XML_UNICODE_WCHAR_T */ +# 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 +# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400 typedef __int64 XML_Index; typedef unsigned __int64 XML_Size; -#else +# else typedef long long XML_Index; typedef unsigned long long XML_Size; -#endif +# endif #else typedef long XML_Index; typedef unsigned long XML_Size; diff --git a/tools/sdk/include/expat/iasciitab.h b/tools/sdk/include/expat/iasciitab.h index 24a1d5ccc9a..ce4a4bf7ede 100644 --- a/tools/sdk/include/expat/iasciitab.h +++ b/tools/sdk/include/expat/iasciitab.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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 */ diff --git a/tools/sdk/include/expat/internal.h b/tools/sdk/include/expat/internal.h index 94cb98e15ca..e33fdcb0238 100644 --- a/tools/sdk/include/expat/internal.h +++ b/tools/sdk/include/expat/internal.h @@ -18,6 +18,35 @@ 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__) @@ -87,7 +116,7 @@ extern "C" { void -align_limit_to_full_utf8_characters(const char * from, const char ** fromLimRef); +_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef); #ifdef __cplusplus diff --git a/tools/sdk/include/expat/latin1tab.h b/tools/sdk/include/expat/latin1tab.h index 53c25d76b26..95dfa52b1fb 100644 --- a/tools/sdk/include/expat/latin1tab.h +++ b/tools/sdk/include/expat/latin1tab.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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, diff --git a/tools/sdk/include/expat/minicheck.h b/tools/sdk/include/expat/minicheck.h deleted file mode 100644 index d54801d1b18..00000000000 --- a/tools/sdk/include/expat/minicheck.h +++ /dev/null @@ -1,95 +0,0 @@ -/* Miniature re-implementation of the "check" library. - * - * This is intended to support just enough of check to run the Expat - * tests. This interface is based entirely on the portion of the - * check library being used. - * - * This is *source* compatible, but not necessary *link* compatible. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#define CK_NOFORK 0 -#define CK_FORK 1 - -#define CK_SILENT 0 -#define CK_NORMAL 1 -#define CK_VERBOSE 2 - -/* Workaround for Microsoft's compiler and Tru64 Unix systems where the - C compiler has a working __func__, but the C++ compiler only has a - working __FUNCTION__. This could be fixed in configure.in, but it's - not worth it right now. */ -#if defined (_MSC_VER) || (defined(__osf__) && defined(__cplusplus)) -#define __func__ __FUNCTION__ -#endif - -/* ISO C90 does not support '__func__' predefined identifier */ -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ < 199901) -# define __func__ "(unknown)" -#endif - -#define START_TEST(testname) static void testname(void) { \ - _check_set_test_info(__func__, __FILE__, __LINE__); \ - { -#define END_TEST - -#define fail(msg) _fail_unless(0, __FILE__, __LINE__, msg) - -typedef void (*tcase_setup_function)(void); -typedef void (*tcase_teardown_function)(void); -typedef void (*tcase_test_function)(void); - -typedef struct SRunner SRunner; -typedef struct Suite Suite; -typedef struct TCase TCase; - -struct SRunner { - Suite *suite; - int nchecks; - int nfailures; -}; - -struct Suite { - const char *name; - TCase *tests; -}; - -struct TCase { - const char *name; - tcase_setup_function setup; - tcase_teardown_function teardown; - tcase_test_function *tests; - int ntests; - int allocated; - TCase *next_tcase; -}; - - -/* Internal helper. */ -void _check_set_test_info(char const *function, - char const *filename, int lineno); - - -/* - * Prototypes for the actual implementation. - */ - -void _fail_unless(int condition, const char *file, int line, const char *msg); -Suite *suite_create(const char *name); -TCase *tcase_create(const char *name); -void suite_add_tcase(Suite *suite, TCase *tc); -void tcase_add_checked_fixture(TCase *, - tcase_setup_function, - tcase_teardown_function); -void tcase_add_test(TCase *tc, tcase_test_function test); -SRunner *srunner_create(Suite *suite); -void srunner_run_all(SRunner *runner, int verbosity); -int srunner_ntests_failed(SRunner *runner); -void srunner_free(SRunner *runner); - -#ifdef __cplusplus -} -#endif diff --git a/tools/sdk/include/expat/nametab.h b/tools/sdk/include/expat/nametab.h index b05e62c77a6..bfa2bd38cd9 100644 --- a/tools/sdk/include/expat/nametab.h +++ b/tools/sdk/include/expat/nametab.h @@ -1,3 +1,35 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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, diff --git a/tools/sdk/include/expat/siphash.h b/tools/sdk/include/expat/siphash.h new file mode 100644 index 00000000000..581872df7b4 --- /dev/null +++ b/tools/sdk/include/expat/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/include/expat/utf8tab.h b/tools/sdk/include/expat/utf8tab.h index 7bb3e77603f..fa0bed6f5d7 100644 --- a/tools/sdk/include/expat/utf8tab.h +++ b/tools/sdk/include/expat/utf8tab.h @@ -1,7 +1,34 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. -*/ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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, diff --git a/tools/sdk/include/expat/winconfig.h b/tools/sdk/include/expat/winconfig.h new file mode 100644 index 00000000000..17fea468900 --- /dev/null +++ b/tools/sdk/include/expat/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/include/expat/xmlrole.h b/tools/sdk/include/expat/xmlrole.h index 4dd9f06f976..e5f048eab55 100644 --- a/tools/sdk/include/expat/xmlrole.h +++ b/tools/sdk/include/expat/xmlrole.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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 diff --git a/tools/sdk/include/expat/xmltok.h b/tools/sdk/include/expat/xmltok.h index 752007e8b9e..50926f38ab3 100644 --- a/tools/sdk/include/expat/xmltok.h +++ b/tools/sdk/include/expat/xmltok.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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 @@ -139,9 +167,6 @@ enum XML_Convert_Result { struct encoding { SCANNER scanners[XML_N_STATES]; SCANNER literalScanners[XML_N_LITERAL_TYPES]; - int (PTRCALL *sameName)(const ENCODING *, - const char *, - const char *); int (PTRCALL *nameMatchesAscii)(const ENCODING *, const char *, const char *, @@ -232,8 +257,6 @@ struct encoding { #define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \ XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr) -#define XmlSameName(enc, ptr1, ptr2) (((enc)->sameName)(enc, ptr1, ptr2)) - #define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \ (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2)) diff --git a/tools/sdk/include/expat/xmltok_impl.h b/tools/sdk/include/expat/xmltok_impl.h index da0ea60a657..a6420f48eed 100644 --- a/tools/sdk/include/expat/xmltok_impl.h +++ b/tools/sdk/include/expat/xmltok_impl.h @@ -1,6 +1,33 @@ /* -Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd -See the file COPYING for copying permission. + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| 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 { diff --git a/tools/sdk/include/fatfs/diskio.h b/tools/sdk/include/fatfs/diskio.h index 64d5d5b8df1..572f03dce03 100644 --- a/tools/sdk/include/fatfs/diskio.h +++ b/tools/sdk/include/fatfs/diskio.h @@ -1,133 +1,133 @@ -/*-----------------------------------------------------------------------/ -/ Low level disk interface modlue include file (C)ChaN, 2014 / -/-----------------------------------------------------------------------*/ - -#ifndef _DISKIO_DEFINED -#define _DISKIO_DEFINED - -#ifdef __cplusplus -extern "C" { -#endif - -#include "integer.h" -#include "sdmmc_cmd.h" -#include "driver/sdmmc_host.h" - -/* 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 */ - - -/* 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 - - -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); - -/** - * Structure of pointers to disk IO driver functions. - * - * See FatFs documentation for details about these functions - */ -typedef struct { - DSTATUS (*init) (BYTE pdrv); /*!< disk initialization function */ - DSTATUS (*status) (BYTE pdrv); /*!< disk status check function */ - DRESULT (*read) (BYTE pdrv, BYTE* buff, DWORD sector, UINT count); /*!< sector read function */ - DRESULT (*write) (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); /*!< sector write function */ - DRESULT (*ioctl) (BYTE pdrv, BYTE 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) - -/** - * 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(BYTE pdrv, sdmmc_card_t* card); - -/** - * 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); - -/* 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 _FS_READONLY == 0) */ -#define GET_SECTOR_COUNT 1 /* Get media size (needed at _USE_MKFS == 1) */ -#define GET_SECTOR_SIZE 2 /* Get sector size (needed at _MAX_SS != _MIN_SS) */ -#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at _USE_MKFS == 1) */ -#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at _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 +/*-----------------------------------------------------------------------/ +/ Low level disk interface modlue include file (C)ChaN, 2014 / +/-----------------------------------------------------------------------*/ + +#ifndef _DISKIO_DEFINED +#define _DISKIO_DEFINED + +#ifdef __cplusplus +extern "C" { +#endif + +#include "integer.h" +#include "sdmmc_cmd.h" +#include "driver/sdmmc_host.h" + +/* 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 */ + + +/* 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 + + +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); + +/** + * Structure of pointers to disk IO driver functions. + * + * See FatFs documentation for details about these functions + */ +typedef struct { + DSTATUS (*init) (BYTE pdrv); /*!< disk initialization function */ + DSTATUS (*status) (BYTE pdrv); /*!< disk status check function */ + DRESULT (*read) (BYTE pdrv, BYTE* buff, DWORD sector, UINT count); /*!< sector read function */ + DRESULT (*write) (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); /*!< sector write function */ + DRESULT (*ioctl) (BYTE pdrv, BYTE 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) + +/** + * 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(BYTE pdrv, sdmmc_card_t* card); + +/** + * 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); + +/* 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 _FS_READONLY == 0) */ +#define GET_SECTOR_COUNT 1 /* Get media size (needed at _USE_MKFS == 1) */ +#define GET_SECTOR_SIZE 2 /* Get sector size (needed at _MAX_SS != _MIN_SS) */ +#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at _USE_MKFS == 1) */ +#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at _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/include/fatfs/diskio_rawflash.h b/tools/sdk/include/fatfs/diskio_rawflash.h new file mode 100644 index 00000000000..a7b61a4708a --- /dev/null +++ b/tools/sdk/include/fatfs/diskio_rawflash.h @@ -0,0 +1,38 @@ +// 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 "integer.h" +#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(BYTE pdrv, const esp_partition_t* part_handle); +BYTE ff_diskio_get_pdrv_raw(const esp_partition_t* part_handle); + +#ifdef __cplusplus +} +#endif + +#endif // _DISKIO_RAWFLASH_DEFINED diff --git a/tools/sdk/include/fatfs/diskio_spiflash.h b/tools/sdk/include/fatfs/diskio_spiflash.h deleted file mode 100644 index d1de1d3dacb..00000000000 --- a/tools/sdk/include/fatfs/diskio_spiflash.h +++ /dev/null @@ -1,39 +0,0 @@ -// 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_SPIFLASH_DEFINED -#define _DISKIO_SPIFLASH_DEFINED - -#ifdef __cplusplus -extern "C" { -#endif - -#include "integer.h" -#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(BYTE pdrv, wl_handle_t flash_handle); -BYTE ff_diskio_get_pdrv_wl(wl_handle_t flash_handle); - -#ifdef __cplusplus -} -#endif - -#endif // _DISKIO_SPIFLASH_DEFINED diff --git a/tools/sdk/include/fatfs/diskio_wl.h b/tools/sdk/include/fatfs/diskio_wl.h new file mode 100644 index 00000000000..9abff7ae06d --- /dev/null +++ b/tools/sdk/include/fatfs/diskio_wl.h @@ -0,0 +1,40 @@ +// 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 "integer.h" +#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(BYTE pdrv, wl_handle_t flash_handle); +BYTE 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/include/fatfs/esp_vfs_fat.h b/tools/sdk/include/fatfs/esp_vfs_fat.h index bd86e681a04..a2a05951e18 100644 --- a/tools/sdk/include/fatfs/esp_vfs_fat.h +++ b/tools/sdk/include/fatfs/esp_vfs_fat.h @@ -205,6 +205,47 @@ esp_err_t esp_vfs_fat_spiflash_mount(const char* base_path, */ 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/include/fatfs/ff.h b/tools/sdk/include/fatfs/ff.h index d36815fceb1..55c1329827a 100644 --- a/tools/sdk/include/fatfs/ff.h +++ b/tools/sdk/include/fatfs/ff.h @@ -1,369 +1,369 @@ -/*----------------------------------------------------------------------------/ -/ FatFs - Generic FAT Filesystem module R0.13a / -/-----------------------------------------------------------------------------/ -/ -/ Copyright (C) 2017, 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 89352 /* Revision ID */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "integer.h" /* Basic integer types */ -#include "ffconf.h" /* FatFs configuration options */ - -#if FF_DEFINED != FFCONF_DEF -#error Wrong configuration file (ffconf.h). -#endif - -#ifdef FF_DEFINE_DIR -#define FF_DIR DIR -#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 - - - -/* 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 < 0 || FF_LFN_UNICODE > 2) -#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 -typedef QWORD FSIZE_t; -#else -typedef DWORD FSIZE_t; -#endif - - - -/* Filesystem object structure (FATFS) */ - -typedef struct { - BYTE fs_type; /* Filesystem type (0:N/A) */ - BYTE pdrv; /* Physical drive number */ - 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 */ - 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:flagmented 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 szf, 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 */ +/*----------------------------------------------------------------------------/ +/ FatFs - Generic FAT Filesystem module R0.13a / +/-----------------------------------------------------------------------------/ +/ +/ Copyright (C) 2017, 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 89352 /* Revision ID */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "integer.h" /* Basic integer types */ +#include "ffconf.h" /* FatFs configuration options */ + +#if FF_DEFINED != FFCONF_DEF +#error Wrong configuration file (ffconf.h). +#endif + +#ifdef FF_DEFINE_DIR +#define FF_DIR DIR +#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 + + + +/* 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 < 0 || FF_LFN_UNICODE > 2) +#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 +typedef QWORD FSIZE_t; +#else +typedef DWORD FSIZE_t; +#endif + + + +/* Filesystem object structure (FATFS) */ + +typedef struct { + BYTE fs_type; /* Filesystem type (0:N/A) */ + BYTE pdrv; /* Physical drive number */ + 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 */ + 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:flagmented 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 szf, 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/include/fatfs/ffconf.h b/tools/sdk/include/fatfs/ffconf.h index 7a491655d8b..1b1cf8c85ca 100644 --- a/tools/sdk/include/fatfs/ffconf.h +++ b/tools/sdk/include/fatfs/ffconf.h @@ -1,304 +1,304 @@ -#include -#include "sdkconfig.h" -/*---------------------------------------------------------------------------/ -/ FatFs - Configuration file -/---------------------------------------------------------------------------*/ - -#define FFCONF_DEF 89352 /* 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 0 -/* 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 0 -/* 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) -/ -/ 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 string support for volume ID. -/ When FF_STR_VOLUME_ID is set to 1, also pre-defined strings can be used as drive -/ number in the path name. FF_VOLUME_STRS defines the drive ID strings for each -/ logical drives. Number of items must be equal to FF_VOLUMES. Valid characters for -/ the drive ID strings are: A-Z and 0-9. */ - - -#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) -/ When enable exFAT, also LFN needs to be enabled. -/ 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 2017 -/* 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. All objects 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 "freertos/FreeRTOS.h" -#include "freertos/semphr.h" - -/*--- End of configuration options ---*/ +#include +#include "sdkconfig.h" +/*---------------------------------------------------------------------------/ +/ FatFs - Configuration file +/---------------------------------------------------------------------------*/ + +#define FFCONF_DEF 89352 /* 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 0 +/* 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 0 +/* 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) +/ +/ 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 string support for volume ID. +/ When FF_STR_VOLUME_ID is set to 1, also pre-defined strings can be used as drive +/ number in the path name. FF_VOLUME_STRS defines the drive ID strings for each +/ logical drives. Number of items must be equal to FF_VOLUMES. Valid characters for +/ the drive ID strings are: A-Z and 0-9. */ + + +#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) +/ When enable exFAT, also LFN needs to be enabled. +/ 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 2017 +/* 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. All objects 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 "freertos/FreeRTOS.h" +#include "freertos/semphr.h" + +/*--- End of configuration options ---*/ diff --git a/tools/sdk/include/fatfs/integer.h b/tools/sdk/include/fatfs/integer.h index 850dbf1483b..4fcf5c443ff 100644 --- a/tools/sdk/include/fatfs/integer.h +++ b/tools/sdk/include/fatfs/integer.h @@ -1,38 +1,38 @@ -/*-------------------------------------------*/ -/* Integer type definitions for FatFs module */ -/*-------------------------------------------*/ - -#ifndef FF_INTEGER -#define FF_INTEGER - -#ifdef _WIN32 /* FatFs development platform */ - -#include -#include -typedef unsigned __int64 QWORD; - - -#else /* Embedded platform */ - -/* These types MUST be 16-bit or 32-bit */ -typedef int INT; -typedef unsigned int UINT; - -/* This type MUST be 8-bit */ -typedef unsigned char BYTE; - -/* These types MUST be 16-bit */ -typedef short SHORT; -typedef unsigned short WORD; -typedef unsigned short WCHAR; - -/* These types MUST be 32-bit */ -typedef long LONG; -typedef unsigned long DWORD; - -/* This type MUST be 64-bit (Remove this for ANSI C (C89) compatibility) */ -typedef unsigned long long QWORD; - -#endif - -#endif +/*-------------------------------------------*/ +/* Integer type definitions for FatFs module */ +/*-------------------------------------------*/ + +#ifndef FF_INTEGER +#define FF_INTEGER + +#ifdef _WIN32 /* FatFs development platform */ + +#include +#include +typedef unsigned __int64 QWORD; + + +#else /* Embedded platform */ + +/* These types MUST be 16-bit or 32-bit */ +typedef int INT; +typedef unsigned int UINT; + +/* This type MUST be 8-bit */ +typedef unsigned char BYTE; + +/* These types MUST be 16-bit */ +typedef short SHORT; +typedef unsigned short WORD; +typedef unsigned short WCHAR; + +/* These types MUST be 32-bit */ +typedef long LONG; +typedef unsigned long DWORD; + +/* This type MUST be 64-bit (Remove this for ANSI C (C89) compatibility) */ +typedef unsigned long long QWORD; + +#endif + +#endif diff --git a/tools/sdk/include/fb_gfx/fb_gfx.h b/tools/sdk/include/fb_gfx/fb_gfx.h new file mode 100644 index 00000000000..079ff7bfe4a --- /dev/null +++ b/tools/sdk/include/fb_gfx/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/include/freemodbus/mb.h b/tools/sdk/include/freemodbus/mb.h new file mode 100644 index 00000000000..8d6be7b4226 --- /dev/null +++ b/tools/sdk/include/freemodbus/mb.h @@ -0,0 +1,417 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * 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: $Id: mb.h,v 1.17 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_H +#define _MB_H + +#include "port.h" + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +#include "mbport.h" +#include "mbproto.h" + +/*! \defgroup modbus Modbus + * \code #include "mb.h" \endcode + * + * This module defines the interface for the application. It contains + * the basic functions and types required to use the Modbus protocol stack. + * A typical application will want to call eMBInit() first. If the device + * is ready to answer network requests it must then call eMBEnable() to activate + * the protocol stack. In the main loop the function eMBPoll() must be called + * periodically. The time interval between pooling depends on the configured + * Modbus timeout. If an RTOS is available a separate task should be created + * and the task should always call the function eMBPoll(). + * + * \code + * // Initialize protocol stack in RTU mode for a slave with address 10 = 0x0A + * eMBInit( MB_RTU, 0x0A, 38400, MB_PAR_EVEN ); + * // Enable the Modbus Protocol Stack. + * eMBEnable( ); + * for( ;; ) + * { + * // Call the main polling loop of the Modbus protocol stack. + * eMBPoll( ); + * ... + * } + * \endcode + */ + +/* ----------------------- Defines ------------------------------------------*/ + +/*! \ingroup modbus + * \brief Use the default Modbus TCP port (502) + */ +#define MB_TCP_PORT_USE_DEFAULT 0 + +/* ----------------------- Type definitions ---------------------------------*/ + +/*! \ingroup modbus + * \brief Modbus serial transmission modes (RTU/ASCII). + * + * Modbus serial supports two transmission modes. Either ASCII or RTU. RTU + * is faster but has more hardware requirements and requires a network with + * a low jitter. ASCII is slower and more reliable on slower links (E.g. modems) + */ + typedef enum +{ + MB_RTU, /*!< RTU transmission mode. */ + MB_ASCII, /*!< ASCII transmission mode. */ + MB_TCP /*!< TCP mode. */ +} eMBMode; + +/*! \ingroup modbus + * \brief If register should be written or read. + * + * This value is passed to the callback functions which support either + * reading or writing register values. Writing means that the application + * registers should be updated and reading means that the modbus protocol + * stack needs to know the current register values. + * + * \see eMBRegHoldingCB( ), eMBRegCoilsCB( ), eMBRegDiscreteCB( ) and + * eMBRegInputCB( ). + */ +typedef enum +{ + MB_REG_READ, /*!< Read register values and pass to protocol stack. */ + MB_REG_WRITE /*!< Update register values. */ +} eMBRegisterMode; + +/*! \ingroup modbus + * \brief Errorcodes used by all function in the protocol stack. + */ +typedef enum +{ + MB_ENOERR, /*!< no error. */ + MB_ENOREG, /*!< illegal register address. */ + MB_EINVAL, /*!< illegal argument. */ + MB_EPORTERR, /*!< porting layer error. */ + MB_ENORES, /*!< insufficient resources. */ + MB_EIO, /*!< I/O error. */ + MB_EILLSTATE, /*!< protocol stack in illegal state. */ + MB_ETIMEDOUT /*!< timeout error occurred. */ +} eMBErrorCode; + + +/* ----------------------- Function prototypes ------------------------------*/ +/*! \ingroup modbus + * \brief Initialize the Modbus protocol stack. + * + * This functions initializes the ASCII or RTU module and calls the + * init functions of the porting layer to prepare the hardware. Please + * note that the receiver is still disabled and no Modbus frames are + * processed until eMBEnable( ) has been called. + * + * \param eMode If ASCII or RTU mode should be used. + * \param ucSlaveAddress The slave address. Only frames sent to this + * address or to the broadcast address are processed. + * \param ucPort The port to use. E.g. 1 for COM1 on windows. This value + * is platform dependent and some ports simply choose to ignore it. + * \param ulBaudRate The baudrate. E.g. 19200. Supported baudrates depend + * on the porting layer. + * \param eParity Parity used for serial transmission. + * + * \return If no error occurs the function returns eMBErrorCode::MB_ENOERR. + * The protocol is then in the disabled state and ready for activation + * by calling eMBEnable( ). Otherwise one of the following error codes + * is returned: + * - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid + * slave addresses are in the range 1 - 247. + * - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error. + */ +eMBErrorCode eMBInit( eMBMode eMode, UCHAR ucSlaveAddress, + UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ); + +/*! \ingroup modbus + * \brief Initialize the Modbus protocol stack for Modbus TCP. + * + * This function initializes the Modbus TCP Module. Please note that + * frame processing is still disabled until eMBEnable( ) is called. + * + * \param usTCPPort The TCP port to listen on. + * \return If the protocol stack has been initialized correctly the function + * returns eMBErrorCode::MB_ENOERR. Otherwise one of the following error + * codes is returned: + * - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid + * slave addresses are in the range 1 - 247. + * - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error. + */ +eMBErrorCode eMBTCPInit( USHORT usTCPPort ); + +/*! \ingroup modbus + * \brief Release resources used by the protocol stack. + * + * This function disables the Modbus protocol stack and release all + * hardware resources. It must only be called when the protocol stack + * is disabled. + * + * \note Note all ports implement this function. A port which wants to + * get an callback must define the macro MB_PORT_HAS_CLOSE to 1. + * + * \return If the resources where released it return eMBErrorCode::MB_ENOERR. + * If the protocol stack is not in the disabled state it returns + * eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBClose( void ); + +/*! \ingroup modbus + * \brief Enable the Modbus protocol stack. + * + * This function enables processing of Modbus frames. Enabling the protocol + * stack is only possible if it is in the disabled state. + * + * \return If the protocol stack is now in the state enabled it returns + * eMBErrorCode::MB_ENOERR. If it was not in the disabled state it + * return eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBEnable( void ); + +/*! \ingroup modbus + * \brief Disable the Modbus protocol stack. + * + * This function disables processing of Modbus frames. + * + * \return If the protocol stack has been disabled it returns + * eMBErrorCode::MB_ENOERR. If it was not in the enabled state it returns + * eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBDisable( void ); + +/*! \ingroup modbus + * \brief The main pooling loop of the Modbus protocol stack. + * + * This function must be called periodically. The timer interval required + * is given by the application dependent Modbus slave timeout. Internally the + * function calls xMBPortEventGet() and waits for an event from the receiver or + * transmitter state machines. + * + * \return If the protocol stack is not in the enabled state the function + * returns eMBErrorCode::MB_EILLSTATE. Otherwise it returns + * eMBErrorCode::MB_ENOERR. + */ +eMBErrorCode eMBPoll( void ); + +/*! \ingroup modbus + * \brief Configure the slave id of the device. + * + * This function should be called when the Modbus function Report Slave ID + * is enabled ( By defining MB_FUNC_OTHER_REP_SLAVEID_ENABLED in mbconfig.h ). + * + * \param ucSlaveID Values is returned in the Slave ID byte of the + * Report Slave ID response. + * \param xIsRunning If TRUE the Run Indicator Status byte is set to 0xFF. + * otherwise the Run Indicator Status is 0x00. + * \param pucAdditional Values which should be returned in the Additional + * bytes of the Report Slave ID response. + * \param usAdditionalLen Length of the buffer pucAdditonal. + * + * \return If the static buffer defined by MB_FUNC_OTHER_REP_SLAVEID_BUF in + * mbconfig.h is to small it returns eMBErrorCode::MB_ENORES. Otherwise + * it returns eMBErrorCode::MB_ENOERR. + */ +eMBErrorCode eMBSetSlaveID( UCHAR ucSlaveID, BOOL xIsRunning, + UCHAR const *pucAdditional, + USHORT usAdditionalLen ); + +/*! \ingroup modbus + * \brief Registers a callback handler for a given function code. + * + * This function registers a new callback handler for a given function code. + * The callback handler supplied is responsible for interpreting the Modbus PDU and + * the creation of an appropriate response. In case of an error it should return + * one of the possible Modbus exceptions which results in a Modbus exception frame + * sent by the protocol stack. + * + * \param ucFunctionCode The Modbus function code for which this handler should + * be registers. Valid function codes are in the range 1 to 127. + * \param pxHandler The function handler which should be called in case + * such a frame is received. If \c NULL a previously registered function handler + * for this function code is removed. + * + * \return eMBErrorCode::MB_ENOERR if the handler has been installed. If no + * more resources are available it returns eMBErrorCode::MB_ENORES. In this + * case the values in mbconfig.h should be adjusted. If the argument was not + * valid it returns eMBErrorCode::MB_EINVAL. + */ +eMBErrorCode eMBRegisterCB( UCHAR ucFunctionCode, + pxMBFunctionHandler pxHandler ); + +/* ----------------------- Callback -----------------------------------------*/ + +/*! \defgroup modbus_registers Modbus Registers + * \code #include "mb.h" \endcode + * The protocol stack does not internally allocate any memory for the + * registers. This makes the protocol stack very small and also usable on + * low end targets. In addition the values don't have to be in the memory + * and could for example be stored in a flash.
+ * Whenever the protocol stack requires a value it calls one of the callback + * function with the register address and the number of registers to read + * as an argument. The application should then read the actual register values + * (for example the ADC voltage) and should store the result in the supplied + * buffer.
+ * If the protocol stack wants to update a register value because a write + * register function was received a buffer with the new register values is + * passed to the callback function. The function should then use these values + * to update the application register values. + */ + +/*! \ingroup modbus_registers + * \brief Callback function used if the value of a Input Register + * is required by the protocol stack. The starting register address is given + * by \c usAddress and the last register is given by usAddress + + * usNRegs - 1. + * + * \param pucRegBuffer A buffer where the callback function should write + * the current value of the modbus registers to. + * \param usAddress The starting address of the register. Input registers + * are in the range 1 - 65535. + * \param usNRegs Number of registers the callback function must supply. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application can not supply values + * for registers within this range. In this case a + * ILLEGAL DATA ADDRESS exception frame is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Holding Register value is + * read or written by the protocol stack. The starting register address + * is given by \c usAddress and the last register is given by + * usAddress + usNRegs - 1. + * + * \param pucRegBuffer If the application registers values should be updated the + * buffer points to the new registers values. If the protocol stack needs + * to now the current values the callback function should write them into + * this buffer. + * \param usAddress The starting address of the register. + * \param usNRegs Number of registers to read or write. + * \param eMode If eMBRegisterMode::MB_REG_WRITE the application register + * values should be updated from the values in the buffer. For example + * this would be the case when the Modbus master has issued an + * WRITE SINGLE REGISTER command. + * If the value eMBRegisterMode::MB_REG_READ the application should copy + * the current values into the buffer \c pucRegBuffer. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application can not supply values + * for registers within this range. In this case a + * ILLEGAL DATA ADDRESS exception frame is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Coil Register value is + * read or written by the protocol stack. If you are going to use + * this function you might use the functions xMBUtilSetBits( ) and + * xMBUtilGetBits( ) for working with bitfields. + * + * \param pucRegBuffer The bits are packed in bytes where the first coil + * starting at address \c usAddress is stored in the LSB of the + * first byte in the buffer pucRegBuffer. + * If the buffer should be written by the callback function unused + * coil values (I.e. if not a multiple of eight coils is used) should be set + * to zero. + * \param usAddress The first coil number. + * \param usNCoils Number of coil values requested. + * \param eMode If eMBRegisterMode::MB_REG_WRITE the application values should + * be updated from the values supplied in the buffer \c pucRegBuffer. + * If eMBRegisterMode::MB_REG_READ the application should store the current + * values in the buffer \c pucRegBuffer. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application does not map an coils + * within the requested address range. In this case a + * ILLEGAL DATA ADDRESS is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Input Discrete Register value is + * read by the protocol stack. + * + * If you are going to use his function you might use the functions + * xMBUtilSetBits( ) and xMBUtilGetBits( ) for working with bitfields. + * + * \param pucRegBuffer The buffer should be updated with the current + * coil values. The first discrete input starting at \c usAddress must be + * stored at the LSB of the first byte in the buffer. If the requested number + * is not a multiple of eight the remaining bits should be set to zero. + * \param usAddress The starting address of the first discrete input. + * \param usNDiscrete Number of discrete input values. + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If no such discrete inputs exists. + * In this case a ILLEGAL DATA ADDRESS exception frame is sent + * as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/tools/sdk/include/freemodbus/mbconfig.h b/tools/sdk/include/freemodbus/mbconfig.h new file mode 100644 index 00000000000..54194de26d9 --- /dev/null +++ b/tools/sdk/include/freemodbus/mbconfig.h @@ -0,0 +1,132 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * 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: $Id: mbconfig.h,v 1.15 2010/06/06 13:54:40 wolti Exp $ + */ + +#ifndef _MB_CONFIG_H +#define _MB_CONFIG_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/* ----------------------- Defines ------------------------------------------*/ +/*! \defgroup modbus_cfg Modbus Configuration + * + * Most modules in the protocol stack are completly optional and can be + * excluded. This is specially important if target resources are very small + * and program memory space should be saved.
+ * + * All of these settings are available in the file mbconfig.h + */ +/*! \addtogroup modbus_cfg + * @{ + */ +/*! \brief If Modbus ASCII support is enabled. */ +#define MB_ASCII_ENABLED ( 0 ) + +/*! \brief If Modbus RTU support is enabled. */ +#define MB_RTU_ENABLED ( 1 ) + +/*! \brief If Modbus TCP support is enabled. */ +#define MB_TCP_ENABLED ( 0 ) + +/*! \brief The character timeout value for Modbus ASCII. + * + * The character timeout value is not fixed for Modbus ASCII and is therefore + * a configuration option. It should be set to the maximum expected delay + * time of the network. + */ +#define MB_ASCII_TIMEOUT_SEC ( 1 ) + +/*! \brief Timeout to wait in ASCII prior to enabling transmitter. + * + * If defined the function calls vMBPortSerialDelay with the argument + * MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS to allow for a delay before + * the serial transmitter is enabled. This is required because some + * targets are so fast that there is no time between receiving and + * transmitting the frame. If the master is to slow with enabling its + * receiver then he will not receive the response correctly. + */ +#ifndef MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS +#define MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS ( 0 ) +#endif + +/*! \brief Maximum number of Modbus functions codes the protocol stack + * should support. + * + * The maximum number of supported Modbus functions must be greater than + * the sum of all enabled functions in this file and custom function + * handlers. If set to small adding more functions will fail. + */ +#define MB_FUNC_HANDLERS_MAX ( 16 ) + +/*! \brief Number of bytes which should be allocated for the Report Slave ID + * command. + * + * This number limits the maximum size of the additional segment in the + * report slave id function. See eMBSetSlaveID( ) for more information on + * how to set this value. It is only used if MB_FUNC_OTHER_REP_SLAVEID_ENABLED + * is set to 1. + */ +#define MB_FUNC_OTHER_REP_SLAVEID_BUF ( 32 ) + +/*! \brief If the Report Slave ID function should be enabled. */ +#define MB_FUNC_OTHER_REP_SLAVEID_ENABLED ( CONFIG_MB_CONTROLLER_SLAVE_ID_SUPPORT ) + +/*! \brief If the Read Input Registers function should be enabled. */ +#define MB_FUNC_READ_INPUT_ENABLED ( 1 ) + +/*! \brief If the Read Holding Registers function should be enabled. */ +#define MB_FUNC_READ_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Write Single Register function should be enabled. */ +#define MB_FUNC_WRITE_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Write Multiple registers function should be enabled. */ +#define MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Read Coils function should be enabled. */ +#define MB_FUNC_READ_COILS_ENABLED ( 1 ) + +/*! \brief If the Write Coils function should be enabled. */ +#define MB_FUNC_WRITE_COIL_ENABLED ( 1 ) + +/*! \brief If the Write Multiple Coils function should be enabled. */ +#define MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED ( 1 ) + +/*! \brief If the Read Discrete Inputs function should be enabled. */ +#define MB_FUNC_READ_DISCRETE_INPUTS_ENABLED ( 1 ) + +/*! \brief If the Read/Write Multiple Registers function should be enabled. */ +#define MB_FUNC_READWRITE_HOLDING_ENABLED ( 1 ) + +/*! @} */ +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/tools/sdk/include/freemodbus/mbcontroller.h b/tools/sdk/include/freemodbus/mbcontroller.h new file mode 100644 index 00000000000..b6b206e2a68 --- /dev/null +++ b/tools/sdk/include/freemodbus/mbcontroller.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. + +// mbcontroller.h +// Implementation of the MbController + +#ifndef _MODBUS_CONTROLLER +#define _MODBUS_CONTROLLER + +#include // for standard int types definition +#include // for NULL and std defines +#include "soc/soc.h" // for BITN definitions +#include "sdkconfig.h" // for KConfig options +#include "driver/uart.h" // for uart port number defines + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_INST_MIN_SIZE (2) // The minimal size of Modbus registers area in bytes +#define MB_INST_MAX_SIZE (2048) // The maximum size of Modbus area in bytes + +#define MB_CONTROLLER_STACK_SIZE (CONFIG_MB_CONTROLLER_STACK_SIZE) // Stack size for Modbus controller +#define MB_CONTROLLER_PRIORITY (CONFIG_MB_SERIAL_TASK_PRIO - 1) // priority of MB controller task +#define MB_CONTROLLER_NOTIFY_QUEUE_SIZE (CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE) // Number of messages in parameter notification queue +#define MB_CONTROLLER_NOTIFY_TIMEOUT (pdMS_TO_TICKS(CONFIG_MB_CONTROLLER_NOTIFY_TIMEOUT)) // notification timeout + +// 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_2) // Default UART port number +#define MB_PAR_INFO_TOUT (10) // Timeout for get parameter info +#define MB_PARITY_NONE (UART_PARITY_DISABLE) + +/** + * @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, /*!< 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 mode. */ +} mb_mode_type_t; + +/** + * @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 Device communication parameters + */ +typedef struct { + mb_mode_type_t mode; /*!< Modbus communication mode */ + uint8_t slave_addr; /*!< Modbus Slave Address */ + uart_port_t port; /*!< Modbus communication port (UART) number */ + uint32_t baudrate; /*!< Modbus baudrate */ + uart_parity_t parity; /*!< Modbus UART parity settings */ +} mb_communication_info_t; + +/** + * @brief Initialize modbus controller and stack + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t mbcontroller_init(void); + +/** + * @brief Destroy Modbus controller and stack + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t mbcontroller_destroy(void); + +/** + * @brief Start Modbus communication stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Modbus stack start error + */ +esp_err_t mbcontroller_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 mbcontroller_setup(mb_communication_info_t 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 mbcontroller_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 mbcontroller_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 mbcontroller_set_descriptor(mb_register_area_descriptor_t descr_data); + +#endif + diff --git a/tools/sdk/include/freemodbus/mbframe.h b/tools/sdk/include/freemodbus/mbframe.h new file mode 100644 index 00000000000..99d59c613e3 --- /dev/null +++ b/tools/sdk/include/freemodbus/mbframe.h @@ -0,0 +1,87 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * 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: $Id: mbframe.h,v 1.9 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_FRAME_H +#define _MB_FRAME_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/*! + * Constants which defines the format of a modbus frame. The example is + * shown for a Modbus RTU/ASCII frame. Note that the Modbus PDU is not + * dependent on the underlying transport. + * + * + * <------------------------ MODBUS SERIAL LINE PDU (1) -------------------> + * <----------- MODBUS PDU (1') ----------------> + * +-----------+---------------+----------------------------+-------------+ + * | Address | Function Code | Data | CRC/LRC | + * +-----------+---------------+----------------------------+-------------+ + * | | | | + * (2) (3/2') (3') (4) + * + * (1) ... MB_SER_PDU_SIZE_MAX = 256 + * (2) ... MB_SER_PDU_ADDR_OFF = 0 + * (3) ... MB_SER_PDU_PDU_OFF = 1 + * (4) ... MB_SER_PDU_SIZE_CRC = 2 + * + * (1') ... MB_PDU_SIZE_MAX = 253 + * (2') ... MB_PDU_FUNC_OFF = 0 + * (3') ... MB_PDU_DATA_OFF = 1 + * + */ + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_SIZE_MAX 253 /*!< Maximum size of a PDU. */ +#define MB_PDU_SIZE_MIN 1 /*!< Function Code */ +#define MB_PDU_FUNC_OFF 0 /*!< Offset of function code in PDU. */ +#define MB_PDU_DATA_OFF 1 /*!< Offset for response data in PDU. */ + +/* ----------------------- Prototypes 0-------------------------------------*/ +typedef void ( *pvMBFrameStart ) ( void ); + +typedef void ( *pvMBFrameStop ) ( void ); + +typedef eMBErrorCode( *peMBFrameReceive ) ( UCHAR * pucRcvAddress, + UCHAR ** pucFrame, + USHORT * pusLength ); + +typedef eMBErrorCode( *peMBFrameSend ) ( UCHAR slaveAddress, + const UCHAR * pucFrame, + USHORT usLength ); + +typedef void( *pvMBFrameClose ) ( void ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/tools/sdk/include/freemodbus/mbfunc.h b/tools/sdk/include/freemodbus/mbfunc.h new file mode 100644 index 00000000000..aea14f75914 --- /dev/null +++ b/tools/sdk/include/freemodbus/mbfunc.h @@ -0,0 +1,80 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * 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: $Id: mbfunc.h,v 1.12 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_FUNC_H +#define _MB_FUNC_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +#if MB_FUNC_OTHER_REP_SLAVEID_BUF > 0 + eMBException eMBFuncReportSlaveID( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_INPUT_ENABLED > 0 +eMBException eMBFuncReadInputRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_HOLDING_ENABLED > 0 +eMBException eMBFuncReadHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_HOLDING_ENABLED > 0 +eMBException eMBFuncWriteHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 +eMBException eMBFuncWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_COILS_ENABLED > 0 +eMBException eMBFuncReadCoils( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_COIL_ENABLED > 0 +eMBException eMBFuncWriteCoil( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 +eMBException eMBFuncWriteMultipleCoils( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_DISCRETE_INPUTS_ENABLED > 0 +eMBException eMBFuncReadDiscreteInputs( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 +eMBException eMBFuncReadWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/tools/sdk/include/freemodbus/mbport.h b/tools/sdk/include/freemodbus/mbport.h new file mode 100644 index 00000000000..8d334d0e0b5 --- /dev/null +++ b/tools/sdk/include/freemodbus/mbport.h @@ -0,0 +1,130 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * 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: $Id: mbport.h,v 1.19 2010/06/06 13:54:40 wolti Exp $ + */ + +#ifndef _MB_PORT_H +#define _MB_PORT_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Type definitions ---------------------------------*/ + +typedef enum +{ + EV_READY, /*!< Startup finished. */ + EV_FRAME_RECEIVED, /*!< Frame received. */ + EV_EXECUTE, /*!< Execute function. */ + EV_FRAME_SENT /*!< Frame sent. */ +} eMBEventType; + +/*! \ingroup modbus + * \brief Parity used for characters in serial mode. + * + * The parity which should be applied to the characters sent over the serial + * link. Please note that this values are actually passed to the porting + * layer and therefore not all parity modes might be available. + */ +typedef enum +{ + MB_PAR_NONE, /*!< No parity. */ + MB_PAR_ODD, /*!< Odd parity. */ + MB_PAR_EVEN /*!< Even parity. */ +} eMBParity; + +/* ----------------------- Supporting functions -----------------------------*/ +BOOL xMBPortEventInit( void ); + +BOOL xMBPortEventPost( eMBEventType eEvent ); + +BOOL xMBPortEventGet( /*@out@ */ eMBEventType * eEvent ); + +/* ----------------------- Serial port functions ----------------------------*/ + +BOOL xMBPortSerialInit( UCHAR ucPort, ULONG ulBaudRate, + UCHAR ucDataBits, eMBParity eParity ); + +void vMBPortClose( void ); + +void xMBPortSerialClose( void ); + +void vMBPortSerialEnable( BOOL xRxEnable, BOOL xTxEnable ); + +BOOL xMBPortSerialGetByte( CHAR * pucByte ); + +BOOL xMBPortSerialPutByte( CHAR ucByte ); + +/* ----------------------- Timers functions ---------------------------------*/ +BOOL xMBPortTimersInit( USHORT usTimeOut50us ); + +void xMBPortTimersClose( void ); + +void vMBPortTimersEnable( void ); + +void vMBPortTimersDisable( void ); + +void vMBPortTimersDelay( USHORT usTimeOutMS ); + +/* ----------------------- Callback for the protocol stack ------------------*/ +/*! + * \brief Callback function for the porting layer when a new byte is + * available. + * + * Depending upon the mode this callback function is used by the RTU or + * ASCII transmission layers. In any case a call to xMBPortSerialGetByte() + * must immediately return a new character. + * + * \return TRUE if a event was posted to the queue because + * a new byte was received. The port implementation should wake up the + * tasks which are currently blocked on the eventqueue. + */ +extern BOOL( *pxMBFrameCBByteReceived ) ( void ); + +extern BOOL( *pxMBFrameCBTransmitterEmpty ) ( void ); + +extern BOOL( *pxMBPortCBTimerExpired ) ( void ); + +/* ----------------------- TCP port functions -------------------------------*/ +#if MB_TCP_ENABLED == 1 +BOOL xMBTCPPortInit( USHORT usTCPPort ); + +void vMBTCPPortClose( void ); + +void vMBTCPPortDisable( void ); + +BOOL xMBTCPPortGetRequest( UCHAR **ppucMBTCPFrame, USHORT * usTCPLength ); + +BOOL xMBTCPPortSendResponse( const UCHAR *pucMBTCPFrame, USHORT usTCPLength ); +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/tools/sdk/include/freemodbus/mbproto.h b/tools/sdk/include/freemodbus/mbproto.h new file mode 100644 index 00000000000..786aaf4030d --- /dev/null +++ b/tools/sdk/include/freemodbus/mbproto.h @@ -0,0 +1,83 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * 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: $Id: mbproto.h,v 1.14 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_PROTO_H +#define _MB_PROTO_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/* ----------------------- Defines ------------------------------------------*/ +#define MB_ADDRESS_BROADCAST ( 0 ) /*! Modbus broadcast address. */ +#define MB_ADDRESS_MIN ( 1 ) /*! Smallest possible slave address. */ +#define MB_ADDRESS_MAX ( 247 ) /*! Biggest possible slave address. */ +#define MB_FUNC_NONE ( 0 ) +#define MB_FUNC_READ_COILS ( 1 ) +#define MB_FUNC_READ_DISCRETE_INPUTS ( 2 ) +#define MB_FUNC_WRITE_SINGLE_COIL ( 5 ) +#define MB_FUNC_WRITE_MULTIPLE_COILS ( 15 ) +#define MB_FUNC_READ_HOLDING_REGISTER ( 3 ) +#define MB_FUNC_READ_INPUT_REGISTER ( 4 ) +#define MB_FUNC_WRITE_REGISTER ( 6 ) +#define MB_FUNC_WRITE_MULTIPLE_REGISTERS ( 16 ) +#define MB_FUNC_READWRITE_MULTIPLE_REGISTERS ( 23 ) +#define MB_FUNC_DIAG_READ_EXCEPTION ( 7 ) +#define MB_FUNC_DIAG_DIAGNOSTIC ( 8 ) +#define MB_FUNC_DIAG_GET_COM_EVENT_CNT ( 11 ) +#define MB_FUNC_DIAG_GET_COM_EVENT_LOG ( 12 ) +#define MB_FUNC_OTHER_REPORT_SLAVEID ( 17 ) +#define MB_FUNC_ERROR ( 128 ) +/* ----------------------- Type definitions ---------------------------------*/ + typedef enum +{ + MB_EX_NONE = 0x00, + MB_EX_ILLEGAL_FUNCTION = 0x01, + MB_EX_ILLEGAL_DATA_ADDRESS = 0x02, + MB_EX_ILLEGAL_DATA_VALUE = 0x03, + MB_EX_SLAVE_DEVICE_FAILURE = 0x04, + MB_EX_ACKNOWLEDGE = 0x05, + MB_EX_SLAVE_BUSY = 0x06, + MB_EX_MEMORY_PARITY_ERROR = 0x08, + MB_EX_GATEWAY_PATH_FAILED = 0x0A, + MB_EX_GATEWAY_TGT_FAILED = 0x0B +} eMBException; + +typedef eMBException( *pxMBFunctionHandler ) ( UCHAR * pucFrame, USHORT * pusLength ); + +typedef struct +{ + UCHAR ucFunctionCode; + pxMBFunctionHandler pxHandler; +} xMBFunctionHandler; + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/tools/sdk/include/freemodbus/mbutils.h b/tools/sdk/include/freemodbus/mbutils.h new file mode 100644 index 00000000000..61495751d46 --- /dev/null +++ b/tools/sdk/include/freemodbus/mbutils.h @@ -0,0 +1,108 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * 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: $Id: mbutils.h,v 1.5 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_UTILS_H +#define _MB_UTILS_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/*! \defgroup modbus_utils Utilities + * + * This module contains some utility functions which can be used by + * the application. It includes some special functions for working with + * bitfields backed by a character array buffer. + * + */ +/*! \addtogroup modbus_utils + * @{ + */ +/*! \brief Function to set bits in a byte buffer. + * + * This function allows the efficient use of an array to implement bitfields. + * The array used for storing the bits must always be a multiple of two + * bytes. Up to eight bits can be set or cleared in one operation. + * + * \param ucByteBuf A buffer where the bit values are stored. Must be a + * multiple of 2 bytes. No length checking is performed and if + * usBitOffset / 8 is greater than the size of the buffer memory contents + * is overwritten. + * \param usBitOffset The starting address of the bits to set. The first + * bit has the offset 0. + * \param ucNBits Number of bits to modify. The value must always be smaller + * than 8. + * \param ucValues Thew new values for the bits. The value for the first bit + * starting at usBitOffset is the LSB of the value + * ucValues + * + * \code + * ucBits[2] = {0, 0}; + * + * // Set bit 4 to 1 (read: set 1 bit starting at bit offset 4 to value 1) + * xMBUtilSetBits( ucBits, 4, 1, 1 ); + * + * // Set bit 7 to 1 and bit 8 to 0. + * xMBUtilSetBits( ucBits, 7, 2, 0x01 ); + * + * // Set bits 8 - 11 to 0x05 and bits 12 - 15 to 0x0A; + * xMBUtilSetBits( ucBits, 8, 8, 0x5A); + * \endcode + */ +void xMBUtilSetBits( UCHAR * ucByteBuf, USHORT usBitOffset, + UCHAR ucNBits, UCHAR ucValues ); + +/*! \brief Function to read bits in a byte buffer. + * + * This function is used to extract up bit values from an array. Up to eight + * bit values can be extracted in one step. + * + * \param ucByteBuf A buffer where the bit values are stored. + * \param usBitOffset The starting address of the bits to set. The first + * bit has the offset 0. + * \param ucNBits Number of bits to modify. The value must always be smaller + * than 8. + * + * \code + * UCHAR ucBits[2] = {0, 0}; + * UCHAR ucResult; + * + * // Extract the bits 3 - 10. + * ucResult = xMBUtilGetBits( ucBits, 3, 8 ); + * \endcode + */ +UCHAR xMBUtilGetBits( UCHAR * ucByteBuf, USHORT usBitOffset, + UCHAR ucNBits ); + +/*! @} */ + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/tools/sdk/include/freertos/freertos/FreeRTOS.h b/tools/sdk/include/freertos/freertos/FreeRTOS.h index 1bc931757c8..486d9c329aa 100644 --- a/tools/sdk/include/freertos/freertos/FreeRTOS.h +++ b/tools/sdk/include/freertos/freertos/FreeRTOS.h @@ -740,6 +740,10 @@ extern "C" { #define configUSE_STATS_FORMATTING_FUNCTIONS 0 #endif +#ifndef configTASKLIST_INCLUDE_COREID + #define configTASKLIST_INCLUDE_COREID 0 +#endif + #ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() #endif diff --git a/tools/sdk/include/freertos/freertos/FreeRTOSConfig.h b/tools/sdk/include/freertos/freertos/FreeRTOSConfig.h index 37912a66ce1..aa33917e2c0 100644 --- a/tools/sdk/include/freertos/freertos/FreeRTOSConfig.h +++ b/tools/sdk/include/freertos/freertos/FreeRTOSConfig.h @@ -159,9 +159,8 @@ int xt_clock_freq(void) __attribute__((deprecated)); *----------------------------------------------------------*/ #define configUSE_PREEMPTION 1 -#define configUSE_IDLE_HOOK ( CONFIG_FREERTOS_LEGACY_IDLE_HOOK ) - -#define configUSE_TICK_HOOK ( CONFIG_FREERTOS_LEGACY_TICK_HOOK ) +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 1 #define configTICK_RATE_HZ ( CONFIG_FREERTOS_HZ ) @@ -211,6 +210,10 @@ int xt_clock_freq(void) __attribute__((deprecated)); #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 @@ -289,6 +292,10 @@ extern void vPortCleanUpTCB ( void *pxTCB ); #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 #define configXT_BOARD 1 /* Board mode */ #define configXT_SIMULATOR 0 diff --git a/tools/sdk/include/freertos/freertos/portable.h b/tools/sdk/include/freertos/freertos/portable.h index 9fe74b60c0a..ce189f31cde 100644 --- a/tools/sdk/include/freertos/freertos/portable.h +++ b/tools/sdk/include/freertos/freertos/portable.h @@ -205,7 +205,7 @@ BaseType_t xPortInterruptedFromISRContext(); /* Multi-core: get current core ID */ static inline uint32_t IRAM_ATTR xPortGetCoreID() { int id; - asm ( + __asm__ __volatile__ ( "rsr.prid %0\n" " extui %0,%0,13,1" :"=r"(id)); diff --git a/tools/sdk/include/freertos/freertos/portmacro.h b/tools/sdk/include/freertos/freertos/portmacro.h index 93d2071ba54..adeb3bb0097 100644 --- a/tools/sdk/include/freertos/freertos/portmacro.h +++ b/tools/sdk/include/freertos/freertos/portmacro.h @@ -74,7 +74,6 @@ extern "C" { #include -#include #include #include #include /* required for XSHAL_CLIB */ @@ -259,8 +258,11 @@ static inline unsigned portENTER_CRITICAL_NESTED() { //Because the ROM routines don't necessarily handle a stack in external RAM correctly, we force //the stack memory to always be internal. -#define pvPortMallocTcbMem(size) heap_caps_malloc(size, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) -#define pvPortMallocStackMem(size) heap_caps_malloc(size, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) +#define portTcbMemoryCaps (MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) +#define portStackMemoryCaps (MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) + +#define pvPortMallocTcbMem(size) heap_caps_malloc(size, portTcbMemoryCaps) +#define pvPortMallocStackMem(size) heap_caps_malloc(size, portStackMemoryCaps) //xTaskCreateStatic uses these functions to check incoming memory. #define portVALID_TCB_MEM(ptr) (esp_ptr_internal(ptr) && esp_ptr_byte_accessible(ptr)) @@ -365,9 +367,18 @@ typedef struct { #define PRIVILEGED_DATA #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 */ void _xt_coproc_release(volatile void * coproc_sa_base); +void vApplicationSleep( TickType_t xExpectedIdleTime ); +#define portSUPPRESS_TICKS_AND_SLEEP( idleTime ) vApplicationSleep( idleTime ) // porttrace #if configUSE_TRACE_FACILITY_2 diff --git a/tools/sdk/include/freertos/freertos/ringbuf.h b/tools/sdk/include/freertos/freertos/ringbuf.h deleted file mode 100644 index 0f23a44e6b6..00000000000 --- a/tools/sdk/include/freertos/freertos/ringbuf.h +++ /dev/null @@ -1,341 +0,0 @@ -#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 - -//An opaque handle for a ringbuff object. -typedef void * RingbufHandle_t; - -/** - * @brief The various types of buffer - * - * A ringbuffer instantiated by these functions essentially acts like a - * FreeRTOS queue, with the difference that it's strictly FIFO and with - * the main advantage that you can put in randomly-sized items. The capacity, - * accordingly, isn't measured in the amount of items, but the amount of - * memory that is used for storing the items. Dependent on the size of - * the items, more or less of them will fit in the ring buffer. - * - * This ringbuffer tries to be efficient with memory: when inserting an item, - * the item data will be copied to the ringbuffer memory. When retrieving - * an item, however, a reference to ringbuffer memory will be returned. - * The returned memory is guaranteed to be 32-bit aligned and contiguous. - * The application can use this memory, but as long as it does, ringbuffer - * writes that would write to this bit of memory will block. - * - * The requirement for items to be contiguous is slightly problematic when - * the only way to place the next item would involve a wraparound from the end - * to the beginning of the ringbuffer. This can be solved (or not) in a few ways, - * see descriptions of possible ringbuf_type_t types below. - * - * The maximum size of an item will be affected by ringbuffer type. - * When split items are allowed, it is acceptable to push items of - * (buffer_size)-16 bytes into the buffer. - * When it's not allowed, the maximum size is (buffer_size/2)-8 bytes. - * The bytebuf can fill the entire buffer with data, it has no overhead. - */ -typedef enum { - /** The insertion code will leave the room at the end of the ringbuffer - * unused and instead will put the entire item at the start of the ringbuffer, - * as soon as there is enough free space. - */ - RINGBUF_TYPE_NOSPLIT = 0, - /** The insertion code will split the item in two items; one which fits - * in the space left at the end of the ringbuffer, one that contains - * the remaining data which is placed in the beginning. - * Two xRingbufferReceive calls will be needed to retrieve the data. - */ - RINGBUF_TYPE_ALLOWSPLIT, - /** This is your conventional byte-based ringbuffer. It does have no - * overhead, but it has no item contiguousness either: a read will just - * give you the entire written buffer space, or the space up to the end - * of the buffer, and writes can be broken up in any way possible. - * Note that this type cannot do a 2nd read before returning the memory - * of the 1st. - */ - RINGBUF_TYPE_BYTEBUF -} ringbuf_type_t; - - -/** - * @brief Create a ring buffer - * - * @param buf_length Length of circular buffer, in bytes. Each entry will - * take up its own length, plus a header that at the moment - * is equal to sizeof(size_t). - * @param type Type of ring buffer, see ringbuf_type_t. - * - * @return A RingbufHandle_t handle to the created ringbuffer, or NULL in case of error. - */ -RingbufHandle_t xRingbufferCreate(size_t buf_length, ringbuf_type_t type); - -/** - * @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 item_size Size of each item to be put into the ring buffer - * @param num_item Maximum number of items the buffer needs to hold simultaneously - * - * @return A RingbufHandle_t handle to the created ringbuffer, or NULL in case of error. - */ -RingbufHandle_t xRingbufferCreateNoSplit(size_t item_size, size_t num_item); - -/** - * @brief Delete a ring buffer - * - * @param ringbuf Ring buffer to delete - */ -void vRingbufferDelete(RingbufHandle_t ringbuf); - - -/** - * @brief Get maximum size of an item that can be placed in the ring buffer - * - * @param ringbuf Ring buffer to query - * - * @return Maximum size, in bytes, of an item that can be placed in a ring buffer. - */ -size_t xRingbufferGetMaxItemSize(RingbufHandle_t ringbuf); - -/** - * @brief Get current free size available in the buffer - * - * This gives the real time free space available in the ring buffer. So basically, - * this will be the maximum size of the entry that can be sent into the buffer. - * - * @note 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 - * - * @param ringbuf - Ring buffer to query - * - * @return Current free size, in bytes, available for an entry - */ -size_t xRingbufferGetCurFreeSize(RingbufHandle_t ringbuf); - -/** - * @brief Check if the next item is wrapped - * - * This API tells if the next item that is available for a Receive is wrapped - * or not. This is valid only if the ring buffer type is RINGBUF_TYPE_ALLOWSPLIT - * - * @note 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 Receive - * - * @param ringbuf - Ring buffer to query - * - * @return true if the next item is wrapped around - * @return false if the next item is not wrapped - */ -bool xRingbufferIsNextItemWrapped(RingbufHandle_t ringbuf); - -/** - * @brief Insert an item into the ring buffer - * - * @param ringbuf Ring buffer to insert the item into - * @param data Pointer to data to insert. NULL is allowed if data_size is 0. - * @param data_size Size of data to insert. A value of 0 is allowed. - * @param ticks_to_wait Ticks to wait for room in the ringbuffer. - * - * @return - * - pdTRUE if succeeded - * - pdFALSE on time-out or when the buffer is larger than indicated - * by xRingbufferGetMaxItemSize(ringbuf). - */ -BaseType_t xRingbufferSend(RingbufHandle_t ringbuf, void *data, size_t data_size, TickType_t ticks_to_wait); - - -/** - * @brief Insert an item into the ring buffer from an ISR - * - * @param ringbuf Ring buffer to insert the item into - * @param data Pointer to data to insert. NULL is allowed if data_size is 0. - * @param data_size Size of data to insert. A value of 0 is allowed. - * @param[out] higher_prio_task_awoken Value pointed to will be set to pdTRUE - * if the push woke up a higher priority task. - * - * @return pdTRUE if succeeded, pdFALSE when the ring buffer does not have space. - */ -BaseType_t xRingbufferSendFromISR(RingbufHandle_t ringbuf, void *data, size_t data_size, BaseType_t *higher_prio_task_awoken); - -/** - * @brief Retrieve an item from the ring buffer - * - * @note A call to vRingbufferReturnItem() is required after this to free up - * the data received. - * - * @param ringbuf Ring buffer to retrieve the item from - * @param[out] item_size Pointer to a variable to which the size of the - * retrieved item will be written. - * @param ticks_to_wait Ticks to wait for items in the ringbuffer. - * - * @return - * - pointer to the retrieved item on success; *item_size filled with - * the length of the item. - * - NULL on timeout, *item_size is untouched in that case. - */ -void *xRingbufferReceive(RingbufHandle_t ringbuf, size_t *item_size, TickType_t ticks_to_wait); - - -/** - * @brief Retrieve an item from the ring buffer from an ISR - * - * @note A call to vRingbufferReturnItemFromISR() is required after this to - * free up the data received - * - * @param ringbuf Ring buffer to retrieve the item from - * @param[out] item_size Pointer to a variable to which the size of the - * retrieved item will be written. - * - * @return - * - Pointer to the retrieved item on success; *item_size filled with - * the length of the item. - * - NULL when the ringbuffer is empty, *item_size is untouched in that case. - */ -void *xRingbufferReceiveFromISR(RingbufHandle_t ringbuf, size_t *item_size); - - -/** - * @brief Retrieve bytes from a ByteBuf type of ring buffer, - * specifying the maximum amount of bytes to return - * - * @note A call to vRingbufferReturnItem() is required after this to free up - * the data received. - * - * @param ringbuf Ring buffer to retrieve the item from - * @param[out] item_size Pointer to a variable to which the size - * of the retrieved item will be written. - * @param ticks_to_wait Ticks to wait for items in the ringbuffer. - * @param wanted_size Maximum number of bytes to return. - * - * @return - * - Pointer to the retrieved item on success; *item_size filled with - * the length of the item. - * - NULL on timeout, *item_size is untouched in that case. - */ -void *xRingbufferReceiveUpTo(RingbufHandle_t ringbuf, size_t *item_size, TickType_t ticks_to_wait, size_t wanted_size); - - -/** - * @brief Retrieve bytes from a ByteBuf type of ring buffer, - * specifying the maximum amount of bytes to return. Call this from an ISR. - * - * @note A call to vRingbufferReturnItemFromISR() is required after this - * to free up the data received. - * - * @param ringbuf Ring buffer to retrieve the item from - * @param[out] item_size Pointer to a variable to which the size of the - * retrieved item will be written. - * @param wanted_size Maximum number of bytes to return. - * - * @return - * - Pointer to the retrieved item on success; *item_size filled with - * the length of the item. - * - NULL when the ringbuffer is empty, *item_size is untouched in that case. - */ -void *xRingbufferReceiveUpToFromISR(RingbufHandle_t ringbuf, size_t *item_size, size_t wanted_size); - - - -/** - * @brief Return a previously-retrieved item to the ringbuffer - * - * @param ringbuf Ring buffer the item was retrieved from - * @param item Item that was received earlier - */ -void vRingbufferReturnItem(RingbufHandle_t ringbuf, void *item); - - - -/** - * @brief Return a previously-retrieved item to the ringbuffer from an ISR - * - * @param ringbuf Ring buffer the item was retrieved from - * @param item Item that was received earlier - * @param[out] higher_prio_task_awoken Value pointed to will be set to pdTRUE - * if the push woke up a higher priority task. - */ -void vRingbufferReturnItemFromISR(RingbufHandle_t ringbuf, void *item, BaseType_t *higher_prio_task_awoken); - - -/** - * @brief Add the ringbuffer to a queue set. - * - * This specifically adds the semaphore that indicates more space - * has become available in the ringbuffer. - * - * @param ringbuf Ring buffer to add to the queue set - * @param xQueueSet Queue set to add the ringbuffer to - * - * @return - * - pdTRUE on success, pdFALSE otherwise - */ -BaseType_t xRingbufferAddToQueueSetRead(RingbufHandle_t ringbuf, QueueSetHandle_t xQueueSet); - - -/** - * @brief Add the ringbuffer to a queue set. - * - * This specifically adds the semaphore that indicates something has been - * written into the ringbuffer. - * - * @param ringbuf Ring buffer to add to the queue set - * @param xQueueSet Queue set to add the ringbuffer to - * - * @return pdTRUE on success, pdFALSE otherwise - */ -BaseType_t xRingbufferAddToQueueSetWrite(RingbufHandle_t ringbuf, QueueSetHandle_t xQueueSet); - - -/** - * @brief Remove the ringbuffer from a queue set. - * - * This specifically removes the semaphore that indicates more space - * has become available in the ringbuffer. - * - * @param ringbuf Ring buffer to remove from the queue set - * @param xQueueSet Queue set to remove the ringbuffer from - * - * @return pdTRUE on success, pdFALSE otherwise - */ -BaseType_t xRingbufferRemoveFromQueueSetRead(RingbufHandle_t ringbuf, QueueSetHandle_t xQueueSet); - - -/** - * @brief Remove the ringbuffer from a queue set. - * - * This specifically removes the semaphore that indicates something - * has been written to the ringbuffer. - * - * @param ringbuf Ring buffer to remove from the queue set - * @param xQueueSet Queue set to remove the ringbuffer from - * - * @return pdTRUE on success, pdFALSE otherwise - */ -BaseType_t xRingbufferRemoveFromQueueSetWrite(RingbufHandle_t ringbuf, QueueSetHandle_t xQueueSet); - - -/** - * @brief Debugging function to print the internal pointers in the ring buffer - * - * @param ringbuf Ring buffer to show - */ -void xRingbufferPrintInfo(RingbufHandle_t ringbuf); - -#ifdef __cplusplus -} -#endif - -#endif /* FREERTOS_RINGBUF_H */ - diff --git a/tools/sdk/include/freertos/freertos/task.h b/tools/sdk/include/freertos/freertos/task.h index 5af62c69c66..3fc06d9e38a 100644 --- a/tools/sdk/include/freertos/freertos/task.h +++ b/tools/sdk/include/freertos/freertos/task.h @@ -93,6 +93,9 @@ extern "C" { #define tskKERNEL_VERSION_MINOR 2 #define tskKERNEL_VERSION_BUILD 0 +/** + * @brief Argument of xTaskCreatePinnedToCore indicating that task has no affinity + */ #define tskNO_AFFINITY INT_MAX /** @@ -181,6 +184,9 @@ typedef struct xTASK_STATUS 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. */ uint32_t 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. This field is present if CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID is set. */ +#endif } TaskStatus_t; /** @@ -233,7 +239,11 @@ typedef enum * * \ingroup SchedulerControl */ +#ifdef _ESP_FREERTOS_INTERNAL #define taskENTER_CRITICAL(mux) portENTER_CRITICAL(mux) +#else +#define taskENTER_CRITICAL(mux) _Pragma("GCC warning \"'taskENTER_CRITICAL(mux)' is deprecated in ESP-IDF, consider using 'portENTER_CRITICAL(mux)'\"") portENTER_CRITICAL(mux) +#endif #define taskENTER_CRITICAL_ISR(mux) portENTER_CRITICAL_ISR(mux) /** @@ -247,7 +257,11 @@ typedef enum * * \ingroup SchedulerControl */ +#ifdef _ESP_FREERTOS_INTERNAL #define taskEXIT_CRITICAL(mux) portEXIT_CRITICAL(mux) +#else +#define taskEXIT_CRITICAL(mux) _Pragma("GCC warning \"'taskEXIT_CRITICAL(mux)' is deprecated in ESP-IDF, consider using 'portEXIT_CRITICAL(mux)'\"") portEXIT_CRITICAL(mux) +#endif #define taskEXIT_CRITICAL_ISR(mux) portEXIT_CRITICAL_ISR(mux) /** @@ -294,9 +308,7 @@ is used in assert() statements. */ * is 16. * * @param usStackDepth The size of the task stack specified as the number of - * variables the stack can hold - not the number of bytes. For example, if - * the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes - * will be allocated for stack storage. + * bytes. Note that this differs from vanilla FreeRTOS. * * @param pvParameters Pointer that will be used as the parameter for the task * being created. @@ -361,9 +373,7 @@ is used in assert() statements. */ * is 16. * * @param usStackDepth The size of the task stack specified as the number of - * variables the stack can hold - not the number of bytes. For example, if - * the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes - * will be allocated for stack storage. + * bytes. Note that this differs from vanilla FreeRTOS. * * @param pvParameters Pointer that will be used as the parameter for the task * being created. @@ -449,9 +459,7 @@ is used in assert() statements. */ * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. * * @param ulStackDepth The size of the task stack specified as the number of - * variables the stack can hold - not the number of bytes. For example, if - * the stack is 32-bits wide and ulStackDepth is defined as 100 then 400 bytes - * will be allocated for stack storage. + * bytes. Note that this differs from vanilla FreeRTOS. * * @param pvParameters Pointer that will be used as the parameter for the task * being created. @@ -511,9 +519,7 @@ is used in assert() statements. */ * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. * * @param ulStackDepth The size of the task stack specified as the number of - * variables the stack can hold - not the number of bytes. For example, if - * the stack is 32-bits wide and ulStackDepth is defined as 100 then 400 bytes - * will be allocated for stack storage. + * bytes. Note that this differs from vanilla FreeRTOS. * * @param pvParameters Pointer that will be used as the parameter for the task * being created. @@ -540,9 +546,8 @@ is used in assert() statements. */ * @code{c} * * // Dimensions the buffer that the task being created will use as its stack. - * // NOTE: This is the number of words the stack will hold, not the number of - * // bytes. For example, if each stack item is 32-bits, and this is set to 100, - * // then 400 bytes (100 * 32-bits) will be allocated. + * // 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. @@ -575,7 +580,7 @@ is used in assert() statements. */ * xHandle = xTaskCreateStatic( * vTaskCode, // Function that implements the task. * "NAME", // Text name for the task. - * STACK_SIZE, // Stack size in words, not bytes. + * 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. @@ -631,7 +636,7 @@ is used in assert() statements. */ * { * 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. + * 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. @@ -1328,15 +1333,15 @@ char *pcTaskGetTaskName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for * this function to be available. * - * High water mark 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. + * High water mark is the minimum free stack space there has been (in bytes + * rather than words as found in vanilla FreeRTOS) since the task started. * The smaller the returned number the closer the task has come to overflowing its stack. * * @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 + * @return The smallest amount of free stack space there has been (in bytes + * rather than words as found in vanilla FreeRTOS) since the task referenced by * xTask was created. */ UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; diff --git a/tools/sdk/include/freertos/freertos/xtensa_rtos.h b/tools/sdk/include/freertos/freertos/xtensa_rtos.h index e5982b83a54..25d42da59bc 100644 --- a/tools/sdk/include/freertos/freertos/xtensa_rtos.h +++ b/tools/sdk/include/freertos/freertos/xtensa_rtos.h @@ -50,7 +50,6 @@ Should be included by all Xtensa generic and RTOS port-specific sources. #include #include -#include /* Include any RTOS specific definitions that are needed by this header. diff --git a/tools/sdk/include/heap/esp_heap_caps.h b/tools/sdk/include/heap/esp_heap_caps.h index c9a983dba6d..5a7aa6bc2f3 100644 --- a/tools/sdk/include/heap/esp_heap_caps.h +++ b/tools/sdk/include/heap/esp_heap_caps.h @@ -67,7 +67,7 @@ void *heap_caps_malloc(size_t size, uint32_t caps); void heap_caps_free( void *ptr); /** - * @brief Reallocate memory previously allocated via heap_caps_malloc() or heaps_caps_realloc(). + * @brief Reallocate memory previously allocated via heap_caps_malloc() or heap_caps_realloc(). * * Equivalent semantics to libc realloc(), for capability-aware memory. * @@ -90,7 +90,7 @@ void *heap_caps_realloc( void *ptr, size_t size, int caps); * * Equivalent semantics to libc calloc(), for capability-aware memory. * - * In IDF, ``calloc(p)`` is equivalent to ``heaps_caps_calloc(p, MALLOC_CAP_8BIT)``. + * In IDF, ``calloc(p)`` is equivalent to ``heap_caps_calloc(p, MALLOC_CAP_8BIT)``. * * @param n Number of continuing chunks of memory to allocate * @param size Size, in bytes, of a chunk of memory to allocate diff --git a/tools/sdk/include/heap/esp_heap_caps_init.h b/tools/sdk/include/heap/esp_heap_caps_init.h index 3cf23ff7f37..3ae6b8e4fc4 100644 --- a/tools/sdk/include/heap/esp_heap_caps_init.h +++ b/tools/sdk/include/heap/esp_heap_caps_init.h @@ -81,6 +81,7 @@ esp_err_t heap_caps_add_region(intptr_t start, intptr_t end); * - ESP_OK on success * - ESP_ERR_INVALID_ARG if a parameter is invalid * - ESP_ERR_NO_MEM if no memory to register new heap. + * - ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap * - ESP_FAIL if region overlaps the start and/or end of an existing region */ esp_err_t heap_caps_add_region_with_caps(const uint32_t caps[], intptr_t start, intptr_t end); diff --git a/tools/sdk/include/heap/esp_heap_trace.h b/tools/sdk/include/heap/esp_heap_trace.h index 08b8caa2184..5573d5e5abb 100644 --- a/tools/sdk/include/heap/esp_heap_trace.h +++ b/tools/sdk/include/heap/esp_heap_trace.h @@ -38,7 +38,7 @@ typedef enum { * @brief Trace record data type. Stores information about an allocated region of memory. */ typedef struct { - uint32_t ccount; ///< CCOUNT of the CPU when the allocation was made. LSB (bit value 1) is the CPU number (0 or 1). */ + uint32_t ccount; ///< CCOUNT of the CPU when the allocation was made. LSB (bit value 1) is the CPU number (0 or 1). void *address; ///< Address which was allocated size_t size; ///< Size of the allocation void *alloced_by[CONFIG_HEAP_TRACING_STACK_DEPTH]; ///< Call stack of the caller which allocated the memory. diff --git a/tools/sdk/include/idf_test/idf_performance.h b/tools/sdk/include/idf_test/idf_performance.h new file mode 100644 index 00000000000..e864b293299 --- /dev/null +++ b/tools/sdk/include/idf_test/idf_performance.h @@ -0,0 +1,35 @@ + +/* @brief macro to print IDF performance + * @param mode : performance item name. a string pointer. + * @param value_fmt: print format and unit of the value, for example: "%02fms", "%dKB" + * @param value : the performance value. +*/ +#define IDF_LOG_PERFORMANCE(item, value_fmt, value) \ + printf("[Performance][%s]: "value_fmt"\n", item, value) + + +/* declare the performance here */ +#define IDF_PERFORMANCE_MAX_HTTPS_REQUEST_BIN_SIZE 800 +#define IDF_PERFORMANCE_MAX_FREERTOS_SPINLOCK_CYCLES_PER_OP 200 +#define IDF_PERFORMANCE_MAX_FREERTOS_SPINLOCK_CYCLES_PER_OP_PSRAM 300 +#define IDF_PERFORMANCE_MAX_FREERTOS_SPINLOCK_CYCLES_PER_OP_UNICORE 130 +#define IDF_PERFORMANCE_MAX_ESP_TIMER_GET_TIME_PER_CALL 1000 +#define IDF_PERFORMANCE_MAX_SPI_PER_TRANS_NO_POLLING 30 +#define IDF_PERFORMANCE_MAX_SPI_PER_TRANS_NO_POLLING_NO_DMA 27 +#define IDF_PERFORMANCE_MAX_SPI_PER_TRANS_POLLING 15 +#define IDF_PERFORMANCE_MAX_SPI_PER_TRANS_POLLING_NO_DMA 15 +/* Due to code size & linker layout differences interacting with cache, VFS + microbenchmark currently runs slower with PSRAM enabled. */ +#define IDF_PERFORMANCE_MAX_VFS_OPEN_WRITE_CLOSE_TIME 50000 +#define IDF_PERFORMANCE_MAX_VFS_OPEN_WRITE_CLOSE_TIME_PSRAM 40000 +// throughput performance by iperf +#define IDF_PERFORMANCE_MIN_TCP_RX_THROUGHPUT 50 +#define IDF_PERFORMANCE_MIN_TCP_TX_THROUGHPUT 40 +#define IDF_PERFORMANCE_MIN_UDP_RX_THROUGHPUT 80 +#define IDF_PERFORMANCE_MIN_UDP_TX_THROUGHPUT 50 +// events dispatched per second by event loop library +#define IDF_PERFORMANCE_MIN_EVENT_DISPATCH 25000 +#define IDF_PERFORMANCE_MIN_EVENT_DISPATCH_PSRAM 21000 +// esp_sha() time to process 32KB of input data from RAM +#define IDF_PERFORMANCE_MAX_ESP32_TIME_SHA1_32KB 5000 +#define IDF_PERFORMANCE_MAX_ESP32_TIME_SHA512_32KB 4500 diff --git a/tools/sdk/include/json/cJSON.h b/tools/sdk/include/json/cJSON.h index 52101e11793..592986b86e9 100644 --- a/tools/sdk/include/json/cJSON.h +++ b/tools/sdk/include/json/cJSON.h @@ -28,10 +28,60 @@ extern "C" { #endif +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + /* project version */ #define CJSON_VERSION_MAJOR 1 #define CJSON_VERSION_MINOR 7 -#define CJSON_VERSION_PATCH 1 +#define CJSON_VERSION_PATCH 12 #include @@ -74,55 +124,13 @@ typedef struct cJSON typedef struct cJSON_Hooks { - void *(*malloc_fn)(size_t sz); - void (*free_fn)(void *ptr); + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); } cJSON_Hooks; typedef int cJSON_bool; -#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) -#define __WINDOWS__ -#endif -#ifdef __WINDOWS__ - -/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 2 define options: - -CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols -CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) -CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol - -For *nix builds that support visibility attribute, you can define similar behavior by - -setting default visibility to hidden by adding --fvisibility=hidden (for gcc) -or --xldscope=hidden (for sun cc) -to CFLAGS - -then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does - -*/ - -/* export symbols by default, this is necessary for copy pasting the C and header file */ -#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) -#define CJSON_EXPORT_SYMBOLS -#endif - -#if defined(CJSON_HIDE_SYMBOLS) -#define CJSON_PUBLIC(type) type __stdcall -#elif defined(CJSON_EXPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllexport) type __stdcall -#elif defined(CJSON_IMPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllimport) type __stdcall -#endif -#else /* !WIN32 */ -#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) -#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type -#else -#define CJSON_PUBLIC(type) type -#endif -#endif - /* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. * This is to prevent stack overflows. */ #ifndef CJSON_NESTING_LIMIT @@ -156,7 +164,7 @@ CJSON_PUBLIC(void) cJSON_Delete(cJSON *c); /* Returns the number of items in an array (or object). */ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); -/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */ +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); /* Get item "string" from object. Case insensitive. */ CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); diff --git a/tools/sdk/include/json/cJSON_Utils.h b/tools/sdk/include/json/cJSON_Utils.h index 03ec10c9e2c..a970c650467 100644 --- a/tools/sdk/include/json/cJSON_Utils.h +++ b/tools/sdk/include/json/cJSON_Utils.h @@ -20,6 +20,14 @@ THE SOFTWARE. */ +#ifndef cJSON_Utils__h +#define cJSON_Utils__h + +#ifdef __cplusplus +extern "C" +{ +#endif + #include "cJSON.h" /* Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec. */ @@ -72,3 +80,9 @@ CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const obje /* Sorts the members of the object into alphabetical order. */ CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object); CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/json/tests/common.h b/tools/sdk/include/json/tests/common.h new file mode 100644 index 00000000000..4db6bf8c2d1 --- /dev/null +++ b/tools/sdk/include/json/tests/common.h @@ -0,0 +1,122 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + 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 CJSON_TESTS_COMMON_H +#define CJSON_TESTS_COMMON_H + +#include "../cJSON.c" + +void reset(cJSON *item); +void reset(cJSON *item) { + if ((item != NULL) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if ((item->valuestring != NULL) && !(item->type & cJSON_IsReference)) + { + global_hooks.deallocate(item->valuestring); + } + if ((item->string != NULL) && !(item->type & cJSON_StringIsConst)) + { + global_hooks.deallocate(item->string); + } + + memset(item, 0, sizeof(cJSON)); +} + +char* read_file(const char *filename); +char* read_file(const char *filename) { + FILE *file = NULL; + long length = 0; + char *content = NULL; + size_t read_chars = 0; + + /* open in read binary mode */ + file = fopen(filename, "rb"); + if (file == NULL) + { + goto cleanup; + } + + /* get the length */ + if (fseek(file, 0, SEEK_END) != 0) + { + goto cleanup; + } + length = ftell(file); + if (length < 0) + { + goto cleanup; + } + if (fseek(file, 0, SEEK_SET) != 0) + { + goto cleanup; + } + + /* allocate content buffer */ + content = (char*)malloc((size_t)length + sizeof("")); + if (content == NULL) + { + goto cleanup; + } + + /* read the file into memory */ + read_chars = fread(content, sizeof(char), (size_t)length, file); + if ((long)read_chars != length) + { + free(content); + content = NULL; + goto cleanup; + } + content[read_chars] = '\0'; + + +cleanup: + if (file != NULL) + { + fclose(file); + } + + return content; +} + +/* assertion helper macros */ +#define assert_has_type(item, item_type) TEST_ASSERT_BITS_MESSAGE(0xFF, item_type, item->type, "Item doesn't have expected type.") +#define assert_has_no_reference(item) TEST_ASSERT_BITS_MESSAGE(cJSON_IsReference, 0, item->type, "Item should not have a string as reference.") +#define assert_has_no_const_string(item) TEST_ASSERT_BITS_MESSAGE(cJSON_StringIsConst, 0, item->type, "Item should not have a const string.") +#define assert_has_valuestring(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->valuestring, "Valuestring is NULL.") +#define assert_has_no_valuestring(item) TEST_ASSERT_NULL_MESSAGE(item->valuestring, "Valuestring is not NULL.") +#define assert_has_string(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->string, "String is NULL") +#define assert_has_no_string(item) TEST_ASSERT_NULL_MESSAGE(item->string, "String is not NULL.") +#define assert_not_in_list(item) \ + TEST_ASSERT_NULL_MESSAGE(item->next, "Linked list next pointer is not NULL.");\ + TEST_ASSERT_NULL_MESSAGE(item->prev, "Linked list previous pointer is not NULL.") +#define assert_has_child(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->child, "Item doesn't have a child.") +#define assert_has_no_child(item) TEST_ASSERT_NULL_MESSAGE(item->child, "Item has a child.") +#define assert_is_invalid(item) \ + assert_has_type(item, cJSON_Invalid);\ + assert_not_in_list(item);\ + assert_has_no_child(item);\ + assert_has_no_string(item);\ + assert_has_no_valuestring(item) + +#endif diff --git a/tools/sdk/include/json/tests/unity/examples/example_1/src/ProductionCode.h b/tools/sdk/include/json/tests/unity/examples/example_1/src/ProductionCode.h new file mode 100644 index 00000000000..250ca0dc6fe --- /dev/null +++ b/tools/sdk/include/json/tests/unity/examples/example_1/src/ProductionCode.h @@ -0,0 +1,3 @@ + +int FindFunction_WhichIsBroken(int NumberToFind); +int FunctionWhichReturnsLocalVariable(void); diff --git a/tools/sdk/include/json/tests/unity/examples/example_1/src/ProductionCode2.h b/tools/sdk/include/json/tests/unity/examples/example_1/src/ProductionCode2.h new file mode 100644 index 00000000000..34ae980d182 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/examples/example_1/src/ProductionCode2.h @@ -0,0 +1,2 @@ + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction); diff --git a/tools/sdk/include/json/tests/unity/examples/example_2/src/ProductionCode.h b/tools/sdk/include/json/tests/unity/examples/example_2/src/ProductionCode.h new file mode 100644 index 00000000000..250ca0dc6fe --- /dev/null +++ b/tools/sdk/include/json/tests/unity/examples/example_2/src/ProductionCode.h @@ -0,0 +1,3 @@ + +int FindFunction_WhichIsBroken(int NumberToFind); +int FunctionWhichReturnsLocalVariable(void); diff --git a/tools/sdk/include/json/tests/unity/examples/example_2/src/ProductionCode2.h b/tools/sdk/include/json/tests/unity/examples/example_2/src/ProductionCode2.h new file mode 100644 index 00000000000..34ae980d182 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/examples/example_2/src/ProductionCode2.h @@ -0,0 +1,2 @@ + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction); diff --git a/tools/sdk/include/json/tests/unity/examples/example_3/helper/UnityHelper.h b/tools/sdk/include/json/tests/unity/examples/example_3/helper/UnityHelper.h new file mode 100644 index 00000000000..151611158a9 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/examples/example_3/helper/UnityHelper.h @@ -0,0 +1,12 @@ +#ifndef _TESTHELPER_H +#define _TESTHELPER_H + +#include "Types.h" + +void AssertEqualExampleStruct(const EXAMPLE_STRUCT_T expected, const EXAMPLE_STRUCT_T actual, const unsigned short line); + +#define UNITY_TEST_ASSERT_EQUAL_EXAMPLE_STRUCT_T(expected, actual, line, message) AssertEqualExampleStruct(expected, actual, line); + +#define TEST_ASSERT_EQUAL_EXAMPLE_STRUCT_T(expected, actual) UNITY_TEST_ASSERT_EQUAL_EXAMPLE_STRUCT_T(expected, actual, __LINE__, NULL); + +#endif // _TESTHELPER_H diff --git a/tools/sdk/include/json/tests/unity/examples/example_3/src/ProductionCode.h b/tools/sdk/include/json/tests/unity/examples/example_3/src/ProductionCode.h new file mode 100644 index 00000000000..250ca0dc6fe --- /dev/null +++ b/tools/sdk/include/json/tests/unity/examples/example_3/src/ProductionCode.h @@ -0,0 +1,3 @@ + +int FindFunction_WhichIsBroken(int NumberToFind); +int FunctionWhichReturnsLocalVariable(void); diff --git a/tools/sdk/include/json/tests/unity/examples/example_3/src/ProductionCode2.h b/tools/sdk/include/json/tests/unity/examples/example_3/src/ProductionCode2.h new file mode 100644 index 00000000000..34ae980d182 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/examples/example_3/src/ProductionCode2.h @@ -0,0 +1,2 @@ + +char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction); diff --git a/tools/sdk/include/json/tests/unity/examples/unity_config.h b/tools/sdk/include/json/tests/unity/examples/unity_config.h new file mode 100644 index 00000000000..a2f161a7a72 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/examples/unity_config.h @@ -0,0 +1,239 @@ +/* Unity Configuration + * As of May 11th, 2016 at ThrowTheSwitch/Unity commit 837c529 + * Update: December 29th, 2016 + * See Also: Unity/docs/UnityConfigurationGuide.pdf + * + * Unity is designed to run on almost anything that is targeted by a C compiler. + * It would be awesome if this could be done with zero configuration. While + * there are some targets that come close to this dream, it is sadly not + * universal. It is likely that you are going to need at least a couple of the + * configuration options described in this document. + * + * All of Unity's configuration options are `#defines`. Most of these are simple + * definitions. A couple are macros with arguments. They live inside the + * unity_internals.h header file. We don't necessarily recommend opening that + * file unless you really need to. That file is proof that a cross-platform + * library is challenging to build. From a more positive perspective, it is also + * proof that a great deal of complexity can be centralized primarily to one + * place in order to provide a more consistent and simple experience elsewhere. + * + * Using These Options + * It doesn't matter if you're using a target-specific compiler and a simulator + * or a native compiler. In either case, you've got a couple choices for + * configuring these options: + * + * 1. Because these options are specified via C defines, you can pass most of + * these options to your compiler through command line compiler flags. Even + * if you're using an embedded target that forces you to use their + * overbearing IDE for all configuration, there will be a place somewhere in + * your project to configure defines for your compiler. + * 2. You can create a custom `unity_config.h` configuration file (present in + * your toolchain's search paths). In this file, you will list definitions + * and macros specific to your target. All you must do is define + * `UNITY_INCLUDE_CONFIG_H` and Unity will rely on `unity_config.h` for any + * further definitions it may need. + */ + +#ifndef UNITY_CONFIG_H +#define UNITY_CONFIG_H + +/* ************************* AUTOMATIC INTEGER TYPES *************************** + * C's concept of an integer varies from target to target. The C Standard has + * rules about the `int` matching the register size of the target + * microprocessor. It has rules about the `int` and how its size relates to + * other integer types. An `int` on one target might be 16 bits while on another + * target it might be 64. There are more specific types in compilers compliant + * with C99 or later, but that's certainly not every compiler you are likely to + * encounter. Therefore, Unity has a number of features for helping to adjust + * itself to match your required integer sizes. It starts off by trying to do it + * automatically. + **************************************************************************** */ + +/* The first attempt to guess your types is to check `limits.h`. Some compilers + * that don't support `stdint.h` could include `limits.h`. If you don't + * want Unity to check this file, define this to make it skip the inclusion. + * Unity looks at UINT_MAX & ULONG_MAX, which were available since C89. + */ +/* #define UNITY_EXCLUDE_LIMITS_H */ + +/* The second thing that Unity does to guess your types is check `stdint.h`. + * This file defines `UINTPTR_MAX`, since C99, that Unity can make use of to + * learn about your system. It's possible you don't want it to do this or it's + * possible that your system doesn't support `stdint.h`. If that's the case, + * you're going to want to define this. That way, Unity will know to skip the + * inclusion of this file and you won't be left with a compiler error. + */ +/* #define UNITY_EXCLUDE_STDINT_H */ + +/* ********************** MANUAL INTEGER TYPE DEFINITION *********************** + * If you've disabled all of the automatic options above, you're going to have + * to do the configuration yourself. There are just a handful of defines that + * you are going to specify if you don't like the defaults. + **************************************************************************** */ + + /* Define this to be the number of bits an `int` takes up on your system. The + * default, if not auto-detected, is 32 bits. + * + * Example: + */ +/* #define UNITY_INT_WIDTH 16 */ + +/* Define this to be the number of bits a `long` takes up on your system. The + * default, if not autodetected, is 32 bits. This is used to figure out what + * kind of 64-bit support your system can handle. Does it need to specify a + * `long` or a `long long` to get a 64-bit value. On 16-bit systems, this option + * is going to be ignored. + * + * Example: + */ +/* #define UNITY_LONG_WIDTH 16 */ + +/* Define this to be the number of bits a pointer takes up on your system. The + * default, if not autodetected, is 32-bits. If you're getting ugly compiler + * warnings about casting from pointers, this is the one to look at. + * + * Example: + */ +/* #define UNITY_POINTER_WIDTH 64 */ + +/* Unity will automatically include 64-bit support if it auto-detects it, or if + * your `int`, `long`, or pointer widths are greater than 32-bits. Define this + * to enable 64-bit support if none of the other options already did it for you. + * There can be a significant size and speed impact to enabling 64-bit support + * on small targets, so don't define it if you don't need it. + */ +/* #define UNITY_INCLUDE_64 */ + + +/* *************************** FLOATING POINT TYPES **************************** + * In the embedded world, it's not uncommon for targets to have no support for + * floating point operations at all or to have support that is limited to only + * single precision. We are able to guess integer sizes on the fly because + * integers are always available in at least one size. Floating point, on the + * other hand, is sometimes not available at all. Trying to include `float.h` on + * these platforms would result in an error. This leaves manual configuration as + * the only option. + **************************************************************************** */ + + /* By default, Unity guesses that you will want single precision floating point + * support, but not double precision. It's easy to change either of these using + * the include and exclude options here. You may include neither, just float, + * or both, as suits your needs. + */ +/* #define UNITY_EXCLUDE_FLOAT */ +#define UNITY_INCLUDE_DOUBLE +/* #define UNITY_EXCLUDE_DOUBLE */ + +/* For features that are enabled, the following floating point options also + * become available. + */ + +/* Unity aims for as small of a footprint as possible and avoids most standard + * library calls (some embedded platforms don't have a standard library!). + * Because of this, its routines for printing integer values are minimalist and + * hand-coded. To keep Unity universal, though, we eventually chose to develop + * our own floating point print routines. Still, the display of floating point + * values during a failure are optional. By default, Unity will print the + * actual results of floating point assertion failures. So a failed assertion + * will produce a message like "Expected 4.0 Was 4.25". If you would like less + * verbose failure messages for floating point assertions, use this option to + * give a failure message `"Values Not Within Delta"` and trim the binary size. + */ +/* #define UNITY_EXCLUDE_FLOAT_PRINT */ + +/* If enabled, Unity assumes you want your `FLOAT` asserts to compare standard C + * floats. If your compiler supports a specialty floating point type, you can + * always override this behavior by using this definition. + * + * Example: + */ +/* #define UNITY_FLOAT_TYPE float16_t */ + +/* If enabled, Unity assumes you want your `DOUBLE` asserts to compare standard + * C doubles. If you would like to change this, you can specify something else + * by using this option. For example, defining `UNITY_DOUBLE_TYPE` to `long + * double` could enable gargantuan floating point types on your 64-bit processor + * instead of the standard `double`. + * + * Example: + */ +/* #define UNITY_DOUBLE_TYPE long double */ + +/* If you look up `UNITY_ASSERT_EQUAL_FLOAT` and `UNITY_ASSERT_EQUAL_DOUBLE` as + * documented in the Unity Assertion Guide, you will learn that they are not + * really asserting that two values are equal but rather that two values are + * "close enough" to equal. "Close enough" is controlled by these precision + * configuration options. If you are working with 32-bit floats and/or 64-bit + * doubles (the normal on most processors), you should have no need to change + * these options. They are both set to give you approximately 1 significant bit + * in either direction. The float precision is 0.00001 while the double is + * 10^-12. For further details on how this works, see the appendix of the Unity + * Assertion Guide. + * + * Example: + */ +/* #define UNITY_FLOAT_PRECISION 0.001f */ +/* #define UNITY_DOUBLE_PRECISION 0.001f */ + + +/* *************************** TOOLSET CUSTOMIZATION *************************** + * In addition to the options listed above, there are a number of other options + * which will come in handy to customize Unity's behavior for your specific + * toolchain. It is possible that you may not need to touch any of these but + * certain platforms, particularly those running in simulators, may need to jump + * through extra hoops to operate properly. These macros will help in those + * situations. + **************************************************************************** */ + +/* By default, Unity prints its results to `stdout` as it runs. This works + * perfectly fine in most situations where you are using a native compiler for + * testing. It works on some simulators as well so long as they have `stdout` + * routed back to the command line. There are times, however, where the + * simulator will lack support for dumping results or you will want to route + * results elsewhere for other reasons. In these cases, you should define the + * `UNITY_OUTPUT_CHAR` macro. This macro accepts a single character at a time + * (as an `int`, since this is the parameter type of the standard C `putchar` + * function most commonly used). You may replace this with whatever function + * call you like. + * + * Example: + * Say you are forced to run your test suite on an embedded processor with no + * `stdout` option. You decide to route your test result output to a custom + * serial `RS232_putc()` function you wrote like thus: + */ +/* #define UNITY_OUTPUT_CHAR(a) RS232_putc(a) */ +/* #define UNITY_OUTPUT_CHAR_HEADER_DECLARATION RS232_putc(int) */ +/* #define UNITY_OUTPUT_FLUSH() RS232_flush() */ +/* #define UNITY_OUTPUT_FLUSH_HEADER_DECLARATION RS232_flush(void) */ +/* #define UNITY_OUTPUT_START() RS232_config(115200,1,8,0) */ +/* #define UNITY_OUTPUT_COMPLETE() RS232_close() */ + +/* For some targets, Unity can make the otherwise required `setUp()` and + * `tearDown()` functions optional. This is a nice convenience for test writers + * since `setUp` and `tearDown` don't often actually _do_ anything. If you're + * using gcc or clang, this option is automatically defined for you. Other + * compilers can also support this behavior, if they support a C feature called + * weak functions. A weak function is a function that is compiled into your + * executable _unless_ a non-weak version of the same function is defined + * elsewhere. If a non-weak version is found, the weak version is ignored as if + * it never existed. If your compiler supports this feature, you can let Unity + * know by defining `UNITY_SUPPORT_WEAK` as the function attributes that would + * need to be applied to identify a function as weak. If your compiler lacks + * support for weak functions, you will always need to define `setUp` and + * `tearDown` functions (though they can be and often will be just empty). The + * most common options for this feature are: + */ +/* #define UNITY_SUPPORT_WEAK weak */ +/* #define UNITY_SUPPORT_WEAK __attribute__((weak)) */ +/* #define UNITY_NO_WEAK */ + +/* Some compilers require a custom attribute to be assigned to pointers, like + * `near` or `far`. In these cases, you can give Unity a safe default for these + * by defining this option with the attribute you would like. + * + * Example: + */ +/* #define UNITY_PTR_ATTRIBUTE __attribute__((far)) */ +/* #define UNITY_PTR_ATTRIBUTE near */ + +#endif /* UNITY_CONFIG_H */ diff --git a/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture.h b/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture.h new file mode 100644 index 00000000000..6f8d6234b37 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture.h @@ -0,0 +1,83 @@ +/* Copyright (c) 2010 James Grenning and Contributed to Unity Project + * ========================================== + * Unity Project - A Test Framework for C + * Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + * [Released under MIT License. Please refer to license.txt for details] + * ========================================== */ + +#ifndef UNITY_FIXTURE_H_ +#define UNITY_FIXTURE_H_ + +#include "unity.h" +#include "unity_internals.h" +#include "unity_fixture_malloc_overrides.h" +#include "unity_fixture_internals.h" + +int UnityMain(int argc, const char* argv[], void (*runAllTests)(void)); + + +#define TEST_GROUP(group)\ + static const char* TEST_GROUP_##group = #group + +#define TEST_SETUP(group) void TEST_##group##_SETUP(void);\ + void TEST_##group##_SETUP(void) + +#define TEST_TEAR_DOWN(group) void TEST_##group##_TEAR_DOWN(void);\ + void TEST_##group##_TEAR_DOWN(void) + + +#define TEST(group, name) \ + void TEST_##group##_##name##_(void);\ + void TEST_##group##_##name##_run(void);\ + void TEST_##group##_##name##_run(void)\ + {\ + UnityTestRunner(TEST_##group##_SETUP,\ + TEST_##group##_##name##_,\ + TEST_##group##_TEAR_DOWN,\ + "TEST(" #group ", " #name ")",\ + TEST_GROUP_##group, #name,\ + __FILE__, __LINE__);\ + }\ + void TEST_##group##_##name##_(void) + +#define IGNORE_TEST(group, name) \ + void TEST_##group##_##name##_(void);\ + void TEST_##group##_##name##_run(void);\ + void TEST_##group##_##name##_run(void)\ + {\ + UnityIgnoreTest("IGNORE_TEST(" #group ", " #name ")", TEST_GROUP_##group, #name);\ + }\ + void TEST_##group##_##name##_(void) + +/* Call this for each test, insider the group runner */ +#define RUN_TEST_CASE(group, name) \ + { void TEST_##group##_##name##_run(void);\ + TEST_##group##_##name##_run(); } + +/* This goes at the bottom of each test file or in a separate c file */ +#define TEST_GROUP_RUNNER(group)\ + void TEST_##group##_GROUP_RUNNER(void);\ + void TEST_##group##_GROUP_RUNNER(void) + +/* Call this from main */ +#define RUN_TEST_GROUP(group)\ + { void TEST_##group##_GROUP_RUNNER(void);\ + TEST_##group##_GROUP_RUNNER(); } + +/* CppUTest Compatibility Macros */ +#ifndef UNITY_EXCLUDE_CPPUTEST_ASSERTS +/* Sets a pointer and automatically restores it to its old value after teardown */ +#define UT_PTR_SET(ptr, newPointerValue) UnityPointer_Set((void**)&(ptr), (void*)(newPointerValue), __LINE__) +#define TEST_ASSERT_POINTERS_EQUAL(expected, actual) TEST_ASSERT_EQUAL_PTR((expected), (actual)) +#define TEST_ASSERT_BYTES_EQUAL(expected, actual) TEST_ASSERT_EQUAL_HEX8(0xff & (expected), 0xff & (actual)) +#define FAIL(message) TEST_FAIL_MESSAGE((message)) +#define CHECK(condition) TEST_ASSERT_TRUE((condition)) +#define LONGS_EQUAL(expected, actual) TEST_ASSERT_EQUAL_INT((expected), (actual)) +#define STRCMP_EQUAL(expected, actual) TEST_ASSERT_EQUAL_STRING((expected), (actual)) +#define DOUBLES_EQUAL(expected, actual, delta) TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual)) +#endif + +/* You must compile with malloc replacement, as defined in unity_fixture_malloc_overrides.h */ +void UnityMalloc_MakeMallocFailAfterCount(int count); + +#endif /* UNITY_FIXTURE_H_ */ diff --git a/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture_internals.h b/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture_internals.h new file mode 100644 index 00000000000..aa0d9e7c0b9 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture_internals.h @@ -0,0 +1,51 @@ +/* Copyright (c) 2010 James Grenning and Contributed to Unity Project + * ========================================== + * Unity Project - A Test Framework for C + * Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + * [Released under MIT License. Please refer to license.txt for details] + * ========================================== */ + +#ifndef UNITY_FIXTURE_INTERNALS_H_ +#define UNITY_FIXTURE_INTERNALS_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif + +struct UNITY_FIXTURE_T +{ + int Verbose; + unsigned int RepeatCount; + const char* NameFilter; + const char* GroupFilter; +}; +extern struct UNITY_FIXTURE_T UnityFixture; + +typedef void unityfunction(void); +void UnityTestRunner(unityfunction* setup, + unityfunction* body, + unityfunction* teardown, + const char* printableName, + const char* group, + const char* name, + const char* file, unsigned int line); + +void UnityIgnoreTest(const char* printableName, const char* group, const char* name); +void UnityMalloc_StartTest(void); +void UnityMalloc_EndTest(void); +int UnityGetCommandLineOptions(int argc, const char* argv[]); +void UnityConcludeFixtureTest(void); + +void UnityPointer_Set(void** ptr, void* newValue, UNITY_LINE_TYPE line); +void UnityPointer_UndoAllSets(void); +void UnityPointer_Init(void); +#ifndef UNITY_MAX_POINTERS +#define UNITY_MAX_POINTERS 5 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* UNITY_FIXTURE_INTERNALS_H_ */ diff --git a/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture_malloc_overrides.h b/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture_malloc_overrides.h new file mode 100644 index 00000000000..7daba50aae5 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/extras/fixture/src/unity_fixture_malloc_overrides.h @@ -0,0 +1,47 @@ +/* Copyright (c) 2010 James Grenning and Contributed to Unity Project + * ========================================== + * Unity Project - A Test Framework for C + * Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + * [Released under MIT License. Please refer to license.txt for details] + * ========================================== */ + +#ifndef UNITY_FIXTURE_MALLOC_OVERRIDES_H_ +#define UNITY_FIXTURE_MALLOC_OVERRIDES_H_ + +#include + +#ifdef UNITY_EXCLUDE_STDLIB_MALLOC +/* Define this macro to remove the use of stdlib.h, malloc, and free. + * Many embedded systems do not have a heap or malloc/free by default. + * This internal unity_malloc() provides allocated memory deterministically from + * the end of an array only, unity_free() only releases from end-of-array, + * blocks are not coalesced, and memory not freed in LIFO order is stranded. */ + #ifndef UNITY_INTERNAL_HEAP_SIZE_BYTES + #define UNITY_INTERNAL_HEAP_SIZE_BYTES 256 + #endif +#endif + +/* These functions are used by the Unity Fixture to allocate and release memory + * on the heap and can be overridden with platform-specific implementations. + * For example, when using FreeRTOS UNITY_FIXTURE_MALLOC becomes pvPortMalloc() + * and UNITY_FIXTURE_FREE becomes vPortFree(). */ +#if !defined(UNITY_FIXTURE_MALLOC) || !defined(UNITY_FIXTURE_FREE) + #include + #define UNITY_FIXTURE_MALLOC(size) malloc(size) + #define UNITY_FIXTURE_FREE(ptr) free(ptr) +#else + extern void* UNITY_FIXTURE_MALLOC(size_t size); + extern void UNITY_FIXTURE_FREE(void* ptr); +#endif + +#define malloc unity_malloc +#define calloc unity_calloc +#define realloc unity_realloc +#define free unity_free + +void* unity_malloc(size_t size); +void* unity_calloc(size_t num, size_t size); +void* unity_realloc(void * oldMem, size_t size); +void unity_free(void * mem); + +#endif /* UNITY_FIXTURE_MALLOC_OVERRIDES_H_ */ diff --git a/tools/sdk/include/json/tests/unity/extras/fixture/test/unity_output_Spy.h b/tools/sdk/include/json/tests/unity/extras/fixture/test/unity_output_Spy.h new file mode 100644 index 00000000000..b30a7f13bbe --- /dev/null +++ b/tools/sdk/include/json/tests/unity/extras/fixture/test/unity_output_Spy.h @@ -0,0 +1,17 @@ +/* Copyright (c) 2010 James Grenning and Contributed to Unity Project + * ========================================== + * Unity Project - A Test Framework for C + * Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + * [Released under MIT License. Please refer to license.txt for details] + * ========================================== */ + +#ifndef D_unity_output_Spy_H +#define D_unity_output_Spy_H + +void UnityOutputCharSpy_Create(int s); +void UnityOutputCharSpy_Destroy(void); +void UnityOutputCharSpy_OutputChar(int c); +const char * UnityOutputCharSpy_Get(void); +void UnityOutputCharSpy_Enable(int enable); + +#endif diff --git a/tools/sdk/include/json/tests/unity/src/unity.h b/tools/sdk/include/json/tests/unity/src/unity.h new file mode 100644 index 00000000000..32ff0e6df46 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/src/unity.h @@ -0,0 +1,503 @@ +/* ========================================== + Unity Project - A Test Framework for C + Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + [Released under MIT License. Please refer to license.txt for details] +========================================== */ + +#ifndef UNITY_FRAMEWORK_H +#define UNITY_FRAMEWORK_H +#define UNITY + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "unity_internals.h" + +/*------------------------------------------------------- + * Test Setup / Teardown + *-------------------------------------------------------*/ + +/* These functions are intended to be called before and after each test. */ +void setUp(void); +void tearDown(void); + +/* These functions are intended to be called at the beginning and end of an + * entire test suite. suiteTearDown() is passed the number of tests that + * failed, and its return value becomes the exit code of main(). */ +void suiteSetUp(void); +int suiteTearDown(int num_failures); + +/* If the compiler supports it, the following block provides stub + * implementations of the above functions as weak symbols. Note that on + * some platforms (MinGW for example), weak function implementations need + * to be in the same translation unit they are called from. This can be + * achieved by defining UNITY_INCLUDE_SETUP_STUBS before including unity.h. */ +#ifdef UNITY_INCLUDE_SETUP_STUBS + #ifdef UNITY_WEAK_ATTRIBUTE + UNITY_WEAK_ATTRIBUTE void setUp(void) { } + UNITY_WEAK_ATTRIBUTE void tearDown(void) { } + UNITY_WEAK_ATTRIBUTE void suiteSetUp(void) { } + UNITY_WEAK_ATTRIBUTE int suiteTearDown(int num_failures) { return num_failures; } + #elif defined(UNITY_WEAK_PRAGMA) + #pragma weak setUp + void setUp(void) { } + #pragma weak tearDown + void tearDown(void) { } + #pragma weak suiteSetUp + void suiteSetUp(void) { } + #pragma weak suiteTearDown + int suiteTearDown(int num_failures) { return num_failures; } + #endif +#endif + +/*------------------------------------------------------- + * Configuration Options + *------------------------------------------------------- + * All options described below should be passed as a compiler flag to all files using Unity. If you must add #defines, place them BEFORE the #include above. + + * Integers/longs/pointers + * - Unity attempts to automatically discover your integer sizes + * - define UNITY_EXCLUDE_STDINT_H to stop attempting to look in + * - define UNITY_EXCLUDE_LIMITS_H to stop attempting to look in + * - If you cannot use the automatic methods above, you can force Unity by using these options: + * - define UNITY_SUPPORT_64 + * - set UNITY_INT_WIDTH + * - set UNITY_LONG_WIDTH + * - set UNITY_POINTER_WIDTH + + * Floats + * - define UNITY_EXCLUDE_FLOAT to disallow floating point comparisons + * - define UNITY_FLOAT_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_FLOAT + * - define UNITY_FLOAT_TYPE to specify doubles instead of single precision floats + * - define UNITY_INCLUDE_DOUBLE to allow double floating point comparisons + * - define UNITY_EXCLUDE_DOUBLE to disallow double floating point comparisons (default) + * - define UNITY_DOUBLE_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_DOUBLE + * - define UNITY_DOUBLE_TYPE to specify something other than double + * - define UNITY_EXCLUDE_FLOAT_PRINT to trim binary size, won't print floating point values in errors + + * Output + * - by default, Unity prints to standard out with putchar. define UNITY_OUTPUT_CHAR(a) with a different function if desired + * - define UNITY_DIFFERENTIATE_FINAL_FAIL to print FAILED (vs. FAIL) at test end summary - for automated search for failure + + * Optimization + * - by default, line numbers are stored in unsigned shorts. Define UNITY_LINE_TYPE with a different type if your files are huge + * - by default, test and failure counters are unsigned shorts. Define UNITY_COUNTER_TYPE with a different type if you want to save space or have more than 65535 Tests. + + * Test Cases + * - define UNITY_SUPPORT_TEST_CASES to include the TEST_CASE macro, though really it's mostly about the runner generator script + + * Parameterized Tests + * - you'll want to create a define of TEST_CASE(...) which basically evaluates to nothing + + * Tests with Arguments + * - you'll want to define UNITY_USE_COMMAND_LINE_ARGS if you have the test runner passing arguments to Unity + + *------------------------------------------------------- + * Basic Fail and Ignore + *-------------------------------------------------------*/ + +#define TEST_FAIL_MESSAGE(message) UNITY_TEST_FAIL(__LINE__, (message)) +#define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL) +#define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message)) +#define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL) +#define TEST_ONLY() + +/* It is not necessary for you to call PASS. A PASS condition is assumed if nothing fails. + * This method allows you to abort a test immediately with a PASS state, ignoring the remainder of the test. */ +#define TEST_PASS() TEST_ABORT() + +/* This macro does nothing, but it is useful for build tools (like Ceedling) to make use of this to figure out + * which files should be linked to in order to perform a test. Use it like TEST_FILE("sandwiches.c") */ +#define TEST_FILE(a) + +/*------------------------------------------------------- + * Test Asserts (simple) + *-------------------------------------------------------*/ + +/* Boolean */ +#define TEST_ASSERT(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expression Evaluated To FALSE") +#define TEST_ASSERT_TRUE(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expected TRUE Was FALSE") +#define TEST_ASSERT_UNLESS(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expression Evaluated To TRUE") +#define TEST_ASSERT_FALSE(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expected FALSE Was TRUE") +#define TEST_ASSERT_NULL(pointer) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, " Expected NULL") +#define TEST_ASSERT_NOT_NULL(pointer) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, " Expected Non-NULL") + +/* Integers (of all sizes) */ +#define TEST_ASSERT_EQUAL_INT(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") +#define TEST_ASSERT_EQUAL_UINT(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX8(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX16(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX32(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX64(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_BITS(mask, expected, actual) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_BITS_HIGH(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, NULL) +#define TEST_ASSERT_BITS_LOW(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, NULL) +#define TEST_ASSERT_BIT_HIGH(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, NULL) +#define TEST_ASSERT_BIT_LOW(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, NULL) + +/* Integer Greater Than/ Less Than (of all sizes) */ +#define TEST_ASSERT_GREATER_THAN(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, NULL) + +#define TEST_ASSERT_LESS_THAN(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, NULL) + +#define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) + +#define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) + +/* Integer Ranges (of all sizes) */ +#define TEST_ASSERT_INT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_INT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, NULL) + +/* Structs and Strings */ +#define TEST_ASSERT_EQUAL_PTR(expected, actual) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING(expected, actual) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, NULL) + +/* Arrays */ +#define TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, NULL) + +/* Arrays Compared To Single Value */ +#define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, NULL) + +/* Floating Point (If Enabled) */ +#define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_FLOAT(expected, actual) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, NULL) + +/* Double (If Enabled) */ +#define TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_DOUBLE(expected, actual) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL) +#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL) + +/*------------------------------------------------------- + * Test Asserts (with additional messages) + *-------------------------------------------------------*/ + +/* Boolean */ +#define TEST_ASSERT_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) +#define TEST_ASSERT_TRUE_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) +#define TEST_ASSERT_UNLESS_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) +#define TEST_ASSERT_FALSE_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) +#define TEST_ASSERT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, (message)) +#define TEST_ASSERT_NOT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, (message)) + +/* Integers (of all sizes) */ +#define TEST_ASSERT_EQUAL_INT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_BITS_MESSAGE(mask, expected, actual, message) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_BITS_HIGH_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) +#define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, (message)) +#define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) +#define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, (message)) + +/* Integer Greater Than/ Less Than (of all sizes) */ +#define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, (message)) + +#define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message)) + +#define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) + +#define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message)) + +/* Integer Ranges (of all sizes) */ +#define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_INT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, (message)) + +/* Structs and Strings */ +#define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MEMORY_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, (message)) + +/* Arrays */ +#define TEST_ASSERT_EQUAL_INT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_INT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_HEX64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, (message)) + +/* Arrays Compared To Single Value*/ +#define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_INT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_HEX64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, (message)) + +/* Floating Point (If Enabled) */ +#define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_FLOAT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_FLOAT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_FLOAT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, (message)) + +/* Double (If Enabled) */ +#define TEST_ASSERT_DOUBLE_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_DOUBLE_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_DOUBLE_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message)) +#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, (message)) + +/* end of UNITY_FRAMEWORK_H */ +#ifdef __cplusplus +} +#endif +#endif diff --git a/tools/sdk/include/json/tests/unity/src/unity_internals.h b/tools/sdk/include/json/tests/unity/src/unity_internals.h new file mode 100644 index 00000000000..f78cebace4e --- /dev/null +++ b/tools/sdk/include/json/tests/unity/src/unity_internals.h @@ -0,0 +1,870 @@ +/* ========================================== + Unity Project - A Test Framework for C + Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + [Released under MIT License. Please refer to license.txt for details] +========================================== */ + +#ifndef UNITY_INTERNALS_H +#define UNITY_INTERNALS_H + +#include "../examples/unity_config.h" + +#ifndef UNITY_EXCLUDE_SETJMP_H +#include +#endif + +#ifndef UNITY_EXCLUDE_MATH_H +#include +#endif + +/* Unity Attempts to Auto-Detect Integer Types + * Attempt 1: UINT_MAX, ULONG_MAX in , or default to 32 bits + * Attempt 2: UINTPTR_MAX in , or default to same size as long + * The user may override any of these derived constants: + * UNITY_INT_WIDTH, UNITY_LONG_WIDTH, UNITY_POINTER_WIDTH */ +#ifndef UNITY_EXCLUDE_STDINT_H +#include +#endif + +#ifndef UNITY_EXCLUDE_LIMITS_H +#include +#endif + +/*------------------------------------------------------- + * Guess Widths If Not Specified + *-------------------------------------------------------*/ + +/* Determine the size of an int, if not already specified. + * We cannot use sizeof(int), because it is not yet defined + * at this stage in the translation of the C program. + * Therefore, infer it from UINT_MAX if possible. */ +#ifndef UNITY_INT_WIDTH + #ifdef UINT_MAX + #if (UINT_MAX == 0xFFFF) + #define UNITY_INT_WIDTH (16) + #elif (UINT_MAX == 0xFFFFFFFF) + #define UNITY_INT_WIDTH (32) + #elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF) + #define UNITY_INT_WIDTH (64) + #endif + #else /* Set to default */ + #define UNITY_INT_WIDTH (32) + #endif /* UINT_MAX */ +#endif + +/* Determine the size of a long, if not already specified. */ +#ifndef UNITY_LONG_WIDTH + #ifdef ULONG_MAX + #if (ULONG_MAX == 0xFFFF) + #define UNITY_LONG_WIDTH (16) + #elif (ULONG_MAX == 0xFFFFFFFF) + #define UNITY_LONG_WIDTH (32) + #elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF) + #define UNITY_LONG_WIDTH (64) + #endif + #else /* Set to default */ + #define UNITY_LONG_WIDTH (32) + #endif /* ULONG_MAX */ +#endif + +/* Determine the size of a pointer, if not already specified. */ +#ifndef UNITY_POINTER_WIDTH + #ifdef UINTPTR_MAX + #if (UINTPTR_MAX <= 0xFFFF) + #define UNITY_POINTER_WIDTH (16) + #elif (UINTPTR_MAX <= 0xFFFFFFFF) + #define UNITY_POINTER_WIDTH (32) + #elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF) + #define UNITY_POINTER_WIDTH (64) + #endif + #else /* Set to default */ + #define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH + #endif /* UINTPTR_MAX */ +#endif + +/*------------------------------------------------------- + * Int Support (Define types based on detected sizes) + *-------------------------------------------------------*/ + +#if (UNITY_INT_WIDTH == 32) + typedef unsigned char UNITY_UINT8; + typedef unsigned short UNITY_UINT16; + typedef unsigned int UNITY_UINT32; + typedef signed char UNITY_INT8; + typedef signed short UNITY_INT16; + typedef signed int UNITY_INT32; +#elif (UNITY_INT_WIDTH == 16) + typedef unsigned char UNITY_UINT8; + typedef unsigned int UNITY_UINT16; + typedef unsigned long UNITY_UINT32; + typedef signed char UNITY_INT8; + typedef signed int UNITY_INT16; + typedef signed long UNITY_INT32; +#else + #error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported) +#endif + +/*------------------------------------------------------- + * 64-bit Support + *-------------------------------------------------------*/ + +#ifndef UNITY_SUPPORT_64 + #if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64 + #define UNITY_SUPPORT_64 + #endif +#endif + +#ifndef UNITY_SUPPORT_64 + /* No 64-bit Support */ + typedef UNITY_UINT32 UNITY_UINT; + typedef UNITY_INT32 UNITY_INT; +#else + + /* 64-bit Support */ + #if (UNITY_LONG_WIDTH == 32) + typedef unsigned long long UNITY_UINT64; + typedef signed long long UNITY_INT64; + #elif (UNITY_LONG_WIDTH == 64) + typedef unsigned long UNITY_UINT64; + typedef signed long UNITY_INT64; + #else + #error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported) + #endif + typedef UNITY_UINT64 UNITY_UINT; + typedef UNITY_INT64 UNITY_INT; + +#endif + +/*------------------------------------------------------- + * Pointer Support + *-------------------------------------------------------*/ + +#if (UNITY_POINTER_WIDTH == 32) +#define UNITY_PTR_TO_INT UNITY_INT32 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 +#elif (UNITY_POINTER_WIDTH == 64) +#define UNITY_PTR_TO_INT UNITY_INT64 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 +#elif (UNITY_POINTER_WIDTH == 16) +#define UNITY_PTR_TO_INT UNITY_INT16 +#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 +#else + #error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) +#endif + +#ifndef UNITY_PTR_ATTRIBUTE +#define UNITY_PTR_ATTRIBUTE +#endif + +#ifndef UNITY_INTERNAL_PTR +#define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void* +#endif + +/*------------------------------------------------------- + * Float Support + *-------------------------------------------------------*/ + +#ifdef UNITY_EXCLUDE_FLOAT + +/* No Floating Point Support */ +#ifndef UNITY_EXCLUDE_DOUBLE +#define UNITY_EXCLUDE_DOUBLE /* Remove double when excluding float support */ +#endif +#ifndef UNITY_EXCLUDE_FLOAT_PRINT +#define UNITY_EXCLUDE_FLOAT_PRINT +#endif + +#else + +/* Floating Point Support */ +#ifndef UNITY_FLOAT_PRECISION +#define UNITY_FLOAT_PRECISION (0.00001f) +#endif +#ifndef UNITY_FLOAT_TYPE +#define UNITY_FLOAT_TYPE float +#endif +typedef UNITY_FLOAT_TYPE UNITY_FLOAT; + +/* isinf & isnan macros should be provided by math.h */ +#ifndef isinf +/* The value of Inf - Inf is NaN */ +#define isinf(n) (isnan((n) - (n)) && !isnan(n)) +#endif + +#ifndef isnan +/* NaN is the only floating point value that does NOT equal itself. + * Therefore if n != n, then it is NaN. */ +#define isnan(n) ((n != n) ? 1 : 0) +#endif + +#endif + +/*------------------------------------------------------- + * Double Float Support + *-------------------------------------------------------*/ + +/* unlike float, we DON'T include by default */ +#if defined(UNITY_EXCLUDE_DOUBLE) || !defined(UNITY_INCLUDE_DOUBLE) + + /* No Floating Point Support */ + #ifndef UNITY_EXCLUDE_DOUBLE + #define UNITY_EXCLUDE_DOUBLE + #else + #undef UNITY_INCLUDE_DOUBLE + #endif + + #ifndef UNITY_EXCLUDE_FLOAT + #ifndef UNITY_DOUBLE_TYPE + #define UNITY_DOUBLE_TYPE double + #endif + typedef UNITY_FLOAT UNITY_DOUBLE; + /* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or float */ + #endif + +#else + + /* Double Floating Point Support */ + #ifndef UNITY_DOUBLE_PRECISION + #define UNITY_DOUBLE_PRECISION (1e-12) + #endif + + #ifndef UNITY_DOUBLE_TYPE + #define UNITY_DOUBLE_TYPE double + #endif + typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE; + +#endif + +/*------------------------------------------------------- + * Output Method: stdout (DEFAULT) + *-------------------------------------------------------*/ +#ifndef UNITY_OUTPUT_CHAR +/* Default to using putchar, which is defined in stdio.h */ +#include +#define UNITY_OUTPUT_CHAR(a) (void)putchar(a) +#else + /* If defined as something else, make sure we declare it here so it's ready for use */ + #ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION +extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION; + #endif +#endif + +#ifndef UNITY_OUTPUT_FLUSH +#ifdef UNITY_USE_FLUSH_STDOUT +/* We want to use the stdout flush utility */ +#include +#define UNITY_OUTPUT_FLUSH() (void)fflush(stdout) +#else +/* We've specified nothing, therefore flush should just be ignored */ +#define UNITY_OUTPUT_FLUSH() +#endif +#else +/* We've defined flush as something else, so make sure we declare it here so it's ready for use */ +#ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION +extern void UNITY_OMIT_OUTPUT_FLUSH_HEADER_DECLARATION; +#endif +#endif + +#ifndef UNITY_OUTPUT_FLUSH +#define UNITY_FLUSH_CALL() +#else +#define UNITY_FLUSH_CALL() UNITY_OUTPUT_FLUSH() +#endif + +#ifndef UNITY_PRINT_EOL +#define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n') +#endif + +#ifndef UNITY_OUTPUT_START +#define UNITY_OUTPUT_START() +#endif + +#ifndef UNITY_OUTPUT_COMPLETE +#define UNITY_OUTPUT_COMPLETE() +#endif + +/*------------------------------------------------------- + * Footprint + *-------------------------------------------------------*/ + +#ifndef UNITY_LINE_TYPE +#define UNITY_LINE_TYPE UNITY_UINT +#endif + +#ifndef UNITY_COUNTER_TYPE +#define UNITY_COUNTER_TYPE UNITY_UINT +#endif + +/*------------------------------------------------------- + * Language Features Available + *-------------------------------------------------------*/ +#if !defined(UNITY_WEAK_ATTRIBUTE) && !defined(UNITY_WEAK_PRAGMA) +# if defined(__GNUC__) || defined(__ghs__) /* __GNUC__ includes clang */ +# if !(defined(__WIN32__) && defined(__clang__)) && !defined(__TMS470__) +# define UNITY_WEAK_ATTRIBUTE __attribute__((weak)) +# endif +# endif +#endif + +#ifdef UNITY_NO_WEAK +# undef UNITY_WEAK_ATTRIBUTE +# undef UNITY_WEAK_PRAGMA +#endif + + +/*------------------------------------------------------- + * Internal Structs Needed + *-------------------------------------------------------*/ + +typedef void (*UnityTestFunction)(void); + +#define UNITY_DISPLAY_RANGE_INT (0x10) +#define UNITY_DISPLAY_RANGE_UINT (0x20) +#define UNITY_DISPLAY_RANGE_HEX (0x40) + +typedef enum +{ +UNITY_DISPLAY_STYLE_INT = sizeof(int)+ UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT, +#ifdef UNITY_SUPPORT_64 + UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT, +#endif + +UNITY_DISPLAY_STYLE_UINT = sizeof(unsigned) + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT, +#ifdef UNITY_SUPPORT_64 + UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT, +#endif + + UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX, + UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX, + UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX, +#ifdef UNITY_SUPPORT_64 + UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX, +#endif + + UNITY_DISPLAY_STYLE_UNKNOWN +} UNITY_DISPLAY_STYLE_T; + +typedef enum +{ + UNITY_EQUAL_TO = 1, + UNITY_GREATER_THAN = 2, + UNITY_GREATER_OR_EQUAL = 2 + UNITY_EQUAL_TO, + UNITY_SMALLER_THAN = 4, + UNITY_SMALLER_OR_EQUAL = 4 + UNITY_EQUAL_TO +} UNITY_COMPARISON_T; + +#ifndef UNITY_EXCLUDE_FLOAT +typedef enum UNITY_FLOAT_TRAIT +{ + UNITY_FLOAT_IS_NOT_INF = 0, + UNITY_FLOAT_IS_INF, + UNITY_FLOAT_IS_NOT_NEG_INF, + UNITY_FLOAT_IS_NEG_INF, + UNITY_FLOAT_IS_NOT_NAN, + UNITY_FLOAT_IS_NAN, + UNITY_FLOAT_IS_NOT_DET, + UNITY_FLOAT_IS_DET, + UNITY_FLOAT_INVALID_TRAIT +} UNITY_FLOAT_TRAIT_T; +#endif + +typedef enum +{ + UNITY_ARRAY_TO_VAL = 0, + UNITY_ARRAY_TO_ARRAY +} UNITY_FLAGS_T; + +struct UNITY_STORAGE_T +{ + const char* TestFile; + const char* CurrentTestName; +#ifndef UNITY_EXCLUDE_DETAILS + const char* CurrentDetail1; + const char* CurrentDetail2; +#endif + UNITY_LINE_TYPE CurrentTestLineNumber; + UNITY_COUNTER_TYPE NumberOfTests; + UNITY_COUNTER_TYPE TestFailures; + UNITY_COUNTER_TYPE TestIgnores; + UNITY_COUNTER_TYPE CurrentTestFailed; + UNITY_COUNTER_TYPE CurrentTestIgnored; +#ifndef UNITY_EXCLUDE_SETJMP_H + jmp_buf AbortFrame; +#endif +}; + +extern struct UNITY_STORAGE_T Unity; + +/*------------------------------------------------------- + * Test Suite Management + *-------------------------------------------------------*/ + +void UnityBegin(const char* filename); +int UnityEnd(void); +void UnityConcludeTest(void); +void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum); + +/*------------------------------------------------------- + * Details Support + *-------------------------------------------------------*/ + +#ifdef UNITY_EXCLUDE_DETAILS +#define UNITY_CLR_DETAILS() +#define UNITY_SET_DETAIL(d1) +#define UNITY_SET_DETAILS(d1,d2) +#else +#define UNITY_CLR_DETAILS() { Unity.CurrentDetail1 = 0; Unity.CurrentDetail2 = 0; } +#define UNITY_SET_DETAIL(d1) { Unity.CurrentDetail1 = d1; Unity.CurrentDetail2 = 0; } +#define UNITY_SET_DETAILS(d1,d2) { Unity.CurrentDetail1 = d1; Unity.CurrentDetail2 = d2; } + +#ifndef UNITY_DETAIL1_NAME +#define UNITY_DETAIL1_NAME "Function" +#endif + +#ifndef UNITY_DETAIL2_NAME +#define UNITY_DETAIL2_NAME "Argument" +#endif +#endif + +/*------------------------------------------------------- + * Test Output + *-------------------------------------------------------*/ + +void UnityPrint(const char* string); +void UnityPrintLen(const char* string, const UNITY_UINT32 length); +void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number); +void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style); +void UnityPrintNumber(const UNITY_INT number); +void UnityPrintNumberUnsigned(const UNITY_UINT number); +void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles); + +#ifndef UNITY_EXCLUDE_FLOAT_PRINT +void UnityPrintFloat(const UNITY_DOUBLE input_number); +#endif + +/*------------------------------------------------------- + * Test Assertion Functions + *------------------------------------------------------- + * Use the macros below this section instead of calling + * these directly. The macros have a consistent naming + * convention and will pull in file and line information + * for you. */ + +void UnityAssertEqualNumber(const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); + +void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, + const UNITY_INT actual, + const UNITY_COMPARISON_T compare, + const char *msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); + +void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags); + +void UnityAssertBits(const UNITY_INT mask, + const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualString(const char* expected, + const char* actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualStringLen(const char* expected, + const char* actual, + const UNITY_UINT32 length, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualStringArray( UNITY_INTERNAL_PTR expected, + const char** actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertEqualMemory( UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 length, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertNumbersWithin(const UNITY_UINT delta, + const UNITY_INT expected, + const UNITY_INT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style); + +void UnityFail(const char* message, const UNITY_LINE_TYPE line); + +void UnityIgnore(const char* message, const UNITY_LINE_TYPE line); + +#ifndef UNITY_EXCLUDE_FLOAT +void UnityAssertFloatsWithin(const UNITY_FLOAT delta, + const UNITY_FLOAT expected, + const UNITY_FLOAT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, + UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertFloatSpecial(const UNITY_FLOAT actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style); +#endif + +#ifndef UNITY_EXCLUDE_DOUBLE +void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, + const UNITY_DOUBLE expected, + const UNITY_DOUBLE actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber); + +void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, + UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLAGS_T flags); + +void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_FLOAT_TRAIT_T style); +#endif + +/*------------------------------------------------------- + * Helpers + *-------------------------------------------------------*/ + +UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size); +#ifndef UNITY_EXCLUDE_FLOAT +UNITY_INTERNAL_PTR UnityFloatToPtr(const float num); +#endif +#ifndef UNITY_EXCLUDE_DOUBLE +UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num); +#endif + +/*------------------------------------------------------- + * Error Strings We Might Need + *-------------------------------------------------------*/ + +extern const char UnityStrErrFloat[]; +extern const char UnityStrErrDouble[]; +extern const char UnityStrErr64[]; + +/*------------------------------------------------------- + * Test Running Macros + *-------------------------------------------------------*/ + +#ifndef UNITY_EXCLUDE_SETJMP_H +#define TEST_PROTECT() (setjmp(Unity.AbortFrame) == 0) +#define TEST_ABORT() longjmp(Unity.AbortFrame, 1) +#else +#define TEST_PROTECT() 1 +#define TEST_ABORT() return +#endif + +/* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */ +#ifndef RUN_TEST +#ifdef __STDC_VERSION__ +#if __STDC_VERSION__ >= 199901L +#define RUN_TEST(...) UnityDefaultTestRun(RUN_TEST_FIRST(__VA_ARGS__), RUN_TEST_SECOND(__VA_ARGS__)) +#define RUN_TEST_FIRST(...) RUN_TEST_FIRST_HELPER(__VA_ARGS__, throwaway) +#define RUN_TEST_FIRST_HELPER(first, ...) (first), #first +#define RUN_TEST_SECOND(...) RUN_TEST_SECOND_HELPER(__VA_ARGS__, __LINE__, throwaway) +#define RUN_TEST_SECOND_HELPER(first, second, ...) (second) +#endif +#endif +#endif + +/* If we can't do the tricky version, we'll just have to require them to always include the line number */ +#ifndef RUN_TEST +#ifdef CMOCK +#define RUN_TEST(func, num) UnityDefaultTestRun(func, #func, num) +#else +#define RUN_TEST(func) UnityDefaultTestRun(func, #func, __LINE__) +#endif +#endif + +#define TEST_LINE_NUM (Unity.CurrentTestLineNumber) +#define TEST_IS_IGNORED (Unity.CurrentTestIgnored) +#define UNITY_NEW_TEST(a) \ + Unity.CurrentTestName = (a); \ + Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \ + Unity.NumberOfTests++; + +#ifndef UNITY_BEGIN +#define UNITY_BEGIN() UnityBegin(__FILE__) +#endif + +#ifndef UNITY_END +#define UNITY_END() UnityEnd() +#endif + +/*----------------------------------------------- + * Command Line Argument Support + *-----------------------------------------------*/ + +#ifdef UNITY_USE_COMMAND_LINE_ARGS +int UnityParseOptions(int argc, char** argv); +int UnityTestMatches(void); +#endif + +/*------------------------------------------------------- + * Basic Fail and Ignore + *-------------------------------------------------------*/ + +#define UNITY_TEST_FAIL(line, message) UnityFail( (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_IGNORE(line, message) UnityIgnore( (message), (UNITY_LINE_TYPE)(line)) + +/*------------------------------------------------------- + * Test Asserts + *-------------------------------------------------------*/ + +#define UNITY_TEST_ASSERT(condition, line, message) if (condition) {} else {UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message));} +#define UNITY_TEST_ASSERT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), (message)) +#define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), (message)) + +#define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line)) + +#define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) +#define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) +#define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) +#define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) +#define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) +#define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) + +#define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER) +#define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, message) UnityAssertEqualStringLen((const char*)(expected), (const char*)(actual), (UNITY_UINT32)(len), (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), 1, (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) + +#define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) + +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) expected, sizeof(int)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) expected, sizeof(unsigned int)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )expected, 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )expected, 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )expected, 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) expected, sizeof(int*)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) + +#ifdef UNITY_SUPPORT_64 +#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#else +#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#endif + +#ifdef UNITY_EXCLUDE_FLOAT +#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) +#else +#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (UNITY_LINE_TYPE)(line), (message)) +#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray((UNITY_FLOAT*)(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray(UnityFloatToPtr(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) +#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) +#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) +#endif + +#ifdef UNITY_EXCLUDE_DOUBLE +#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) +#else +#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)line) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual, (UNITY_LINE_TYPE)(line), message) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)line, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)line, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) +#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) +#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) +#endif + +/* End of UNITY_INTERNALS_H */ +#endif diff --git a/tools/sdk/include/json/tests/unity/test/expectdata/testsample_head1.h b/tools/sdk/include/json/tests/unity/test/expectdata/testsample_head1.h new file mode 100644 index 00000000000..da6b7ab26bb --- /dev/null +++ b/tools/sdk/include/json/tests/unity/test/expectdata/testsample_head1.h @@ -0,0 +1,15 @@ +/* AUTOGENERATED FILE. DO NOT EDIT. */ +#ifndef _TESTSAMPLE_HEAD1_H +#define _TESTSAMPLE_HEAD1_H + +#include "unity.h" +#include "funky.h" +#include "stanky.h" +#include + +void test_TheFirstThingToTest(void); +void test_TheSecondThingToTest(void); +void test_TheThirdThingToTest(void); +void test_TheFourthThingToTest(void); +#endif + diff --git a/tools/sdk/include/json/tests/unity/test/expectdata/testsample_mock_head1.h b/tools/sdk/include/json/tests/unity/test/expectdata/testsample_mock_head1.h new file mode 100644 index 00000000000..30c509ad077 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/test/expectdata/testsample_mock_head1.h @@ -0,0 +1,13 @@ +/* AUTOGENERATED FILE. DO NOT EDIT. */ +#ifndef _TESTSAMPLE_MOCK_HEAD1_H +#define _TESTSAMPLE_MOCK_HEAD1_H + +#include "unity.h" +#include "cmock.h" +#include "funky.h" +#include + +void test_TheFirstThingToTest(void); +void test_TheSecondThingToTest(void); +#endif + diff --git a/tools/sdk/include/json/tests/unity/test/testdata/CException.h b/tools/sdk/include/json/tests/unity/test/testdata/CException.h new file mode 100644 index 00000000000..91ad3e1bf22 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/test/testdata/CException.h @@ -0,0 +1,11 @@ +#ifndef CEXCEPTION_H +#define CEXCEPTION_H + +#define CEXCEPTION_BEING_USED 1 + +#define CEXCEPTION_NONE 0 +#define CEXCEPTION_T int e = 1; (void) +#define Try if (e) +#define Catch(a) if (!a) + +#endif //CEXCEPTION_H diff --git a/tools/sdk/include/json/tests/unity/test/testdata/Defs.h b/tools/sdk/include/json/tests/unity/test/testdata/Defs.h new file mode 100644 index 00000000000..d3a90c0d506 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/test/testdata/Defs.h @@ -0,0 +1,8 @@ +#ifndef DEF_H +#define DEF_H + +#define EXTERN_DECL + +extern int CounterSuiteSetup; + +#endif //DEF_H diff --git a/tools/sdk/include/json/tests/unity/test/testdata/cmock.h b/tools/sdk/include/json/tests/unity/test/testdata/cmock.h new file mode 100644 index 00000000000..c6149be1b01 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/test/testdata/cmock.h @@ -0,0 +1,14 @@ +#ifndef CMOCK_H +#define CMOCK_H + +int CMockMemFreeFinalCounter = 0; +int mockMock_Init_Counter = 0; +int mockMock_Verify_Counter = 0; +int mockMock_Destroy_Counter = 0; + +void CMock_Guts_MemFreeFinal(void) { CMockMemFreeFinalCounter++; } +void mockMock_Init(void) { mockMock_Init_Counter++; } +void mockMock_Verify(void) { mockMock_Verify_Counter++; } +void mockMock_Destroy(void) { mockMock_Destroy_Counter++; } + +#endif //CMOCK_H diff --git a/tools/sdk/include/json/tests/unity/test/testdata/mockMock.h b/tools/sdk/include/json/tests/unity/test/testdata/mockMock.h new file mode 100644 index 00000000000..0a2c616f797 --- /dev/null +++ b/tools/sdk/include/json/tests/unity/test/testdata/mockMock.h @@ -0,0 +1,13 @@ +#ifndef MOCK_MOCK_H +#define MOCK_MOCK_H + +extern int mockMock_Init_Counter; +extern int mockMock_Verify_Counter; +extern int mockMock_Destroy_Counter; +extern int CMockMemFreeFinalCounter; + +void mockMock_Init(void); +void mockMock_Verify(void); +void mockMock_Destroy(void); + +#endif //MOCK_MOCK_H diff --git a/tools/sdk/include/libsodium/sodium.h b/tools/sdk/include/libsodium/sodium.h new file mode 100644 index 00000000000..d0bb25c8741 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium.h @@ -0,0 +1,68 @@ + +#ifndef sodium_H +#define sodium_H + +#include "sodium/version.h" + +#include "sodium/core.h" +#include "sodium/crypto_aead_aes256gcm.h" +#include "sodium/crypto_aead_chacha20poly1305.h" +#include "sodium/crypto_aead_xchacha20poly1305.h" +#include "sodium/crypto_auth.h" +#include "sodium/crypto_auth_hmacsha256.h" +#include "sodium/crypto_auth_hmacsha512.h" +#include "sodium/crypto_auth_hmacsha512256.h" +#include "sodium/crypto_box.h" +#include "sodium/crypto_box_curve25519xsalsa20poly1305.h" +#include "sodium/crypto_core_hsalsa20.h" +#include "sodium/crypto_core_hchacha20.h" +#include "sodium/crypto_core_salsa20.h" +#include "sodium/crypto_core_salsa2012.h" +#include "sodium/crypto_core_salsa208.h" +#include "sodium/crypto_generichash.h" +#include "sodium/crypto_generichash_blake2b.h" +#include "sodium/crypto_hash.h" +#include "sodium/crypto_hash_sha256.h" +#include "sodium/crypto_hash_sha512.h" +#include "sodium/crypto_kdf.h" +#include "sodium/crypto_kdf_blake2b.h" +#include "sodium/crypto_kx.h" +#include "sodium/crypto_onetimeauth.h" +#include "sodium/crypto_onetimeauth_poly1305.h" +#include "sodium/crypto_pwhash.h" +#include "sodium/crypto_pwhash_argon2i.h" +#include "sodium/crypto_pwhash_scryptsalsa208sha256.h" +#include "sodium/crypto_scalarmult.h" +#include "sodium/crypto_scalarmult_curve25519.h" +#include "sodium/crypto_secretbox.h" +#include "sodium/crypto_secretbox_xsalsa20poly1305.h" +#include "sodium/crypto_shorthash.h" +#include "sodium/crypto_shorthash_siphash24.h" +#include "sodium/crypto_sign.h" +#include "sodium/crypto_sign_ed25519.h" +#include "sodium/crypto_stream.h" +#include "sodium/crypto_stream_chacha20.h" +#include "sodium/crypto_stream_salsa20.h" +#include "sodium/crypto_stream_xsalsa20.h" +#include "sodium/crypto_verify_16.h" +#include "sodium/crypto_verify_32.h" +#include "sodium/crypto_verify_64.h" +#include "sodium/randombytes.h" +#ifdef __native_client__ +# include "sodium/randombytes_nativeclient.h" +#endif +#include "sodium/randombytes_salsa20_random.h" +#include "sodium/randombytes_sysrandom.h" +#include "sodium/runtime.h" +#include "sodium/utils.h" + +#ifndef SODIUM_LIBRARY_MINIMAL +# include "sodium/crypto_box_curve25519xchacha20poly1305.h" +# include "sodium/crypto_secretbox_xchacha20poly1305.h" +# include "sodium/crypto_stream_aes128ctr.h" +# include "sodium/crypto_stream_salsa2012.h" +# include "sodium/crypto_stream_salsa208.h" +# include "sodium/crypto_stream_xchacha20.h" +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/core.h b/tools/sdk/include/libsodium/sodium/core.h new file mode 100644 index 00000000000..3ca447628e4 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/core.h @@ -0,0 +1,19 @@ + +#ifndef sodium_core_H +#define sodium_core_H + +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +SODIUM_EXPORT +int sodium_init(void) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_aead_aes256gcm.h b/tools/sdk/include/libsodium/sodium/crypto_aead_aes256gcm.h new file mode 100644 index 00000000000..972df54f6ec --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_aead_aes256gcm.h @@ -0,0 +1,145 @@ +#ifndef crypto_aead_aes256gcm_H +#define crypto_aead_aes256gcm_H + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +SODIUM_EXPORT +int crypto_aead_aes256gcm_is_available(void); + +#define crypto_aead_aes256gcm_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_aead_aes256gcm_keybytes(void); + +#define crypto_aead_aes256gcm_NSECBYTES 0U +SODIUM_EXPORT +size_t crypto_aead_aes256gcm_nsecbytes(void); + +#define crypto_aead_aes256gcm_NPUBBYTES 12U +SODIUM_EXPORT +size_t crypto_aead_aes256gcm_npubbytes(void); + +#define crypto_aead_aes256gcm_ABYTES 16U +SODIUM_EXPORT +size_t crypto_aead_aes256gcm_abytes(void); + +typedef CRYPTO_ALIGN(16) unsigned char crypto_aead_aes256gcm_state[512]; + +SODIUM_EXPORT +size_t crypto_aead_aes256gcm_statebytes(void); + +SODIUM_EXPORT +int crypto_aead_aes256gcm_encrypt(unsigned char *c, + unsigned long long *clen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_aes256gcm_decrypt(unsigned char *m, + unsigned long long *mlen_p, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_aead_aes256gcm_encrypt_detached(unsigned char *c, + unsigned char *mac, + unsigned long long *maclen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_aes256gcm_decrypt_detached(unsigned char *m, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *mac, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +/* -- Precomputation interface -- */ + +SODIUM_EXPORT +int crypto_aead_aes256gcm_beforenm(crypto_aead_aes256gcm_state *ctx_, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_aes256gcm_encrypt_afternm(unsigned char *c, + unsigned long long *clen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const crypto_aead_aes256gcm_state *ctx_); + +SODIUM_EXPORT +int crypto_aead_aes256gcm_decrypt_afternm(unsigned char *m, + unsigned long long *mlen_p, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const crypto_aead_aes256gcm_state *ctx_) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_aead_aes256gcm_encrypt_detached_afternm(unsigned char *c, + unsigned char *mac, + unsigned long long *maclen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const crypto_aead_aes256gcm_state *ctx_); + +SODIUM_EXPORT +int crypto_aead_aes256gcm_decrypt_detached_afternm(unsigned char *m, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *mac, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const crypto_aead_aes256gcm_state *ctx_) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +void crypto_aead_aes256gcm_keygen(unsigned char k[crypto_aead_aes256gcm_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_aead_chacha20poly1305.h b/tools/sdk/include/libsodium/sodium/crypto_aead_chacha20poly1305.h new file mode 100644 index 00000000000..0bbc6885934 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_aead_chacha20poly1305.h @@ -0,0 +1,162 @@ +#ifndef crypto_aead_chacha20poly1305_H +#define crypto_aead_chacha20poly1305_H + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +/* -- IETF ChaCha20-Poly1305 construction with a 96-bit nonce and a 32-bit internal counter -- */ + +#define crypto_aead_chacha20poly1305_ietf_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_aead_chacha20poly1305_ietf_keybytes(void); + +#define crypto_aead_chacha20poly1305_ietf_NSECBYTES 0U +SODIUM_EXPORT +size_t crypto_aead_chacha20poly1305_ietf_nsecbytes(void); + +#define crypto_aead_chacha20poly1305_ietf_NPUBBYTES 12U + +SODIUM_EXPORT +size_t crypto_aead_chacha20poly1305_ietf_npubbytes(void); + +#define crypto_aead_chacha20poly1305_ietf_ABYTES 16U +SODIUM_EXPORT +size_t crypto_aead_chacha20poly1305_ietf_abytes(void); + +SODIUM_EXPORT +int crypto_aead_chacha20poly1305_ietf_encrypt(unsigned char *c, + unsigned long long *clen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_chacha20poly1305_ietf_decrypt(unsigned char *m, + unsigned long long *mlen_p, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_aead_chacha20poly1305_ietf_encrypt_detached(unsigned char *c, + unsigned char *mac, + unsigned long long *maclen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_chacha20poly1305_ietf_decrypt_detached(unsigned char *m, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *mac, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +void crypto_aead_chacha20poly1305_ietf_keygen(unsigned char k[crypto_aead_chacha20poly1305_ietf_KEYBYTES]); + +/* -- Original ChaCha20-Poly1305 construction with a 64-bit nonce and a 64-bit internal counter -- */ + +#define crypto_aead_chacha20poly1305_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_aead_chacha20poly1305_keybytes(void); + +#define crypto_aead_chacha20poly1305_NSECBYTES 0U +SODIUM_EXPORT +size_t crypto_aead_chacha20poly1305_nsecbytes(void); + +#define crypto_aead_chacha20poly1305_NPUBBYTES 8U +SODIUM_EXPORT +size_t crypto_aead_chacha20poly1305_npubbytes(void); + +#define crypto_aead_chacha20poly1305_ABYTES 16U +SODIUM_EXPORT +size_t crypto_aead_chacha20poly1305_abytes(void); + +SODIUM_EXPORT +int crypto_aead_chacha20poly1305_encrypt(unsigned char *c, + unsigned long long *clen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_chacha20poly1305_decrypt(unsigned char *m, + unsigned long long *mlen_p, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_aead_chacha20poly1305_encrypt_detached(unsigned char *c, + unsigned char *mac, + unsigned long long *maclen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_chacha20poly1305_decrypt_detached(unsigned char *m, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *mac, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +void crypto_aead_chacha20poly1305_keygen(unsigned char k[crypto_aead_chacha20poly1305_KEYBYTES]); + +/* Aliases */ + +#define crypto_aead_chacha20poly1305_IETF_KEYBYTES crypto_aead_chacha20poly1305_ietf_KEYBYTES +#define crypto_aead_chacha20poly1305_IETF_NSECBYTES crypto_aead_chacha20poly1305_ietf_NSECBYTES +#define crypto_aead_chacha20poly1305_IETF_NPUBBYTES crypto_aead_chacha20poly1305_ietf_NPUBBYTES +#define crypto_aead_chacha20poly1305_IETF_ABYTES crypto_aead_chacha20poly1305_ietf_ABYTES + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_aead_xchacha20poly1305.h b/tools/sdk/include/libsodium/sodium/crypto_aead_xchacha20poly1305.h new file mode 100644 index 00000000000..f863ce88ca2 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_aead_xchacha20poly1305.h @@ -0,0 +1,91 @@ +#ifndef crypto_aead_xchacha20poly1305_H +#define crypto_aead_xchacha20poly1305_H + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_aead_xchacha20poly1305_ietf_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_aead_xchacha20poly1305_ietf_keybytes(void); + +#define crypto_aead_xchacha20poly1305_ietf_NSECBYTES 0U +SODIUM_EXPORT +size_t crypto_aead_xchacha20poly1305_ietf_nsecbytes(void); + +#define crypto_aead_xchacha20poly1305_ietf_NPUBBYTES 24U +SODIUM_EXPORT +size_t crypto_aead_xchacha20poly1305_ietf_npubbytes(void); + +#define crypto_aead_xchacha20poly1305_ietf_ABYTES 16U +SODIUM_EXPORT +size_t crypto_aead_xchacha20poly1305_ietf_abytes(void); + +SODIUM_EXPORT +int crypto_aead_xchacha20poly1305_ietf_encrypt(unsigned char *c, + unsigned long long *clen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_xchacha20poly1305_ietf_decrypt(unsigned char *m, + unsigned long long *mlen_p, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_aead_xchacha20poly1305_ietf_encrypt_detached(unsigned char *c, + unsigned char *mac, + unsigned long long *maclen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *nsec, + const unsigned char *npub, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_aead_xchacha20poly1305_ietf_decrypt_detached(unsigned char *m, + unsigned char *nsec, + const unsigned char *c, + unsigned long long clen, + const unsigned char *mac, + const unsigned char *ad, + unsigned long long adlen, + const unsigned char *npub, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +void crypto_aead_xchacha20poly1305_ietf_keygen(unsigned char k[crypto_aead_xchacha20poly1305_ietf_KEYBYTES]); + +/* Aliases */ + +#define crypto_aead_xchacha20poly1305_IETF_KEYBYTES crypto_aead_xchacha20poly1305_ietf_KEYBYTES +#define crypto_aead_xchacha20poly1305_IETF_NSECBYTES crypto_aead_xchacha20poly1305_ietf_NSECBYTES +#define crypto_aead_xchacha20poly1305_IETF_NPUBBYTES crypto_aead_xchacha20poly1305_ietf_NPUBBYTES +#define crypto_aead_xchacha20poly1305_IETF_ABYTES crypto_aead_xchacha20poly1305_ietf_ABYTES + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_auth.h b/tools/sdk/include/libsodium/sodium/crypto_auth.h new file mode 100644 index 00000000000..7174e7bcedd --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_auth.h @@ -0,0 +1,44 @@ +#ifndef crypto_auth_H +#define crypto_auth_H + +#include + +#include "crypto_auth_hmacsha512256.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_auth_BYTES crypto_auth_hmacsha512256_BYTES +SODIUM_EXPORT +size_t crypto_auth_bytes(void); + +#define crypto_auth_KEYBYTES crypto_auth_hmacsha512256_KEYBYTES +SODIUM_EXPORT +size_t crypto_auth_keybytes(void); + +#define crypto_auth_PRIMITIVE "hmacsha512256" +SODIUM_EXPORT +const char *crypto_auth_primitive(void); + +SODIUM_EXPORT +int crypto_auth(unsigned char *out, const unsigned char *in, + unsigned long long inlen, const unsigned char *k); + +SODIUM_EXPORT +int crypto_auth_verify(const unsigned char *h, const unsigned char *in, + unsigned long long inlen, const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +void crypto_auth_keygen(unsigned char k[crypto_auth_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha256.h b/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha256.h new file mode 100644 index 00000000000..deec5266e68 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha256.h @@ -0,0 +1,68 @@ +#ifndef crypto_auth_hmacsha256_H +#define crypto_auth_hmacsha256_H + +#include +#include "crypto_hash_sha256.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_auth_hmacsha256_BYTES 32U +SODIUM_EXPORT +size_t crypto_auth_hmacsha256_bytes(void); + +#define crypto_auth_hmacsha256_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_auth_hmacsha256_keybytes(void); + +SODIUM_EXPORT +int crypto_auth_hmacsha256(unsigned char *out, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_auth_hmacsha256_verify(const unsigned char *h, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +/* ------------------------------------------------------------------------- */ + +typedef struct crypto_auth_hmacsha256_state { + crypto_hash_sha256_state ictx; + crypto_hash_sha256_state octx; +} crypto_auth_hmacsha256_state; + +SODIUM_EXPORT +size_t crypto_auth_hmacsha256_statebytes(void); + +SODIUM_EXPORT +int crypto_auth_hmacsha256_init(crypto_auth_hmacsha256_state *state, + const unsigned char *key, + size_t keylen); + +SODIUM_EXPORT +int crypto_auth_hmacsha256_update(crypto_auth_hmacsha256_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_auth_hmacsha256_final(crypto_auth_hmacsha256_state *state, + unsigned char *out); + + +SODIUM_EXPORT +void crypto_auth_hmacsha256_keygen(unsigned char k[crypto_auth_hmacsha256_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha512.h b/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha512.h new file mode 100644 index 00000000000..77a55fbc008 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha512.h @@ -0,0 +1,67 @@ +#ifndef crypto_auth_hmacsha512_H +#define crypto_auth_hmacsha512_H + +#include +#include "crypto_hash_sha512.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_auth_hmacsha512_BYTES 64U +SODIUM_EXPORT +size_t crypto_auth_hmacsha512_bytes(void); + +#define crypto_auth_hmacsha512_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_auth_hmacsha512_keybytes(void); + +SODIUM_EXPORT +int crypto_auth_hmacsha512(unsigned char *out, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_auth_hmacsha512_verify(const unsigned char *h, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +/* ------------------------------------------------------------------------- */ + +typedef struct crypto_auth_hmacsha512_state { + crypto_hash_sha512_state ictx; + crypto_hash_sha512_state octx; +} crypto_auth_hmacsha512_state; + +SODIUM_EXPORT +size_t crypto_auth_hmacsha512_statebytes(void); + +SODIUM_EXPORT +int crypto_auth_hmacsha512_init(crypto_auth_hmacsha512_state *state, + const unsigned char *key, + size_t keylen); + +SODIUM_EXPORT +int crypto_auth_hmacsha512_update(crypto_auth_hmacsha512_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_auth_hmacsha512_final(crypto_auth_hmacsha512_state *state, + unsigned char *out); + +SODIUM_EXPORT +void crypto_auth_hmacsha512_keygen(unsigned char k[crypto_auth_hmacsha512_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha512256.h b/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha512256.h new file mode 100644 index 00000000000..4842f3debc7 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_auth_hmacsha512256.h @@ -0,0 +1,62 @@ +#ifndef crypto_auth_hmacsha512256_H +#define crypto_auth_hmacsha512256_H + +#include +#include "crypto_auth_hmacsha512.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_auth_hmacsha512256_BYTES 32U +SODIUM_EXPORT +size_t crypto_auth_hmacsha512256_bytes(void); + +#define crypto_auth_hmacsha512256_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_auth_hmacsha512256_keybytes(void); + +SODIUM_EXPORT +int crypto_auth_hmacsha512256(unsigned char *out, const unsigned char *in, + unsigned long long inlen,const unsigned char *k); + +SODIUM_EXPORT +int crypto_auth_hmacsha512256_verify(const unsigned char *h, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +/* ------------------------------------------------------------------------- */ + +typedef crypto_auth_hmacsha512_state crypto_auth_hmacsha512256_state; + +SODIUM_EXPORT +size_t crypto_auth_hmacsha512256_statebytes(void); + +SODIUM_EXPORT +int crypto_auth_hmacsha512256_init(crypto_auth_hmacsha512256_state *state, + const unsigned char *key, + size_t keylen); + +SODIUM_EXPORT +int crypto_auth_hmacsha512256_update(crypto_auth_hmacsha512256_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_auth_hmacsha512256_final(crypto_auth_hmacsha512256_state *state, + unsigned char *out); + +SODIUM_EXPORT +void crypto_auth_hmacsha512256_keygen(unsigned char k[crypto_auth_hmacsha512256_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_box.h b/tools/sdk/include/libsodium/sodium/crypto_box.h new file mode 100644 index 00000000000..614cd1e0ac1 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_box.h @@ -0,0 +1,169 @@ +#ifndef crypto_box_H +#define crypto_box_H + +/* + * THREAD SAFETY: crypto_box_keypair() is thread-safe, + * provided that sodium_init() was called before. + * + * Other functions are always thread-safe. + */ + +#include + +#include "crypto_box_curve25519xsalsa20poly1305.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_box_SEEDBYTES crypto_box_curve25519xsalsa20poly1305_SEEDBYTES +SODIUM_EXPORT +size_t crypto_box_seedbytes(void); + +#define crypto_box_PUBLICKEYBYTES crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES +SODIUM_EXPORT +size_t crypto_box_publickeybytes(void); + +#define crypto_box_SECRETKEYBYTES crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES +SODIUM_EXPORT +size_t crypto_box_secretkeybytes(void); + +#define crypto_box_NONCEBYTES crypto_box_curve25519xsalsa20poly1305_NONCEBYTES +SODIUM_EXPORT +size_t crypto_box_noncebytes(void); + +#define crypto_box_MACBYTES crypto_box_curve25519xsalsa20poly1305_MACBYTES +SODIUM_EXPORT +size_t crypto_box_macbytes(void); + +#define crypto_box_PRIMITIVE "curve25519xsalsa20poly1305" +SODIUM_EXPORT +const char *crypto_box_primitive(void); + +SODIUM_EXPORT +int crypto_box_seed_keypair(unsigned char *pk, unsigned char *sk, + const unsigned char *seed); + +SODIUM_EXPORT +int crypto_box_keypair(unsigned char *pk, unsigned char *sk); + +SODIUM_EXPORT +int crypto_box_easy(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *pk, const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_open_easy(unsigned char *m, const unsigned char *c, + unsigned long long clen, const unsigned char *n, + const unsigned char *pk, const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_detached(unsigned char *c, unsigned char *mac, + const unsigned char *m, unsigned long long mlen, + const unsigned char *n, const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_open_detached(unsigned char *m, const unsigned char *c, + const unsigned char *mac, + unsigned long long clen, + const unsigned char *n, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +/* -- Precomputation interface -- */ + +#define crypto_box_BEFORENMBYTES crypto_box_curve25519xsalsa20poly1305_BEFORENMBYTES +SODIUM_EXPORT +size_t crypto_box_beforenmbytes(void); + +SODIUM_EXPORT +int crypto_box_beforenm(unsigned char *k, const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_easy_afternm(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_box_open_easy_afternm(unsigned char *m, const unsigned char *c, + unsigned long long clen, const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_detached_afternm(unsigned char *c, unsigned char *mac, + const unsigned char *m, unsigned long long mlen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_box_open_detached_afternm(unsigned char *m, const unsigned char *c, + const unsigned char *mac, + unsigned long long clen, const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +/* -- Ephemeral SK interface -- */ + +#define crypto_box_SEALBYTES (crypto_box_PUBLICKEYBYTES + crypto_box_MACBYTES) +SODIUM_EXPORT +size_t crypto_box_sealbytes(void); + +SODIUM_EXPORT +int crypto_box_seal(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *pk); + +SODIUM_EXPORT +int crypto_box_seal_open(unsigned char *m, const unsigned char *c, + unsigned long long clen, + const unsigned char *pk, const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +/* -- NaCl compatibility interface ; Requires padding -- */ + +#define crypto_box_ZEROBYTES crypto_box_curve25519xsalsa20poly1305_ZEROBYTES +SODIUM_EXPORT +size_t crypto_box_zerobytes(void); + +#define crypto_box_BOXZEROBYTES crypto_box_curve25519xsalsa20poly1305_BOXZEROBYTES +SODIUM_EXPORT +size_t crypto_box_boxzerobytes(void); + +SODIUM_EXPORT +int crypto_box(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *pk, const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_open(unsigned char *m, const unsigned char *c, + unsigned long long clen, const unsigned char *n, + const unsigned char *pk, const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_afternm(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_box_open_afternm(unsigned char *m, const unsigned char *c, + unsigned long long clen, const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_box_curve25519xchacha20poly1305.h b/tools/sdk/include/libsodium/sodium/crypto_box_curve25519xchacha20poly1305.h new file mode 100644 index 00000000000..29c9b255202 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_box_curve25519xchacha20poly1305.h @@ -0,0 +1,130 @@ + +#ifndef crypto_box_curve25519xchacha20poly1305_H +#define crypto_box_curve25519xchacha20poly1305_H + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_box_curve25519xchacha20poly1305_SEEDBYTES 32U +SODIUM_EXPORT +size_t crypto_box_curve25519xchacha20poly1305_seedbytes(void); + +#define crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES 32U +SODIUM_EXPORT +size_t crypto_box_curve25519xchacha20poly1305_publickeybytes(void); + +#define crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES 32U +SODIUM_EXPORT +size_t crypto_box_curve25519xchacha20poly1305_secretkeybytes(void); + +#define crypto_box_curve25519xchacha20poly1305_BEFORENMBYTES 32U +SODIUM_EXPORT +size_t crypto_box_curve25519xchacha20poly1305_beforenmbytes(void); + +#define crypto_box_curve25519xchacha20poly1305_NONCEBYTES 24U +SODIUM_EXPORT +size_t crypto_box_curve25519xchacha20poly1305_noncebytes(void); + +#define crypto_box_curve25519xchacha20poly1305_MACBYTES 16U +SODIUM_EXPORT +size_t crypto_box_curve25519xchacha20poly1305_macbytes(void); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_seed_keypair(unsigned char *pk, + unsigned char *sk, + const unsigned char *seed); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_keypair(unsigned char *pk, + unsigned char *sk); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_easy(unsigned char *c, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_open_easy(unsigned char *m, + const unsigned char *c, + unsigned long long clen, + const unsigned char *n, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_detached(unsigned char *c, + unsigned char *mac, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_open_detached(unsigned char *m, + const unsigned char *c, + const unsigned char *mac, + unsigned long long clen, + const unsigned char *n, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +/* -- Precomputation interface -- */ + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_beforenm(unsigned char *k, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_easy_afternm(unsigned char *c, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_open_easy_afternm(unsigned char *m, + const unsigned char *c, + unsigned long long clen, + const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_detached_afternm(unsigned char *c, + unsigned char *mac, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_box_curve25519xchacha20poly1305_open_detached_afternm(unsigned char *m, + const unsigned char *c, + const unsigned char *mac, + unsigned long long clen, + const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_box_curve25519xsalsa20poly1305.h b/tools/sdk/include/libsodium/sodium/crypto_box_curve25519xsalsa20poly1305.h new file mode 100644 index 00000000000..9b5a39c3fa4 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_box_curve25519xsalsa20poly1305.h @@ -0,0 +1,100 @@ +#ifndef crypto_box_curve25519xsalsa20poly1305_H +#define crypto_box_curve25519xsalsa20poly1305_H + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_box_curve25519xsalsa20poly1305_SEEDBYTES 32U +SODIUM_EXPORT +size_t crypto_box_curve25519xsalsa20poly1305_seedbytes(void); + +#define crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES 32U +SODIUM_EXPORT +size_t crypto_box_curve25519xsalsa20poly1305_publickeybytes(void); + +#define crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES 32U +SODIUM_EXPORT +size_t crypto_box_curve25519xsalsa20poly1305_secretkeybytes(void); + +#define crypto_box_curve25519xsalsa20poly1305_BEFORENMBYTES 32U +SODIUM_EXPORT +size_t crypto_box_curve25519xsalsa20poly1305_beforenmbytes(void); + +#define crypto_box_curve25519xsalsa20poly1305_NONCEBYTES 24U +SODIUM_EXPORT +size_t crypto_box_curve25519xsalsa20poly1305_noncebytes(void); + +#define crypto_box_curve25519xsalsa20poly1305_MACBYTES 16U +SODIUM_EXPORT +size_t crypto_box_curve25519xsalsa20poly1305_macbytes(void); + +#define crypto_box_curve25519xsalsa20poly1305_BOXZEROBYTES 16U +SODIUM_EXPORT +size_t crypto_box_curve25519xsalsa20poly1305_boxzerobytes(void); + +#define crypto_box_curve25519xsalsa20poly1305_ZEROBYTES \ + (crypto_box_curve25519xsalsa20poly1305_BOXZEROBYTES + \ + crypto_box_curve25519xsalsa20poly1305_MACBYTES) +SODIUM_EXPORT +size_t crypto_box_curve25519xsalsa20poly1305_zerobytes(void); + +SODIUM_EXPORT +int crypto_box_curve25519xsalsa20poly1305(unsigned char *c, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_curve25519xsalsa20poly1305_open(unsigned char *m, + const unsigned char *c, + unsigned long long clen, + const unsigned char *n, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_curve25519xsalsa20poly1305_seed_keypair(unsigned char *pk, + unsigned char *sk, + const unsigned char *seed); + +SODIUM_EXPORT +int crypto_box_curve25519xsalsa20poly1305_keypair(unsigned char *pk, + unsigned char *sk); + +SODIUM_EXPORT +int crypto_box_curve25519xsalsa20poly1305_beforenm(unsigned char *k, + const unsigned char *pk, + const unsigned char *sk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_box_curve25519xsalsa20poly1305_afternm(unsigned char *c, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_box_curve25519xsalsa20poly1305_open_afternm(unsigned char *m, + const unsigned char *c, + unsigned long long clen, + const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_core_hchacha20.h b/tools/sdk/include/libsodium/sodium/crypto_core_hchacha20.h new file mode 100644 index 00000000000..05e5670c10e --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_core_hchacha20.h @@ -0,0 +1,35 @@ +#ifndef crypto_core_hchacha20_H +#define crypto_core_hchacha20_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_core_hchacha20_OUTPUTBYTES 32U +SODIUM_EXPORT +size_t crypto_core_hchacha20_outputbytes(void); + +#define crypto_core_hchacha20_INPUTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_hchacha20_inputbytes(void); + +#define crypto_core_hchacha20_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_core_hchacha20_keybytes(void); + +#define crypto_core_hchacha20_CONSTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_hchacha20_constbytes(void); + +SODIUM_EXPORT +int crypto_core_hchacha20(unsigned char *out, const unsigned char *in, + const unsigned char *k, const unsigned char *c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_core_hsalsa20.h b/tools/sdk/include/libsodium/sodium/crypto_core_hsalsa20.h new file mode 100644 index 00000000000..82e475b8f67 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_core_hsalsa20.h @@ -0,0 +1,35 @@ +#ifndef crypto_core_hsalsa20_H +#define crypto_core_hsalsa20_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_core_hsalsa20_OUTPUTBYTES 32U +SODIUM_EXPORT +size_t crypto_core_hsalsa20_outputbytes(void); + +#define crypto_core_hsalsa20_INPUTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_hsalsa20_inputbytes(void); + +#define crypto_core_hsalsa20_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_core_hsalsa20_keybytes(void); + +#define crypto_core_hsalsa20_CONSTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_hsalsa20_constbytes(void); + +SODIUM_EXPORT +int crypto_core_hsalsa20(unsigned char *out, const unsigned char *in, + const unsigned char *k, const unsigned char *c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_core_salsa20.h b/tools/sdk/include/libsodium/sodium/crypto_core_salsa20.h new file mode 100644 index 00000000000..160cc56d2c4 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_core_salsa20.h @@ -0,0 +1,35 @@ +#ifndef crypto_core_salsa20_H +#define crypto_core_salsa20_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_core_salsa20_OUTPUTBYTES 64U +SODIUM_EXPORT +size_t crypto_core_salsa20_outputbytes(void); + +#define crypto_core_salsa20_INPUTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_salsa20_inputbytes(void); + +#define crypto_core_salsa20_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_core_salsa20_keybytes(void); + +#define crypto_core_salsa20_CONSTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_salsa20_constbytes(void); + +SODIUM_EXPORT +int crypto_core_salsa20(unsigned char *out, const unsigned char *in, + const unsigned char *k, const unsigned char *c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_core_salsa2012.h b/tools/sdk/include/libsodium/sodium/crypto_core_salsa2012.h new file mode 100644 index 00000000000..bdd5f9fdbb2 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_core_salsa2012.h @@ -0,0 +1,35 @@ +#ifndef crypto_core_salsa2012_H +#define crypto_core_salsa2012_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_core_salsa2012_OUTPUTBYTES 64U +SODIUM_EXPORT +size_t crypto_core_salsa2012_outputbytes(void); + +#define crypto_core_salsa2012_INPUTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_salsa2012_inputbytes(void); + +#define crypto_core_salsa2012_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_core_salsa2012_keybytes(void); + +#define crypto_core_salsa2012_CONSTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_salsa2012_constbytes(void); + +SODIUM_EXPORT +int crypto_core_salsa2012(unsigned char *out, const unsigned char *in, + const unsigned char *k, const unsigned char *c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_core_salsa208.h b/tools/sdk/include/libsodium/sodium/crypto_core_salsa208.h new file mode 100644 index 00000000000..3c13efa4ef3 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_core_salsa208.h @@ -0,0 +1,35 @@ +#ifndef crypto_core_salsa208_H +#define crypto_core_salsa208_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_core_salsa208_OUTPUTBYTES 64U +SODIUM_EXPORT +size_t crypto_core_salsa208_outputbytes(void); + +#define crypto_core_salsa208_INPUTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_salsa208_inputbytes(void); + +#define crypto_core_salsa208_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_core_salsa208_keybytes(void); + +#define crypto_core_salsa208_CONSTBYTES 16U +SODIUM_EXPORT +size_t crypto_core_salsa208_constbytes(void); + +SODIUM_EXPORT +int crypto_core_salsa208(unsigned char *out, const unsigned char *in, + const unsigned char *k, const unsigned char *c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_generichash.h b/tools/sdk/include/libsodium/sodium/crypto_generichash.h new file mode 100644 index 00000000000..2398fb9dbba --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_generichash.h @@ -0,0 +1,75 @@ +#ifndef crypto_generichash_H +#define crypto_generichash_H + +#include + +#include "crypto_generichash_blake2b.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_generichash_BYTES_MIN crypto_generichash_blake2b_BYTES_MIN +SODIUM_EXPORT +size_t crypto_generichash_bytes_min(void); + +#define crypto_generichash_BYTES_MAX crypto_generichash_blake2b_BYTES_MAX +SODIUM_EXPORT +size_t crypto_generichash_bytes_max(void); + +#define crypto_generichash_BYTES crypto_generichash_blake2b_BYTES +SODIUM_EXPORT +size_t crypto_generichash_bytes(void); + +#define crypto_generichash_KEYBYTES_MIN crypto_generichash_blake2b_KEYBYTES_MIN +SODIUM_EXPORT +size_t crypto_generichash_keybytes_min(void); + +#define crypto_generichash_KEYBYTES_MAX crypto_generichash_blake2b_KEYBYTES_MAX +SODIUM_EXPORT +size_t crypto_generichash_keybytes_max(void); + +#define crypto_generichash_KEYBYTES crypto_generichash_blake2b_KEYBYTES +SODIUM_EXPORT +size_t crypto_generichash_keybytes(void); + +#define crypto_generichash_PRIMITIVE "blake2b" +SODIUM_EXPORT +const char *crypto_generichash_primitive(void); + +typedef crypto_generichash_blake2b_state crypto_generichash_state; + +SODIUM_EXPORT +size_t crypto_generichash_statebytes(void); + +SODIUM_EXPORT +int crypto_generichash(unsigned char *out, size_t outlen, + const unsigned char *in, unsigned long long inlen, + const unsigned char *key, size_t keylen); + +SODIUM_EXPORT +int crypto_generichash_init(crypto_generichash_state *state, + const unsigned char *key, + const size_t keylen, const size_t outlen); + +SODIUM_EXPORT +int crypto_generichash_update(crypto_generichash_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_generichash_final(crypto_generichash_state *state, + unsigned char *out, const size_t outlen); + +SODIUM_EXPORT +void crypto_generichash_keygen(unsigned char k[crypto_generichash_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_generichash_blake2b.h b/tools/sdk/include/libsodium/sodium/crypto_generichash_blake2b.h new file mode 100644 index 00000000000..7b0c0820743 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_generichash_blake2b.h @@ -0,0 +1,121 @@ +#ifndef crypto_generichash_blake2b_H +#define crypto_generichash_blake2b_H + +#include +#include +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#if defined(__IBMC__) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) +# pragma pack(1) +#else +# pragma pack(push, 1) +#endif + +typedef CRYPTO_ALIGN(64) struct crypto_generichash_blake2b_state { + uint64_t h[8]; + uint64_t t[2]; + uint64_t f[2]; + uint8_t buf[2 * 128]; + size_t buflen; + uint8_t last_node; +} crypto_generichash_blake2b_state; + +#if defined(__IBMC__) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) +# pragma pack() +#else +# pragma pack(pop) +#endif + +#define crypto_generichash_blake2b_BYTES_MIN 16U +SODIUM_EXPORT +size_t crypto_generichash_blake2b_bytes_min(void); + +#define crypto_generichash_blake2b_BYTES_MAX 64U +SODIUM_EXPORT +size_t crypto_generichash_blake2b_bytes_max(void); + +#define crypto_generichash_blake2b_BYTES 32U +SODIUM_EXPORT +size_t crypto_generichash_blake2b_bytes(void); + +#define crypto_generichash_blake2b_KEYBYTES_MIN 16U +SODIUM_EXPORT +size_t crypto_generichash_blake2b_keybytes_min(void); + +#define crypto_generichash_blake2b_KEYBYTES_MAX 64U +SODIUM_EXPORT +size_t crypto_generichash_blake2b_keybytes_max(void); + +#define crypto_generichash_blake2b_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_generichash_blake2b_keybytes(void); + +#define crypto_generichash_blake2b_SALTBYTES 16U +SODIUM_EXPORT +size_t crypto_generichash_blake2b_saltbytes(void); + +#define crypto_generichash_blake2b_PERSONALBYTES 16U +SODIUM_EXPORT +size_t crypto_generichash_blake2b_personalbytes(void); + +SODIUM_EXPORT +size_t crypto_generichash_blake2b_statebytes(void); + +SODIUM_EXPORT +int crypto_generichash_blake2b(unsigned char *out, size_t outlen, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *key, size_t keylen); + +SODIUM_EXPORT +int crypto_generichash_blake2b_salt_personal(unsigned char *out, size_t outlen, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *key, + size_t keylen, + const unsigned char *salt, + const unsigned char *personal); + +SODIUM_EXPORT +int crypto_generichash_blake2b_init(crypto_generichash_blake2b_state *state, + const unsigned char *key, + const size_t keylen, const size_t outlen); + +SODIUM_EXPORT +int crypto_generichash_blake2b_init_salt_personal(crypto_generichash_blake2b_state *state, + const unsigned char *key, + const size_t keylen, const size_t outlen, + const unsigned char *salt, + const unsigned char *personal); + +SODIUM_EXPORT +int crypto_generichash_blake2b_update(crypto_generichash_blake2b_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_generichash_blake2b_final(crypto_generichash_blake2b_state *state, + unsigned char *out, + const size_t outlen); + +SODIUM_EXPORT +void crypto_generichash_blake2b_keygen(unsigned char k[crypto_generichash_blake2b_KEYBYTES]); + +/* ------------------------------------------------------------------------- */ + +int _crypto_generichash_blake2b_pick_best_implementation(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_hash.h b/tools/sdk/include/libsodium/sodium/crypto_hash.h new file mode 100644 index 00000000000..302ed5c5ea2 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_hash.h @@ -0,0 +1,40 @@ +#ifndef crypto_hash_H +#define crypto_hash_H + +/* + * WARNING: Unless you absolutely need to use SHA512 for interoperatibility, + * purposes, you might want to consider crypto_generichash() instead. + * Unlike SHA512, crypto_generichash() is not vulnerable to length + * extension attacks. + */ + +#include + +#include "crypto_hash_sha512.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_hash_BYTES crypto_hash_sha512_BYTES +SODIUM_EXPORT +size_t crypto_hash_bytes(void); + +SODIUM_EXPORT +int crypto_hash(unsigned char *out, const unsigned char *in, + unsigned long long inlen); + +#define crypto_hash_PRIMITIVE "sha512" +SODIUM_EXPORT +const char *crypto_hash_primitive(void) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_hash_sha256.h b/tools/sdk/include/libsodium/sodium/crypto_hash_sha256.h new file mode 100644 index 00000000000..f64d16e0e5c --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_hash_sha256.h @@ -0,0 +1,57 @@ +#ifndef crypto_hash_sha256_H +#define crypto_hash_sha256_H + +/* + * WARNING: Unless you absolutely need to use SHA256 for interoperatibility, + * purposes, you might want to consider crypto_generichash() instead. + * Unlike SHA256, crypto_generichash() is not vulnerable to length + * extension attacks. + */ + +#include +#include +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef struct crypto_hash_sha256_state { + uint32_t state[8]; + uint64_t count; + uint8_t buf[64]; +} crypto_hash_sha256_state; + +SODIUM_EXPORT +size_t crypto_hash_sha256_statebytes(void); + +#define crypto_hash_sha256_BYTES 32U +SODIUM_EXPORT +size_t crypto_hash_sha256_bytes(void); + +SODIUM_EXPORT +int crypto_hash_sha256(unsigned char *out, const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_hash_sha256_init(crypto_hash_sha256_state *state); + +SODIUM_EXPORT +int crypto_hash_sha256_update(crypto_hash_sha256_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_hash_sha256_final(crypto_hash_sha256_state *state, + unsigned char *out); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_hash_sha512.h b/tools/sdk/include/libsodium/sodium/crypto_hash_sha512.h new file mode 100644 index 00000000000..6b0330f14fe --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_hash_sha512.h @@ -0,0 +1,57 @@ +#ifndef crypto_hash_sha512_H +#define crypto_hash_sha512_H + +/* + * WARNING: Unless you absolutely need to use SHA512 for interoperatibility, + * purposes, you might want to consider crypto_generichash() instead. + * Unlike SHA512, crypto_generichash() is not vulnerable to length + * extension attacks. + */ + +#include +#include +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef struct crypto_hash_sha512_state { + uint64_t state[8]; + uint64_t count[2]; + uint8_t buf[128]; +} crypto_hash_sha512_state; + +SODIUM_EXPORT +size_t crypto_hash_sha512_statebytes(void); + +#define crypto_hash_sha512_BYTES 64U +SODIUM_EXPORT +size_t crypto_hash_sha512_bytes(void); + +SODIUM_EXPORT +int crypto_hash_sha512(unsigned char *out, const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_hash_sha512_init(crypto_hash_sha512_state *state); + +SODIUM_EXPORT +int crypto_hash_sha512_update(crypto_hash_sha512_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_hash_sha512_final(crypto_hash_sha512_state *state, + unsigned char *out); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_kdf.h b/tools/sdk/include/libsodium/sodium/crypto_kdf.h new file mode 100644 index 00000000000..52e496a7449 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_kdf.h @@ -0,0 +1,51 @@ +#ifndef crypto_kdf_H +#define crypto_kdf_H + +#include +#include + +#include "crypto_kdf_blake2b.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_kdf_BYTES_MIN crypto_kdf_blake2b_BYTES_MIN +SODIUM_EXPORT +size_t crypto_kdf_bytes_min(void); + +#define crypto_kdf_BYTES_MAX crypto_kdf_blake2b_BYTES_MAX +SODIUM_EXPORT +size_t crypto_kdf_bytes_max(void); + +#define crypto_kdf_CONTEXTBYTES crypto_kdf_blake2b_CONTEXTBYTES +SODIUM_EXPORT +size_t crypto_kdf_contextbytes(void); + +#define crypto_kdf_KEYBYTES crypto_kdf_blake2b_KEYBYTES +SODIUM_EXPORT +size_t crypto_kdf_keybytes(void); + +#define crypto_kdf_PRIMITIVE "blake2b" +SODIUM_EXPORT +const char *crypto_kdf_primitive(void) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_kdf_derive_from_key(unsigned char *subkey, size_t subkey_len, + uint64_t subkey_id, + const char ctx[crypto_kdf_CONTEXTBYTES], + const unsigned char key[crypto_kdf_KEYBYTES]); + +SODIUM_EXPORT +void crypto_kdf_keygen(unsigned char k[crypto_kdf_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_kdf_blake2b.h b/tools/sdk/include/libsodium/sodium/crypto_kdf_blake2b.h new file mode 100644 index 00000000000..5480ebe82f1 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_kdf_blake2b.h @@ -0,0 +1,42 @@ +#ifndef crypto_kdf_blake2b_H +#define crypto_kdf_blake2b_H + +#include +#include + +#include "crypto_kdf_blake2b.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_kdf_blake2b_BYTES_MIN 16 +SODIUM_EXPORT +size_t crypto_kdf_blake2b_bytes_min(void); + +#define crypto_kdf_blake2b_BYTES_MAX 64 +SODIUM_EXPORT +size_t crypto_kdf_blake2b_bytes_max(void); + +#define crypto_kdf_blake2b_CONTEXTBYTES 8 +SODIUM_EXPORT +size_t crypto_kdf_blake2b_contextbytes(void); + +#define crypto_kdf_blake2b_KEYBYTES 32 +SODIUM_EXPORT +size_t crypto_kdf_blake2b_keybytes(void); + +SODIUM_EXPORT +int crypto_kdf_blake2b_derive_from_key(unsigned char *subkey, size_t subkey_len, + uint64_t subkey_id, + const char ctx[crypto_kdf_blake2b_CONTEXTBYTES], + const unsigned char key[crypto_kdf_blake2b_KEYBYTES]); +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_kx.h b/tools/sdk/include/libsodium/sodium/crypto_kx.h new file mode 100644 index 00000000000..d1fce90da57 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_kx.h @@ -0,0 +1,64 @@ +#ifndef crypto_kx_H +#define crypto_kx_H + +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_kx_PUBLICKEYBYTES 32 +SODIUM_EXPORT +size_t crypto_kx_publickeybytes(void); + +#define crypto_kx_SECRETKEYBYTES 32 +SODIUM_EXPORT +size_t crypto_kx_secretkeybytes(void); + +#define crypto_kx_SEEDBYTES 32 +SODIUM_EXPORT +size_t crypto_kx_seedbytes(void); + +#define crypto_kx_SESSIONKEYBYTES 32 +SODIUM_EXPORT +size_t crypto_kx_sessionkeybytes(void); + +#define crypto_kx_PRIMITIVE "x25519blake2b" +SODIUM_EXPORT +const char *crypto_kx_primitive(void); + +SODIUM_EXPORT +int crypto_kx_seed_keypair(unsigned char pk[crypto_kx_PUBLICKEYBYTES], + unsigned char sk[crypto_kx_SECRETKEYBYTES], + const unsigned char seed[crypto_kx_SEEDBYTES]); + +SODIUM_EXPORT +int crypto_kx_keypair(unsigned char pk[crypto_kx_PUBLICKEYBYTES], + unsigned char sk[crypto_kx_SECRETKEYBYTES]); + +SODIUM_EXPORT +int crypto_kx_client_session_keys(unsigned char rx[crypto_kx_SESSIONKEYBYTES], + unsigned char tx[crypto_kx_SESSIONKEYBYTES], + const unsigned char client_pk[crypto_kx_PUBLICKEYBYTES], + const unsigned char client_sk[crypto_kx_SECRETKEYBYTES], + const unsigned char server_pk[crypto_kx_PUBLICKEYBYTES]) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_kx_server_session_keys(unsigned char rx[crypto_kx_SESSIONKEYBYTES], + unsigned char tx[crypto_kx_SESSIONKEYBYTES], + const unsigned char server_pk[crypto_kx_PUBLICKEYBYTES], + const unsigned char server_sk[crypto_kx_SECRETKEYBYTES], + const unsigned char client_pk[crypto_kx_PUBLICKEYBYTES]) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_onetimeauth.h b/tools/sdk/include/libsodium/sodium/crypto_onetimeauth.h new file mode 100644 index 00000000000..5951c5b82d3 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_onetimeauth.h @@ -0,0 +1,62 @@ +#ifndef crypto_onetimeauth_H +#define crypto_onetimeauth_H + +#include + +#include "crypto_onetimeauth_poly1305.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef crypto_onetimeauth_poly1305_state crypto_onetimeauth_state; + +SODIUM_EXPORT +size_t crypto_onetimeauth_statebytes(void); + +#define crypto_onetimeauth_BYTES crypto_onetimeauth_poly1305_BYTES +SODIUM_EXPORT +size_t crypto_onetimeauth_bytes(void); + +#define crypto_onetimeauth_KEYBYTES crypto_onetimeauth_poly1305_KEYBYTES +SODIUM_EXPORT +size_t crypto_onetimeauth_keybytes(void); + +#define crypto_onetimeauth_PRIMITIVE "poly1305" +SODIUM_EXPORT +const char *crypto_onetimeauth_primitive(void); + +SODIUM_EXPORT +int crypto_onetimeauth(unsigned char *out, const unsigned char *in, + unsigned long long inlen, const unsigned char *k); + +SODIUM_EXPORT +int crypto_onetimeauth_verify(const unsigned char *h, const unsigned char *in, + unsigned long long inlen, const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_onetimeauth_init(crypto_onetimeauth_state *state, + const unsigned char *key); + +SODIUM_EXPORT +int crypto_onetimeauth_update(crypto_onetimeauth_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_onetimeauth_final(crypto_onetimeauth_state *state, + unsigned char *out); + +SODIUM_EXPORT +void crypto_onetimeauth_keygen(unsigned char k[crypto_onetimeauth_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_onetimeauth_poly1305.h b/tools/sdk/include/libsodium/sodium/crypto_onetimeauth_poly1305.h new file mode 100644 index 00000000000..479e923dccb --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_onetimeauth_poly1305.h @@ -0,0 +1,71 @@ +#ifndef crypto_onetimeauth_poly1305_H +#define crypto_onetimeauth_poly1305_H + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#include +#include +#include + +#include + +#include "export.h" + +typedef CRYPTO_ALIGN(16) struct crypto_onetimeauth_poly1305_state { + unsigned char opaque[256]; +} crypto_onetimeauth_poly1305_state; + +SODIUM_EXPORT +size_t crypto_onetimeauth_poly1305_statebytes(void); + +#define crypto_onetimeauth_poly1305_BYTES 16U +SODIUM_EXPORT +size_t crypto_onetimeauth_poly1305_bytes(void); + +#define crypto_onetimeauth_poly1305_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_onetimeauth_poly1305_keybytes(void); + +SODIUM_EXPORT +int crypto_onetimeauth_poly1305(unsigned char *out, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_onetimeauth_poly1305_verify(const unsigned char *h, + const unsigned char *in, + unsigned long long inlen, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_onetimeauth_poly1305_init(crypto_onetimeauth_poly1305_state *state, + const unsigned char *key); + +SODIUM_EXPORT +int crypto_onetimeauth_poly1305_update(crypto_onetimeauth_poly1305_state *state, + const unsigned char *in, + unsigned long long inlen); + +SODIUM_EXPORT +int crypto_onetimeauth_poly1305_final(crypto_onetimeauth_poly1305_state *state, + unsigned char *out); + +SODIUM_EXPORT +void crypto_onetimeauth_poly1305_keygen(unsigned char k[crypto_onetimeauth_poly1305_KEYBYTES]); + +/* ------------------------------------------------------------------------- */ + +int _crypto_onetimeauth_poly1305_pick_best_implementation(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_pwhash.h b/tools/sdk/include/libsodium/sodium/crypto_pwhash.h new file mode 100644 index 00000000000..56eca0680c1 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_pwhash.h @@ -0,0 +1,121 @@ +#ifndef crypto_pwhash_H +#define crypto_pwhash_H + +#include + +#include "crypto_pwhash_argon2i.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_pwhash_ALG_ARGON2I13 crypto_pwhash_argon2i_ALG_ARGON2I13 +SODIUM_EXPORT +int crypto_pwhash_alg_argon2i13(void); + +#define crypto_pwhash_ALG_DEFAULT crypto_pwhash_ALG_ARGON2I13 +SODIUM_EXPORT +int crypto_pwhash_alg_default(void); + +#define crypto_pwhash_BYTES_MIN crypto_pwhash_argon2i_BYTES_MIN +SODIUM_EXPORT +size_t crypto_pwhash_bytes_min(void); + +#define crypto_pwhash_BYTES_MAX crypto_pwhash_argon2i_BYTES_MAX +SODIUM_EXPORT +size_t crypto_pwhash_bytes_max(void); + +#define crypto_pwhash_PASSWD_MIN crypto_pwhash_argon2i_PASSWD_MIN +SODIUM_EXPORT +size_t crypto_pwhash_passwd_min(void); + +#define crypto_pwhash_PASSWD_MAX crypto_pwhash_argon2i_PASSWD_MAX +SODIUM_EXPORT +size_t crypto_pwhash_passwd_max(void); + +#define crypto_pwhash_SALTBYTES crypto_pwhash_argon2i_SALTBYTES +SODIUM_EXPORT +size_t crypto_pwhash_saltbytes(void); + +#define crypto_pwhash_STRBYTES crypto_pwhash_argon2i_STRBYTES +SODIUM_EXPORT +size_t crypto_pwhash_strbytes(void); + +#define crypto_pwhash_STRPREFIX crypto_pwhash_argon2i_STRPREFIX +SODIUM_EXPORT +const char *crypto_pwhash_strprefix(void); + +#define crypto_pwhash_OPSLIMIT_MIN crypto_pwhash_argon2i_OPSLIMIT_MIN +SODIUM_EXPORT +size_t crypto_pwhash_opslimit_min(void); + +#define crypto_pwhash_OPSLIMIT_MAX crypto_pwhash_argon2i_OPSLIMIT_MAX +SODIUM_EXPORT +size_t crypto_pwhash_opslimit_max(void); + +#define crypto_pwhash_MEMLIMIT_MIN crypto_pwhash_argon2i_MEMLIMIT_MIN +SODIUM_EXPORT +size_t crypto_pwhash_memlimit_min(void); + +#define crypto_pwhash_MEMLIMIT_MAX crypto_pwhash_argon2i_MEMLIMIT_MAX +SODIUM_EXPORT +size_t crypto_pwhash_memlimit_max(void); + +#define crypto_pwhash_OPSLIMIT_INTERACTIVE crypto_pwhash_argon2i_OPSLIMIT_INTERACTIVE +SODIUM_EXPORT +size_t crypto_pwhash_opslimit_interactive(void); + +#define crypto_pwhash_MEMLIMIT_INTERACTIVE crypto_pwhash_argon2i_MEMLIMIT_INTERACTIVE +SODIUM_EXPORT +size_t crypto_pwhash_memlimit_interactive(void); + +#define crypto_pwhash_OPSLIMIT_MODERATE crypto_pwhash_argon2i_OPSLIMIT_MODERATE +SODIUM_EXPORT +size_t crypto_pwhash_opslimit_moderate(void); + +#define crypto_pwhash_MEMLIMIT_MODERATE crypto_pwhash_argon2i_MEMLIMIT_MODERATE +SODIUM_EXPORT +size_t crypto_pwhash_memlimit_moderate(void); + +#define crypto_pwhash_OPSLIMIT_SENSITIVE crypto_pwhash_argon2i_OPSLIMIT_SENSITIVE +SODIUM_EXPORT +size_t crypto_pwhash_opslimit_sensitive(void); + +#define crypto_pwhash_MEMLIMIT_SENSITIVE crypto_pwhash_argon2i_MEMLIMIT_SENSITIVE +SODIUM_EXPORT +size_t crypto_pwhash_memlimit_sensitive(void); + +SODIUM_EXPORT +int crypto_pwhash(unsigned char * const out, unsigned long long outlen, + const char * const passwd, unsigned long long passwdlen, + const unsigned char * const salt, + unsigned long long opslimit, size_t memlimit, int alg) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_pwhash_str(char out[crypto_pwhash_STRBYTES], + const char * const passwd, unsigned long long passwdlen, + unsigned long long opslimit, size_t memlimit) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_pwhash_str_verify(const char str[crypto_pwhash_STRBYTES], + const char * const passwd, + unsigned long long passwdlen) + __attribute__ ((warn_unused_result)); + +#define crypto_pwhash_PRIMITIVE "argon2i" +SODIUM_EXPORT +const char *crypto_pwhash_primitive(void) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/tools/sdk/include/libsodium/sodium/crypto_pwhash_argon2i.h b/tools/sdk/include/libsodium/sodium/crypto_pwhash_argon2i.h new file mode 100644 index 00000000000..d414b939d1f --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_pwhash_argon2i.h @@ -0,0 +1,120 @@ +#ifndef crypto_pwhash_argon2i_H +#define crypto_pwhash_argon2i_H + +#include +#include +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_pwhash_argon2i_ALG_ARGON2I13 1 +SODIUM_EXPORT +int crypto_pwhash_argon2i_alg_argon2i13(void); + +#define crypto_pwhash_argon2i_BYTES_MIN 16U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_bytes_min(void); + +#define crypto_pwhash_argon2i_BYTES_MAX 4294967295U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_bytes_max(void); + +#define crypto_pwhash_argon2i_PASSWD_MIN 0U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_passwd_min(void); + +#define crypto_pwhash_argon2i_PASSWD_MAX 4294967295U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_passwd_max(void); + +#define crypto_pwhash_argon2i_SALTBYTES 16U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_saltbytes(void); + +#define crypto_pwhash_argon2i_STRBYTES 128U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_strbytes(void); + +#define crypto_pwhash_argon2i_STRPREFIX "$argon2i$" +SODIUM_EXPORT +const char *crypto_pwhash_argon2i_strprefix(void); + +#define crypto_pwhash_argon2i_OPSLIMIT_MIN 3U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_opslimit_min(void); + +#define crypto_pwhash_argon2i_OPSLIMIT_MAX 4294967295U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_opslimit_max(void); + +#define crypto_pwhash_argon2i_MEMLIMIT_MIN 1U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_memlimit_min(void); + +#define crypto_pwhash_argon2i_MEMLIMIT_MAX ((SIZE_MAX >= 1ULL << 48) ? 4398046510080U : (SIZE_MAX >= 1ULL << 32) ? 2147483648U : 32768U) +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_memlimit_max(void); + +#define crypto_pwhash_argon2i_OPSLIMIT_INTERACTIVE 4U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_opslimit_interactive(void); + +#define crypto_pwhash_argon2i_MEMLIMIT_INTERACTIVE 33554432U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_memlimit_interactive(void); + +#define crypto_pwhash_argon2i_OPSLIMIT_MODERATE 6U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_opslimit_moderate(void); + +#define crypto_pwhash_argon2i_MEMLIMIT_MODERATE 134217728U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_memlimit_moderate(void); + +#define crypto_pwhash_argon2i_OPSLIMIT_SENSITIVE 8U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_opslimit_sensitive(void); + +#define crypto_pwhash_argon2i_MEMLIMIT_SENSITIVE 536870912U +SODIUM_EXPORT +size_t crypto_pwhash_argon2i_memlimit_sensitive(void); + +SODIUM_EXPORT +int crypto_pwhash_argon2i(unsigned char * const out, + unsigned long long outlen, + const char * const passwd, + unsigned long long passwdlen, + const unsigned char * const salt, + unsigned long long opslimit, size_t memlimit, + int alg) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_pwhash_argon2i_str(char out[crypto_pwhash_argon2i_STRBYTES], + const char * const passwd, + unsigned long long passwdlen, + unsigned long long opslimit, size_t memlimit) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_pwhash_argon2i_str_verify(const char str[crypto_pwhash_argon2i_STRBYTES], + const char * const passwd, + unsigned long long passwdlen) + __attribute__ ((warn_unused_result)); + +/* ------------------------------------------------------------------------- */ + +int _crypto_pwhash_argon2i_pick_best_implementation(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_pwhash_scryptsalsa208sha256.h b/tools/sdk/include/libsodium/sodium/crypto_pwhash_scryptsalsa208sha256.h new file mode 100644 index 00000000000..9f693e540e7 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_pwhash_scryptsalsa208sha256.h @@ -0,0 +1,112 @@ +#ifndef crypto_pwhash_scryptsalsa208sha256_H +#define crypto_pwhash_scryptsalsa208sha256_H + +#include +#include +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_pwhash_scryptsalsa208sha256_BYTES_MIN 16U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_bytes_min(void); + +#define crypto_pwhash_scryptsalsa208sha256_BYTES_MAX SIZE_MAX +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_bytes_max(void); + +#define crypto_pwhash_scryptsalsa208sha256_PASSWD_MIN 0U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_passwd_min(void); + +#define crypto_pwhash_scryptsalsa208sha256_PASSWD_MAX SIZE_MAX +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_passwd_max(void); + +#define crypto_pwhash_scryptsalsa208sha256_SALTBYTES 32U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_saltbytes(void); + +#define crypto_pwhash_scryptsalsa208sha256_STRBYTES 102U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_strbytes(void); + +#define crypto_pwhash_scryptsalsa208sha256_STRPREFIX "$7$" +SODIUM_EXPORT +const char *crypto_pwhash_scryptsalsa208sha256_strprefix(void); + +#define crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN 32768U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_opslimit_min(void); + +#define crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX 4294967295U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_opslimit_max(void); + +#define crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN 16777216U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_memlimit_min(void); + +#define crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX ((SIZE_MAX >= 68719476736U) ? 68719476736U : SIZE_MAX) +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_memlimit_max(void); + +#define crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE 524288U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_opslimit_interactive(void); + +#define crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE 16777216U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_memlimit_interactive(void); + +#define crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE 33554432U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_opslimit_sensitive(void); + +#define crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE 1073741824U +SODIUM_EXPORT +size_t crypto_pwhash_scryptsalsa208sha256_memlimit_sensitive(void); + +SODIUM_EXPORT +int crypto_pwhash_scryptsalsa208sha256(unsigned char * const out, + unsigned long long outlen, + const char * const passwd, + unsigned long long passwdlen, + const unsigned char * const salt, + unsigned long long opslimit, + size_t memlimit) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_pwhash_scryptsalsa208sha256_str(char out[crypto_pwhash_scryptsalsa208sha256_STRBYTES], + const char * const passwd, + unsigned long long passwdlen, + unsigned long long opslimit, + size_t memlimit) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_pwhash_scryptsalsa208sha256_str_verify(const char str[crypto_pwhash_scryptsalsa208sha256_STRBYTES], + const char * const passwd, + unsigned long long passwdlen) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_pwhash_scryptsalsa208sha256_ll(const uint8_t * passwd, size_t passwdlen, + const uint8_t * salt, size_t saltlen, + uint64_t N, uint32_t r, uint32_t p, + uint8_t * buf, size_t buflen) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_scalarmult.h b/tools/sdk/include/libsodium/sodium/crypto_scalarmult.h new file mode 100644 index 00000000000..830c10f6473 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_scalarmult.h @@ -0,0 +1,37 @@ +#ifndef crypto_scalarmult_H +#define crypto_scalarmult_H + +#include + +#include "crypto_scalarmult_curve25519.h" +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_scalarmult_BYTES crypto_scalarmult_curve25519_BYTES +SODIUM_EXPORT +size_t crypto_scalarmult_bytes(void); + +#define crypto_scalarmult_SCALARBYTES crypto_scalarmult_curve25519_SCALARBYTES +SODIUM_EXPORT +size_t crypto_scalarmult_scalarbytes(void); + +#define crypto_scalarmult_PRIMITIVE "curve25519" +SODIUM_EXPORT +const char *crypto_scalarmult_primitive(void); + +SODIUM_EXPORT +int crypto_scalarmult_base(unsigned char *q, const unsigned char *n); + +SODIUM_EXPORT +int crypto_scalarmult(unsigned char *q, const unsigned char *n, + const unsigned char *p) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_scalarmult_curve25519.h b/tools/sdk/include/libsodium/sodium/crypto_scalarmult_curve25519.h new file mode 100644 index 00000000000..953f8923c5e --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_scalarmult_curve25519.h @@ -0,0 +1,36 @@ +#ifndef crypto_scalarmult_curve25519_H +#define crypto_scalarmult_curve25519_H + +#include + +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_scalarmult_curve25519_BYTES 32U +SODIUM_EXPORT +size_t crypto_scalarmult_curve25519_bytes(void); + +#define crypto_scalarmult_curve25519_SCALARBYTES 32U +SODIUM_EXPORT +size_t crypto_scalarmult_curve25519_scalarbytes(void); + +SODIUM_EXPORT +int crypto_scalarmult_curve25519(unsigned char *q, const unsigned char *n, + const unsigned char *p) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_scalarmult_curve25519_base(unsigned char *q, const unsigned char *n); + +/* ------------------------------------------------------------------------- */ + +int _crypto_scalarmult_curve25519_pick_best_implementation(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_secretbox.h b/tools/sdk/include/libsodium/sodium/crypto_secretbox.h new file mode 100644 index 00000000000..9b098200e0b --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_secretbox.h @@ -0,0 +1,87 @@ +#ifndef crypto_secretbox_H +#define crypto_secretbox_H + +#include + +#include "crypto_secretbox_xsalsa20poly1305.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_secretbox_KEYBYTES crypto_secretbox_xsalsa20poly1305_KEYBYTES +SODIUM_EXPORT +size_t crypto_secretbox_keybytes(void); + +#define crypto_secretbox_NONCEBYTES crypto_secretbox_xsalsa20poly1305_NONCEBYTES +SODIUM_EXPORT +size_t crypto_secretbox_noncebytes(void); + +#define crypto_secretbox_MACBYTES crypto_secretbox_xsalsa20poly1305_MACBYTES +SODIUM_EXPORT +size_t crypto_secretbox_macbytes(void); + +#define crypto_secretbox_PRIMITIVE "xsalsa20poly1305" +SODIUM_EXPORT +const char *crypto_secretbox_primitive(void); + +SODIUM_EXPORT +int crypto_secretbox_easy(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_secretbox_open_easy(unsigned char *m, const unsigned char *c, + unsigned long long clen, const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_secretbox_detached(unsigned char *c, unsigned char *mac, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_secretbox_open_detached(unsigned char *m, + const unsigned char *c, + const unsigned char *mac, + unsigned long long clen, + const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +void crypto_secretbox_keygen(unsigned char k[crypto_secretbox_KEYBYTES]); + +/* -- NaCl compatibility interface ; Requires padding -- */ + +#define crypto_secretbox_ZEROBYTES crypto_secretbox_xsalsa20poly1305_ZEROBYTES +SODIUM_EXPORT +size_t crypto_secretbox_zerobytes(void); + +#define crypto_secretbox_BOXZEROBYTES crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES +SODIUM_EXPORT +size_t crypto_secretbox_boxzerobytes(void); + +SODIUM_EXPORT +int crypto_secretbox(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_secretbox_open(unsigned char *m, const unsigned char *c, + unsigned long long clen, const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_secretbox_xchacha20poly1305.h b/tools/sdk/include/libsodium/sodium/crypto_secretbox_xchacha20poly1305.h new file mode 100644 index 00000000000..7a61a09174e --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_secretbox_xchacha20poly1305.h @@ -0,0 +1,62 @@ +#ifndef crypto_secretbox_xchacha20poly1305_H +#define crypto_secretbox_xchacha20poly1305_H + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_secretbox_xchacha20poly1305_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_secretbox_xchacha20poly1305_keybytes(void); + +#define crypto_secretbox_xchacha20poly1305_NONCEBYTES 24U +SODIUM_EXPORT +size_t crypto_secretbox_xchacha20poly1305_noncebytes(void); + +#define crypto_secretbox_xchacha20poly1305_MACBYTES 16U +SODIUM_EXPORT +size_t crypto_secretbox_xchacha20poly1305_macbytes(void); + +SODIUM_EXPORT +int crypto_secretbox_xchacha20poly1305_easy(unsigned char *c, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_secretbox_xchacha20poly1305_open_easy(unsigned char *m, + const unsigned char *c, + unsigned long long clen, + const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_secretbox_xchacha20poly1305_detached(unsigned char *c, + unsigned char *mac, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_secretbox_xchacha20poly1305_open_detached(unsigned char *m, + const unsigned char *c, + const unsigned char *mac, + unsigned long long clen, + const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_secretbox_xsalsa20poly1305.h b/tools/sdk/include/libsodium/sodium/crypto_secretbox_xsalsa20poly1305.h new file mode 100644 index 00000000000..5aa30805d6c --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_secretbox_xsalsa20poly1305.h @@ -0,0 +1,58 @@ +#ifndef crypto_secretbox_xsalsa20poly1305_H +#define crypto_secretbox_xsalsa20poly1305_H + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_secretbox_xsalsa20poly1305_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_secretbox_xsalsa20poly1305_keybytes(void); + +#define crypto_secretbox_xsalsa20poly1305_NONCEBYTES 24U +SODIUM_EXPORT +size_t crypto_secretbox_xsalsa20poly1305_noncebytes(void); + +#define crypto_secretbox_xsalsa20poly1305_MACBYTES 16U +SODIUM_EXPORT +size_t crypto_secretbox_xsalsa20poly1305_macbytes(void); + +#define crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES 16U +SODIUM_EXPORT +size_t crypto_secretbox_xsalsa20poly1305_boxzerobytes(void); + +#define crypto_secretbox_xsalsa20poly1305_ZEROBYTES \ + (crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES + \ + crypto_secretbox_xsalsa20poly1305_MACBYTES) +SODIUM_EXPORT +size_t crypto_secretbox_xsalsa20poly1305_zerobytes(void); + +SODIUM_EXPORT +int crypto_secretbox_xsalsa20poly1305(unsigned char *c, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_secretbox_xsalsa20poly1305_open(unsigned char *m, + const unsigned char *c, + unsigned long long clen, + const unsigned char *n, + const unsigned char *k) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +void crypto_secretbox_xsalsa20poly1305_keygen(unsigned char k[crypto_secretbox_xsalsa20poly1305_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_shorthash.h b/tools/sdk/include/libsodium/sodium/crypto_shorthash.h new file mode 100644 index 00000000000..a4988082471 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_shorthash.h @@ -0,0 +1,39 @@ +#ifndef crypto_shorthash_H +#define crypto_shorthash_H + +#include + +#include "crypto_shorthash_siphash24.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_shorthash_BYTES crypto_shorthash_siphash24_BYTES +SODIUM_EXPORT +size_t crypto_shorthash_bytes(void); + +#define crypto_shorthash_KEYBYTES crypto_shorthash_siphash24_KEYBYTES +SODIUM_EXPORT +size_t crypto_shorthash_keybytes(void); + +#define crypto_shorthash_PRIMITIVE "siphash24" +SODIUM_EXPORT +const char *crypto_shorthash_primitive(void); + +SODIUM_EXPORT +int crypto_shorthash(unsigned char *out, const unsigned char *in, + unsigned long long inlen, const unsigned char *k); + +SODIUM_EXPORT +void crypto_shorthash_keygen(unsigned char k[crypto_shorthash_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_shorthash_siphash24.h b/tools/sdk/include/libsodium/sodium/crypto_shorthash_siphash24.h new file mode 100644 index 00000000000..745ed48fae9 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_shorthash_siphash24.h @@ -0,0 +1,48 @@ +#ifndef crypto_shorthash_siphash24_H +#define crypto_shorthash_siphash24_H + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +/* -- 64-bit output -- */ + +#define crypto_shorthash_siphash24_BYTES 8U +SODIUM_EXPORT +size_t crypto_shorthash_siphash24_bytes(void); + +#define crypto_shorthash_siphash24_KEYBYTES 16U +SODIUM_EXPORT +size_t crypto_shorthash_siphash24_keybytes(void); + +SODIUM_EXPORT +int crypto_shorthash_siphash24(unsigned char *out, const unsigned char *in, + unsigned long long inlen, const unsigned char *k); + +#ifndef SODIUM_LIBRARY_MINIMAL +/* -- 128-bit output -- */ + +#define crypto_shorthash_siphashx24_BYTES 16U +SODIUM_EXPORT +size_t crypto_shorthash_siphashx24_bytes(void); + +#define crypto_shorthash_siphashx24_KEYBYTES 16U +SODIUM_EXPORT +size_t crypto_shorthash_siphashx24_keybytes(void); + +SODIUM_EXPORT +int crypto_shorthash_siphashx24(unsigned char *out, const unsigned char *in, + unsigned long long inlen, const unsigned char *k); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_sign.h b/tools/sdk/include/libsodium/sodium/crypto_sign.h new file mode 100644 index 00000000000..b0335bf274c --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_sign.h @@ -0,0 +1,99 @@ +#ifndef crypto_sign_H +#define crypto_sign_H + +/* + * THREAD SAFETY: crypto_sign_keypair() is thread-safe, + * provided that sodium_init() was called before. + * + * Other functions, including crypto_sign_seed_keypair() are always thread-safe. + */ + +#include + +#include "crypto_sign_ed25519.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef crypto_sign_ed25519ph_state crypto_sign_state; + +SODIUM_EXPORT +size_t crypto_sign_statebytes(void); + +#define crypto_sign_BYTES crypto_sign_ed25519_BYTES +SODIUM_EXPORT +size_t crypto_sign_bytes(void); + +#define crypto_sign_SEEDBYTES crypto_sign_ed25519_SEEDBYTES +SODIUM_EXPORT +size_t crypto_sign_seedbytes(void); + +#define crypto_sign_PUBLICKEYBYTES crypto_sign_ed25519_PUBLICKEYBYTES +SODIUM_EXPORT +size_t crypto_sign_publickeybytes(void); + +#define crypto_sign_SECRETKEYBYTES crypto_sign_ed25519_SECRETKEYBYTES +SODIUM_EXPORT +size_t crypto_sign_secretkeybytes(void); + +#define crypto_sign_PRIMITIVE "ed25519" +SODIUM_EXPORT +const char *crypto_sign_primitive(void); + +SODIUM_EXPORT +int crypto_sign_seed_keypair(unsigned char *pk, unsigned char *sk, + const unsigned char *seed); + +SODIUM_EXPORT +int crypto_sign_keypair(unsigned char *pk, unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign(unsigned char *sm, unsigned long long *smlen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_open(unsigned char *m, unsigned long long *mlen_p, + const unsigned char *sm, unsigned long long smlen, + const unsigned char *pk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_sign_detached(unsigned char *sig, unsigned long long *siglen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_verify_detached(const unsigned char *sig, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *pk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_sign_init(crypto_sign_state *state); + +SODIUM_EXPORT +int crypto_sign_update(crypto_sign_state *state, + const unsigned char *m, unsigned long long mlen); + +SODIUM_EXPORT +int crypto_sign_final_create(crypto_sign_state *state, unsigned char *sig, + unsigned long long *siglen_p, + const unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_final_verify(crypto_sign_state *state, unsigned char *sig, + const unsigned char *pk) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_sign_ed25519.h b/tools/sdk/include/libsodium/sodium/crypto_sign_ed25519.h new file mode 100644 index 00000000000..17c150f284a --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_sign_ed25519.h @@ -0,0 +1,110 @@ +#ifndef crypto_sign_ed25519_H +#define crypto_sign_ed25519_H + +#include +#include "crypto_hash_sha512.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef struct crypto_sign_ed25519ph_state { + crypto_hash_sha512_state hs; +} crypto_sign_ed25519ph_state; + +SODIUM_EXPORT +size_t crypto_sign_ed25519ph_statebytes(void); + +#define crypto_sign_ed25519_BYTES 64U +SODIUM_EXPORT +size_t crypto_sign_ed25519_bytes(void); + +#define crypto_sign_ed25519_SEEDBYTES 32U +SODIUM_EXPORT +size_t crypto_sign_ed25519_seedbytes(void); + +#define crypto_sign_ed25519_PUBLICKEYBYTES 32U +SODIUM_EXPORT +size_t crypto_sign_ed25519_publickeybytes(void); + +#define crypto_sign_ed25519_SECRETKEYBYTES (32U + 32U) +SODIUM_EXPORT +size_t crypto_sign_ed25519_secretkeybytes(void); + +SODIUM_EXPORT +int crypto_sign_ed25519(unsigned char *sm, unsigned long long *smlen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_ed25519_open(unsigned char *m, unsigned long long *mlen_p, + const unsigned char *sm, unsigned long long smlen, + const unsigned char *pk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_sign_ed25519_detached(unsigned char *sig, + unsigned long long *siglen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_ed25519_verify_detached(const unsigned char *sig, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *pk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_sign_ed25519_keypair(unsigned char *pk, unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_ed25519_seed_keypair(unsigned char *pk, unsigned char *sk, + const unsigned char *seed); + +SODIUM_EXPORT +int crypto_sign_ed25519_pk_to_curve25519(unsigned char *curve25519_pk, + const unsigned char *ed25519_pk) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int crypto_sign_ed25519_sk_to_curve25519(unsigned char *curve25519_sk, + const unsigned char *ed25519_sk); + +SODIUM_EXPORT +int crypto_sign_ed25519_sk_to_seed(unsigned char *seed, + const unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_ed25519_sk_to_pk(unsigned char *pk, const unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_ed25519ph_init(crypto_sign_ed25519ph_state *state); + +SODIUM_EXPORT +int crypto_sign_ed25519ph_update(crypto_sign_ed25519ph_state *state, + const unsigned char *m, + unsigned long long mlen); + +SODIUM_EXPORT +int crypto_sign_ed25519ph_final_create(crypto_sign_ed25519ph_state *state, + unsigned char *sig, + unsigned long long *siglen_p, + const unsigned char *sk); + +SODIUM_EXPORT +int crypto_sign_ed25519ph_final_verify(crypto_sign_ed25519ph_state *state, + unsigned char *sig, + const unsigned char *pk) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_sign_edwards25519sha512batch.h b/tools/sdk/include/libsodium/sodium/crypto_sign_edwards25519sha512batch.h new file mode 100644 index 00000000000..2224a94e013 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_sign_edwards25519sha512batch.h @@ -0,0 +1,54 @@ +#ifndef crypto_sign_edwards25519sha512batch_H +#define crypto_sign_edwards25519sha512batch_H + +/* + * WARNING: This construction was a prototype, which should not be used + * any more in new projects. + * + * crypto_sign_edwards25519sha512batch is provided for applications + * initially built with NaCl, but as recommended by the author of this + * construction, new applications should use ed25519 instead. + * + * In Sodium, you should use the high-level crypto_sign_*() functions instead. + */ + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_sign_edwards25519sha512batch_BYTES 64U +#define crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES 32U +#define crypto_sign_edwards25519sha512batch_SECRETKEYBYTES (32U + 32U) + +SODIUM_EXPORT +int crypto_sign_edwards25519sha512batch(unsigned char *sm, + unsigned long long *smlen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *sk) + __attribute__ ((deprecated)); + +SODIUM_EXPORT +int crypto_sign_edwards25519sha512batch_open(unsigned char *m, + unsigned long long *mlen_p, + const unsigned char *sm, + unsigned long long smlen, + const unsigned char *pk) + __attribute__ ((deprecated)); + +SODIUM_EXPORT +int crypto_sign_edwards25519sha512batch_keypair(unsigned char *pk, + unsigned char *sk) + __attribute__ ((deprecated)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_stream.h b/tools/sdk/include/libsodium/sodium/crypto_stream.h new file mode 100644 index 00000000000..22de6ff52d3 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_stream.h @@ -0,0 +1,52 @@ +#ifndef crypto_stream_H +#define crypto_stream_H + +/* + * WARNING: This is just a stream cipher. It is NOT authenticated encryption. + * While it provides some protection against eavesdropping, it does NOT + * provide any security against active attacks. + * Unless you know what you're doing, what you are looking for is probably + * the crypto_box functions. + */ + +#include + +#include "crypto_stream_xsalsa20.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_stream_KEYBYTES crypto_stream_xsalsa20_KEYBYTES +SODIUM_EXPORT +size_t crypto_stream_keybytes(void); + +#define crypto_stream_NONCEBYTES crypto_stream_xsalsa20_NONCEBYTES +SODIUM_EXPORT +size_t crypto_stream_noncebytes(void); + +#define crypto_stream_PRIMITIVE "xsalsa20" +SODIUM_EXPORT +const char *crypto_stream_primitive(void); + +SODIUM_EXPORT +int crypto_stream(unsigned char *c, unsigned long long clen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_xor(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +void crypto_stream_keygen(unsigned char k[crypto_stream_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_stream_aes128ctr.h b/tools/sdk/include/libsodium/sodium/crypto_stream_aes128ctr.h new file mode 100644 index 00000000000..33ee1b89714 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_stream_aes128ctr.h @@ -0,0 +1,65 @@ +#ifndef crypto_stream_aes128ctr_H +#define crypto_stream_aes128ctr_H + +/* + * WARNING: This is just a stream cipher. It is NOT authenticated encryption. + * While it provides some protection against eavesdropping, it does NOT + * provide any security against active attacks. + * Unless you know what you're doing, what you are looking for is probably + * the crypto_box functions. + */ + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_stream_aes128ctr_KEYBYTES 16U +SODIUM_EXPORT +size_t crypto_stream_aes128ctr_keybytes(void); + +#define crypto_stream_aes128ctr_NONCEBYTES 16U +SODIUM_EXPORT +size_t crypto_stream_aes128ctr_noncebytes(void); + +#define crypto_stream_aes128ctr_BEFORENMBYTES 1408U +SODIUM_EXPORT +size_t crypto_stream_aes128ctr_beforenmbytes(void); + +SODIUM_EXPORT +int crypto_stream_aes128ctr(unsigned char *out, unsigned long long outlen, + const unsigned char *n, const unsigned char *k) + __attribute__ ((deprecated)); + +SODIUM_EXPORT +int crypto_stream_aes128ctr_xor(unsigned char *out, const unsigned char *in, + unsigned long long inlen, const unsigned char *n, + const unsigned char *k) + __attribute__ ((deprecated)); + +SODIUM_EXPORT +int crypto_stream_aes128ctr_beforenm(unsigned char *c, const unsigned char *k) + __attribute__ ((deprecated)); + +SODIUM_EXPORT +int crypto_stream_aes128ctr_afternm(unsigned char *out, unsigned long long len, + const unsigned char *nonce, const unsigned char *c) + __attribute__ ((deprecated)); + +SODIUM_EXPORT +int crypto_stream_aes128ctr_xor_afternm(unsigned char *out, const unsigned char *in, + unsigned long long len, + const unsigned char *nonce, + const unsigned char *c) + __attribute__ ((deprecated)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_stream_chacha20.h b/tools/sdk/include/libsodium/sodium/crypto_stream_chacha20.h new file mode 100644 index 00000000000..cf3ffe89595 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_stream_chacha20.h @@ -0,0 +1,92 @@ +#ifndef crypto_stream_chacha20_H +#define crypto_stream_chacha20_H + +/* + * WARNING: This is just a stream cipher. It is NOT authenticated encryption. + * While it provides some protection against eavesdropping, it does NOT + * provide any security against active attacks. + * Unless you know what you're doing, what you are looking for is probably + * the crypto_box functions. + */ + +#include +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_stream_chacha20_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_stream_chacha20_keybytes(void); + +#define crypto_stream_chacha20_NONCEBYTES 8U +SODIUM_EXPORT +size_t crypto_stream_chacha20_noncebytes(void); + +/* ChaCha20 with a 64-bit nonce and a 64-bit counter, as originally designed */ + +SODIUM_EXPORT +int crypto_stream_chacha20(unsigned char *c, unsigned long long clen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_chacha20_xor(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_chacha20_xor_ic(unsigned char *c, const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, uint64_t ic, + const unsigned char *k); + +SODIUM_EXPORT +void crypto_stream_chacha20_keygen(unsigned char k[crypto_stream_chacha20_KEYBYTES]); + +/* ChaCha20 with a 96-bit nonce and a 32-bit counter (IETF) */ + +#define crypto_stream_chacha20_ietf_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_stream_chacha20_ietf_keybytes(void); + +#define crypto_stream_chacha20_ietf_NONCEBYTES 12U +SODIUM_EXPORT +size_t crypto_stream_chacha20_ietf_noncebytes(void); + +SODIUM_EXPORT +int crypto_stream_chacha20_ietf(unsigned char *c, unsigned long long clen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_chacha20_ietf_xor(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_chacha20_ietf_xor_ic(unsigned char *c, const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, uint32_t ic, + const unsigned char *k); + +SODIUM_EXPORT +void crypto_stream_chacha20_ietf_keygen(unsigned char k[crypto_stream_chacha20_ietf_KEYBYTES]); + +/* ------------------------------------------------------------------------- */ + +int _crypto_stream_chacha20_pick_best_implementation(void); + +/* Aliases */ + +#define crypto_stream_chacha20_IETF_KEYBYTES crypto_stream_chacha20_ietf_KEYBYTES +#define crypto_stream_chacha20_IETF_NONCEBYTES crypto_stream_chacha20_ietf_NONCEBYTES + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_stream_salsa20.h b/tools/sdk/include/libsodium/sodium/crypto_stream_salsa20.h new file mode 100644 index 00000000000..741140eb22d --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_stream_salsa20.h @@ -0,0 +1,57 @@ +#ifndef crypto_stream_salsa20_H +#define crypto_stream_salsa20_H + +/* + * WARNING: This is just a stream cipher. It is NOT authenticated encryption. + * While it provides some protection against eavesdropping, it does NOT + * provide any security against active attacks. + * Unless you know what you're doing, what you are looking for is probably + * the crypto_box functions. + */ + +#include +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_stream_salsa20_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_stream_salsa20_keybytes(void); + +#define crypto_stream_salsa20_NONCEBYTES 8U +SODIUM_EXPORT +size_t crypto_stream_salsa20_noncebytes(void); + +SODIUM_EXPORT +int crypto_stream_salsa20(unsigned char *c, unsigned long long clen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_salsa20_xor(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_salsa20_xor_ic(unsigned char *c, const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, uint64_t ic, + const unsigned char *k); + +SODIUM_EXPORT +void crypto_stream_salsa20_keygen(unsigned char k[crypto_stream_salsa20_KEYBYTES]); + +/* ------------------------------------------------------------------------- */ + +int _crypto_stream_salsa20_pick_best_implementation(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_stream_salsa2012.h b/tools/sdk/include/libsodium/sodium/crypto_stream_salsa2012.h new file mode 100644 index 00000000000..d5c44282174 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_stream_salsa2012.h @@ -0,0 +1,46 @@ +#ifndef crypto_stream_salsa2012_H +#define crypto_stream_salsa2012_H + +/* + * WARNING: This is just a stream cipher. It is NOT authenticated encryption. + * While it provides some protection against eavesdropping, it does NOT + * provide any security against active attacks. + * Unless you know what you're doing, what you are looking for is probably + * the crypto_box functions. + */ + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_stream_salsa2012_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_stream_salsa2012_keybytes(void); + +#define crypto_stream_salsa2012_NONCEBYTES 8U +SODIUM_EXPORT +size_t crypto_stream_salsa2012_noncebytes(void); + +SODIUM_EXPORT +int crypto_stream_salsa2012(unsigned char *c, unsigned long long clen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_salsa2012_xor(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +void crypto_stream_salsa2012_keygen(unsigned char k[crypto_stream_salsa2012_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_stream_salsa208.h b/tools/sdk/include/libsodium/sodium/crypto_stream_salsa208.h new file mode 100644 index 00000000000..02b4166e1ca --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_stream_salsa208.h @@ -0,0 +1,46 @@ +#ifndef crypto_stream_salsa208_H +#define crypto_stream_salsa208_H + +/* + * WARNING: This is just a stream cipher. It is NOT authenticated encryption. + * While it provides some protection against eavesdropping, it does NOT + * provide any security against active attacks. + * Unless you know what you're doing, what you are looking for is probably + * the crypto_box functions. + */ + +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_stream_salsa208_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_stream_salsa208_keybytes(void); + +#define crypto_stream_salsa208_NONCEBYTES 8U +SODIUM_EXPORT +size_t crypto_stream_salsa208_noncebytes(void); + +SODIUM_EXPORT +int crypto_stream_salsa208(unsigned char *c, unsigned long long clen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_salsa208_xor(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +void crypto_stream_salsa208_keygen(unsigned char k[crypto_stream_salsa208_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_stream_xchacha20.h b/tools/sdk/include/libsodium/sodium/crypto_stream_xchacha20.h new file mode 100644 index 00000000000..f884798e740 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_stream_xchacha20.h @@ -0,0 +1,53 @@ +#ifndef crypto_stream_xchacha20_H +#define crypto_stream_xchacha20_H + +/* + * WARNING: This is just a stream cipher. It is NOT authenticated encryption. + * While it provides some protection against eavesdropping, it does NOT + * provide any security against active attacks. + * Unless you know what you're doing, what you are looking for is probably + * the crypto_box functions. + */ + +#include +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_stream_xchacha20_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_stream_xchacha20_keybytes(void); + +#define crypto_stream_xchacha20_NONCEBYTES 24U +SODIUM_EXPORT +size_t crypto_stream_xchacha20_noncebytes(void); + +SODIUM_EXPORT +int crypto_stream_xchacha20(unsigned char *c, unsigned long long clen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_xchacha20_xor(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_xchacha20_xor_ic(unsigned char *c, const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, uint64_t ic, + const unsigned char *k); + +SODIUM_EXPORT +void crypto_stream_xchacha20_keygen(unsigned char k[crypto_stream_xchacha20_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_stream_xsalsa20.h b/tools/sdk/include/libsodium/sodium/crypto_stream_xsalsa20.h new file mode 100644 index 00000000000..ed5ae3c3d3c --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_stream_xsalsa20.h @@ -0,0 +1,53 @@ +#ifndef crypto_stream_xsalsa20_H +#define crypto_stream_xsalsa20_H + +/* + * WARNING: This is just a stream cipher. It is NOT authenticated encryption. + * While it provides some protection against eavesdropping, it does NOT + * provide any security against active attacks. + * Unless you know what you're doing, what you are looking for is probably + * the crypto_box functions. + */ + +#include +#include +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +#define crypto_stream_xsalsa20_KEYBYTES 32U +SODIUM_EXPORT +size_t crypto_stream_xsalsa20_keybytes(void); + +#define crypto_stream_xsalsa20_NONCEBYTES 24U +SODIUM_EXPORT +size_t crypto_stream_xsalsa20_noncebytes(void); + +SODIUM_EXPORT +int crypto_stream_xsalsa20(unsigned char *c, unsigned long long clen, + const unsigned char *n, const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_xsalsa20_xor(unsigned char *c, const unsigned char *m, + unsigned long long mlen, const unsigned char *n, + const unsigned char *k); + +SODIUM_EXPORT +int crypto_stream_xsalsa20_xor_ic(unsigned char *c, const unsigned char *m, + unsigned long long mlen, + const unsigned char *n, uint64_t ic, + const unsigned char *k); + +SODIUM_EXPORT +void crypto_stream_xsalsa20_keygen(unsigned char k[crypto_stream_xsalsa20_KEYBYTES]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_verify_16.h b/tools/sdk/include/libsodium/sodium/crypto_verify_16.h new file mode 100644 index 00000000000..5e9eeabee84 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_verify_16.h @@ -0,0 +1,23 @@ +#ifndef crypto_verify_16_H +#define crypto_verify_16_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_verify_16_BYTES 16U +SODIUM_EXPORT +size_t crypto_verify_16_bytes(void); + +SODIUM_EXPORT +int crypto_verify_16(const unsigned char *x, const unsigned char *y) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_verify_32.h b/tools/sdk/include/libsodium/sodium/crypto_verify_32.h new file mode 100644 index 00000000000..281b5a1bb79 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_verify_32.h @@ -0,0 +1,23 @@ +#ifndef crypto_verify_32_H +#define crypto_verify_32_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_verify_32_BYTES 32U +SODIUM_EXPORT +size_t crypto_verify_32_bytes(void); + +SODIUM_EXPORT +int crypto_verify_32(const unsigned char *x, const unsigned char *y) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/crypto_verify_64.h b/tools/sdk/include/libsodium/sodium/crypto_verify_64.h new file mode 100644 index 00000000000..0dc7c304a99 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/crypto_verify_64.h @@ -0,0 +1,23 @@ +#ifndef crypto_verify_64_H +#define crypto_verify_64_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_verify_64_BYTES 64U +SODIUM_EXPORT +size_t crypto_verify_64_bytes(void); + +SODIUM_EXPORT +int crypto_verify_64(const unsigned char *x, const unsigned char *y) + __attribute__ ((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/export.h b/tools/sdk/include/libsodium/sodium/export.h new file mode 100644 index 00000000000..c33bced8188 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/export.h @@ -0,0 +1,44 @@ + +#ifndef sodium_export_H +#define sodium_export_H + +#ifndef __GNUC__ +# ifdef __attribute__ +# undef __attribute__ +# endif +# define __attribute__(a) +#endif + +#ifdef SODIUM_STATIC +# define SODIUM_EXPORT +#else +# if defined(_MSC_VER) +# ifdef SODIUM_DLL_EXPORT +# define SODIUM_EXPORT __declspec(dllexport) +# else +# define SODIUM_EXPORT __declspec(dllimport) +# endif +# else +# if defined(__SUNPRO_C) +# ifndef __GNU_C__ +# define SODIUM_EXPORT __attribute__ (visibility(__global)) +# else +# define SODIUM_EXPORT __attribute__ __global +# endif +# elif defined(_MSG_VER) +# define SODIUM_EXPORT extern __declspec(dllexport) +# else +# define SODIUM_EXPORT __attribute__ ((visibility ("default"))) +# endif +# endif +#endif + +#ifndef CRYPTO_ALIGN +# if defined(__INTEL_COMPILER) || defined(_MSC_VER) +# define CRYPTO_ALIGN(x) __declspec(align(x)) +# else +# define CRYPTO_ALIGN(x) __attribute__ ((aligned(x))) +# endif +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/private/common.h b/tools/sdk/include/libsodium/sodium/private/common.h new file mode 100644 index 00000000000..5e27e5749f9 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/private/common.h @@ -0,0 +1,217 @@ +#ifndef common_H +#define common_H 1 + +#include +#include +#include + +#define COMPILER_ASSERT(X) (void) sizeof(char[(X) ? 1 : -1]) + +#define ROTL32(X, B) rotl32((X), (B)) +static inline uint32_t +rotl32(const uint32_t x, const int b) +{ + return (x << b) | (x >> (32 - b)); +} + +#define ROTL64(X, B) rotl64((X), (B)) +static inline uint64_t +rotl64(const uint64_t x, const int b) +{ + return (x << b) | (x >> (64 - b)); +} + +#define ROTR32(X, B) rotr32((X), (B)) +static inline uint32_t +rotr32(const uint32_t x, const int b) +{ + return (x >> b) | (x << (32 - b)); +} + +#define ROTR64(X, B) rotr64((X), (B)) +static inline uint64_t +rotr64(const uint64_t x, const int b) +{ + return (x >> b) | (x << (64 - b)); +} + +#define LOAD64_LE(SRC) load64_le(SRC) +static inline uint64_t +load64_le(const uint8_t src[8]) +{ +#ifdef NATIVE_LITTLE_ENDIAN + uint64_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint64_t w = (uint64_t) src[0]; + w |= (uint64_t) src[1] << 8; + w |= (uint64_t) src[2] << 16; + w |= (uint64_t) src[3] << 24; + w |= (uint64_t) src[4] << 32; + w |= (uint64_t) src[5] << 40; + w |= (uint64_t) src[6] << 48; + w |= (uint64_t) src[7] << 56; + return w; +#endif +} + +#define STORE64_LE(DST, W) store64_le((DST), (W)) +static inline void +store64_le(uint8_t dst[8], uint64_t w) +{ +#ifdef NATIVE_LITTLE_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[0] = (uint8_t) w; w >>= 8; + dst[1] = (uint8_t) w; w >>= 8; + dst[2] = (uint8_t) w; w >>= 8; + dst[3] = (uint8_t) w; w >>= 8; + dst[4] = (uint8_t) w; w >>= 8; + dst[5] = (uint8_t) w; w >>= 8; + dst[6] = (uint8_t) w; w >>= 8; + dst[7] = (uint8_t) w; +#endif +} + +#define LOAD32_LE(SRC) load32_le(SRC) +static inline uint32_t +load32_le(const uint8_t src[4]) +{ +#ifdef NATIVE_LITTLE_ENDIAN + uint32_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint32_t w = (uint32_t) src[0]; + w |= (uint32_t) src[1] << 8; + w |= (uint32_t) src[2] << 16; + w |= (uint32_t) src[3] << 24; + return w; +#endif +} + +#define STORE32_LE(DST, W) store32_le((DST), (W)) +static inline void +store32_le(uint8_t dst[4], uint32_t w) +{ +#ifdef NATIVE_LITTLE_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[0] = (uint8_t) w; w >>= 8; + dst[1] = (uint8_t) w; w >>= 8; + dst[2] = (uint8_t) w; w >>= 8; + dst[3] = (uint8_t) w; +#endif +} + +/* ----- */ + +#define LOAD64_BE(SRC) load64_be(SRC) +static inline uint64_t +load64_be(const uint8_t src[8]) +{ +#ifdef NATIVE_BIG_ENDIAN + uint64_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint64_t w = (uint64_t) src[7]; + w |= (uint64_t) src[6] << 8; + w |= (uint64_t) src[5] << 16; + w |= (uint64_t) src[4] << 24; + w |= (uint64_t) src[3] << 32; + w |= (uint64_t) src[2] << 40; + w |= (uint64_t) src[1] << 48; + w |= (uint64_t) src[0] << 56; + return w; +#endif +} + +#define STORE64_BE(DST, W) store64_be((DST), (W)) +static inline void +store64_be(uint8_t dst[8], uint64_t w) +{ +#ifdef NATIVE_BIG_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[7] = (uint8_t) w; w >>= 8; + dst[6] = (uint8_t) w; w >>= 8; + dst[5] = (uint8_t) w; w >>= 8; + dst[4] = (uint8_t) w; w >>= 8; + dst[3] = (uint8_t) w; w >>= 8; + dst[2] = (uint8_t) w; w >>= 8; + dst[1] = (uint8_t) w; w >>= 8; + dst[0] = (uint8_t) w; +#endif +} + +#define LOAD32_BE(SRC) load32_be(SRC) +static inline uint32_t +load32_be(const uint8_t src[4]) +{ +#ifdef NATIVE_BIG_ENDIAN + uint32_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint32_t w = (uint32_t) src[3]; + w |= (uint32_t) src[2] << 8; + w |= (uint32_t) src[1] << 16; + w |= (uint32_t) src[0] << 24; + return w; +#endif +} + +#define STORE32_BE(DST, W) store32_be((DST), (W)) +static inline void +store32_be(uint8_t dst[4], uint32_t w) +{ +#ifdef NATIVE_BIG_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[3] = (uint8_t) w; w >>= 8; + dst[2] = (uint8_t) w; w >>= 8; + dst[1] = (uint8_t) w; w >>= 8; + dst[0] = (uint8_t) w; +#endif +} + +#ifndef __GNUC__ +# ifdef __attribute__ +# undef __attribute__ +# endif +# define __attribute__(a) +#endif + +#ifndef CRYPTO_ALIGN +# if defined(__INTEL_COMPILER) || defined(_MSC_VER) +# define CRYPTO_ALIGN(x) __declspec(align(x)) +# else +# define CRYPTO_ALIGN(x) __attribute__ ((aligned(x))) +# endif +#endif + +#if defined(_MSC_VER) && \ + (defined(_M_X64) || defined(_M_AMD64) || defined(_M_IX86)) + +# include + +# define HAVE_INTRIN_H 1 +# define HAVE_MMINTRIN_H 1 +# define HAVE_EMMINTRIN_H 1 +# define HAVE_PMMINTRIN_H 1 +# define HAVE_TMMINTRIN_H 1 +# define HAVE_SMMINTRIN_H 1 +# define HAVE_AVXINTRIN_H 1 +# if _MSC_VER >= 1600 +# define HAVE_WMMINTRIN_H 1 +# endif +# if _MSC_VER >= 1700 && defined(_M_X64) +# define HAVE_AVX2INTRIN_H 1 +# endif +#elif defined(HAVE_INTRIN_H) +# include +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/private/curve25519_ref10.h b/tools/sdk/include/libsodium/sodium/private/curve25519_ref10.h new file mode 100644 index 00000000000..2b9caeb1f0d --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/private/curve25519_ref10.h @@ -0,0 +1,160 @@ +#ifndef curve25519_ref10_H +#define curve25519_ref10_H + +#include +#include + +#define fe crypto_core_curve25519_ref10_fe +typedef int32_t fe[10]; + +/* + fe means field element. + Here the field is \Z/(2^255-19). + An element t, entries t[0]...t[9], represents the integer + t[0]+2^26 t[1]+2^51 t[2]+2^77 t[3]+2^102 t[4]+...+2^230 t[9]. + Bounds on each t[i] vary depending on context. + */ + +#define fe_frombytes crypto_core_curve25519_ref10_fe_frombytes +#define fe_tobytes crypto_core_curve25519_ref10_fe_tobytes +#define fe_copy crypto_core_curve25519_ref10_fe_copy +#define fe_isnonzero crypto_core_curve25519_ref10_fe_isnonzero +#define fe_isnegative crypto_core_curve25519_ref10_fe_isnegative +#define fe_0 crypto_core_curve25519_ref10_fe_0 +#define fe_1 crypto_core_curve25519_ref10_fe_1 +#define fe_cmov crypto_core_curve25519_ref10_fe_cmov +#define fe_add crypto_core_curve25519_ref10_fe_add +#define fe_sub crypto_core_curve25519_ref10_fe_sub +#define fe_neg crypto_core_curve25519_ref10_fe_neg +#define fe_mul crypto_core_curve25519_ref10_fe_mul +#define fe_sq crypto_core_curve25519_ref10_fe_sq +#define fe_sq2 crypto_core_curve25519_ref10_fe_sq2 +#define fe_invert crypto_core_curve25519_ref10_fe_invert +#define fe_pow22523 crypto_core_curve25519_ref10_fe_pow22523 + +extern void fe_frombytes(fe,const unsigned char *); +extern void fe_tobytes(unsigned char *,const fe); + +extern void fe_copy(fe,const fe); +extern int fe_isnonzero(const fe); +extern int fe_isnegative(const fe); +extern void fe_0(fe); +extern void fe_1(fe); +extern void fe_cmov(fe,const fe,unsigned int); +extern void fe_add(fe,const fe,const fe); +extern void fe_sub(fe,const fe,const fe); +extern void fe_neg(fe,const fe); +extern void fe_mul(fe,const fe,const fe); +extern void fe_sq(fe,const fe); +extern void fe_sq2(fe,const fe); +extern void fe_invert(fe,const fe); +extern void fe_pow22523(fe,const fe); + +/* + ge means group element. + * + Here the group is the set of pairs (x,y) of field elements (see fe.h) + satisfying -x^2 + y^2 = 1 + d x^2y^2 + where d = -121665/121666. + * + Representations: + ge_p2 (projective): (X:Y:Z) satisfying x=X/Z, y=Y/Z + ge_p3 (extended): (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT + ge_p1p1 (completed): ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T + ge_precomp (Duif): (y+x,y-x,2dxy) + */ + +#define ge_p2 crypto_core_curve25519_ref10_ge_p2 +typedef struct { + fe X; + fe Y; + fe Z; +} ge_p2; + +#define ge_p3 crypto_core_curve25519_ref10_ge_p3 +typedef struct { + fe X; + fe Y; + fe Z; + fe T; +} ge_p3; + +#define ge_p1p1 crypto_core_curve25519_ref10_ge_p1p1 +typedef struct { + fe X; + fe Y; + fe Z; + fe T; +} ge_p1p1; + +#define ge_precomp crypto_core_curve25519_ref10_ge_precomp +typedef struct { + fe yplusx; + fe yminusx; + fe xy2d; +} ge_precomp; + +#define ge_cached crypto_core_curve25519_ref10_ge_cached +typedef struct { + fe YplusX; + fe YminusX; + fe Z; + fe T2d; +} ge_cached; + +#define ge_frombytes_negate_vartime crypto_core_curve25519_ref10_ge_frombytes_negate_vartime +#define ge_tobytes crypto_core_curve25519_ref10_ge_tobytes +#define ge_p3_tobytes crypto_core_curve25519_ref10_ge_p3_tobytes + +#define ge_p2_0 crypto_core_curve25519_ref10_ge_p2_0 +#define ge_p3_0 crypto_core_curve25519_ref10_ge_p3_0 +#define ge_precomp_0 crypto_core_curve25519_ref10_ge_precomp_0 +#define ge_p3_to_p2 crypto_core_curve25519_ref10_ge_p3_to_p2 +#define ge_p3_to_cached crypto_core_curve25519_ref10_ge_p3_to_cached +#define ge_p1p1_to_p2 crypto_core_curve25519_ref10_ge_p1p1_to_p2 +#define ge_p1p1_to_p3 crypto_core_curve25519_ref10_ge_p1p1_to_p3 +#define ge_p2_dbl crypto_core_curve25519_ref10_ge_p2_dbl +#define ge_p3_dbl crypto_core_curve25519_ref10_ge_p3_dbl + +#define ge_madd crypto_core_curve25519_ref10_ge_madd +#define ge_msub crypto_core_curve25519_ref10_ge_msub +#define ge_add crypto_core_curve25519_ref10_ge_add +#define ge_sub crypto_core_curve25519_ref10_ge_sub +#define ge_scalarmult_base crypto_core_curve25519_ref10_ge_scalarmult_base +#define ge_double_scalarmult_vartime crypto_core_curve25519_ref10_ge_double_scalarmult_vartime +#define ge_scalarmult_vartime crypto_core_curve25519_ref10_ge_scalarmult_vartime + +extern void ge_tobytes(unsigned char *,const ge_p2 *); +extern void ge_p3_tobytes(unsigned char *,const ge_p3 *); +extern int ge_frombytes_negate_vartime(ge_p3 *,const unsigned char *); + +extern void ge_p2_0(ge_p2 *); +extern void ge_p3_0(ge_p3 *); +extern void ge_precomp_0(ge_precomp *); +extern void ge_p3_to_p2(ge_p2 *,const ge_p3 *); +extern void ge_p3_to_cached(ge_cached *,const ge_p3 *); +extern void ge_p1p1_to_p2(ge_p2 *,const ge_p1p1 *); +extern void ge_p1p1_to_p3(ge_p3 *,const ge_p1p1 *); +extern void ge_p2_dbl(ge_p1p1 *,const ge_p2 *); +extern void ge_p3_dbl(ge_p1p1 *,const ge_p3 *); + +extern void ge_madd(ge_p1p1 *,const ge_p3 *,const ge_precomp *); +extern void ge_msub(ge_p1p1 *,const ge_p3 *,const ge_precomp *); +extern void ge_add(ge_p1p1 *,const ge_p3 *,const ge_cached *); +extern void ge_sub(ge_p1p1 *,const ge_p3 *,const ge_cached *); +extern void ge_scalarmult_base(ge_p3 *,const unsigned char *); +extern void ge_double_scalarmult_vartime(ge_p2 *,const unsigned char *,const ge_p3 *,const unsigned char *); +extern void ge_scalarmult_vartime(ge_p3 *,const unsigned char *,const ge_p3 *); + +/* + The set of scalars is \Z/l + where l = 2^252 + 27742317777372353535851937790883648493. + */ + +#define sc_reduce crypto_core_curve25519_ref10_sc_reduce +#define sc_muladd crypto_core_curve25519_ref10_sc_muladd + +extern void sc_reduce(unsigned char *); +extern void sc_muladd(unsigned char *,const unsigned char *,const unsigned char *,const unsigned char *); + +#endif diff --git a/tools/sdk/include/libsodium/sodium/private/mutex.h b/tools/sdk/include/libsodium/sodium/private/mutex.h new file mode 100644 index 00000000000..322b6742b26 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/private/mutex.h @@ -0,0 +1,7 @@ +#ifndef mutex_H +#define mutex_H 1 + +extern int sodium_crit_enter(void); +extern int sodium_crit_leave(void); + +#endif diff --git a/tools/sdk/include/libsodium/sodium/private/sse2_64_32.h b/tools/sdk/include/libsodium/sodium/private/sse2_64_32.h new file mode 100644 index 00000000000..d0455b41b49 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/private/sse2_64_32.h @@ -0,0 +1,50 @@ +#ifndef sse2_64_32_H +#define sse2_64_32_H 1 + +#include "common.h" + +#ifdef HAVE_INTRIN_H +# include +#endif + +#if defined(HAVE_EMMINTRIN_H) && \ + !(defined(__amd64) || defined(__amd64__) || defined(__x86_64__) || \ + defined(_M_X64) || defined(_M_AMD64)) + +# include +# include + +# ifndef _mm_set_epi64x +# define _mm_set_epi64x(Q0, Q1) sodium__mm_set_epi64x((Q0), (Q1)) +static inline __m128i +sodium__mm_set_epi64x(int64_t q1, int64_t q0) +{ + union { int64_t as64; int32_t as32[2]; } x0, x1; + x0.as64 = q0; x1.as64 = q1; + return _mm_set_epi32(x1.as32[1], x1.as32[0], x0.as32[1], x0.as32[0]); +} +# endif + +# ifndef _mm_set1_epi64x +# define _mm_set1_epi64x(Q) sodium__mm_set1_epi64x(Q) +static inline __m128i +sodium__mm_set1_epi64x(int64_t q) +{ + return _mm_set_epi64x(q, q); +} +# endif + +# ifndef _mm_cvtsi64_si128 +# define _mm_cvtsi64_si128(Q) sodium__mm_cvtsi64_si128(Q) +static inline __m128i +sodium__mm_cvtsi64_si128(int64_t q) +{ + union { int64_t as64; int32_t as32[2]; } x; + x.as64 = q; + return _mm_setr_epi32(x.as32[0], x.as32[1], 0, 0); +} +# endif + +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/randombytes.h b/tools/sdk/include/libsodium/sodium/randombytes.h new file mode 100644 index 00000000000..d112fb293e5 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/randombytes.h @@ -0,0 +1,66 @@ + +#ifndef randombytes_H +#define randombytes_H + +#include +#include + +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef struct randombytes_implementation { + const char *(*implementation_name)(void); /* required */ + uint32_t (*random)(void); /* required */ + void (*stir)(void); /* optional */ + uint32_t (*uniform)(const uint32_t upper_bound); /* optional, a default implementation will be used if NULL */ + void (*buf)(void * const buf, const size_t size); /* required */ + int (*close)(void); /* optional */ +} randombytes_implementation; + +#define randombytes_SEEDBYTES 32U +SODIUM_EXPORT +size_t randombytes_seedbytes(void); + +SODIUM_EXPORT +void randombytes_buf(void * const buf, const size_t size); + +SODIUM_EXPORT +void randombytes_buf_deterministic(void * const buf, const size_t size, + const unsigned char seed[randombytes_SEEDBYTES]); + +SODIUM_EXPORT +uint32_t randombytes_random(void); + +SODIUM_EXPORT +uint32_t randombytes_uniform(const uint32_t upper_bound); + +SODIUM_EXPORT +void randombytes_stir(void); + +SODIUM_EXPORT +int randombytes_close(void); + +SODIUM_EXPORT +int randombytes_set_implementation(randombytes_implementation *impl); + +SODIUM_EXPORT +const char *randombytes_implementation_name(void); + +/* -- NaCl compatibility interface -- */ + +SODIUM_EXPORT +void randombytes(unsigned char * const buf, const unsigned long long buf_len); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/randombytes_nativeclient.h b/tools/sdk/include/libsodium/sodium/randombytes_nativeclient.h new file mode 100644 index 00000000000..5158d8c3c33 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/randombytes_nativeclient.h @@ -0,0 +1,23 @@ + +#ifndef randombytes_nativeclient_H +#define randombytes_nativeclient_H + +#ifdef __native_client__ + +# include "export.h" +# include "randombytes.h" + +# ifdef __cplusplus +extern "C" { +# endif + +SODIUM_EXPORT +extern struct randombytes_implementation randombytes_nativeclient_implementation; + +# ifdef __cplusplus +} +# endif + +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/randombytes_salsa20_random.h b/tools/sdk/include/libsodium/sodium/randombytes_salsa20_random.h new file mode 100644 index 00000000000..4deae15b6d9 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/randombytes_salsa20_random.h @@ -0,0 +1,19 @@ + +#ifndef randombytes_salsa20_random_H +#define randombytes_salsa20_random_H + +#include "export.h" +#include "randombytes.h" + +#ifdef __cplusplus +extern "C" { +#endif + +SODIUM_EXPORT +extern struct randombytes_implementation randombytes_salsa20_implementation; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/randombytes_sysrandom.h b/tools/sdk/include/libsodium/sodium/randombytes_sysrandom.h new file mode 100644 index 00000000000..9e27b674c79 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/randombytes_sysrandom.h @@ -0,0 +1,19 @@ + +#ifndef randombytes_sysrandom_H +#define randombytes_sysrandom_H + +#include "export.h" +#include "randombytes.h" + +#ifdef __cplusplus +extern "C" { +#endif + +SODIUM_EXPORT +extern struct randombytes_implementation randombytes_sysrandom_implementation; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/runtime.h b/tools/sdk/include/libsodium/sodium/runtime.h new file mode 100644 index 00000000000..76859ea0e13 --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/runtime.h @@ -0,0 +1,46 @@ + +#ifndef sodium_runtime_H +#define sodium_runtime_H + +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +SODIUM_EXPORT +int sodium_runtime_has_neon(void); + +SODIUM_EXPORT +int sodium_runtime_has_sse2(void); + +SODIUM_EXPORT +int sodium_runtime_has_sse3(void); + +SODIUM_EXPORT +int sodium_runtime_has_ssse3(void); + +SODIUM_EXPORT +int sodium_runtime_has_sse41(void); + +SODIUM_EXPORT +int sodium_runtime_has_avx(void); + +SODIUM_EXPORT +int sodium_runtime_has_avx2(void); + +SODIUM_EXPORT +int sodium_runtime_has_pclmul(void); + +SODIUM_EXPORT +int sodium_runtime_has_aesni(void); + +/* ------------------------------------------------------------------------- */ + +int _sodium_runtime_get_cpu_features(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/utils.h b/tools/sdk/include/libsodium/sodium/utils.h new file mode 100644 index 00000000000..0a7aadb434c --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/utils.h @@ -0,0 +1,131 @@ + +#ifndef sodium_utils_H +#define sodium_utils_H + +#include + +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef SODIUM_C99 +# if defined(__cplusplus) || !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L +# define SODIUM_C99(X) +# else +# define SODIUM_C99(X) X +# endif +#endif + +SODIUM_EXPORT +void sodium_memzero(void * const pnt, const size_t len); + +/* + * WARNING: sodium_memcmp() must be used to verify if two secret keys + * are equal, in constant time. + * It returns 0 if the keys are equal, and -1 if they differ. + * This function is not designed for lexicographical comparisons. + */ +SODIUM_EXPORT +int sodium_memcmp(const void * const b1_, const void * const b2_, size_t len) + __attribute__ ((warn_unused_result)); + +/* + * sodium_compare() returns -1 if b1_ < b2_, 1 if b1_ > b2_ and 0 if b1_ == b2_ + * It is suitable for lexicographical comparisons, or to compare nonces + * and counters stored in little-endian format. + * However, it is slower than sodium_memcmp(). + */ +SODIUM_EXPORT +int sodium_compare(const unsigned char *b1_, const unsigned char *b2_, + size_t len) + __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int sodium_is_zero(const unsigned char *n, const size_t nlen); + +SODIUM_EXPORT +void sodium_increment(unsigned char *n, const size_t nlen); + +SODIUM_EXPORT +void sodium_add(unsigned char *a, const unsigned char *b, const size_t len); + +SODIUM_EXPORT +char *sodium_bin2hex(char * const hex, const size_t hex_maxlen, + const unsigned char * const bin, const size_t bin_len); + +SODIUM_EXPORT +int sodium_hex2bin(unsigned char * const bin, const size_t bin_maxlen, + const char * const hex, const size_t hex_len, + const char * const ignore, size_t * const bin_len, + const char ** const hex_end); + +SODIUM_EXPORT +int sodium_mlock(void * const addr, const size_t len); + +SODIUM_EXPORT +int sodium_munlock(void * const addr, const size_t len); + +/* WARNING: sodium_malloc() and sodium_allocarray() are not general-purpose + * allocation functions. + * + * They return a pointer to a region filled with 0xd0 bytes, immediately + * followed by a guard page. + * As a result, accessing a single byte after the requested allocation size + * will intentionally trigger a segmentation fault. + * + * A canary and an additional guard page placed before the beginning of the + * region may also kill the process if a buffer underflow is detected. + * + * The memory layout is: + * [unprotected region size (read only)][guard page (no access)][unprotected pages (read/write)][guard page (no access)] + * With the layout of the unprotected pages being: + * [optional padding][16-bytes canary][user region] + * + * However: + * - These functions are significantly slower than standard functions + * - Each allocation requires 3 or 4 additional pages + * - The returned address will not be aligned if the allocation size is not + * a multiple of the required alignment. For this reason, these functions + * are designed to store data, such as secret keys and messages. + * + * sodium_malloc() can be used to allocate any libsodium data structure. + * + * The crypto_generichash_state structure is packed and its length is + * either 357 or 361 bytes. For this reason, when using sodium_malloc() to + * allocate a crypto_generichash_state structure, padding must be added in + * order to ensure proper alignment. crypto_generichash_statebytes() + * returns the rounded up structure size, and should be prefered to sizeof(): + * state = sodium_malloc(crypto_generichash_statebytes()); + */ + +SODIUM_EXPORT +void *sodium_malloc(const size_t size) + __attribute__ ((malloc)); + +SODIUM_EXPORT +void *sodium_allocarray(size_t count, size_t size) + __attribute__ ((malloc)); + +SODIUM_EXPORT +void sodium_free(void *ptr); + +SODIUM_EXPORT +int sodium_mprotect_noaccess(void *ptr); + +SODIUM_EXPORT +int sodium_mprotect_readonly(void *ptr); + +SODIUM_EXPORT +int sodium_mprotect_readwrite(void *ptr); + +/* -------- */ + +int _sodium_alloc_init(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/libsodium/sodium/version.h b/tools/sdk/include/libsodium/sodium/version.h new file mode 100644 index 00000000000..c0bf5869deb --- /dev/null +++ b/tools/sdk/include/libsodium/sodium/version.h @@ -0,0 +1,35 @@ + +#ifndef sodium_version_H +#define sodium_version_H + +#include + +/* IMPORTANT: As we don't use autotools, these version are not automatically + updated if we change submodules. They need to be changed manually. +*/ + +#define SODIUM_VERSION_STRING "1.0.12-idf" + +/* Note: these are not the same as the overall version, see + configure.ac for the relevant macros */ +#define SODIUM_LIBRARY_VERSION_MAJOR 9 +#define SODIUM_LIBRARY_VERSION_MINOR 4 + +#ifdef __cplusplus +extern "C" { +#endif + +SODIUM_EXPORT +const char *sodium_version_string(void); + +SODIUM_EXPORT +int sodium_library_version_major(void); + +SODIUM_EXPORT +int sodium_library_version_minor(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/log/esp_log.h b/tools/sdk/include/log/esp_log.h index c13a3f22719..e57aabbdd53 100644 --- a/tools/sdk/include/log/esp_log.h +++ b/tools/sdk/include/log/esp_log.h @@ -44,10 +44,18 @@ typedef int (*vprintf_like_t)(const char *, va_list); * * If logging for given component has already been enabled, changes previous setting. * + * Note that this function can not raise log level above the level set using + * CONFIG_LOG_DEFAULT_LEVEL setting in menuconfig. + * + * To raise log level above the default one for a given file, define + * LOG_LOCAL_LEVEL to one of the ESP_LOG_* values, before including + * esp_log.h in this file. + * * @param tag Tag of the log entries to enable. Must be a non-NULL zero terminated string. * Value "*" resets log level for all tags to the given value. * - * @param level Selects log level to enable. Only logs at this and lower levels will be shown. + * @param level Selects log level to enable. Only logs at this and lower verbosity + * levels will be shown. */ void esp_log_level_set(const char* tag, esp_log_level_t level); @@ -98,6 +106,8 @@ uint32_t esp_log_early_timestamp(void); */ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, ...) __attribute__ ((format (printf, 3, 4))); +/** @cond */ + #include "esp_log_internal.h" #ifndef LOG_LOCAL_LEVEL @@ -108,16 +118,15 @@ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, . #endif #endif +/** @endcond */ + /** * @brief Log a buffer of hex bytes at specified level, separated into 16 bytes each line. * * @param tag description tag - * * @param buffer Pointer to the buffer array - * * @param buff_len length of buffer in bytes - * - * @param level level of the log + * @param level level of the log * */ #define ESP_LOG_BUFFER_HEX_LEVEL( tag, buffer, buff_len, level ) \ @@ -131,12 +140,9 @@ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, . * @brief Log a buffer of characters at specified level, separated into 16 bytes each line. Buffer should contain only printable characters. * * @param tag description tag - * * @param buffer Pointer to the buffer array - * * @param buff_len length of buffer in bytes - * - * @param level level of the log + * @param level level of the log * */ #define ESP_LOG_BUFFER_CHAR_LEVEL( tag, buffer, buff_len, level ) \ @@ -158,11 +164,8 @@ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, . * It is highly recommend to use terminals with over 102 text width. * * @param tag description tag - * * @param buffer Pointer to the buffer array - * * @param buff_len length of buffer in bytes - * * @param level level of the log */ #define ESP_LOG_BUFFER_HEXDUMP( tag, buffer, buff_len, level ) \ @@ -176,9 +179,7 @@ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, . * @brief Log a buffer of hex bytes at Info level * * @param tag description tag - * * @param buffer Pointer to the buffer array - * * @param buff_len length of buffer in bytes * * @see ``esp_log_buffer_hex_level`` @@ -195,9 +196,7 @@ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, . * @brief Log a buffer of characters at Info level. Buffer should contain only printable characters. * * @param tag description tag - * * @param buffer Pointer to the buffer array - * * @param buff_len length of buffer in bytes * * @see ``esp_log_buffer_char_level`` @@ -210,6 +209,7 @@ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, . }\ } while(0) +/** @cond */ //to be back compatible #define esp_log_buffer_hex ESP_LOG_BUFFER_HEX @@ -243,27 +243,34 @@ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, . #define LOG_FORMAT(letter, format) LOG_COLOR_ ## letter #letter " (%d) %s: " format LOG_RESET_COLOR "\n" +/** @endcond */ + /// macro to output logs in startup code, before heap allocator and syscalls have been initialized. log at ``ESP_LOG_ERROR`` level. @see ``printf``,``ESP_LOGE`` -#define ESP_EARLY_LOGE( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_ERROR) { ets_printf(LOG_FORMAT(E, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } +#define ESP_EARLY_LOGE( tag, format, ... ) ESP_LOG_EARLY_IMPL(tag, format, ESP_LOG_ERROR, E, ##__VA_ARGS__) /// macro to output logs in startup code at ``ESP_LOG_WARN`` level. @see ``ESP_EARLY_LOGE``,``ESP_LOGE``, ``printf`` -#define ESP_EARLY_LOGW( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_WARN) { ets_printf(LOG_FORMAT(W, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } +#define ESP_EARLY_LOGW( tag, format, ... ) ESP_LOG_EARLY_IMPL(tag, format, ESP_LOG_WARN, W, ##__VA_ARGS__) /// macro to output logs in startup code at ``ESP_LOG_INFO`` level. @see ``ESP_EARLY_LOGE``,``ESP_LOGE``, ``printf`` -#define ESP_EARLY_LOGI( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_INFO) { ets_printf(LOG_FORMAT(I, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } +#define ESP_EARLY_LOGI( tag, format, ... ) ESP_LOG_EARLY_IMPL(tag, format, ESP_LOG_INFO, I, ##__VA_ARGS__) /// macro to output logs in startup code at ``ESP_LOG_DEBUG`` level. @see ``ESP_EARLY_LOGE``,``ESP_LOGE``, ``printf`` -#define ESP_EARLY_LOGD( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_DEBUG) { ets_printf(LOG_FORMAT(D, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } +#define ESP_EARLY_LOGD( tag, format, ... ) ESP_LOG_EARLY_IMPL(tag, format, ESP_LOG_DEBUG, D, ##__VA_ARGS__) /// macro to output logs in startup code at ``ESP_LOG_VERBOSE`` level. @see ``ESP_EARLY_LOGE``,``ESP_LOGE``, ``printf`` -#define ESP_EARLY_LOGV( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_VERBOSE) { ets_printf(LOG_FORMAT(V, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } +#define ESP_EARLY_LOGV( tag, format, ... ) ESP_LOG_EARLY_IMPL(tag, format, ESP_LOG_VERBOSE, V, ##__VA_ARGS__) + +#define ESP_LOG_EARLY_IMPL(tag, format, log_level, log_tag_letter, ...) do { \ + if (LOG_LOCAL_LEVEL >= log_level) { \ + ets_printf(LOG_FORMAT(log_tag_letter, format), esp_log_timestamp(), tag, ##__VA_ARGS__); \ + }} while(0) #ifndef BOOTLOADER_BUILD -#define ESP_LOGE( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_ERROR) { esp_log_write(ESP_LOG_ERROR, tag, LOG_FORMAT(E, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } -#define ESP_LOGW( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_WARN) { esp_log_write(ESP_LOG_WARN, tag, LOG_FORMAT(W, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } -#define ESP_LOGI( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_INFO) { esp_log_write(ESP_LOG_INFO, tag, LOG_FORMAT(I, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } -#define ESP_LOGD( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_DEBUG) { esp_log_write(ESP_LOG_DEBUG, tag, LOG_FORMAT(D, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } -#define ESP_LOGV( tag, format, ... ) if (LOG_LOCAL_LEVEL >= ESP_LOG_VERBOSE) { esp_log_write(ESP_LOG_VERBOSE, tag, LOG_FORMAT(V, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } +#define ESP_LOGE( tag, format, ... ) ESP_LOG_LEVEL_LOCAL(ESP_LOG_ERROR, tag, format, ##__VA_ARGS__) +#define ESP_LOGW( tag, format, ... ) ESP_LOG_LEVEL_LOCAL(ESP_LOG_WARN, tag, format, ##__VA_ARGS__) +#define ESP_LOGI( tag, format, ... ) ESP_LOG_LEVEL_LOCAL(ESP_LOG_INFO, tag, format, ##__VA_ARGS__) +#define ESP_LOGD( tag, format, ... ) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG, tag, format, ##__VA_ARGS__) +#define ESP_LOGV( tag, format, ... ) ESP_LOG_LEVEL_LOCAL(ESP_LOG_VERBOSE, tag, format, ##__VA_ARGS__) #else /** * macro to output logs at ESP_LOG_ERROR level. - * + * * @param tag tag of the log, which can be used to change the log level by ``esp_log_level_set`` at runtime. * * @see ``printf`` @@ -282,28 +289,27 @@ void esp_log_write(esp_log_level_t level, const char* tag, const char* format, . /** runtime macro to output logs at a specified level. * * @param tag tag of the log, which can be used to change the log level by ``esp_log_level_set`` at runtime. - * * @param level level of the output log. - * * @param format format of the output log. see ``printf`` - * * @param ... variables to be replaced into the log. see ``printf`` * * @see ``printf`` */ -#define ESP_LOG_LEVEL(level, tag, format, ...) do {\ - if (level==ESP_LOG_ERROR ) { esp_log_write(ESP_LOG_ERROR, tag, LOG_FORMAT(E, format), esp_log_timestamp(), tag, ##__VA_ARGS__); }\ - else if (level==ESP_LOG_WARN ) { esp_log_write(ESP_LOG_WARN, tag, LOG_FORMAT(W, format), esp_log_timestamp(), tag, ##__VA_ARGS__); }\ - else if (level==ESP_LOG_DEBUG ) { esp_log_write(ESP_LOG_DEBUG, tag, LOG_FORMAT(D, format), esp_log_timestamp(), tag, ##__VA_ARGS__); }\ - else if (level==ESP_LOG_VERBOSE ) { esp_log_write(ESP_LOG_VERBOSE, tag, LOG_FORMAT(V, format), esp_log_timestamp(), tag, ##__VA_ARGS__); }\ - else { esp_log_write(ESP_LOG_INFO, tag, LOG_FORMAT(I, format), esp_log_timestamp(), tag, ##__VA_ARGS__); }}while(0) +#define ESP_LOG_LEVEL(level, tag, format, ...) do { \ + if (level==ESP_LOG_ERROR ) { esp_log_write(ESP_LOG_ERROR, tag, LOG_FORMAT(E, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } \ + else if (level==ESP_LOG_WARN ) { esp_log_write(ESP_LOG_WARN, tag, LOG_FORMAT(W, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } \ + else if (level==ESP_LOG_DEBUG ) { esp_log_write(ESP_LOG_DEBUG, tag, LOG_FORMAT(D, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } \ + else if (level==ESP_LOG_VERBOSE ) { esp_log_write(ESP_LOG_VERBOSE, tag, LOG_FORMAT(V, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } \ + else { esp_log_write(ESP_LOG_INFO, tag, LOG_FORMAT(I, format), esp_log_timestamp(), tag, ##__VA_ARGS__); } \ + } while(0) /** runtime macro to output logs at a specified level. Also check the level with ``LOG_LOCAL_LEVEL``. - * + * * @see ``printf``, ``ESP_LOG_LEVEL`` */ -#define ESP_LOG_LEVEL_LOCAL(level, tag, format, ...) do {\ - if ( LOG_LOCAL_LEVEL >= level ) ESP_LOG_LEVEL(level, tag, format, ##__VA_ARGS__); } while(0); +#define ESP_LOG_LEVEL_LOCAL(level, tag, format, ...) do { \ + if ( LOG_LOCAL_LEVEL >= level ) ESP_LOG_LEVEL(level, tag, format, ##__VA_ARGS__); \ + } while(0) #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/apps/sntp/sntp.h b/tools/sdk/include/lwip/apps/sntp/sntp.h index b00869365b6..3db0fba1eba 100644 --- a/tools/sdk/include/lwip/apps/sntp/sntp.h +++ b/tools/sdk/include/lwip/apps/sntp/sntp.h @@ -1,71 +1,3 @@ -/* - * Copyright (c) 2007-2009 Frédéric Bernon, Simon Goldschmidt - * All rights reserved. - * - * 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. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Frédéric Bernon, Simon Goldschmidt - * - */ -#ifndef LWIP_HDR_APPS_SNTP_H -#define LWIP_HDR_APPS_SNTP_H - -#include "apps/sntp/sntp_opts.h" -#include "lwip/ip_addr.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* SNTP operating modes: default is to poll using unicast. - The mode has to be set before calling sntp_init(). */ -#define SNTP_OPMODE_POLL 0 -#define SNTP_OPMODE_LISTENONLY 1 -void sntp_setoperatingmode(u8_t operating_mode); -u8_t sntp_getoperatingmode(void); - -void sntp_init(void); -void sntp_stop(void); -u8_t sntp_enabled(void); - -void sntp_setserver(u8_t idx, const ip_addr_t *addr); -ip_addr_t sntp_getserver(u8_t idx); - -#if SNTP_SERVER_DNS -void sntp_setservername(u8_t idx, char *server); -char *sntp_getservername(u8_t idx); -#endif /* SNTP_SERVER_DNS */ - -#if SNTP_GET_SERVERS_FROM_DHCP -void sntp_servermode_dhcp(int set_servers_from_dhcp); -#else /* SNTP_GET_SERVERS_FROM_DHCP */ -#define sntp_servermode_dhcp(x) -#endif /* SNTP_GET_SERVERS_FROM_DHCP */ - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_HDR_APPS_SNTP_H */ +#pragma once +#warning "This header file is deprecated, please include lwip/apps/sntp.h instead." +#include "lwip/apps/sntp.h" diff --git a/tools/sdk/include/lwip/arch/sys_arch.h b/tools/sdk/include/lwip/arch/sys_arch.h index bb7ea18af73..9638fdfd621 100644 --- a/tools/sdk/include/lwip/arch/sys_arch.h +++ b/tools/sdk/include/lwip/arch/sys_arch.h @@ -1,81 +1,98 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * 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. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * - */ - -#ifndef __SYS_ARCH_H__ -#define __SYS_ARCH_H__ - -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "freertos/queue.h" -#include "freertos/semphr.h" +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef __SYS_ARCH_H__ +#define __SYS_ARCH_H__ + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" #include "arch/vfs_lwip.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef xSemaphoreHandle sys_sem_t; -typedef xSemaphoreHandle sys_mutex_t; -typedef xTaskHandle sys_thread_t; + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef xSemaphoreHandle sys_sem_t; +typedef xSemaphoreHandle sys_mutex_t; +typedef xTaskHandle sys_thread_t; typedef struct sys_mbox_s { xQueueHandle os_mbox; - sys_mutex_t lock; - uint8_t alive; + void *owner; }* sys_mbox_t; - -#define LWIP_COMPAT_MUTEX 0 - -#if !LWIP_COMPAT_MUTEX -#define sys_mutex_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) -#define sys_mutex_set_invalid( x ) ( ( *x ) = NULL ) -#endif - -#define sys_mbox_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) -#define sys_mbox_set_invalid( x ) ( ( *x ) = NULL ) - -#define sys_sem_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) -#define sys_sem_set_invalid( x ) ( ( *x ) = NULL ) - + +#define LWIP_COMPAT_MUTEX 0 + +#if !LWIP_COMPAT_MUTEX +#define sys_mutex_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_mutex_set_invalid( x ) ( ( *x ) = NULL ) +#endif + +#define sys_mbox_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) + +/* Define the sys_mbox_set_invalid() to empty to support lock-free mbox in ESP LWIP. + * + * The basic idea about the lock-free mbox is that the mbox should always be valid unless + * no socket APIs are using the socket and the socket is closed. ESP LWIP achieves this by + * following two changes to official LWIP: + * 1. Postpone the deallocation of mbox to netconn_free(), in other words, free the mbox when + * no one is using the socket. + * 2. Define the sys_mbox_set_invalid() to empty if the mbox is not actually freed. + + * The second change is necessary. Consider a common scenario: the application task calls + * recv() to receive packets from the socket, the sys_mbox_valid() returns true. Because there + * is no lock for the mbox, the LWIP CORE can call sys_mbox_set_invalid() to set the mbox at + * anytime and the thread-safe issue may happen. + * + * However, if the sys_mbox_set_invalid() is not called after sys_mbox_free(), e.g. in netconn_alloc(), + * we need to initialize the mbox to invalid explicitly since sys_mbox_set_invalid() now is empty. + */ +#define sys_mbox_set_invalid( x ) + +#define sys_sem_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_sem_set_invalid( x ) ( ( *x ) = NULL ) + void sys_delay_ms(uint32_t ms); sys_sem_t* sys_thread_sem_init(void); void sys_thread_sem_deinit(void); -sys_sem_t* sys_thread_sem_get(void); - -#ifdef __cplusplus -} -#endif - -#endif /* __SYS_ARCH_H__ */ - +sys_sem_t* sys_thread_sem_get(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __SYS_ARCH_H__ */ + diff --git a/tools/sdk/include/lwip/arch/vfs_lwip.h b/tools/sdk/include/lwip/arch/vfs_lwip.h index 88714b03b9f..1957304b9f2 100644 --- a/tools/sdk/include/lwip/arch/vfs_lwip.h +++ b/tools/sdk/include/lwip/arch/vfs_lwip.h @@ -16,11 +16,6 @@ extern "C" { #endif -/* Internal declarations used to ingreate LWIP port layer - to ESP-IDF VFS for POSIX I/O. -*/ -extern int lwip_socket_offset; - void esp_vfs_lwip_sockets_register(); #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/arpa/inet.h b/tools/sdk/include/lwip/arpa/inet.h index 94c6c17ed5a..90428f687d7 100644 --- a/tools/sdk/include/lwip/arpa/inet.h +++ b/tools/sdk/include/lwip/arpa/inet.h @@ -15,6 +15,6 @@ #ifndef INET_H_ #define INET_H_ -#include "lwip/inet.h" +#include "../../../lwip/src/include/lwip/inet.h" #endif /* INET_H_ */ diff --git a/tools/sdk/include/lwip/cc.h b/tools/sdk/include/lwip/cc.h new file mode 100644 index 00000000000..cba0b365ea2 --- /dev/null +++ b/tools/sdk/include/lwip/cc.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __ARCH_CC_H__ +#define __ARCH_CC_H__ + +#include +#include +#include +#include + +#include "arch/sys_arch.h" + +#define BYTE_ORDER LITTLE_ENDIAN + +typedef uint8_t u8_t; +typedef int8_t s8_t; +typedef uint16_t u16_t; +typedef int16_t s16_t; +typedef uint32_t u32_t; +typedef int32_t s32_t; + +typedef unsigned long mem_ptr_t; +typedef int sys_prot_t; + +#define S16_F "d" +#define U16_F "d" +#define X16_F "x" + +#define S32_F "d" +#define U32_F "d" +#define X32_F "x" + +#define PACK_STRUCT_FIELD(x) x +#define PACK_STRUCT_STRUCT __attribute__((packed)) +#define PACK_STRUCT_BEGIN +#define PACK_STRUCT_END + +#include + +#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0) +// __assert_func is the assertion failure handler from newlib, defined in assert.h +#define LWIP_PLATFORM_ASSERT(message) __assert_func(__FILE__, __LINE__, __ASSERT_FUNC, message) + +#ifdef NDEBUG +#define LWIP_NOASSERT +#else // Assertions enabled + +// If assertions are on, the default LWIP_ERROR handler behaviour is to +// abort w/ an assertion failure. Don't do this, instead just print the error (if LWIP_DEBUG is set) +// and run the handler (same as the LWIP_ERROR behaviour if LWIP_NOASSERT is set). +#ifdef LWIP_DEBUG +#define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ + puts(message); handler;}} while(0) +#else +// If LWIP_DEBUG is not set, return the error silently (default LWIP behaviour, also.) +#define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ + handler;}} while(0) +#endif // LWIP_DEBUG + +#endif /* NDEBUG */ + + +#endif /* __ARCH_CC_H__ */ diff --git a/tools/sdk/include/lwip/lwip/lwip_debug.h b/tools/sdk/include/lwip/debug/lwip_debug.h similarity index 100% rename from tools/sdk/include/lwip/lwip/lwip_debug.h rename to tools/sdk/include/lwip/debug/lwip_debug.h diff --git a/tools/sdk/include/lwip/apps/dhcpserver.h b/tools/sdk/include/lwip/dhcpserver/dhcpserver.h similarity index 96% rename from tools/sdk/include/lwip/apps/dhcpserver.h rename to tools/sdk/include/lwip/dhcpserver/dhcpserver.h index 015ffe6e098..a6ad51d9957 100644 --- a/tools/sdk/include/lwip/apps/dhcpserver.h +++ b/tools/sdk/include/lwip/dhcpserver/dhcpserver.h @@ -70,6 +70,8 @@ typedef struct { dhcps_lease_t dhcps_poll; } dhcps_options_t; +typedef void (*dhcps_cb_t)(u8_t client_ip[4]); + static inline bool dhcps_router_enabled (dhcps_offer_t offer) { return (offer & OFFER_ROUTER) != 0; @@ -87,6 +89,7 @@ void dhcps_set_option_info(u8_t op_id, void *opt_info, u32_t opt_len); bool dhcp_search_ip_on_mac(u8_t *mac, ip4_addr_t *ip); void dhcps_dns_setserver(const ip_addr_t *dnsserver); ip4_addr_t dhcps_dns_getserver(); +void dhcps_set_new_lease_cb(dhcps_cb_t cb); #endif diff --git a/tools/sdk/include/lwip/apps/dhcpserver_options.h b/tools/sdk/include/lwip/dhcpserver/dhcpserver_options.h similarity index 100% rename from tools/sdk/include/lwip/apps/dhcpserver_options.h rename to tools/sdk/include/lwip/dhcpserver/dhcpserver_options.h diff --git a/tools/sdk/include/lwip/esp_ping.h b/tools/sdk/include/lwip/esp_ping.h new file mode 100644 index 00000000000..9abb883c233 --- /dev/null +++ b/tools/sdk/include/lwip/esp_ping.h @@ -0,0 +1,111 @@ +// 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_PING_H_ +#define ESP_PING_H_ + +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// gen_esp_err_to_name.py: include this as "esp_ping.h" because "components/lwip/include/apps/" is in the compiler path +// and not "components/lwip/include" + +#define ESP_ERR_PING_BASE 0x6000 + +#define ESP_ERR_PING_INVALID_PARAMS ESP_ERR_PING_BASE + 0x01 +#define ESP_ERR_PING_NO_MEM ESP_ERR_PING_BASE + 0x02 + +#define ESP_PING_CHECK_OPTLEN(optlen, opttype) do { if ((optlen) < sizeof(opttype)) { return ESP_ERR_PING_INVALID_PARAMS; }}while(0) + +typedef struct _ping_found { + uint32_t resp_time; + uint32_t timeout_count; + uint32_t send_count; + uint32_t recv_count; + uint32_t err_count; + uint32_t bytes; + uint32_t total_bytes; + uint32_t total_time; + uint32_t min_time; + uint32_t max_time; + int8_t ping_err; +} esp_ping_found; + +typedef enum { + PING_TARGET_IP_ADDRESS = 50, /**< target IP address */ + PING_TARGET_IP_ADDRESS_COUNT = 51, /**< target IP address total counter */ + PING_TARGET_RCV_TIMEO = 52, /**< receive timeout in milliseconds */ + PING_TARGET_DELAY_TIME = 53, /**< delay time in milliseconds */ + PING_TARGET_ID = 54, /**< identifier */ + PING_TARGET_RES_FN = 55, /**< ping result callback function */ + PING_TARGET_RES_RESET = 56, /**< ping result statistic reset */ + PING_TARGET_DATA_LEN = 57, /**< ping data length*/ + PING_TARGET_IP_TOS = 58 /**< ping QOS*/ +} ping_target_id_t; + +typedef enum { + PING_RES_TIMEOUT = 0, + PING_RES_OK = 1, + PING_RES_FINISH = 2, +} ping_res_t; + +typedef void (* esp_ping_found_fn)(ping_target_id_t found_id, esp_ping_found *found_val); + +/** + * @brief Set PING function option + * + * @param[in] opt_id: option index, 50 for IP, 51 for COUNT, 52 for RCV TIMEOUT, 53 for DELAY TIME, 54 for ID + * @param[in] opt_val: option parameter + * @param[in] opt_len: option length + * + * @return + * - ESP_OK + * - ESP_ERR_PING_INVALID_PARAMS + */ +esp_err_t esp_ping_set_target(ping_target_id_t opt_id, void *opt_val, uint32_t opt_len); + +/** + * @brief Get PING function option + * + * @param[in] opt_id: option index, 50 for IP, 51 for COUNT, 52 for RCV TIMEOUT, 53 for DELAY TIME, 54 for ID + * @param[in] opt_val: option parameter + * @param[in] opt_len: option length + * + * @return + * - ESP_OK + * - ESP_ERR_PING_INVALID_PARAMS + */ +esp_err_t esp_ping_get_target(ping_target_id_t opt_id, void *opt_val, uint32_t opt_len); + +/** + * @brief Get PING function result action + * + * @param[in] res_val: ping function action, 1 for successful, 0 for fail. + * res_len: response bytes + * res_time: response time + * + * @return + * - ESP_OK + * - ESP_ERR_PING_INVALID_PARAMS + */ +esp_err_t esp_ping_result(uint8_t res_val, uint16_t res_len, uint32_t res_time); + +#ifdef __cplusplus +} +#endif + +#endif /* ESP_PING_H_ */ diff --git a/tools/sdk/include/lwip/lwip/api.h b/tools/sdk/include/lwip/lwip/api.h old mode 100755 new mode 100644 index 5b6a21ecf38..a4fed9bbfbf --- a/tools/sdk/include/lwip/lwip/api.h +++ b/tools/sdk/include/lwip/lwip/api.h @@ -1,3 +1,8 @@ +/** + * @file + * netconn API (to be used from non-TCPIP threads) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,8 +43,7 @@ /* Note: Netconn API is always available when sockets are enabled - * sockets are implemented on top of them */ -#include /* for size_t */ - +#include "lwip/arch.h" #include "lwip/netbuf.h" #include "lwip/sys.h" #include "lwip/ip_addr.h" @@ -65,9 +69,11 @@ extern "C" { #define NETCONN_FLAG_NON_BLOCKING 0x02 /** Was the last connect action a non-blocking one? */ #define NETCONN_FLAG_IN_NONBLOCKING_CONNECT 0x04 +#if ESP_AUTO_RECV /** If this is set, a TCP netconn must call netconn_recved() to update the TCP receive window (done automatically if not set). */ #define NETCONN_FLAG_NO_AUTO_RECVED 0x08 +#endif /** If a nonblocking write has been rejected before, poll_tcp needs to check if the netconn is writable again */ #define NETCONN_FLAG_CHECK_WRITESPACE 0x10 @@ -79,7 +85,7 @@ extern "C" { #endif /* LWIP_IPV6 */ - /* Helpers to process several netconn_types by the same code */ +/* Helpers to process several netconn_types by the same code */ #define NETCONNTYPE_GROUP(t) ((t)&0xF0) #define NETCONNTYPE_DATAGRAM(t) ((t)&0xE0) #if LWIP_IPV6 @@ -88,32 +94,42 @@ extern "C" { #define NETCONNTYPE_ISUDPLITE(t) (((t)&0xF3) == NETCONN_UDPLITE) #define NETCONNTYPE_ISUDPNOCHKSUM(t) (((t)&0xF3) == NETCONN_UDPNOCHKSUM) #else /* LWIP_IPV6 */ +#define NETCONNTYPE_ISIPV6(t) (0) #define NETCONNTYPE_ISUDPLITE(t) ((t) == NETCONN_UDPLITE) #define NETCONNTYPE_ISUDPNOCHKSUM(t) ((t) == NETCONN_UDPNOCHKSUM) #endif /* LWIP_IPV6 */ -/** Protocol family and type of the netconn */ +/** @ingroup netconn_common + * Protocol family and type of the netconn + */ enum netconn_type { NETCONN_INVALID = 0, - /* NETCONN_TCP Group */ + /** TCP IPv4 */ NETCONN_TCP = 0x10, #if LWIP_IPV6 + /** TCP IPv6 */ NETCONN_TCP_IPV6 = NETCONN_TCP | NETCONN_TYPE_IPV6 /* 0x18 */, #endif /* LWIP_IPV6 */ - /* NETCONN_UDP Group */ + /** UDP IPv4 */ NETCONN_UDP = 0x20, + /** UDP IPv4 lite */ NETCONN_UDPLITE = 0x21, + /** UDP IPv4 no checksum */ NETCONN_UDPNOCHKSUM = 0x22, #if LWIP_IPV6 + /** UDP IPv6 (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ NETCONN_UDP_IPV6 = NETCONN_UDP | NETCONN_TYPE_IPV6 /* 0x28 */, + /** UDP IPv6 lite (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ NETCONN_UDPLITE_IPV6 = NETCONN_UDPLITE | NETCONN_TYPE_IPV6 /* 0x29 */, + /** UDP IPv6 no checksum (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ NETCONN_UDPNOCHKSUM_IPV6 = NETCONN_UDPNOCHKSUM | NETCONN_TYPE_IPV6 /* 0x2a */, #endif /* LWIP_IPV6 */ - /* NETCONN_RAW Group */ + /** Raw connection IPv4 */ NETCONN_RAW = 0x40 #if LWIP_IPV6 + /** Raw connection IPv6 (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ , NETCONN_RAW_IPV6 = NETCONN_RAW | NETCONN_TYPE_IPV6 /* 0x48 */ #endif /* LWIP_IPV6 */ }; @@ -128,7 +144,32 @@ enum netconn_state { NETCONN_CLOSE }; -/** Use to inform the callback function about changes */ +/** Used to inform the callback function about changes + * + * Event explanation: + * + * In the netconn implementation, there are three ways to block a client: + * + * - accept mbox (sys_arch_mbox_fetch(&conn->acceptmbox, &accept_ptr, 0); in netconn_accept()) + * - receive mbox (sys_arch_mbox_fetch(&conn->recvmbox, &buf, 0); in netconn_recv_data()) + * - send queue is full (sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); in lwip_netconn_do_write()) + * + * The events have to be seen as events signaling the state of these mboxes/semaphores. For non-blocking + * connections, you need to know in advance whether a call to a netconn function call would block or not, + * and these events tell you about that. + * + * RCVPLUS events say: Safe to perform a potentially blocking call call once more. + * They are counted in sockets - three RCVPLUS events for accept mbox means you are safe + * to call netconn_accept 3 times without being blocked. + * Same thing for receive mbox. + * + * RCVMINUS events say: Your call to to a possibly blocking function is "acknowledged". + * Socket implementation decrements the counter. + * + * For TX, there is no need to count, its merely a flag. SENDPLUS means you may send something. + * SENDPLUS occurs when enough data was delivered to peer so netconn_send() can be called again. + * A SENDMINUS event occurs when the next call to a netconn_send() would be blocking. + */ enum netconn_evt { NETCONN_EVT_RCVPLUS, NETCONN_EVT_RCVMINUS, @@ -160,7 +201,7 @@ struct tcp_pcb; struct udp_pcb; struct raw_pcb; struct netconn; -struct api_msg_msg; +struct api_msg; /** A callback prototype to inform about events for a netconn */ typedef void (* netconn_callback)(struct netconn *, enum netconn_evt, u16_t len); @@ -180,13 +221,10 @@ struct netconn { } pcb; /** the last error this netconn had */ err_t last_err; - #if !LWIP_NETCONN_SEM_PER_THREAD /** sem that is used to synchronously execute functions in the core context */ sys_sem_t op_completed; - #endif - /** mbox where received packets are stored until they are fetched by the netconn application thread (can grow quite big) */ sys_mbox_t recvmbox; @@ -231,7 +269,7 @@ struct netconn { /** TCP: when data passed to netconn_write doesn't fit into the send buffer, this temporarily stores the message. Also used during connect and close. */ - struct api_msg_msg *current_msg; + struct api_msg *current_msg; #endif /* LWIP_TCP */ /** A callback function that is informed about events for this netconn */ netconn_callback callback; @@ -253,6 +291,10 @@ struct netconn { }} while(0); /* Network connection functions: */ + +/** @ingroup netconn_common + * Create new netconn connection + * @param t @ref netconn_type */ #define netconn_new(t) netconn_new_with_proto_and_callback(t, 0, NULL) #define netconn_new_with_callback(t, c) netconn_new_with_proto_and_callback(t, 0, c) struct netconn *netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto, @@ -263,23 +305,29 @@ err_t netconn_delete(struct netconn *conn); err_t netconn_getaddr(struct netconn *conn, ip_addr_t *addr, u16_t *port, u8_t local); +/** @ingroup netconn_common */ #define netconn_peer(c,i,p) netconn_getaddr(c,i,p,0) +/** @ingroup netconn_common */ #define netconn_addr(c,i,p) netconn_getaddr(c,i,p,1) err_t netconn_bind(struct netconn *conn, const ip_addr_t *addr, u16_t port); err_t netconn_connect(struct netconn *conn, const ip_addr_t *addr, u16_t port); err_t netconn_disconnect (struct netconn *conn); err_t netconn_listen_with_backlog(struct netconn *conn, u8_t backlog); +/** @ingroup netconn_tcp */ #define netconn_listen(conn) netconn_listen_with_backlog(conn, TCP_DEFAULT_LISTEN_BACKLOG) err_t netconn_accept(struct netconn *conn, struct netconn **new_conn); err_t netconn_recv(struct netconn *conn, struct netbuf **new_buf); err_t netconn_recv_tcp_pbuf(struct netconn *conn, struct pbuf **new_buf); +#if ESP_AUTO_RECV void netconn_recved(struct netconn *conn, u32_t length); +#endif err_t netconn_sendto(struct netconn *conn, struct netbuf *buf, const ip_addr_t *addr, u16_t port); err_t netconn_send(struct netconn *conn, struct netbuf *buf); err_t netconn_write_partly(struct netconn *conn, const void *dataptr, size_t size, u8_t apiflags, size_t *bytes_written); +/** @ingroup netconn_tcp */ #define netconn_write(conn, dataptr, size, apiflags) \ netconn_write_partly(conn, dataptr, size, apiflags, NULL) err_t netconn_close(struct netconn *conn); @@ -310,6 +358,7 @@ err_t netconn_gethostbyname(const char *name, ip_addr_t *addr); /** Get the blocking status of netconn calls (@todo: write/send is missing) */ #define netconn_is_nonblocking(conn) (((conn)->flags & NETCONN_FLAG_NON_BLOCKING) != 0) +#if ESP_AUTO_RECV /** TCP: Set the no-auto-recved status of netconn calls (see NETCONN_FLAG_NO_AUTO_RECVED) */ #define netconn_set_noautorecved(conn, val) do { if(val) { \ (conn)->flags |= NETCONN_FLAG_NO_AUTO_RECVED; \ @@ -317,14 +366,19 @@ err_t netconn_gethostbyname(const char *name, ip_addr_t *addr); (conn)->flags &= ~ NETCONN_FLAG_NO_AUTO_RECVED; }} while(0) /** TCP: Get the no-auto-recved status of netconn calls (see NETCONN_FLAG_NO_AUTO_RECVED) */ #define netconn_get_noautorecved(conn) (((conn)->flags & NETCONN_FLAG_NO_AUTO_RECVED) != 0) +#endif #if LWIP_IPV6 -/** TCP: Set the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) */ +/** @ingroup netconn_common + * TCP: Set the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) + */ #define netconn_set_ipv6only(conn, val) do { if(val) { \ (conn)->flags |= NETCONN_FLAG_IPV6_V6ONLY; \ } else { \ (conn)->flags &= ~ NETCONN_FLAG_IPV6_V6ONLY; }} while(0) -/** TCP: Get the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) */ +/** @ingroup netconn_common + * TCP: Get the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) + */ #define netconn_get_ipv6only(conn) (((conn)->flags & NETCONN_FLAG_IPV6_V6ONLY) != 0) #endif /* LWIP_IPV6 */ diff --git a/tools/sdk/include/lwip/lwip/apps/fs.h b/tools/sdk/include/lwip/lwip/apps/fs.h new file mode 100644 index 00000000000..bb176fa0107 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/fs.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_APPS_FS_H +#define LWIP_HDR_APPS_FS_H + +#include "httpd_opts.h" +#include "lwip/err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define FS_READ_EOF -1 +#define FS_READ_DELAYED -2 + +#if HTTPD_PRECALCULATED_CHECKSUM +struct fsdata_chksum { + u32_t offset; + u16_t chksum; + u16_t len; +}; +#endif /* HTTPD_PRECALCULATED_CHECKSUM */ + +#define FS_FILE_FLAGS_HEADER_INCLUDED 0x01 +#define FS_FILE_FLAGS_HEADER_PERSISTENT 0x02 + +struct fs_file { + const char *data; + int len; + int index; + void *pextension; +#if HTTPD_PRECALCULATED_CHECKSUM + const struct fsdata_chksum *chksum; + u16_t chksum_count; +#endif /* HTTPD_PRECALCULATED_CHECKSUM */ + u8_t flags; +#if LWIP_HTTPD_CUSTOM_FILES + u8_t is_custom_file; +#endif /* LWIP_HTTPD_CUSTOM_FILES */ +#if LWIP_HTTPD_FILE_STATE + void *state; +#endif /* LWIP_HTTPD_FILE_STATE */ +}; + +#if LWIP_HTTPD_FS_ASYNC_READ +typedef void (*fs_wait_cb)(void *arg); +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ + +err_t fs_open(struct fs_file *file, const char *name); +void fs_close(struct fs_file *file); +#if LWIP_HTTPD_DYNAMIC_FILE_READ +#if LWIP_HTTPD_FS_ASYNC_READ +int fs_read_async(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg); +#else /* LWIP_HTTPD_FS_ASYNC_READ */ +int fs_read(struct fs_file *file, char *buffer, int count); +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ +#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ +#if LWIP_HTTPD_FS_ASYNC_READ +int fs_is_file_ready(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg); +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ +int fs_bytes_left(struct fs_file *file); + +#if LWIP_HTTPD_FILE_STATE +/** This user-defined function is called when a file is opened. */ +void *fs_state_init(struct fs_file *file, const char *name); +/** This user-defined function is called when a file is closed. */ +void fs_state_free(struct fs_file *file, void *state); +#endif /* #if LWIP_HTTPD_FILE_STATE */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_FS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/httpd.h b/tools/sdk/include/lwip/lwip/apps/httpd.h new file mode 100644 index 00000000000..40f1811e574 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/httpd.h @@ -0,0 +1,236 @@ +/** + * @file + * HTTP server + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * This version of the file has been modified by Texas Instruments to offer + * simple server-side-include (SSI) and Common Gateway Interface (CGI) + * capability. + */ + +#ifndef LWIP_HDR_APPS_HTTPD_H +#define LWIP_HDR_APPS_HTTPD_H + +#include "httpd_opts.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_HTTPD_CGI + +/* + * Function pointer for a CGI script handler. + * + * This function is called each time the HTTPD server is asked for a file + * whose name was previously registered as a CGI function using a call to + * http_set_cgi_handler. The iIndex parameter provides the index of the + * CGI within the ppcURLs array passed to http_set_cgi_handler. Parameters + * pcParam and pcValue provide access to the parameters provided along with + * the URI. iNumParams provides a count of the entries in the pcParam and + * pcValue arrays. Each entry in the pcParam array contains the name of a + * parameter with the corresponding entry in the pcValue array containing the + * value for that parameter. Note that pcParam may contain multiple elements + * with the same name if, for example, a multi-selection list control is used + * in the form generating the data. + * + * The function should return a pointer to a character string which is the + * path and filename of the response that is to be sent to the connected + * browser, for example "/thanks.htm" or "/response/error.ssi". + * + * The maximum number of parameters that will be passed to this function via + * iNumParams is defined by LWIP_HTTPD_MAX_CGI_PARAMETERS. Any parameters in the incoming + * HTTP request above this number will be discarded. + * + * Requests intended for use by this CGI mechanism must be sent using the GET + * method (which encodes all parameters within the URI rather than in a block + * later in the request). Attempts to use the POST method will result in the + * request being ignored. + * + */ +typedef const char *(*tCGIHandler)(int iIndex, int iNumParams, char *pcParam[], + char *pcValue[]); + +/* + * Structure defining the base filename (URL) of a CGI and the associated + * function which is to be called when that URL is requested. + */ +typedef struct +{ + const char *pcCGIName; + tCGIHandler pfnCGIHandler; +} tCGI; + +void http_set_cgi_handlers(const tCGI *pCGIs, int iNumHandlers); + +#endif /* LWIP_HTTPD_CGI */ + +#if LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI + +#if LWIP_HTTPD_CGI_SSI +/** Define this generic CGI handler in your application. + * It is called once for every URI with parameters. + * The parameters can be stored to + */ +extern void httpd_cgi_handler(const char* uri, int iNumParams, char **pcParam, char **pcValue +#if defined(LWIP_HTTPD_FILE_STATE) && LWIP_HTTPD_FILE_STATE + , void *connection_state +#endif /* LWIP_HTTPD_FILE_STATE */ + ); +#endif /* LWIP_HTTPD_CGI_SSI */ + +#endif /* LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI */ + +#if LWIP_HTTPD_SSI + +/* + * Function pointer for the SSI tag handler callback. + * + * This function will be called each time the HTTPD server detects a tag of the + * form in a .shtml, .ssi or .shtm file where "name" appears as + * one of the tags supplied to http_set_ssi_handler in the ppcTags array. The + * returned insert string, which will be appended after the the string + * "" in file sent back to the client,should be written to pointer + * pcInsert. iInsertLen contains the size of the buffer pointed to by + * pcInsert. The iIndex parameter provides the zero-based index of the tag as + * found in the ppcTags array and identifies the tag that is to be processed. + * + * The handler returns the number of characters written to pcInsert excluding + * any terminating NULL or a negative number to indicate a failure (tag not + * recognized, for example). + * + * Note that the behavior of this SSI mechanism is somewhat different from the + * "normal" SSI processing as found in, for example, the Apache web server. In + * this case, the inserted text is appended following the SSI tag rather than + * replacing the tag entirely. This allows for an implementation that does not + * require significant additional buffering of output data yet which will still + * offer usable SSI functionality. One downside to this approach is when + * attempting to use SSI within JavaScript. The SSI tag is structured to + * resemble an HTML comment but this syntax does not constitute a comment + * within JavaScript and, hence, leaving the tag in place will result in + * problems in these cases. To work around this, any SSI tag which needs to + * output JavaScript code must do so in an encapsulated way, sending the whole + * HTML section as a single include. + */ +typedef u16_t (*tSSIHandler)( +#if LWIP_HTTPD_SSI_RAW + const char* ssi_tag_name, +#else /* LWIP_HTTPD_SSI_RAW */ + int iIndex, +#endif /* LWIP_HTTPD_SSI_RAW */ + char *pcInsert, int iInsertLen +#if LWIP_HTTPD_SSI_MULTIPART + , u16_t current_tag_part, u16_t *next_tag_part +#endif /* LWIP_HTTPD_SSI_MULTIPART */ +#if defined(LWIP_HTTPD_FILE_STATE) && LWIP_HTTPD_FILE_STATE + , void *connection_state +#endif /* LWIP_HTTPD_FILE_STATE */ + ); + +/** Set the SSI handler function + * (if LWIP_HTTPD_SSI_RAW==1, only the first argument is used) + */ +void http_set_ssi_handler(tSSIHandler pfnSSIHandler, + const char **ppcTags, int iNumTags); + +/** For LWIP_HTTPD_SSI_RAW==1, return this to indicate the tag is unknown. + * In this case, the webserver writes a warning into the page. + * You can also just return 0 to write nothing for unknown tags. + */ +#define HTTPD_SSI_TAG_UNKNOWN 0xFFFF + +#endif /* LWIP_HTTPD_SSI */ + +#if LWIP_HTTPD_SUPPORT_POST + +/* These functions must be implemented by the application */ + +/** Called when a POST request has been received. The application can decide + * whether to accept it or not. + * + * @param connection Unique connection identifier, valid until httpd_post_end + * is called. + * @param uri The HTTP header URI receiving the POST request. + * @param http_request The raw HTTP request (the first packet, normally). + * @param http_request_len Size of 'http_request'. + * @param content_len Content-Length from HTTP header. + * @param response_uri Filename of response file, to be filled when denying the + * request + * @param response_uri_len Size of the 'response_uri' buffer. + * @param post_auto_wnd Set this to 0 to let the callback code handle window + * updates by calling 'httpd_post_data_recved' (to throttle rx speed) + * default is 1 (httpd handles window updates automatically) + * @return ERR_OK: Accept the POST request, data may be passed in + * another err_t: Deny the POST request, send back 'bad request'. + */ +err_t httpd_post_begin(void *connection, const char *uri, const char *http_request, + u16_t http_request_len, int content_len, char *response_uri, + u16_t response_uri_len, u8_t *post_auto_wnd); + +/** Called for each pbuf of data that has been received for a POST. + * ATTENTION: The application is responsible for freeing the pbufs passed in! + * + * @param connection Unique connection identifier. + * @param p Received data. + * @return ERR_OK: Data accepted. + * another err_t: Data denied, http_post_get_response_uri will be called. + */ +err_t httpd_post_receive_data(void *connection, struct pbuf *p); + +/** Called when all data is received or when the connection is closed. + * The application must return the filename/URI of a file to send in response + * to this POST request. If the response_uri buffer is untouched, a 404 + * response is returned. + * + * @param connection Unique connection identifier. + * @param response_uri Filename of response file, to be filled when denying the request + * @param response_uri_len Size of the 'response_uri' buffer. + */ +void httpd_post_finished(void *connection, char *response_uri, u16_t response_uri_len); + +#if LWIP_HTTPD_POST_MANUAL_WND +void httpd_post_data_recved(void *connection, u16_t recved_len); +#endif /* LWIP_HTTPD_POST_MANUAL_WND */ + +#endif /* LWIP_HTTPD_SUPPORT_POST */ + +void httpd_init(void); + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HTTPD_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/httpd_opts.h b/tools/sdk/include/lwip/lwip/apps/httpd_opts.h new file mode 100644 index 00000000000..340db15f663 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/httpd_opts.h @@ -0,0 +1,323 @@ +/** + * @file + * HTTP server options list + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * This version of the file has been modified by Texas Instruments to offer + * simple server-side-include (SSI) and Common Gateway Interface (CGI) + * capability. + */ + +#ifndef LWIP_HDR_APPS_HTTPD_OPTS_H +#define LWIP_HDR_APPS_HTTPD_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup httpd_opts Options + * @ingroup httpd + * @{ + */ + +/** Set this to 1 to support CGI (old style) */ +#if !defined LWIP_HTTPD_CGI || defined __DOXYGEN__ +#define LWIP_HTTPD_CGI 0 +#endif + +/** Set this to 1 to support CGI (new style) */ +#if !defined LWIP_HTTPD_CGI_SSI || defined __DOXYGEN__ +#define LWIP_HTTPD_CGI_SSI 0 +#endif + +/** Set this to 1 to support SSI (Server-Side-Includes) */ +#if !defined LWIP_HTTPD_SSI || defined __DOXYGEN__ +#define LWIP_HTTPD_SSI 0 +#endif + +/** Set this to 1 to implement an SSI tag handler callback that gets a const char* + * to the tag (instead of an index into a pre-registered array of known tags) */ +#if !defined LWIP_HTTPD_SSI_RAW || defined __DOXYGEN__ +#define LWIP_HTTPD_SSI_RAW 0 +#endif + +/** Set this to 1 to support HTTP POST */ +#if !defined LWIP_HTTPD_SUPPORT_POST || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_POST 0 +#endif + +/* The maximum number of parameters that the CGI handler can be sent. */ +#if !defined LWIP_HTTPD_MAX_CGI_PARAMETERS || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_CGI_PARAMETERS 16 +#endif + +/** LWIP_HTTPD_SSI_MULTIPART==1: SSI handler function is called with 2 more + * arguments indicating a counter for insert string that are too long to be + * inserted at once: the SSI handler function must then set 'next_tag_part' + * which will be passed back to it in the next call. */ +#if !defined LWIP_HTTPD_SSI_MULTIPART || defined __DOXYGEN__ +#define LWIP_HTTPD_SSI_MULTIPART 0 +#endif + +/* The maximum length of the string comprising the tag name */ +#if !defined LWIP_HTTPD_MAX_TAG_NAME_LEN || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_TAG_NAME_LEN 8 +#endif + +/* The maximum length of string that can be returned to replace any given tag */ +#if !defined LWIP_HTTPD_MAX_TAG_INSERT_LEN || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_TAG_INSERT_LEN 192 +#endif + +#if !defined LWIP_HTTPD_POST_MANUAL_WND || defined __DOXYGEN__ +#define LWIP_HTTPD_POST_MANUAL_WND 0 +#endif + +/** This string is passed in the HTTP header as "Server: " */ +#if !defined HTTPD_SERVER_AGENT || defined __DOXYGEN__ +#define HTTPD_SERVER_AGENT "lwIP/" LWIP_VERSION_STRING " (http://savannah.nongnu.org/projects/lwip)" +#endif + +/** Set this to 1 if you want to include code that creates HTTP headers + * at runtime. Default is off: HTTP headers are then created statically + * by the makefsdata tool. Static headers mean smaller code size, but + * the (readonly) fsdata will grow a bit as every file includes the HTTP + * header. */ +#if !defined LWIP_HTTPD_DYNAMIC_HEADERS || defined __DOXYGEN__ +#define LWIP_HTTPD_DYNAMIC_HEADERS 0 +#endif + +#if !defined HTTPD_DEBUG || defined __DOXYGEN__ +#define HTTPD_DEBUG LWIP_DBG_OFF +#endif + +/** Set this to 1 to use a memp pool for allocating + * struct http_state instead of the heap. + */ +#if !defined HTTPD_USE_MEM_POOL || defined __DOXYGEN__ +#define HTTPD_USE_MEM_POOL 0 +#endif + +/** The server port for HTTPD to use */ +#if !defined HTTPD_SERVER_PORT || defined __DOXYGEN__ +#define HTTPD_SERVER_PORT 80 +#endif + +/** Maximum retries before the connection is aborted/closed. + * - number of times pcb->poll is called -> default is 4*500ms = 2s; + * - reset when pcb->sent is called + */ +#if !defined HTTPD_MAX_RETRIES || defined __DOXYGEN__ +#define HTTPD_MAX_RETRIES 4 +#endif + +/** The poll delay is X*500ms */ +#if !defined HTTPD_POLL_INTERVAL || defined __DOXYGEN__ +#define HTTPD_POLL_INTERVAL 4 +#endif + +/** Priority for tcp pcbs created by HTTPD (very low by default). + * Lower priorities get killed first when running out of memory. + */ +#if !defined HTTPD_TCP_PRIO || defined __DOXYGEN__ +#define HTTPD_TCP_PRIO TCP_PRIO_MIN +#endif + +/** Set this to 1 to enable timing each file sent */ +#if !defined LWIP_HTTPD_TIMING || defined __DOXYGEN__ +#define LWIP_HTTPD_TIMING 0 +#endif +/** Set this to 1 to enable timing each file sent */ +#if !defined HTTPD_DEBUG_TIMING || defined __DOXYGEN__ +#define HTTPD_DEBUG_TIMING LWIP_DBG_OFF +#endif + +/** Set this to one to show error pages when parsing a request fails instead + of simply closing the connection. */ +#if !defined LWIP_HTTPD_SUPPORT_EXTSTATUS || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_EXTSTATUS 0 +#endif + +/** Set this to 0 to drop support for HTTP/0.9 clients (to save some bytes) */ +#if !defined LWIP_HTTPD_SUPPORT_V09 || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_V09 1 +#endif + +/** Set this to 1 to enable HTTP/1.1 persistent connections. + * ATTENTION: If the generated file system includes HTTP headers, these must + * include the "Connection: keep-alive" header (pass argument "-11" to makefsdata). + */ +#if !defined LWIP_HTTPD_SUPPORT_11_KEEPALIVE || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_11_KEEPALIVE 0 +#endif + +/** Set this to 1 to support HTTP request coming in in multiple packets/pbufs */ +#if !defined LWIP_HTTPD_SUPPORT_REQUESTLIST || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_REQUESTLIST 1 +#endif + +#if LWIP_HTTPD_SUPPORT_REQUESTLIST +/** Number of rx pbufs to enqueue to parse an incoming request (up to the first + newline) */ +#if !defined LWIP_HTTPD_REQ_QUEUELEN || defined __DOXYGEN__ +#define LWIP_HTTPD_REQ_QUEUELEN 5 +#endif + +/** Number of (TCP payload-) bytes (in pbufs) to enqueue to parse and incoming + request (up to the first double-newline) */ +#if !defined LWIP_HTTPD_REQ_BUFSIZE || defined __DOXYGEN__ +#define LWIP_HTTPD_REQ_BUFSIZE LWIP_HTTPD_MAX_REQ_LENGTH +#endif + +/** Defines the maximum length of a HTTP request line (up to the first CRLF, + copied from pbuf into this a global buffer when pbuf- or packet-queues + are received - otherwise the input pbuf is used directly) */ +#if !defined LWIP_HTTPD_MAX_REQ_LENGTH || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_REQ_LENGTH LWIP_MIN(1023, (LWIP_HTTPD_REQ_QUEUELEN * PBUF_POOL_BUFSIZE)) +#endif +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + +/** This is the size of a static buffer used when URIs end with '/'. + * In this buffer, the directory requested is concatenated with all the + * configured default file names. + * Set to 0 to disable checking default filenames on non-root directories. + */ +#if !defined LWIP_HTTPD_MAX_REQUEST_URI_LEN || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_REQUEST_URI_LEN 63 +#endif + +/** Maximum length of the filename to send as response to a POST request, + * filled in by the application when a POST is finished. + */ +#if !defined LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN || defined __DOXYGEN__ +#define LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN 63 +#endif + +/** Set this to 0 to not send the SSI tag (default is on, so the tag will + * be sent in the HTML page */ +#if !defined LWIP_HTTPD_SSI_INCLUDE_TAG || defined __DOXYGEN__ +#define LWIP_HTTPD_SSI_INCLUDE_TAG 1 +#endif + +/** Set this to 1 to call tcp_abort when tcp_close fails with memory error. + * This can be used to prevent consuming all memory in situations where the + * HTTP server has low priority compared to other communication. */ +#if !defined LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR || defined __DOXYGEN__ +#define LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR 0 +#endif + +/** Set this to 1 to kill the oldest connection when running out of + * memory for 'struct http_state' or 'struct http_ssi_state'. + * ATTENTION: This puts all connections on a linked list, so may be kind of slow. + */ +#if !defined LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED || defined __DOXYGEN__ +#define LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED 0 +#endif + +/** Set this to 1 to send URIs without extension without headers + * (who uses this at all??) */ +#if !defined LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI || defined __DOXYGEN__ +#define LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI 0 +#endif + +/** Default: Tags are sent from struct http_state and are therefore volatile */ +#if !defined HTTP_IS_TAG_VOLATILE || defined __DOXYGEN__ +#define HTTP_IS_TAG_VOLATILE(ptr) TCP_WRITE_FLAG_COPY +#endif + +/* By default, the httpd is limited to send 2*pcb->mss to keep resource usage low + when http is not an important protocol in the device. */ +#if !defined HTTPD_LIMIT_SENDING_TO_2MSS || defined __DOXYGEN__ +#define HTTPD_LIMIT_SENDING_TO_2MSS 1 +#endif + +/* Define this to a function that returns the maximum amount of data to enqueue. + The function have this signature: u16_t fn(struct tcp_pcb* pcb); */ +#if !defined HTTPD_MAX_WRITE_LEN || defined __DOXYGEN__ +#if HTTPD_LIMIT_SENDING_TO_2MSS +#define HTTPD_MAX_WRITE_LEN(pcb) (2 * tcp_mss(pcb)) +#endif +#endif + +/*------------------- FS OPTIONS -------------------*/ + +/** Set this to 1 and provide the functions: + * - "int fs_open_custom(struct fs_file *file, const char *name)" + * Called first for every opened file to allow opening files + * that are not included in fsdata(_custom).c + * - "void fs_close_custom(struct fs_file *file)" + * Called to free resources allocated by fs_open_custom(). + */ +#if !defined LWIP_HTTPD_CUSTOM_FILES || defined __DOXYGEN__ +#define LWIP_HTTPD_CUSTOM_FILES 0 +#endif + +/** Set this to 1 to support fs_read() to dynamically read file data. + * Without this (default=off), only one-block files are supported, + * and the contents must be ready after fs_open(). + */ +#if !defined LWIP_HTTPD_DYNAMIC_FILE_READ || defined __DOXYGEN__ +#define LWIP_HTTPD_DYNAMIC_FILE_READ 0 +#endif + +/** Set this to 1 to include an application state argument per file + * that is opened. This allows to keep a state per connection/file. + */ +#if !defined LWIP_HTTPD_FILE_STATE || defined __DOXYGEN__ +#define LWIP_HTTPD_FILE_STATE 0 +#endif + +/** HTTPD_PRECALCULATED_CHECKSUM==1: include precompiled checksums for + * predefined (MSS-sized) chunks of the files to prevent having to calculate + * the checksums at runtime. */ +#if !defined HTTPD_PRECALCULATED_CHECKSUM || defined __DOXYGEN__ +#define HTTPD_PRECALCULATED_CHECKSUM 0 +#endif + +/** LWIP_HTTPD_FS_ASYNC_READ==1: support asynchronous read operations + * (fs_read_async returns FS_READ_DELAYED and calls a callback when finished). + */ +#if !defined LWIP_HTTPD_FS_ASYNC_READ || defined __DOXYGEN__ +#define LWIP_HTTPD_FS_ASYNC_READ 0 +#endif + +/** Set this to 1 to include "fsdata_custom.c" instead of "fsdata.c" for the + * file system (to prevent changing the file included in CVS) */ +#if !defined HTTPD_USE_CUSTOM_FSDATA || defined __DOXYGEN__ +#define HTTPD_USE_CUSTOM_FSDATA 0 +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_HTTPD_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/lwiperf.h b/tools/sdk/include/lwip/lwip/apps/lwiperf.h new file mode 100644 index 00000000000..7dbebb08264 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/lwiperf.h @@ -0,0 +1,84 @@ +/** + * @file + * lwIP iPerf server implementation + */ + +/* + * Copyright (c) 2014 Simon Goldschmidt + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ +#ifndef LWIP_HDR_APPS_LWIPERF_H +#define LWIP_HDR_APPS_LWIPERF_H + +#include "lwip/opt.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LWIPERF_TCP_PORT_DEFAULT 5001 + +/** lwIPerf test results */ +enum lwiperf_report_type +{ + /** The server side test is done */ + LWIPERF_TCP_DONE_SERVER, + /** The client side test is done */ + LWIPERF_TCP_DONE_CLIENT, + /** Local error lead to test abort */ + LWIPERF_TCP_ABORTED_LOCAL, + /** Data check error lead to test abort */ + LWIPERF_TCP_ABORTED_LOCAL_DATAERROR, + /** Transmit error lead to test abort */ + LWIPERF_TCP_ABORTED_LOCAL_TXERROR, + /** Remote side aborted the test */ + LWIPERF_TCP_ABORTED_REMOTE +}; + +/** Prototype of a report function that is called when a session is finished. + This report function can show the test results. + @param report_type contains the test result */ +typedef void (*lwiperf_report_fn)(void *arg, enum lwiperf_report_type report_type, + const ip_addr_t* local_addr, u16_t local_port, const ip_addr_t* remote_addr, u16_t remote_port, + u32_t bytes_transferred, u32_t ms_duration, u32_t bandwidth_kbitpsec); + + +void* lwiperf_start_tcp_server(const ip_addr_t* local_addr, u16_t local_port, + lwiperf_report_fn report_fn, void* report_arg); +void* lwiperf_start_tcp_server_default(lwiperf_report_fn report_fn, void* report_arg); +void lwiperf_abort(void* lwiperf_session); + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_LWIPERF_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/mdns.h b/tools/sdk/include/lwip/lwip/apps/mdns.h new file mode 100644 index 00000000000..d036816115d --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mdns.h @@ -0,0 +1,69 @@ +/** + * @file + * MDNS responder + */ + + /* + * Copyright (c) 2015 Verisure Innovation AB + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Ekman + * + */ +#ifndef LWIP_HDR_MDNS_H +#define LWIP_HDR_MDNS_H + +#include "lwip/apps/mdns_opts.h" +#include "lwip/netif.h" + +#if LWIP_MDNS_RESPONDER + +enum mdns_sd_proto { + DNSSD_PROTO_UDP = 0, + DNSSD_PROTO_TCP = 1 +}; + +#define MDNS_LABEL_MAXLEN 63 + +struct mdns_host; +struct mdns_service; + +/** Callback function to add text to a reply, called when generating the reply */ +typedef void (*service_get_txt_fn_t)(struct mdns_service *service, void *txt_userdata); + +void mdns_resp_init(void); + +err_t mdns_resp_add_netif(struct netif *netif, const char *hostname, u32_t dns_ttl); +err_t mdns_resp_remove_netif(struct netif *netif); + +err_t mdns_resp_add_service(struct netif *netif, const char *name, const char *service, enum mdns_sd_proto proto, u16_t port, u32_t dns_ttl, service_get_txt_fn_t txt_fn, void *txt_userdata); +err_t mdns_resp_add_service_txtitem(struct mdns_service *service, const char *txt, u8_t txt_len); +void mdns_resp_netif_settings_changed(struct netif *netif); + +#endif /* LWIP_MDNS_RESPONDER */ + +#endif /* LWIP_HDR_MDNS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/mdns_opts.h b/tools/sdk/include/lwip/lwip/apps/mdns_opts.h new file mode 100644 index 00000000000..bf186bcce17 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mdns_opts.h @@ -0,0 +1,74 @@ +/** + * @file + * MDNS responder + */ + + /* + * Copyright (c) 2015 Verisure Innovation AB + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Ekman + * + */ + +#ifndef LWIP_HDR_APPS_MDNS_OPTS_H +#define LWIP_HDR_APPS_MDNS_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup mdns_opts Options + * @ingroup mdns + * @{ + */ + +/** + * LWIP_MDNS_RESPONDER==1: Turn on multicast DNS module. UDP must be available for MDNS + * transport. IGMP is needed for IPv4 multicast. + */ +#ifndef LWIP_MDNS_RESPONDER +#define LWIP_MDNS_RESPONDER 0 +#endif /* LWIP_MDNS_RESPONDER */ + +/** The maximum number of services per netif */ +#ifndef MDNS_MAX_SERVICES +#define MDNS_MAX_SERVICES 1 +#endif + +/** + * MDNS_DEBUG: Enable debugging for multicast DNS. + */ +#ifndef MDNS_DEBUG +#define MDNS_DEBUG LWIP_DBG_OFF +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_MDNS_OPTS_H */ + diff --git a/tools/sdk/include/lwip/lwip/apps/mdns_priv.h b/tools/sdk/include/lwip/lwip/apps/mdns_priv.h new file mode 100644 index 00000000000..8ee6db86af4 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mdns_priv.h @@ -0,0 +1,66 @@ +/** + * @file + * MDNS responder private definitions + */ + + /* + * Copyright (c) 2015 Verisure Innovation AB + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Ekman + * + */ +#ifndef LWIP_HDR_MDNS_PRIV_H +#define LWIP_HDR_MDNS_PRIV_H + +#include "lwip/apps/mdns_opts.h" +#include "lwip/pbuf.h" + +#if LWIP_MDNS_RESPONDER + +/* Domain struct and methods - visible for unit tests */ + +#define MDNS_DOMAIN_MAXLEN 256 +#define MDNS_READNAME_ERROR 0xFFFF + +struct mdns_domain { + /* Encoded domain name */ + u8_t name[MDNS_DOMAIN_MAXLEN]; + /* Total length of domain name, including zero */ + u16_t length; + /* Set if compression of this domain is not allowed */ + u8_t skip_compression; +}; + +err_t mdns_domain_add_label(struct mdns_domain *domain, const char *label, u8_t len); +u16_t mdns_readname(struct pbuf *p, u16_t offset, struct mdns_domain *domain); +int mdns_domain_eq(struct mdns_domain *a, struct mdns_domain *b); +u16_t mdns_compress_domain(struct pbuf *pbuf, u16_t *offset, struct mdns_domain *domain); + +#endif /* LWIP_MDNS_RESPONDER */ + +#endif /* LWIP_HDR_MDNS_PRIV_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/mqtt.h b/tools/sdk/include/lwip/lwip/apps/mqtt.h new file mode 100644 index 00000000000..34b230b888b --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mqtt.h @@ -0,0 +1,244 @@ +/** + * @file + * MQTT client + */ + +/* + * Copyright (c) 2016 Erik Andersson + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Andersson + * + */ +#ifndef LWIP_HDR_APPS_MQTT_CLIENT_H +#define LWIP_HDR_APPS_MQTT_CLIENT_H + +#include "lwip/apps/mqtt_opts.h" +#include "lwip/err.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct mqtt_client_t mqtt_client_t; + +/** @ingroup mqtt + * Default MQTT port */ +#define MQTT_PORT 1883 + +/*---------------------------------------------------------------------------------------------- */ +/* Connection with server */ + +/** + * @ingroup mqtt + * Client information and connection parameters */ +struct mqtt_connect_client_info_t { + /** Client identifier, must be set by caller */ + const char *client_id; + /** User name and password, set to NULL if not used */ + const char* client_user; + const char* client_pass; + /** keep alive time in seconds, 0 to disable keep alive functionality*/ + u16_t keep_alive; + /** will topic, set to NULL if will is not to be used, + will_msg, will_qos and will retain are then ignored */ + const char* will_topic; + const char* will_msg; + u8_t will_qos; + u8_t will_retain; +}; + +/** + * @ingroup mqtt + * Connection status codes */ +typedef enum +{ + MQTT_CONNECT_ACCEPTED = 0, + MQTT_CONNECT_REFUSED_PROTOCOL_VERSION = 1, + MQTT_CONNECT_REFUSED_IDENTIFIER = 2, + MQTT_CONNECT_REFUSED_SERVER = 3, + MQTT_CONNECT_REFUSED_USERNAME_PASS = 4, + MQTT_CONNECT_REFUSED_NOT_AUTHORIZED_ = 5, + MQTT_CONNECT_DISCONNECTED = 256, + MQTT_CONNECT_TIMEOUT = 257 +} mqtt_connection_status_t; + +/** + * @ingroup mqtt + * Function prototype for mqtt connection status callback. Called when + * client has connected to the server after initiating a mqtt connection attempt by + * calling mqtt_connect() or when connection is closed by server or an error + * + * @param client MQTT client itself + * @param arg Additional argument to pass to the callback function + * @param status Connect result code or disconnection notification @see mqtt_connection_status_t + * + */ +typedef void (*mqtt_connection_cb_t)(mqtt_client_t *client, void *arg, mqtt_connection_status_t status); + + +/** + * @ingroup mqtt + * Data callback flags */ +enum { + /** Flag set when last fragment of data arrives in data callback */ + MQTT_DATA_FLAG_LAST = 1 +}; + +/** + * @ingroup mqtt + * Function prototype for MQTT incoming publish data callback function. Called when data + * arrives to a subscribed topic @see mqtt_subscribe + * + * @param arg Additional argument to pass to the callback function + * @param data User data, pointed object, data may not be referenced after callback return, + NULL is passed when all publish data are delivered + * @param len Length of publish data fragment + * @param flags MQTT_DATA_FLAG_LAST set when this call contains the last part of data from publish message + * + */ +typedef void (*mqtt_incoming_data_cb_t)(void *arg, const u8_t *data, u16_t len, u8_t flags); + + +/** + * @ingroup mqtt + * Function prototype for MQTT incoming publish function. Called when an incoming publish + * arrives to a subscribed topic @see mqtt_subscribe + * + * @param arg Additional argument to pass to the callback function + * @param topic Zero terminated Topic text string, topic may not be referenced after callback return + * @param tot_len Total length of publish data, if set to 0 (no publish payload) data callback will not be invoked + */ +typedef void (*mqtt_incoming_publish_cb_t)(void *arg, const char *topic, u32_t tot_len); + + +/** + * @ingroup mqtt + * Function prototype for mqtt request callback. Called when a subscribe, unsubscribe + * or publish request has completed + * @param arg Pointer to user data supplied when invoking request + * @param err ERR_OK on success + * ERR_TIMEOUT if no response was received within timeout, + * ERR_ABRT if (un)subscribe was denied + */ +typedef void (*mqtt_request_cb_t)(void *arg, err_t err); + + +/** + * Pending request item, binds application callback to pending server requests + */ +struct mqtt_request_t +{ + /** Next item in list, NULL means this is the last in chain, + next pointing at itself means request is unallocated */ + struct mqtt_request_t *next; + /** Callback to upper layer */ + mqtt_request_cb_t cb; + void *arg; + /** MQTT packet identifier */ + u16_t pkt_id; + /** Expire time relative to element before this */ + u16_t timeout_diff; +}; + +/** Ring buffer */ +struct mqtt_ringbuf_t { + u16_t put; + u16_t get; + u8_t buf[MQTT_OUTPUT_RINGBUF_SIZE]; +}; + +/** MQTT client */ +struct mqtt_client_t +{ + /** Timers and timeouts */ + u16_t cyclic_tick; + u16_t keep_alive; + u16_t server_watchdog; + /** Packet identifier generator*/ + u16_t pkt_id_seq; + /** Packet identifier of pending incoming publish */ + u16_t inpub_pkt_id; + /** Connection state */ + u8_t conn_state; + struct tcp_pcb *conn; + /** Connection callback */ + void *connect_arg; + mqtt_connection_cb_t connect_cb; + /** Pending requests to server */ + struct mqtt_request_t *pend_req_queue; + struct mqtt_request_t req_list[MQTT_REQ_MAX_IN_FLIGHT]; + void *inpub_arg; + /** Incoming data callback */ + mqtt_incoming_data_cb_t data_cb; + mqtt_incoming_publish_cb_t pub_cb; + /** Input */ + u32_t msg_idx; + u8_t rx_buffer[MQTT_VAR_HEADER_BUFFER_LEN]; + /** Output ring-buffer */ + struct mqtt_ringbuf_t output; +}; + + +/** Connect to server */ +err_t mqtt_client_connect(mqtt_client_t *client, const ip_addr_t *ipaddr, u16_t port, mqtt_connection_cb_t cb, void *arg, + const struct mqtt_connect_client_info_t *client_info); + +/** Disconnect from server */ +void mqtt_disconnect(mqtt_client_t *client); + +/** Create new client */ +mqtt_client_t *mqtt_client_new(void); + +/** Check connection status */ +u8_t mqtt_client_is_connected(mqtt_client_t *client); + +/** Set callback to call for incoming publish */ +void mqtt_set_inpub_callback(mqtt_client_t *client, mqtt_incoming_publish_cb_t, + mqtt_incoming_data_cb_t data_cb, void *arg); + +/** Common function for subscribe and unsubscribe */ +err_t mqtt_sub_unsub(mqtt_client_t *client, const char *topic, u8_t qos, mqtt_request_cb_t cb, void *arg, u8_t sub); + +/** @ingroup mqtt + *Subscribe to topic */ +#define mqtt_subscribe(client, topic, qos, cb, arg) mqtt_sub_unsub(client, topic, qos, cb, arg, 1) +/** @ingroup mqtt + * Unsubscribe to topic */ +#define mqtt_unsubscribe(client, topic, cb, arg) mqtt_sub_unsub(client, topic, 0, cb, arg, 0) + + +/** Publish data to topic */ +err_t mqtt_publish(mqtt_client_t *client, const char *topic, const void *payload, u16_t payload_length, u8_t qos, u8_t retain, + mqtt_request_cb_t cb, void *arg); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_MQTT_CLIENT_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/mqtt_opts.h b/tools/sdk/include/lwip/lwip/apps/mqtt_opts.h new file mode 100644 index 00000000000..ffefacd2595 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mqtt_opts.h @@ -0,0 +1,103 @@ +/** + * @file + * MQTT client options + */ + +/* + * Copyright (c) 2016 Erik Andersson + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Andersson + * + */ +#ifndef LWIP_HDR_APPS_MQTT_OPTS_H +#define LWIP_HDR_APPS_MQTT_OPTS_H + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup mqtt_opts Options + * @ingroup mqtt + * @{ + */ + +/** + * Output ring-buffer size, must be able to fit largest outgoing publish message topic+payloads + */ +#ifndef MQTT_OUTPUT_RINGBUF_SIZE +#define MQTT_OUTPUT_RINGBUF_SIZE 256 +#endif + +/** + * Number of bytes in receive buffer, must be at least the size of the longest incoming topic + 8 + * If one wants to avoid fragmented incoming publish, set length to max incoming topic length + max payload length + 8 + */ +#ifndef MQTT_VAR_HEADER_BUFFER_LEN +#define MQTT_VAR_HEADER_BUFFER_LEN 128 +#endif + +/** + * Maximum number of pending subscribe, unsubscribe and publish requests to server . + */ +#ifndef MQTT_REQ_MAX_IN_FLIGHT +#define MQTT_REQ_MAX_IN_FLIGHT 4 +#endif + +/** + * Seconds between each cyclic timer call. + */ +#ifndef MQTT_CYCLIC_TIMER_INTERVAL +#define MQTT_CYCLIC_TIMER_INTERVAL 5 +#endif + +/** + * Publish, subscribe and unsubscribe request timeout in seconds. + */ +#ifndef MQTT_REQ_TIMEOUT +#define MQTT_REQ_TIMEOUT 30 +#endif + +/** + * Seconds for MQTT connect response timeout after sending connect request + */ +#ifndef MQTT_CONNECT_TIMOUT +#define MQTT_CONNECT_TIMOUT 100 +#endif + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_MQTT_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/netbiosns.h b/tools/sdk/include/lwip/lwip/apps/netbiosns.h new file mode 100644 index 00000000000..c9f68d8d12c --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/netbiosns.h @@ -0,0 +1,43 @@ +/** + * @file + * NETBIOS name service responder + */ + +/* + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + */ +#ifndef LWIP_HDR_APPS_NETBIOS_H +#define LWIP_HDR_APPS_NETBIOS_H + +#include "lwip/apps/netbiosns_opts.h" + +void netbiosns_init(void); +#ifndef NETBIOS_LWIP_NAME +void netbiosns_set_name(const char* hostname); +#endif +void netbiosns_stop(void); + +#endif /* LWIP_HDR_APPS_NETBIOS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/netbiosns_opts.h b/tools/sdk/include/lwip/lwip/apps/netbiosns_opts.h new file mode 100644 index 00000000000..0909ef7b94e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/netbiosns_opts.h @@ -0,0 +1,59 @@ +/** + * @file + * NETBIOS name service responder options + */ + +/* + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + */ +#ifndef LWIP_HDR_APPS_NETBIOS_OPTS_H +#define LWIP_HDR_APPS_NETBIOS_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup netbiosns_opts Options + * @ingroup netbiosns + * @{ + */ + +/** NetBIOS name of lwip device + * This must be uppercase until NETBIOS_STRCMP() is defined to a string + * comparision function that is case insensitive. + * If you want to use the netif's hostname, use this (with LWIP_NETIF_HOSTNAME): + * (ip_current_netif() != NULL ? ip_current_netif()->hostname != NULL ? ip_current_netif()->hostname : "" : "") + * + * If this is not defined, netbiosns_set_name() can be called at runtime to change the name. + */ +#ifdef __DOXYGEN__ +#define NETBIOS_LWIP_NAME "NETBIOSLWIPDEV" +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_NETBIOS_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp.h b/tools/sdk/include/lwip/lwip/apps/snmp.h new file mode 100644 index 00000000000..10e8ff434bb --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp.h @@ -0,0 +1,128 @@ +/** + * @file + * SNMP server main API - start and basic configuration + */ + +/* + * Copyright (c) 2001, 2002 Leon Woestenberg + * Copyright (c) 2001, 2002 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Leon Woestenberg + * Martin Hentschel + * + */ +#ifndef LWIP_HDR_APPS_SNMP_H +#define LWIP_HDR_APPS_SNMP_H + +#include "lwip/apps/snmp_opts.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/err.h" +#include "lwip/apps/snmp_core.h" + +/** SNMP variable binding descriptor (publically needed for traps) */ +struct snmp_varbind +{ + /** pointer to next varbind, NULL for last in list */ + struct snmp_varbind *next; + /** pointer to previous varbind, NULL for first in list */ + struct snmp_varbind *prev; + + /** object identifier */ + struct snmp_obj_id oid; + + /** value ASN1 type */ + u8_t type; + /** object value length */ + u16_t value_len; + /** object value */ + void *value; +}; + +/** + * @ingroup snmp_core + * Agent setup, start listening to port 161. + */ +void snmp_init(void); +void snmp_set_mibs(const struct snmp_mib **mibs, u8_t num_mibs); + +void snmp_set_device_enterprise_oid(const struct snmp_obj_id* device_enterprise_oid); +const struct snmp_obj_id* snmp_get_device_enterprise_oid(void); + +void snmp_trap_dst_enable(u8_t dst_idx, u8_t enable); +void snmp_trap_dst_ip_set(u8_t dst_idx, const ip_addr_t *dst); + +/** Generic trap: cold start */ +#define SNMP_GENTRAP_COLDSTART 0 +/** Generic trap: warm start */ +#define SNMP_GENTRAP_WARMSTART 1 +/** Generic trap: link down */ +#define SNMP_GENTRAP_LINKDOWN 2 +/** Generic trap: link up */ +#define SNMP_GENTRAP_LINKUP 3 +/** Generic trap: authentication failure */ +#define SNMP_GENTRAP_AUTH_FAILURE 4 +/** Generic trap: EGP neighbor lost */ +#define SNMP_GENTRAP_EGP_NEIGHBOR_LOSS 5 +/** Generic trap: enterprise specific */ +#define SNMP_GENTRAP_ENTERPRISE_SPECIFIC 6 + +err_t snmp_send_trap_generic(s32_t generic_trap); +err_t snmp_send_trap_specific(s32_t specific_trap, struct snmp_varbind *varbinds); +err_t snmp_send_trap(const struct snmp_obj_id* oid, s32_t generic_trap, s32_t specific_trap, struct snmp_varbind *varbinds); + +#define SNMP_AUTH_TRAPS_DISABLED 0 +#define SNMP_AUTH_TRAPS_ENABLED 1 +void snmp_set_auth_traps_enabled(u8_t enable); +u8_t snmp_get_auth_traps_enabled(void); + +const char * snmp_get_community(void); +const char * snmp_get_community_write(void); +const char * snmp_get_community_trap(void); +void snmp_set_community(const char * const community); +void snmp_set_community_write(const char * const community); +void snmp_set_community_trap(const char * const community); + +void snmp_coldstart_trap(void); +void snmp_authfail_trap(void); + +typedef void (*snmp_write_callback_fct)(const u32_t* oid, u8_t oid_len, void* callback_arg); +void snmp_set_write_callback(snmp_write_callback_fct write_callback, void* callback_arg); + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_core.h b/tools/sdk/include/lwip/lwip/apps/snmp_core.h new file mode 100644 index 00000000000..e781c532b38 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_core.h @@ -0,0 +1,364 @@ +/** + * @file + * SNMP core API for implementing MIBs + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * 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. + * + * Author: Christiaan Simons + * Martin Hentschel + */ + +#ifndef LWIP_HDR_APPS_SNMP_CORE_H +#define LWIP_HDR_APPS_SNMP_CORE_H + +#include "lwip/apps/snmp_opts.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/ip_addr.h" +#include "lwip/err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* basic ASN1 defines */ +#define SNMP_ASN1_CLASS_UNIVERSAL 0x00 +#define SNMP_ASN1_CLASS_APPLICATION 0x40 +#define SNMP_ASN1_CLASS_CONTEXT 0x80 +#define SNMP_ASN1_CLASS_PRIVATE 0xC0 + +#define SNMP_ASN1_CONTENTTYPE_PRIMITIVE 0x00 +#define SNMP_ASN1_CONTENTTYPE_CONSTRUCTED 0x20 + +/* universal tags (from ASN.1 spec.) */ +#define SNMP_ASN1_UNIVERSAL_END_OF_CONTENT 0 +#define SNMP_ASN1_UNIVERSAL_INTEGER 2 +#define SNMP_ASN1_UNIVERSAL_OCTET_STRING 4 +#define SNMP_ASN1_UNIVERSAL_NULL 5 +#define SNMP_ASN1_UNIVERSAL_OBJECT_ID 6 +#define SNMP_ASN1_UNIVERSAL_SEQUENCE_OF 16 + +/* application specific (SNMP) tags (from SNMPv2-SMI) */ +#define SNMP_ASN1_APPLICATION_IPADDR 0 /* [APPLICATION 0] IMPLICIT OCTET STRING (SIZE (4)) */ +#define SNMP_ASN1_APPLICATION_COUNTER 1 /* [APPLICATION 1] IMPLICIT INTEGER (0..4294967295) => u32_t */ +#define SNMP_ASN1_APPLICATION_GAUGE 2 /* [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) => u32_t */ +#define SNMP_ASN1_APPLICATION_TIMETICKS 3 /* [APPLICATION 3] IMPLICIT INTEGER (0..4294967295) => u32_t */ +#define SNMP_ASN1_APPLICATION_OPAQUE 4 /* [APPLICATION 4] IMPLICIT OCTET STRING */ +#define SNMP_ASN1_APPLICATION_COUNTER64 6 /* [APPLICATION 6] IMPLICIT INTEGER (0..18446744073709551615) */ + +/* context specific (SNMP) tags (from RFC 1905) */ +#define SNMP_ASN1_CONTEXT_VARBIND_NO_SUCH_INSTANCE 1 + +/* full ASN1 type defines */ +#define SNMP_ASN1_TYPE_END_OF_CONTENT (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_END_OF_CONTENT) +#define SNMP_ASN1_TYPE_INTEGER (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_INTEGER) +#define SNMP_ASN1_TYPE_OCTET_STRING (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_OCTET_STRING) +#define SNMP_ASN1_TYPE_NULL (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_NULL) +#define SNMP_ASN1_TYPE_OBJECT_ID (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_OBJECT_ID) +#define SNMP_ASN1_TYPE_SEQUENCE (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_UNIVERSAL_SEQUENCE_OF) +#define SNMP_ASN1_TYPE_IPADDR (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_IPADDR) +#define SNMP_ASN1_TYPE_IPADDRESS SNMP_ASN1_TYPE_IPADDR +#define SNMP_ASN1_TYPE_COUNTER (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_COUNTER) +#define SNMP_ASN1_TYPE_COUNTER32 SNMP_ASN1_TYPE_COUNTER +#define SNMP_ASN1_TYPE_GAUGE (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_GAUGE) +#define SNMP_ASN1_TYPE_GAUGE32 SNMP_ASN1_TYPE_GAUGE +#define SNMP_ASN1_TYPE_UNSIGNED32 SNMP_ASN1_TYPE_GAUGE +#define SNMP_ASN1_TYPE_TIMETICKS (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_TIMETICKS) +#define SNMP_ASN1_TYPE_OPAQUE (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_OPAQUE) +#define SNMP_ASN1_TYPE_COUNTER64 (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_COUNTER64) + +#define SNMP_VARBIND_EXCEPTION_OFFSET 0xF0 +#define SNMP_VARBIND_EXCEPTION_MASK 0x0F + +/** error codes predefined by SNMP prot. */ +typedef enum { + SNMP_ERR_NOERROR = 0, +/* +outdated v1 error codes. do not use anmore! +#define SNMP_ERR_NOSUCHNAME 2 use SNMP_ERR_NOSUCHINSTANCE instead +#define SNMP_ERR_BADVALUE 3 use SNMP_ERR_WRONGTYPE,SNMP_ERR_WRONGLENGTH,SNMP_ERR_WRONGENCODING or SNMP_ERR_WRONGVALUE instead +#define SNMP_ERR_READONLY 4 use SNMP_ERR_NOTWRITABLE instead +*/ + SNMP_ERR_GENERROR = 5, + SNMP_ERR_NOACCESS = 6, + SNMP_ERR_WRONGTYPE = 7, + SNMP_ERR_WRONGLENGTH = 8, + SNMP_ERR_WRONGENCODING = 9, + SNMP_ERR_WRONGVALUE = 10, + SNMP_ERR_NOCREATION = 11, + SNMP_ERR_INCONSISTENTVALUE = 12, + SNMP_ERR_RESOURCEUNAVAILABLE = 13, + SNMP_ERR_COMMITFAILED = 14, + SNMP_ERR_UNDOFAILED = 15, + SNMP_ERR_NOTWRITABLE = 17, + SNMP_ERR_INCONSISTENTNAME = 18, + + SNMP_ERR_NOSUCHINSTANCE = SNMP_VARBIND_EXCEPTION_OFFSET + SNMP_ASN1_CONTEXT_VARBIND_NO_SUCH_INSTANCE +} snmp_err_t; + +/** internal object identifier representation */ +struct snmp_obj_id +{ + u8_t len; + u32_t id[SNMP_MAX_OBJ_ID_LEN]; +}; + +struct snmp_obj_id_const_ref +{ + u8_t len; + const u32_t* id; +}; + +extern const struct snmp_obj_id_const_ref snmp_zero_dot_zero; /* administrative identifier from SNMPv2-SMI */ + +/** SNMP variant value, used as reference in struct snmp_node_instance and table implementation */ +union snmp_variant_value +{ + void* ptr; + const void* const_ptr; + u32_t u32; + s32_t s32; +}; + + +/** +SNMP MIB node types + tree node is the only node the stack can process in order to walk the tree, + all other nodes are assumed to be leaf nodes. + This cannot be an enum because users may want to define their own node types. +*/ +#define SNMP_NODE_TREE 0x00 +/* predefined leaf node types */ +#define SNMP_NODE_SCALAR 0x01 +#define SNMP_NODE_SCALAR_ARRAY 0x02 +#define SNMP_NODE_TABLE 0x03 +#define SNMP_NODE_THREADSYNC 0x04 + +/** node "base class" layout, the mandatory fields for a node */ +struct snmp_node +{ + /** one out of SNMP_NODE_TREE or any leaf node type (like SNMP_NODE_SCALAR) */ + u8_t node_type; + /** the number assigned to this node which used as part of the full OID */ + u32_t oid; +}; + +/** SNMP node instance access types */ +typedef enum { + SNMP_NODE_INSTANCE_ACCESS_READ = 1, + SNMP_NODE_INSTANCE_ACCESS_WRITE = 2, + SNMP_NODE_INSTANCE_READ_ONLY = SNMP_NODE_INSTANCE_ACCESS_READ, + SNMP_NODE_INSTANCE_READ_WRITE = (SNMP_NODE_INSTANCE_ACCESS_READ | SNMP_NODE_INSTANCE_ACCESS_WRITE), + SNMP_NODE_INSTANCE_WRITE_ONLY = SNMP_NODE_INSTANCE_ACCESS_WRITE, + SNMP_NODE_INSTANCE_NOT_ACCESSIBLE = 0 +} snmp_access_t; + +struct snmp_node_instance; + +typedef s16_t (*node_instance_get_value_method)(struct snmp_node_instance*, void*); +typedef snmp_err_t (*node_instance_set_test_method)(struct snmp_node_instance*, u16_t, void*); +typedef snmp_err_t (*node_instance_set_value_method)(struct snmp_node_instance*, u16_t, void*); +typedef void (*node_instance_release_method)(struct snmp_node_instance*); + +#define SNMP_GET_VALUE_RAW_DATA 0x8000 + +/** SNMP node instance */ +struct snmp_node_instance +{ + /** prefilled with the node, get_instance() is called on; may be changed by user to any value to pass an arbitrary node between calls to get_instance() and get_value/test_value/set_value */ + const struct snmp_node* node; + /** prefilled with the instance id requested; for get_instance() this is the exact oid requested; for get_next_instance() this is the relative starting point, stack expects relative oid of next node here */ + struct snmp_obj_id instance_oid; + + /** ASN type for this object (see snmp_asn1.h for definitions) */ + u8_t asn1_type; + /** one out of instance access types defined above (SNMP_NODE_INSTANCE_READ_ONLY,...) */ + snmp_access_t access; + + /** returns object value for the given object identifier. Return values <0 to indicate an error */ + node_instance_get_value_method get_value; + /** tests length and/or range BEFORE setting */ + node_instance_set_test_method set_test; + /** sets object value, only called when set_test() was successful */ + node_instance_set_value_method set_value; + /** called in any case when the instance is not required anymore by stack (useful for freeing memory allocated in get_instance/get_next_instance methods) */ + node_instance_release_method release_instance; + + /** reference to pass arbitrary value between calls to get_instance() and get_value/test_value/set_value */ + union snmp_variant_value reference; + /** see reference (if reference is a pointer, the length of underlying data may be stored here or anything else) */ + u32_t reference_len; +}; + + +/** SNMP tree node */ +struct snmp_tree_node +{ + /** inherited "base class" members */ + struct snmp_node node; + u16_t subnode_count; + const struct snmp_node* const *subnodes; +}; + +#define SNMP_CREATE_TREE_NODE(oid, subnodes) \ + {{ SNMP_NODE_TREE, (oid) }, \ + (u16_t)LWIP_ARRAYSIZE(subnodes), (subnodes) } + +#define SNMP_CREATE_EMPTY_TREE_NODE(oid) \ + {{ SNMP_NODE_TREE, (oid) }, \ + 0, NULL } + +/** SNMP leaf node */ +struct snmp_leaf_node +{ + /** inherited "base class" members */ + struct snmp_node node; + snmp_err_t (*get_instance)(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + snmp_err_t (*get_next_instance)(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +}; + +/** represents a single mib with its base oid and root node */ +struct snmp_mib +{ + const u32_t *base_oid; + u8_t base_oid_len; + const struct snmp_node *root_node; +}; + +#define SNMP_MIB_CREATE(oid_list, root_node) { (oid_list), (u8_t)LWIP_ARRAYSIZE(oid_list), root_node } + +/** OID range structure */ +struct snmp_oid_range +{ + u32_t min; + u32_t max; +}; + +/** checks if incoming OID length and values are in allowed ranges */ +u8_t snmp_oid_in_range(const u32_t *oid_in, u8_t oid_len, const struct snmp_oid_range *oid_ranges, u8_t oid_ranges_len); + +typedef enum { + SNMP_NEXT_OID_STATUS_SUCCESS, + SNMP_NEXT_OID_STATUS_NO_MATCH, + SNMP_NEXT_OID_STATUS_BUF_TO_SMALL +} snmp_next_oid_status_t; + +/** state for next_oid_init / next_oid_check functions */ +struct snmp_next_oid_state +{ + const u32_t* start_oid; + u8_t start_oid_len; + + u32_t* next_oid; + u8_t next_oid_len; + u8_t next_oid_max_len; + + snmp_next_oid_status_t status; + void* reference; +}; + +void snmp_next_oid_init(struct snmp_next_oid_state *state, + const u32_t *start_oid, u8_t start_oid_len, + u32_t *next_oid_buf, u8_t next_oid_max_len); +u8_t snmp_next_oid_precheck(struct snmp_next_oid_state *state, const u32_t *oid, const u8_t oid_len); +u8_t snmp_next_oid_check(struct snmp_next_oid_state *state, const u32_t *oid, const u8_t oid_len, void* reference); + +void snmp_oid_assign(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len); +void snmp_oid_combine(struct snmp_obj_id* target, const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len); +void snmp_oid_prefix(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len); +void snmp_oid_append(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len); +u8_t snmp_oid_equal(const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len); +s8_t snmp_oid_compare(const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len); + +#if LWIP_IPV4 +u8_t snmp_oid_to_ip4(const u32_t *oid, ip4_addr_t *ip); +void snmp_ip4_to_oid(const ip4_addr_t *ip, u32_t *oid); +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 +u8_t snmp_oid_to_ip6(const u32_t *oid, ip6_addr_t *ip); +void snmp_ip6_to_oid(const ip6_addr_t *ip, u32_t *oid); +#endif /* LWIP_IPV6 */ +#if LWIP_IPV4 || LWIP_IPV6 +u8_t snmp_ip_to_oid(const ip_addr_t *ip, u32_t *oid); +u8_t snmp_ip_port_to_oid(const ip_addr_t *ip, u16_t port, u32_t *oid); + +u8_t snmp_oid_to_ip(const u32_t *oid, u8_t oid_len, ip_addr_t *ip); +u8_t snmp_oid_to_ip_port(const u32_t *oid, u8_t oid_len, ip_addr_t *ip, u16_t *port); +#endif /* LWIP_IPV4 || LWIP_IPV6 */ + +struct netif; +u8_t netif_to_num(const struct netif *netif); + +snmp_err_t snmp_set_test_ok(struct snmp_node_instance* instance, u16_t value_len, void* value); /* generic function which can be used if test is always successful */ + +err_t snmp_decode_bits(const u8_t *buf, u32_t buf_len, u32_t *bit_value); +err_t snmp_decode_truthvalue(const s32_t *asn1_value, u8_t *bool_value); +u8_t snmp_encode_bits(u8_t *buf, u32_t buf_len, u32_t bit_value, u8_t bit_count); +u8_t snmp_encode_truthvalue(s32_t *asn1_value, u32_t bool_value); + +struct snmp_statistics +{ + u32_t inpkts; + u32_t outpkts; + u32_t inbadversions; + u32_t inbadcommunitynames; + u32_t inbadcommunityuses; + u32_t inasnparseerrs; + u32_t intoobigs; + u32_t innosuchnames; + u32_t inbadvalues; + u32_t inreadonlys; + u32_t ingenerrs; + u32_t intotalreqvars; + u32_t intotalsetvars; + u32_t ingetrequests; + u32_t ingetnexts; + u32_t insetrequests; + u32_t ingetresponses; + u32_t intraps; + u32_t outtoobigs; + u32_t outnosuchnames; + u32_t outbadvalues; + u32_t outgenerrs; + u32_t outgetrequests; + u32_t outgetnexts; + u32_t outsetrequests; + u32_t outgetresponses; + u32_t outtraps; +}; + +extern struct snmp_statistics snmp_stats; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_SNMP */ + +#endif /* LWIP_HDR_APPS_SNMP_CORE_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_mib2.h b/tools/sdk/include/lwip/lwip/apps/snmp_mib2.h new file mode 100644 index 00000000000..2f4a68935e2 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_mib2.h @@ -0,0 +1,78 @@ +/** + * @file + * SNMP MIB2 API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ +#ifndef LWIP_HDR_APPS_SNMP_MIB2_H +#define LWIP_HDR_APPS_SNMP_MIB2_H + +#include "lwip/apps/snmp_opts.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ +#if SNMP_LWIP_MIB2 + +#include "lwip/apps/snmp_core.h" + +extern const struct snmp_mib mib2; + +#if SNMP_USE_NETCONN +#include "lwip/apps/snmp_threadsync.h" +void snmp_mib2_lwip_synchronizer(snmp_threadsync_called_fn fn, void* arg); +extern struct snmp_threadsync_instance snmp_mib2_lwip_locks; +#endif + +#ifndef SNMP_SYSSERVICES +#define SNMP_SYSSERVICES ((1 << 6) | (1 << 3) | ((IP_FORWARD) << 2)) +#endif + +void snmp_mib2_set_sysdescr(const u8_t* str, const u16_t* len); /* read-only be defintion */ +void snmp_mib2_set_syscontact(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize); +void snmp_mib2_set_syscontact_readonly(const u8_t *ocstr, const u16_t *ocstrlen); +void snmp_mib2_set_sysname(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize); +void snmp_mib2_set_sysname_readonly(const u8_t *ocstr, const u16_t *ocstrlen); +void snmp_mib2_set_syslocation(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize); +void snmp_mib2_set_syslocation_readonly(const u8_t *ocstr, const u16_t *ocstrlen); + +#endif /* SNMP_LWIP_MIB2 */ +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_MIB2_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_opts.h b/tools/sdk/include/lwip/lwip/apps/snmp_opts.h new file mode 100644 index 00000000000..6c9ba7beb33 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_opts.h @@ -0,0 +1,293 @@ +/** + * @file + * SNMP server options list + */ + +/* + * Copyright (c) 2015 Dirk Ziegelmeier + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ +#ifndef LWIP_HDR_SNMP_OPTS_H +#define LWIP_HDR_SNMP_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup snmp_opts Options + * @ingroup snmp + * @{ + */ + +/** + * LWIP_SNMP==1: This enables the lwIP SNMP agent. UDP must be available + * for SNMP transport. + * If you want to use your own SNMP agent, leave this disabled. + * To integrate MIB2 of an external agent, you need to enable + * LWIP_MIB2_CALLBACKS and MIB2_STATS. This will give you the callbacks + * and statistics counters you need to get MIB2 working. + */ +#if !defined LWIP_SNMP || defined __DOXYGEN__ +#define LWIP_SNMP 0 +#endif + +/** + * SNMP_USE_NETCONN: Use netconn API instead of raw API. + * Makes SNMP agent run in a worker thread, so blocking operations + * can be done in MIB calls. + */ +#if !defined SNMP_USE_NETCONN || defined __DOXYGEN__ +#define SNMP_USE_NETCONN 0 +#endif + +/** + * SNMP_USE_RAW: Use raw API. + * SNMP agent does not run in a worker thread, so blocking operations + * should not be done in MIB calls. + */ +#if !defined SNMP_USE_RAW || defined __DOXYGEN__ +#define SNMP_USE_RAW 1 +#endif + +#if SNMP_USE_NETCONN && SNMP_USE_RAW +#error SNMP stack can use only one of the APIs {raw, netconn} +#endif + +#if LWIP_SNMP && !SNMP_USE_NETCONN && !SNMP_USE_RAW +#error SNMP stack needs a receive API and UDP {raw, netconn} +#endif + +#if SNMP_USE_NETCONN +/** + * SNMP_STACK_SIZE: Stack size of SNMP netconn worker thread + */ +#if !defined SNMP_STACK_SIZE || defined __DOXYGEN__ +#define SNMP_STACK_SIZE DEFAULT_THREAD_STACKSIZE +#endif + +/** + * SNMP_THREAD_PRIO: SNMP netconn worker thread priority + */ +#if !defined SNMP_THREAD_PRIO || defined __DOXYGEN__ +#define SNMP_THREAD_PRIO DEFAULT_THREAD_PRIO +#endif +#endif /* SNMP_USE_NETCONN */ + +/** + * SNMP_TRAP_DESTINATIONS: Number of trap destinations. At least one trap + * destination is required + */ +#if !defined SNMP_TRAP_DESTINATIONS || defined __DOXYGEN__ +#define SNMP_TRAP_DESTINATIONS 1 +#endif + +/** + * Only allow SNMP write actions that are 'safe' (e.g. disabling netifs is not + * a safe action and disabled when SNMP_SAFE_REQUESTS = 1). + * Unsafe requests are disabled by default! + */ +#if !defined SNMP_SAFE_REQUESTS || defined __DOXYGEN__ +#define SNMP_SAFE_REQUESTS 1 +#endif + +/** + * The maximum length of strings used. + */ +#if !defined SNMP_MAX_OCTET_STRING_LEN || defined __DOXYGEN__ +#define SNMP_MAX_OCTET_STRING_LEN 127 +#endif + +/** + * The maximum number of Sub ID's inside an object identifier. + * Indirectly this also limits the maximum depth of SNMP tree. + */ +#if !defined SNMP_MAX_OBJ_ID_LEN || defined __DOXYGEN__ +#define SNMP_MAX_OBJ_ID_LEN 50 +#endif + +#if !defined SNMP_MAX_VALUE_SIZE || defined __DOXYGEN__ +/** + * The maximum size of a value. + */ +#define SNMP_MIN_VALUE_SIZE (2 * sizeof(u32_t*)) /* size required to store the basic types (8 bytes for counter64) */ +/** + * The minimum size of a value. + */ +#define SNMP_MAX_VALUE_SIZE LWIP_MAX(LWIP_MAX((SNMP_MAX_OCTET_STRING_LEN), sizeof(u32_t)*(SNMP_MAX_OBJ_ID_LEN)), SNMP_MIN_VALUE_SIZE) +#endif + +/** + * The snmp read-access community. Used for write-access and traps, too + * unless SNMP_COMMUNITY_WRITE or SNMP_COMMUNITY_TRAP are enabled, respectively. + */ +#if !defined SNMP_COMMUNITY || defined __DOXYGEN__ +#define SNMP_COMMUNITY "public" +#endif + +/** + * The snmp write-access community. + * Set this community to "" in order to disallow any write access. + */ +#if !defined SNMP_COMMUNITY_WRITE || defined __DOXYGEN__ +#define SNMP_COMMUNITY_WRITE "private" +#endif + +/** + * The snmp community used for sending traps. + */ +#if !defined SNMP_COMMUNITY_TRAP || defined __DOXYGEN__ +#define SNMP_COMMUNITY_TRAP "public" +#endif + +/** + * The maximum length of community string. + * If community names shall be adjusted at runtime via snmp_set_community() calls, + * enter here the possible maximum length (+1 for terminating null character). + */ +#if !defined SNMP_MAX_COMMUNITY_STR_LEN || defined __DOXYGEN__ +#define SNMP_MAX_COMMUNITY_STR_LEN LWIP_MAX(LWIP_MAX(sizeof(SNMP_COMMUNITY), sizeof(SNMP_COMMUNITY_WRITE)), sizeof(SNMP_COMMUNITY_TRAP)) +#endif + +/** + * The OID identifiying the device. This may be the enterprise OID itself or any OID located below it in tree. + */ +#if !defined SNMP_DEVICE_ENTERPRISE_OID || defined __DOXYGEN__ +#define SNMP_LWIP_ENTERPRISE_OID 26381 +/** + * IANA assigned enterprise ID for lwIP is 26381 + * @see http://www.iana.org/assignments/enterprise-numbers + * + * @note this enterprise ID is assigned to the lwIP project, + * all object identifiers living under this ID are assigned + * by the lwIP maintainers! + * @note don't change this define, use snmp_set_device_enterprise_oid() + * + * If you need to create your own private MIB you'll need + * to apply for your own enterprise ID with IANA: + * http://www.iana.org/numbers.html + */ +#define SNMP_DEVICE_ENTERPRISE_OID {1, 3, 6, 1, 4, 1, SNMP_LWIP_ENTERPRISE_OID} +/** + * Length of SNMP_DEVICE_ENTERPRISE_OID + */ +#define SNMP_DEVICE_ENTERPRISE_OID_LEN 7 +#endif + +/** + * SNMP_DEBUG: Enable debugging for SNMP messages. + */ +#if !defined SNMP_DEBUG || defined __DOXYGEN__ +#define SNMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SNMP_MIB_DEBUG: Enable debugging for SNMP MIBs. + */ +#if !defined SNMP_MIB_DEBUG || defined __DOXYGEN__ +#define SNMP_MIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * Indicates if the MIB2 implementation of LWIP SNMP stack is used. + */ +#if !defined SNMP_LWIP_MIB2 || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2 LWIP_SNMP +#endif + +/** + * Value return for sysDesc field of MIB2. + */ +#if !defined SNMP_LWIP_MIB2_SYSDESC || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2_SYSDESC "lwIP" +#endif + +/** + * Value return for sysName field of MIB2. + * To make sysName field settable, call snmp_mib2_set_sysname() to provide the necessary buffers. + */ +#if !defined SNMP_LWIP_MIB2_SYSNAME || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2_SYSNAME "FQDN-unk" +#endif + +/** + * Value return for sysContact field of MIB2. + * To make sysContact field settable, call snmp_mib2_set_syscontact() to provide the necessary buffers. + */ +#if !defined SNMP_LWIP_MIB2_SYSCONTACT || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2_SYSCONTACT "" +#endif + +/** + * Value return for sysLocation field of MIB2. + * To make sysLocation field settable, call snmp_mib2_set_syslocation() to provide the necessary buffers. + */ +#if !defined SNMP_LWIP_MIB2_SYSLOCATION || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2_SYSLOCATION "" +#endif + +/** + * This value is used to limit the repetitions processed in GetBulk requests (value == 0 means no limitation). + * This may be useful to limit the load for a single request. + * According to SNMP RFC 1905 it is allowed to not return all requested variables from a GetBulk request if system load would be too high. + * so the effect is that the client will do more requests to gather all data. + * For the stack this could be useful in case that SNMP processing is done in TCP/IP thread. In this situation a request with many + * repetitions could block the thread for a longer time. Setting limit here will keep the stack more responsive. + */ +#if !defined SNMP_LWIP_GETBULK_MAX_REPETITIONS || defined __DOXYGEN__ +#define SNMP_LWIP_GETBULK_MAX_REPETITIONS 0 +#endif + +/** + * @} + */ + +/* + ------------------------------------ + ---------- SNMPv3 options ---------- + ------------------------------------ +*/ + +/** + * LWIP_SNMP_V3==1: This enables EXPERIMENTAL SNMPv3 support. LWIP_SNMP must + * also be enabled. + * THIS IS UNDER DEVELOPMENT AND SHOULD NOT BE ENABLED IN PRODUCTS. + */ +#ifndef LWIP_SNMP_V3 +#define LWIP_SNMP_V3 0 +#endif + +#ifndef LWIP_SNMP_V3_CRYPTO +#define LWIP_SNMP_V3_CRYPTO LWIP_SNMP_V3 +#endif + +#ifndef LWIP_SNMP_V3_MBEDTLS +#define LWIP_SNMP_V3_MBEDTLS LWIP_SNMP_V3 +#endif + +#endif /* LWIP_HDR_SNMP_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_scalar.h b/tools/sdk/include/lwip/lwip/apps/snmp_scalar.h new file mode 100644 index 00000000000..40a060c6404 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_scalar.h @@ -0,0 +1,113 @@ +/** + * @file + * SNMP server MIB API to implement scalar nodes + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +#ifndef LWIP_HDR_APPS_SNMP_SCALAR_H +#define LWIP_HDR_APPS_SNMP_SCALAR_H + +#include "lwip/apps/snmp_opts.h" +#include "lwip/apps/snmp_core.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +/** basic scalar node */ +struct snmp_scalar_node +{ + /** inherited "base class" members */ + struct snmp_leaf_node node; + u8_t asn1_type; + snmp_access_t access; + node_instance_get_value_method get_value; + node_instance_set_test_method set_test; + node_instance_set_value_method set_value; +}; + + +snmp_err_t snmp_scalar_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_scalar_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +#define SNMP_SCALAR_CREATE_NODE(oid, access, asn1_type, get_value_method, set_test_method, set_value_method) \ + {{{ SNMP_NODE_SCALAR, (oid) }, \ + snmp_scalar_get_instance, \ + snmp_scalar_get_next_instance }, \ + (asn1_type), (access), (get_value_method), (set_test_method), (set_value_method) } + +#define SNMP_SCALAR_CREATE_NODE_READONLY(oid, asn1_type, get_value_method) SNMP_SCALAR_CREATE_NODE(oid, SNMP_NODE_INSTANCE_READ_ONLY, asn1_type, get_value_method, NULL, NULL) + +/** scalar array node - a tree node which contains scalars only as children */ +struct snmp_scalar_array_node_def +{ + u32_t oid; + u8_t asn1_type; + snmp_access_t access; +}; + +typedef s16_t (*snmp_scalar_array_get_value_method)(const struct snmp_scalar_array_node_def*, void*); +typedef snmp_err_t (*snmp_scalar_array_set_test_method)(const struct snmp_scalar_array_node_def*, u16_t, void*); +typedef snmp_err_t (*snmp_scalar_array_set_value_method)(const struct snmp_scalar_array_node_def*, u16_t, void*); + +/** basic scalar array node */ +struct snmp_scalar_array_node +{ + /** inherited "base class" members */ + struct snmp_leaf_node node; + u16_t array_node_count; + const struct snmp_scalar_array_node_def* array_nodes; + snmp_scalar_array_get_value_method get_value; + snmp_scalar_array_set_test_method set_test; + snmp_scalar_array_set_value_method set_value; +}; + +snmp_err_t snmp_scalar_array_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_scalar_array_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +#define SNMP_SCALAR_CREATE_ARRAY_NODE(oid, array_nodes, get_value_method, set_test_method, set_value_method) \ + {{{ SNMP_NODE_SCALAR_ARRAY, (oid) }, \ + snmp_scalar_array_get_instance, \ + snmp_scalar_array_get_next_instance }, \ + (u16_t)LWIP_ARRAYSIZE(array_nodes), (array_nodes), (get_value_method), (set_test_method), (set_value_method) } + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_SCALAR_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_table.h b/tools/sdk/include/lwip/lwip/apps/snmp_table.h new file mode 100644 index 00000000000..4988b51c250 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_table.h @@ -0,0 +1,134 @@ +/** + * @file + * SNMP server MIB API to implement table nodes + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +#ifndef LWIP_HDR_APPS_SNMP_TABLE_H +#define LWIP_HDR_APPS_SNMP_TABLE_H + +#include "lwip/apps/snmp_opts.h" +#include "lwip/apps/snmp_core.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +/** default (customizable) read/write table */ +struct snmp_table_col_def +{ + u32_t index; + u8_t asn1_type; + snmp_access_t access; +}; + +/** table node */ +struct snmp_table_node +{ + /** inherited "base class" members */ + struct snmp_leaf_node node; + u16_t column_count; + const struct snmp_table_col_def* columns; + snmp_err_t (*get_cell_instance)(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, struct snmp_node_instance* cell_instance); + snmp_err_t (*get_next_cell_instance)(const u32_t* column, struct snmp_obj_id* row_oid, struct snmp_node_instance* cell_instance); + /** returns object value for the given object identifier */ + node_instance_get_value_method get_value; + /** tests length and/or range BEFORE setting */ + node_instance_set_test_method set_test; + /** sets object value, only called when set_test() was successful */ + node_instance_set_value_method set_value; +}; + +snmp_err_t snmp_table_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_table_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +#define SNMP_TABLE_CREATE(oid, columns, get_cell_instance_method, get_next_cell_instance_method, get_value_method, set_test_method, set_value_method) \ + {{{ SNMP_NODE_TABLE, (oid) }, \ + snmp_table_get_instance, \ + snmp_table_get_next_instance }, \ + (u16_t)LWIP_ARRAYSIZE(columns), (columns), \ + (get_cell_instance_method), (get_next_cell_instance_method), \ + (get_value_method), (set_test_method), (set_value_method)} + +#define SNMP_TABLE_GET_COLUMN_FROM_OID(oid) ((oid)[1]) /* first array value is (fixed) row entry (fixed to 1) and 2nd value is column, follow3ed by instance */ + + +/** simple read-only table */ +typedef enum { + SNMP_VARIANT_VALUE_TYPE_U32, + SNMP_VARIANT_VALUE_TYPE_S32, + SNMP_VARIANT_VALUE_TYPE_PTR, + SNMP_VARIANT_VALUE_TYPE_CONST_PTR +} snmp_table_column_data_type_t; + +struct snmp_table_simple_col_def +{ + u32_t index; + u8_t asn1_type; + snmp_table_column_data_type_t data_type; /* depending of what union member is used to store the value*/ +}; + +/** simple read-only table node */ +struct snmp_table_simple_node +{ + /* inherited "base class" members */ + struct snmp_leaf_node node; + u16_t column_count; + const struct snmp_table_simple_col_def* columns; + snmp_err_t (*get_cell_value)(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len); + snmp_err_t (*get_next_cell_instance_and_value)(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len); +}; + +snmp_err_t snmp_table_simple_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_table_simple_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +#define SNMP_TABLE_CREATE_SIMPLE(oid, columns, get_cell_value_method, get_next_cell_instance_and_value_method) \ + {{{ SNMP_NODE_TABLE, (oid) }, \ + snmp_table_simple_get_instance, \ + snmp_table_simple_get_next_instance }, \ + (u16_t)LWIP_ARRAYSIZE(columns), (columns), (get_cell_value_method), (get_next_cell_instance_and_value_method) } + +s16_t snmp_table_extract_value_from_s32ref(struct snmp_node_instance* instance, void* value); +s16_t snmp_table_extract_value_from_u32ref(struct snmp_node_instance* instance, void* value); +s16_t snmp_table_extract_value_from_refconstptr(struct snmp_node_instance* instance, void* value); + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_TABLE_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_threadsync.h b/tools/sdk/include/lwip/lwip/apps/snmp_threadsync.h new file mode 100644 index 00000000000..a25dbf2d0f0 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_threadsync.h @@ -0,0 +1,114 @@ +/** + * @file + * SNMP server MIB API to implement thread synchronization + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ + +#ifndef LWIP_HDR_APPS_SNMP_THREADSYNC_H +#define LWIP_HDR_APPS_SNMP_THREADSYNC_H + +#include "lwip/apps/snmp_opts.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/apps/snmp_core.h" +#include "lwip/sys.h" + +typedef void (*snmp_threadsync_called_fn)(void* arg); +typedef void (*snmp_threadsync_synchronizer_fn)(snmp_threadsync_called_fn fn, void* arg); + + +/** Thread sync runtime data. For internal usage only. */ +struct threadsync_data +{ + union { + snmp_err_t err; + s16_t s16; + } retval; + union { + const u32_t *root_oid; + void *value; + } arg1; + union { + u8_t root_oid_len; + u16_t len; + } arg2; + const struct snmp_threadsync_node *threadsync_node; + struct snmp_node_instance proxy_instance; +}; + +/** Thread sync instance. Needed EXCATLY once for every thread to be synced into. */ +struct snmp_threadsync_instance +{ + sys_sem_t sem; + sys_mutex_t sem_usage_mutex; + snmp_threadsync_synchronizer_fn sync_fn; + struct threadsync_data data; +}; + +/** SNMP thread sync proxy leaf node */ +struct snmp_threadsync_node +{ + /* inherited "base class" members */ + struct snmp_leaf_node node; + + const struct snmp_leaf_node *target; + struct snmp_threadsync_instance *instance; +}; + +snmp_err_t snmp_threadsync_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_threadsync_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +/** Create thread sync proxy node */ +#define SNMP_CREATE_THREAD_SYNC_NODE(oid, target_leaf_node, threadsync_instance) \ + {{{ SNMP_NODE_THREADSYNC, (oid) }, \ + snmp_threadsync_get_instance, \ + snmp_threadsync_get_next_instance }, \ + (target_leaf_node), \ + (threadsync_instance) } + +/** Create thread sync instance data */ +void snmp_threadsync_init(struct snmp_threadsync_instance *instance, snmp_threadsync_synchronizer_fn sync_fn); + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_THREADSYNC_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmpv3.h b/tools/sdk/include/lwip/lwip/apps/snmpv3.h new file mode 100644 index 00000000000..c99fed4e101 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmpv3.h @@ -0,0 +1,90 @@ +/** + * @file + * Additional SNMPv3 functionality RFC3414 and RFC3826. + */ + +/* + * Copyright (c) 2016 Elias Oenal. + * All rights reserved. + * + * 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. + * + * Author: Elias Oenal + */ + +#ifndef LWIP_HDR_APPS_SNMP_V3_H +#define LWIP_HDR_APPS_SNMP_V3_H + +#include "lwip/apps/snmp_opts.h" +#include "lwip/err.h" + +#if LWIP_SNMP && LWIP_SNMP_V3 + +#define SNMP_V3_AUTH_ALGO_INVAL 0 +#define SNMP_V3_AUTH_ALGO_MD5 1 +#define SNMP_V3_AUTH_ALGO_SHA 2 + +#define SNMP_V3_PRIV_ALGO_INVAL 0 +#define SNMP_V3_PRIV_ALGO_DES 1 +#define SNMP_V3_PRIV_ALGO_AES 2 + +#define SNMP_V3_PRIV_MODE_DECRYPT 0 +#define SNMP_V3_PRIV_MODE_ENCRYPT 1 + +/* + * The following callback functions must be implemented by the application. + * There is a dummy implementation in snmpv3_dummy.c. + */ + +void snmpv3_get_engine_id(const char **id, u8_t *len); +err_t snmpv3_set_engine_id(const char* id, u8_t len); + +u32_t snmpv3_get_engine_boots(void); +void snmpv3_set_engine_boots(u32_t boots); + +u32_t snmpv3_get_engine_time(void); +void snmpv3_reset_engine_time(void); + +err_t snmpv3_get_user(const char* username, u8_t *auth_algo, u8_t *auth_key, u8_t *priv_algo, u8_t *priv_key); + +/* The following functions are provided by the SNMPv3 agent */ + +void snmpv3_engine_id_changed(void); + +void snmpv3_password_to_key_md5( + const u8_t *password, /* IN */ + u8_t passwordlen, /* IN */ + const u8_t *engineID, /* IN - pointer to snmpEngineID */ + u8_t engineLength, /* IN - length of snmpEngineID */ + u8_t *key); /* OUT - pointer to caller 16-octet buffer */ + +void snmpv3_password_to_key_sha( + const u8_t *password, /* IN */ + u8_t passwordlen, /* IN */ + const u8_t *engineID, /* IN - pointer to snmpEngineID */ + u8_t engineLength, /* IN - length of snmpEngineID */ + u8_t *key); /* OUT - pointer to caller 20-octet buffer */ + +#endif + +#endif /* LWIP_HDR_APPS_SNMP_V3_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/sntp.h b/tools/sdk/include/lwip/lwip/apps/sntp.h new file mode 100644 index 00000000000..40df9cc590f --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/sntp.h @@ -0,0 +1,76 @@ +/** + * @file + * SNTP client API + */ + +/* + * Copyright (c) 2007-2009 Frédéric Bernon, Simon Goldschmidt + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Frédéric Bernon, Simon Goldschmidt + * + */ +#ifndef LWIP_HDR_APPS_SNTP_H +#define LWIP_HDR_APPS_SNTP_H + +#include "lwip/apps/sntp_opts.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* SNTP operating modes: default is to poll using unicast. + The mode has to be set before calling sntp_init(). */ +#define SNTP_OPMODE_POLL 0 +#define SNTP_OPMODE_LISTENONLY 1 +void sntp_setoperatingmode(u8_t operating_mode); +u8_t sntp_getoperatingmode(void); + +void sntp_init(void); +void sntp_stop(void); +u8_t sntp_enabled(void); + +void sntp_setserver(u8_t idx, const ip_addr_t *addr); +const ip_addr_t* sntp_getserver(u8_t idx); + +#if SNTP_SERVER_DNS +void sntp_setservername(u8_t idx, char *server); +char *sntp_getservername(u8_t idx); +#endif /* SNTP_SERVER_DNS */ + +#if SNTP_GET_SERVERS_FROM_DHCP +void sntp_servermode_dhcp(int set_servers_from_dhcp); +#else /* SNTP_GET_SERVERS_FROM_DHCP */ +#define sntp_servermode_dhcp(x) +#endif /* SNTP_GET_SERVERS_FROM_DHCP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNTP_H */ diff --git a/tools/sdk/include/lwip/apps/sntp/sntp_opts.h b/tools/sdk/include/lwip/lwip/apps/sntp_opts.h similarity index 80% rename from tools/sdk/include/lwip/apps/sntp/sntp_opts.h rename to tools/sdk/include/lwip/lwip/apps/sntp_opts.h index c8a39649367..dee0f0a41bd 100644 --- a/tools/sdk/include/lwip/apps/sntp/sntp_opts.h +++ b/tools/sdk/include/lwip/lwip/apps/sntp_opts.h @@ -1,3 +1,8 @@ +/** + * @file + * SNTP client options list + */ + /* * Copyright (c) 2007-2009 Frédéric Bernon, Simon Goldschmidt * All rights reserved. @@ -34,48 +39,53 @@ #include "lwip/opt.h" +/** + * @defgroup sntp_opts Options + * @ingroup sntp + * @{ + */ + /** SNTP macro to change system time in seconds * Define SNTP_SET_SYSTEM_TIME_US(sec, us) to set the time in microseconds instead of this one * if you need the additional precision. */ -#ifndef SNTP_SET_SYSTEM_TIME +#if !defined SNTP_SET_SYSTEM_TIME || defined __DOXYGEN__ #define SNTP_SET_SYSTEM_TIME(sec) LWIP_UNUSED_ARG(sec) #endif /** The maximum number of SNTP servers that can be set */ -#ifndef SNTP_MAX_SERVERS +#if !defined SNTP_MAX_SERVERS || defined __DOXYGEN__ #define SNTP_MAX_SERVERS LWIP_DHCP_MAX_NTP_SERVERS #endif /** Set this to 1 to implement the callback function called by dhcp when * NTP servers are received. */ -#ifndef SNTP_GET_SERVERS_FROM_DHCP +#if !defined SNTP_GET_SERVERS_FROM_DHCP || defined __DOXYGEN__ #define SNTP_GET_SERVERS_FROM_DHCP LWIP_DHCP_GET_NTP_SRV #endif -/* Set this to 1 to support DNS names (or IP address strings) to set sntp servers */ -#ifndef SNTP_SERVER_DNS +/** Set this to 1 to support DNS names (or IP address strings) to set sntp servers + * One server address/name can be defined as default if SNTP_SERVER_DNS == 1: + * \#define SNTP_SERVER_ADDRESS "pool.ntp.org" + */ +#if !defined SNTP_SERVER_DNS || defined __DOXYGEN__ #define SNTP_SERVER_DNS 1 #endif -/** One server address/name can be defined as default if SNTP_SERVER_DNS == 1: - * #define SNTP_SERVER_ADDRESS "pool.ntp.org" - */ - /** * SNTP_DEBUG: Enable debugging for SNTP. */ -#ifndef SNTP_DEBUG +#if !defined SNTP_DEBUG || defined __DOXYGEN__ #define SNTP_DEBUG LWIP_DBG_OFF #endif /** SNTP server port */ -#ifndef SNTP_PORT +#if !defined SNTP_PORT || defined __DOXYGEN__ #define SNTP_PORT 123 #endif /** Set this to 1 to allow config of SNTP server(s) by DNS name */ -#ifndef SNTP_SERVER_DNS +#if !defined SNTP_SERVER_DNS || defined __DOXYGEN__ #define SNTP_SERVER_DNS 0 #endif @@ -93,7 +103,7 @@ * currently a cozy number like one second. This check avoids using a * server whose synchronization source has expired for a very long time. */ -#ifndef SNTP_CHECK_RESPONSE +#if !defined SNTP_CHECK_RESPONSE || defined __DOXYGEN__ #define SNTP_CHECK_RESPONSE 0 #endif @@ -103,14 +113,14 @@ * which must return the delay in milliseconds as u32_t. * Turned off by default. */ -#ifndef SNTP_STARTUP_DELAY +#if !defined SNTP_STARTUP_DELAY || defined __DOXYGEN__ #define SNTP_STARTUP_DELAY 0 #endif /** If you want the startup delay to be a function, define this * to a function (including the brackets) and define SNTP_STARTUP_DELAY to 1. */ -#ifndef SNTP_STARTUP_DELAY_FUNC +#if !defined SNTP_STARTUP_DELAY_FUNC || defined __DOXYGEN__ #define SNTP_STARTUP_DELAY_FUNC SNTP_STARTUP_DELAY #endif @@ -118,21 +128,21 @@ * Also used as retry timeout - this shouldn't be too low. * Default is 3 seconds. */ -#ifndef SNTP_RECV_TIMEOUT +#if !defined SNTP_RECV_TIMEOUT || defined __DOXYGEN__ #define SNTP_RECV_TIMEOUT 3000 #endif /** SNTP update delay - in milliseconds * Default is 1 hour. Must not be beolw 15 seconds by specification (i.e. 15000) */ -#ifndef SNTP_UPDATE_DELAY +#if !defined SNTP_UPDATE_DELAY || defined __DOXYGEN__ #define SNTP_UPDATE_DELAY 3600000 #endif /** SNTP macro to get system time, used with SNTP_CHECK_RESPONSE >= 2 * to send in request and compare in response. */ -#ifndef SNTP_GET_SYSTEM_TIME +#if !defined SNTP_GET_SYSTEM_TIME || defined __DOXYGEN__ #define SNTP_GET_SYSTEM_TIME(sec, us) do { (sec) = 0; (us) = 0; } while(0) #endif @@ -140,20 +150,24 @@ * received is invalid. * This is doubled with each retry until SNTP_RETRY_TIMEOUT_MAX is reached. */ -#ifndef SNTP_RETRY_TIMEOUT +#if !defined SNTP_RETRY_TIMEOUT || defined __DOXYGEN__ #define SNTP_RETRY_TIMEOUT SNTP_RECV_TIMEOUT #endif /** Maximum retry timeout (in milliseconds). */ -#ifndef SNTP_RETRY_TIMEOUT_MAX +#if !defined SNTP_RETRY_TIMEOUT_MAX || defined __DOXYGEN__ #define SNTP_RETRY_TIMEOUT_MAX (SNTP_RETRY_TIMEOUT * 10) #endif /** Increase retry timeout with every retry sent * Default is on to conform to RFC. */ -#ifndef SNTP_RETRY_TIMEOUT_EXP +#if !defined SNTP_RETRY_TIMEOUT_EXP || defined __DOXYGEN__ #define SNTP_RETRY_TIMEOUT_EXP 1 #endif +/** + * @} + */ + #endif /* LWIP_HDR_APPS_SNTP_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/tftp_opts.h b/tools/sdk/include/lwip/lwip/apps/tftp_opts.h new file mode 100644 index 00000000000..6968a803b43 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/tftp_opts.h @@ -0,0 +1,105 @@ +/****************************************************************//** + * + * @file tftp_opts.h + * + * @author Logan Gunthorpe + * + * @brief Trivial File Transfer Protocol (RFC 1350) implementation options + * + * Copyright (c) Deltatee Enterprises Ltd. 2013 + * All rights reserved. + * + ********************************************************************/ + +/* + * 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. + * + * Author: Logan Gunthorpe + * + */ + +#ifndef LWIP_HDR_APPS_TFTP_OPTS_H +#define LWIP_HDR_APPS_TFTP_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup tftp_opts Options + * @ingroup tftp + * @{ + */ + +/** + * Enable TFTP debug messages + */ +#if !defined TFTP_DEBUG || defined __DOXYGEN__ +#define TFTP_DEBUG LWIP_DBG_ON +#endif + +/** + * TFTP server port + */ +#if !defined TFTP_PORT || defined __DOXYGEN__ +#define TFTP_PORT 69 +#endif + +/** + * TFTP timeout + */ +#if !defined TFTP_TIMEOUT_MSECS || defined __DOXYGEN__ +#define TFTP_TIMEOUT_MSECS 10000 +#endif + +/** + * Max. number of retries when a file is read from server + */ +#if !defined TFTP_MAX_RETRIES || defined __DOXYGEN__ +#define TFTP_MAX_RETRIES 5 +#endif + +/** + * TFTP timer cyclic interval + */ +#if !defined TFTP_TIMER_MSECS || defined __DOXYGEN__ +#define TFTP_TIMER_MSECS 50 +#endif + +/** + * Max. length of TFTP filename + */ +#if !defined TFTP_MAX_FILENAME_LEN || defined __DOXYGEN__ +#define TFTP_MAX_FILENAME_LEN 20 +#endif + +/** + * Max. length of TFTP mode + */ +#if !defined TFTP_MAX_MODE_LEN || defined __DOXYGEN__ +#define TFTP_MAX_MODE_LEN 7 +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_TFTP_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/tftp_server.h b/tools/sdk/include/lwip/lwip/apps/tftp_server.h new file mode 100644 index 00000000000..3fbe701e0a2 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/tftp_server.h @@ -0,0 +1,94 @@ +/****************************************************************//** + * + * @file tftp_server.h + * + * @author Logan Gunthorpe + * + * @brief Trivial File Transfer Protocol (RFC 1350) + * + * Copyright (c) Deltatee Enterprises Ltd. 2013 + * All rights reserved. + * + ********************************************************************/ + +/* + * 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. + * + * Author: Logan Gunthorpe + * + */ + +#ifndef LWIP_HDR_APPS_TFTP_SERVER_H +#define LWIP_HDR_APPS_TFTP_SERVER_H + +#include "lwip/apps/tftp_opts.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @ingroup tftp + * TFTP context containing callback functions for TFTP transfers + */ +struct tftp_context { + /** + * Open file for read/write. + * @param fname Filename + * @param mode Mode string from TFTP RFC 1350 (netascii, octet, mail) + * @param write Flag indicating read (0) or write (!= 0) access + * @returns File handle supplied to other functions + */ + void* (*open)(const char* fname, const char* mode, u8_t write); + /** + * Close file handle + * @param handle File handle returned by open() + */ + void (*close)(void* handle); + /** + * Read from file + * @param handle File handle returned by open() + * @param buf Target buffer to copy read data to + * @param bytes Number of bytes to copy to buf + * @returns >= 0: Success; < 0: Error + */ + int (*read)(void* handle, void* buf, int bytes); + /** + * Write to file + * @param handle File handle returned by open() + * @param pbuf PBUF adjusted such that payload pointer points + * to the beginning of write data. In other words, + * TFTP headers are stripped off. + * @returns >= 0: Success; < 0: Error + */ + int (*write)(void* handle, struct pbuf* p); +}; + +err_t tftp_init(const struct tftp_context* ctx); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_TFTP_SERVER_H */ diff --git a/tools/sdk/include/lwip/lwip/arch.h b/tools/sdk/include/lwip/lwip/arch.h old mode 100755 new mode 100644 index 7b99c2606b8..31d92ca3f44 --- a/tools/sdk/include/lwip/lwip/arch.h +++ b/tools/sdk/include/lwip/lwip/arch.h @@ -1,3 +1,8 @@ +/** + * @file + * Support for different processor and compiler architectures + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -42,189 +47,269 @@ #include "arch/cc.h" -/** Temporary: define format string for size_t if not defined in cc.h */ -#ifndef SZT_F -#define SZT_F U32_F -#endif /* SZT_F */ -/** Temporary upgrade helper: define format string for u8_t as hex if not - defined in cc.h */ +/** + * @defgroup compiler_abstraction Compiler/platform abstraction + * @ingroup sys_layer + * All defines related to this section must not be placed in lwipopts.h, + * but in arch/cc.h! + * These options cannot be \#defined in lwipopts.h since they are not options + * of lwIP itself, but options of the lwIP port to your system. + * @{ + */ + +/** Define the byte order of the system. + * Needed for conversion of network data to host byte order. + * Allowed values: LITTLE_ENDIAN and BIG_ENDIAN + */ +#ifndef BYTE_ORDER +#define BYTE_ORDER LITTLE_ENDIAN +#endif + +/** Define random number generator function of your system */ +#ifdef __DOXYGEN__ +#define LWIP_RAND() ((u32_t)rand()) +#endif + +/** Platform specific diagnostic output.\n + * Note the default implementation pulls in printf, which may + * in turn pull in a lot of standard libary code. In resource-constrained + * systems, this should be defined to something less resource-consuming. + */ +#ifndef LWIP_PLATFORM_DIAG +#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0) +#include +#include +#endif + +/** Platform specific assertion handling.\n + * Note the default implementation pulls in printf, fflush and abort, which may + * in turn pull in a lot of standard libary code. In resource-constrained + * systems, this should be defined to something less resource-consuming. + */ +#ifndef LWIP_PLATFORM_ASSERT +#define LWIP_PLATFORM_ASSERT(x) do {printf("Assertion \"%s\" failed at line %d in %s\n", \ + x, __LINE__, __FILE__); fflush(NULL); abort();} while(0) +#include +#include +#endif + +/** Define this to 1 in arch/cc.h of your port if you do not want to + * include stddef.h header to get size_t. You need to typedef size_t + * by yourself in this case. + */ +#ifndef LWIP_NO_STDDEF_H +#define LWIP_NO_STDDEF_H 0 +#endif + +#if !LWIP_NO_STDDEF_H +#include /* for size_t */ +#endif + +/** Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the stdint.h header. You need to typedef the generic types listed in + * lwip/arch.h yourself in this case (u8_t, u16_t...). + */ +#ifndef LWIP_NO_STDINT_H +#define LWIP_NO_STDINT_H 0 +#endif + +/* Define generic types used in lwIP */ +#if !LWIP_NO_STDINT_H +#include +typedef uint8_t u8_t; +typedef int8_t s8_t; +typedef uint16_t u16_t; +typedef int16_t s16_t; +typedef uint32_t u32_t; +typedef int32_t s32_t; +#endif + +/** Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the inttypes.h header. You need to define the format strings listed in + * lwip/arch.h yourself in this case (X8_F, U16_F...). + */ +#ifndef LWIP_NO_INTTYPES_H +#define LWIP_NO_INTTYPES_H 0 +#endif + +/* Define (sn)printf formatters for these lwIP types */ +#if !LWIP_NO_INTTYPES_H +#include #ifndef X8_F -#define X8_F "02x" -#endif /* X8_F */ +#define X8_F "02" PRIx8 +#endif +#ifndef U16_F +#define U16_F PRIu16 +#endif +#ifndef S16_F +#define S16_F PRId16 +#endif +#ifndef X16_F +#define X16_F PRIx16 +#endif +#ifndef U32_F +#define U32_F PRIu32 +#endif +#ifndef S32_F +#define S32_F PRId32 +#endif +#ifndef X32_F +#define X32_F PRIx32 +#endif +#ifndef SZT_F +#define SZT_F PRIuPTR +#endif +#endif + +/** Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the limits.h header. You need to define the type limits yourself in this case + * (e.g. INT_MAX). + */ +#ifndef LWIP_NO_LIMITS_H +#define LWIP_NO_LIMITS_H 0 +#endif + +/* Include limits.h? */ +#if !LWIP_NO_LIMITS_H +#include +#endif + +/** C++ const_cast(val) equivalent to remove constness from a value (GCC -Wcast-qual) */ +#ifndef LWIP_CONST_CAST +#define LWIP_CONST_CAST(target_type, val) ((target_type)((ptrdiff_t)val)) +#endif + +/** Get rid of alignment cast warnings (GCC -Wcast-align) */ +#ifndef LWIP_ALIGNMENT_CAST +#define LWIP_ALIGNMENT_CAST(target_type, val) LWIP_CONST_CAST(target_type, val) +#endif + +/** Get rid of warnings related to pointer-to-numeric and vice-versa casts, + * e.g. "conversion from 'u8_t' to 'void *' of greater size" + */ +#ifndef LWIP_PTR_NUMERIC_CAST +#define LWIP_PTR_NUMERIC_CAST(target_type, val) LWIP_CONST_CAST(target_type, val) +#endif + +/** Allocates a memory buffer of specified size that is of sufficient size to align + * its start address using LWIP_MEM_ALIGN. + * You can declare your own version here e.g. to enforce alignment without adding + * trailing padding bytes (see LWIP_MEM_ALIGN_BUFFER) or your own section placement + * requirements.\n + * e.g. if you use gcc and need 32 bit alignment:\n + * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u8_t variable_name[size] \_\_attribute\_\_((aligned(4)))\n + * or more portable:\n + * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u32_t variable_name[(size + sizeof(u32_t) - 1) / sizeof(u32_t)] + */ +#ifndef LWIP_DECLARE_MEMORY_ALIGNED +#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u8_t variable_name[LWIP_MEM_ALIGN_BUFFER(size)] +#endif + +/** Calculate memory size for an aligned buffer - returns the next highest + * multiple of MEM_ALIGNMENT (e.g. LWIP_MEM_ALIGN_SIZE(3) and + * LWIP_MEM_ALIGN_SIZE(4) will both yield 4 for MEM_ALIGNMENT == 4). + */ +#ifndef LWIP_MEM_ALIGN_SIZE +#define LWIP_MEM_ALIGN_SIZE(size) (((size) + MEM_ALIGNMENT - 1U) & ~(MEM_ALIGNMENT-1U)) +#endif + +/** Calculate safe memory size for an aligned buffer when using an unaligned + * type as storage. This includes a safety-margin on (MEM_ALIGNMENT - 1) at the + * start (e.g. if buffer is u8_t[] and actual data will be u32_t*) + */ +#ifndef LWIP_MEM_ALIGN_BUFFER +#define LWIP_MEM_ALIGN_BUFFER(size) (((size) + MEM_ALIGNMENT - 1U)) +#endif + +/** Align a memory pointer to the alignment defined by MEM_ALIGNMENT + * so that ADDR % MEM_ALIGNMENT == 0 + */ +#ifndef LWIP_MEM_ALIGN +#define LWIP_MEM_ALIGN(addr) ((void *)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) & ~(mem_ptr_t)(MEM_ALIGNMENT-1))) +#endif #ifdef __cplusplus extern "C" { #endif +/** Packed structs support. + * Placed BEFORE declaration of a packed struct.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_BEGIN #define PACK_STRUCT_BEGIN #endif /* PACK_STRUCT_BEGIN */ +/** Packed structs support. + * Placed AFTER declaration of a packed struct.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_END #define PACK_STRUCT_END #endif /* PACK_STRUCT_END */ +/** Packed structs support. + * Placed between end of declaration of a packed struct and trailing semicolon.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_STRUCT +#if defined(__GNUC__) || defined(__clang__) +#define PACK_STRUCT_STRUCT __attribute__((packed)) +#else #define PACK_STRUCT_STRUCT +#endif #endif /* PACK_STRUCT_STRUCT */ +/** Packed structs support. + * Wraps u32_t and u16_t members.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_FIELD #define PACK_STRUCT_FIELD(x) x #endif /* PACK_STRUCT_FIELD */ -/* Used for struct fields of u8_t, - * where some compilers warn that packing is not necessary */ +/** Packed structs support. + * Wraps u8_t members, where some compilers warn that packing is not necessary.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_FLD_8 #define PACK_STRUCT_FLD_8(x) PACK_STRUCT_FIELD(x) #endif /* PACK_STRUCT_FLD_8 */ -/* Used for struct fields of that are packed structs themself, - * where some compilers warn that packing is not necessary */ +/** Packed structs support. + * Wraps members that are packed structs themselves, where some compilers warn that packing is not necessary.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_FLD_S #define PACK_STRUCT_FLD_S(x) PACK_STRUCT_FIELD(x) #endif /* PACK_STRUCT_FLD_S */ +/** Packed structs support using \#include files before and after struct to be packed.\n + * The file included BEFORE the struct is "arch/bpstruct.h".\n + * The file included AFTER the struct is "arch/epstruct.h".\n + * This can be used to implement struct packing on MS Visual C compilers, see + * the Win32 port in the lwIP contrib repository for reference. + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifdef __DOXYGEN__ +#define PACK_STRUCT_USE_INCLUDES +#endif +/** Eliminates compiler warning about unused arguments (GCC -Wextra -Wunused). */ #ifndef LWIP_UNUSED_ARG #define LWIP_UNUSED_ARG(x) (void)x #endif /* LWIP_UNUSED_ARG */ - -#ifdef LWIP_PROVIDE_ERRNO - -#define EPERM 1 /* Operation not permitted */ -#define ENOENT 2 /* No such file or directory */ -#define ESRCH 3 /* No such process */ -#define EINTR 4 /* Interrupted system call */ -#define EIO 5 /* I/O error */ -#define ENXIO 6 /* No such device or address */ -#define E2BIG 7 /* Arg list too long */ -#define ENOEXEC 8 /* Exec format error */ -#define EBADF 9 /* Bad file number */ -#define ECHILD 10 /* No child processes */ -#define EAGAIN 11 /* Try again */ -#define ENOMEM 12 /* Out of memory */ -#define EACCES 13 /* Permission denied */ -#define EFAULT 14 /* Bad address */ -#define ENOTBLK 15 /* Block device required */ -#define EBUSY 16 /* Device or resource busy */ -#define EEXIST 17 /* File exists */ -#define EXDEV 18 /* Cross-device link */ -#define ENODEV 19 /* No such device */ -#define ENOTDIR 20 /* Not a directory */ -#define EISDIR 21 /* Is a directory */ -#define EINVAL 22 /* Invalid argument */ -#define ENFILE 23 /* File table overflow */ -#define EMFILE 24 /* Too many open files */ -#define ENOTTY 25 /* Not a typewriter */ -#define ETXTBSY 26 /* Text file busy */ -#define EFBIG 27 /* File too large */ -#define ENOSPC 28 /* No space left on device */ -#define ESPIPE 29 /* Illegal seek */ -#define EROFS 30 /* Read-only file system */ -#define EMLINK 31 /* Too many links */ -#define EPIPE 32 /* Broken pipe */ -#define EDOM 33 /* Math argument out of domain of func */ -#define ERANGE 34 /* Math result not representable */ -#define EDEADLK 35 /* Resource deadlock would occur */ -#define ENAMETOOLONG 36 /* File name too long */ -#define ENOLCK 37 /* No record locks available */ -#define ENOSYS 38 /* Function not implemented */ -#define ENOTEMPTY 39 /* Directory not empty */ -#define ELOOP 40 /* Too many symbolic links encountered */ -#define EWOULDBLOCK EAGAIN /* Operation would block */ -#define ENOMSG 42 /* No message of desired type */ -#define EIDRM 43 /* Identifier removed */ -#define ECHRNG 44 /* Channel number out of range */ -#define EL2NSYNC 45 /* Level 2 not synchronized */ -#define EL3HLT 46 /* Level 3 halted */ -#define EL3RST 47 /* Level 3 reset */ -#define ELNRNG 48 /* Link number out of range */ -#define EUNATCH 49 /* Protocol driver not attached */ -#define ENOCSI 50 /* No CSI structure available */ -#define EL2HLT 51 /* Level 2 halted */ -#define EBADE 52 /* Invalid exchange */ -#define EBADR 53 /* Invalid request descriptor */ -#define EXFULL 54 /* Exchange full */ -#define ENOANO 55 /* No anode */ -#define EBADRQC 56 /* Invalid request code */ -#define EBADSLT 57 /* Invalid slot */ - -#define EDEADLOCK EDEADLK - -#define EBFONT 59 /* Bad font file format */ -#define ENOSTR 60 /* Device not a stream */ -#define ENODATA 61 /* No data available */ -#define ETIME 62 /* Timer expired */ -#define ENOSR 63 /* Out of streams resources */ -#define ENONET 64 /* Machine is not on the network */ -#define ENOPKG 65 /* Package not installed */ -#define EREMOTE 66 /* Object is remote */ -#define ENOLINK 67 /* Link has been severed */ -#define EADV 68 /* Advertise error */ -#define ESRMNT 69 /* Srmount error */ -#define ECOMM 70 /* Communication error on send */ -#define EPROTO 71 /* Protocol error */ -#define EMULTIHOP 72 /* Multihop attempted */ -#define EDOTDOT 73 /* RFS specific error */ -#define EBADMSG 74 /* Not a data message */ -#define EOVERFLOW 75 /* Value too large for defined data type */ -#define ENOTUNIQ 76 /* Name not unique on network */ -#define EBADFD 77 /* File descriptor in bad state */ -#define EREMCHG 78 /* Remote address changed */ -#define ELIBACC 79 /* Can not access a needed shared library */ -#define ELIBBAD 80 /* Accessing a corrupted shared library */ -#define ELIBSCN 81 /* .lib section in a.out corrupted */ -#define ELIBMAX 82 /* Attempting to link in too many shared libraries */ -#define ELIBEXEC 83 /* Cannot exec a shared library directly */ -#define EILSEQ 84 /* Illegal byte sequence */ -#define ERESTART 85 /* Interrupted system call should be restarted */ -#define ESTRPIPE 86 /* Streams pipe error */ -#define EUSERS 87 /* Too many users */ -#define ENOTSOCK 88 /* Socket operation on non-socket */ -#define EDESTADDRREQ 89 /* Destination address required */ -#define EMSGSIZE 90 /* Message too long */ -#define EPROTOTYPE 91 /* Protocol wrong type for socket */ -#define ENOPROTOOPT 92 /* Protocol not available */ -#define EPROTONOSUPPORT 93 /* Protocol not supported */ -#define ESOCKTNOSUPPORT 94 /* Socket type not supported */ -#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ -#define EPFNOSUPPORT 96 /* Protocol family not supported */ -#define EAFNOSUPPORT 97 /* Address family not supported by protocol */ -#define EADDRINUSE 98 /* Address already in use */ -#define EADDRNOTAVAIL 99 /* Cannot assign requested address */ -#define ENETDOWN 100 /* Network is down */ -#define ENETUNREACH 101 /* Network is unreachable */ -#define ENETRESET 102 /* Network dropped connection because of reset */ -#define ECONNABORTED 103 /* Software caused connection abort */ -#define ECONNRESET 104 /* Connection reset by peer */ -#define ENOBUFS 105 /* No buffer space available */ -#define EISCONN 106 /* Transport endpoint is already connected */ -#define ENOTCONN 107 /* Transport endpoint is not connected */ -#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ -#define ETOOMANYREFS 109 /* Too many references: cannot splice */ -#define ETIMEDOUT 110 /* Connection timed out */ -#define ECONNREFUSED 111 /* Connection refused */ -#define EHOSTDOWN 112 /* Host is down */ -#define EHOSTUNREACH 113 /* No route to host */ -#define EALREADY 114 /* Operation already in progress */ -#define EINPROGRESS 115 /* Operation now in progress */ -#define ESTALE 116 /* Stale NFS file handle */ -#define EUCLEAN 117 /* Structure needs cleaning */ -#define ENOTNAM 118 /* Not a XENIX named type file */ -#define ENAVAIL 119 /* No XENIX semaphores available */ -#define EISNAM 120 /* Is a named type file */ -#define EREMOTEIO 121 /* Remote I/O error */ -#define EDQUOT 122 /* Quota exceeded */ - -#define ENOMEDIUM 123 /* No medium found */ -#define EMEDIUMTYPE 124 /* Wrong medium type */ - -#ifndef errno -extern int errno; -#endif - -#endif /* LWIP_PROVIDE_ERRNO */ +/** + * @} + */ #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/autoip.h b/tools/sdk/include/lwip/lwip/autoip.h old mode 100755 new mode 100644 index 16eac510e9a..1d85bccff8b --- a/tools/sdk/include/lwip/lwip/autoip.h +++ b/tools/sdk/include/lwip/lwip/autoip.h @@ -36,9 +36,6 @@ * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform * with RFC 3927. * - * - * Please coordinate changes and requests with Dominik Spies - * */ #ifndef LWIP_HDR_AUTOIP_H @@ -50,70 +47,48 @@ #include "lwip/netif.h" /* #include "lwip/udp.h" */ -#include "netif/etharp.h" +#include "lwip/etharp.h" #ifdef __cplusplus extern "C" { #endif -/* AutoIP Timing */ +/** AutoIP Timing */ #define AUTOIP_TMR_INTERVAL 100 #define AUTOIP_TICKS_PER_SECOND (1000 / AUTOIP_TMR_INTERVAL) -/* RFC 3927 Constants */ -#define PROBE_WAIT 1 /* second (initial random delay) */ -#define PROBE_MIN 1 /* second (minimum delay till repeated probe) */ -#define PROBE_MAX 2 /* seconds (maximum delay till repeated probe) */ -#define PROBE_NUM 3 /* (number of probe packets) */ -#define ANNOUNCE_NUM 2 /* (number of announcement packets) */ -#define ANNOUNCE_INTERVAL 2 /* seconds (time between announcement packets) */ -#define ANNOUNCE_WAIT 2 /* seconds (delay before announcing) */ -#define MAX_CONFLICTS LWIP_AUTOIP_MAX_CONFLICTS /* (max conflicts before rate limiting) */ -#define RATE_LIMIT_INTERVAL LWIP_AUTOIP_RATE_LIMIT_INTERVAL /* seconds (delay between successive attempts) */ -#define DEFEND_INTERVAL 10 /* seconds (min. wait between defensive ARPs) */ - -/* AutoIP client states */ -#define AUTOIP_STATE_OFF 0 -#define AUTOIP_STATE_PROBING 1 -#define AUTOIP_STATE_ANNOUNCING 2 -#define AUTOIP_STATE_BOUND 3 - +/** AutoIP state information per netif */ struct autoip { - ip4_addr_t llipaddr; /* the currently selected, probed, announced or used LL IP-Address */ - u8_t state; /* current AutoIP state machine state */ - u8_t sent_num; /* sent number of probes or announces, dependent on state */ - u16_t ttw; /* ticks to wait, tick is AUTOIP_TMR_INTERVAL long */ - u8_t lastconflict; /* ticks until a conflict can be solved by defending */ - u8_t tried_llipaddr; /* total number of probed/used Link Local IP-Addresses */ + /** the currently selected, probed, announced or used LL IP-Address */ + ip4_addr_t llipaddr; + /** current AutoIP state machine state */ + u8_t state; + /** sent number of probes or announces, dependent on state */ + u8_t sent_num; + /** ticks to wait, tick is AUTOIP_TMR_INTERVAL long */ + u16_t ttw; + /** ticks until a conflict can be solved by defending */ + u8_t lastconflict; + /** total number of probed/used Link Local IP-Addresses */ + u8_t tried_llipaddr; }; -#define autoip_init() /* Compatibility define, no init needed. */ - -/** Set a struct autoip allocated by the application to work with */ void autoip_set_struct(struct netif *netif, struct autoip *autoip); - /** Remove a struct autoip previously set to the netif using autoip_set_struct() */ #define autoip_remove_struct(netif) do { (netif)->autoip = NULL; } while (0) - -/** Start AutoIP client */ err_t autoip_start(struct netif *netif); - -/** Stop AutoIP client */ err_t autoip_stop(struct netif *netif); - -/** Handles every incoming ARP Packet, called by etharp_arp_input */ void autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr); - -/** Has to be called in loop every AUTOIP_TMR_INTERVAL milliseconds */ void autoip_tmr(void); - -/** Handle a possible change in the network configuration */ void autoip_network_changed(struct netif *netif); +u8_t autoip_supplied_address(const struct netif *netif); + +/* for lwIP internal use by ip4.c */ +u8_t autoip_accept_packet(struct netif *netif, const ip4_addr_t *addr); -/** check if AutoIP supplied netif->ip_addr */ -u8_t autoip_supplied_address(struct netif *netif); +#define netif_autoip_data(netif) ((struct autoip*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP)) #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/debug.h b/tools/sdk/include/lwip/lwip/debug.h old mode 100755 new mode 100644 index 973a633d9de..a142f1cff3c --- a/tools/sdk/include/lwip/lwip/debug.h +++ b/tools/sdk/include/lwip/lwip/debug.h @@ -1,3 +1,8 @@ +/** + * @file + * Debug messages infrastructure + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -35,24 +40,45 @@ #include "lwip/arch.h" #include "lwip/opt.h" -/** lower two bits indicate debug level - * - 0 all - * - 1 warning - * - 2 serious - * - 3 severe +/** + * @defgroup debugging_levels LWIP_DBG_MIN_LEVEL and LWIP_DBG_TYPES_ON values + * @ingroup lwip_opts_debugmsg + * @{ + */ + +/** @name Debug level (LWIP_DBG_MIN_LEVEL) + * @{ */ +/** Debug level: ALL messages*/ #define LWIP_DBG_LEVEL_ALL 0x00 -#define LWIP_DBG_LEVEL_OFF LWIP_DBG_LEVEL_ALL /* compatibility define only */ -#define LWIP_DBG_LEVEL_WARNING 0x01 /* bad checksums, dropped packets, ... */ -#define LWIP_DBG_LEVEL_SERIOUS 0x02 /* memory allocation failures, ... */ +/** Debug level: Warnings. bad checksums, dropped packets, ... */ +#define LWIP_DBG_LEVEL_WARNING 0x01 +/** Debug level: Serious. memory allocation failures, ... */ +#define LWIP_DBG_LEVEL_SERIOUS 0x02 +/** Debug level: Severe */ #define LWIP_DBG_LEVEL_SEVERE 0x03 +/** + * @} + */ + #define LWIP_DBG_MASK_LEVEL 0x03 +/* compatibility define only */ +#define LWIP_DBG_LEVEL_OFF LWIP_DBG_LEVEL_ALL +/** @name Enable/disable debug messages completely (LWIP_DBG_TYPES_ON) + * @{ + */ /** flag for LWIP_DEBUGF to enable that debug message */ #define LWIP_DBG_ON 0x80U /** flag for LWIP_DEBUGF to disable that debug message */ #define LWIP_DBG_OFF 0x00U +/** + * @} + */ +/** @name Debug message types (LWIP_DBG_TYPES_ON) + * @{ + */ /** flag for LWIP_DEBUGF indicating a tracing message (to follow program flow) */ #define LWIP_DBG_TRACE 0x40U /** flag for LWIP_DEBUGF indicating a state debug message (to follow module states) */ @@ -61,14 +87,34 @@ #define LWIP_DBG_FRESH 0x10U /** flag for LWIP_DEBUGF to halt after printing this debug message */ #define LWIP_DBG_HALT 0x08U +/** + * @} + */ /** - * LWIP_NOASSERT: Disable LWIP_ASSERT checks. - * -- To disable assertions define LWIP_NOASSERT in arch/cc.h. + * @} */ + +/** + * @defgroup lwip_assertions Assertion handling + * @ingroup lwip_opts_debug + * @{ + */ +/** + * LWIP_NOASSERT: Disable LWIP_ASSERT checks: + * To disable assertions define LWIP_NOASSERT in arch/cc.h. + */ +#ifdef __DOXYGEN__ +#define LWIP_NOASSERT +#undef LWIP_NOASSERT +#endif +/** + * @} + */ + #ifndef LWIP_NOASSERT -#define LWIP_ASSERT(message, assertion) do { if(!(assertion)) \ - LWIP_PLATFORM_ASSERT(message); } while(0) +#define LWIP_ASSERT(message, assertion) do { if (!(assertion)) { \ + LWIP_PLATFORM_ASSERT(message); }} while(0) #ifndef LWIP_PLATFORM_ASSERT #error "If you want to use LWIP_ASSERT, LWIP_PLATFORM_ASSERT(message) needs to be defined in your arch/cc.h" #endif @@ -76,7 +122,6 @@ #define LWIP_ASSERT(message, assertion) #endif /* LWIP_NOASSERT */ -/** if "expression" isn't true, then print "message" and execute "handler" expression */ #ifndef LWIP_ERROR #ifndef LWIP_NOASSERT #define LWIP_PLATFORM_ERROR(message) LWIP_PLATFORM_ASSERT(message) @@ -86,17 +131,23 @@ #define LWIP_PLATFORM_ERROR(message) #endif +/* if "expression" isn't true, then print "message" and execute "handler" expression */ #define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ LWIP_PLATFORM_ERROR(message); handler;}} while(0) #endif /* LWIP_ERROR */ +/** Enable debug message printing, but only if debug message type is enabled + * AND is of correct type AND is at least LWIP_DBG_LEVEL. + */ +#ifdef __DOXYGEN__ +#define LWIP_DEBUG +#undef LWIP_DEBUG +#endif + #ifdef LWIP_DEBUG #ifndef LWIP_PLATFORM_DIAG #error "If you want to use LWIP_DEBUG, LWIP_PLATFORM_DIAG(message) needs to be defined in your arch/cc.h" #endif -/** print debug message only if debug message type is enabled... - * AND is of correct type AND is at least LWIP_DBG_LEVEL - */ #define LWIP_DEBUGF(debug, message) do { \ if ( \ ((debug) & LWIP_DBG_ON) && \ @@ -114,4 +165,3 @@ #endif /* LWIP_DEBUG */ #endif /* LWIP_HDR_DEBUG_H */ - diff --git a/tools/sdk/include/lwip/lwip/def.h b/tools/sdk/include/lwip/lwip/def.h old mode 100755 new mode 100644 index 49571363cd5..82a9d896f0f --- a/tools/sdk/include/lwip/lwip/def.h +++ b/tools/sdk/include/lwip/lwip/def.h @@ -1,3 +1,8 @@ +/** + * @file + * various utility macros + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -52,43 +57,20 @@ extern "C" { /* Get the number of entries in an array ('x' must NOT be a pointer!) */ #define LWIP_ARRAYSIZE(x) (sizeof(x)/sizeof((x)[0])) -#ifndef NULL -#define NULL ((void *)0) -#endif +/** Create u32_t value from bytes */ +#define LWIP_MAKEU32(a,b,c,d) (((u32_t)((a) & 0xff) << 24) | \ + ((u32_t)((b) & 0xff) << 16) | \ + ((u32_t)((c) & 0xff) << 8) | \ + (u32_t)((d) & 0xff)) -/* Endianess-optimized shifting of two u8_t to create one u16_t */ -#if BYTE_ORDER == LITTLE_ENDIAN -#define LWIP_MAKE_U16(a, b) ((a << 8) | b) +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 #else -#define LWIP_MAKE_U16(a, b) ((b << 8) | a) +#define NULL ((void *)0) #endif - -#ifndef LWIP_PLATFORM_BYTESWAP -#define LWIP_PLATFORM_BYTESWAP 0 #endif -#ifndef LWIP_PREFIX_BYTEORDER_FUNCS -/* workaround for naming collisions on some platforms */ - -#ifdef htons -#undef htons -#endif /* htons */ -#ifdef htonl -#undef htonl -#endif /* htonl */ -#ifdef ntohs -#undef ntohs -#endif /* ntohs */ -#ifdef ntohl -#undef ntohl -#endif /* ntohl */ - -#define htons(x) lwip_htons(x) -#define ntohs(x) lwip_ntohs(x) -#define htonl(x) lwip_htonl(x) -#define ntohl(x) lwip_ntohl(x) -#endif /* LWIP_PREFIX_BYTEORDER_FUNCS */ - #if BYTE_ORDER == BIG_ENDIAN #define lwip_htons(x) (x) #define lwip_ntohs(x) (x) @@ -99,34 +81,61 @@ extern "C" { #define PP_HTONL(x) (x) #define PP_NTOHL(x) (x) #else /* BYTE_ORDER != BIG_ENDIAN */ -#if LWIP_PLATFORM_BYTESWAP -#define lwip_htons(x) LWIP_PLATFORM_HTONS(x) -#define lwip_ntohs(x) LWIP_PLATFORM_HTONS(x) -#define lwip_htonl(x) LWIP_PLATFORM_HTONL(x) -#define lwip_ntohl(x) LWIP_PLATFORM_HTONL(x) -#else /* LWIP_PLATFORM_BYTESWAP */ +#ifndef lwip_htons u16_t lwip_htons(u16_t x); -u16_t lwip_ntohs(u16_t x); +#endif +#define lwip_ntohs(x) lwip_htons(x) + +#ifndef lwip_htonl u32_t lwip_htonl(u32_t x); -u32_t lwip_ntohl(u32_t x); -#endif /* LWIP_PLATFORM_BYTESWAP */ +#endif +#define lwip_ntohl(x) lwip_htonl(x) /* These macros should be calculated by the preprocessor and are used with compile-time constants only (so that there is no little-endian overhead at runtime). */ -#define PP_HTONS(x) ((((x) & 0xff) << 8) | (((x) & 0xff00) >> 8)) +#define PP_HTONS(x) ((((x) & 0x00ffUL) << 8) | (((x) & 0xff00UL) >> 8)) #define PP_NTOHS(x) PP_HTONS(x) -#define PP_HTONL(x) ((((x) & 0xff) << 24) | \ - (((x) & 0xff00) << 8) | \ - (((x) & 0xff0000UL) >> 8) | \ +#define PP_HTONL(x) ((((x) & 0x000000ffUL) << 24) | \ + (((x) & 0x0000ff00UL) << 8) | \ + (((x) & 0x00ff0000UL) >> 8) | \ (((x) & 0xff000000UL) >> 24)) #define PP_NTOHL(x) PP_HTONL(x) - #endif /* BYTE_ORDER == BIG_ENDIAN */ +/* Provide usual function names as macros for users, but this can be turned off */ +#ifndef LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS +#define htons(x) lwip_htons(x) +#define ntohs(x) lwip_ntohs(x) +#define htonl(x) lwip_htonl(x) +#define ntohl(x) lwip_ntohl(x) +#endif + +/* Functions that are not available as standard implementations. + * In cc.h, you can #define these to implementations available on + * your platform to save some code bytes if you use these functions + * in your application, too. + */ + +#ifndef lwip_itoa +/* This can be #defined to itoa() or snprintf(result, bufsize, "%d", number) depending on your platform */ +void lwip_itoa(char* result, size_t bufsize, int number); +#endif +#ifndef lwip_strnicmp +/* This can be #defined to strnicmp() or strncasecmp() depending on your platform */ +int lwip_strnicmp(const char* str1, const char* str2, size_t len); +#endif +#ifndef lwip_stricmp +/* This can be #defined to stricmp() or strcasecmp() depending on your platform */ +int lwip_stricmp(const char* str1, const char* str2); +#endif +#ifndef lwip_strnstr +/* This can be #defined to strnstr() depending on your platform */ +char* lwip_strnstr(const char* buffer, const char* token, size_t n); +#endif + #ifdef __cplusplus } #endif #endif /* LWIP_HDR_DEF_H */ - diff --git a/tools/sdk/include/lwip/lwip/dhcp.h b/tools/sdk/include/lwip/lwip/dhcp.h old mode 100755 new mode 100644 index f282c8ab49c..23a36bb02b9 --- a/tools/sdk/include/lwip/lwip/dhcp.h +++ b/tools/sdk/include/lwip/lwip/dhcp.h @@ -1,3 +1,8 @@ +/** + * @file + * DHCP client API + */ + /* * Copyright (c) 2001-2004 Leon Woestenberg * Copyright (c) 2001-2004 Axon Digital Design B.V., The Netherlands. @@ -45,15 +50,23 @@ extern "C" { #endif /** period (in seconds) of the application calling dhcp_coarse_tmr() */ +#if ESP_DHCP #define DHCP_COARSE_TIMER_SECS 1 +#else +#define DHCP_COARSE_TIMER_SECS 60 +#endif /** period (in milliseconds) of the application calling dhcp_coarse_tmr() */ #define DHCP_COARSE_TIMER_MSECS (DHCP_COARSE_TIMER_SECS * 1000UL) /** period (in milliseconds) of the application calling dhcp_fine_tmr() */ -#define DHCP_FINE_TIMER_MSECS 500 +#define DHCP_FINE_TIMER_MSECS 500 + +#define DHCP_BOOT_FILE_LEN 128U -#define DHCP_CHADDR_LEN 16U -#define DHCP_SNAME_LEN 64U -#define DHCP_FILE_LEN 128U +/* AutoIP cooperation flags (struct dhcp.autoip_coop_state) */ +typedef enum { + DHCP_AUTOIP_COOP_STATE_OFF = 0, + DHCP_AUTOIP_COOP_STATE_ON = 1 +} dhcp_autoip_coop_state_enum_t; struct dhcp { @@ -76,12 +89,12 @@ struct dhcp struct dhcp_msg *msg_out; /* outgoing msg */ u16_t options_out_len; /* outgoing msg options length */ u16_t request_timeout; /* #ticks with period DHCP_FINE_TIMER_SECS for request timeout */ - u32_t t1_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for renewal time */ - u32_t t2_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for rebind time */ - u32_t t1_renew_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next renew try */ - u32_t t2_rebind_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next rebind try */ - u32_t lease_used; /* #ticks with period DHCP_COARSE_TIMER_SECS since last received DHCP ack */ - u32_t t0_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for lease time */ + u16_t t1_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for renewal time */ + u16_t t2_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for rebind time */ + u16_t t1_renew_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next renew try */ + u16_t t2_rebind_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next rebind try */ + u16_t lease_used; /* #ticks with period DHCP_COARSE_TIMER_SECS since last received DHCP ack */ + u16_t t0_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for lease time */ ip_addr_t server_ip_addr; /* dhcp server address that offered this lease (ip_addr_t because passed to UDP) */ ip4_addr_t offered_ip_addr; ip4_addr_t offered_sn_mask; @@ -91,12 +104,12 @@ struct dhcp u32_t offered_t1_renew; /* recommended renew time (usually 50% of lease period) */ u32_t offered_t2_rebind; /* recommended rebind time (usually 87.5 of lease period) */ #if LWIP_DHCP_BOOTP_FILE - ip_addr_t offered_si_addr; - char boot_file_name[DHCP_FILE_LEN]; + ip4_addr_t offered_si_addr; + char boot_file_name[DHCP_BOOT_FILE_LEN]; #endif /* LWIP_DHCP_BOOTPFILE */ /* Espressif add start. */ -#ifdef ESP_LWIP +#ifdef ESP_DHCP void (*cb)(struct netif*); /* callback for dhcp, add a parameter to show dhcp status if needed */ #else void (*cb)(void); /* callback for dhcp, add a parameter to show dhcp status if needed */ @@ -104,200 +117,36 @@ struct dhcp /* Espressif add end. */ }; -/* MUST be compiled with "pack structs" or equivalent! */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -/** minimum set of fields of any DHCP message */ -struct dhcp_msg -{ - PACK_STRUCT_FLD_8(u8_t op); - PACK_STRUCT_FLD_8(u8_t htype); - PACK_STRUCT_FLD_8(u8_t hlen); - PACK_STRUCT_FLD_8(u8_t hops); - PACK_STRUCT_FIELD(u32_t xid); - PACK_STRUCT_FIELD(u16_t secs); - PACK_STRUCT_FIELD(u16_t flags); - PACK_STRUCT_FLD_S(ip4_addr_p_t ciaddr); - PACK_STRUCT_FLD_S(ip4_addr_p_t yiaddr); - PACK_STRUCT_FLD_S(ip4_addr_p_t siaddr); - PACK_STRUCT_FLD_S(ip4_addr_p_t giaddr); - PACK_STRUCT_FLD_8(u8_t chaddr[DHCP_CHADDR_LEN]); - PACK_STRUCT_FLD_8(u8_t sname[DHCP_SNAME_LEN]); - PACK_STRUCT_FLD_8(u8_t file[DHCP_FILE_LEN]); - PACK_STRUCT_FIELD(u32_t cookie); -#define DHCP_MIN_OPTIONS_LEN 68U -/** make sure user does not configure this too small */ -#if ((defined(DHCP_OPTIONS_LEN)) && (DHCP_OPTIONS_LEN < DHCP_MIN_OPTIONS_LEN)) -# undef DHCP_OPTIONS_LEN -#endif -/** allow this to be configured in lwipopts.h, but not too small */ -#if (!defined(DHCP_OPTIONS_LEN)) -/** set this to be sufficient for your options in outgoing DHCP msgs */ -# define DHCP_OPTIONS_LEN DHCP_MIN_OPTIONS_LEN -#endif - PACK_STRUCT_FLD_8(u8_t options[DHCP_OPTIONS_LEN]); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif void dhcp_set_struct(struct netif *netif, struct dhcp *dhcp); /** Remove a struct dhcp previously set to the netif using dhcp_set_struct() */ -#define dhcp_remove_struct(netif) do { (netif)->dhcp = NULL; } while(0) +#define dhcp_remove_struct(netif) netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, NULL) void dhcp_cleanup(struct netif *netif); +err_t dhcp_start(struct netif *netif); +err_t dhcp_renew(struct netif *netif); +err_t dhcp_release(struct netif *netif); +void dhcp_stop(struct netif *netif); +void dhcp_inform(struct netif *netif); +void dhcp_network_changed(struct netif *netif); + /* Espressif add start. */ /** set callback for DHCP */ -#ifdef ESP_LWIP +#ifdef ESP_DHCP void dhcp_set_cb(struct netif *netif, void (*cb)(struct netif*)); #else void dhcp_set_cb(struct netif *netif, void (*cb)(void)); #endif /* Espressif add end. */ -/** start DHCP configuration */ -err_t dhcp_start(struct netif *netif); -/** enforce early lease renewal (not needed normally)*/ -err_t dhcp_renew(struct netif *netif); -/** release the DHCP lease, usually called before dhcp_stop()*/ -err_t dhcp_release(struct netif *netif); -/** stop DHCP configuration */ -void dhcp_stop(struct netif *netif); -/** inform server of our manual IP address */ -void dhcp_inform(struct netif *netif); -/** Handle a possible change in the network configuration */ -void dhcp_network_changed(struct netif *netif); -/** if enabled, check whether the offered IP address is not in use, using ARP */ #if DHCP_DOES_ARP_CHECK void dhcp_arp_reply(struct netif *netif, const ip4_addr_t *addr); #endif - -/** check if DHCP supplied netif->ip_addr */ -u8_t dhcp_supplied_address(struct netif *netif); - -/** to be called every minute */ +u8_t dhcp_supplied_address(const struct netif *netif); +/* to be called every minute */ void dhcp_coarse_tmr(void); -/** to be called every half second */ +/* to be called every half second */ void dhcp_fine_tmr(void); -/** DHCP message item offsets and length */ -#define DHCP_OP_OFS 0 -#define DHCP_HTYPE_OFS 1 -#define DHCP_HLEN_OFS 2 -#define DHCP_HOPS_OFS 3 -#define DHCP_XID_OFS 4 -#define DHCP_SECS_OFS 8 -#define DHCP_FLAGS_OFS 10 -#define DHCP_CIADDR_OFS 12 -#define DHCP_YIADDR_OFS 16 -#define DHCP_SIADDR_OFS 20 -#define DHCP_GIADDR_OFS 24 -#define DHCP_CHADDR_OFS 28 -#define DHCP_SNAME_OFS 44 -#define DHCP_FILE_OFS 108 -#define DHCP_MSG_LEN 236 - -#define DHCP_COOKIE_OFS DHCP_MSG_LEN -#define DHCP_OPTIONS_OFS (DHCP_MSG_LEN + 4) - -#define DHCP_CLIENT_PORT 68 -#define DHCP_SERVER_PORT 67 - -/** DHCP client states */ -#define DHCP_STATE_OFF 0 -#define DHCP_STATE_REQUESTING 1 -#define DHCP_STATE_INIT 2 -#define DHCP_STATE_REBOOTING 3 -#define DHCP_STATE_REBINDING 4 -#define DHCP_STATE_RENEWING 5 -#define DHCP_STATE_SELECTING 6 -#define DHCP_STATE_INFORMING 7 -#define DHCP_STATE_CHECKING 8 -/** not yet implemented #define DHCP_STATE_PERMANENT 9 */ -#define DHCP_STATE_BOUND 10 -/** not yet implemented #define DHCP_STATE_RELEASING 11 */ -#define DHCP_STATE_BACKING_OFF 12 - -/** AUTOIP cooperation flags */ -#define DHCP_AUTOIP_COOP_STATE_OFF 0 -#define DHCP_AUTOIP_COOP_STATE_ON 1 - -#define DHCP_BOOTREQUEST 1 -#define DHCP_BOOTREPLY 2 - -/** DHCP message types */ -#define DHCP_DISCOVER 1 -#define DHCP_OFFER 2 -#define DHCP_REQUEST 3 -#define DHCP_DECLINE 4 -#define DHCP_ACK 5 -#define DHCP_NAK 6 -#define DHCP_RELEASE 7 -#define DHCP_INFORM 8 - -/** DHCP hardware type, currently only ethernet is supported */ -#define DHCP_HTYPE_ETH 1 - -#define DHCP_MAGIC_COOKIE 0x63825363UL - -/* This is a list of options for BOOTP and DHCP, see RFC 2132 for descriptions */ - -/** BootP options */ -#define DHCP_OPTION_PAD 0 -#define DHCP_OPTION_SUBNET_MASK 1 /* RFC 2132 3.3 */ -#define DHCP_OPTION_ROUTER 3 -#define DHCP_OPTION_DNS_SERVER 6 -#define DHCP_OPTION_HOSTNAME 12 -#define DHCP_OPTION_IP_TTL 23 -#define DHCP_OPTION_MTU 26 -#define DHCP_OPTION_BROADCAST 28 -#define DHCP_OPTION_TCP_TTL 37 -#define DHCP_OPTION_NTP 42 -#define DHCP_OPTION_END 255 - -#if ESP_LWIP -/**add options for support more router by liuHan**/ -#define DHCP_OPTION_DOMAIN_NAME 15 -#define DHCP_OPTION_PRD 31 -#define DHCP_OPTION_STATIC_ROUTER 33 -#define DHCP_OPTION_VSN 43 -#define DHCP_OPTION_NB_TINS 44 -#define DHCP_OPTION_NB_TINT 46 -#define DHCP_OPTION_NB_TIS 47 -#define DHCP_OPTION_CLASSLESS_STATIC_ROUTER 121 -#endif - - - -/** DHCP options */ -#define DHCP_OPTION_REQUESTED_IP 50 /* RFC 2132 9.1, requested IP address */ -#define DHCP_OPTION_LEASE_TIME 51 /* RFC 2132 9.2, time in seconds, in 4 bytes */ -#define DHCP_OPTION_OVERLOAD 52 /* RFC2132 9.3, use file and/or sname field for options */ - -#define DHCP_OPTION_MESSAGE_TYPE 53 /* RFC 2132 9.6, important for DHCP */ -#define DHCP_OPTION_MESSAGE_TYPE_LEN 1 - -#define DHCP_OPTION_SERVER_ID 54 /* RFC 2132 9.7, server IP address */ -#define DHCP_OPTION_PARAMETER_REQUEST_LIST 55 /* RFC 2132 9.8, requested option types */ - -#define DHCP_OPTION_MAX_MSG_SIZE 57 /* RFC 2132 9.10, message size accepted >= 576 */ -#define DHCP_OPTION_MAX_MSG_SIZE_LEN 2 - -#define DHCP_OPTION_T1 58 /* T1 renewal time */ -#define DHCP_OPTION_T2 59 /* T2 rebinding time */ -#define DHCP_OPTION_US 60 -#define DHCP_OPTION_CLIENT_ID 61 -#define DHCP_OPTION_TFTP_SERVERNAME 66 -#define DHCP_OPTION_BOOTFILE 67 - -/** possible combinations of overloading the file and sname fields with options */ -#define DHCP_OVERLOAD_NONE 0 -#define DHCP_OVERLOAD_FILE 1 -#define DHCP_OVERLOAD_SNAME 2 -#define DHCP_OVERLOAD_SNAME_FILE 3 - #if LWIP_DHCP_GET_NTP_SRV /** This function must exist, in other to add offered NTP servers to * the NTP (or SNTP) engine. @@ -305,6 +154,8 @@ void dhcp_fine_tmr(void); extern void dhcp_set_ntp_servers(u8_t num_ntp_servers, const ip4_addr_t* ntp_server_addrs); #endif /* LWIP_DHCP_GET_NTP_SRV */ +#define netif_dhcp_data(netif) ((struct dhcp*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP)) + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/dhcp6.h b/tools/sdk/include/lwip/lwip/dhcp6.h old mode 100755 new mode 100644 index 345bcf00ec2..455336d37dc --- a/tools/sdk/include/lwip/lwip/dhcp6.h +++ b/tools/sdk/include/lwip/lwip/dhcp6.h @@ -50,7 +50,7 @@ struct dhcp6 { - /*TODO: implement DHCP6*/ + /*@todo: implement DHCP6*/ }; #endif /* LWIP_IPV6_DHCP6 */ diff --git a/tools/sdk/include/lwip/lwip/dns.h b/tools/sdk/include/lwip/lwip/dns.h old mode 100755 new mode 100644 index e080280391d..38ea6367e1c --- a/tools/sdk/include/lwip/lwip/dns.h +++ b/tools/sdk/include/lwip/lwip/dns.h @@ -1,3 +1,8 @@ +/** + * @file + * DNS API + */ + /** * lwip DNS resolver header file. @@ -36,14 +41,10 @@ #include "lwip/opt.h" -#if ESP_DNS -#include "lwip/err.h" -#endif - - #if LWIP_DNS #include "lwip/ip_addr.h" +#include "lwip/err.h" #ifdef __cplusplus extern "C" { @@ -61,7 +62,7 @@ extern "C" { #ifndef LWIP_DNS_ADDRTYPE_DEFAULT #define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV4_IPV6 #endif -#elif defined(LWIP_IPV4) +#elif LWIP_IPV4 #define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV4 #else #define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV6 @@ -76,6 +77,7 @@ struct local_hostlist_entry { ip_addr_t addr; struct local_hostlist_entry *next; }; +#define DNS_LOCAL_HOSTLIST_ELEM(name, addr_init) {name, addr_init, NULL} #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC #ifndef DNS_LOCAL_HOSTLIST_MAX_NAMELEN #define DNS_LOCAL_HOSTLIST_MAX_NAMELEN DNS_MAX_NAME_LENGTH @@ -84,6 +86,13 @@ struct local_hostlist_entry { #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ #endif /* DNS_LOCAL_HOSTLIST */ +#if LWIP_IPV4 +extern const ip_addr_t dns_mquery_v4group; +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 +extern const ip_addr_t dns_mquery_v6group; +#endif /* LWIP_IPV6 */ + /** Callback which is invoked when a hostname is found. * A function of this type must be implemented by the application using the DNS resolver. * @param name pointer to the name that was looked up. @@ -93,22 +102,32 @@ struct local_hostlist_entry { */ typedef void (*dns_found_callback)(const char *name, const ip_addr_t *ipaddr, void *callback_arg); -void dns_init(void); -void dns_tmr(void); -void dns_setserver(u8_t numdns, const ip_addr_t *dnsserver); -void dns_clear_servers(bool keep_fallback); -ip_addr_t dns_getserver(u8_t numdns); -err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, - dns_found_callback found, void *callback_arg); -err_t dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, - dns_found_callback found, void *callback_arg, - u8_t dns_addrtype); +void dns_init(void); +void dns_tmr(void); +void dns_setserver(u8_t numdns, const ip_addr_t *dnsserver); +#if ESP_DNS +ip_addr_t dns_getserver(u8_t numdns); +#else +const ip_addr_t* dns_getserver(u8_t numdns); +#endif +err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, + dns_found_callback found, void *callback_arg); +err_t dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, + dns_found_callback found, void *callback_arg, + u8_t dns_addrtype); +#if ESP_DNS +void dns_clear_servers(bool keep_fallback); +#endif -#if DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#if DNS_LOCAL_HOSTLIST +size_t dns_local_iterate(dns_found_callback iterator_fn, void *iterator_arg); +err_t dns_local_lookup(const char *hostname, ip_addr_t *addr, u8_t dns_addrtype); +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC int dns_local_removehost(const char *hostname, const ip_addr_t *addr); err_t dns_local_addhost(const char *hostname, const ip_addr_t *addr); -#endif /* DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +#endif /* DNS_LOCAL_HOSTLIST */ #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/err.h b/tools/sdk/include/lwip/lwip/err.h old mode 100755 new mode 100644 index a766ee186df..84e528d1ed8 --- a/tools/sdk/include/lwip/lwip/err.h +++ b/tools/sdk/include/lwip/lwip/err.h @@ -1,3 +1,7 @@ +/** + * @file + * lwIP Error codes + */ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -39,6 +43,12 @@ extern "C" { #endif +/** + * @defgroup infrastructure_errors Error codes + * @ingroup infrastructure + * @{ + */ + /** Define LWIP_ERR_T in cc.h if you want to use * a different type for your platform (must be signed). */ #ifdef LWIP_ERR_T @@ -47,40 +57,50 @@ typedef LWIP_ERR_T err_t; typedef s8_t err_t; #endif /* LWIP_ERR_T*/ -/* Definitions for error constants. */ +/** Definitions for error constants. */ +typedef enum { +/** No error, everything OK. */ + ERR_OK = 0, +/** Out of memory error. */ + ERR_MEM = -1, +/** Buffer error. */ + ERR_BUF = -2, +/** Timeout. */ + ERR_TIMEOUT = -3, +/** Routing problem. */ + ERR_RTE = -4, +/** Operation in progress */ + ERR_INPROGRESS = -5, +/** Illegal value. */ + ERR_VAL = -6, +/** Operation would block. */ + ERR_WOULDBLOCK = -7, +/** Address in use. */ + ERR_USE = -8, +/** Already connecting. */ + ERR_ALREADY = -9, +/** Conn already established.*/ + ERR_ISCONN = -10, +/** Not connected. */ + ERR_CONN = -11, +/** Low-level netif error */ + ERR_IF = -12, -#define ERR_OK 0 /* No error, everything OK. */ -#define ERR_MEM -1 /* Out of memory error. */ -#define ERR_BUF -2 /* Buffer error. */ -#define ERR_TIMEOUT -3 /* Timeout. */ -#define ERR_RTE -4 /* Routing problem. */ -#define ERR_INPROGRESS -5 /* Operation in progress */ -#define ERR_VAL -6 /* Illegal value. */ -#define ERR_WOULDBLOCK -7 /* Operation would block. */ -#define ERR_USE -8 /* Address in use. */ +/** Connection aborted. */ + ERR_ABRT = -13, +/** Connection reset. */ + ERR_RST = -14, +/** Connection closed. */ + ERR_CLSD = -15, +/** Illegal argument. */ + ERR_ARG = -16 +} err_enum_t; - -#if ESP_LWIP -#define ERR_ALREADY -9 /* Already connected. */ -#define ERR_ISCONN -10 /* Conn already established.*/ -#define ERR_IS_FATAL(e) ((e) < ERR_ISCONN) -#define ERR_ABRT -11 /* Connection aborted. */ -#define ERR_RST -12 /* Connection reset. */ -#define ERR_CLSD -13 /* Connection closed. */ -#define ERR_CONN -14 /* Not connected. */ -#define ERR_ARG -15 /* Illegal argument. */ -#define ERR_IF -16 /* Low-level netif error */ -#else -#define ERR_ALREADY -9 /* Already connecting. */ -#define ERR_ISCONN -10 /* Conn already established.*/ -#define ERR_CONN -11 /* Not connected. */ -#define ERR_IF -12 /* Low-level netif error */ #define ERR_IS_FATAL(e) ((e) <= ERR_ABRT) -#define ERR_ABRT -13 /* Connection aborted. */ -#define ERR_RST -14 /* Connection reset. */ -#define ERR_CLSD -15 /* Connection closed. */ -#define ERR_ARG -16 /* Illegal argument. */ -#endif + +/** + * @} + */ #ifdef LWIP_DEBUG extern const char *lwip_strerr(err_t err); @@ -88,6 +108,10 @@ extern const char *lwip_strerr(err_t err); #define lwip_strerr(x) "" #endif /* LWIP_DEBUG */ +#if !NO_SYS +int err_to_errno(err_t err); +#endif /* !NO_SYS */ + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/errno.h b/tools/sdk/include/lwip/lwip/errno.h new file mode 100644 index 00000000000..641cffb09cc --- /dev/null +++ b/tools/sdk/include/lwip/lwip/errno.h @@ -0,0 +1,193 @@ +/** + * @file + * Posix Errno defines + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_ERRNO_H +#define LWIP_HDR_ERRNO_H + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef LWIP_PROVIDE_ERRNO + +#define EPERM 1 /* Operation not permitted */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such process */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* I/O error */ +#define ENXIO 6 /* No such device or address */ +#define E2BIG 7 /* Arg list too long */ +#define ENOEXEC 8 /* Exec format error */ +#define EBADF 9 /* Bad file number */ +#define ECHILD 10 /* No child processes */ +#define EAGAIN 11 /* Try again */ +#define ENOMEM 12 /* Out of memory */ +#define EACCES 13 /* Permission denied */ +#define EFAULT 14 /* Bad address */ +#define ENOTBLK 15 /* Block device required */ +#define EBUSY 16 /* Device or resource busy */ +#define EEXIST 17 /* File exists */ +#define EXDEV 18 /* Cross-device link */ +#define ENODEV 19 /* No such device */ +#define ENOTDIR 20 /* Not a directory */ +#define EISDIR 21 /* Is a directory */ +#define EINVAL 22 /* Invalid argument */ +#define ENFILE 23 /* File table overflow */ +#define EMFILE 24 /* Too many open files */ +#define ENOTTY 25 /* Not a typewriter */ +#define ETXTBSY 26 /* Text file busy */ +#define EFBIG 27 /* File too large */ +#define ENOSPC 28 /* No space left on device */ +#define ESPIPE 29 /* Illegal seek */ +#define EROFS 30 /* Read-only file system */ +#define EMLINK 31 /* Too many links */ +#define EPIPE 32 /* Broken pipe */ +#define EDOM 33 /* Math argument out of domain of func */ +#define ERANGE 34 /* Math result not representable */ +#define EDEADLK 35 /* Resource deadlock would occur */ +#define ENAMETOOLONG 36 /* File name too long */ +#define ENOLCK 37 /* No record locks available */ +#define ENOSYS 38 /* Function not implemented */ +#define ENOTEMPTY 39 /* Directory not empty */ +#define ELOOP 40 /* Too many symbolic links encountered */ +#define EWOULDBLOCK EAGAIN /* Operation would block */ +#define ENOMSG 42 /* No message of desired type */ +#define EIDRM 43 /* Identifier removed */ +#define ECHRNG 44 /* Channel number out of range */ +#define EL2NSYNC 45 /* Level 2 not synchronized */ +#define EL3HLT 46 /* Level 3 halted */ +#define EL3RST 47 /* Level 3 reset */ +#define ELNRNG 48 /* Link number out of range */ +#define EUNATCH 49 /* Protocol driver not attached */ +#define ENOCSI 50 /* No CSI structure available */ +#define EL2HLT 51 /* Level 2 halted */ +#define EBADE 52 /* Invalid exchange */ +#define EBADR 53 /* Invalid request descriptor */ +#define EXFULL 54 /* Exchange full */ +#define ENOANO 55 /* No anode */ +#define EBADRQC 56 /* Invalid request code */ +#define EBADSLT 57 /* Invalid slot */ + +#define EDEADLOCK EDEADLK + +#define EBFONT 59 /* Bad font file format */ +#define ENOSTR 60 /* Device not a stream */ +#define ENODATA 61 /* No data available */ +#define ETIME 62 /* Timer expired */ +#define ENOSR 63 /* Out of streams resources */ +#define ENONET 64 /* Machine is not on the network */ +#define ENOPKG 65 /* Package not installed */ +#define EREMOTE 66 /* Object is remote */ +#define ENOLINK 67 /* Link has been severed */ +#define EADV 68 /* Advertise error */ +#define ESRMNT 69 /* Srmount error */ +#define ECOMM 70 /* Communication error on send */ +#define EPROTO 71 /* Protocol error */ +#define EMULTIHOP 72 /* Multihop attempted */ +#define EDOTDOT 73 /* RFS specific error */ +#define EBADMSG 74 /* Not a data message */ +#define EOVERFLOW 75 /* Value too large for defined data type */ +#define ENOTUNIQ 76 /* Name not unique on network */ +#define EBADFD 77 /* File descriptor in bad state */ +#define EREMCHG 78 /* Remote address changed */ +#define ELIBACC 79 /* Can not access a needed shared library */ +#define ELIBBAD 80 /* Accessing a corrupted shared library */ +#define ELIBSCN 81 /* .lib section in a.out corrupted */ +#define ELIBMAX 82 /* Attempting to link in too many shared libraries */ +#define ELIBEXEC 83 /* Cannot exec a shared library directly */ +#define EILSEQ 84 /* Illegal byte sequence */ +#define ERESTART 85 /* Interrupted system call should be restarted */ +#define ESTRPIPE 86 /* Streams pipe error */ +#define EUSERS 87 /* Too many users */ +#define ENOTSOCK 88 /* Socket operation on non-socket */ +#define EDESTADDRREQ 89 /* Destination address required */ +#define EMSGSIZE 90 /* Message too long */ +#define EPROTOTYPE 91 /* Protocol wrong type for socket */ +#define ENOPROTOOPT 92 /* Protocol not available */ +#define EPROTONOSUPPORT 93 /* Protocol not supported */ +#define ESOCKTNOSUPPORT 94 /* Socket type not supported */ +#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define EPFNOSUPPORT 96 /* Protocol family not supported */ +#define EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define EADDRINUSE 98 /* Address already in use */ +#define EADDRNOTAVAIL 99 /* Cannot assign requested address */ +#define ENETDOWN 100 /* Network is down */ +#define ENETUNREACH 101 /* Network is unreachable */ +#define ENETRESET 102 /* Network dropped connection because of reset */ +#define ECONNABORTED 103 /* Software caused connection abort */ +#define ECONNRESET 104 /* Connection reset by peer */ +#define ENOBUFS 105 /* No buffer space available */ +#define EISCONN 106 /* Transport endpoint is already connected */ +#define ENOTCONN 107 /* Transport endpoint is not connected */ +#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +#define ETOOMANYREFS 109 /* Too many references: cannot splice */ +#define ETIMEDOUT 110 /* Connection timed out */ +#define ECONNREFUSED 111 /* Connection refused */ +#define EHOSTDOWN 112 /* Host is down */ +#define EHOSTUNREACH 113 /* No route to host */ +#define EALREADY 114 /* Operation already in progress */ +#define EINPROGRESS 115 /* Operation now in progress */ +#define ESTALE 116 /* Stale NFS file handle */ +#define EUCLEAN 117 /* Structure needs cleaning */ +#define ENOTNAM 118 /* Not a XENIX named type file */ +#define ENAVAIL 119 /* No XENIX semaphores available */ +#define EISNAM 120 /* Is a named type file */ +#define EREMOTEIO 121 /* Remote I/O error */ +#define EDQUOT 122 /* Quota exceeded */ + +#define ENOMEDIUM 123 /* No medium found */ +#define EMEDIUMTYPE 124 /* Wrong medium type */ + +#ifndef errno +extern int errno; +#endif + +#else /* LWIP_PROVIDE_ERRNO */ + +/* Define LWIP_ERRNO_INCLUDE to to include the error defines here */ +#ifdef LWIP_ERRNO_INCLUDE +#include LWIP_ERRNO_INCLUDE +#endif /* LWIP_ERRNO_INCLUDE */ + +#endif /* LWIP_PROVIDE_ERRNO */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_ERRNO_H */ diff --git a/tools/sdk/include/lwip/lwip/etharp.h b/tools/sdk/include/lwip/lwip/etharp.h new file mode 100644 index 00000000000..0662f07241e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/etharp.h @@ -0,0 +1,116 @@ +/** + * @file + * Ethernet output function - handles OUTGOING ethernet level traffic, implements + * ARP resolving. + * To be used in most low-level netif implementations + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * Copyright (c) 2003-2004 Leon Woestenberg + * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef LWIP_HDR_NETIF_ETHARP_H +#define LWIP_HDR_NETIF_ETHARP_H + +#include "lwip/opt.h" + +#if LWIP_ARP || LWIP_ETHERNET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip4_addr.h" +#include "lwip/netif.h" +#include "lwip/ip4.h" +#include "lwip/prot/ethernet.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_IPV4 && LWIP_ARP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/prot/etharp.h" + +/** 1 seconds period */ +#define ARP_TMR_INTERVAL 1000 + +#if ARP_QUEUEING +/** struct for queueing outgoing packets for unknown address + * defined here to be accessed by memp.h + */ +struct etharp_q_entry { + struct etharp_q_entry *next; + struct pbuf *p; +}; +#endif /* ARP_QUEUEING */ + +#if ESP_GRATUITOUS_ARP +#ifdef CONFIG_GARP_TMR_INTERVAL +#define GARP_TMR_INTERVAL (CONFIG_GARP_TMR_INTERVAL*1000UL) +#else +#define GARP_TMR_INTERVAL 60000 +#endif + +void garp_tmr(void); +#endif + +#define etharp_init() /* Compatibility define, no init needed. */ +void etharp_tmr(void); +s8_t etharp_find_addr(struct netif *netif, const ip4_addr_t *ipaddr, + struct eth_addr **eth_ret, const ip4_addr_t **ip_ret); +u8_t etharp_get_entry(u8_t i, ip4_addr_t **ipaddr, struct netif **netif, struct eth_addr **eth_ret); +err_t etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr); +err_t etharp_query(struct netif *netif, const ip4_addr_t *ipaddr, struct pbuf *q); +err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr); +/** For Ethernet network interfaces, we might want to send "gratuitous ARP"; + * this is an ARP packet sent by a node in order to spontaneously cause other + * nodes to update an entry in their ARP cache. + * From RFC 3220 "IP Mobility Support for IPv4" section 4.6. */ +#define etharp_gratuitous(netif) etharp_request((netif), netif_ip4_addr(netif)) +void etharp_cleanup_netif(struct netif *netif); + +#if ETHARP_SUPPORT_STATIC_ENTRIES +err_t etharp_add_static_entry(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr); +err_t etharp_remove_static_entry(const ip4_addr_t *ipaddr); +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + +#endif /* LWIP_IPV4 && LWIP_ARP */ + +void etharp_input(struct pbuf *p, struct netif *netif); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_ARP || LWIP_ETHERNET */ + +#endif /* LWIP_HDR_NETIF_ETHARP_H */ diff --git a/tools/sdk/include/lwip/lwip/ethip6.h b/tools/sdk/include/lwip/lwip/ethip6.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/lwip/lwip/icmp.h b/tools/sdk/include/lwip/lwip/icmp.h old mode 100755 new mode 100644 index af3a455083b..f5a31fd4c07 --- a/tools/sdk/include/lwip/lwip/icmp.h +++ b/tools/sdk/include/lwip/lwip/icmp.h @@ -1,3 +1,8 @@ +/** + * @file + * ICMP API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -36,6 +41,7 @@ #include "lwip/pbuf.h" #include "lwip/ip_addr.h" #include "lwip/netif.h" +#include "lwip/prot/icmp.h" #if LWIP_IPV6 && LWIP_ICMP6 #include "lwip/icmp6.h" @@ -45,63 +51,30 @@ extern "C" { #endif -#define ICMP_ER 0 /* echo reply */ -#define ICMP_DUR 3 /* destination unreachable */ -#define ICMP_SQ 4 /* source quench */ -#define ICMP_RD 5 /* redirect */ -#define ICMP_ECHO 8 /* echo */ -#define ICMP_TE 11 /* time exceeded */ -#define ICMP_PP 12 /* parameter problem */ -#define ICMP_TS 13 /* timestamp */ -#define ICMP_TSR 14 /* timestamp reply */ -#define ICMP_IRQ 15 /* information request */ -#define ICMP_IR 16 /* information reply */ -#define ICMP_AM 17 /* address mask request */ -#define ICMP_AMR 18 /* address mask reply */ - +/** ICMP destination unreachable codes */ enum icmp_dur_type { - ICMP_DUR_NET = 0, /* net unreachable */ - ICMP_DUR_HOST = 1, /* host unreachable */ - ICMP_DUR_PROTO = 2, /* protocol unreachable */ - ICMP_DUR_PORT = 3, /* port unreachable */ - ICMP_DUR_FRAG = 4, /* fragmentation needed and DF set */ - ICMP_DUR_SR = 5 /* source route failed */ + /** net unreachable */ + ICMP_DUR_NET = 0, + /** host unreachable */ + ICMP_DUR_HOST = 1, + /** protocol unreachable */ + ICMP_DUR_PROTO = 2, + /** port unreachable */ + ICMP_DUR_PORT = 3, + /** fragmentation needed and DF set */ + ICMP_DUR_FRAG = 4, + /** source route failed */ + ICMP_DUR_SR = 5 }; +/** ICMP time exceeded codes */ enum icmp_te_type { - ICMP_TE_TTL = 0, /* time to live exceeded in transit */ - ICMP_TE_FRAG = 1 /* fragment reassembly time exceeded */ + /** time to live exceeded in transit */ + ICMP_TE_TTL = 0, + /** fragment reassembly time exceeded */ + ICMP_TE_FRAG = 1 }; -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -/** This is the standard ICMP header only that the u32_t data - * is split to two u16_t like ICMP echo needs it. - * This header is also used for other ICMP types that do not - * use the data part. - */ -PACK_STRUCT_BEGIN -struct icmp_echo_hdr { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u16_t id); - PACK_STRUCT_FIELD(u16_t seqno); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define ICMPH_TYPE(hdr) ((hdr)->type) -#define ICMPH_CODE(hdr) ((hdr)->code) - -/** Combines type and code to an u16_t */ -#define ICMPH_TYPE_SET(hdr, t) ((hdr)->type = (t)) -#define ICMPH_CODE_SET(hdr, c) ((hdr)->code = (c)) - - #if LWIP_IPV4 && LWIP_ICMP /* don't build if not configured for use in lwipopts.h */ void icmp_input(struct pbuf *p, struct netif *inp); diff --git a/tools/sdk/include/lwip/lwip/icmp6.h b/tools/sdk/include/lwip/lwip/icmp6.h old mode 100755 new mode 100644 index 9d57103fc1f..a29dc8c1c23 --- a/tools/sdk/include/lwip/lwip/icmp6.h +++ b/tools/sdk/include/lwip/lwip/icmp6.h @@ -45,94 +45,12 @@ #include "lwip/pbuf.h" #include "lwip/ip6_addr.h" #include "lwip/netif.h" - +#include "lwip/prot/icmp6.h" #ifdef __cplusplus extern "C" { #endif -enum icmp6_type { - ICMP6_TYPE_DUR = 1, /* Destination unreachable */ - ICMP6_TYPE_PTB = 2, /* Packet too big */ - ICMP6_TYPE_TE = 3, /* Time exceeded */ - ICMP6_TYPE_PP = 4, /* Parameter problem */ - ICMP6_TYPE_PE1 = 100, /* Private experimentation */ - ICMP6_TYPE_PE2 = 101, /* Private experimentation */ - ICMP6_TYPE_RSV_ERR = 127, /* Reserved for expansion of error messages */ - - ICMP6_TYPE_EREQ = 128, /* Echo request */ - ICMP6_TYPE_EREP = 129, /* Echo reply */ - ICMP6_TYPE_MLQ = 130, /* Multicast listener query */ - ICMP6_TYPE_MLR = 131, /* Multicast listener report */ - ICMP6_TYPE_MLD = 132, /* Multicast listener done */ - ICMP6_TYPE_RS = 133, /* Router solicitation */ - ICMP6_TYPE_RA = 134, /* Router advertisement */ - ICMP6_TYPE_NS = 135, /* Neighbor solicitation */ - ICMP6_TYPE_NA = 136, /* Neighbor advertisement */ - ICMP6_TYPE_RD = 137, /* Redirect */ - ICMP6_TYPE_MRA = 151, /* Multicast router advertisement */ - ICMP6_TYPE_MRS = 152, /* Multicast router solicitation */ - ICMP6_TYPE_MRT = 153, /* Multicast router termination */ - ICMP6_TYPE_PE3 = 200, /* Private experimentation */ - ICMP6_TYPE_PE4 = 201, /* Private experimentation */ - ICMP6_TYPE_RSV_INF = 255 /* Reserved for expansion of informational messages */ -}; - -enum icmp6_dur_code { - ICMP6_DUR_NO_ROUTE = 0, /* No route to destination */ - ICMP6_DUR_PROHIBITED = 1, /* Communication with destination administratively prohibited */ - ICMP6_DUR_SCOPE = 2, /* Beyond scope of source address */ - ICMP6_DUR_ADDRESS = 3, /* Address unreachable */ - ICMP6_DUR_PORT = 4, /* Port unreachable */ - ICMP6_DUR_POLICY = 5, /* Source address failed ingress/egress policy */ - ICMP6_DUR_REJECT_ROUTE = 6 /* Reject route to destination */ -}; - -enum icmp6_te_code { - ICMP6_TE_HL = 0, /* Hop limit exceeded in transit */ - ICMP6_TE_FRAG = 1 /* Fragment reassembly time exceeded */ -}; - -enum icmp6_pp_code { - ICMP6_PP_FIELD = 0, /* Erroneous header field encountered */ - ICMP6_PP_HEADER = 1, /* Unrecognized next header type encountered */ - ICMP6_PP_OPTION = 2 /* Unrecognized IPv6 option encountered */ -}; - -/** This is the standard ICMP6 header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct icmp6_hdr { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u32_t data); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** This is the ICMP6 header adapted for echo req/resp. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct icmp6_echo_hdr { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u16_t id); - PACK_STRUCT_FIELD(u16_t seqno); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - - #if LWIP_ICMP6 && LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ void icmp6_input(struct pbuf *p, struct netif *inp); diff --git a/tools/sdk/include/lwip/lwip/igmp.h b/tools/sdk/include/lwip/lwip/igmp.h old mode 100755 new mode 100644 index bff1a613506..ffd80e680c3 --- a/tools/sdk/include/lwip/lwip/igmp.h +++ b/tools/sdk/include/lwip/lwip/igmp.h @@ -1,3 +1,8 @@ +/** + * @file + * IGMP API + */ + /* * Copyright (c) 2002 CITEL Technologies Ltd. * All rights reserved. @@ -46,17 +51,14 @@ extern "C" { #endif - /* IGMP timer */ #define IGMP_TMR_INTERVAL 100 /* Milliseconds */ #define IGMP_V1_DELAYING_MEMBER_TMR (1000/IGMP_TMR_INTERVAL) #define IGMP_JOIN_DELAYING_MEMBER_TMR (500 /IGMP_TMR_INTERVAL) -/* MAC Filter Actions, these are passed to a netif's - * igmp_mac_filter callback function. */ -#define IGMP_DEL_MAC_FILTER 0 -#define IGMP_ADD_MAC_FILTER 1 - +/* Compatibility defines (don't use for new code) */ +#define IGMP_DEL_MAC_FILTER NETIF_DEL_MAC_FILTER +#define IGMP_ADD_MAC_FILTER NETIF_ADD_MAC_FILTER /** * igmp group structure - there is @@ -70,10 +72,8 @@ extern "C" { * from all the other groups */ struct igmp_group { - /** next link */ + /** next link */ struct igmp_group *next; - /** interface on which the group is active */ - struct netif *netif; /** multicast address */ ip4_addr_t group_address; /** signifies we were the last person to report */ @@ -83,7 +83,7 @@ struct igmp_group { /** timer for reporting, negative is OFF */ u16_t timer; /** counter of simultaneous uses */ - u8_t use; + u8_t use; }; /* Prototypes */ @@ -99,6 +99,13 @@ err_t igmp_leavegroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr); err_t igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr); void igmp_tmr(void); +/** @ingroup igmp + * Get list head of IGMP groups for netif. + * Note: The allsystems group IP is contained in the list as first entry. + * @see @ref netif_set_igmp_mac_filter() + */ +#define netif_igmp_data(netif) ((struct igmp_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP)) + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/inet.h b/tools/sdk/include/lwip/lwip/inet.h old mode 100755 new mode 100644 index 036cd988d2a..4a34f026533 --- a/tools/sdk/include/lwip/lwip/inet.h +++ b/tools/sdk/include/lwip/lwip/inet.h @@ -132,10 +132,10 @@ extern const struct in6_addr in6addr_any; #if LWIP_IPV4 -#define inet_addr_from_ipaddr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr)) -#define inet_addr_to_ipaddr(target_ipaddr, source_inaddr) (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr)) -/* ATTENTION: the next define only works because both s_addr and ip_addr_t are an u32_t effectively! */ -#define inet_addr_to_ipaddr_p(target_ipaddr_p, source_inaddr) ((target_ipaddr_p) = (ip_addr_t*)&((source_inaddr)->s_addr)) +#define inet_addr_from_ip4addr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr)) +#define inet_addr_to_ip4addr(target_ipaddr, source_inaddr) (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr)) +/* ATTENTION: the next define only works because both s_addr and ip4_addr_t are an u32_t effectively! */ +#define inet_addr_to_ip4addr_p(target_ip4addr_p, source_inaddr) ((target_ip4addr_p) = (ip4_addr_t*)&((source_inaddr)->s_addr)) /* directly map this to the lwip internal functions */ #define inet_addr(cp) ipaddr_addr(cp) diff --git a/tools/sdk/include/lwip/lwip/inet_chksum.h b/tools/sdk/include/lwip/lwip/inet_chksum.h old mode 100755 new mode 100644 index 1766f4b5d85..4e23d7f1944 --- a/tools/sdk/include/lwip/lwip/inet_chksum.h +++ b/tools/sdk/include/lwip/lwip/inet_chksum.h @@ -1,3 +1,8 @@ +/** + * @file + * IP checksum calculation functions + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -37,15 +42,9 @@ #include "lwip/pbuf.h" #include "lwip/ip_addr.h" -/** Swap the bytes in an u16_t: much like htons() for little-endian */ +/** Swap the bytes in an u16_t: much like lwip_htons() for little-endian */ #ifndef SWAP_BYTES_IN_WORD -#if LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) -/* little endian and PLATFORM_BYTESWAP defined */ -#define SWAP_BYTES_IN_WORD(w) LWIP_PLATFORM_HTONS(w) -#else /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) */ -/* can't use htons on big endian (or PLATFORM_BYTESWAP not defined)... */ #define SWAP_BYTES_IN_WORD(w) (((w) & 0xff) << 8) | (((w) & 0xff00) >> 8) -#endif /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN)*/ #endif /* SWAP_BYTES_IN_WORD */ /** Split an u32_t in two u16_ts and add them up */ diff --git a/tools/sdk/include/lwip/lwip/init.h b/tools/sdk/include/lwip/lwip/init.h old mode 100755 new mode 100644 index 70351b86fcf..3c234cb58de --- a/tools/sdk/include/lwip/lwip/init.h +++ b/tools/sdk/include/lwip/lwip/init.h @@ -1,3 +1,8 @@ +/** + * @file + * lwIP initialization API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,29 +43,52 @@ extern "C" { #endif +/** + * @defgroup lwip_version Version + * @ingroup lwip + * @{ + */ + /** X.x.x: Major version of the stack */ -#define LWIP_VERSION_MAJOR 1U +#define LWIP_VERSION_MAJOR 2 /** x.X.x: Minor version of the stack */ -#define LWIP_VERSION_MINOR 5U +#define LWIP_VERSION_MINOR 0 /** x.x.X: Revision of the stack */ -#define LWIP_VERSION_REVISION 0U +#define LWIP_VERSION_REVISION 3 /** For release candidates, this is set to 1..254 * For official releases, this is set to 255 (LWIP_RC_RELEASE) * For development versions (Git), this is set to 0 (LWIP_RC_DEVELOPMENT) */ -#define LWIP_VERSION_RC 0U +#define LWIP_VERSION_RC LWIP_RC_RELEASE /** LWIP_VERSION_RC is set to LWIP_RC_RELEASE for official releases */ -#define LWIP_RC_RELEASE 255U +#define LWIP_RC_RELEASE 255 /** LWIP_VERSION_RC is set to LWIP_RC_DEVELOPMENT for Git versions */ -#define LWIP_RC_DEVELOPMENT 0U +#define LWIP_RC_DEVELOPMENT 0 #define LWIP_VERSION_IS_RELEASE (LWIP_VERSION_RC == LWIP_RC_RELEASE) #define LWIP_VERSION_IS_DEVELOPMENT (LWIP_VERSION_RC == LWIP_RC_DEVELOPMENT) #define LWIP_VERSION_IS_RC ((LWIP_VERSION_RC != LWIP_RC_RELEASE) && (LWIP_VERSION_RC != LWIP_RC_DEVELOPMENT)) +/* Some helper defines to get a version string */ +#define LWIP_VERSTR2(x) #x +#define LWIP_VERSTR(x) LWIP_VERSTR2(x) +#if LWIP_VERSION_IS_RELEASE +#define LWIP_VERSION_STRING_SUFFIX "" +#elif LWIP_VERSION_IS_DEVELOPMENT +#define LWIP_VERSION_STRING_SUFFIX "d" +#else +#define LWIP_VERSION_STRING_SUFFIX "rc" LWIP_VERSTR(LWIP_VERSION_RC) +#endif + /** Provides the version of the stack */ -#define LWIP_VERSION (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 | \ - LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) +#define LWIP_VERSION (((u32_t)LWIP_VERSION_MAJOR) << 24 | ((u32_t)LWIP_VERSION_MINOR) << 16 | \ + ((u32_t)LWIP_VERSION_REVISION) << 8 | ((u32_t)LWIP_VERSION_RC)) +/** Provides the version of the stack as string */ +#define LWIP_VERSION_STRING LWIP_VERSTR(LWIP_VERSION_MAJOR) "." LWIP_VERSTR(LWIP_VERSION_MINOR) "." LWIP_VERSTR(LWIP_VERSION_REVISION) LWIP_VERSION_STRING_SUFFIX + +/** + * @} + */ /* Modules initialization */ void lwip_init(void); diff --git a/tools/sdk/include/lwip/lwip/ip.h b/tools/sdk/include/lwip/lwip/ip.h old mode 100755 new mode 100644 index d42fe68110d..0673be9b4a8 --- a/tools/sdk/include/lwip/lwip/ip.h +++ b/tools/sdk/include/lwip/lwip/ip.h @@ -1,3 +1,8 @@ +/** + * @file + * IP API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -29,8 +34,8 @@ * Author: Adam Dunkels * */ -#ifndef LWIP_HDR_IP_H__ -#define LWIP_HDR_IP_H__ +#ifndef LWIP_HDR_IP_H +#define LWIP_HDR_IP_H #include "lwip/opt.h" @@ -41,27 +46,16 @@ #include "lwip/netif.h" #include "lwip/ip4.h" #include "lwip/ip6.h" +#include "lwip/prot/ip.h" #ifdef __cplusplus extern "C" { #endif -#define IP_PROTO_ICMP 1 -#define IP_PROTO_IGMP 2 -#define IP_PROTO_UDP 17 -#define IP_PROTO_UDPLITE 136 -#define IP_PROTO_TCP 6 - -/** This operates on a void* by loading the first byte */ -#define IP_HDR_GET_VERSION(ptr) ((*(u8_t*)(ptr)) >> 4) - /* This is passed as the destination address to ip_output_if (not to ip_output), meaning that an IP header already is constructed in the pbuf. This is used when TCP retransmits. */ -#ifdef IP_HDRINCL -#undef IP_HDRINCL -#endif /* IP_HDRINCL */ -#define IP_HDRINCL NULL +#define LWIP_IP_HDRINCL NULL /** pbufs passed to IP must have a ref-count of 1 as their payload pointer gets altered as the packet is passed down the stack */ @@ -75,7 +69,7 @@ extern "C" { #define IP_PCB_ADDRHINT #endif /* LWIP_NETIF_HWADDRHINT */ -/* This is the common part of all PCB types. It needs to be at the +/** This is the common part of all PCB types. It needs to be at the beginning of a PCB type definition. It is located here so that changes to this common part are made in one location instead of having to change all PCB structs. */ @@ -107,7 +101,7 @@ struct ip_pcb { /* These flags are inherited (e.g. from a listen-pcb to a connection-pcb): */ #define SOF_INHERITED (SOF_REUSEADDR|SOF_KEEPALIVE) -/* Global variables of this module, kept in a struct for efficient access using base+index. */ +/** Global variables of this module, kept in a struct for efficient access using base+index. */ struct ip_globals { /** The interface that accepted the packet for the current callback invocation. */ @@ -225,26 +219,47 @@ extern struct ip_globals ip_data; #define ip_reset_option(pcb, opt) ((pcb)->so_options &= ~(opt)) #if LWIP_IPV4 && LWIP_IPV6 +/** + * @ingroup ip + * Output IP packet, netif is selected by source address + */ #define ip_output(p, src, dest, ttl, tos, proto) \ (IP_IS_V6(dest) ? \ ip6_output(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto) : \ ip4_output(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto)) +/** + * @ingroup ip + * Output IP packet to specified interface + */ #define ip_output_if(p, src, dest, ttl, tos, proto, netif) \ (IP_IS_V6(dest) ? \ ip6_output_if(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, netif) : \ ip4_output_if(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, netif)) +/** + * @ingroup ip + * Output IP packet to interface specifying source address + */ #define ip_output_if_src(p, src, dest, ttl, tos, proto, netif) \ (IP_IS_V6(dest) ? \ ip6_output_if_src(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, netif) : \ ip4_output_if_src(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, netif)) +/** Output IP packet with addr_hint */ #define ip_output_hinted(p, src, dest, ttl, tos, proto, addr_hint) \ (IP_IS_V6(dest) ? \ ip6_output_hinted(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, addr_hint) : \ ip4_output_hinted(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, addr_hint)) +/** + * @ingroup ip + * Get netif for address combination. See \ref ip6_route and \ref ip4_route + */ #define ip_route(src, dest) \ (IP_IS_V6(dest) ? \ ip6_route(ip_2_ip6(src), ip_2_ip6(dest)) : \ ip4_route_src(ip_2_ip4(dest), ip_2_ip4(src))) +/** + * @ingroup ip + * Get netif for IP. + */ #define ip_netif_get_local_ip(netif, dest) (IP_IS_V6(dest) ? \ ip6_netif_get_local_ip(netif, ip_2_ip6(dest)) : \ ip4_netif_get_local_ip(netif)) @@ -299,6 +314,6 @@ err_t ip_input(struct pbuf *p, struct netif *inp); } #endif -#endif /* LWIP_HDR_IP_H__ */ +#endif /* LWIP_HDR_IP_H */ diff --git a/tools/sdk/include/lwip/lwip/ip4.h b/tools/sdk/include/lwip/lwip/ip4.h old mode 100755 new mode 100644 index e69e55c7549..48246ecc257 --- a/tools/sdk/include/lwip/lwip/ip4.h +++ b/tools/sdk/include/lwip/lwip/ip4.h @@ -1,3 +1,8 @@ +/** + * @file + * IPv4 API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -41,6 +46,7 @@ #include "lwip/ip4_addr.h" #include "lwip/err.h" #include "lwip/netif.h" +#include "lwip/prot/ip4.h" #ifdef __cplusplus extern "C" { @@ -55,62 +61,6 @@ extern "C" { /** Currently, the function ip_output_if_opt() is only used with IGMP */ #define IP_OPTIONS_SEND (LWIP_IPV4 && LWIP_IGMP) -#define IP_HLEN 20 - - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip_hdr { - /* version / header length */ - PACK_STRUCT_FLD_8(u8_t _v_hl); - /* type of service */ - PACK_STRUCT_FLD_8(u8_t _tos); - /* total length */ - PACK_STRUCT_FIELD(u16_t _len); - /* identification */ - PACK_STRUCT_FIELD(u16_t _id); - /* fragment offset field */ - PACK_STRUCT_FIELD(u16_t _offset); -#define IP_RF 0x8000U /* reserved fragment flag */ -#define IP_DF 0x4000U /* don't fragment flag */ -#define IP_MF 0x2000U /* more fragments flag */ -#define IP_OFFMASK 0x1fffU /* mask for fragmenting bits */ - /* time to live */ - PACK_STRUCT_FLD_8(u8_t _ttl); - /* protocol*/ - PACK_STRUCT_FLD_8(u8_t _proto); - /* checksum */ - PACK_STRUCT_FIELD(u16_t _chksum); - /* source and destination IP addresses */ - PACK_STRUCT_FLD_S(ip4_addr_p_t src); - PACK_STRUCT_FLD_S(ip4_addr_p_t dest); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define IPH_V(hdr) ((hdr)->_v_hl >> 4) -#define IPH_HL(hdr) ((hdr)->_v_hl & 0x0f) -#define IPH_TOS(hdr) ((hdr)->_tos) -#define IPH_LEN(hdr) ((hdr)->_len) -#define IPH_ID(hdr) ((hdr)->_id) -#define IPH_OFFSET(hdr) ((hdr)->_offset) -#define IPH_TTL(hdr) ((hdr)->_ttl) -#define IPH_PROTO(hdr) ((hdr)->_proto) -#define IPH_CHKSUM(hdr) ((hdr)->_chksum) - -#define IPH_VHL_SET(hdr, v, hl) (hdr)->_v_hl = (u8_t)((((v) << 4) | (hl))) -#define IPH_TOS_SET(hdr, tos) (hdr)->_tos = (tos) -#define IPH_LEN_SET(hdr, len) (hdr)->_len = (len) -#define IPH_ID_SET(hdr, id) (hdr)->_id = (id) -#define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off) -#define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl = (u8_t)(ttl) -#define IPH_PROTO_SET(hdr, proto) (hdr)->_proto = (u8_t)(proto) -#define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum) - #define ip_init() /* Compatibility define, no init needed. */ struct netif *ip4_route(const ip4_addr_t *dest); #if LWIP_IPV4_SRC_ROUTING diff --git a/tools/sdk/include/lwip/lwip/ip4_addr.h b/tools/sdk/include/lwip/lwip/ip4_addr.h old mode 100755 new mode 100644 index 9483a2f7b98..51b46b8d4c6 --- a/tools/sdk/include/lwip/lwip/ip4_addr.h +++ b/tools/sdk/include/lwip/lwip/ip4_addr.h @@ -1,3 +1,8 @@ +/** + * @file + * IPv4 address API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -41,32 +46,17 @@ extern "C" { #endif -/* This is the aligned version of ip4_addr_t, +/** This is the aligned version of ip4_addr_t, used as local variable, on the stack, etc. */ struct ip4_addr { u32_t addr; }; -/* This is the packed version of ip4_addr_t, - used in network headers that are itself packed */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip4_addr_packed { - PACK_STRUCT_FIELD(u32_t addr); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - /** ip4_addr_t uses a struct for convenience only, so that the same defines can * operate both on ip4_addr_t as well as on ip4_addr_p_t. */ typedef struct ip4_addr ip4_addr_t; -typedef struct ip4_addr_packed ip4_addr_p_t; -/* +/** * struct ipaddr2 is used in the definition of the ARP packet format in * order to support compilers that don't have structure packing. */ @@ -126,23 +116,8 @@ struct netif; #define IP_LOOPBACKNET 127 /* official! */ - -#if BYTE_ORDER == BIG_ENDIAN /** Set an IP address given by the four byte-parts */ -#define IP4_ADDR(ipaddr, a,b,c,d) \ - (ipaddr)->addr = ((u32_t)((a) & 0xff) << 24) | \ - ((u32_t)((b) & 0xff) << 16) | \ - ((u32_t)((c) & 0xff) << 8) | \ - (u32_t)((d) & 0xff) -#else -/** Set an IP address given by the four byte-parts. - Little-endian version that prevents the use of htonl. */ -#define IP4_ADDR(ipaddr, a,b,c,d) \ - (ipaddr)->addr = ((u32_t)((d) & 0xff) << 24) | \ - ((u32_t)((c) & 0xff) << 16) | \ - ((u32_t)((b) & 0xff) << 8) | \ - (u32_t)((a) & 0xff) -#endif +#define IP4_ADDR(ipaddr, a,b,c,d) (ipaddr)->addr = PP_HTONL(LWIP_MAKEU32(a,b,c,d)) /** MEMCPY-like copying of IP addresses where addresses are known to be * 16-bit-aligned if the port is correctly configured (so a port could define @@ -159,7 +134,7 @@ struct netif; (src)->addr)) /** Set complete address to zero */ #define ip4_addr_set_zero(ipaddr) ((ipaddr)->addr = 0) -/** Set address to IPADDR_ANY (no need for htonl()) */ +/** Set address to IPADDR_ANY (no need for lwip_htonl()) */ #define ip4_addr_set_any(ipaddr) ((ipaddr)->addr = IPADDR_ANY) /** Set address to loopback address */ #define ip4_addr_set_loopback(ipaddr) ((ipaddr)->addr = PP_HTONL(IPADDR_LOOPBACK)) @@ -169,7 +144,7 @@ struct netif; * from host- to network-order. */ #define ip4_addr_set_hton(dest, src) ((dest)->addr = \ ((src) == NULL ? 0:\ - htonl((src)->addr))) + lwip_htonl((src)->addr))) /** IPv4 only: set the IP address given as an u32_t */ #define ip4_addr_set_u32(dest_ipaddr, src_u32) ((dest_ipaddr)->addr = (src_u32)) /** IPv4 only: get the IP address as an u32_t */ @@ -209,10 +184,10 @@ u8_t ip4_addr_netmask_valid(u32_t netmask); LWIP_DEBUGF(debug, ("%" U16_F ".%" U16_F ".%" U16_F ".%" U16_F, a, b, c, d)) #define ip4_addr_debug_print(debug, ipaddr) \ ip4_addr_debug_print_parts(debug, \ - (ipaddr) != NULL ? ip4_addr1_16(ipaddr) : 0, \ - (ipaddr) != NULL ? ip4_addr2_16(ipaddr) : 0, \ - (ipaddr) != NULL ? ip4_addr3_16(ipaddr) : 0, \ - (ipaddr) != NULL ? ip4_addr4_16(ipaddr) : 0) + (u16_t)((ipaddr) != NULL ? ip4_addr1_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr2_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr3_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr4_16(ipaddr) : 0)) #define ip4_addr_debug_print_val(debug, ipaddr) \ ip4_addr_debug_print_parts(debug, \ ip4_addr1_16(&(ipaddr)), \ @@ -233,7 +208,6 @@ u8_t ip4_addr_netmask_valid(u32_t netmask); #define ip4_addr4_16(ipaddr) ((u16_t)ip4_addr4(ipaddr)) #define IP4ADDR_STRLEN_MAX 16 -#define IPADDR_STRLEN_MAX IP4ADDR_STRLEN_MAX /** For backwards compatibility */ #define ip_ntoa(ipaddr) ipaddr_ntoa(ipaddr) diff --git a/tools/sdk/include/lwip/lwip/ip4_frag.h b/tools/sdk/include/lwip/lwip/ip4_frag.h new file mode 100644 index 00000000000..ed5bf14a31c --- /dev/null +++ b/tools/sdk/include/lwip/lwip/ip4_frag.h @@ -0,0 +1,100 @@ +/** + * @file + * IP fragmentation/reassembly + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Jani Monoses + * + */ + +#ifndef LWIP_HDR_IP4_FRAG_H +#define LWIP_HDR_IP4_FRAG_H + +#include "lwip/opt.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" +#include "lwip/netif.h" +#include "lwip/ip_addr.h" +#include "lwip/ip.h" + +#if LWIP_IPV4 + +#ifdef __cplusplus +extern "C" { +#endif + +#if IP_REASSEMBLY +/* The IP reassembly timer interval in milliseconds. */ +#define IP_TMR_INTERVAL 1000 + +/** IP reassembly helper struct. + * This is exported because memp needs to know the size. + */ +struct ip_reassdata { + struct ip_reassdata *next; + struct pbuf *p; + struct ip_hdr iphdr; + u16_t datagram_len; + u8_t flags; + u8_t timer; +}; + +void ip_reass_init(void); +void ip_reass_tmr(void); +struct pbuf * ip4_reass(struct pbuf *p); +#endif /* IP_REASSEMBLY */ + +#if IP_FRAG +#if !LWIP_NETIF_TX_SINGLE_PBUF +#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED +#define LWIP_PBUF_CUSTOM_REF_DEFINED +/** A custom pbuf that holds a reference to another pbuf, which is freed + * when this custom pbuf is freed. This is used to create a custom PBUF_REF + * that points into the original pbuf. */ +struct pbuf_custom_ref { + /** 'base class' */ + struct pbuf_custom pc; + /** pointer to the original pbuf that is referenced */ + struct pbuf *original; +}; +#endif /* LWIP_PBUF_CUSTOM_REF_DEFINED */ +#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */ + +err_t ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest); +#endif /* IP_FRAG */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_IPV4 */ + +#endif /* LWIP_HDR_IP4_FRAG_H */ diff --git a/tools/sdk/include/lwip/lwip/ip6.h b/tools/sdk/include/lwip/lwip/ip6.h old mode 100755 new mode 100644 index f1ffb6b7335..099b94fb74f --- a/tools/sdk/include/lwip/lwip/ip6.h +++ b/tools/sdk/include/lwip/lwip/ip6.h @@ -46,6 +46,7 @@ #if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ #include "lwip/ip6_addr.h" +#include "lwip/prot/ip6.h" #include "lwip/def.h" #include "lwip/pbuf.h" #include "lwip/netif.h" @@ -56,111 +57,6 @@ extern "C" { #endif -#define IP6_HLEN 40 - -#define IP6_NEXTH_HOPBYHOP 0 -#define IP6_NEXTH_TCP 6 -#define IP6_NEXTH_UDP 17 -#define IP6_NEXTH_ENCAPS 41 -#define IP6_NEXTH_ROUTING 43 -#define IP6_NEXTH_FRAGMENT 44 -#define IP6_NEXTH_ICMP6 58 -#define IP6_NEXTH_NONE 59 -#define IP6_NEXTH_DESTOPTS 60 -#define IP6_NEXTH_UDPLITE 136 - - -/* The IPv6 header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip6_hdr { - /* version / traffic class / flow label */ - PACK_STRUCT_FIELD(u32_t _v_tc_fl); - /* payload length */ - PACK_STRUCT_FIELD(u16_t _plen); - /* next header */ - PACK_STRUCT_FLD_8(u8_t _nexth); - /* hop limit */ - PACK_STRUCT_FLD_8(u8_t _hoplim); - /* source and destination IP addresses */ - PACK_STRUCT_FLD_S(ip6_addr_p_t src); - PACK_STRUCT_FLD_S(ip6_addr_p_t dest); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/* Hop-by-hop router alert option. */ -#define IP6_HBH_HLEN 8 -#define IP6_PAD1_OPTION 0 -#define IP6_PADN_ALERT_OPTION 1 -#define IP6_ROUTER_ALERT_OPTION 5 -#define IP6_ROUTER_ALERT_VALUE_MLD 0 -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip6_hbh_hdr { - /* next header */ - PACK_STRUCT_FLD_8(u8_t _nexth); - /* header length */ - PACK_STRUCT_FLD_8(u8_t _hlen); - /* router alert option type */ - PACK_STRUCT_FLD_8(u8_t _ra_opt_type); - /* router alert option data len */ - PACK_STRUCT_FLD_8(u8_t _ra_opt_dlen); - /* router alert option data */ - PACK_STRUCT_FIELD(u16_t _ra_opt_data); - /* PadN option type */ - PACK_STRUCT_FLD_8(u8_t _padn_opt_type); - /* PadN option data len */ - PACK_STRUCT_FLD_8(u8_t _padn_opt_dlen); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/* Fragment header. */ -#define IP6_FRAG_HLEN 8 -#define IP6_FRAG_OFFSET_MASK 0xfff8 -#define IP6_FRAG_MORE_FLAG 0x0001 -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip6_frag_hdr { - /* next header */ - PACK_STRUCT_FLD_8(u8_t _nexth); - /* reserved */ - PACK_STRUCT_FLD_8(u8_t reserved); - /* fragment offset */ - PACK_STRUCT_FIELD(u16_t _fragment_offset); - /* fragmented packet identification */ - PACK_STRUCT_FIELD(u32_t _identification); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define IP6H_V(hdr) ((ntohl((hdr)->_v_tc_fl) >> 28) & 0x0f) -#define IP6H_TC(hdr) ((ntohl((hdr)->_v_tc_fl) >> 20) & 0xff) -#define IP6H_FL(hdr) (ntohl((hdr)->_v_tc_fl) & 0x000fffff) -#define IP6H_PLEN(hdr) (ntohs((hdr)->_plen)) -#define IP6H_NEXTH(hdr) ((hdr)->_nexth) -#define IP6H_NEXTH_P(hdr) ((u8_t *)(hdr) + 6) -#define IP6H_HOPLIM(hdr) ((hdr)->_hoplim) - -#define IP6H_VTCFL_SET(hdr, v, tc, fl) (hdr)->_v_tc_fl = (htonl((((u32_t)(v)) << 28) | (((u32_t)(tc)) << 20) | (fl))) -#define IP6H_PLEN_SET(hdr, plen) (hdr)->_plen = htons(plen) -#define IP6H_NEXTH_SET(hdr, nexth) (hdr)->_nexth = (nexth) -#define IP6H_HOPLIM_SET(hdr, hl) (hdr)->_hoplim = (u8_t)(hl) - - struct netif *ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest); const ip_addr_t *ip6_select_source_address(struct netif *netif, const ip6_addr_t * dest); err_t ip6_input(struct pbuf *p, struct netif *inp); diff --git a/tools/sdk/include/lwip/lwip/ip6_addr.h b/tools/sdk/include/lwip/lwip/ip6_addr.h old mode 100755 new mode 100644 index a75d8948515..ee381aeb233 --- a/tools/sdk/include/lwip/lwip/ip6_addr.h +++ b/tools/sdk/include/lwip/lwip/ip6_addr.h @@ -43,6 +43,7 @@ #define LWIP_HDR_IP6_ADDR_H #include "lwip/opt.h" +#include "def.h" #if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ @@ -52,46 +53,18 @@ extern "C" { #endif -/* This is the aligned version of ip6_addr_t, - used as local variable, on the stack, etc. */ +/** This is the aligned version of ip6_addr_t, + used as local variable, on the stack, etc. */ struct ip6_addr { u32_t addr[4]; }; -/* This is the packed version of ip6_addr_t, - used in network headers that are itself packed */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip6_addr_packed { - PACK_STRUCT_FIELD(u32_t addr[4]); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - +/** IPv6 address */ typedef struct ip6_addr ip6_addr_t; -typedef struct ip6_addr_packed ip6_addr_p_t; - -#if BYTE_ORDER == BIG_ENDIAN -/** Set an IPv6 partial address given by byte-parts. */ +/** Set an IPv6 partial address given by byte-parts */ #define IP6_ADDR_PART(ip6addr, index, a,b,c,d) \ - (ip6addr)->addr[index] = ((u32_t)((a) & 0xff) << 24) | \ - ((u32_t)((b) & 0xff) << 16) | \ - ((u32_t)((c) & 0xff) << 8) | \ - (u32_t)((d) & 0xff) -#else -/** Set an IPv6 partial address given by byte-parts. -Little-endian version, stored in network order (no htonl). */ -#define IP6_ADDR_PART(ip6addr, index, a,b,c,d) \ - (ip6addr)->addr[index] = ((u32_t)((d) & 0xff) << 24) | \ - ((u32_t)((c) & 0xff) << 16) | \ - ((u32_t)((b) & 0xff) << 8) | \ - (u32_t)((a) & 0xff) -#endif + (ip6addr)->addr[index] = PP_HTONL(LWIP_MAKEU32(a,b,c,d)) /** Set a full IPv6 address by passing the 4 u32_t indices in network byte order (use PP_HTONL() for constants) */ @@ -102,14 +75,21 @@ Little-endian version, stored in network order (no htonl). */ (ip6addr)->addr[3] = idx3; } while(0) /** Access address in 16-bit block */ -#define IP6_ADDR_BLOCK1(ip6addr) ((u16_t)(htonl((ip6addr)->addr[0]) >> 16) & 0xffff) -#define IP6_ADDR_BLOCK2(ip6addr) ((u16_t)(htonl((ip6addr)->addr[0])) & 0xffff) -#define IP6_ADDR_BLOCK3(ip6addr) ((u16_t)(htonl((ip6addr)->addr[1]) >> 16) & 0xffff) -#define IP6_ADDR_BLOCK4(ip6addr) ((u16_t)(htonl((ip6addr)->addr[1])) & 0xffff) -#define IP6_ADDR_BLOCK5(ip6addr) ((u16_t)(htonl((ip6addr)->addr[2]) >> 16) & 0xffff) -#define IP6_ADDR_BLOCK6(ip6addr) ((u16_t)(htonl((ip6addr)->addr[2])) & 0xffff) -#define IP6_ADDR_BLOCK7(ip6addr) ((u16_t)(htonl((ip6addr)->addr[3]) >> 16) & 0xffff) -#define IP6_ADDR_BLOCK8(ip6addr) ((u16_t)(htonl((ip6addr)->addr[3])) & 0xffff) +#define IP6_ADDR_BLOCK1(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[0]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK2(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[0])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK3(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[1]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK4(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[1])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK5(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[2]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK6(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[2])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK7(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[3]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK8(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[3])) & 0xffff)) /** Copy IPv6 address - faster than ip6_addr_set: no NULL check */ #define ip6_addr_copy(dest, src) do{(dest).addr[0] = (src).addr[0]; \ @@ -128,7 +108,7 @@ Little-endian version, stored in network order (no htonl). */ (ip6addr)->addr[2] = 0; \ (ip6addr)->addr[3] = 0;}while(0) -/** Set address to ipv6 'any' (no need for htonl()) */ +/** Set address to ipv6 'any' (no need for lwip_htonl()) */ #define ip6_addr_set_any(ip6addr) ip6_addr_set_zero(ip6addr) /** Set address to ipv6 loopback address */ #define ip6_addr_set_loopback(ip6addr) do{(ip6addr)->addr[0] = 0; \ @@ -137,10 +117,10 @@ Little-endian version, stored in network order (no htonl). */ (ip6addr)->addr[3] = PP_HTONL(0x00000001UL);}while(0) /** Safely copy one IPv6 address to another and change byte order * from host- to network-order. */ -#define ip6_addr_set_hton(dest, src) do{(dest)->addr[0] = (src) == NULL ? 0 : htonl((src)->addr[0]); \ - (dest)->addr[1] = (src) == NULL ? 0 : htonl((src)->addr[1]); \ - (dest)->addr[2] = (src) == NULL ? 0 : htonl((src)->addr[2]); \ - (dest)->addr[3] = (src) == NULL ? 0 : htonl((src)->addr[3]);}while(0) +#define ip6_addr_set_hton(dest, src) do{(dest)->addr[0] = (src) == NULL ? 0 : lwip_htonl((src)->addr[0]); \ + (dest)->addr[1] = (src) == NULL ? 0 : lwip_htonl((src)->addr[1]); \ + (dest)->addr[2] = (src) == NULL ? 0 : lwip_htonl((src)->addr[2]); \ + (dest)->addr[3] = (src) == NULL ? 0 : lwip_htonl((src)->addr[3]);}while(0) /** @@ -158,7 +138,7 @@ Little-endian version, stored in network order (no htonl). */ ((addr1)->addr[2] == (addr2)->addr[2]) && \ ((addr1)->addr[3] == (addr2)->addr[3])) -#define ip6_get_subnet_id(ip6addr) (htonl((ip6addr)->addr[2]) & 0x0000ffffUL) +#define ip6_get_subnet_id(ip6addr) (lwip_htonl((ip6addr)->addr[2]) & 0x0000ffffUL) #define ip6_addr_isany_val(ip6addr) (((ip6addr).addr[0] == 0) && \ ((ip6addr).addr[1] == 0) && \ @@ -179,11 +159,13 @@ Little-endian version, stored in network order (no htonl). */ #define ip6_addr_isuniquelocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xfe000000UL)) == PP_HTONL(0xfc000000UL)) +#define ip6_addr_isipv4mappedipv6(ip6addr) (((ip6addr)->addr[0] == 0) && ((ip6addr)->addr[1] == 0) && (((ip6addr)->addr[2]) == PP_HTONL(0x0000FFFFUL))) + #define ip6_addr_ismulticast(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff000000UL)) == PP_HTONL(0xff000000UL)) #define ip6_addr_multicast_transient_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00100000UL)) #define ip6_addr_multicast_prefix_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00200000UL)) #define ip6_addr_multicast_rendezvous_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00400000UL)) -#define ip6_addr_multicast_scope(ip6addr) ((htonl((ip6addr)->addr[0]) >> 16) & 0xf) +#define ip6_addr_multicast_scope(ip6addr) ((lwip_htonl((ip6addr)->addr[0]) >> 16) & 0xf) #define IP6_MULTICAST_SCOPE_RESERVED 0x0 #define IP6_MULTICAST_SCOPE_RESERVED0 0x0 #define IP6_MULTICAST_SCOPE_INTERFACE_LOCAL 0x1 @@ -201,7 +183,7 @@ Little-endian version, stored in network order (no htonl). */ #define ip6_addr_ismulticast_orglocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff080000UL)) #define ip6_addr_ismulticast_global(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff0e0000UL)) -/* TODO define get/set for well-know multicast addresses, e.g. ff02::1 */ +/* @todo define get/set for well-know multicast addresses, e.g. ff02::1 */ #define ip6_addr_isallnodes_iflocal(ip6addr) (((ip6addr)->addr[0] == PP_HTONL(0xff010000UL)) && \ ((ip6addr)->addr[1] == 0UL) && \ ((ip6addr)->addr[2] == 0UL) && \ @@ -249,9 +231,11 @@ Little-endian version, stored in network order (no htonl). */ #define IP6_ADDR_TENTATIVE_5 0x0d /* 5 probes sent */ #define IP6_ADDR_TENTATIVE_6 0x0e /* 6 probes sent */ #define IP6_ADDR_TENTATIVE_7 0x0f /* 7 probes sent */ -#define IP6_ADDR_VALID 0x10 +#define IP6_ADDR_VALID 0x10 /* This bit marks an address as valid (preferred or deprecated) */ #define IP6_ADDR_PREFERRED 0x30 -#define IP6_ADDR_DEPRECATED 0x50 +#define IP6_ADDR_DEPRECATED 0x10 /* Same as VALID (valid but not preferred) */ + +#define IP6_ADDR_TENTATIVE_COUNT_MASK 0x07 /* 1-7 probes sent */ #define ip6_addr_isinvalid(addr_state) (addr_state == IP6_ADDR_INVALID) #define ip6_addr_istentative(addr_state) (addr_state & IP6_ADDR_TENTATIVE) @@ -264,14 +248,14 @@ Little-endian version, stored in network order (no htonl). */ a, b, c, d, e, f, g, h)) #define ip6_addr_debug_print(debug, ipaddr) \ ip6_addr_debug_print_parts(debug, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK1(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK2(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK3(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK4(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK5(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK6(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK7(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK8(ipaddr) : 0) + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK1(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK2(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK3(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK4(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK5(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK6(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK7(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK8(ipaddr) : 0)) #define ip6_addr_debug_print_val(debug, ipaddr) \ ip6_addr_debug_print_parts(debug, \ IP6_ADDR_BLOCK1(&(ipaddr)), \ diff --git a/tools/sdk/include/lwip/lwip/ip6_frag.h b/tools/sdk/include/lwip/lwip/ip6_frag.h old mode 100755 new mode 100644 index 16336e58724..6be274734b2 --- a/tools/sdk/include/lwip/lwip/ip6_frag.h +++ b/tools/sdk/include/lwip/lwip/ip6_frag.h @@ -61,7 +61,7 @@ extern "C" { #define IPV6_FRAG_COPYHEADER 0 #endif -/* The IPv6 reassembly timer interval in milliseconds. */ +/** The IPv6 reassembly timer interval in milliseconds. */ #define IP6_REASS_TMR_INTERVAL 1000 /* Copy the complete header of the first fragment to struct ip6_reassdata @@ -74,7 +74,7 @@ extern "C" { #define IPV6_FRAG_HDRREF(hdr) (hdr) #endif /* IPV6_FRAG_COPYHEADER */ -/* IPv6 reassembly helper struct. +/** IPv6 reassembly helper struct. * This is exported because memp needs to know the size. */ struct ip6_reassdata { @@ -89,17 +89,17 @@ struct ip6_reassdata { #define ip6_reass_init() /* Compatibility define */ void ip6_reass_tmr(void); -struct pbuf * ip6_reass(struct pbuf *p); +struct pbuf *ip6_reass(struct pbuf *p); #endif /* LWIP_IPV6 && LWIP_IPV6_REASS */ #if LWIP_IPV6 && LWIP_IPV6_FRAG /* don't build if not configured for use in lwipopts.h */ +#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED +#define LWIP_PBUF_CUSTOM_REF_DEFINED /** A custom pbuf that holds a reference to another pbuf, which is freed * when this custom pbuf is freed. This is used to create a custom PBUF_REF * that points into the original pbuf. */ -#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED -#define LWIP_PBUF_CUSTOM_REF_DEFINED struct pbuf_custom_ref { /** 'base class' */ struct pbuf_custom pc; diff --git a/tools/sdk/include/lwip/lwip/ip_addr.h b/tools/sdk/include/lwip/lwip/ip_addr.h old mode 100755 new mode 100644 index 74897a9ee92..ca09ed3982a --- a/tools/sdk/include/lwip/lwip/ip_addr.h +++ b/tools/sdk/include/lwip/lwip/ip_addr.h @@ -1,3 +1,8 @@ +/** + * @file + * IP address API (common IPv4 and IPv6) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -29,8 +34,8 @@ * Author: Adam Dunkels * */ -#ifndef LWIP_HDR_IP_ADDR_H__ -#define LWIP_HDR_IP_ADDR_H__ +#ifndef LWIP_HDR_IP_ADDR_H +#define LWIP_HDR_IP_ADDR_H #include "lwip/opt.h" #include "lwip/def.h" @@ -42,36 +47,63 @@ extern "C" { #endif -/** These are the values for ip_addr_t.type */ -#define IPADDR_TYPE_V4 0U -#define IPADDR_TYPE_V6 6U -#define IPADDR_TYPE_ANY 46U +/** @ingroup ipaddr + * IP address types for use in ip_addr_t.type member. + * @see tcp_new_ip_type(), udp_new_ip_type(), raw_new_ip_type(). + */ +enum lwip_ip_addr_type { + /** IPv4 */ + IPADDR_TYPE_V4 = 0U, + /** IPv6 */ + IPADDR_TYPE_V6 = 6U, + /** IPv4+IPv6 ("dual-stack") */ + IPADDR_TYPE_ANY = 46U +}; #if LWIP_IPV4 && LWIP_IPV6 -/** A union struct for both IP version's addresses. +/** + * @ingroup ipaddr + * A union struct for both IP version's addresses. * ATTENTION: watch out for its size when adding IPv6 address scope! */ -typedef struct _ip_addr { +typedef struct ip_addr { union { ip6_addr_t ip6; ip4_addr_t ip4; } u_addr; + /** @ref lwip_ip_addr_type */ u8_t type; } ip_addr_t; extern const ip_addr_t ip_addr_any_type; +/** @ingroup ip4addr */ #define IPADDR4_INIT(u32val) { { { { u32val, 0ul, 0ul, 0ul } } }, IPADDR_TYPE_V4 } +/** @ingroup ip4addr */ +#define IPADDR4_INIT_BYTES(a,b,c,d) IPADDR4_INIT(PP_HTONL(LWIP_MAKEU32(a,b,c,d))) +/** @ingroup ip6addr */ #define IPADDR6_INIT(a, b, c, d) { { { { a, b, c, d } } }, IPADDR_TYPE_V6 } +/** @ingroup ip6addr */ +#define IPADDR6_INIT_HOST(a, b, c, d) { { { { PP_HTONL(a), PP_HTONL(b), PP_HTONL(c), PP_HTONL(d) } } }, IPADDR_TYPE_V6 } +/** @ingroup ipaddr */ #define IP_IS_ANY_TYPE_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_ANY) +/** @ingroup ipaddr */ #define IPADDR_ANY_TYPE_INIT { { { { 0ul, 0ul, 0ul, 0ul } } }, IPADDR_TYPE_ANY } +/** @ingroup ip4addr */ +#define IP_IS_V4_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_V4) +/** @ingroup ip6addr */ #define IP_IS_V6_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_V6) +/** @ingroup ip4addr */ +#define IP_IS_V4(ipaddr) (((ipaddr) == NULL) || IP_IS_V4_VAL(*(ipaddr))) +/** @ingroup ip6addr */ #define IP_IS_V6(ipaddr) (((ipaddr) != NULL) && IP_IS_V6_VAL(*(ipaddr))) +#if ESP_LWIP #define IP_V6_EQ_PART(ipaddr, WORD, VAL) (ip_2_ip6(ipaddr)->addr[WORD] == htonl(VAL)) #define IP_IS_V4MAPPEDV6(ipaddr) (IP_IS_V6(ipaddr) && IP_V6_EQ_PART(ipaddr, 0, 0) && IP_V6_EQ_PART(ipaddr, 1, 0) && IP_V6_EQ_PART(ipaddr, 2, 0x0000FFFF)) +#endif #define IP_SET_TYPE_VAL(ipaddr, iptype) do { (ipaddr).type = (iptype); }while(0) #define IP_SET_TYPE(ipaddr, iptype) do { if((ipaddr) != NULL) { IP_SET_TYPE_VAL(*(ipaddr), iptype); }}while(0) @@ -80,71 +112,100 @@ extern const ip_addr_t ip_addr_any_type; #define IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr) (IP_GET_TYPE(&pcb->local_ip) == IP_GET_TYPE(ipaddr)) #define IP_ADDR_PCB_VERSION_MATCH(pcb, ipaddr) (IP_IS_ANY_TYPE_VAL(pcb->local_ip) || IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) -/* Convert generic ip address to specific protocol version */ +/** @ingroup ip6addr + * Convert generic ip address to specific protocol version + */ #define ip_2_ip6(ipaddr) (&((ipaddr)->u_addr.ip6)) +/** @ingroup ip4addr + * Convert generic ip address to specific protocol version + */ #define ip_2_ip4(ipaddr) (&((ipaddr)->u_addr.ip4)) +/** @ingroup ip4addr */ #define IP_ADDR4(ipaddr,a,b,c,d) do { IP4_ADDR(ip_2_ip4(ipaddr),a,b,c,d); \ IP_SET_TYPE_VAL(*(ipaddr), IPADDR_TYPE_V4); } while(0) +/** @ingroup ip6addr */ #define IP_ADDR6(ipaddr,i0,i1,i2,i3) do { IP6_ADDR(ip_2_ip6(ipaddr),i0,i1,i2,i3); \ IP_SET_TYPE_VAL(*(ipaddr), IPADDR_TYPE_V6); } while(0) +/** @ingroup ip6addr */ +#define IP_ADDR6_HOST(ipaddr,i0,i1,i2,i3) IP_ADDR6(ipaddr,PP_HTONL(i0),PP_HTONL(i1),PP_HTONL(i2),PP_HTONL(i3)) +/** @ingroup ipaddr */ #define ip_addr_copy(dest, src) do{ IP_SET_TYPE_VAL(dest, IP_GET_TYPE(&src)); if(IP_IS_V6_VAL(src)){ \ ip6_addr_copy(*ip_2_ip6(&(dest)), *ip_2_ip6(&(src))); }else{ \ ip4_addr_copy(*ip_2_ip4(&(dest)), *ip_2_ip4(&(src))); }}while(0) +/** @ingroup ip6addr */ #define ip_addr_copy_from_ip6(dest, src) do{ \ ip6_addr_copy(*ip_2_ip6(&(dest)), src); IP_SET_TYPE_VAL(dest, IPADDR_TYPE_V6); }while(0) +/** @ingroup ip4addr */ #define ip_addr_copy_from_ip4(dest, src) do{ \ ip4_addr_copy(*ip_2_ip4(&(dest)), src); IP_SET_TYPE_VAL(dest, IPADDR_TYPE_V4); }while(0) +/** @ingroup ip4addr */ #define ip_addr_set_ip4_u32(ipaddr, val) do{if(ipaddr){ip4_addr_set_u32(ip_2_ip4(ipaddr), val); \ IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); }}while(0) -#define ip_addr_get_ip4_u32(ipaddr) (((ipaddr) && !IP_IS_V6(ipaddr)) ? \ +/** @ingroup ip4addr */ +#define ip_addr_get_ip4_u32(ipaddr) (((ipaddr) && IP_IS_V4(ipaddr)) ? \ ip4_addr_get_u32(ip_2_ip4(ipaddr)) : 0) - +/** @ingroup ipaddr */ #define ip_addr_set(dest, src) do{ IP_SET_TYPE(dest, IP_GET_TYPE(src)); if(IP_IS_V6(src)){ \ ip6_addr_set(ip_2_ip6(dest), ip_2_ip6(src)); }else{ \ ip4_addr_set(ip_2_ip4(dest), ip_2_ip4(src)); }}while(0) - +/** @ingroup ipaddr */ #define ip_addr_set_ipaddr(dest, src) ip_addr_set(dest, src) +/** @ingroup ipaddr */ #define ip_addr_set_zero(ipaddr) do{ \ ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, 0); }while(0) +/** @ingroup ip5addr */ #define ip_addr_set_zero_ip4(ipaddr) do{ \ ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); }while(0) +/** @ingroup ip6addr */ #define ip_addr_set_zero_ip6(ipaddr) do{ \ ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V6); }while(0) +/** @ingroup ipaddr */ #define ip_addr_set_any(is_ipv6, ipaddr) do{if(is_ipv6){ \ ip6_addr_set_any(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V6); }else{ \ ip4_addr_set_any(ip_2_ip4(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); }}while(0) +/** @ingroup ipaddr */ #define ip_addr_set_loopback(is_ipv6, ipaddr) do{if(is_ipv6){ \ ip6_addr_set_loopback(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V6); }else{ \ ip4_addr_set_loopback(ip_2_ip4(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); }}while(0) +/** @ingroup ipaddr */ #define ip_addr_set_hton(dest, src) do{if(IP_IS_V6(src)){ \ ip6_addr_set_hton(ip_2_ip6(ipaddr), (src)); IP_SET_TYPE(dest, IPADDR_TYPE_V6); }else{ \ ip4_addr_set_hton(ip_2_ip4(ipaddr), (src)); IP_SET_TYPE(dest, IPADDR_TYPE_V4); }}while(0) +/** @ingroup ipaddr */ #define ip_addr_get_network(target, host, netmask) do{if(IP_IS_V6(host)){ \ ip4_addr_set_zero(ip_2_ip4(target)); IP_SET_TYPE(target, IPADDR_TYPE_V6); } else { \ ip4_addr_get_network(ip_2_ip4(target), ip_2_ip4(host), ip_2_ip4(netmask)); IP_SET_TYPE(target, IPADDR_TYPE_V4); }}while(0) +/** @ingroup ipaddr */ #define ip_addr_netcmp(addr1, addr2, mask) ((IP_IS_V6(addr1) && IP_IS_V6(addr2)) ? \ 0 : \ ip4_addr_netcmp(ip_2_ip4(addr1), ip_2_ip4(addr2), mask)) +/** @ingroup ipaddr */ #define ip_addr_cmp(addr1, addr2) ((IP_GET_TYPE(addr1) != IP_GET_TYPE(addr2)) ? 0 : (IP_IS_V6_VAL(*(addr1)) ? \ ip6_addr_cmp(ip_2_ip6(addr1), ip_2_ip6(addr2)) : \ ip4_addr_cmp(ip_2_ip4(addr1), ip_2_ip4(addr2)))) +/** @ingroup ipaddr */ #define ip_addr_isany(ipaddr) ((IP_IS_V6(ipaddr)) ? \ ip6_addr_isany(ip_2_ip6(ipaddr)) : \ ip4_addr_isany(ip_2_ip4(ipaddr))) +/** @ingroup ipaddr */ #define ip_addr_isany_val(ipaddr) ((IP_IS_V6_VAL(ipaddr)) ? \ ip6_addr_isany_val(*ip_2_ip6(&(ipaddr))) : \ ip4_addr_isany_val(*ip_2_ip4(&(ipaddr)))) +/** @ingroup ipaddr */ #define ip_addr_isbroadcast(ipaddr, netif) ((IP_IS_V6(ipaddr)) ? \ 0 : \ ip4_addr_isbroadcast(ip_2_ip4(ipaddr), netif)) +/** @ingroup ipaddr */ #define ip_addr_ismulticast(ipaddr) ((IP_IS_V6(ipaddr)) ? \ ip6_addr_ismulticast(ip_2_ip6(ipaddr)) : \ ip4_addr_ismulticast(ip_2_ip4(ipaddr))) +/** @ingroup ipaddr */ #define ip_addr_isloopback(ipaddr) ((IP_IS_V6(ipaddr)) ? \ ip6_addr_isloopback(ip_2_ip6(ipaddr)) : \ ip4_addr_isloopback(ip_2_ip4(ipaddr))) +/** @ingroup ipaddr */ #define ip_addr_islinklocal(ipaddr) ((IP_IS_V6(ipaddr)) ? \ ip6_addr_islinklocal(ip_2_ip6(ipaddr)) : \ ip4_addr_islinklocal(ip_2_ip4(ipaddr))) @@ -154,32 +215,29 @@ extern const ip_addr_t ip_addr_any_type; #define ip_addr_debug_print_val(debug, ipaddr) do { if(IP_IS_V6_VAL(ipaddr)) { \ ip6_addr_debug_print_val(debug, *ip_2_ip6(&(ipaddr))); } else { \ ip4_addr_debug_print_val(debug, *ip_2_ip4(&(ipaddr))); }}while(0) +/** @ingroup ipaddr */ #define ipaddr_ntoa(addr) (((addr) == NULL) ? "NULL" : \ ((IP_IS_V6(addr)) ? ip6addr_ntoa(ip_2_ip6(addr)) : ip4addr_ntoa(ip_2_ip4(addr)))) +/** @ingroup ipaddr */ #define ipaddr_ntoa_r(addr, buf, buflen) (((addr) == NULL) ? "NULL" : \ ((IP_IS_V6(addr)) ? ip6addr_ntoa_r(ip_2_ip6(addr), buf, buflen) : ip4addr_ntoa_r(ip_2_ip4(addr), buf, buflen))) int ipaddr_aton(const char *cp, ip_addr_t *addr); -/* Map an IPv4 ip_addr into an IPV6 ip_addr, using format - defined in RFC4291 2.5.5.2. - - Safe to call when dest==src. -*/ -#define ip_addr_make_ip4_mapped_ip6(dest, src) do { \ - u32_t tmp = ip_2_ip4(src)->addr; \ - IP_ADDR6((dest), 0x0, 0x0, htonl(0x0000FFFF), tmp); \ - } while(0) +/** @ingroup ipaddr */ +#define IPADDR_STRLEN_MAX IP6ADDR_STRLEN_MAX -/* Convert an IPv4 mapped V6 address to an IPV4 address. +/** @ingroup ipaddr */ +#define ip4_2_ipv4_mapped_ipv6(ip6addr, ip4addr) do { \ + (ip6addr)->addr[3] = (ip4addr)->addr; \ + (ip6addr)->addr[2] = PP_HTONL(0x0000FFFFUL); \ + (ip6addr)->addr[1] = 0; \ + (ip6addr)->addr[0] = 0; } while(0); - Check IP_IS_V4MAPPEDV6(src) before using this. +/** @ingroup ipaddr */ +#define unmap_ipv4_mapped_ipv6(ip4addr, ip6addr) \ + (ip4addr)->addr = (ip6addr)->addr[3]; - Safe to call when dest == src. -*/ -#define ip_addr_ip4_from_mapped_ip6(dest, src) do { \ - ip_2_ip4(dest)->addr = ip_2_ip6(src)->addr[3]; \ - IP_SET_TYPE(dest, IPADDR_TYPE_V4); \ - } while(0) +#define IP46_ADDR_ANY(type) (((type) == IPADDR_TYPE_V6)? IP6_ADDR_ANY : IP4_ADDR_ANY) #else /* LWIP_IPV4 && LWIP_IPV6 */ @@ -190,7 +248,10 @@ int ipaddr_aton(const char *cp, ip_addr_t *addr); typedef ip4_addr_t ip_addr_t; #define IPADDR4_INIT(u32val) { u32val } +#define IPADDR4_INIT_BYTES(a,b,c,d) IPADDR4_INIT(PP_HTONL(LWIP_MAKEU32(a,b,c,d))) +#define IP_IS_V4_VAL(ipaddr) 1 #define IP_IS_V6_VAL(ipaddr) 0 +#define IP_IS_V4(ipaddr) 1 #define IP_IS_V6(ipaddr) 0 #define IP_IS_ANY_TYPE_VAL(ipaddr) 0 #define IP_SET_TYPE_VAL(ipaddr, iptype) @@ -225,11 +286,18 @@ typedef ip4_addr_t ip_addr_t; #define ipaddr_ntoa_r(ipaddr, buf, buflen) ip4addr_ntoa_r(ipaddr, buf, buflen) #define ipaddr_aton(cp, addr) ip4addr_aton(cp, addr) +#define IPADDR_STRLEN_MAX IP4ADDR_STRLEN_MAX + +#define IP46_ADDR_ANY(type) (IP4_ADDR_ANY) + #else /* LWIP_IPV4 */ typedef ip6_addr_t ip_addr_t; #define IPADDR6_INIT(a, b, c, d) { { a, b, c, d } } +#define IPADDR6_INIT_HOST(a, b, c, d) { { PP_HTONL(a), PP_HTONL(b), PP_HTONL(c), PP_HTONL(d) } } +#define IP_IS_V4_VAL(ipaddr) 0 #define IP_IS_V6_VAL(ipaddr) 1 +#define IP_IS_V4(ipaddr) 0 #define IP_IS_V6(ipaddr) 1 #define IP_IS_ANY_TYPE_VAL(ipaddr) 0 #define IP_SET_TYPE_VAL(ipaddr, iptype) @@ -237,6 +305,7 @@ typedef ip6_addr_t ip_addr_t; #define IP_GET_TYPE(ipaddr) IPADDR_TYPE_V6 #define ip_2_ip6(ipaddr) (ipaddr) #define IP_ADDR6(ipaddr,i0,i1,i2,i3) IP6_ADDR(ipaddr,i0,i1,i2,i3) +#define IP_ADDR6_HOST(ipaddr,i0,i1,i2,i3) IP_ADDR6(ipaddr,PP_HTONL(i0),PP_HTONL(i1),PP_HTONL(i2),PP_HTONL(i3)) #define ip_addr_copy(dest, src) ip6_addr_copy(dest, src) #define ip_addr_copy_from_ip6(dest, src) ip6_addr_copy(dest, src) @@ -262,6 +331,10 @@ typedef ip6_addr_t ip_addr_t; #define ipaddr_ntoa_r(ipaddr, buf, buflen) ip6addr_ntoa_r(ipaddr, buf, buflen) #define ipaddr_aton(cp, addr) ip6addr_aton(cp, addr) +#define IPADDR_STRLEN_MAX IP6ADDR_STRLEN_MAX + +#define IP46_ADDR_ANY(type) (IP6_ADDR_ANY) + #endif /* LWIP_IPV4 */ #endif /* LWIP_IPV4 && LWIP_IPV6 */ @@ -270,15 +343,33 @@ typedef ip6_addr_t ip_addr_t; extern const ip_addr_t ip_addr_any; extern const ip_addr_t ip_addr_broadcast; -/** IP_ADDR_ can be used as a fixed/const ip_addr_t - * for the IPv4 wildcard and the broadcast address +/** + * @ingroup ip4addr + * Can be used as a fixed/const ip_addr_t + * for the IP wildcard. + * Defined to @ref IP4_ADDR_ANY when IPv4 is enabled. + * Defined to @ref IP6_ADDR_ANY in IPv6 only systems. + * Use this if you can handle IPv4 _AND_ IPv6 addresses. + * Use @ref IP4_ADDR_ANY or @ref IP6_ADDR_ANY when the IP + * type matters. */ -#define IP_ADDR_ANY (&ip_addr_any) -#define IP_ADDR_BROADCAST (&ip_addr_broadcast) -/** IP4_ADDR_ can be used as a fixed/const ip4_addr_t - * for the wildcard and the broadcast address +#define IP_ADDR_ANY IP4_ADDR_ANY +/** + * @ingroup ip4addr + * Can be used as a fixed/const ip_addr_t + * for the IPv4 wildcard and the broadcast address + */ +#define IP4_ADDR_ANY (&ip_addr_any) +/** + * @ingroup ip4addr + * Can be used as a fixed/const ip4_addr_t + * for the wildcard and the broadcast address */ -#define IP4_ADDR_ANY (ip_2_ip4(&ip_addr_any)) +#define IP4_ADDR_ANY4 (ip_2_ip4(&ip_addr_any)) + +/** @ingroup ip4addr */ +#define IP_ADDR_BROADCAST (&ip_addr_broadcast) +/** @ingroup ip4addr */ #define IP4_ADDR_BROADCAST (ip_2_ip4(&ip_addr_broadcast)) #endif /* LWIP_IPV4*/ @@ -287,23 +378,28 @@ extern const ip_addr_t ip_addr_broadcast; extern const ip_addr_t ip6_addr_any; -/** IP6_ADDR_ANY can be used as a fixed ip_addr_t - * for the IPv6 wildcard address +/** + * @ingroup ip6addr + * IP6_ADDR_ANY can be used as a fixed ip_addr_t + * for the IPv6 wildcard address */ #define IP6_ADDR_ANY (&ip6_addr_any) -/** IP6_ADDR_ANY6 can be used as a fixed ip6_addr_t - * for the IPv6 wildcard address +/** + * @ingroup ip6addr + * IP6_ADDR_ANY6 can be used as a fixed ip6_addr_t + * for the IPv6 wildcard address */ #define IP6_ADDR_ANY6 (ip_2_ip6(&ip6_addr_any)) #if !LWIP_IPV4 -/** Just a little upgrade-helper for IPv6-only configurations: */ +/** IPv6-only configurations */ #define IP_ADDR_ANY IP6_ADDR_ANY #endif /* !LWIP_IPV4 */ #endif #if LWIP_IPV4 && LWIP_IPV6 +/** @ingroup ipaddr */ #define IP_ANY_TYPE (&ip_addr_any_type) #else #define IP_ANY_TYPE IP_ADDR_ANY @@ -313,4 +409,4 @@ extern const ip_addr_t ip6_addr_any; } #endif -#endif /* LWIP_HDR_IP_ADDR_H__ */ +#endif /* LWIP_HDR_IP_ADDR_H */ diff --git a/tools/sdk/include/lwip/lwip/ip_frag.h b/tools/sdk/include/lwip/lwip/ip_frag.h deleted file mode 100755 index deeb2f4efc9..00000000000 --- a/tools/sdk/include/lwip/lwip/ip_frag.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2001-2004 Swedish Institute of Computer Science. - * All rights reserved. - * - * 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. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Jani Monoses - * - */ - -#ifndef LWIP_HDR_IP_FRAG_H -#define LWIP_HDR_IP_FRAG_H - -#include "lwip/opt.h" -#include "lwip/err.h" -#include "lwip/pbuf.h" -#include "lwip/netif.h" -#include "lwip/ip_addr.h" -#include "lwip/ip.h" - -#if LWIP_IPV4 - -#ifdef __cplusplus -extern "C" { -#endif - -#if IP_REASSEMBLY -/* The IP reassembly timer interval in milliseconds. */ -#define IP_TMR_INTERVAL 1000 - -/* IP reassembly helper struct. - * This is exported because memp needs to know the size. - */ -struct ip_reassdata { - struct ip_reassdata *next; - struct pbuf *p; - struct ip_hdr iphdr; - u16_t datagram_len; - u8_t flags; - u8_t timer; -}; - -void ip_reass_init(void); -void ip_reass_tmr(void); -struct pbuf * ip4_reass(struct pbuf *p); -#endif /* IP_REASSEMBLY */ - -#if IP_FRAG -#if !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF -/** A custom pbuf that holds a reference to another pbuf, which is freed - * when this custom pbuf is freed. This is used to create a custom PBUF_REF - * that points into the original pbuf. */ -#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED -#define LWIP_PBUF_CUSTOM_REF_DEFINED -struct pbuf_custom_ref { - /** 'base class' */ - struct pbuf_custom pc; - /** pointer to the original pbuf that is referenced */ - struct pbuf *original; -}; -#endif /* LWIP_PBUF_CUSTOM_REF_DEFINED */ -#endif /* !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ - -err_t ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest); -#endif /* IP_FRAG */ - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_IPV4 */ - -#endif /* LWIP_HDR_IP_FRAG_H */ diff --git a/tools/sdk/include/lwip/lwip/mem.h b/tools/sdk/include/lwip/lwip/mem.h old mode 100755 new mode 100644 index 966d6bbb0c1..ff208d25c32 --- a/tools/sdk/include/lwip/lwip/mem.h +++ b/tools/sdk/include/lwip/lwip/mem.h @@ -1,3 +1,8 @@ +/** + * @file + * Heap API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -40,47 +45,17 @@ extern "C" { #if MEM_LIBC_MALLOC -#include /* for size_t */ +#include "lwip/arch.h" typedef size_t mem_size_t; #define MEM_SIZE_F SZT_F -/* aliases for C library malloc() */ -#define mem_init() -/* in case C library malloc() needs extra protection, - * allow these defines to be overridden. - */ +#elif MEM_USE_POOLS -#ifndef mem_free -#define mem_free free -#endif -/** - * lwip_malloc: if CONFIG_ALLOC_MEMORY_IN_SPIRAM_FIRST is enabled, Try to - * allocate memory for lwip in SPIRAM firstly. If failed, try to allocate - * internal memory then. - */ -#if CONFIG_WIFI_LWIP_ALLOCATION_FROM_SPIRAM_FIRST -#ifndef mem_malloc -#define mem_malloc(size) heap_caps_malloc_prefer(size, 2, MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL) -#endif -#ifndef mem_calloc -#define mem_calloc(n, size) heap_caps_calloc_prefer(n, size, 2, MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL) -#endif -#else -#ifndef mem_malloc -#define mem_malloc malloc -#endif -#ifndef mem_calloc -#define mem_calloc calloc -#endif -#endif +typedef u16_t mem_size_t; +#define MEM_SIZE_F U16_F -/* Since there is no C library allocation function to shrink memory without - moving it, define this to nothing. */ -#ifndef mem_trim -#define mem_trim(mem, size) (mem) -#endif -#else /* MEM_LIBC_MALLOC */ +#else /* MEM_SIZE would have to be aligned, but using 64000 here instead of * 65535 leaves some room for alignment... @@ -92,45 +67,13 @@ typedef u32_t mem_size_t; typedef u16_t mem_size_t; #define MEM_SIZE_F U16_F #endif /* MEM_SIZE > 64000 */ +#endif -#if MEM_USE_POOLS -/** mem_init is not used when using pools instead of a heap */ -#define mem_init() -/** mem_trim is not used when using pools instead of a heap: - we can't free part of a pool element and don't want to copy the rest */ -#define mem_trim(mem, size) (mem) -#else /* MEM_USE_POOLS */ -/* lwIP alternative malloc */ void mem_init(void); void *mem_trim(void *mem, mem_size_t size); -#endif /* MEM_USE_POOLS */ void *mem_malloc(mem_size_t size); void *mem_calloc(mem_size_t count, mem_size_t size); void mem_free(void *mem); -#endif /* MEM_LIBC_MALLOC */ - -/** Calculate memory size for an aligned buffer - returns the next highest - * multiple of MEM_ALIGNMENT (e.g. LWIP_MEM_ALIGN_SIZE(3) and - * LWIP_MEM_ALIGN_SIZE(4) will both yield 4 for MEM_ALIGNMENT == 4). - */ -#ifndef LWIP_MEM_ALIGN_SIZE -#define LWIP_MEM_ALIGN_SIZE(size) (((size) + MEM_ALIGNMENT - 1U) & ~(MEM_ALIGNMENT-1U)) -#endif - -/** Calculate safe memory size for an aligned buffer when using an unaligned - * type as storage. This includes a safety-margin on (MEM_ALIGNMENT - 1) at the - * start (e.g. if buffer is u8_t[] and actual data will be u32_t*) - */ -#ifndef LWIP_MEM_ALIGN_BUFFER -#define LWIP_MEM_ALIGN_BUFFER(size) (((size) + MEM_ALIGNMENT - 1U)) -#endif - -/** Align a memory pointer to the alignment defined by MEM_ALIGNMENT - * so that ADDR % MEM_ALIGNMENT == 0 - */ -#ifndef LWIP_MEM_ALIGN -#define LWIP_MEM_ALIGN(addr) ((void *)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) & ~(mem_ptr_t)(MEM_ALIGNMENT-1))) -#endif #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/memp.h b/tools/sdk/include/lwip/lwip/memp.h old mode 100755 new mode 100644 index abb8e57f66c..562cd05bffd --- a/tools/sdk/include/lwip/lwip/memp.h +++ b/tools/sdk/include/lwip/lwip/memp.h @@ -1,3 +1,8 @@ +/** + * @file + * Memory pool API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -33,6 +38,8 @@ #ifndef LWIP_HDR_MEMP_H #define LWIP_HDR_MEMP_H +#include "lwip/opt.h" + #ifdef __cplusplus extern "C" { #endif @@ -41,7 +48,7 @@ extern "C" { #define LWIP_MEMPOOL(name,num,size,desc) #include "lwip/priv/memp_std.h" -/* Create the list of all memory pools managed by memp. MEMP_MAX represents a NULL pool at the end */ +/** Create the list of all memory pools managed by memp. MEMP_MAX represents a NULL pool at the end */ typedef enum { #define LWIP_MEMPOOL(name,num,size,desc) MEMP_##name, #include "lwip/priv/memp_std.h" @@ -49,86 +56,86 @@ typedef enum { } memp_t; #include "lwip/priv/memp_priv.h" - -/* Private mempools example: - * .h: only when pool is used in multiple .c files: LWIP_MEMPOOL_PROTOTYPE(my_private_pool); - * .c: - * - in global variables section: LWIP_MEMPOOL_DECLARE(my_private_pool, 10, sizeof(foo), "Some description") - * - call ONCE before using pool (e.g. in some init() function): LWIP_MEMPOOL_INIT(my_private_pool); - * - allocate: void* my_new_mem = LWIP_MEMPOOL_ALLOC(my_private_pool); - * - free: LWIP_MEMPOOL_FREE(my_private_pool, my_new_mem); - * - * To relocate a pool, declare it as extern in cc.h. Example for GCC: - * extern u8_t __attribute__((section(".onchip_mem"))) memp_memory_my_private_pool[]; - */ +#include "lwip/stats.h" extern const struct memp_desc* const memp_pools[MEMP_MAX]; +/** + * @ingroup mempool + * Declare prototype for private memory pool if it is used in multiple files + */ #define LWIP_MEMPOOL_PROTOTYPE(name) extern const struct memp_desc memp_ ## name #if MEMP_MEM_MALLOC -#include "lwip/mem.h" - -#define memp_init() -#if ESP_STATS_MEM -static inline void* memp_malloc(int type) -{ - ESP_CNT_MEM_MALLOC_INC(type); - return mem_malloc(memp_pools[type]->size); -} - -static inline void memp_free(int type, void *mem) -{ - ESP_CNT_MEM_FREE_INC(type); - mem_free(mem); -} - -//#define memp_malloc(type) mem_malloc(memp_pools[type]->size); ESP_CNT_MEM_MALLOC_INC(type) -//#define memp_free(type, mem) mem_free(mem); ESP_CNT_MEM_FREE_INC(type) -#else -#define memp_malloc(type) mem_malloc(memp_pools[type]->size) -#define memp_free(type, mem) mem_free(mem) -#endif - #define LWIP_MEMPOOL_DECLARE(name,num,size,desc) \ + LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(memp_stats_ ## name) \ const struct memp_desc memp_ ## name = { \ + DECLARE_LWIP_MEMPOOL_DESC(desc) \ + LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(memp_stats_ ## name) \ LWIP_MEM_ALIGN_SIZE(size) \ }; -#define LWIP_MEMPOOL_INIT(name) -#define LWIP_MEMPOOL_ALLOC(name) mem_malloc(memp_ ## name.size) -#define LWIP_MEMPOOL_FREE(name, x) mem_free(x) - #else /* MEMP_MEM_MALLOC */ -#define LWIP_MEMPOOL_DECLARE(name,num,size,desc) u8_t memp_memory_ ## name ## _base \ - [((num) * (MEMP_SIZE + MEMP_ALIGN_SIZE(size)))]; \ +/** + * @ingroup mempool + * Declare a private memory pool + * Private mempools example: + * .h: only when pool is used in multiple .c files: LWIP_MEMPOOL_PROTOTYPE(my_private_pool); + * .c: + * - in global variables section: LWIP_MEMPOOL_DECLARE(my_private_pool, 10, sizeof(foo), "Some description") + * - call ONCE before using pool (e.g. in some init() function): LWIP_MEMPOOL_INIT(my_private_pool); + * - allocate: void* my_new_mem = LWIP_MEMPOOL_ALLOC(my_private_pool); + * - free: LWIP_MEMPOOL_FREE(my_private_pool, my_new_mem); + * + * To relocate a pool, declare it as extern in cc.h. Example for GCC: + * extern u8_t __attribute__((section(".onchip_mem"))) memp_memory_my_private_pool[]; + */ +#define LWIP_MEMPOOL_DECLARE(name,num,size,desc) \ + LWIP_DECLARE_MEMORY_ALIGNED(memp_memory_ ## name ## _base, ((num) * (MEMP_SIZE + MEMP_ALIGN_SIZE(size)))); \ + \ + LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(memp_stats_ ## name) \ \ static struct memp *memp_tab_ ## name; \ \ const struct memp_desc memp_ ## name = { \ + DECLARE_LWIP_MEMPOOL_DESC(desc) \ + LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(memp_stats_ ## name) \ LWIP_MEM_ALIGN_SIZE(size), \ (num), \ - DECLARE_LWIP_MEMPOOL_DESC(desc) \ memp_memory_ ## name ## _base, \ &memp_tab_ ## name \ }; +#endif /* MEMP_MEM_MALLOC */ + +/** + * @ingroup mempool + * Initialize a private memory pool + */ #define LWIP_MEMPOOL_INIT(name) memp_init_pool(&memp_ ## name) +/** + * @ingroup mempool + * Allocate from a private memory pool + */ #define LWIP_MEMPOOL_ALLOC(name) memp_malloc_pool(&memp_ ## name) +/** + * @ingroup mempool + * Free element from a private memory pool + */ #define LWIP_MEMPOOL_FREE(name, x) memp_free_pool(&memp_ ## name, (x)) #if MEM_USE_POOLS -/** This structure is used to save the pool one element came from. */ +/** This structure is used to save the pool one element came from. + * This has to be defined here as it is required for pool size calculation. */ struct memp_malloc_helper { memp_t poolnr; -#if MEMP_OVERFLOW_CHECK +#if MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) u16_t size; -#endif /* MEMP_OVERFLOW_CHECK */ +#endif /* MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) */ }; - #endif /* MEM_USE_POOLS */ void memp_init(void); @@ -141,8 +148,6 @@ void *memp_malloc(memp_t type); #endif void memp_free(memp_t type, void *mem); -#endif /* MEMP_MEM_MALLOC */ - #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/mld6.h b/tools/sdk/include/lwip/lwip/mld6.h old mode 100755 new mode 100644 index a54dd49e918..7fa0797f272 --- a/tools/sdk/include/lwip/lwip/mld6.h +++ b/tools/sdk/include/lwip/lwip/mld6.h @@ -50,16 +50,14 @@ #include "lwip/pbuf.h" #include "lwip/netif.h" - #ifdef __cplusplus extern "C" { #endif +/** MLD group */ struct mld_group { /** next link */ struct mld_group *next; - /** interface on which the group is active */ - struct netif *netif; /** multicast address */ ip6_addr_t group_address; /** signifies we were the last person to report */ @@ -72,33 +70,8 @@ struct mld_group { u8_t use; }; -/** Multicast listener report/query/done message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct mld_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u16_t max_resp_delay); - PACK_STRUCT_FIELD(u16_t reserved); - PACK_STRUCT_FLD_S(ip6_addr_p_t multicast_address); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - #define MLD6_TMR_INTERVAL 100 /* Milliseconds */ -/* MAC Filter Actions, these are passed to a netif's - * mld_mac_filter callback function. */ -#define MLD6_DEL_MAC_FILTER 0 -#define MLD6_ADD_MAC_FILTER 1 - - err_t mld6_stop(struct netif *netif); void mld6_report_groups(struct netif *netif); void mld6_tmr(void); @@ -109,6 +82,13 @@ err_t mld6_joingroup_netif(struct netif *netif, const ip6_addr_t *groupaddr); err_t mld6_leavegroup(const ip6_addr_t *srcaddr, const ip6_addr_t *groupaddr); err_t mld6_leavegroup_netif(struct netif *netif, const ip6_addr_t *groupaddr); +/** @ingroup mld6 + * Get list head of MLD6 groups for netif. + * Note: The allnodes group IP is NOT in the list, since it must always + * be received for correct IPv6 operation. + * @see @ref netif_set_mld_mac_filter() + */ +#define netif_mld6_data(netif) ((struct mld_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_MLD6)) #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/nd6.h b/tools/sdk/include/lwip/lwip/nd6.h old mode 100755 new mode 100644 index 27a4c8137af..d9fba970729 --- a/tools/sdk/include/lwip/lwip/nd6.h +++ b/tools/sdk/include/lwip/lwip/nd6.h @@ -48,314 +48,38 @@ #if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ -#include "lwip/pbuf.h" -#include "lwip/ip6.h" #include "lwip/ip6_addr.h" -#include "lwip/netif.h" - +#include "lwip/err.h" #ifdef __cplusplus extern "C" { #endif -/* Struct for tables. */ -struct nd6_neighbor_cache_entry { - ip6_addr_t next_hop_address; - struct netif * netif; - u8_t lladdr[NETIF_MAX_HWADDR_LEN]; - /*u32_t pmtu;*/ -#if LWIP_ND6_QUEUEING - /** Pointer to queue of pending outgoing packets on this entry. */ - struct nd6_q_entry *q; -#else /* LWIP_ND6_QUEUEING */ - /** Pointer to a single pending outgoing packet on this entry. */ - struct pbuf *q; -#endif /* LWIP_ND6_QUEUEING */ - u8_t state; - u8_t isrouter; - union { - u32_t reachable_time; - u32_t delay_time; - u32_t probes_sent; - u32_t stale_time; - } counter; -}; - -struct nd6_destination_cache_entry { - ip6_addr_t destination_addr; - ip6_addr_t next_hop_addr; - u16_t pmtu; - u32_t age; -}; - -struct nd6_prefix_list_entry { - ip6_addr_t prefix; - struct netif * netif; - u32_t invalidation_timer; -#if LWIP_IPV6_AUTOCONFIG - u8_t flags; -#define ND6_PREFIX_AUTOCONFIG_AUTONOMOUS 0x01 -#define ND6_PREFIX_AUTOCONFIG_ADDRESS_GENERATED 0x02 -#define ND6_PREFIX_AUTOCONFIG_ADDRESS_DUPLICATE 0x04 -#endif /* LWIP_IPV6_AUTOCONFIG */ -}; - -struct nd6_router_list_entry { - struct nd6_neighbor_cache_entry * neighbor_entry; - u32_t invalidation_timer; - u8_t flags; -}; - - -enum nd6_neighbor_cache_entry_state { - ND6_NO_ENTRY = 0, - ND6_INCOMPLETE, - ND6_REACHABLE, - ND6_STALE, - ND6_DELAY, - ND6_PROBE -}; - -#if LWIP_ND6_QUEUEING -/** struct for queueing outgoing packets for unknown address - * defined here to be accessed by memp.h - */ -struct nd6_q_entry { - struct nd6_q_entry *next; - struct pbuf *p; -}; -#endif /* LWIP_ND6_QUEUEING */ - -/** Neighbor solicitation message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ns_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u32_t reserved); - PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Neighbor advertisement message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct na_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FLD_8(u8_t flags); - PACK_STRUCT_FLD_8(u8_t reserved[3]); - PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif -#define ND6_FLAG_ROUTER (0x80) -#define ND6_FLAG_SOLICITED (0x40) -#define ND6_FLAG_OVERRIDE (0x20) - -/** Router solicitation message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct rs_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u32_t reserved); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Router advertisement message header. */ -#define ND6_RA_FLAG_MANAGED_ADDR_CONFIG (0x80) -#define ND6_RA_FLAG_OTHER_CONFIG (0x40) -#define ND6_RA_FLAG_HOME_AGENT (0x20) -#define ND6_RA_PREFERENCE_MASK (0x18) -#define ND6_RA_PREFERENCE_HIGH (0x08) -#define ND6_RA_PREFERENCE_MEDIUM (0x00) -#define ND6_RA_PREFERENCE_LOW (0x18) -#define ND6_RA_PREFERENCE_DISABLED (0x10) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ra_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FLD_8(u8_t current_hop_limit); - PACK_STRUCT_FLD_8(u8_t flags); - PACK_STRUCT_FIELD(u16_t router_lifetime); - PACK_STRUCT_FIELD(u32_t reachable_time); - PACK_STRUCT_FIELD(u32_t retrans_timer); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Redirect message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct redirect_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u32_t reserved); - PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); - PACK_STRUCT_FLD_S(ip6_addr_p_t destination_address); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Link-layer address option. */ -#define ND6_OPTION_TYPE_SOURCE_LLADDR (0x01) -#define ND6_OPTION_TYPE_TARGET_LLADDR (0x02) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct lladdr_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FLD_8(u8_t addr[NETIF_MAX_HWADDR_LEN]); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Prefix information option. */ -#define ND6_OPTION_TYPE_PREFIX_INFO (0x03) -#define ND6_PREFIX_FLAG_ON_LINK (0x80) -#define ND6_PREFIX_FLAG_AUTONOMOUS (0x40) -#define ND6_PREFIX_FLAG_ROUTER_ADDRESS (0x20) -#define ND6_PREFIX_FLAG_SITE_PREFIX (0x10) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct prefix_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FLD_8(u8_t prefix_length); - PACK_STRUCT_FLD_8(u8_t flags); - PACK_STRUCT_FIELD(u32_t valid_lifetime); - PACK_STRUCT_FIELD(u32_t preferred_lifetime); - PACK_STRUCT_FLD_8(u8_t reserved2[3]); - PACK_STRUCT_FLD_8(u8_t site_prefix_length); - PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Redirected header option. */ -#define ND6_OPTION_TYPE_REDIR_HDR (0x04) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct redirected_header_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FLD_8(u8_t reserved[6]); - /* Portion of redirected packet follows. */ - /* PACK_STRUCT_FLD_8(u8_t redirected[8]); */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** MTU option. */ -#define ND6_OPTION_TYPE_MTU (0x05) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct mtu_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FIELD(u16_t reserved); - PACK_STRUCT_FIELD(u32_t mtu); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Route information option. */ -#define ND6_OPTION_TYPE_ROUTE_INFO (24) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct route_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FLD_8(u8_t prefix_length); - PACK_STRUCT_FLD_8(u8_t preference); - PACK_STRUCT_FIELD(u32_t route_lifetime); - PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - /** 1 second period */ #define ND6_TMR_INTERVAL 1000 -/* Router tables. */ -/* TODO make these static? and entries accessible through API? */ -extern struct nd6_neighbor_cache_entry neighbor_cache[]; -extern struct nd6_destination_cache_entry destination_cache[]; -extern struct nd6_prefix_list_entry prefix_list[]; -extern struct nd6_router_list_entry default_router_list[]; - -/* Default values, can be updated by a RA message. */ -extern u32_t reachable_time; -extern u32_t retrans_timer; +struct pbuf; +struct netif; void nd6_tmr(void); void nd6_input(struct pbuf *p, struct netif *inp); -s8_t nd6_get_next_hop_entry(const ip6_addr_t * ip6addr, struct netif * netif); -s8_t nd6_select_router(const ip6_addr_t * ip6addr, struct netif * netif); -u16_t nd6_get_destination_mtu(const ip6_addr_t * ip6addr, struct netif * netif); -err_t nd6_queue_packet(s8_t neighbor_index, struct pbuf * p); +void nd6_clear_destination_cache(void); +struct netif *nd6_find_route(const ip6_addr_t *ip6addr); +err_t nd6_get_next_hop_addr_or_queue(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr, const u8_t **hwaddrp); +u16_t nd6_get_destination_mtu(const ip6_addr_t *ip6addr, struct netif *netif); #if LWIP_ND6_TCP_REACHABILITY_HINTS -void nd6_reachability_hint(const ip6_addr_t * ip6addr); +void nd6_reachability_hint(const ip6_addr_t *ip6addr); #endif /* LWIP_ND6_TCP_REACHABILITY_HINTS */ +void nd6_cleanup_netif(struct netif *netif); +#if LWIP_IPV6_MLD +void nd6_adjust_mld_membership(struct netif *netif, s8_t addr_idx, u8_t new_state); +#endif /* LWIP_IPV6_MLD */ #if ESP_LWIP /** set nd6 callback when ipv6 addr state pref*/ void nd6_set_cb(struct netif *netif, void (*cb)(struct netif *netif, u8_t ip_index)); #endif + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/netbuf.h b/tools/sdk/include/lwip/lwip/netbuf.h old mode 100755 new mode 100644 index 8875e12d8e6..e6865f80f94 --- a/tools/sdk/include/lwip/lwip/netbuf.h +++ b/tools/sdk/include/lwip/lwip/netbuf.h @@ -1,3 +1,8 @@ +/** + * @file + * netbuf API (for netconn API) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -51,6 +56,7 @@ extern "C" { /** This netbuf includes a checksum */ #define NETBUF_FLAG_CHKSUM 0x02 +/** "Network buffer" - contains data and addressing info */ struct netbuf { struct pbuf *p, *ptr; ip_addr_t addr; diff --git a/tools/sdk/include/lwip/lwip/netdb.h b/tools/sdk/include/lwip/lwip/netdb.h old mode 100755 new mode 100644 index 144a6e0bd49..e0b07accc9d --- a/tools/sdk/include/lwip/lwip/netdb.h +++ b/tools/sdk/include/lwip/lwip/netdb.h @@ -1,3 +1,8 @@ +/** + * @file + * NETDB API (sockets) + */ + /* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -33,8 +38,7 @@ #if LWIP_DNS && LWIP_SOCKET -#include /* for size_t */ - +#include "lwip/arch.h" #include "lwip/inet.h" #include "lwip/sockets.h" @@ -125,12 +129,47 @@ int lwip_getaddrinfo(const char *nodename, struct addrinfo **res); #if LWIP_COMPAT_SOCKETS +#if ESP_LWIP +#if LWIP_COMPAT_SOCKET_ADDR == 1 +/* Some libraries have problems with inet_... being macros, so please use this define + to declare normal functions */ +static inline int gethostbyname_r(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop) +{ return lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop); } +static inline struct hostent *gethostbyname(const char *name) +{ return lwip_gethostbyname(name); } +static inline void freeaddrinfo(struct addrinfo *ai) +{ lwip_freeaddrinfo(ai); } +static inline int getaddrinfo(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res) +{ return lwip_getaddrinfo(nodename, servname, hints, res); } +#else +/* By default fall back to original inet_... macros */ + +/** @ingroup netdbapi */ +#define gethostbyname(name) lwip_gethostbyname(name) +/** @ingroup netdbapi */ +#define gethostbyname_r(name, ret, buf, buflen, result, h_errnop) \ + lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop) +/** @ingroup netdbapi */ +#define freeaddrinfo(addrinfo) lwip_freeaddrinfo(addrinfo) +/** @ingroup netdbapi */ +#define getaddrinfo(nodname, servname, hints, res) \ + lwip_getaddrinfo(nodname, servname, hints, res) +#endif /* LWIP_COMPAT_SOCKET_ADDR == 1 */ + +#else /* ESP_LWIP */ + +/** @ingroup netdbapi */ #define gethostbyname(name) lwip_gethostbyname(name) +/** @ingroup netdbapi */ #define gethostbyname_r(name, ret, buf, buflen, result, h_errnop) \ lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop) +/** @ingroup netdbapi */ #define freeaddrinfo(addrinfo) lwip_freeaddrinfo(addrinfo) +/** @ingroup netdbapi */ #define getaddrinfo(nodname, servname, hints, res) \ lwip_getaddrinfo(nodname, servname, hints, res) + +#endif /* ESP_LWIP */ #endif /* LWIP_COMPAT_SOCKETS */ #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/lwip/netif.h b/tools/sdk/include/lwip/lwip/netif.h old mode 100755 new mode 100644 index bd25b821734..bcc9c5b1d0b --- a/tools/sdk/include/lwip/lwip/netif.h +++ b/tools/sdk/include/lwip/lwip/netif.h @@ -1,3 +1,8 @@ +/** + * @file + * netif API (to be used from TCPIP thread) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -44,16 +49,6 @@ #include "lwip/pbuf.h" #include "lwip/stats.h" -#if LWIP_DHCP -struct dhcp; -#endif -#if LWIP_AUTOIP -struct autoip; -#endif -#if LWIP_IPV6_DHCP6 -struct dhcp6; -#endif /* LWIP_IPV6_DHCP6 */ - #ifdef __cplusplus extern "C" { #endif @@ -68,6 +63,12 @@ extern "C" { #define NETIF_MAX_HWADDR_LEN 6U #endif +/** + * @defgroup netif_flags Flags + * @ingroup netif + * @{ + */ + /** Whether the network interface is 'up'. This is * a software flag used to control whether this network * interface is enabled and processes traffic. @@ -99,6 +100,32 @@ extern "C" { * Set by the netif driver in its init function. */ #define NETIF_FLAG_MLD6 0x40U +#if ESP_GRATUITOUS_ARP +/** If set, the netif will send gratuitous ARP periodically */ +#define NETIF_FLAG_GARP 0x80U +#endif + +/** + * @} + */ + +enum lwip_internal_netif_client_data_index +{ +#if LWIP_DHCP + LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, +#endif +#if LWIP_AUTOIP + LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP, +#endif +#if LWIP_IGMP + LWIP_NETIF_CLIENT_DATA_INDEX_IGMP, +#endif +#if LWIP_IPV6_MLD + LWIP_NETIF_CLIENT_DATA_INDEX_MLD6, +#endif + LWIP_NETIF_CLIENT_DATA_INDEX_MAX +}; + #if LWIP_CHECKSUM_CTRL_PER_NETIF #define NETIF_CHECKSUM_GEN_IP 0x0001 #define NETIF_CHECKSUM_GEN_UDP 0x0002 @@ -116,6 +143,15 @@ extern "C" { struct netif; +/** MAC Filter Actions, these are passed to a netif's igmp_mac_filter or + * mld_mac_filter callback function. */ +enum netif_mac_filter_action { + /** Delete a filter entry */ + NETIF_DEL_MAC_FILTER = 0, + /** Add a filter entry */ + NETIF_ADD_MAC_FILTER = 1 +}; + /** Function prototype for netif init functions. Set up flags and output/linkoutput * callback functions in this function. * @@ -168,21 +204,31 @@ typedef void (*netif_status_callback_fn)(struct netif *netif); #if LWIP_IPV4 && LWIP_IGMP /** Function prototype for netif igmp_mac_filter functions */ typedef err_t (*netif_igmp_mac_filter_fn)(struct netif *netif, - const ip4_addr_t *group, u8_t action); + const ip4_addr_t *group, enum netif_mac_filter_action action); #endif /* LWIP_IPV4 && LWIP_IGMP */ #if LWIP_IPV6 && LWIP_IPV6_MLD /** Function prototype for netif mld_mac_filter functions */ typedef err_t (*netif_mld_mac_filter_fn)(struct netif *netif, - const ip6_addr_t *group, u8_t action); + const ip6_addr_t *group, enum netif_mac_filter_action action); #endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ +#if LWIP_DHCP || LWIP_AUTOIP || LWIP_IGMP || LWIP_IPV6_MLD || (LWIP_NUM_NETIF_CLIENT_DATA > 0) +u8_t netif_alloc_client_data_id(void); +/** @ingroup netif_cd + * Set client data. Obtain ID from netif_alloc_client_data_id(). + */ +#define netif_set_client_data(netif, id, data) netif_get_client_data(netif, id) = (data) +/** @ingroup netif_cd + * Get client data. Obtain ID from netif_alloc_client_data_id(). + */ +#define netif_get_client_data(netif, id) (netif)->client_data[(id)] +#endif /* LWIP_DHCP || LWIP_AUTOIP || (LWIP_NUM_NETIF_CLIENT_DATA > 0) */ #if ESP_DHCP /*add DHCP event processing by LiuHan*/ typedef void (*dhcp_event_fn)(void); #endif - /** Generic data structure used for all lwIP network interfaces. * The following fields should be filled in by the initialization * function for the device driver: hwaddr_len, hwaddr[], mtu, flags */ @@ -213,17 +259,19 @@ struct netif { #if LWIP_IPV4 /** This function is called by the IP module when it wants * to send a packet on the interface. This function typically - * first resolves the hardware address, then sends the packet. */ + * first resolves the hardware address, then sends the packet. + * For ethernet physical layer, this is usually etharp_output() */ netif_output_fn output; #endif /* LWIP_IPV4 */ - /** This function is called by the ARP module when it wants + /** This function is called by ethernet_output() when it wants * to send a packet on the interface. This function outputs * the pbuf as-is on the link medium. */ netif_linkoutput_fn linkoutput; #if LWIP_IPV6 /** This function is called by the IPv6 module when it wants * to send a packet on the interface. This function typically - * first resolves the hardware address, then sends the packet. */ + * first resolves the hardware address, then sends the packet. + * For ethernet physical layer, this is usually ethip6_output() */ netif_output_ip6_fn output_ip6; #endif /* LWIP_IPV6 */ #if LWIP_NETIF_STATUS_CALLBACK @@ -243,59 +291,42 @@ struct netif { /** This field can be set by the device driver and could point * to state information for the device. */ void *state; -#if LWIP_DHCP - /** the DHCP client state information for this netif */ - struct dhcp *dhcp; +#ifdef netif_get_client_data + void* client_data[LWIP_NETIF_CLIENT_DATA_INDEX_MAX + LWIP_NUM_NETIF_CLIENT_DATA]; +#endif -#if ESP_LWIP +#if ESP_DHCP struct udp_pcb *dhcps_pcb; dhcp_event_fn dhcp_event; -#endif - -#endif /* LWIP_DHCP */ - -#if LWIP_AUTOIP - /** the AutoIP client state information for this netif */ - struct autoip *autoip; #endif #if LWIP_IPV6_AUTOCONFIG /** is this netif enabled for IPv6 autoconfiguration */ u8_t ip6_autoconfig_enabled; #endif /* LWIP_IPV6_AUTOCONFIG */ - #if LWIP_IPV6_SEND_ROUTER_SOLICIT /** Number of Router Solicitation messages that remain to be sent. */ u8_t rs_count; #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */ - -#if LWIP_IPV6_DHCP6 - /** the DHCPv6 client state information for this netif */ - struct dhcp6 *dhcp6; -#endif /* LWIP_IPV6_DHCP6 */ - #if LWIP_NETIF_HOSTNAME /* the hostname for this netif, NULL is a valid value */ const char* hostname; #endif /* LWIP_NETIF_HOSTNAME */ - #if LWIP_CHECKSUM_CTRL_PER_NETIF u16_t chksum_flags; #endif /* LWIP_CHECKSUM_CTRL_PER_NETIF*/ - /** maximum transfer unit (in bytes) */ u16_t mtu; /** number of bytes used in hwaddr */ u8_t hwaddr_len; /** link level hardware address of this interface */ u8_t hwaddr[NETIF_MAX_HWADDR_LEN]; - /** flags (see NETIF_FLAG_ above) */ + /** flags (@see @ref netif_flags) */ u8_t flags; /** descriptive abbreviation */ char name[2]; /** number of this interface */ u8_t num; - #if MIB2_STATS /** link type (from "snmp_ifType" enum from snmp_mib2.h) */ u8_t link_type; @@ -306,19 +337,16 @@ struct netif { /** counters */ struct stats_mib2_netif_ctrs mib2_counters; #endif /* MIB2_STATS */ - #if LWIP_IPV4 && LWIP_IGMP /** This function could be called to add or delete an entry in the multicast filter table of the ethernet MAC.*/ netif_igmp_mac_filter_fn igmp_mac_filter; #endif /* LWIP_IPV4 && LWIP_IGMP */ - #if LWIP_IPV6 && LWIP_IPV6_MLD /** This function could be called to add or delete an entry in the IPv6 multicast filter table of the ethernet MAC. */ netif_mld_mac_filter_fn mld_mac_filter; #endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ - #if LWIP_NETIF_HWADDRHINT u8_t *addr_hint; #endif /* LWIP_NETIF_HWADDRHINT */ @@ -362,6 +390,11 @@ struct netif *netif_add(struct netif *netif, void netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw); #endif /* LWIP_IPV4 */ + +#if ESP_GRATUITOUS_ARP +void netif_set_garp_flag(struct netif *netif); +#endif + void netif_remove(struct netif * netif); /* Returns a network interface given its name. The name is of the form @@ -376,17 +409,30 @@ void netif_set_default(struct netif *netif); void netif_set_ipaddr(struct netif *netif, const ip4_addr_t *ipaddr); void netif_set_netmask(struct netif *netif, const ip4_addr_t *netmask); void netif_set_gw(struct netif *netif, const ip4_addr_t *gw); +/** @ingroup netif_ip4 */ #define netif_ip4_addr(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->ip_addr))) +/** @ingroup netif_ip4 */ #define netif_ip4_netmask(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->netmask))) +/** @ingroup netif_ip4 */ #define netif_ip4_gw(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->gw))) +/** @ingroup netif_ip4 */ #define netif_ip_addr4(netif) ((const ip_addr_t*)&((netif)->ip_addr)) +/** @ingroup netif_ip4 */ +#define netif_ip_netmask4(netif) ((const ip_addr_t*)&((netif)->netmask)) +/** @ingroup netif_ip4 */ #define netif_ip_gw4(netif) ((const ip_addr_t*)&((netif)->gw)) #endif /* LWIP_IPV4 */ void netif_set_up(struct netif *netif); void netif_set_down(struct netif *netif); -/** Ask if an interface is up */ +/** @ingroup netif + * Ask if an interface is up + */ +#if ESP_LWIP #define netif_is_up(netif) ( ((netif) && ((netif)->flags & NETIF_FLAG_UP)) ? (u8_t)1 : (u8_t)0) +#else +#define netif_is_up(netif) (((netif)->flags & NETIF_FLAG_UP) ? (u8_t)1 : (u8_t)0) +#endif #if LWIP_NETIF_STATUS_CALLBACK void netif_set_status_callback(struct netif *netif, netif_status_callback_fn status_callback); @@ -405,18 +451,23 @@ void netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_ #endif /* LWIP_NETIF_LINK_CALLBACK */ #if LWIP_NETIF_HOSTNAME +/** @ingroup netif */ #define netif_set_hostname(netif, name) do { if((netif) != NULL) { (netif)->hostname = name; }}while(0) +/** @ingroup netif */ #define netif_get_hostname(netif) (((netif) != NULL) ? ((netif)->hostname) : NULL) #endif /* LWIP_NETIF_HOSTNAME */ #if LWIP_IGMP +/** @ingroup netif */ #define netif_set_igmp_mac_filter(netif, function) do { if((netif) != NULL) { (netif)->igmp_mac_filter = function; }}while(0) #define netif_get_igmp_mac_filter(netif) (((netif) != NULL) ? ((netif)->igmp_mac_filter) : NULL) #endif /* LWIP_IGMP */ #if LWIP_IPV6 && LWIP_IPV6_MLD +/** @ingroup netif */ #define netif_set_mld_mac_filter(netif, function) do { if((netif) != NULL) { (netif)->mld_mac_filter = function; }}while(0) #define netif_get_mld_mac_filter(netif) (((netif) != NULL) ? ((netif)->mld_mac_filter) : NULL) +#define netif_mld_mac_filter(netif, addr, action) do { if((netif) && (netif)->mld_mac_filter) { (netif)->mld_mac_filter((netif), (addr), (action)); }}while(0) #endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ #if ENABLE_LOOPBACK @@ -427,15 +478,21 @@ void netif_poll_all(void); #endif /* !LWIP_NETIF_LOOPBACK_MULTITHREADING */ #endif /* ENABLE_LOOPBACK */ +err_t netif_input(struct pbuf *p, struct netif *inp); + #if LWIP_IPV6 +/** @ingroup netif_ip6 */ #define netif_ip_addr6(netif, i) ((const ip_addr_t*)(&((netif)->ip6_addr[i]))) +/** @ingroup netif_ip6 */ #define netif_ip6_addr(netif, i) ((const ip6_addr_t*)ip_2_ip6(&((netif)->ip6_addr[i]))) -#define netif_ip6_addr_set(netif, i, addr6) do { ip6_addr_set(ip_2_ip6(&((netif)->ip6_addr[i])), addr6); IP_SET_TYPE_VAL((netif)->ip6_addr[i], IPADDR_TYPE_V6); } while(0) +void netif_ip6_addr_set(struct netif *netif, s8_t addr_idx, const ip6_addr_t *addr6); +void netif_ip6_addr_set_parts(struct netif *netif, s8_t addr_idx, u32_t i0, u32_t i1, u32_t i2, u32_t i3); #define netif_ip6_addr_state(netif, i) ((netif)->ip6_addr_state[i]) -#define netif_ip6_addr_set_state(netif, i, state) ((netif)->ip6_addr_state[i] = (state)) +void netif_ip6_addr_set_state(struct netif* netif, s8_t addr_idx, u8_t state); s8_t netif_get_ip6_addr_match(struct netif *netif, const ip6_addr_t *ip6addr); void netif_create_ip6_linklocal_address(struct netif *netif, u8_t from_mac_48bit); err_t netif_add_ip6_address(struct netif *netif, const ip6_addr_t *ip6addr, s8_t *chosen_idx); +#define netif_set_ip6_autoconfig_enabled(netif, action) do { if(netif) { (netif)->ip6_autoconfig_enabled = (action); }}while(0) #endif /* LWIP_IPV6 */ #if LWIP_NETIF_HWADDRHINT diff --git a/tools/sdk/include/lwip/lwip/netifapi.h b/tools/sdk/include/lwip/lwip/netifapi.h old mode 100755 new mode 100644 index b09316be667..8bd2b4f76f7 --- a/tools/sdk/include/lwip/lwip/netifapi.h +++ b/tools/sdk/include/lwip/lwip/netifapi.h @@ -1,3 +1,8 @@ +/** + * @file + * netif API (to be used from non-TCPIP threads) + */ + /* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -51,7 +56,7 @@ typedef void (*netifapi_void_fn)(struct netif *netif); typedef err_t (*netifapi_errt_fn)(struct netif *netif); struct netifapi_msg { - struct tcpip_api_call call; + struct tcpip_api_call_data call; struct netif *netif; union { struct { @@ -87,16 +92,43 @@ err_t netifapi_netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, err_t netifapi_netif_common(struct netif *netif, netifapi_void_fn voidfunc, netifapi_errt_fn errtfunc); -#define netifapi_netif_remove(n) netifapi_netif_common(n, netif_remove, NULL) -#define netifapi_netif_set_up(n) netifapi_netif_common(n, netif_set_up, NULL) -#define netifapi_netif_set_down(n) netifapi_netif_common(n, netif_set_down, NULL) -#define netifapi_netif_set_default(n) netifapi_netif_common(n, netif_set_default, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_remove(n) netifapi_netif_common(n, netif_remove, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_up(n) netifapi_netif_common(n, netif_set_up, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_down(n) netifapi_netif_common(n, netif_set_down, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_default(n) netifapi_netif_common(n, netif_set_default, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_link_up(n) netifapi_netif_common(n, netif_set_link_up, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_link_down(n) netifapi_netif_common(n, netif_set_link_down, NULL) + +/** + * @defgroup netifapi_dhcp4 DHCPv4 + * @ingroup netifapi + * To be called from non-TCPIP threads + */ +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_start(n) netifapi_netif_common(n, NULL, dhcp_start) +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_stop(n) netifapi_netif_common(n, dhcp_stop, NULL) +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_inform(n) netifapi_netif_common(n, dhcp_inform, NULL) +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_renew(n) netifapi_netif_common(n, NULL, dhcp_renew) +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_release(n) netifapi_netif_common(n, NULL, dhcp_release) + +/** + * @defgroup netifapi_autoip AUTOIP + * @ingroup netifapi + * To be called from non-TCPIP threads + */ +/** @ingroup netifapi_autoip */ #define netifapi_autoip_start(n) netifapi_netif_common(n, NULL, autoip_start) +/** @ingroup netifapi_autoip */ #define netifapi_autoip_stop(n) netifapi_netif_common(n, NULL, autoip_stop) #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/lwip/opt.h b/tools/sdk/include/lwip/lwip/opt.h old mode 100755 new mode 100644 index 6ea556ac11d..f15aa7b6887 --- a/tools/sdk/include/lwip/lwip/opt.h +++ b/tools/sdk/include/lwip/lwip/opt.h @@ -35,7 +35,13 @@ * Author: Adam Dunkels * */ -#ifndef LWIP_HDR_OPT_H + +/* + * NOTE: || defined __DOXYGEN__ is a workaround for doxygen bug - + * without this, doxygen does not see the actual #define + */ + +#if !defined LWIP_HDR_OPT_H #define LWIP_HDR_OPT_H /* @@ -45,42 +51,89 @@ #include "lwipopts.h" #include "lwip/debug.h" -/* - ----------------------------------------------- - ---------- Platform specific locking ---------- - ----------------------------------------------- -*/ +/** + * @defgroup lwip_opts Options (lwipopts.h) + * @ingroup lwip + * + * @defgroup lwip_opts_debug Debugging + * @ingroup lwip_opts + * + * @defgroup lwip_opts_infrastructure Infrastructure + * @ingroup lwip_opts + * + * @defgroup lwip_opts_callback Callback-style APIs + * @ingroup lwip_opts + * + * @defgroup lwip_opts_threadsafe_apis Thread-safe APIs + * @ingroup lwip_opts + */ + /* + ------------------------------------ + -------------- NO SYS -------------- + ------------------------------------ +*/ +/** + * @defgroup lwip_opts_nosys NO_SYS + * @ingroup lwip_opts_infrastructure + * @{ + */ /** - * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain - * critical regions during buffer allocation, deallocation and memory - * allocation and deallocation. + * NO_SYS==1: Use lwIP without OS-awareness (no thread, semaphores, mutexes or + * mboxes). This means threaded APIs cannot be used (socket, netconn, + * i.e. everything in the 'api' folder), only the callback-style raw API is + * available (and you have to watch out for yourself that you don't access + * lwIP functions/structures from more than one context at a time!) */ -#ifndef SYS_LIGHTWEIGHT_PROT -#define SYS_LIGHTWEIGHT_PROT 0 +#if !defined NO_SYS || defined __DOXYGEN__ +#define NO_SYS 0 #endif +/** + * @} + */ /** - * NO_SYS==1: Provides VERY minimal functionality. Otherwise, - * use lwIP facilities. + * @defgroup lwip_opts_timers Timers + * @ingroup lwip_opts_infrastructure + * @{ */ -#ifndef NO_SYS -#define NO_SYS 0 +/** + * LWIP_TIMERS==0: Drop support for sys_timeout and lwip-internal cyclic timers. + * (the array of lwip-internal cyclic timers is still provided) + * (check NO_SYS_NO_TIMERS for compatibility to old versions) + */ +#if !defined LWIP_TIMERS || defined __DOXYGEN__ +#ifdef NO_SYS_NO_TIMERS +#define LWIP_TIMERS (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) +#else +#define LWIP_TIMERS 1 +#endif #endif /** - * NO_SYS_NO_TIMERS==1: Drop support for sys_timeout when NO_SYS==1 - * Mainly for compatibility to old versions. + * LWIP_TIMERS_CUSTOM==1: Provide your own timer implementation. + * Function prototypes in timeouts.h and the array of lwip-internal cyclic timers + * are still included, but the implementation is not. The following functions + * will be required: sys_timeouts_init(), sys_timeout(), sys_untimeout(), + * sys_timeouts_mbox_fetch() */ -#ifndef NO_SYS_NO_TIMERS -#define NO_SYS_NO_TIMERS 0 +#if !defined LWIP_TIMERS_CUSTOM || defined __DOXYGEN__ +#define LWIP_TIMERS_CUSTOM 0 #endif +/** + * @} + */ +/** + * @defgroup lwip_opts_memcpy memcpy + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * MEMCPY: override this if you have a faster implementation at hand than the * one included in your C library */ -#ifndef MEMCPY +#if !defined MEMCPY || defined __DOXYGEN__ #define MEMCPY(dst,src,len) memcpy(dst,src,len) #endif @@ -88,49 +141,110 @@ * SMEMCPY: override this with care! Some compilers (e.g. gcc) can inline a * call to memcpy() if the length is known at compile time and is small. */ -#ifndef SMEMCPY +#if !defined SMEMCPY || defined __DOXYGEN__ #define SMEMCPY(dst,src,len) memcpy(dst,src,len) #endif +/** + * @} + */ +/* + ------------------------------------ + ----------- Core locking ----------- + ------------------------------------ +*/ +/** + * @defgroup lwip_opts_lock Core locking and MPU + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * LWIP_MPU_COMPATIBLE: enables special memory management mechanism * which makes lwip able to work on MPU (Memory Protection Unit) system * by not passing stack-pointers to other threads - * (this decreases performance) + * (this decreases performance as memory is allocated from pools instead + * of keeping it on the stack) */ -#ifndef LWIP_MPU_COMPATIBLE +#if !defined LWIP_MPU_COMPATIBLE || defined __DOXYGEN__ #define LWIP_MPU_COMPATIBLE 0 #endif +/** + * LWIP_TCPIP_CORE_LOCKING + * Creates a global mutex that is held during TCPIP thread operations. + * Can be locked by client code to perform lwIP operations without changing + * into TCPIP thread using callbacks. See LOCK_TCPIP_CORE() and + * UNLOCK_TCPIP_CORE(). + * Your system should provide mutexes supporting priority inversion to use this. + */ +#if !defined LWIP_TCPIP_CORE_LOCKING || defined __DOXYGEN__ +#define LWIP_TCPIP_CORE_LOCKING 1 +#endif + +/** + * LWIP_TCPIP_CORE_LOCKING_INPUT: when LWIP_TCPIP_CORE_LOCKING is enabled, + * this lets tcpip_input() grab the mutex for input packets as well, + * instead of allocating a message and passing it to tcpip_thread. + * + * ATTENTION: this does not work when tcpip_input() is called from + * interrupt context! + */ +#if !defined LWIP_TCPIP_CORE_LOCKING_INPUT || defined __DOXYGEN__ +#define LWIP_TCPIP_CORE_LOCKING_INPUT 0 +#endif + +/** + * SYS_LIGHTWEIGHT_PROT==1: enable inter-task protection (and task-vs-interrupt + * protection) for certain critical regions during buffer allocation, deallocation + * and memory allocation and deallocation. + * ATTENTION: This is required when using lwIP from more than one context! If + * you disable this, you must be sure what you are doing! + */ +#if !defined SYS_LIGHTWEIGHT_PROT || defined __DOXYGEN__ +#define SYS_LIGHTWEIGHT_PROT 1 +#endif +/** + * @} + */ + /* ------------------------------------ ---------- Memory options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_mem Heap and memory pools + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library * instead of the lwip internal allocator. Can save code size if you * already use it. */ -#ifndef MEM_LIBC_MALLOC +#if !defined MEM_LIBC_MALLOC || defined __DOXYGEN__ #define MEM_LIBC_MALLOC 0 #endif /** -* MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator. -* Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution -* speed and usage from interrupts! -*/ -#ifndef MEMP_MEM_MALLOC + * MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator. + * Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution + * speed (heap alloc can be much slower than pool alloc) and usage from interrupts + * (especially if your netif driver allocates PBUF_POOL pbufs for received frames + * from interrupt)! + * ATTENTION: Currently, this uses the heap for ALL pools (also for private pools, + * not only for internal pools defined in memp_std.h)! + */ +#if !defined MEMP_MEM_MALLOC || defined __DOXYGEN__ #define MEMP_MEM_MALLOC 0 #endif /** * MEM_ALIGNMENT: should be set to the alignment of the CPU - * 4 byte alignment -> #define MEM_ALIGNMENT 4 - * 2 byte alignment -> #define MEM_ALIGNMENT 2 + * 4 byte alignment -> \#define MEM_ALIGNMENT 4 + * 2 byte alignment -> \#define MEM_ALIGNMENT 2 */ -#ifndef MEM_ALIGNMENT +#if !defined MEM_ALIGNMENT || defined __DOXYGEN__ #define MEM_ALIGNMENT 1 #endif @@ -138,7 +252,7 @@ * MEM_SIZE: the size of the heap memory. If the application will send * a lot of data that needs to be copied, this should be set high. */ -#ifndef MEM_SIZE +#if !defined MEM_SIZE || defined __DOXYGEN__ #define MEM_SIZE 1600 #endif @@ -151,7 +265,7 @@ * MEMP_OVERFLOW_CHECK >= 2 checks each element in every pool every time * memp_malloc() or memp_free() is called (useful but slow!) */ -#ifndef MEMP_OVERFLOW_CHECK +#if !defined MEMP_OVERFLOW_CHECK || defined __DOXYGEN__ #define MEMP_OVERFLOW_CHECK 0 #endif @@ -159,7 +273,7 @@ * MEMP_SANITY_CHECK==1: run a sanity check after each memp_free() to make * sure that there are no cycles in the linked lists. */ -#ifndef MEMP_SANITY_CHECK +#if !defined MEMP_SANITY_CHECK || defined __DOXYGEN__ #define MEMP_SANITY_CHECK 0 #endif @@ -169,7 +283,7 @@ * the smallest pool that can provide the length needed is returned. * To use this, MEMP_USE_CUSTOM_POOLS also has to be enabled. */ -#ifndef MEM_USE_POOLS +#if !defined MEM_USE_POOLS || defined __DOXYGEN__ #define MEM_USE_POOLS 0 #endif @@ -177,7 +291,7 @@ * MEM_USE_POOLS_TRY_BIGGER_POOL==1: if one malloc-pool is empty, try the next * bigger pool - WARNING: THIS MIGHT WASTE MEMORY but it can make a system more * reliable. */ -#ifndef MEM_USE_POOLS_TRY_BIGGER_POOL +#if !defined MEM_USE_POOLS_TRY_BIGGER_POOL || defined __DOXYGEN__ #define MEM_USE_POOLS_TRY_BIGGER_POOL 0 #endif @@ -187,7 +301,7 @@ * by lwIP. If you set this to 1, you must have lwippools.h in your * include path somewhere. */ -#ifndef MEMP_USE_CUSTOM_POOLS +#if !defined MEMP_USE_CUSTOM_POOLS || defined __DOXYGEN__ #define MEMP_USE_CUSTOM_POOLS 0 #endif @@ -209,21 +323,29 @@ * - pbuf_free_callback(p); * - mem_free_callback(m); */ -#ifndef LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT +#if !defined LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT || defined __DOXYGEN__ #define LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT 0 #endif +/** + * @} + */ /* ------------------------------------------------ ---------- Internal Memory Pool Sizes ---------- ------------------------------------------------ */ +/** + * @defgroup lwip_opts_memp Internal memory pools + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF). * If the application sends a lot of data out of ROM (or other static memory), * this should be set high. */ -#ifndef MEMP_NUM_PBUF +#if !defined MEMP_NUM_PBUF || defined __DOXYGEN__ #define MEMP_NUM_PBUF 16 #endif @@ -231,7 +353,7 @@ * MEMP_NUM_RAW_PCB: Number of raw connection PCBs * (requires the LWIP_RAW option) */ -#ifndef MEMP_NUM_RAW_PCB +#if !defined MEMP_NUM_RAW_PCB || defined __DOXYGEN__ #define MEMP_NUM_RAW_PCB 4 #endif @@ -240,7 +362,7 @@ * per active UDP "connection". * (requires the LWIP_UDP option) */ -#ifndef MEMP_NUM_UDP_PCB +#if !defined MEMP_NUM_UDP_PCB || defined __DOXYGEN__ #define MEMP_NUM_UDP_PCB 4 #endif @@ -248,7 +370,7 @@ * MEMP_NUM_TCP_PCB: the number of simultaneously active TCP connections. * (requires the LWIP_TCP option) */ -#ifndef MEMP_NUM_TCP_PCB +#if !defined MEMP_NUM_TCP_PCB || defined __DOXYGEN__ #define MEMP_NUM_TCP_PCB 5 #endif @@ -256,7 +378,7 @@ * MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. * (requires the LWIP_TCP option) */ -#ifndef MEMP_NUM_TCP_PCB_LISTEN +#if !defined MEMP_NUM_TCP_PCB_LISTEN || defined __DOXYGEN__ #define MEMP_NUM_TCP_PCB_LISTEN 8 #endif @@ -264,7 +386,7 @@ * MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. * (requires the LWIP_TCP option) */ -#ifndef MEMP_NUM_TCP_SEG +#if !defined MEMP_NUM_TCP_SEG || defined __DOXYGEN__ #define MEMP_NUM_TCP_SEG 16 #endif @@ -272,18 +394,18 @@ * MEMP_NUM_REASSDATA: the number of IP packets simultaneously queued for * reassembly (whole packets, not fragments!) */ -#ifndef MEMP_NUM_REASSDATA +#if !defined MEMP_NUM_REASSDATA || defined __DOXYGEN__ #define MEMP_NUM_REASSDATA 5 #endif /** * MEMP_NUM_FRAG_PBUF: the number of IP fragments simultaneously sent * (fragments, not whole packets!). - * This is only used with IP_FRAG_USES_STATIC_BUF==0 and - * LWIP_NETIF_TX_SINGLE_PBUF==0 and only has to be > 1 with DMA-enabled MACs - * where the packet is not yet sent when netif->output returns. + * This is only used with LWIP_NETIF_TX_SINGLE_PBUF==0 and only has to be > 1 + * with DMA-enabled MACs where the packet is not yet sent when netif->output + * returns. */ -#ifndef MEMP_NUM_FRAG_PBUF +#if !defined MEMP_NUM_FRAG_PBUF || defined __DOXYGEN__ #define MEMP_NUM_FRAG_PBUF 15 #endif @@ -293,7 +415,7 @@ * their destination address) to finish. * (requires the ARP_QUEUEING option) */ -#ifndef MEMP_NUM_ARP_QUEUE +#if !defined MEMP_NUM_ARP_QUEUE || defined __DOXYGEN__ #define MEMP_NUM_ARP_QUEUE 30 #endif @@ -303,7 +425,7 @@ * per netif membership). * (requires the LWIP_IGMP option) */ -#ifndef MEMP_NUM_IGMP_GROUP +#if !defined MEMP_NUM_IGMP_GROUP || defined __DOXYGEN__ #define MEMP_NUM_IGMP_GROUP 8 #endif @@ -312,15 +434,19 @@ * The default number of timeouts is calculated here for all enabled modules. * The formula expects settings to be either '0' or '1'. */ -#ifndef MEMP_NUM_SYS_TIMEOUT +#if !defined MEMP_NUM_SYS_TIMEOUT || defined __DOXYGEN__ +#if ESP_LWIP +#define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + (LWIP_ARP + (ESP_GRATUITOUS_ARP ? 1 : 0)) + (2*LWIP_DHCP + (ESP_DHCPS_TIMER ? 1 : 0)) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + (PPP_SUPPORT*6*MEMP_NUM_PPP_PCB) + (LWIP_IPV6 ? (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD) : 0)) +#else #define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + (PPP_SUPPORT*6*MEMP_NUM_PPP_PCB) + (LWIP_IPV6 ? (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD) : 0)) #endif +#endif /** * MEMP_NUM_NETBUF: the number of struct netbufs. * (only needed if you use the sequential API, like api_lib.c) */ -#ifndef MEMP_NUM_NETBUF +#if !defined MEMP_NUM_NETBUF || defined __DOXYGEN__ #define MEMP_NUM_NETBUF 2 #endif @@ -328,7 +454,7 @@ * MEMP_NUM_NETCONN: the number of struct netconns. * (only needed if you use the sequential API, like api_lib.c) */ -#ifndef MEMP_NUM_NETCONN +#if !defined MEMP_NUM_NETCONN || defined __DOXYGEN__ #define MEMP_NUM_NETCONN 4 #endif @@ -337,7 +463,7 @@ * for callback/timeout API communication. * (only needed if you use tcpip.c) */ -#ifndef MEMP_NUM_TCPIP_MSG_API +#if !defined MEMP_NUM_TCPIP_MSG_API || defined __DOXYGEN__ #define MEMP_NUM_TCPIP_MSG_API 8 #endif @@ -346,7 +472,7 @@ * for incoming packets. * (only needed if you use tcpip.c) */ -#ifndef MEMP_NUM_TCPIP_MSG_INPKT +#if !defined MEMP_NUM_TCPIP_MSG_INPKT || defined __DOXYGEN__ #define MEMP_NUM_TCPIP_MSG_INPKT 8 #endif @@ -354,7 +480,7 @@ * MEMP_NUM_NETDB: the number of concurrently running lwip_addrinfo() calls * (before freeing the corresponding memory using lwip_freeaddrinfo()). */ -#ifndef MEMP_NUM_NETDB +#if !defined MEMP_NUM_NETDB || defined __DOXYGEN__ #define MEMP_NUM_NETDB 1 #endif @@ -362,92 +488,68 @@ * MEMP_NUM_LOCALHOSTLIST: the number of host entries in the local host list * if DNS_LOCAL_HOSTLIST_IS_DYNAMIC==1. */ -#ifndef MEMP_NUM_LOCALHOSTLIST +#if !defined MEMP_NUM_LOCALHOSTLIST || defined __DOXYGEN__ #define MEMP_NUM_LOCALHOSTLIST 1 #endif -/** - * MEMP_NUM_PPP_PCB: the number of simultaneously active PPP - * connections (requires the PPP_SUPPORT option) - */ -#ifndef MEMP_NUM_PPP_PCB -#define MEMP_NUM_PPP_PCB 1 -#endif - -/** - * MEMP_NUM_PPPOS_INTERFACES: the number of concurrently active PPPoS - * interfaces (only used with PPPOS_SUPPORT==1) - */ -#ifndef MEMP_NUM_PPPOS_INTERFACES -#define MEMP_NUM_PPPOS_INTERFACES MEMP_NUM_PPP_PCB -#endif - -/** - * MEMP_NUM_PPPOE_INTERFACES: the number of concurrently active PPPoE - * interfaces (only used with PPPOE_SUPPORT==1) - */ -#ifndef MEMP_NUM_PPPOE_INTERFACES -#define MEMP_NUM_PPPOE_INTERFACES 1 -#endif - -/** - * MEMP_NUM_PPPOL2TP_INTERFACES: the number of concurrently active PPPoL2TP - * interfaces (only used with PPPOL2TP_SUPPORT==1) - */ -#ifndef MEMP_NUM_PPPOL2TP_INTERFACES -#define MEMP_NUM_PPPOL2TP_INTERFACES 1 -#endif - /** * PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ -#ifndef PBUF_POOL_SIZE +#if !defined PBUF_POOL_SIZE || defined __DOXYGEN__ #define PBUF_POOL_SIZE 16 #endif /** MEMP_NUM_API_MSG: the number of concurrently active calls to various * socket, netconn, and tcpip functions */ -#ifndef MEMP_NUM_API_MSG +#if !defined MEMP_NUM_API_MSG || defined __DOXYGEN__ #define MEMP_NUM_API_MSG MEMP_NUM_TCPIP_MSG_API #endif /** MEMP_NUM_DNS_API_MSG: the number of concurrently active calls to netconn_gethostbyname */ -#ifndef MEMP_NUM_DNS_API_MSG +#if !defined MEMP_NUM_DNS_API_MSG || defined __DOXYGEN__ #define MEMP_NUM_DNS_API_MSG MEMP_NUM_TCPIP_MSG_API #endif /** MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA: the number of concurrently active calls * to getsockopt/setsockopt */ -#ifndef MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA +#if !defined MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA || defined __DOXYGEN__ #define MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA MEMP_NUM_TCPIP_MSG_API #endif /** MEMP_NUM_NETIFAPI_MSG: the number of concurrently active calls to the * netifapi functions */ -#ifndef MEMP_NUM_NETIFAPI_MSG +#if !defined MEMP_NUM_NETIFAPI_MSG || defined __DOXYGEN__ #define MEMP_NUM_NETIFAPI_MSG MEMP_NUM_TCPIP_MSG_API #endif +/** + * @} + */ /* --------------------------------- ---------- ARP options ---------- --------------------------------- */ +/** + * @defgroup lwip_opts_arp ARP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_ARP==1: Enable ARP functionality. */ -#ifndef LWIP_ARP +#if !defined LWIP_ARP || defined __DOXYGEN__ #define LWIP_ARP 1 #endif /** * ARP_TABLE_SIZE: Number of active MAC-IP address pairs cached. */ -#ifndef ARP_TABLE_SIZE +#if !defined ARP_TABLE_SIZE || defined __DOXYGEN__ #define ARP_TABLE_SIZE 10 #endif @@ -455,7 +557,7 @@ * for ARP_TMR_INTERVAL = 1000, this is * (60 * 5) seconds = 5 minutes. */ -#ifndef ARP_MAXAGE +#if !defined ARP_MAXAGE || defined __DOXYGEN__ #define ARP_MAXAGE 300 #endif @@ -466,7 +568,7 @@ * startup time. Set this to 1 if you know your application sends more than one * packet in a row to an IP address that is not in the ARP cache. */ -#ifndef ARP_QUEUEING +#if !defined ARP_QUEUEING || defined __DOXYGEN__ #define ARP_QUEUEING 0 #endif @@ -474,24 +576,10 @@ * unresolved address by other network layers. Defaults to 3, 0 means disabled. * Old packets are dropped, new packets are queued. */ -#ifndef ARP_QUEUE_LEN +#if !defined ARP_QUEUE_LEN || defined __DOXYGEN__ #define ARP_QUEUE_LEN 3 #endif -/** - * ETHARP_TRUST_IP_MAC==1: Incoming IP packets cause the ARP table to be - * updated with the source MAC and IP addresses supplied in the packet. - * You may want to disable this if you do not trust LAN peers to have the - * correct addresses, or as a limited approach to attempt to handle - * spoofing. If disabled, lwIP will need to make a new ARP request if - * the peer is not already in the ARP table, adding a little latency. - * The peer *is* in the ARP table if it requested our address before. - * Also notice that this slows down input processing of every IP packet! - */ -#ifndef ETHARP_TRUST_IP_MAC -#define ETHARP_TRUST_IP_MAC 0 -#endif - /** * ETHARP_SUPPORT_VLAN==1: support receiving and sending ethernet packets with * VLAN header. See the description of LWIP_HOOK_VLAN_CHECK and @@ -502,15 +590,14 @@ * Alternatively, define a function/define ETHARP_VLAN_CHECK_FN(eth_hdr, vlan) * that returns 1 to accept a packet or 0 to drop a packet. */ -#ifndef ETHARP_SUPPORT_VLAN +#if !defined ETHARP_SUPPORT_VLAN || defined __DOXYGEN__ #define ETHARP_SUPPORT_VLAN 0 #endif -/** LWIP_ETHERNET==1: enable ethernet support for PPPoE even though ARP - * might be disabled +/** LWIP_ETHERNET==1: enable ethernet support even though ARP might be disabled */ -#ifndef LWIP_ETHERNET -#define LWIP_ETHERNET (LWIP_ARP || PPPOE_SUPPORT) +#if !defined LWIP_ETHERNET || defined __DOXYGEN__ +#define LWIP_ETHERNET LWIP_ARP #endif /** ETH_PAD_SIZE: number of bytes added before the ethernet header to ensure @@ -518,14 +605,14 @@ * without this padding e.g. addresses in the IP header will not be aligned * on a 32-bit boundary, so setting this to 2 can speed up 32-bit-platforms. */ -#ifndef ETH_PAD_SIZE +#if !defined ETH_PAD_SIZE || defined __DOXYGEN__ #define ETH_PAD_SIZE 0 #endif /** ETHARP_SUPPORT_STATIC_ENTRIES==1: enable code to support static ARP table * entries (using etharp_add_static_entry/etharp_remove_static_entry). */ -#ifndef ETHARP_SUPPORT_STATIC_ENTRIES +#if !defined ETHARP_SUPPORT_STATIC_ENTRIES || defined __DOXYGEN__ #define ETHARP_SUPPORT_STATIC_ENTRIES 0 #endif @@ -533,19 +620,27 @@ * If disabled, duplicate IP address on multiple netifs are not supported * (but this should only occur for AutoIP). */ -#ifndef ETHARP_TABLE_MATCH_NETIF +#if !defined ETHARP_TABLE_MATCH_NETIF || defined __DOXYGEN__ #define ETHARP_TABLE_MATCH_NETIF 0 #endif +/** + * @} + */ /* -------------------------------- ---------- IP options ---------- -------------------------------- */ +/** + * @defgroup lwip_opts_ipv4 IPv4 + * @ingroup lwip_opts + * @{ + */ /** * LWIP_IPV4==1: Enable IPv4 */ -#ifndef LWIP_IPV4 +#if !defined LWIP_IPV4 || defined __DOXYGEN__ #define LWIP_IPV4 1 #endif @@ -554,7 +649,7 @@ * interfaces. If you are going to run lwIP on a device with only one network * interface, define this to 0. */ -#ifndef IP_FORWARD +#if !defined IP_FORWARD || defined __DOXYGEN__ #define IP_FORWARD 0 #endif @@ -563,7 +658,7 @@ * this option does not affect outgoing packet sizes, which can be controlled * via IP_FRAG. */ -#ifndef IP_REASSEMBLY +#if !defined IP_REASSEMBLY || defined __DOXYGEN__ #define IP_REASSEMBLY 1 #endif @@ -572,7 +667,7 @@ * that this option does not affect incoming packet sizes, which can be * controlled via IP_REASSEMBLY. */ -#ifndef IP_FRAG +#if !defined IP_FRAG || defined __DOXYGEN__ #define IP_FRAG 1 #endif @@ -591,7 +686,7 @@ * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped. * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed). */ -#ifndef IP_OPTIONS_ALLOWED +#if !defined IP_OPTIONS_ALLOWED || defined __DOXYGEN__ #define IP_OPTIONS_ALLOWED 1 #endif @@ -600,7 +695,7 @@ * a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived * in this time, the whole packet is discarded. */ -#ifndef IP_REASS_MAXAGE +#if !defined IP_REASS_MAXAGE || defined __DOXYGEN__ #define IP_REASS_MAXAGE 3 #endif @@ -610,33 +705,14 @@ * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive * packets even if the maximum amount of fragments is enqueued for reassembly! */ -#ifndef IP_REASS_MAX_PBUFS +#if !defined IP_REASS_MAX_PBUFS || defined __DOXYGEN__ #define IP_REASS_MAX_PBUFS 10 #endif -/** - * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP - * fragmentation. Otherwise pbufs are allocated and reference the original - * packet data to be fragmented (or with LWIP_NETIF_TX_SINGLE_PBUF==1, - * new PBUF_RAM pbufs are used for fragments). - * ATTENTION: IP_FRAG_USES_STATIC_BUF==1 may not be used for DMA-enabled MACs! - */ -#ifndef IP_FRAG_USES_STATIC_BUF -#define IP_FRAG_USES_STATIC_BUF 0 -#endif - -/** - * IP_FRAG_MAX_MTU: Assumed max MTU on any interface for IP frag buffer - * (requires IP_FRAG_USES_STATIC_BUF==1) - */ -#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MAX_MTU) -#define IP_FRAG_MAX_MTU 1500 -#endif - /** * IP_DEFAULT_TTL: Default value for Time-To-Live used by transport layers. */ -#ifndef IP_DEFAULT_TTL +#if !defined IP_DEFAULT_TTL || defined __DOXYGEN__ #define IP_DEFAULT_TTL 255 #endif @@ -645,7 +721,7 @@ * filter per pcb on udp and raw send operations. To enable broadcast filter * on recv operations, you also have to set IP_SOF_BROADCAST_RECV=1. */ -#ifndef IP_SOF_BROADCAST +#if !defined IP_SOF_BROADCAST || defined __DOXYGEN__ #define IP_SOF_BROADCAST 0 #endif @@ -653,7 +729,7 @@ * IP_SOF_BROADCAST_RECV (requires IP_SOF_BROADCAST=1) enable the broadcast * filter on recv operations. */ -#ifndef IP_SOF_BROADCAST_RECV +#if !defined IP_SOF_BROADCAST_RECV || defined __DOXYGEN__ #define IP_SOF_BROADCAST_RECV 0 #endif @@ -664,7 +740,7 @@ * ATTENTION: When this is 1, make sure your netif driver correctly marks incoming * link-layer-broadcast/multicast packets as such using the corresponding pbuf flags! */ -#ifndef IP_FORWARD_ALLOW_TX_ON_RX_NETIF +#if !defined IP_FORWARD_ALLOW_TX_ON_RX_NETIF || defined __DOXYGEN__ #define IP_FORWARD_ALLOW_TX_ON_RX_NETIF 0 #endif @@ -673,72 +749,96 @@ * local TCP/UDP pcb (default==0). This can prevent creating predictable port * numbers after booting a device. */ -#ifndef LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS +#if !defined LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS || defined __DOXYGEN__ #define LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS 0 #endif +/** + * @} + */ /* ---------------------------------- ---------- ICMP options ---------- ---------------------------------- */ +/** + * @defgroup lwip_opts_icmp ICMP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_ICMP==1: Enable ICMP module inside the IP stack. * Be careful, disable that make your product non-compliant to RFC1122 */ -#ifndef LWIP_ICMP +#if !defined LWIP_ICMP || defined __DOXYGEN__ #define LWIP_ICMP 1 #endif /** * ICMP_TTL: Default value for Time-To-Live used by ICMP packets. */ -#ifndef ICMP_TTL +#if !defined ICMP_TTL || defined __DOXYGEN__ #define ICMP_TTL (IP_DEFAULT_TTL) #endif /** * LWIP_BROADCAST_PING==1: respond to broadcast pings (default is unicast only) */ -#ifndef LWIP_BROADCAST_PING +#if !defined LWIP_BROADCAST_PING || defined __DOXYGEN__ #define LWIP_BROADCAST_PING 0 #endif /** * LWIP_MULTICAST_PING==1: respond to multicast pings (default is unicast only) */ -#ifndef LWIP_MULTICAST_PING +#if !defined LWIP_MULTICAST_PING || defined __DOXYGEN__ #define LWIP_MULTICAST_PING 0 #endif +/** + * @} + */ /* --------------------------------- ---------- RAW options ---------- --------------------------------- */ +/** + * @defgroup lwip_opts_raw RAW + * @ingroup lwip_opts_callback + * @{ + */ /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ -#ifndef LWIP_RAW +#if !defined LWIP_RAW || defined __DOXYGEN__ #define LWIP_RAW 0 #endif /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ -#ifndef RAW_TTL +#if !defined RAW_TTL || defined __DOXYGEN__ #define RAW_TTL (IP_DEFAULT_TTL) #endif +/** + * @} + */ /* ---------------------------------- ---------- DHCP options ---------- ---------------------------------- */ +/** + * @defgroup lwip_opts_dhcp DHCP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_DHCP==1: Enable DHCP module. */ -#ifndef LWIP_DHCP +#if !defined LWIP_DHCP || defined __DOXYGEN__ #define LWIP_DHCP 0 #endif #if !LWIP_IPV4 @@ -750,7 +850,7 @@ /** * DHCP_DOES_ARP_CHECK==1: Do an ARP check on the offered address. */ -#ifndef DHCP_DOES_ARP_CHECK +#if !defined DHCP_DOES_ARP_CHECK || defined __DOXYGEN__ #define DHCP_DOES_ARP_CHECK ((LWIP_DHCP) && (LWIP_ARP)) #endif @@ -760,14 +860,14 @@ * netif drivers might not set this flag, the default is off. If enabled, * netif_set_link_up() must be called to continue dhcp starting. */ -#ifndef LWIP_DHCP_CHECK_LINK_UP +#if !defined LWIP_DHCP_CHECK_LINK_UP #define LWIP_DHCP_CHECK_LINK_UP 0 #endif /** * LWIP_DHCP_BOOTP_FILE==1: Store offered_si_addr and boot_file_name. */ -#ifndef LWIP_DHCP_BOOTP_FILE +#if !defined LWIP_DHCP_BOOTP_FILE || defined __DOXYGEN__ #define LWIP_DHCP_BOOTP_FILE 0 #endif @@ -776,26 +876,55 @@ * response packet, an callback is called, which has to be provided by the port: * void dhcp_set_ntp_servers(u8_t num_ntp_servers, ip_addr_t* ntp_server_addrs); */ -#ifndef LWIP_DHCP_GET_NTP_SRV +#if !defined LWIP_DHCP_GET_NTP_SRV || defined __DOXYGEN__ #define LWIP_DHCP_GET_NTP_SRV 0 #endif /** * The maximum of NTP servers requested */ -#ifndef LWIP_DHCP_MAX_NTP_SERVERS +#if !defined LWIP_DHCP_MAX_NTP_SERVERS || defined __DOXYGEN__ #define LWIP_DHCP_MAX_NTP_SERVERS 1 #endif +/** + * LWIP_DHCP_MAX_DNS_SERVERS > 0: Request DNS servers with discover/select. + * DHCP servers received in the response are passed to DNS via @ref dns_setserver() + * (up to the maximum limit defined here). + */ +#if !defined LWIP_DHCP_MAX_DNS_SERVERS || defined __DOXYGEN__ +#define LWIP_DHCP_MAX_DNS_SERVERS DNS_MAX_SERVERS +#endif +/** + * @} + */ + +#ifndef LWIP_DHCP_IP_ADDR_RESTORE +#define LWIP_DHCP_IP_ADDR_RESTORE() 0 +#endif + +#ifndef LWIP_DHCP_IP_ADDR_STORE +#define LWIP_DHCP_IP_ADDR_STORE() +#endif + +#ifndef LWIP_DHCP_IP_ADDR_ERASE +#define LWIP_DHCP_IP_ADDR_ERASE() +#endif + /* ------------------------------------ ---------- AUTOIP options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_autoip AUTOIP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_AUTOIP==1: Enable AUTOIP module. */ -#ifndef LWIP_AUTOIP +#if !defined LWIP_AUTOIP || defined __DOXYGEN__ #define LWIP_AUTOIP 0 #endif #if !LWIP_IPV4 @@ -808,61 +937,61 @@ * LWIP_DHCP_AUTOIP_COOP==1: Allow DHCP and AUTOIP to be both enabled on * the same interface at the same time. */ -#ifndef LWIP_DHCP_AUTOIP_COOP +#if !defined LWIP_DHCP_AUTOIP_COOP || defined __DOXYGEN__ #define LWIP_DHCP_AUTOIP_COOP 0 #endif /** * LWIP_DHCP_AUTOIP_COOP_TRIES: Set to the number of DHCP DISCOVER probes - * that should be sent before falling back on AUTOIP. This can be set - * as low as 1 to get an AutoIP address very quickly, but you should - * be prepared to handle a changing IP address when DHCP overrides - * AutoIP. + * that should be sent before falling back on AUTOIP (the DHCP client keeps + * running in this case). This can be set as low as 1 to get an AutoIP address + * very quickly, but you should be prepared to handle a changing IP address + * when DHCP overrides AutoIP. */ -#ifndef LWIP_DHCP_AUTOIP_COOP_TRIES +#if !defined LWIP_DHCP_AUTOIP_COOP_TRIES || defined __DOXYGEN__ #define LWIP_DHCP_AUTOIP_COOP_TRIES 9 #endif - -/** - * LWIP_AUTOIP_MAX_CONFLICTS: - * Maximum number of AutoIP IP conflicts before rate limiting is enabled. - */ -#ifndef LWIP_AUTOIP_MAX_CONFLICTS -#define LWIP_AUTOIP_MAX_CONFLICTS 10 -#endif - /** - * LWIP_AUTOIP_RATE_LIMIT_INTERVAL: - * Rate limited request interval, in seconds. + * @} */ -#ifndef LWIP_AUTOIP_RATE_LIMIT_INTERVAL -#define LWIP_AUTOIP_RATE_LIMIT_INTERVAL 60 -#endif /* ---------------------------------- ----- SNMP MIB2 support ----- ---------------------------------- */ +/** + * @defgroup lwip_opts_mib2 SNMP MIB2 callbacks + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * LWIP_MIB2_CALLBACKS==1: Turn on SNMP MIB2 callbacks. * Turn this on to get callbacks needed to implement MIB2. * Usually MIB2_STATS should be enabled, too. */ -#ifndef LWIP_MIB2_CALLBACKS +#if !defined LWIP_MIB2_CALLBACKS || defined __DOXYGEN__ #define LWIP_MIB2_CALLBACKS 0 #endif +/** + * @} + */ /* ---------------------------------- ----- Multicast/IGMP options ----- ---------------------------------- */ +/** + * @defgroup lwip_opts_igmp IGMP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_IGMP==1: Turn on IGMP module. */ -#ifndef LWIP_IGMP -#define LWIP_IGMP 1 +#if !defined LWIP_IGMP || defined __DOXYGEN__ +#define LWIP_IGMP 0 #endif #if !LWIP_IPV4 #undef LWIP_IGMP @@ -873,30 +1002,38 @@ * LWIP_MULTICAST_TX_OPTIONS==1: Enable multicast TX support like the socket options * IP_MULTICAST_TTL/IP_MULTICAST_IF/IP_MULTICAST_LOOP */ -#ifndef LWIP_MULTICAST_TX_OPTIONS -#define LWIP_MULTICAST_TX_OPTIONS LWIP_IGMP +#if !defined LWIP_MULTICAST_TX_OPTIONS || defined __DOXYGEN__ +#define LWIP_MULTICAST_TX_OPTIONS (LWIP_IGMP && LWIP_UDP) #endif +/** + * @} + */ /* ---------------------------------- ---------- DNS options ----------- ---------------------------------- */ +/** + * @defgroup lwip_opts_dns DNS + * @ingroup lwip_opts_callback + * @{ + */ /** * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS * transport. */ -#ifndef LWIP_DNS +#if !defined LWIP_DNS || defined __DOXYGEN__ #define LWIP_DNS 0 #endif /** DNS maximum number of entries to maintain locally. */ -#ifndef DNS_TABLE_SIZE +#if !defined DNS_TABLE_SIZE || defined __DOXYGEN__ #define DNS_TABLE_SIZE 4 #endif /** DNS maximum host name length supported in the name table. */ -#ifndef DNS_MAX_NAME_LENGTH +#if !defined DNS_MAX_NAME_LENGTH || defined __DOXYGEN__ #define DNS_MAX_NAME_LENGTH 256 #endif @@ -904,12 +1041,12 @@ * The first server can be initialized automatically by defining * DNS_SERVER_ADDRESS(ipaddr), where 'ipaddr' is an 'ip_addr_t*' */ -#ifndef DNS_MAX_SERVERS +#if !defined DNS_MAX_SERVERS || defined __DOXYGEN__ #define DNS_MAX_SERVERS 2 #endif /** DNS do a name checking between the query and the response. */ -#ifndef DNS_DOES_NAME_CHECK +#if !defined DNS_DOES_NAME_CHECK || defined __DOXYGEN__ #define DNS_DOES_NAME_CHECK 1 #endif @@ -917,105 +1054,129 @@ * Use all DNS security features by default. * This is overridable but should only be needed by very small targets * or when using against non standard DNS servers. */ -#ifndef LWIP_DNS_SECURE +#if !defined LWIP_DNS_SECURE || defined __DOXYGEN__ #define LWIP_DNS_SECURE (LWIP_DNS_SECURE_RAND_XID | LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT) #endif + /* A list of DNS security features follows */ #define LWIP_DNS_SECURE_RAND_XID 1 #define LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING 2 #define LWIP_DNS_SECURE_RAND_SRC_PORT 4 -/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, - * you have to define - * #define DNS_LOCAL_HOSTLIST_INIT {{"host1", 0x123}, {"host2", 0x234}} - * (an array of structs name/address, where address is an u32_t in network - * byte order). +/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, you have to define an initializer: + * \#define DNS_LOCAL_HOSTLIST_INIT {DNS_LOCAL_HOSTLIST_ELEM("host_ip4", IPADDR4_INIT_BYTES(1,2,3,4)), \ + * DNS_LOCAL_HOSTLIST_ELEM("host_ip6", IPADDR6_INIT_HOST(123, 234, 345, 456)} * * Instead, you can also use an external function: - * #define DNS_LOOKUP_LOCAL_EXTERN(x) extern u32_t my_lookup_function(const char *name) - * that returns the IP address or INADDR_NONE if not found. + * \#define DNS_LOOKUP_LOCAL_EXTERN(x) extern err_t my_lookup_function(const char *name, ip_addr_t *addr, u8_t dns_addrtype) + * that looks up the IP address and returns ERR_OK if found (LWIP_DNS_ADDRTYPE_xxx is passed in dns_addrtype). */ -#ifndef DNS_LOCAL_HOSTLIST +#if !defined DNS_LOCAL_HOSTLIST || defined __DOXYGEN__ #define DNS_LOCAL_HOSTLIST 0 #endif /* DNS_LOCAL_HOSTLIST */ /** If this is turned on, the local host-list can be dynamically changed * at runtime. */ -#ifndef DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#if !defined DNS_LOCAL_HOSTLIST_IS_DYNAMIC || defined __DOXYGEN__ #define DNS_LOCAL_HOSTLIST_IS_DYNAMIC 0 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +/** Set this to 1 to enable querying ".local" names via mDNS + * using a One-Shot Multicast DNS Query */ +#if !defined LWIP_DNS_SUPPORT_MDNS_QUERIES || defined __DOXYGEN__ +#define LWIP_DNS_SUPPORT_MDNS_QUERIES 0 +#endif +/** + * @} + */ + /* --------------------------------- ---------- UDP options ---------- --------------------------------- */ +/** + * @defgroup lwip_opts_udp UDP + * @ingroup lwip_opts_callback + * @{ + */ /** * LWIP_UDP==1: Turn on UDP. */ -#ifndef LWIP_UDP +#if !defined LWIP_UDP || defined __DOXYGEN__ #define LWIP_UDP 1 #endif /** * LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP) */ -#ifndef LWIP_UDPLITE +#if !defined LWIP_UDPLITE || defined __DOXYGEN__ #define LWIP_UDPLITE 0 #endif /** * UDP_TTL: Default Time-To-Live value. */ -#ifndef UDP_TTL +#if !defined UDP_TTL || defined __DOXYGEN__ #define UDP_TTL (IP_DEFAULT_TTL) #endif /** * LWIP_NETBUF_RECVINFO==1: append destination addr and port to every netbuf. */ -#ifndef LWIP_NETBUF_RECVINFO +#if !defined LWIP_NETBUF_RECVINFO || defined __DOXYGEN__ #define LWIP_NETBUF_RECVINFO 0 #endif +/** + * @} + */ /* --------------------------------- ---------- TCP options ---------- --------------------------------- */ +/** + * @defgroup lwip_opts_tcp TCP + * @ingroup lwip_opts_callback + * @{ + */ /** * LWIP_TCP==1: Turn on TCP. */ -#ifndef LWIP_TCP +#if !defined LWIP_TCP || defined __DOXYGEN__ #define LWIP_TCP 1 #endif /** * TCP_TTL: Default Time-To-Live value. */ -#ifndef TCP_TTL +#if !defined TCP_TTL || defined __DOXYGEN__ #define TCP_TTL (IP_DEFAULT_TTL) #endif /** * TCP_WND: The size of a TCP window. This must be at least - * (2 * TCP_MSS) for things to work well + * (2 * TCP_MSS) for things to work well. + * ATTENTION: when using TCP_RCV_SCALE, TCP_WND is the total size + * with scaling applied. Maximum window value in the TCP header + * will be TCP_WND >> TCP_RCV_SCALE */ -#ifndef TCP_WND -#define TCP_WND(pcb) (4 * TCP_MSS) +#if !defined TCP_WND || defined __DOXYGEN__ +#define TCP_WND (4 * TCP_MSS) #endif /** * TCP_MAXRTX: Maximum number of retransmissions of data segments. */ -#ifndef TCP_MAXRTX +#if !defined TCP_MAXRTX || defined __DOXYGEN__ #define TCP_MAXRTX 12 #endif /** * TCP_SYNMAXRTX: Maximum number of retransmissions of SYN segments. */ -#ifndef TCP_SYNMAXRTX +#if !defined TCP_SYNMAXRTX || defined __DOXYGEN__ #define TCP_SYNMAXRTX 6 #endif @@ -1023,7 +1184,7 @@ * TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order. * Define to 0 if your device is low on memory. */ -#ifndef TCP_QUEUE_OOSEQ +#if !defined TCP_QUEUE_OOSEQ || defined __DOXYGEN__ #define TCP_QUEUE_OOSEQ (LWIP_TCP) #endif @@ -1034,7 +1195,7 @@ * when opening a connection. For the transmit size, this MSS sets * an upper limit on the MSS advertised by the remote host. */ -#ifndef TCP_MSS +#if !defined TCP_MSS || defined __DOXYGEN__ #define TCP_MSS 536 #endif @@ -1046,7 +1207,7 @@ * Setting this to 1 enables code that checks TCP_MSS against the MTU of the * netif used for a connection and limits the MSS if it would be too big otherwise. */ -#ifndef TCP_CALCULATE_EFF_SEND_MSS +#if !defined TCP_CALCULATE_EFF_SEND_MSS || defined __DOXYGEN__ #define TCP_CALCULATE_EFF_SEND_MSS 1 #endif @@ -1055,16 +1216,16 @@ * TCP_SND_BUF: TCP sender buffer space (bytes). * To achieve good performance, this should be at least 2 * TCP_MSS. */ -#ifndef TCP_SND_BUF -#define TCP_SND_BUF(pcb) (2 * TCP_MSS) +#if !defined TCP_SND_BUF || defined __DOXYGEN__ +#define TCP_SND_BUF (2 * TCP_MSS) #endif /** * TCP_SND_QUEUELEN: TCP sender buffer space (pbufs). This must be at least * as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work. */ -#ifndef TCP_SND_QUEUELEN -#define TCP_SND_QUEUELEN(pcb) ((4 * (TCP_SND_BUF((pcb))) + (TCP_MSS - 1))/(TCP_MSS)) +#if !defined TCP_SND_QUEUELEN || defined __DOXYGEN__ +#define TCP_SND_QUEUELEN ((4 * (TCP_SND_BUF) + (TCP_MSS - 1))/(TCP_MSS)) #endif /** @@ -1072,8 +1233,8 @@ * TCP_SND_BUF. It is the amount of space which must be available in the * TCP snd_buf for select to return writable (combined with TCP_SNDQUEUELOWAT). */ -#ifndef TCP_SNDLOWAT -#define TCP_SNDLOWAT(pcb) LWIP_MIN(LWIP_MAX(((TCP_SND_BUF((pcb)))/2), (2 * TCP_MSS) + 1), (TCP_SND_BUF((pcb))) - 1) +#if !defined TCP_SNDLOWAT || defined __DOXYGEN__ +#define TCP_SNDLOWAT LWIP_MIN(LWIP_MAX(((TCP_SND_BUF)/2), (2 * TCP_MSS) + 1), (TCP_SND_BUF) - 1) #endif /** @@ -1081,30 +1242,30 @@ * than TCP_SND_QUEUELEN. If the number of pbufs queued on a pcb drops below * this number, select returns writable (combined with TCP_SNDLOWAT). */ -#ifndef TCP_SNDQUEUELOWAT -#define TCP_SNDQUEUELOWAT(pcb) LWIP_MAX(((TCP_SND_QUEUELEN((pcb)))/2), 5) +#if !defined TCP_SNDQUEUELOWAT || defined __DOXYGEN__ +#define TCP_SNDQUEUELOWAT LWIP_MAX(((TCP_SND_QUEUELEN)/2), 5) #endif /** * TCP_OOSEQ_MAX_BYTES: The maximum number of bytes queued on ooseq per pcb. - * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==0. + * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==1. */ -#ifndef TCP_OOSEQ_MAX_BYTES +#if !defined TCP_OOSEQ_MAX_BYTES || defined __DOXYGEN__ #define TCP_OOSEQ_MAX_BYTES 0 #endif /** * TCP_OOSEQ_MAX_PBUFS: The maximum number of pbufs queued on ooseq per pcb. - * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==0. + * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==1. */ -#ifndef TCP_OOSEQ_MAX_PBUFS +#if !defined TCP_OOSEQ_MAX_PBUFS || defined __DOXYGEN__ #define TCP_OOSEQ_MAX_PBUFS 0 #endif /** * TCP_LISTEN_BACKLOG: Enable the backlog option for tcp listen pcb. */ -#ifndef TCP_LISTEN_BACKLOG +#if !defined TCP_LISTEN_BACKLOG || defined __DOXYGEN__ #define TCP_LISTEN_BACKLOG 0 #endif @@ -1113,7 +1274,7 @@ * This backlog is used unless another is explicitly specified. * 0xff is the maximum (u8_t). */ -#ifndef TCP_DEFAULT_LISTEN_BACKLOG +#if !defined TCP_DEFAULT_LISTEN_BACKLOG || defined __DOXYGEN__ #define TCP_DEFAULT_LISTEN_BACKLOG 0xff #endif @@ -1131,7 +1292,7 @@ * TCP_MSS: Try to create unfragmented TCP packets. * TCP_MSS/4: Try to create 4 fragments or less per TCP packet. */ -#ifndef TCP_OVERSIZE +#if !defined TCP_OVERSIZE || defined __DOXYGEN__ #define TCP_OVERSIZE TCP_MSS #endif @@ -1141,7 +1302,7 @@ * really used locally. Therefore, it is only enabled when a TS option is * received in the initial SYN packet from a remote host. */ -#ifndef LWIP_TCP_TIMESTAMPS +#if !defined LWIP_TCP_TIMESTAMPS || defined __DOXYGEN__ #define LWIP_TCP_TIMESTAMPS 0 #endif @@ -1149,8 +1310,8 @@ * TCP_WND_UPDATE_THRESHOLD: difference in window to trigger an * explicit window update */ -#ifndef TCP_WND_UPDATE_THRESHOLD -#define TCP_WND_UPDATE_THRESHOLD(pcb) LWIP_MIN((TCP_WND((pcb)) / 4), (TCP_MSS * 4)) +#if !defined TCP_WND_UPDATE_THRESHOLD || defined __DOXYGEN__ +#define TCP_WND_UPDATE_THRESHOLD LWIP_MIN((TCP_WND / 4), (TCP_MSS * 4)) #endif /** @@ -1160,9 +1321,16 @@ * LWIP_CALLBACK_API==1: The PCB callback function is called directly * for the event. This is the default. */ -#if !defined(LWIP_EVENT_API) && !defined(LWIP_CALLBACK_API) +#if !defined(LWIP_EVENT_API) && !defined(LWIP_CALLBACK_API) || defined __DOXYGEN__ #define LWIP_EVENT_API 0 #define LWIP_CALLBACK_API 1 +#else +#ifndef LWIP_EVENT_API +#define LWIP_EVENT_API 0 +#endif +#ifndef LWIP_CALLBACK_API +#define LWIP_CALLBACK_API 0 +#endif #endif /** @@ -1173,24 +1341,31 @@ * When LWIP_WND_SCALE is enabled but TCP_RCV_SCALE is 0, we can use a large * send window while having a small receive window only. */ -#ifndef LWIP_WND_SCALE +#if !defined LWIP_WND_SCALE || defined __DOXYGEN__ #define LWIP_WND_SCALE 0 #define TCP_RCV_SCALE 0 #endif - +/** + * @} + */ /* ---------------------------------- ---------- Pbuf options ---------- ---------------------------------- */ +/** + * @defgroup lwip_opts_pbuf PBUF + * @ingroup lwip_opts + * @{ + */ /** * PBUF_LINK_HLEN: the number of bytes that should be allocated for a * link level header. The default is 14, the standard value for * Ethernet. */ -#ifndef PBUF_LINK_HLEN -#ifdef LWIP_HOOK_VLAN_SET +#if !defined PBUF_LINK_HLEN || defined __DOXYGEN__ +#if defined LWIP_HOOK_VLAN_SET && !defined __DOXYGEN__ #define PBUF_LINK_HLEN (18 + ETH_PAD_SIZE) #else /* LWIP_HOOK_VLAN_SET */ #define PBUF_LINK_HLEN (14 + ETH_PAD_SIZE) @@ -1201,8 +1376,8 @@ * PBUF_LINK_ENCAPSULATION_HLEN: the number of bytes that should be allocated * for an additional encapsulation header before ethernet headers (e.g. 802.11) */ -#ifndef PBUF_LINK_ENCAPSULATION_HLEN -#define PBUF_LINK_ENCAPSULATION_HLEN 0 +#if !defined PBUF_LINK_ENCAPSULATION_HLEN || defined __DOXYGEN__ +#define PBUF_LINK_ENCAPSULATION_HLEN 0u #endif /** @@ -1210,27 +1385,35 @@ * designed to accommodate single full size TCP frame in one pbuf, including * TCP_MSS, IP header, and link header. */ -#ifndef PBUF_POOL_BUFSIZE +#if !defined PBUF_POOL_BUFSIZE || defined __DOXYGEN__ #define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_ENCAPSULATION_HLEN+PBUF_LINK_HLEN) #endif +/** + * @} + */ /* ------------------------------------------------ ---------- Network Interfaces options ---------- ------------------------------------------------ */ +/** + * @defgroup lwip_opts_netif NETIF + * @ingroup lwip_opts + * @{ + */ /** * LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname * field. */ -#ifndef LWIP_NETIF_HOSTNAME +#if !defined LWIP_NETIF_HOSTNAME || defined __DOXYGEN__ #define LWIP_NETIF_HOSTNAME 0 #endif /** * LWIP_NETIF_API==1: Support netif api (in netifapi.c) */ -#ifndef LWIP_NETIF_API +#if !defined LWIP_NETIF_API || defined __DOXYGEN__ #define LWIP_NETIF_API 0 #endif @@ -1238,7 +1421,7 @@ * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface * changes its up/down status (i.e., due to DHCP IP acquisition) */ -#ifndef LWIP_NETIF_STATUS_CALLBACK +#if !defined LWIP_NETIF_STATUS_CALLBACK || defined __DOXYGEN__ #define LWIP_NETIF_STATUS_CALLBACK 0 #endif @@ -1246,7 +1429,7 @@ * LWIP_NETIF_LINK_CALLBACK==1: Support a callback function from an interface * whenever the link changes (i.e., link down) */ -#ifndef LWIP_NETIF_LINK_CALLBACK +#if !defined LWIP_NETIF_LINK_CALLBACK || defined __DOXYGEN__ #define LWIP_NETIF_LINK_CALLBACK 0 #endif @@ -1254,7 +1437,7 @@ * LWIP_NETIF_REMOVE_CALLBACK==1: Support a callback function that is called * when a netif has been removed */ -#ifndef LWIP_NETIF_REMOVE_CALLBACK +#if !defined LWIP_NETIF_REMOVE_CALLBACK || defined __DOXYGEN__ #define LWIP_NETIF_REMOVE_CALLBACK 0 #endif @@ -1265,43 +1448,10 @@ * ARP tables or many concurrent connections, it might be counterproductive * if you have a tiny ARP table or if there never are concurrent connections. */ -#ifndef LWIP_NETIF_HWADDRHINT +#if !defined LWIP_NETIF_HWADDRHINT || defined __DOXYGEN__ #define LWIP_NETIF_HWADDRHINT 0 #endif -/** - * LWIP_NETIF_LOOPBACK==1: Support sending packets with a destination IP - * address equal to the netif IP address, looping them back up the stack. - */ -#ifndef LWIP_NETIF_LOOPBACK -#define LWIP_NETIF_LOOPBACK 0 -#endif - -/** - * LWIP_LOOPBACK_MAX_PBUFS: Maximum number of pbufs on queue for loopback - * sending for each netif (0 = disabled) - */ -#ifndef LWIP_LOOPBACK_MAX_PBUFS -#define LWIP_LOOPBACK_MAX_PBUFS 0 -#endif - -/** - * LWIP_NETIF_LOOPBACK_MULTITHREADING: Indicates whether threading is enabled in - * the system, as netifs must change how they behave depending on this setting - * for the LWIP_NETIF_LOOPBACK option to work. - * Setting this is needed to avoid reentering non-reentrant functions like - * tcp_input(). - * LWIP_NETIF_LOOPBACK_MULTITHREADING==1: Indicates that the user is using a - * multithreaded environment like tcpip.c. In this case, netif->input() - * is called directly. - * LWIP_NETIF_LOOPBACK_MULTITHREADING==0: Indicates a polling (or NO_SYS) setup. - * The packets are put on a list and netif_poll() must be called in - * the main application loop. - */ -#ifndef LWIP_NETIF_LOOPBACK_MULTITHREADING -#define LWIP_NETIF_LOOPBACK_MULTITHREADING (!NO_SYS) -#endif - /** * LWIP_NETIF_TX_SINGLE_PBUF: if this is set to 1, lwIP tries to put all data * to be sent into one single pbuf. This is for compatibility with DMA-enabled @@ -1311,52 +1461,97 @@ * * @todo: TCP and IP-frag do not work with this, yet: */ -#ifndef LWIP_NETIF_TX_SINGLE_PBUF +#if !defined LWIP_NETIF_TX_SINGLE_PBUF || defined __DOXYGEN__ #define LWIP_NETIF_TX_SINGLE_PBUF 0 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */ +/** + * LWIP_NUM_NETIF_CLIENT_DATA: Number of clients that may store + * data in client_data member array of struct netif. + */ +#if !defined LWIP_NUM_NETIF_CLIENT_DATA || defined __DOXYGEN__ +#define LWIP_NUM_NETIF_CLIENT_DATA 0 +#endif +/** + * @} + */ + /* ------------------------------------ ---------- LOOPIF options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_loop Loopback interface + * @ingroup lwip_opts_netif + * @{ + */ /** * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1). * This is only needed when no real netifs are available. If at least one other * netif is available, loopback traffic uses this netif. */ -#ifndef LWIP_HAVE_LOOPIF +#if !defined LWIP_HAVE_LOOPIF || defined __DOXYGEN__ #define LWIP_HAVE_LOOPIF LWIP_NETIF_LOOPBACK #endif /** * LWIP_LOOPIF_MULTICAST==1: Support multicast/IGMP on loop interface (127.0.0.1). */ -#ifndef LWIP_LOOPIF_MULTICAST +#if !defined LWIP_LOOPIF_MULTICAST || defined __DOXYGEN__ #define LWIP_LOOPIF_MULTICAST 0 #endif -/* - ------------------------------------ - ---------- SLIPIF options ---------- - ------------------------------------ -*/ /** - * LWIP_HAVE_SLIPIF==1: Support slip interface and slipif.c + * LWIP_NETIF_LOOPBACK==1: Support sending packets with a destination IP + * address equal to the netif IP address, looping them back up the stack. + */ +#if !defined LWIP_NETIF_LOOPBACK || defined __DOXYGEN__ +#define LWIP_NETIF_LOOPBACK 0 +#endif + +/** + * LWIP_LOOPBACK_MAX_PBUFS: Maximum number of pbufs on queue for loopback + * sending for each netif (0 = disabled) + */ +#if !defined LWIP_LOOPBACK_MAX_PBUFS || defined __DOXYGEN__ +#define LWIP_LOOPBACK_MAX_PBUFS 0 +#endif + +/** + * LWIP_NETIF_LOOPBACK_MULTITHREADING: Indicates whether threading is enabled in + * the system, as netifs must change how they behave depending on this setting + * for the LWIP_NETIF_LOOPBACK option to work. + * Setting this is needed to avoid reentering non-reentrant functions like + * tcp_input(). + * LWIP_NETIF_LOOPBACK_MULTITHREADING==1: Indicates that the user is using a + * multithreaded environment like tcpip.c. In this case, netif->input() + * is called directly. + * LWIP_NETIF_LOOPBACK_MULTITHREADING==0: Indicates a polling (or NO_SYS) setup. + * The packets are put on a list and netif_poll() must be called in + * the main application loop. */ -#ifndef LWIP_HAVE_SLIPIF -#define LWIP_HAVE_SLIPIF 0 +#if !defined LWIP_NETIF_LOOPBACK_MULTITHREADING || defined __DOXYGEN__ +#define LWIP_NETIF_LOOPBACK_MULTITHREADING (!NO_SYS) #endif +/** + * @} + */ /* ------------------------------------ ---------- Thread options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_thread Threading + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * TCPIP_THREAD_NAME: The name assigned to the main tcpip thread. */ -#ifndef TCPIP_THREAD_NAME +#if !defined TCPIP_THREAD_NAME || defined __DOXYGEN__ #define TCPIP_THREAD_NAME "tcpip_thread" #endif @@ -1365,7 +1560,7 @@ * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef TCPIP_THREAD_STACKSIZE +#if !defined TCPIP_THREAD_STACKSIZE || defined __DOXYGEN__ #define TCPIP_THREAD_STACKSIZE 0 #endif @@ -1374,7 +1569,7 @@ * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef TCPIP_THREAD_PRIO +#if !defined TCPIP_THREAD_PRIO || defined __DOXYGEN__ #define TCPIP_THREAD_PRIO 1 #endif @@ -1383,14 +1578,22 @@ * The queue size value itself is platform-dependent, but is passed to * sys_mbox_new() when tcpip_init is called. */ -#ifndef TCPIP_MBOX_SIZE +#if !defined TCPIP_MBOX_SIZE || defined __DOXYGEN__ #define TCPIP_MBOX_SIZE 0 #endif +/** + * Define this to something that triggers a watchdog. This is called from + * tcpip_thread after processing a message. + */ +#if !defined LWIP_TCPIP_THREAD_ALIVE || defined __DOXYGEN__ +#define LWIP_TCPIP_THREAD_ALIVE() +#endif + /** * SLIPIF_THREAD_NAME: The name assigned to the slipif_loop thread. */ -#ifndef SLIPIF_THREAD_NAME +#if !defined SLIPIF_THREAD_NAME || defined __DOXYGEN__ #define SLIPIF_THREAD_NAME "slipif_loop" #endif @@ -1399,7 +1602,7 @@ * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef SLIPIF_THREAD_STACKSIZE +#if !defined SLIPIF_THREAD_STACKSIZE || defined __DOXYGEN__ #define SLIPIF_THREAD_STACKSIZE 0 #endif @@ -1408,14 +1611,14 @@ * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef SLIPIF_THREAD_PRIO +#if !defined SLIPIF_THREAD_PRIO || defined __DOXYGEN__ #define SLIPIF_THREAD_PRIO 1 #endif /** * DEFAULT_THREAD_NAME: The name assigned to any other lwIP thread. */ -#ifndef DEFAULT_THREAD_NAME +#if !defined DEFAULT_THREAD_NAME || defined __DOXYGEN__ #define DEFAULT_THREAD_NAME "lwIP" #endif @@ -1424,7 +1627,7 @@ * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef DEFAULT_THREAD_STACKSIZE +#if !defined DEFAULT_THREAD_STACKSIZE || defined __DOXYGEN__ #define DEFAULT_THREAD_STACKSIZE 0 #endif @@ -1433,7 +1636,7 @@ * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef DEFAULT_THREAD_PRIO +#if !defined DEFAULT_THREAD_PRIO || defined __DOXYGEN__ #define DEFAULT_THREAD_PRIO 1 #endif @@ -1442,7 +1645,7 @@ * NETCONN_RAW. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ -#ifndef DEFAULT_RAW_RECVMBOX_SIZE +#if !defined DEFAULT_RAW_RECVMBOX_SIZE || defined __DOXYGEN__ #define DEFAULT_RAW_RECVMBOX_SIZE 0 #endif @@ -1451,7 +1654,7 @@ * NETCONN_UDP. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ -#ifndef DEFAULT_UDP_RECVMBOX_SIZE +#if !defined DEFAULT_UDP_RECVMBOX_SIZE || defined __DOXYGEN__ #define DEFAULT_UDP_RECVMBOX_SIZE 0 #endif @@ -1460,7 +1663,7 @@ * NETCONN_TCP. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ -#ifndef DEFAULT_TCP_RECVMBOX_SIZE +#if !defined DEFAULT_TCP_RECVMBOX_SIZE || defined __DOXYGEN__ #define DEFAULT_TCP_RECVMBOX_SIZE 0 #endif @@ -1469,9 +1672,12 @@ * The queue size value itself is platform-dependent, but is passed to * sys_mbox_new() when the acceptmbox is created. */ -#ifndef DEFAULT_ACCEPTMBOX_SIZE +#if !defined DEFAULT_ACCEPTMBOX_SIZE || defined __DOXYGEN__ #define DEFAULT_ACCEPTMBOX_SIZE 0 #endif +/** + * @} + */ /* ---------------------------------------------- @@ -1479,32 +1685,21 @@ ---------------------------------------------- */ /** - * LWIP_TCPIP_CORE_LOCKING: (EXPERIMENTAL!) - * Don't use it if you're not an active lwIP project member - */ -#ifndef LWIP_TCPIP_CORE_LOCKING -#define LWIP_TCPIP_CORE_LOCKING 0 -#endif - -/** - * LWIP_TCPIP_CORE_LOCKING_INPUT: (EXPERIMENTAL!) - * Don't use it if you're not an active lwIP project member + * @defgroup lwip_opts_netconn Netconn + * @ingroup lwip_opts_threadsafe_apis + * @{ */ -#ifndef LWIP_TCPIP_CORE_LOCKING_INPUT -#define LWIP_TCPIP_CORE_LOCKING_INPUT 0 -#endif - /** * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) */ -#ifndef LWIP_NETCONN +#if !defined LWIP_NETCONN || defined __DOXYGEN__ #define LWIP_NETCONN 1 #endif /** LWIP_TCPIP_TIMEOUT==1: Enable tcpip_timeout/tcpip_untimeout to create * timers running in tcpip_thread from another thread. */ -#ifndef LWIP_TCPIP_TIMEOUT +#if !defined LWIP_TCPIP_TIMEOUT || defined __DOXYGEN__ #define LWIP_TCPIP_TIMEOUT 0 #endif @@ -1518,7 +1713,7 @@ * The latter 2 can be invoked up by calling netconn_thread_init()/netconn_thread_cleanup(). * Ports may call these for threads created with sys_thread_new(). */ -#ifndef LWIP_NETCONN_SEM_PER_THREAD +#if !defined LWIP_NETCONN_SEM_PER_THREAD || defined __DOXYGEN__ #define LWIP_NETCONN_SEM_PER_THREAD 0 #endif @@ -1530,26 +1725,34 @@ * - sys_mbox_free() has to unblock receive tasks waiting on recvmbox/acceptmbox * and prevent a task pending on this during/after deletion */ -#ifndef LWIP_NETCONN_FULLDUPLEX +#if !defined LWIP_NETCONN_FULLDUPLEX || defined __DOXYGEN__ #define LWIP_NETCONN_FULLDUPLEX 0 #endif +/** + * @} + */ /* ------------------------------------ ---------- Socket options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_socket Sockets + * @ingroup lwip_opts_threadsafe_apis + * @{ + */ /** * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) */ -#ifndef LWIP_SOCKET +#if !defined LWIP_SOCKET || defined __DOXYGEN__ #define LWIP_SOCKET 1 #endif /* LWIP_SOCKET_SET_ERRNO==1: Set errno when socket functions cannot complete * successfully, as required by POSIX. Default is POSIX-compliant. */ -#ifndef LWIP_SOCKET_SET_ERRNO +#if !defined LWIP_SOCKET_SET_ERRNO || defined __DOXYGEN__ #define LWIP_SOCKET_SET_ERRNO 1 #endif @@ -1559,7 +1762,7 @@ * While this helps code completion, it might conflict with existing libraries. * (only used if you use sockets.c) */ -#ifndef LWIP_COMPAT_SOCKETS +#if !defined LWIP_COMPAT_SOCKETS || defined __DOXYGEN__ #define LWIP_COMPAT_SOCKETS 1 #endif @@ -1568,7 +1771,7 @@ * Disable this option if you use a POSIX operating system that uses the same * names (read, write & close). (only used if you use sockets.c) */ -#ifndef LWIP_POSIX_SOCKETS_IO_NAMES +#if !defined LWIP_POSIX_SOCKETS_IO_NAMES || defined __DOXYGEN__ #define LWIP_POSIX_SOCKETS_IO_NAMES 1 #endif @@ -1579,7 +1782,7 @@ * re implement read/write/close/ioctl/fnctl to send the requested action to the right * library (sharing select will need more work though). */ -#ifndef LWIP_SOCKET_OFFSET +#if !defined LWIP_SOCKET_OFFSET || defined __DOXYGEN__ #define LWIP_SOCKET_OFFSET 0 #endif @@ -1588,7 +1791,7 @@ * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set * in seconds. (does not require sockets.c, and will affect tcp.c) */ -#ifndef LWIP_TCP_KEEPALIVE +#if !defined LWIP_TCP_KEEPALIVE || defined __DOXYGEN__ #define LWIP_TCP_KEEPALIVE 0 #endif @@ -1596,7 +1799,7 @@ * LWIP_SO_SNDTIMEO==1: Enable send timeout for sockets/netconns and * SO_SNDTIMEO processing. */ -#ifndef LWIP_SO_SNDTIMEO +#if !defined LWIP_SO_SNDTIMEO || defined __DOXYGEN__ #define LWIP_SO_SNDTIMEO 0 #endif @@ -1604,7 +1807,7 @@ * LWIP_SO_RCVTIMEO==1: Enable receive timeout for sockets/netconns and * SO_RCVTIMEO processing. */ -#ifndef LWIP_SO_RCVTIMEO +#if !defined LWIP_SO_RCVTIMEO || defined __DOXYGEN__ #define LWIP_SO_RCVTIMEO 0 #endif @@ -1612,42 +1815,42 @@ * LWIP_SO_SNDRCVTIMEO_NONSTANDARD==1: SO_RCVTIMEO/SO_SNDTIMEO take an int * (milliseconds, much like winsock does) instead of a struct timeval (default). */ -#ifndef LWIP_SO_SNDRCVTIMEO_NONSTANDARD +#if !defined LWIP_SO_SNDRCVTIMEO_NONSTANDARD || defined __DOXYGEN__ #define LWIP_SO_SNDRCVTIMEO_NONSTANDARD 0 #endif /** * LWIP_SO_RCVBUF==1: Enable SO_RCVBUF processing. */ -#ifndef LWIP_SO_RCVBUF +#if !defined LWIP_SO_RCVBUF || defined __DOXYGEN__ #define LWIP_SO_RCVBUF 0 #endif /** * LWIP_SO_LINGER==1: Enable SO_LINGER processing. */ -#ifndef LWIP_SO_LINGER +#if !defined LWIP_SO_LINGER || defined __DOXYGEN__ #define LWIP_SO_LINGER 0 #endif /** * If LWIP_SO_RCVBUF is used, this is the default value for recv_bufsize. */ -#ifndef RECV_BUFSIZE_DEFAULT +#if !defined RECV_BUFSIZE_DEFAULT || defined __DOXYGEN__ #define RECV_BUFSIZE_DEFAULT INT_MAX #endif /** * By default, TCP socket/netconn close waits 20 seconds max to send the FIN */ -#ifndef LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT +#if !defined LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT || defined __DOXYGEN__ #define LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT 20000 #endif /** * SO_REUSE==1: Enable SO_REUSEADDR option. */ -#ifndef SO_REUSE +#if !defined SO_REUSE || defined __DOXYGEN__ #define SO_REUSE 0 #endif @@ -1656,7 +1859,7 @@ * to all local matches if SO_REUSEADDR is turned on. * WARNING: Adds a memcpy for every packet if passing to more than one pcb! */ -#ifndef SO_REUSE_RXTOALL +#if !defined SO_REUSE_RXTOALL || defined __DOXYGEN__ #define SO_REUSE_RXTOALL 0 #endif @@ -1668,20 +1871,28 @@ * pending datagram in bytes. This is the way linux does it. This code is only * here for compatibility. */ -#ifndef LWIP_FIONREAD_LINUXMODE +#if !defined LWIP_FIONREAD_LINUXMODE || defined __DOXYGEN__ #define LWIP_FIONREAD_LINUXMODE 0 #endif - +/** + * @} + */ + /* ---------------------------------------- ---------- Statistics options ---------- ---------------------------------------- */ +/** + * @defgroup lwip_opts_stats Statistics + * @ingroup lwip_opts_debug + * @{ + */ /** * LWIP_STATS==1: Enable statistics collection in lwip_stats. */ -#ifndef LWIP_STATS -#define LWIP_STATS 0 +#if !defined LWIP_STATS || defined __DOXYGEN__ +#define LWIP_STATS 1 #endif #if LWIP_STATS @@ -1689,28 +1900,28 @@ /** * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. */ -#ifndef LWIP_STATS_DISPLAY +#if !defined LWIP_STATS_DISPLAY || defined __DOXYGEN__ #define LWIP_STATS_DISPLAY 0 #endif /** * LINK_STATS==1: Enable link stats. */ -#ifndef LINK_STATS +#if !defined LINK_STATS || defined __DOXYGEN__ #define LINK_STATS 1 #endif /** * ETHARP_STATS==1: Enable etharp stats. */ -#ifndef ETHARP_STATS +#if !defined ETHARP_STATS || defined __DOXYGEN__ #define ETHARP_STATS (LWIP_ARP) #endif /** * IP_STATS==1: Enable IP stats. */ -#ifndef IP_STATS +#if !defined IP_STATS || defined __DOXYGEN__ #define IP_STATS 1 #endif @@ -1718,21 +1929,21 @@ * IPFRAG_STATS==1: Enable IP fragmentation stats. Default is * on if using either frag or reass. */ -#ifndef IPFRAG_STATS +#if !defined IPFRAG_STATS || defined __DOXYGEN__ #define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG) #endif /** * ICMP_STATS==1: Enable ICMP stats. */ -#ifndef ICMP_STATS +#if !defined ICMP_STATS || defined __DOXYGEN__ #define ICMP_STATS 1 #endif /** * IGMP_STATS==1: Enable IGMP stats. */ -#ifndef IGMP_STATS +#if !defined IGMP_STATS || defined __DOXYGEN__ #define IGMP_STATS (LWIP_IGMP) #endif @@ -1740,7 +1951,7 @@ * UDP_STATS==1: Enable UDP stats. Default is on if * UDP enabled, otherwise off. */ -#ifndef UDP_STATS +#if !defined UDP_STATS || defined __DOXYGEN__ #define UDP_STATS (LWIP_UDP) #endif @@ -1748,70 +1959,70 @@ * TCP_STATS==1: Enable TCP stats. Default is on if TCP * enabled, otherwise off. */ -#ifndef TCP_STATS +#if !defined TCP_STATS || defined __DOXYGEN__ #define TCP_STATS (LWIP_TCP) #endif /** * MEM_STATS==1: Enable mem.c stats. */ -#ifndef MEM_STATS +#if !defined MEM_STATS || defined __DOXYGEN__ #define MEM_STATS ((MEM_LIBC_MALLOC == 0) && (MEM_USE_POOLS == 0)) #endif /** * MEMP_STATS==1: Enable memp.c pool stats. */ -#ifndef MEMP_STATS +#if !defined MEMP_STATS || defined __DOXYGEN__ #define MEMP_STATS (MEMP_MEM_MALLOC == 0) #endif /** * SYS_STATS==1: Enable system stats (sem and mbox counts, etc). */ -#ifndef SYS_STATS +#if !defined SYS_STATS || defined __DOXYGEN__ #define SYS_STATS (NO_SYS == 0) #endif /** * IP6_STATS==1: Enable IPv6 stats. */ -#ifndef IP6_STATS +#if !defined IP6_STATS || defined __DOXYGEN__ #define IP6_STATS (LWIP_IPV6) #endif /** * ICMP6_STATS==1: Enable ICMP for IPv6 stats. */ -#ifndef ICMP6_STATS +#if !defined ICMP6_STATS || defined __DOXYGEN__ #define ICMP6_STATS (LWIP_IPV6 && LWIP_ICMP6) #endif /** * IP6_FRAG_STATS==1: Enable IPv6 fragmentation stats. */ -#ifndef IP6_FRAG_STATS +#if !defined IP6_FRAG_STATS || defined __DOXYGEN__ #define IP6_FRAG_STATS (LWIP_IPV6 && (LWIP_IPV6_FRAG || LWIP_IPV6_REASS)) #endif /** * MLD6_STATS==1: Enable MLD for IPv6 stats. */ -#ifndef MLD6_STATS +#if !defined MLD6_STATS || defined __DOXYGEN__ #define MLD6_STATS (LWIP_IPV6 && LWIP_IPV6_MLD) #endif /** * ND6_STATS==1: Enable Neighbor discovery for IPv6 stats. */ -#ifndef ND6_STATS +#if !defined ND6_STATS || defined __DOXYGEN__ #define ND6_STATS (LWIP_IPV6) #endif /** * MIB2_STATS==1: Stats for SNMP MIB2. */ -#ifndef MIB2_STATS +#if !defined MIB2_STATS || defined __DOXYGEN__ #define MIB2_STATS 0 #endif @@ -1837,602 +2048,96 @@ #define MIB2_STATS 0 #endif /* LWIP_STATS */ - -/* - --------------------------------- - ---------- PPP options ---------- - --------------------------------- -*/ - -/** - * PPP_SUPPORT==1: Enable PPP. - */ -#ifndef PPP_SUPPORT -#define PPP_SUPPORT 0 -#endif - -/** - * PPPOE_SUPPORT==1: Enable PPP Over Ethernet - */ -#ifndef PPPOE_SUPPORT -#define PPPOE_SUPPORT 0 -#endif - -/** - * PPPOL2TP_SUPPORT==1: Enable PPP Over L2TP - */ -#ifndef PPPOL2TP_SUPPORT -#define PPPOL2TP_SUPPORT 0 -#endif - -/** - * PPPOL2TP_AUTH_SUPPORT==1: Enable PPP Over L2TP Auth (enable MD5 support) - */ -#ifndef PPPOL2TP_AUTH_SUPPORT -#define PPPOL2TP_AUTH_SUPPORT PPPOL2TP_SUPPORT -#endif - -/** - * PPPOS_SUPPORT==1: Enable PPP Over Serial - */ -#ifndef PPPOS_SUPPORT -#define PPPOS_SUPPORT PPP_SUPPORT -#endif - -/** - * LWIP_PPP_API==1: Enable PPP API (in pppapi.c) - */ -#ifndef LWIP_PPP_API -#define LWIP_PPP_API (PPP_SUPPORT && (NO_SYS == 0)) -#endif - -#if PPP_SUPPORT - -/** - * PPP_INPROC_IRQ_SAFE==1 call pppos_input() using tcpip_callback(). - * - * Please read the "PPPoS input path" chapter in the PPP documentation about this option. - */ -#ifndef PPP_INPROC_IRQ_SAFE -#define PPP_INPROC_IRQ_SAFE 0 -#endif - -/** - * PRINTPKT_SUPPORT==1: Enable PPP print packet support - * - * Mandatory for debugging, it displays exchanged packet content in debug trace. - */ -#ifndef PRINTPKT_SUPPORT -#define PRINTPKT_SUPPORT 0 -#endif - -/** - * PPP_IPV4_SUPPORT==1: Enable PPP IPv4 support - */ -#ifndef PPP_IPV4_SUPPORT -#define PPP_IPV4_SUPPORT (LWIP_IPV4) -#endif - -/** - * PPP_IPV6_SUPPORT==1: Enable PPP IPv6 support - */ -#ifndef PPP_IPV6_SUPPORT -#define PPP_IPV6_SUPPORT (LWIP_IPV6) -#endif - -/** - * PPP_NOTIFY_PHASE==1: Support PPP notify phase support - * - * PPP notify phase support allows you to set a callback which is - * called on change of the internal PPP state machine. - * - * This can be used for example to set a LED pattern depending on the - * current phase of the PPP session. - */ -#ifndef PPP_NOTIFY_PHASE -#define PPP_NOTIFY_PHASE 0 -#endif - -/** - * pbuf_type PPP is using for LCP, PAP, CHAP, EAP, CCP, IPCP and IP6CP packets. - * - * Memory allocated must be single buffered for PPP to works, it requires pbuf - * that are not going to be chained when allocated. This requires setting - * PBUF_POOL_BUFSIZE to at least 512 bytes, which is quite huge for small systems. - * - * Setting PPP_USE_PBUF_RAM to 1 makes PPP use memory from heap where continuous - * buffers are required, allowing you to use a smaller PBUF_POOL_BUFSIZE. - */ -#ifndef PPP_USE_PBUF_RAM -#define PPP_USE_PBUF_RAM 0 -#endif - -/** - * PPP_FCS_TABLE: Keep a 256*2 byte table to speed up FCS calculation for PPPoS - */ -#ifndef PPP_FCS_TABLE -#define PPP_FCS_TABLE 1 -#endif - -/** - * PAP_SUPPORT==1: Support PAP. - */ -#ifndef PAP_SUPPORT -#define PAP_SUPPORT 0 -#endif - -/** - * CHAP_SUPPORT==1: Support CHAP. - */ -#ifndef CHAP_SUPPORT -#define CHAP_SUPPORT 0 -#endif - -/** - * MSCHAP_SUPPORT==1: Support MSCHAP. - */ -#ifndef MSCHAP_SUPPORT -#define MSCHAP_SUPPORT 0 -#endif -#if MSCHAP_SUPPORT -/* MSCHAP requires CHAP support */ -#undef CHAP_SUPPORT -#define CHAP_SUPPORT 1 -#endif /* MSCHAP_SUPPORT */ - -/** - * EAP_SUPPORT==1: Support EAP. - */ -#ifndef EAP_SUPPORT -#define EAP_SUPPORT 0 -#endif - -/** - * CCP_SUPPORT==1: Support CCP. - */ -#ifndef CCP_SUPPORT -#define CCP_SUPPORT 0 -#endif - -/** - * MPPE_SUPPORT==1: Support MPPE. - */ -#ifndef MPPE_SUPPORT -#define MPPE_SUPPORT 0 -#endif -#if MPPE_SUPPORT -/* MPPE requires CCP support */ -#undef CCP_SUPPORT -#define CCP_SUPPORT 1 -/* MPPE requires MSCHAP support */ -#undef MSCHAP_SUPPORT -#define MSCHAP_SUPPORT 1 -/* MSCHAP requires CHAP support */ -#undef CHAP_SUPPORT -#define CHAP_SUPPORT 1 -#endif /* MPPE_SUPPORT */ - -/** - * CBCP_SUPPORT==1: Support CBCP. CURRENTLY NOT SUPPORTED! DO NOT SET! - */ -#ifndef CBCP_SUPPORT -#define CBCP_SUPPORT 0 -#endif - -/** - * ECP_SUPPORT==1: Support ECP. CURRENTLY NOT SUPPORTED! DO NOT SET! - */ -#ifndef ECP_SUPPORT -#define ECP_SUPPORT 0 -#endif - -/** - * DEMAND_SUPPORT==1: Support dial on demand. CURRENTLY NOT SUPPORTED! DO NOT SET! - */ -#ifndef DEMAND_SUPPORT -#define DEMAND_SUPPORT 0 -#endif - -/** - * LQR_SUPPORT==1: Support Link Quality Report. Do nothing except exchanging some LCP packets. - */ -#ifndef LQR_SUPPORT -#define LQR_SUPPORT 0 -#endif - -/** - * PPP_SERVER==1: Enable PPP server support (waiting for incoming PPP session). - * - * Currently only supported for PPPoS. - */ -#ifndef PPP_SERVER -#define PPP_SERVER 0 -#endif - -#if PPP_SERVER -/* - * PPP_OUR_NAME: Our name for authentication purposes - */ -#ifndef PPP_OUR_NAME -#define PPP_OUR_NAME "lwIP" -#endif -#endif /* PPP_SERVER */ - -/** - * VJ_SUPPORT==1: Support VJ header compression. - */ -#ifndef VJ_SUPPORT -#define VJ_SUPPORT 1 -#endif -/* VJ compression is only supported for IPv4 over PPPoS. */ -#if !PPPOS_SUPPORT || !PPP_IPV4_SUPPORT -#undef VJ_SUPPORT -#define VJ_SUPPORT 0 -#endif /* !PPPOS_SUPPORT */ - -/** - * PPP_MD5_RANDM==1: Use MD5 for better randomness. - * Enabled by default if CHAP, EAP, or L2TP AUTH support is enabled. - */ -#ifndef PPP_MD5_RANDM -#define PPP_MD5_RANDM (CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT) -#endif - -/** - * PolarSSL library, used if necessary and not previously disabled - * - * - * lwIP contains some files fetched from the latest BSD release of - * the PolarSSL project for ciphers and encryption methods we need for lwIP - * PPP support. - * - * The PolarSSL files were cleaned to contain only the necessary struct - * fields and functions needed for lwIP. - * - * The PolarSSL API was not changed at all, so if you are already using - * PolarSSL you can choose to skip the compilation of the included PolarSSL - * library into lwIP: - * - * The following defines are available for flexibility: - * - * LWIP_INCLUDED_POLARSSL_MD4 ; Use lwIP internal PolarSSL for MD4 - * LWIP_INCLUDED_POLARSSL_MD5 ; Use lwIP internal PolarSSL for MD5 - * LWIP_INCLUDED_POLARSSL_SHA1 ; Use lwIP internal PolarSSL for SHA1 - * LWIP_INCLUDED_POLARSSL_DES ; Use lwIP internal PolarSSL for DES - * - * If set (=1), the default if required by another enabled PPP feature unless - * explicitly set to 0, using included lwIP PolarSSL. - * - * If clear (=0), not needed or using external PolarSSL. - * - * Beware of the stack requirements which can be a lot larger if you are not - * using our cleaned PolarSSL library. - */ - -/* CHAP, EAP, L2TP AUTH and MD5 Random require MD5 support */ -#if CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM -#ifndef LWIP_INCLUDED_POLARSSL_MD5 -#define LWIP_INCLUDED_POLARSSL_MD5 1 -#endif /* LWIP_INCLUDED_POLARSSL_MD5 */ -#endif /* CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM */ - -#if MSCHAP_SUPPORT -/* MSCHAP require MD4 support */ -#ifndef LWIP_INCLUDED_POLARSSL_MD4 -#define LWIP_INCLUDED_POLARSSL_MD4 1 -#endif /* LWIP_INCLUDED_POLARSSL_MD4 */ -/* MSCHAP require SHA1 support */ -#ifndef LWIP_INCLUDED_POLARSSL_SHA1 -#define LWIP_INCLUDED_POLARSSL_SHA1 1 -#endif /* LWIP_INCLUDED_POLARSSL_SHA1 */ -/* MSCHAP require DES support */ -#ifndef LWIP_INCLUDED_POLARSSL_DES -#define LWIP_INCLUDED_POLARSSL_DES 1 -#endif /* LWIP_INCLUDED_POLARSSL_DES */ -/* MS-CHAP support is required for MPPE */ -#if MPPE_SUPPORT -/* MPPE require ARC4 support */ -#ifndef LWIP_INCLUDED_POLARSSL_ARC4 -#define LWIP_INCLUDED_POLARSSL_ARC4 1 -#endif /* LWIP_INCLUDED_POLARSSL_ARC4*/ -#endif /* MPPE_SUPPORT */ -#endif /* MSCHAP_SUPPORT */ - -/* Default value if unset */ -#ifndef LWIP_INCLUDED_POLARSSL_MD4 -#define LWIP_INCLUDED_POLARSSL_MD4 0 -#endif /* LWIP_INCLUDED_POLARSSL_MD4 */ -#ifndef LWIP_INCLUDED_POLARSSL_MD5 -#define LWIP_INCLUDED_POLARSSL_MD5 0 -#endif /* LWIP_INCLUDED_POLARSSL_MD5 */ -#ifndef LWIP_INCLUDED_POLARSSL_SHA1 -#define LWIP_INCLUDED_POLARSSL_SHA1 0 -#endif /* LWIP_INCLUDED_POLARSSL_SHA1 */ -#ifndef LWIP_INCLUDED_POLARSSL_DES -#define LWIP_INCLUDED_POLARSSL_DES 0 -#endif /* LWIP_INCLUDED_POLARSSL_DES */ -#ifndef LWIP_INCLUDED_POLARSSL_ARC4 -#define LWIP_INCLUDED_POLARSSL_ARC4 0 -#endif /* LWIP_INCLUDED_POLARSSL_ARC4 */ - -/* - * PPP Timeouts - */ - -/** - * FSM_DEFTIMEOUT: Timeout time in seconds - */ -#ifndef FSM_DEFTIMEOUT -#define FSM_DEFTIMEOUT 6 -#endif - -/** - * FSM_DEFMAXTERMREQS: Maximum Terminate-Request transmissions - */ -#ifndef FSM_DEFMAXTERMREQS -#define FSM_DEFMAXTERMREQS 2 -#endif - -/** - * FSM_DEFMAXCONFREQS: Maximum Configure-Request transmissions - */ -#ifndef FSM_DEFMAXCONFREQS -#define FSM_DEFMAXCONFREQS 10 -#endif - -/** - * FSM_DEFMAXNAKLOOPS: Maximum number of nak loops - */ -#ifndef FSM_DEFMAXNAKLOOPS -#define FSM_DEFMAXNAKLOOPS 5 -#endif - -/** - * UPAP_DEFTIMEOUT: Timeout (seconds) for retransmitting req - */ -#ifndef UPAP_DEFTIMEOUT -#define UPAP_DEFTIMEOUT 6 -#endif - -/** - * UPAP_DEFTRANSMITS: Maximum number of auth-reqs to send - */ -#ifndef UPAP_DEFTRANSMITS -#define UPAP_DEFTRANSMITS 10 -#endif - -#if PPP_SERVER -/** - * UPAP_DEFREQTIME: Time to wait for auth-req from peer - */ -#ifndef UPAP_DEFREQTIME -#define UPAP_DEFREQTIME 30 -#endif -#endif /* PPP_SERVER */ - -/** - * CHAP_DEFTIMEOUT: Timeout (seconds) for retransmitting req - */ -#ifndef CHAP_DEFTIMEOUT -#define CHAP_DEFTIMEOUT 6 -#endif - -/** - * CHAP_DEFTRANSMITS: max # times to send challenge - */ -#ifndef CHAP_DEFTRANSMITS -#define CHAP_DEFTRANSMITS 10 -#endif - -#if PPP_SERVER /** - * CHAP_DEFRECHALLENGETIME: If this option is > 0, rechallenge the peer every n seconds + * @} */ -#ifndef CHAP_DEFRECHALLENGETIME -#define CHAP_DEFRECHALLENGETIME 0 -#endif -#endif /* PPP_SERVER */ - -/** - * EAP_DEFREQTIME: Time to wait for peer request - */ -#ifndef EAP_DEFREQTIME -#define EAP_DEFREQTIME 6 -#endif - -/** - * EAP_DEFALLOWREQ: max # times to accept requests - */ -#ifndef EAP_DEFALLOWREQ -#define EAP_DEFALLOWREQ 10 -#endif - -#if PPP_SERVER -/** - * EAP_DEFTIMEOUT: Timeout (seconds) for rexmit - */ -#ifndef EAP_DEFTIMEOUT -#define EAP_DEFTIMEOUT 6 -#endif - -/** - * EAP_DEFTRANSMITS: max # times to transmit - */ -#ifndef EAP_DEFTRANSMITS -#define EAP_DEFTRANSMITS 10 -#endif -#endif /* PPP_SERVER */ - -/** - * LCP_DEFLOOPBACKFAIL: Default number of times we receive our magic number from the peer - * before deciding the link is looped-back. - */ -#ifndef LCP_DEFLOOPBACKFAIL -#define LCP_DEFLOOPBACKFAIL 10 -#endif - -/** - * LCP_ECHOINTERVAL: Interval in seconds between keepalive echo requests, 0 to disable. - */ -#ifndef LCP_ECHOINTERVAL -#define LCP_ECHOINTERVAL 0 -#endif - -/** - * LCP_MAXECHOFAILS: Number of unanswered echo requests before failure. - */ -#ifndef LCP_MAXECHOFAILS -#define LCP_MAXECHOFAILS 3 -#endif - -/** - * PPP_MAXIDLEFLAG: Max Xmit idle time (in ms) before resend flag char. - */ -#ifndef PPP_MAXIDLEFLAG -#define PPP_MAXIDLEFLAG 100 -#endif - -/** - * PPP Packet sizes - */ - -/** - * PPP_MRU: Default MRU - */ -#ifndef PPP_MRU -#define PPP_MRU 1500 -#endif - -/** - * PPP_DEFMRU: Default MRU to try - */ -#ifndef PPP_DEFMRU -#define PPP_DEFMRU 1500 -#endif - -/** - * PPP_MAXMRU: Normally limit MRU to this (pppd default = 16384) - */ -#ifndef PPP_MAXMRU -#define PPP_MAXMRU 1500 -#endif - -/** - * PPP_MINMRU: No MRUs below this - */ -#ifndef PPP_MINMRU -#define PPP_MINMRU 128 -#endif - -/** - * PPPOL2TP_DEFMRU: Default MTU and MRU for L2TP - * Default = 1500 - PPPoE(6) - PPP Protocol(2) - IPv4 header(20) - UDP Header(8) - * - L2TP Header(6) - HDLC Header(2) - PPP Protocol(2) - MPPE Header(2) - PPP Protocol(2) - */ -#if PPPOL2TP_SUPPORT -#ifndef PPPOL2TP_DEFMRU -#define PPPOL2TP_DEFMRU 1450 -#endif -#endif /* PPPOL2TP_SUPPORT */ - -/** - * MAXNAMELEN: max length of hostname or name for auth - */ -#ifndef MAXNAMELEN -#define MAXNAMELEN 256 -#endif - -/** - * MAXSECRETLEN: max length of password or secret - */ -#ifndef MAXSECRETLEN -#define MAXSECRETLEN 256 -#endif - -#endif /* PPP_SUPPORT */ /* -------------------------------------- ---------- Checksum options ---------- -------------------------------------- */ - +/** + * @defgroup lwip_opts_checksum Checksum + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * LWIP_CHECKSUM_CTRL_PER_NETIF==1: Checksum generation/check can be enabled/disabled * per netif. * ATTENTION: if enabled, the CHECKSUM_GEN_* and CHECKSUM_CHECK_* defines must be enabled! */ -#ifndef LWIP_CHECKSUM_CTRL_PER_NETIF +#if !defined LWIP_CHECKSUM_CTRL_PER_NETIF || defined __DOXYGEN__ #define LWIP_CHECKSUM_CTRL_PER_NETIF 0 #endif /** * CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets. */ -#ifndef CHECKSUM_GEN_IP +#if !defined CHECKSUM_GEN_IP || defined __DOXYGEN__ #define CHECKSUM_GEN_IP 1 #endif /** * CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets. */ -#ifndef CHECKSUM_GEN_UDP +#if !defined CHECKSUM_GEN_UDP || defined __DOXYGEN__ #define CHECKSUM_GEN_UDP 1 #endif /** * CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets. */ -#ifndef CHECKSUM_GEN_TCP +#if !defined CHECKSUM_GEN_TCP || defined __DOXYGEN__ #define CHECKSUM_GEN_TCP 1 #endif /** * CHECKSUM_GEN_ICMP==1: Generate checksums in software for outgoing ICMP packets. */ -#ifndef CHECKSUM_GEN_ICMP +#if !defined CHECKSUM_GEN_ICMP || defined __DOXYGEN__ #define CHECKSUM_GEN_ICMP 1 #endif /** * CHECKSUM_GEN_ICMP6==1: Generate checksums in software for outgoing ICMP6 packets. */ -#ifndef CHECKSUM_GEN_ICMP6 +#if !defined CHECKSUM_GEN_ICMP6 || defined __DOXYGEN__ #define CHECKSUM_GEN_ICMP6 1 #endif /** * CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets. */ -#ifndef CHECKSUM_CHECK_IP +#if !defined CHECKSUM_CHECK_IP || defined __DOXYGEN__ #define CHECKSUM_CHECK_IP 1 #endif /** * CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets. */ -#ifndef CHECKSUM_CHECK_UDP +#if !defined CHECKSUM_CHECK_UDP || defined __DOXYGEN__ #define CHECKSUM_CHECK_UDP 1 #endif /** * CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets. */ -#ifndef CHECKSUM_CHECK_TCP +#if !defined CHECKSUM_CHECK_TCP || defined __DOXYGEN__ #define CHECKSUM_CHECK_TCP 1 #endif /** * CHECKSUM_CHECK_ICMP==1: Check checksums in software for incoming ICMP packets. */ -#ifndef CHECKSUM_CHECK_ICMP +#if !defined CHECKSUM_CHECK_ICMP || defined __DOXYGEN__ #define CHECKSUM_CHECK_ICMP 1 #endif /** * CHECKSUM_CHECK_ICMP6==1: Check checksums in software for incoming ICMPv6 packets */ -#ifndef CHECKSUM_CHECK_ICMP6 +#if !defined CHECKSUM_CHECK_ICMP6 || defined __DOXYGEN__ #define CHECKSUM_CHECK_ICMP6 1 #endif @@ -2440,40 +2145,92 @@ * LWIP_CHECKSUM_ON_COPY==1: Calculate checksum when copying data from * application buffers to pbufs. */ -#ifndef LWIP_CHECKSUM_ON_COPY +#if !defined LWIP_CHECKSUM_ON_COPY || defined __DOXYGEN__ #define LWIP_CHECKSUM_ON_COPY 0 #endif +/** + * @} + */ /* --------------------------------------- ---------- IPv6 options --------------- --------------------------------------- */ +/** + * @defgroup lwip_opts_ipv6 IPv6 + * @ingroup lwip_opts + * @{ + */ /** * LWIP_IPV6==1: Enable IPv6 */ -#ifndef LWIP_IPV6 +#if !defined LWIP_IPV6 || defined __DOXYGEN__ #define LWIP_IPV6 0 #endif /** * LWIP_IPV6_NUM_ADDRESSES: Number of IPv6 addresses per netif. */ -#ifndef LWIP_IPV6_NUM_ADDRESSES +#if !defined LWIP_IPV6_NUM_ADDRESSES || defined __DOXYGEN__ #define LWIP_IPV6_NUM_ADDRESSES 3 #endif /** * LWIP_IPV6_FORWARD==1: Forward IPv6 packets across netifs */ -#ifndef LWIP_IPV6_FORWARD +#if !defined LWIP_IPV6_FORWARD || defined __DOXYGEN__ #define LWIP_IPV6_FORWARD 0 #endif +/** + * LWIP_IPV6_FRAG==1: Fragment outgoing IPv6 packets that are too big. + */ +#if !defined LWIP_IPV6_FRAG || defined __DOXYGEN__ +#define LWIP_IPV6_FRAG 0 +#endif + +/** + * LWIP_IPV6_REASS==1: reassemble incoming IPv6 packets that fragmented + */ +#if !defined LWIP_IPV6_REASS || defined __DOXYGEN__ +#define LWIP_IPV6_REASS (LWIP_IPV6) +#endif + +/** + * LWIP_IPV6_SEND_ROUTER_SOLICIT==1: Send router solicitation messages during + * network startup. + */ +#if !defined LWIP_IPV6_SEND_ROUTER_SOLICIT || defined __DOXYGEN__ +#define LWIP_IPV6_SEND_ROUTER_SOLICIT 1 +#endif + +/** + * LWIP_IPV6_AUTOCONFIG==1: Enable stateless address autoconfiguration as per RFC 4862. + */ +#if !defined LWIP_IPV6_AUTOCONFIG || defined __DOXYGEN__ +#define LWIP_IPV6_AUTOCONFIG (LWIP_IPV6) +#endif + +/** + * LWIP_IPV6_DUP_DETECT_ATTEMPTS=[0..7]: Number of duplicate address detection attempts. + */ +#if !defined LWIP_IPV6_DUP_DETECT_ATTEMPTS || defined __DOXYGEN__ +#define LWIP_IPV6_DUP_DETECT_ATTEMPTS 1 +#endif +/** + * @} + */ + +/** + * @defgroup lwip_opts_icmp6 ICMP6 + * @ingroup lwip_opts_ipv6 + * @{ + */ /** * LWIP_ICMP6==1: Enable ICMPv6 (mandatory per RFC) */ -#ifndef LWIP_ICMP6 +#if !defined LWIP_ICMP6 || defined __DOXYGEN__ #define LWIP_ICMP6 (LWIP_IPV6) #endif @@ -2481,85 +2238,92 @@ * LWIP_ICMP6_DATASIZE: bytes from original packet to send back in * ICMPv6 error messages. */ -#ifndef LWIP_ICMP6_DATASIZE +#if !defined LWIP_ICMP6_DATASIZE || defined __DOXYGEN__ #define LWIP_ICMP6_DATASIZE 8 #endif /** * LWIP_ICMP6_HL: default hop limit for ICMPv6 messages */ -#ifndef LWIP_ICMP6_HL +#if !defined LWIP_ICMP6_HL || defined __DOXYGEN__ #define LWIP_ICMP6_HL 255 #endif +/** + * @} + */ +/** + * @defgroup lwip_opts_mld6 Multicast listener discovery + * @ingroup lwip_opts_ipv6 + * @{ + */ /** * LWIP_IPV6_MLD==1: Enable multicast listener discovery protocol. + * If LWIP_IPV6 is enabled but this setting is disabled, the MAC layer must + * indiscriminately pass all inbound IPv6 multicast traffic to lwIP. */ -#ifndef LWIP_IPV6_MLD +#if !defined LWIP_IPV6_MLD || defined __DOXYGEN__ #define LWIP_IPV6_MLD (LWIP_IPV6) #endif /** - * MEMP_NUM_MLD6_GROUP: Max number of IPv6 multicast that can be joined. + * MEMP_NUM_MLD6_GROUP: Max number of IPv6 multicast groups that can be joined. + * There must be enough groups so that each netif can join the solicited-node + * multicast group for each of its local addresses, plus one for MDNS if + * applicable, plus any number of groups to be joined on UDP sockets. */ -#ifndef MEMP_NUM_MLD6_GROUP +#if !defined MEMP_NUM_MLD6_GROUP || defined __DOXYGEN__ #define MEMP_NUM_MLD6_GROUP 4 #endif - /** - * LWIP_IPV6_FRAG==1: Fragment outgoing IPv6 packets that are too big. + * @} */ -#ifndef LWIP_IPV6_FRAG -#define LWIP_IPV6_FRAG 0 -#endif /** - * LWIP_IPV6_REASS==1: reassemble incoming IPv6 packets that fragmented + * @defgroup lwip_opts_nd6 Neighbor discovery + * @ingroup lwip_opts_ipv6 + * @{ */ -#ifndef LWIP_IPV6_REASS -#define LWIP_IPV6_REASS (LWIP_IPV6) -#endif - /** * LWIP_ND6_QUEUEING==1: queue outgoing IPv6 packets while MAC address * is being resolved. */ -#ifndef LWIP_ND6_QUEUEING +#if !defined LWIP_ND6_QUEUEING || defined __DOXYGEN__ #define LWIP_ND6_QUEUEING (LWIP_IPV6) #endif /** * MEMP_NUM_ND6_QUEUE: Max number of IPv6 packets to queue during MAC resolution. */ -#ifndef MEMP_NUM_ND6_QUEUE +#if !defined MEMP_NUM_ND6_QUEUE || defined __DOXYGEN__ #define MEMP_NUM_ND6_QUEUE 20 #endif /** * LWIP_ND6_NUM_NEIGHBORS: Number of entries in IPv6 neighbor cache */ -#ifndef LWIP_ND6_NUM_NEIGHBORS +#if !defined LWIP_ND6_NUM_NEIGHBORS || defined __DOXYGEN__ #define LWIP_ND6_NUM_NEIGHBORS 10 #endif /** * LWIP_ND6_NUM_DESTINATIONS: number of entries in IPv6 destination cache */ -#ifndef LWIP_ND6_NUM_DESTINATIONS +#if !defined LWIP_ND6_NUM_DESTINATIONS || defined __DOXYGEN__ #define LWIP_ND6_NUM_DESTINATIONS 10 #endif /** * LWIP_ND6_NUM_PREFIXES: number of entries in IPv6 on-link prefixes cache */ -#ifndef LWIP_ND6_NUM_PREFIXES +#if !defined LWIP_ND6_NUM_PREFIXES || defined __DOXYGEN__ #define LWIP_ND6_NUM_PREFIXES 5 #endif /** * LWIP_ND6_NUM_ROUTERS: number of entries in IPv6 default router cache */ -#ifndef LWIP_ND6_NUM_ROUTERS +#if !defined LWIP_ND6_NUM_ROUTERS || defined __DOXYGEN__ #define LWIP_ND6_NUM_ROUTERS 3 #endif @@ -2567,7 +2331,7 @@ * LWIP_ND6_MAX_MULTICAST_SOLICIT: max number of multicast solicit messages to send * (neighbor solicit and router solicit) */ -#ifndef LWIP_ND6_MAX_MULTICAST_SOLICIT +#if !defined LWIP_ND6_MAX_MULTICAST_SOLICIT || defined __DOXYGEN__ #define LWIP_ND6_MAX_MULTICAST_SOLICIT 3 #endif @@ -2575,21 +2339,21 @@ * LWIP_ND6_MAX_UNICAST_SOLICIT: max number of unicast neighbor solicitation messages * to send during neighbor reachability detection. */ -#ifndef LWIP_ND6_MAX_UNICAST_SOLICIT +#if !defined LWIP_ND6_MAX_UNICAST_SOLICIT || defined __DOXYGEN__ #define LWIP_ND6_MAX_UNICAST_SOLICIT 3 #endif /** * Unused: See ND RFC (time in milliseconds). */ -#ifndef LWIP_ND6_MAX_ANYCAST_DELAY_TIME +#if !defined LWIP_ND6_MAX_ANYCAST_DELAY_TIME || defined __DOXYGEN__ #define LWIP_ND6_MAX_ANYCAST_DELAY_TIME 1000 #endif /** * Unused: See ND RFC */ -#ifndef LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT +#if !defined LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT || defined __DOXYGEN__ #define LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT 3 #endif @@ -2597,14 +2361,14 @@ * LWIP_ND6_REACHABLE_TIME: default neighbor reachable time (in milliseconds). * May be updated by router advertisement messages. */ -#ifndef LWIP_ND6_REACHABLE_TIME +#if !defined LWIP_ND6_REACHABLE_TIME || defined __DOXYGEN__ #define LWIP_ND6_REACHABLE_TIME 30000 #endif /** * LWIP_ND6_RETRANS_TIMER: default retransmission timer for solicitation messages */ -#ifndef LWIP_ND6_RETRANS_TIMER +#if !defined LWIP_ND6_RETRANS_TIMER || defined __DOXYGEN__ #define LWIP_ND6_RETRANS_TIMER 1000 #endif @@ -2612,7 +2376,7 @@ * LWIP_ND6_DELAY_FIRST_PROBE_TIME: Delay before first unicast neighbor solicitation * message is sent, during neighbor reachability detection. */ -#ifndef LWIP_ND6_DELAY_FIRST_PROBE_TIME +#if !defined LWIP_ND6_DELAY_FIRST_PROBE_TIME || defined __DOXYGEN__ #define LWIP_ND6_DELAY_FIRST_PROBE_TIME 5000 #endif @@ -2620,45 +2384,35 @@ * LWIP_ND6_ALLOW_RA_UPDATES==1: Allow Router Advertisement messages to update * Reachable time and retransmission timers, and netif MTU. */ -#ifndef LWIP_ND6_ALLOW_RA_UPDATES +#if !defined LWIP_ND6_ALLOW_RA_UPDATES || defined __DOXYGEN__ #define LWIP_ND6_ALLOW_RA_UPDATES 1 #endif -/** - * LWIP_IPV6_SEND_ROUTER_SOLICIT==1: Send router solicitation messages during - * network startup. - */ -#ifndef LWIP_IPV6_SEND_ROUTER_SOLICIT -#define LWIP_IPV6_SEND_ROUTER_SOLICIT 1 -#endif - /** * LWIP_ND6_TCP_REACHABILITY_HINTS==1: Allow TCP to provide Neighbor Discovery * with reachability hints for connected destinations. This helps avoid sending * unicast neighbor solicitation messages. */ -#ifndef LWIP_ND6_TCP_REACHABILITY_HINTS +#if !defined LWIP_ND6_TCP_REACHABILITY_HINTS || defined __DOXYGEN__ #define LWIP_ND6_TCP_REACHABILITY_HINTS 1 #endif /** - * LWIP_IPV6_AUTOCONFIG==1: Enable stateless address autoconfiguration as per RFC 4862. + * LWIP_ND6_RDNSS_MAX_DNS_SERVERS > 0: Use IPv6 Router Advertisement Recursive + * DNS Server Option (as per RFC 6106) to copy a defined maximum number of DNS + * servers to the DNS module. */ -#ifndef LWIP_IPV6_AUTOCONFIG -#define LWIP_IPV6_AUTOCONFIG (LWIP_IPV6) +#if !defined LWIP_ND6_RDNSS_MAX_DNS_SERVERS || defined __DOXYGEN__ +#define LWIP_ND6_RDNSS_MAX_DNS_SERVERS 0 #endif - /** - * LWIP_IPV6_DUP_DETECT_ATTEMPTS: Number of duplicate address detection attempts. + * @} */ -#ifndef LWIP_IPV6_DUP_DETECT_ATTEMPTS -#define LWIP_IPV6_DUP_DETECT_ATTEMPTS 1 -#endif /** * LWIP_IPV6_DHCP6==1: enable DHCPv6 stateful address autoconfiguration. */ -#ifndef LWIP_IPV6_DHCP6 +#if !defined LWIP_IPV6_DHCP6 || defined __DOXYGEN__ #define LWIP_IPV6_DHCP6 0 #endif @@ -2668,7 +2422,44 @@ --------------------------------------- */ -/* Hooks are undefined by default, define them to a function if you need them. */ +/** + * @defgroup lwip_opts_hooks Hooks + * @ingroup lwip_opts_infrastructure + * Hooks are undefined by default, define them to a function if you need them. + * @{ + */ + +/** + * LWIP_HOOK_FILENAME: Custom filename to #include in files that provide hooks. + * Declare your hook function prototypes in there, you may also #include all headers + * providing data types that are need in this file. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_FILENAME "path/to/my/lwip_hooks.h" +#endif + +/** + * LWIP_HOOK_TCP_ISN: + * Hook for generation of the Initial Sequence Number (ISN) for a new TCP + * connection. The default lwIP ISN generation algorithm is very basic and may + * allow for TCP spoofing attacks. This hook provides the means to implement + * the standardized ISN generation algorithm from RFC 6528 (see contrib/adons/tcp_isn), + * or any other desired algorithm as a replacement. + * Called from tcp_connect() and tcp_listen_input() when an ISN is needed for + * a new TCP connection, if TCP support (@ref LWIP_TCP) is enabled.\n + * Signature: u32_t my_hook_tcp_isn(const ip_addr_t* local_ip, u16_t local_port, const ip_addr_t* remote_ip, u16_t remote_port); + * - it may be necessary to use "struct ip_addr" (ip4_addr, ip6_addr) instead of "ip_addr_t" in function declarations\n + * Arguments: + * - local_ip: pointer to the local IP address of the connection + * - local_port: local port number of the connection (host-byte order) + * - remote_ip: pointer to the remote IP address of the connection + * - remote_port: remote port number of the connection (host-byte order)\n + * Return value: + * - the 32-bit Initial Sequence Number to use for the new TCP connection. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_TCP_ISN(local_ip, local_port, remote_ip, remote_port) +#endif /** * LWIP_HOOK_IP4_INPUT(pbuf, input_netif): @@ -2681,6 +2472,9 @@ * If the hook consumed the packet, 'pbuf' is in the responsibility of the hook * (i.e. free it when done). */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_INPUT(pbuf, input_netif) +#endif /** * LWIP_HOOK_IP4_ROUTE(dest): @@ -2689,11 +2483,17 @@ * Returns the destination netif or NULL if no destination netif is found. In * that case, ip_route() continues as normal. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_ROUTE() +#endif /** * LWIP_HOOK_IP4_ROUTE_SRC(dest, src): * - source-based routing for IPv4 (see LWIP_HOOK_IP4_ROUTE(), src may be NULL) */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_ROUTE_SRC(dest, src) +#endif /** * LWIP_HOOK_ETHARP_GET_GW(netif, dest): @@ -2702,11 +2502,14 @@ * - dest: the destination IPv4 address * Returns the IPv4 address of the gateway to handle the specified destination * IPv4 address. If NULL is returned, the netif's default gateway is used. - * The returned address MUST be reachable on the specified netif! + * The returned address MUST be directly reachable on the specified netif! * This function is meant to implement advanced IPv4 routing together with * LWIP_HOOK_IP4_ROUTE(). The actual routing/gateway table implementation is * not part of lwIP but can e.g. be hidden in the netif's state argument. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_ETHARP_GET_GW(netif, dest) +#endif /** * LWIP_HOOK_IP6_INPUT(pbuf, input_netif): @@ -2719,6 +2522,9 @@ * If the hook consumed the packet, 'pbuf' is in the responsibility of the hook * (i.e. free it when done). */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP6_INPUT(pbuf, input_netif) +#endif /** * LWIP_HOOK_IP6_ROUTE(src, dest): @@ -2728,6 +2534,25 @@ * Returns the destination netif or NULL if no destination netif is found. In * that case, ip6_route() continues as normal. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP6_ROUTE(src, dest) +#endif + +/** + * LWIP_HOOK_ND6_GET_GW(netif, dest): + * - called from nd6_get_next_hop_entry() (IPv6) + * - netif: the netif used for sending + * - dest: the destination IPv6 address + * Returns the IPv6 address of the next hop to handle the specified destination + * IPv6 address. If NULL is returned, a NDP-discovered router is used instead. + * The returned address MUST be directly reachable on the specified netif! + * This function is meant to implement advanced IPv6 routing together with + * LWIP_HOOK_IP6_ROUTE(). The actual routing/gateway table implementation is + * not part of lwIP but can e.g. be hidden in the netif's state argument. +*/ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_ND6_GET_GW(netif, dest) +#endif /** * LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr): @@ -2739,176 +2564,212 @@ * - 0: Packet must be dropped. * - != 0: Packet must be accepted. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr) +#endif /** - * LWIP_HOOK_VLAN_SET(netif, eth_hdr, vlan_hdr): - * - called from etharp_raw() and etharp_send_ip() if VLAN support is enabled + * LWIP_HOOK_VLAN_SET: + * Hook can be used to set prio_vid field of vlan_hdr. If you need to store data + * on per-netif basis to implement this callback, see @ref netif_cd. + * Called from ethernet_output() if VLAN support (@ref ETHARP_SUPPORT_VLAN) is enabled.\n + * Signature: s32_t my_hook_vlan_set(struct netif* netif, struct pbuf* pbuf, const struct eth_addr* src, const struct eth_addr* dst, u16_t eth_type);\n + * Arguments: * - netif: struct netif that the packet will be sent through - * - eth_hdr: struct eth_hdr of the packet - * - vlan_hdr: struct eth_vlan_hdr of the packet + * - p: struct pbuf packet to be sent + * - src: source eth address + * - dst: destination eth address + * - eth_type: ethernet type to packet to be sent\n + * + * * Return values: - * - 0: Packet shall not contain VLAN header. - * - != 0: Packet shall contain VLAN header. - * Hook can be used to set prio_vid field of vlan_hdr. + * - <0: Packet shall not contain VLAN header. + * - 0 <= return value <= 0xFFFF: Packet shall contain VLAN header. Return value is prio_vid in host byte order. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_VLAN_SET(netif, p, src, dst, eth_type) +#endif /** * LWIP_HOOK_MEMP_AVAILABLE(memp_t_type): * - called from memp_free() when a memp pool was empty and an item is now available */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_MEMP_AVAILABLE(memp_t_type) +#endif + +/** + * LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(pbuf, netif): + * Called from ethernet_input() when an unknown eth type is encountered. + * Return ERR_OK if packet is accepted, any error code otherwise. + * Payload points to ethernet header! + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(pbuf, netif) +#endif +/** + * @} + */ /* --------------------------------------- ---------- Debugging options ---------- --------------------------------------- */ +/** + * @defgroup lwip_opts_debugmsg Debug messages + * @ingroup lwip_opts_debug + * @{ + */ /** * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is * compared against this value. If it is smaller, then debugging * messages are written. + * @see debugging_levels */ -#ifndef LWIP_DBG_MIN_LEVEL +#if !defined LWIP_DBG_MIN_LEVEL || defined __DOXYGEN__ #define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_ALL #endif /** * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable * debug messages of certain types. + * @see debugging_levels */ -#ifndef LWIP_DBG_TYPES_ON +#if !defined LWIP_DBG_TYPES_ON || defined __DOXYGEN__ #define LWIP_DBG_TYPES_ON LWIP_DBG_ON #endif /** * ETHARP_DEBUG: Enable debugging in etharp.c. */ -#ifndef ETHARP_DEBUG +#if !defined ETHARP_DEBUG || defined __DOXYGEN__ #define ETHARP_DEBUG LWIP_DBG_OFF #endif /** * NETIF_DEBUG: Enable debugging in netif.c. */ -#ifndef NETIF_DEBUG +#if !defined NETIF_DEBUG || defined __DOXYGEN__ #define NETIF_DEBUG LWIP_DBG_OFF #endif /** * PBUF_DEBUG: Enable debugging in pbuf.c. */ -#ifndef PBUF_DEBUG +#if !defined PBUF_DEBUG || defined __DOXYGEN__ #define PBUF_DEBUG LWIP_DBG_OFF #endif /** * API_LIB_DEBUG: Enable debugging in api_lib.c. */ -#ifndef API_LIB_DEBUG +#if !defined API_LIB_DEBUG || defined __DOXYGEN__ #define API_LIB_DEBUG LWIP_DBG_OFF #endif /** * API_MSG_DEBUG: Enable debugging in api_msg.c. */ -#ifndef API_MSG_DEBUG +#if !defined API_MSG_DEBUG || defined __DOXYGEN__ #define API_MSG_DEBUG LWIP_DBG_OFF #endif /** * SOCKETS_DEBUG: Enable debugging in sockets.c. */ -#ifndef SOCKETS_DEBUG +#if !defined SOCKETS_DEBUG || defined __DOXYGEN__ #define SOCKETS_DEBUG LWIP_DBG_OFF #endif /** * ICMP_DEBUG: Enable debugging in icmp.c. */ -#ifndef ICMP_DEBUG +#if !defined ICMP_DEBUG || defined __DOXYGEN__ #define ICMP_DEBUG LWIP_DBG_OFF #endif /** * IGMP_DEBUG: Enable debugging in igmp.c. */ -#ifndef IGMP_DEBUG +#if !defined IGMP_DEBUG || defined __DOXYGEN__ #define IGMP_DEBUG LWIP_DBG_OFF #endif /** * INET_DEBUG: Enable debugging in inet.c. */ -#ifndef INET_DEBUG +#if !defined INET_DEBUG || defined __DOXYGEN__ #define INET_DEBUG LWIP_DBG_OFF #endif /** * IP_DEBUG: Enable debugging for IP. */ -#ifndef IP_DEBUG +#if !defined IP_DEBUG || defined __DOXYGEN__ #define IP_DEBUG LWIP_DBG_OFF #endif /** * IP_REASS_DEBUG: Enable debugging in ip_frag.c for both frag & reass. */ -#ifndef IP_REASS_DEBUG +#if !defined IP_REASS_DEBUG || defined __DOXYGEN__ #define IP_REASS_DEBUG LWIP_DBG_OFF #endif /** * RAW_DEBUG: Enable debugging in raw.c. */ -#ifndef RAW_DEBUG +#if !defined RAW_DEBUG || defined __DOXYGEN__ #define RAW_DEBUG LWIP_DBG_OFF #endif /** * MEM_DEBUG: Enable debugging in mem.c. */ -#ifndef MEM_DEBUG +#if !defined MEM_DEBUG || defined __DOXYGEN__ #define MEM_DEBUG LWIP_DBG_OFF #endif /** * MEMP_DEBUG: Enable debugging in memp.c. */ -#ifndef MEMP_DEBUG +#if !defined MEMP_DEBUG || defined __DOXYGEN__ #define MEMP_DEBUG LWIP_DBG_OFF #endif /** * SYS_DEBUG: Enable debugging in sys.c. */ -#ifndef SYS_DEBUG +#if !defined SYS_DEBUG || defined __DOXYGEN__ #define SYS_DEBUG LWIP_DBG_OFF #endif /** * TIMERS_DEBUG: Enable debugging in timers.c. */ -#ifndef TIMERS_DEBUG +#if !defined TIMERS_DEBUG || defined __DOXYGEN__ #define TIMERS_DEBUG LWIP_DBG_OFF #endif /** * TCP_DEBUG: Enable debugging for TCP. */ -#ifndef TCP_DEBUG +#if !defined TCP_DEBUG || defined __DOXYGEN__ #define TCP_DEBUG LWIP_DBG_OFF #endif /** * TCP_INPUT_DEBUG: Enable debugging in tcp_in.c for incoming debug. */ -#ifndef TCP_INPUT_DEBUG +#if !defined TCP_INPUT_DEBUG || defined __DOXYGEN__ #define TCP_INPUT_DEBUG LWIP_DBG_OFF #endif /** * TCP_FR_DEBUG: Enable debugging in tcp_in.c for fast retransmit. */ -#ifndef TCP_FR_DEBUG +#if !defined TCP_FR_DEBUG || defined __DOXYGEN__ #define TCP_FR_DEBUG LWIP_DBG_OFF #endif @@ -2916,123 +2777,116 @@ * TCP_RTO_DEBUG: Enable debugging in TCP for retransmit * timeout. */ -#ifndef TCP_RTO_DEBUG +#if !defined TCP_RTO_DEBUG || defined __DOXYGEN__ #define TCP_RTO_DEBUG LWIP_DBG_OFF #endif /** * TCP_CWND_DEBUG: Enable debugging for TCP congestion window. */ -#ifndef TCP_CWND_DEBUG +#if !defined TCP_CWND_DEBUG || defined __DOXYGEN__ #define TCP_CWND_DEBUG LWIP_DBG_OFF #endif /** * TCP_WND_DEBUG: Enable debugging in tcp_in.c for window updating. */ -#ifndef TCP_WND_DEBUG +#if !defined TCP_WND_DEBUG || defined __DOXYGEN__ #define TCP_WND_DEBUG LWIP_DBG_OFF #endif /** * TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions. */ -#ifndef TCP_OUTPUT_DEBUG +#if !defined TCP_OUTPUT_DEBUG || defined __DOXYGEN__ #define TCP_OUTPUT_DEBUG LWIP_DBG_OFF #endif /** * TCP_RST_DEBUG: Enable debugging for TCP with the RST message. */ -#ifndef TCP_RST_DEBUG +#if !defined TCP_RST_DEBUG || defined __DOXYGEN__ #define TCP_RST_DEBUG LWIP_DBG_OFF #endif /** * TCP_QLEN_DEBUG: Enable debugging for TCP queue lengths. */ -#ifndef TCP_QLEN_DEBUG +#if !defined TCP_QLEN_DEBUG || defined __DOXYGEN__ #define TCP_QLEN_DEBUG LWIP_DBG_OFF #endif /** * UDP_DEBUG: Enable debugging in UDP. */ -#ifndef UDP_DEBUG +#if !defined UDP_DEBUG || defined __DOXYGEN__ #define UDP_DEBUG LWIP_DBG_OFF #endif /** * TCPIP_DEBUG: Enable debugging in tcpip.c. */ -#ifndef TCPIP_DEBUG +#if !defined TCPIP_DEBUG || defined __DOXYGEN__ #define TCPIP_DEBUG LWIP_DBG_OFF #endif -/** - * PPP_DEBUG: Enable debugging for PPP. - */ -#ifndef PPP_DEBUG -#define PPP_DEBUG LWIP_DBG_OFF -#endif - /** * SLIP_DEBUG: Enable debugging in slipif.c. */ -#ifndef SLIP_DEBUG +#if !defined SLIP_DEBUG || defined __DOXYGEN__ #define SLIP_DEBUG LWIP_DBG_OFF #endif /** * DHCP_DEBUG: Enable debugging in dhcp.c. */ -#ifndef DHCP_DEBUG +#if !defined DHCP_DEBUG || defined __DOXYGEN__ #define DHCP_DEBUG LWIP_DBG_OFF #endif /** * AUTOIP_DEBUG: Enable debugging in autoip.c. */ -#ifndef AUTOIP_DEBUG +#if !defined AUTOIP_DEBUG || defined __DOXYGEN__ #define AUTOIP_DEBUG LWIP_DBG_OFF #endif /** * DNS_DEBUG: Enable debugging for DNS. */ -#ifndef DNS_DEBUG +#if !defined DNS_DEBUG || defined __DOXYGEN__ #define DNS_DEBUG LWIP_DBG_OFF #endif /** * IP6_DEBUG: Enable debugging for IPv6. */ -#ifndef IP6_DEBUG +#if !defined IP6_DEBUG || defined __DOXYGEN__ #define IP6_DEBUG LWIP_DBG_OFF #endif +/** + * @} + */ /* -------------------------------------------------- ---------- Performance tracking options ---------- -------------------------------------------------- */ +/** + * @defgroup lwip_opts_perf Performance + * @ingroup lwip_opts_debug + * @{ + */ /** * LWIP_PERF: Enable performance testing for lwIP * (if enabled, arch/perf.h is included) */ -#ifndef LWIP_PERF +#if !defined LWIP_PERF || defined __DOXYGEN__ #define LWIP_PERF 0 #endif - /** - * ESP_L2_TO_L3_COPY: enable memcpy when receiving packet from L2 + * @} */ -#ifndef ESP_L2_TO_L3_COPY -#define ESP_L2_TO_L3_COPY 0 -#endif - -#ifndef ESP_THREAD_SAFE_DEBUG -#define ESP_THREAD_SAFE_DEBUG 0 -#endif #endif /* LWIP_HDR_OPT_H */ diff --git a/tools/sdk/include/lwip/lwip/pbuf.h b/tools/sdk/include/lwip/lwip/pbuf.h old mode 100755 new mode 100644 index 42146f6fc46..a8f1d951ade --- a/tools/sdk/include/lwip/lwip/pbuf.h +++ b/tools/sdk/include/lwip/lwip/pbuf.h @@ -1,3 +1,8 @@ +/** + * @file + * pbuf API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -47,7 +52,7 @@ extern "C" { * Currently, the pbuf_custom code is only needed for one specific configuration * of IP_FRAG, unless required by external driver/application code. */ #ifndef LWIP_SUPPORT_CUSTOM_PBUF -#define LWIP_SUPPORT_CUSTOM_PBUF ((IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG)) +#define LWIP_SUPPORT_CUSTOM_PBUF ((IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG)) #endif /* @todo: We need a mechanism to prevent wasting memory in every pbuf @@ -60,20 +65,46 @@ extern "C" { #define PBUF_IP_HLEN 20 #endif +/** + * @ingroup pbuf + * Enumeration of pbuf layers + */ typedef enum { + /** Includes spare room for transport layer header, e.g. UDP header. + * Use this if you intend to pass the pbuf to functions like udp_send(). + */ PBUF_TRANSPORT, + /** Includes spare room for IP header. + * Use this if you intend to pass the pbuf to functions like raw_send(). + */ PBUF_IP, + /** Includes spare room for link layer header (ethernet header). + * Use this if you intend to pass the pbuf to functions like ethernet_output(). + * @see PBUF_LINK_HLEN + */ PBUF_LINK, + /** Includes spare room for additional encapsulation header before ethernet + * headers (e.g. 802.11). + * Use this if you intend to pass the pbuf to functions like netif->linkoutput(). + * @see PBUF_LINK_ENCAPSULATION_HLEN + */ PBUF_RAW_TX, + /** Use this for input packets in a netif driver when calling netif->input() + * in the most common case - ethernet-layer netif driver. */ PBUF_RAW } pbuf_layer; +/** + * @ingroup pbuf + * Enumeration of pbuf types + */ typedef enum { /** pbuf data is stored in RAM, used for TX mostly, struct pbuf and its payload are allocated in one piece of contiguous memory (so the first payload byte - can be calculated from struct pbuf) + can be calculated from struct pbuf). pbuf_alloc() allocates PBUF_RAM pbufs as unchained pbufs (although that might - change in future versions) */ + change in future versions). + This should be used for all OUTGOING packets (TX).*/ PBUF_RAM, /** pbuf data is stored in ROM, i.e. struct pbuf and its payload are located in totally different memory areas. Since it points to ROM, payload does not @@ -86,7 +117,9 @@ typedef enum { /** pbuf payload refers to RAM. This one comes from a pool and should be used for RX. Payload can be chained (scatter-gather RX) but like PBUF_RAM, struct pbuf and its payload are allocated in one piece of contiguous memory (so - the first payload byte can be calculated from struct pbuf) */ + the first payload byte can be calculated from struct pbuf). + Don't use this for TX, if the pool becomes empty e.g. because of TCP queuing, + you are unable to receive TCP acks! */ PBUF_POOL } pbuf_type; @@ -105,6 +138,7 @@ typedef enum { /** indicates this pbuf includes a TCP FIN flag */ #define PBUF_FLAG_TCP_FIN 0x20U +/** Main packet buffer struct */ struct pbuf { /** next pbuf in singly linked pbuf chain */ struct pbuf *next; @@ -169,12 +203,11 @@ struct pbuf_custom { }; #endif /* LWIP_SUPPORT_CUSTOM_PBUF */ -#if LWIP_TCP && TCP_QUEUE_OOSEQ /** Define this to 0 to prevent freeing ooseq pbufs when the PBUF_POOL is empty */ #ifndef PBUF_POOL_FREE_OOSEQ #define PBUF_POOL_FREE_OOSEQ 1 #endif /* PBUF_POOL_FREE_OOSEQ */ -#if NO_SYS && PBUF_POOL_FREE_OOSEQ +#if LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ extern volatile u8_t pbuf_free_ooseq_pending; void pbuf_free_ooseq(void); /** When not using sys_check_timeouts(), call PBUF_CHECK_FREE_OOSEQ() @@ -184,8 +217,10 @@ void pbuf_free_ooseq(void); /* pbuf_alloc() reported PBUF_POOL to be empty -> try to free some \ ooseq queued pbufs now */ \ pbuf_free_ooseq(); }}while(0) -#endif /* NO_SYS && PBUF_POOL_FREE_OOSEQ*/ -#endif /* LWIP_TCP && TCP_QUEUE_OOSEQ */ +#else /* LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ */ + /* Otherwise declare an empty PBUF_CHECK_FREE_OOSEQ */ + #define PBUF_CHECK_FREE_OOSEQ() +#endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ*/ /* Initializes the pbuf module. This call is empty for now, but may not be in future. */ #define pbuf_init() @@ -201,12 +236,12 @@ u8_t pbuf_header(struct pbuf *p, s16_t header_size); u8_t pbuf_header_force(struct pbuf *p, s16_t header_size); void pbuf_ref(struct pbuf *p); u8_t pbuf_free(struct pbuf *p); -u8_t pbuf_clen(struct pbuf *p); +u16_t pbuf_clen(const struct pbuf *p); void pbuf_cat(struct pbuf *head, struct pbuf *tail); void pbuf_chain(struct pbuf *head, struct pbuf *tail); struct pbuf *pbuf_dechain(struct pbuf *p); -err_t pbuf_copy(struct pbuf *p_to, struct pbuf *p_from); -u16_t pbuf_copy_partial(struct pbuf *p, void *dataptr, u16_t len, u16_t offset); +err_t pbuf_copy(struct pbuf *p_to, const struct pbuf *p_from); +u16_t pbuf_copy_partial(const struct pbuf *p, void *dataptr, u16_t len, u16_t offset); err_t pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len); err_t pbuf_take_at(struct pbuf *buf, const void *dataptr, u16_t len, u16_t offset); struct pbuf *pbuf_skip(struct pbuf* in, u16_t in_offset, u16_t* out_offset); @@ -219,11 +254,12 @@ err_t pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr, void pbuf_split_64k(struct pbuf *p, struct pbuf **rest); #endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */ -u8_t pbuf_get_at(struct pbuf* p, u16_t offset); +u8_t pbuf_get_at(const struct pbuf* p, u16_t offset); +int pbuf_try_get_at(const struct pbuf* p, u16_t offset); void pbuf_put_at(struct pbuf* p, u16_t offset, u8_t data); -u16_t pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n); -u16_t pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset); -u16_t pbuf_strstr(struct pbuf* p, const char* substr); +u16_t pbuf_memcmp(const struct pbuf* p, u16_t offset, const void* s2, u16_t n); +u16_t pbuf_memfind(const struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset); +u16_t pbuf_strstr(const struct pbuf* p, const char* substr); #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/priv/api_msg.h b/tools/sdk/include/lwip/lwip/priv/api_msg.h old mode 100755 new mode 100644 index 02d191a53cd..bcc0b5019af --- a/tools/sdk/include/lwip/lwip/priv/api_msg.h +++ b/tools/sdk/include/lwip/lwip/priv/api_msg.h @@ -1,3 +1,8 @@ +/** + * @file + * netconn API lwIP internal implementations (do not use in application code) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,29 +43,25 @@ /* Note: Netconn API is always available when sockets are enabled - * sockets are implemented on top of them */ -#include /* for size_t */ - +#include "lwip/arch.h" #include "lwip/ip_addr.h" #include "lwip/err.h" #include "lwip/sys.h" #include "lwip/igmp.h" #include "lwip/api.h" +#include "lwip/priv/tcpip_priv.h" #ifdef __cplusplus extern "C" { #endif #if LWIP_MPU_COMPATIBLE -#define API_MSG_M_DEF(m) m -#define API_MSG_M_DEF_C(t, m) t m #if LWIP_NETCONN_SEM_PER_THREAD #define API_MSG_M_DEF_SEM(m) *m #else #define API_MSG_M_DEF_SEM(m) API_MSG_M_DEF(m) #endif #else /* LWIP_MPU_COMPATIBLE */ -#define API_MSG_M_DEF(m) *m -#define API_MSG_M_DEF_C(t, m) const t * m #define API_MSG_M_DEF_SEM(m) API_MSG_M_DEF(m) #endif /* LWIP_MPU_COMPATIBLE */ @@ -75,7 +76,7 @@ extern "C" { /** This struct includes everything that is necessary to execute a function for a netconn in another thread context (mainly used to process netconns in the tcpip_thread context to be thread safe). */ -struct api_msg_msg { +struct api_msg { /** The netconn which to process - always needed: it includes the semaphore which is used to block the application thread until the function finished. */ struct netconn *conn; @@ -150,16 +151,6 @@ struct api_msg_msg { #endif /* LWIP_NETCONN_SEM_PER_THREAD */ -/** This struct contains a function to execute in another thread context and - a struct api_msg_msg that serves as an argument for this function. - This is passed to tcpip_apimsg to execute functions in tcpip_thread context. */ -struct api_msg { - /** function to execute in tcpip_thread context */ - void (* function)(void *msg); - /** arguments for this function */ - struct api_msg_msg msg; -}; - #if LWIP_DNS /** As lwip_netconn_do_gethostbyname requires more arguments but doesn't require a netconn, it has its own struct (to avoid struct api_msg getting bigger than necessary). @@ -194,35 +185,9 @@ struct dns_api_msg { #endif #endif -#if LWIP_TCPIP_CORE_LOCKING -#ifdef LWIP_DEBUG -#define TCIP_APIMSG_SET_ERR(m, e) (m)->msg.err = e /* catch functions that don't set err */ -#else -#define TCIP_APIMSG_SET_ERR(m, e) -#endif -#if LWIP_NETCONN_SEM_PER_THREAD -#define TCPIP_APIMSG_SET_SEM(m) ((m)->msg.op_completed_sem = LWIP_NETCONN_THREAD_SEM_GET()) -#else -#define TCPIP_APIMSG_SET_SEM(m) -#endif -#define TCPIP_APIMSG_NOERR(m,f) do { \ - TCIP_APIMSG_SET_ERR(m, ERR_VAL); \ - TCPIP_APIMSG_SET_SEM(m); \ - LOCK_TCPIP_CORE(); \ - f(&((m)->msg)); \ - UNLOCK_TCPIP_CORE(); \ -} while(0) -#define TCPIP_APIMSG(m,f,e) do { \ - TCPIP_APIMSG_NOERR(m,f); \ - (e) = (m)->msg.err; \ -} while(0) -#define TCPIP_APIMSG_ACK(m) NETCONN_SET_SAFE_ERR((m)->conn, (m)->err) -#else /* LWIP_TCPIP_CORE_LOCKING */ -#define TCPIP_APIMSG_NOERR(m,f) do { (m)->function = f; tcpip_apimsg(m); } while(0) -#define TCPIP_APIMSG(m,f,e) do { (m)->function = f; (e) = tcpip_apimsg(m); } while(0) -#define TCPIP_APIMSG_ACK(m) do { NETCONN_SET_SAFE_ERR((m)->conn, (m)->err); sys_sem_signal(LWIP_API_MSG_SEM(m)); } while(0) - -#endif /* LWIP_TCPIP_CORE_LOCKING */ +#if LWIP_TCP +extern u8_t netconn_aborted; +#endif /* LWIP_TCP */ void lwip_netconn_do_newconn (void *m); void lwip_netconn_do_delconn (void *m); @@ -232,6 +197,9 @@ void lwip_netconn_do_disconnect (void *m); void lwip_netconn_do_listen (void *m); void lwip_netconn_do_send (void *m); void lwip_netconn_do_recv (void *m); +#if TCP_LISTEN_BACKLOG +void lwip_netconn_do_accepted (void *m); +#endif /* TCP_LISTEN_BACKLOG */ void lwip_netconn_do_write (void *m); void lwip_netconn_do_getaddr (void *m); void lwip_netconn_do_close (void *m); diff --git a/tools/sdk/include/lwip/lwip/priv/memp_priv.h b/tools/sdk/include/lwip/lwip/priv/memp_priv.h old mode 100755 new mode 100644 index abb5ebcf72a..f246061dadf --- a/tools/sdk/include/lwip/lwip/priv/memp_priv.h +++ b/tools/sdk/include/lwip/lwip/priv/memp_priv.h @@ -1,3 +1,8 @@ +/** + * @file + * memory pools lwIP internal implementations (do not use in application code) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,7 +43,7 @@ #ifdef __cplusplus extern "C" { #endif - + #include "lwip/mem.h" #if MEMP_OVERFLOW_CHECK @@ -82,6 +87,7 @@ extern "C" { #endif /* MEMP_OVERFLOW_CHECK */ +#if !MEMP_MEM_MALLOC || MEMP_OVERFLOW_CHECK struct memp { struct memp *next; #if MEMP_OVERFLOW_CHECK @@ -89,8 +95,9 @@ struct memp { int line; #endif /* MEMP_OVERFLOW_CHECK */ }; +#endif /* !MEMP_MEM_MALLOC || MEMP_OVERFLOW_CHECK */ -#if MEM_USE_POOLS +#if MEM_USE_POOLS && MEMP_USE_CUSTOM_POOLS /* Use a helper type to get the start and end of the user "memory pools" for mem_malloc */ typedef enum { /* Get the first (via: @@ -117,9 +124,19 @@ typedef enum { We use this helper type and these defines so we can avoid using const memp_t values */ #define MEMP_POOL_FIRST ((memp_t) MEMP_POOL_HELPER_FIRST) #define MEMP_POOL_LAST ((memp_t) MEMP_POOL_HELPER_LAST) -#endif /* MEM_USE_POOLS */ +#endif /* MEM_USE_POOLS && MEMP_USE_CUSTOM_POOLS */ +/** Memory pool descriptor */ struct memp_desc { +#if defined(LWIP_DEBUG) || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY + /** Textual description */ + const char *desc; +#endif /* LWIP_DEBUG || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY */ +#if MEMP_STATS + /** Statistics */ + struct stats_mem *stats; +#endif + /** Element size */ u16_t size; @@ -127,33 +144,26 @@ struct memp_desc { /** Number of elements */ u16_t num; -#if defined(LWIP_DEBUG) || MEMP_OVERFLOW_CHECK - /** Textual description */ - const char *desc; -#endif /* LWIP_DEBUG || MEMP_OVERFLOW_CHECK */ - - /** Base */ - u8_t *base; + /** Base address */ + u8_t *base; /** First free element of each pool. Elements form a linked list. */ struct memp **tab; #endif /* MEMP_MEM_MALLOC */ }; -#if (ESP_STATS_MEM == 1) -extern uint32_t g_lwip_mem_cnt[MEMP_MAX][2]; -#define ESP_CNT_MEM_MALLOC_INC(type) g_lwip_mem_cnt[type][0]++ -#define ESP_CNT_MEM_FREE_INC(type) g_lwip_mem_cnt[type][1]++ +#if defined(LWIP_DEBUG) || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY +#define DECLARE_LWIP_MEMPOOL_DESC(desc) (desc), #else -#define ESP_CNT_MEM_MALLOC_INC(type) -#define ESP_CNT_MEM_FREE_INC(type) +#define DECLARE_LWIP_MEMPOOL_DESC(desc) #endif - -#ifdef LWIP_DEBUG -#define DECLARE_LWIP_MEMPOOL_DESC(desc) (desc), +#if MEMP_STATS +#define LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(name) static struct stats_mem name; +#define LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(name) &name, #else -#define DECLARE_LWIP_MEMPOOL_DESC(desc) +#define LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(name) +#define LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(name) #endif void memp_init_pool(const struct memp_desc *desc); diff --git a/tools/sdk/include/lwip/lwip/priv/memp_std.h b/tools/sdk/include/lwip/lwip/priv/memp_std.h old mode 100755 new mode 100644 index 4def116d828..ce9fd500312 --- a/tools/sdk/include/lwip/lwip/priv/memp_std.h +++ b/tools/sdk/include/lwip/lwip/priv/memp_std.h @@ -1,3 +1,11 @@ +/** + * @file + * lwIP internal memory pools (do not use in application code) + * This file is deliberately included multiple times: once with empty + * definition of LWIP_MEMPOOL() to handle all includes and multiple times + * to build up various lists of mem pools. + */ + /* * SETUP: Make sure we define everything we will need. * @@ -47,9 +55,9 @@ LWIP_MEMPOOL(TCP_SEG, MEMP_NUM_TCP_SEG, sizeof(struct tcp_seg), #if LWIP_IPV4 && IP_REASSEMBLY LWIP_MEMPOOL(REASSDATA, MEMP_NUM_REASSDATA, sizeof(struct ip_reassdata), "REASSDATA") #endif /* LWIP_IPV4 && IP_REASSEMBLY */ -#if (IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG) +#if (IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG) LWIP_MEMPOOL(FRAG_PBUF, MEMP_NUM_FRAG_PBUF, sizeof(struct pbuf_custom_ref),"FRAG_PBUF") -#endif /* IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ +#endif /* IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF || (LWIP_IPV6 && LWIP_IPV6_FRAG) */ #if LWIP_NETCONN || LWIP_SOCKET LWIP_MEMPOOL(NETBUF, MEMP_NUM_NETBUF, sizeof(struct netbuf), "NETBUF") @@ -83,9 +91,9 @@ LWIP_MEMPOOL(ARP_QUEUE, MEMP_NUM_ARP_QUEUE, sizeof(struct etharp_q_en LWIP_MEMPOOL(IGMP_GROUP, MEMP_NUM_IGMP_GROUP, sizeof(struct igmp_group), "IGMP_GROUP") #endif /* LWIP_IGMP */ -#if (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) /* LWIP_TIMERS */ +#if LWIP_TIMERS && !LWIP_TIMERS_CUSTOM LWIP_MEMPOOL(SYS_TIMEOUT, MEMP_NUM_SYS_TIMEOUT, sizeof(struct sys_timeo), "SYS_TIMEOUT") -#endif /* LWIP_TIMERS */ +#endif /* LWIP_TIMERS && !LWIP_TIMERS_CUSTOM */ #if LWIP_DNS && LWIP_SOCKET LWIP_MEMPOOL(NETDB, MEMP_NUM_NETDB, NETDB_ELEM_SIZE, "NETDB") @@ -94,19 +102,6 @@ LWIP_MEMPOOL(NETDB, MEMP_NUM_NETDB, NETDB_ELEM_SIZE, LWIP_MEMPOOL(LOCALHOSTLIST, MEMP_NUM_LOCALHOSTLIST, LOCALHOSTLIST_ELEM_SIZE, "LOCALHOSTLIST") #endif /* LWIP_DNS && DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ -#if PPP_SUPPORT -LWIP_MEMPOOL(PPP_PCB, MEMP_NUM_PPP_PCB, sizeof(ppp_pcb), "PPP_PCB") -#if PPPOS_SUPPORT -LWIP_MEMPOOL(PPPOS_PCB, MEMP_NUM_PPPOS_INTERFACES, sizeof(pppos_pcb), "PPPOS_PCB") -#endif /* PPPOS_SUPPORT */ -#if PPPOE_SUPPORT -LWIP_MEMPOOL(PPPOE_IF, MEMP_NUM_PPPOE_INTERFACES, sizeof(struct pppoe_softc), "PPPOE_IF") -#endif /* PPPOE_SUPPORT */ -#if PPPOL2TP_SUPPORT -LWIP_MEMPOOL(PPPOL2TP_PCB, MEMP_NUM_PPPOL2TP_INTERFACES, sizeof(pppol2tp_pcb), "PPPOL2TP_PCB") -#endif /* PPPOL2TP_SUPPORT */ -#endif /* PPP_SUPPORT */ - #if LWIP_IPV6 && LWIP_ND6_QUEUEING LWIP_MEMPOOL(ND6_QUEUE, MEMP_NUM_ND6_QUEUE, sizeof(struct nd6_q_entry), "ND6_QUEUE") #endif /* LWIP_IPV6 && LWIP_ND6_QUEUEING */ diff --git a/tools/sdk/include/lwip/lwip/priv/nd6_priv.h b/tools/sdk/include/lwip/lwip/priv/nd6_priv.h new file mode 100644 index 00000000000..4bda0b793a3 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/priv/nd6_priv.h @@ -0,0 +1,144 @@ +/** + * @file + * + * Neighbor discovery and stateless address autoconfiguration for IPv6. + * Aims to be compliant with RFC 4861 (Neighbor discovery) and RFC 4862 + * (Address autoconfiguration). + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ + +#ifndef LWIP_HDR_ND6_PRIV_H +#define LWIP_HDR_ND6_PRIV_H + +#include "lwip/opt.h" + +#if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip6_addr.h" +#include "lwip/netif.h" + + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_ND6_QUEUEING +/** struct for queueing outgoing packets for unknown address + * defined here to be accessed by memp.h + */ +struct nd6_q_entry { + struct nd6_q_entry *next; + struct pbuf *p; +}; +#endif /* LWIP_ND6_QUEUEING */ + +/** Struct for tables. */ +struct nd6_neighbor_cache_entry { + ip6_addr_t next_hop_address; + struct netif *netif; + u8_t lladdr[NETIF_MAX_HWADDR_LEN]; + /*u32_t pmtu;*/ +#if LWIP_ND6_QUEUEING + /** Pointer to queue of pending outgoing packets on this entry. */ + struct nd6_q_entry *q; +#else /* LWIP_ND6_QUEUEING */ + /** Pointer to a single pending outgoing packet on this entry. */ + struct pbuf *q; +#endif /* LWIP_ND6_QUEUEING */ + u8_t state; + u8_t isrouter; + union { + u32_t reachable_time; /* in ms since value may originate from network packet */ + u32_t delay_time; /* ticks (ND6_TMR_INTERVAL) */ + u32_t probes_sent; + u32_t stale_time; /* ticks (ND6_TMR_INTERVAL) */ + } counter; +}; + +struct nd6_destination_cache_entry { + ip6_addr_t destination_addr; + ip6_addr_t next_hop_addr; + u16_t pmtu; + u32_t age; +}; + +struct nd6_prefix_list_entry { + ip6_addr_t prefix; + struct netif *netif; + u32_t invalidation_timer; /* in ms since value may originate from network packet */ +#if LWIP_IPV6_AUTOCONFIG + u8_t flags; +#define ND6_PREFIX_AUTOCONFIG_AUTONOMOUS 0x01 +#define ND6_PREFIX_AUTOCONFIG_ADDRESS_GENERATED 0x02 +#define ND6_PREFIX_AUTOCONFIG_ADDRESS_DUPLICATE 0x04 +#endif /* LWIP_IPV6_AUTOCONFIG */ +}; + +struct nd6_router_list_entry { + struct nd6_neighbor_cache_entry *neighbor_entry; + u32_t invalidation_timer; /* in ms since value may originate from network packet */ + u8_t flags; +}; + +enum nd6_neighbor_cache_entry_state { + ND6_NO_ENTRY = 0, + ND6_INCOMPLETE, + ND6_REACHABLE, + ND6_STALE, + ND6_DELAY, + ND6_PROBE +}; + +/* Router tables. */ +/* @todo make these static? and entries accessible through API? */ +extern struct nd6_neighbor_cache_entry neighbor_cache[]; +extern struct nd6_destination_cache_entry destination_cache[]; +extern struct nd6_prefix_list_entry prefix_list[]; +extern struct nd6_router_list_entry default_router_list[]; + +/* Default values, can be updated by a RA message. */ +extern u32_t reachable_time; +extern u32_t retrans_timer; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_IPV6 */ + +#endif /* LWIP_HDR_ND6_PRIV_H */ diff --git a/tools/sdk/include/lwip/lwip/priv/tcp_priv.h b/tools/sdk/include/lwip/lwip/priv/tcp_priv.h old mode 100755 new mode 100644 index 0c498944b3e..73e8967e47d --- a/tools/sdk/include/lwip/lwip/priv/tcp_priv.h +++ b/tools/sdk/include/lwip/lwip/priv/tcp_priv.h @@ -1,3 +1,8 @@ +/** + * @file + * TCP internal implementations (do not use in application code) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -29,8 +34,8 @@ * Author: Adam Dunkels * */ -#ifndef LWIP_HDR_TCP_IMPL_H -#define LWIP_HDR_TCP_IMPL_H +#ifndef LWIP_HDR_TCP_PRIV_H +#define LWIP_HDR_TCP_PRIV_H #include "lwip/opt.h" @@ -44,6 +49,7 @@ #include "lwip/err.h" #include "lwip/ip6.h" #include "lwip/ip6_addr.h" +#include "lwip/prot/tcp.h" #ifdef __cplusplus extern "C" { @@ -92,7 +98,7 @@ err_t tcp_process_refused_data(struct tcp_pcb *pcb); ((tpcb)->flags & (TF_NODELAY | TF_INFR)) || \ (((tpcb)->unsent != NULL) && (((tpcb)->unsent->next != NULL) || \ ((tpcb)->unsent->len >= (tpcb)->mss))) || \ - ((tcp_sndbuf(tpcb) == 0) || (tcp_sndqueuelen(tpcb) >= TCP_SND_QUEUELEN(tpcb))) \ + ((tcp_sndbuf(tpcb) == 0) || (tcp_sndqueuelen(tpcb) >= TCP_SND_QUEUELEN)) \ ) ? 1 : 0) #define tcp_output_nagle(tpcb) (tcp_do_output_nagle(tpcb) ? tcp_output(tpcb) : ERR_OK) @@ -106,19 +112,6 @@ err_t tcp_process_refused_data(struct tcp_pcb *pcb); #define TCP_SEQ_BETWEEN(a,b,c) ((c)-(b) >= (a)-(b)) #endif #define TCP_SEQ_BETWEEN(a,b,c) (TCP_SEQ_GEQ(a,b) && TCP_SEQ_LEQ(a,c)) -#define TCP_FIN 0x01U -#define TCP_SYN 0x02U -#define TCP_RST 0x04U -#define TCP_PSH 0x08U -#define TCP_ACK 0x10U -#define TCP_URG 0x20U -#define TCP_ECE 0x40U -#define TCP_CWR 0x80U - -#define TCP_FLAGS 0x3fU - -/* Length of the TCP header, excluding options. */ -#define TCP_HLEN 20 #ifndef TCP_TMR_INTERVAL #define TCP_TMR_INTERVAL 250 /* The TCP timer interval in milliseconds. */ @@ -156,38 +149,6 @@ err_t tcp_process_refused_data(struct tcp_pcb *pcb); #define TCP_MAXIDLE TCP_KEEPCNT_DEFAULT * TCP_KEEPINTVL_DEFAULT /* Maximum KEEPALIVE probe time */ -/* Fields are (of course) in network byte order. - * Some fields are converted to host byte order in tcp_input(). - */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct tcp_hdr { - PACK_STRUCT_FIELD(u16_t src); - PACK_STRUCT_FIELD(u16_t dest); - PACK_STRUCT_FIELD(u32_t seqno); - PACK_STRUCT_FIELD(u32_t ackno); - PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags); - PACK_STRUCT_FIELD(u16_t wnd); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u16_t urgp); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define TCPH_HDRLEN(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 12) -#define TCPH_FLAGS(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS) - -#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | TCPH_FLAGS(phdr)) -#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = (((phdr)->_hdrlen_rsvd_flags & PP_HTONS(~TCP_FLAGS)) | htons(flags)) -#define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | (flags)) - -#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | htons(flags)) -#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags & ~htons(flags)) - #define TCP_TCPLEN(seg) ((seg)->len + (((TCPH_FLAGS((seg)->tcphdr) & (TCP_FIN | TCP_SYN)) != 0) ? 1U : 0U)) /** Flags used on input processing, not on pcb->flags @@ -199,7 +160,7 @@ PACK_STRUCT_END #if LWIP_EVENT_API -#define TCP_EVENT_ACCEPT(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ +#define TCP_EVENT_ACCEPT(lpcb,pcb,arg,err,ret) ret = lwip_tcp_event(arg, (pcb),\ LWIP_EVENT_ACCEPT, NULL, 0, err) #define TCP_EVENT_SENT(pcb,space,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_SENT, NULL, space, ERR_OK) @@ -209,17 +170,19 @@ PACK_STRUCT_END LWIP_EVENT_RECV, NULL, 0, ERR_OK) #define TCP_EVENT_CONNECTED(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_CONNECTED, NULL, 0, (err)) -#define TCP_EVENT_POLL(pcb,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ - LWIP_EVENT_POLL, NULL, 0, ERR_OK) -#define TCP_EVENT_ERR(errf,arg,err) lwip_tcp_event((arg), NULL, \ - LWIP_EVENT_ERR, NULL, 0, (err)) +#define TCP_EVENT_POLL(pcb,ret) do { if ((pcb)->state != SYN_RCVD) { \ + ret = lwip_tcp_event((pcb)->callback_arg, (pcb), LWIP_EVENT_POLL, NULL, 0, ERR_OK); \ + } else { \ + ret = ERR_ARG; } } while(0) +#define TCP_EVENT_ERR(last_state,errf,arg,err) do { if (last_state != SYN_RCVD) { \ + lwip_tcp_event((arg), NULL, LWIP_EVENT_ERR, NULL, 0, (err)); } } while(0) #else /* LWIP_EVENT_API */ -#define TCP_EVENT_ACCEPT(pcb,err,ret) \ +#define TCP_EVENT_ACCEPT(lpcb,pcb,arg,err,ret) \ do { \ - if((pcb)->accept != NULL) \ - (ret) = (pcb)->accept((pcb)->callback_arg,(pcb),(err)); \ + if((lpcb)->accept != NULL) \ + (ret) = (lpcb)->accept((arg),(pcb),(err)); \ else (ret) = ERR_ARG; \ } while (0) @@ -262,8 +225,9 @@ PACK_STRUCT_END else (ret) = ERR_OK; \ } while (0) -#define TCP_EVENT_ERR(errf,arg,err) \ +#define TCP_EVENT_ERR(last_state,errf,arg,err) \ do { \ + LWIP_UNUSED_ARG(last_state); \ if((errf) != NULL) \ (errf)((arg),(err)); \ } while (0) @@ -288,7 +252,7 @@ struct tcp_seg { #if TCP_OVERSIZE_DBGCHECK u16_t oversize_left; /* Extra bytes available at the end of the last pbuf in unsent (used for asserting vs. - tcp_pcb.unsent_oversized only) */ + tcp_pcb.unsent_oversize only) */ #endif /* TCP_OVERSIZE_DBGCHECK */ #if TCP_CHECKSUM_ON_COPY u16_t chksum; @@ -329,7 +293,7 @@ struct tcp_seg { (flags & TF_SEG_OPTS_WND_SCALE ? LWIP_TCP_OPT_LEN_WS_OUT : 0) /** This returns a TCP header option for MSS in an u32_t */ -#define TCP_BUILD_MSS_OPTION(mss) htonl(0x02040000 | ((mss) & 0xFFFF)) +#define TCP_BUILD_MSS_OPTION(mss) lwip_htonl(0x02040000 | ((mss) & 0xFFFF)) #if LWIP_WND_SCALE #define TCPWNDSIZE_F U32_F @@ -491,7 +455,7 @@ void tcp_rst(u32_t seqno, u32_t ackno, const ip_addr_t *local_ip, const ip_addr_t *remote_ip, u16_t local_port, u16_t remote_port); -u32_t tcp_next_iss(void); +u32_t tcp_next_iss(struct tcp_pcb *pcb); err_t tcp_keepalive(struct tcp_pcb *pcb); err_t tcp_zero_window_probe(struct tcp_pcb *pcb); @@ -532,9 +496,7 @@ s16_t tcp_pcbs_sane(void); * that a timer is needed (i.e. active- or time-wait-pcb found). */ void tcp_timer_needed(void); -#if LWIP_IPV4 -void tcp_netif_ipv4_addr_changed(const ip4_addr_t* old_addr, const ip4_addr_t* new_addr); -#endif /* LWIP_IPV4 */ +void tcp_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr); #ifdef __cplusplus } @@ -542,4 +504,4 @@ void tcp_netif_ipv4_addr_changed(const ip4_addr_t* old_addr, const ip4_addr_t* n #endif /* LWIP_TCP */ -#endif /* LWIP_HDR_TCP_H */ +#endif /* LWIP_HDR_TCP_PRIV_H */ diff --git a/tools/sdk/include/lwip/lwip/priv/tcpip_priv.h b/tools/sdk/include/lwip/lwip/priv/tcpip_priv.h old mode 100755 new mode 100644 index cc1c54ebb51..630efb14022 --- a/tools/sdk/include/lwip/lwip/priv/tcpip_priv.h +++ b/tools/sdk/include/lwip/lwip/priv/tcpip_priv.h @@ -1,3 +1,8 @@ +/** + * @file + * TCPIP API internal implementations (do not use in application code) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,91 +43,79 @@ #include "lwip/tcpip.h" #include "lwip/sys.h" -#include "lwip/timers.h" +#include "lwip/timeouts.h" #ifdef __cplusplus extern "C" { #endif - + struct pbuf; struct netif; -/** Define this to something that triggers a watchdog. This is called from - * tcpip_thread after processing a message. */ -#ifndef LWIP_TCPIP_THREAD_ALIVE -#define LWIP_TCPIP_THREAD_ALIVE() -#endif - -#if LWIP_TCPIP_CORE_LOCKING -/** The global semaphore to lock the stack. */ -extern sys_mutex_t lock_tcpip_core; -#define LOCK_TCPIP_CORE() sys_mutex_lock(&lock_tcpip_core) -#define UNLOCK_TCPIP_CORE() sys_mutex_unlock(&lock_tcpip_core) -#else /* LWIP_TCPIP_CORE_LOCKING */ -#define LOCK_TCPIP_CORE() -#define UNLOCK_TCPIP_CORE() -#endif /* LWIP_TCPIP_CORE_LOCKING */ - #if LWIP_MPU_COMPATIBLE #define API_VAR_REF(name) (*(name)) #define API_VAR_DECLARE(type, name) type * name -#define API_VAR_ALLOC(type, pool, name) do { \ +#define API_VAR_ALLOC(type, pool, name, errorval) do { \ name = (type *)memp_malloc(pool); \ if (name == NULL) { \ - return ERR_MEM; \ + return errorval; \ } \ } while(0) -#define API_VAR_ALLOC_DONTFAIL(type, pool, name) do { \ - name = (type *)memp_malloc(pool); \ - LWIP_ASSERT("pool empty", name != NULL); \ +#define API_VAR_ALLOC_POOL(type, pool, name, errorval) do { \ + name = (type *)LWIP_MEMPOOL_ALLOC(pool); \ + if (name == NULL) { \ + return errorval; \ + } \ } while(0) #define API_VAR_FREE(pool, name) memp_free(pool, name) -#define API_EXPR_REF(expr) &(expr) +#define API_VAR_FREE_POOL(pool, name) LWIP_MEMPOOL_FREE(pool, name) +#define API_EXPR_REF(expr) (&(expr)) #if LWIP_NETCONN_SEM_PER_THREAD #define API_EXPR_REF_SEM(expr) (expr) #else #define API_EXPR_REF_SEM(expr) API_EXPR_REF(expr) #endif #define API_EXPR_DEREF(expr) expr +#define API_MSG_M_DEF(m) m +#define API_MSG_M_DEF_C(t, m) t m #else /* LWIP_MPU_COMPATIBLE */ #define API_VAR_REF(name) name #define API_VAR_DECLARE(type, name) type name -#define API_VAR_ALLOC(type, pool, name) -#define API_VAR_ALLOC_DONTFAIL(type, pool, name) +#define API_VAR_ALLOC(type, pool, name, errorval) +#define API_VAR_ALLOC_POOL(type, pool, name, errorval) #define API_VAR_FREE(pool, name) +#define API_VAR_FREE_POOL(pool, name) #define API_EXPR_REF(expr) expr #define API_EXPR_REF_SEM(expr) API_EXPR_REF(expr) -#define API_EXPR_DEREF(expr) *(expr) +#define API_EXPR_DEREF(expr) (*(expr)) +#define API_MSG_M_DEF(m) *m +#define API_MSG_M_DEF_C(t, m) const t * m #endif /* LWIP_MPU_COMPATIBLE */ -#if !LWIP_TCPIP_CORE_LOCKING -err_t tcpip_send_api_msg(tcpip_callback_fn fn, void *apimsg, sys_sem_t* sem); -#endif /* !LWIP_TCPIP_CORE_LOCKING */ +err_t tcpip_send_msg_wait_sem(tcpip_callback_fn fn, void *apimsg, sys_sem_t* sem); -struct tcpip_api_call; -typedef err_t (*tcpip_api_call_fn)(struct tcpip_api_call* call); -struct tcpip_api_call +struct tcpip_api_call_data { - tcpip_api_call_fn function; #if !LWIP_TCPIP_CORE_LOCKING -#if LWIP_NETCONN_SEM_PER_THREAD - sys_sem_t *sem; -#else /* LWIP_NETCONN_SEM_PER_THREAD */ + err_t err; +#if !LWIP_NETCONN_SEM_PER_THREAD sys_sem_t sem; #endif /* LWIP_NETCONN_SEM_PER_THREAD */ - err_t err; +#else /* !LWIP_TCPIP_CORE_LOCKING */ + u8_t dummy; /* avoid empty struct :-( */ #endif /* !LWIP_TCPIP_CORE_LOCKING */ }; -err_t tcpip_api_call(tcpip_api_call_fn fn, struct tcpip_api_call *call); +typedef err_t (*tcpip_api_call_fn)(struct tcpip_api_call_data* call); +err_t tcpip_api_call(tcpip_api_call_fn fn, struct tcpip_api_call_data *call); enum tcpip_msg_type { TCPIP_MSG_API, TCPIP_MSG_API_CALL, TCPIP_MSG_INPKT, -#if LWIP_TCPIP_TIMEOUT +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS TCPIP_MSG_TIMEOUT, TCPIP_MSG_UNTIMEOUT, -#endif /* LWIP_TCPIP_TIMEOUT */ +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ TCPIP_MSG_CALLBACK, TCPIP_MSG_CALLBACK_STATIC }; @@ -133,8 +126,12 @@ struct tcpip_msg { struct { tcpip_callback_fn function; void* msg; - } api; - struct tcpip_api_call *api_call; + } api_msg; + struct { + tcpip_api_call_fn function; + struct tcpip_api_call_data *arg; + sys_sem_t *sem; + } api_call; struct { struct pbuf *p; struct netif *netif; @@ -144,13 +141,13 @@ struct tcpip_msg { tcpip_callback_fn function; void *ctx; } cb; -#if LWIP_TCPIP_TIMEOUT +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS struct { u32_t msecs; sys_timeout_handler h; void *arg; } tmo; -#endif /* LWIP_TCPIP_TIMEOUT */ +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ } msg; }; diff --git a/tools/sdk/include/lwip/lwip/prot/autoip.h b/tools/sdk/include/lwip/lwip/prot/autoip.h new file mode 100644 index 00000000000..96f93f57809 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/autoip.h @@ -0,0 +1,83 @@ +/** + * @file + * AutoIP protocol definitions + */ + +/* + * + * Copyright (c) 2007 Dominik Spies + * All rights reserved. + * + * 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. + * + * Author: Dominik Spies + * + * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform + * with RFC 3927. + * + */ + +#ifndef LWIP_HDR_PROT_AUTOIP_H +#define LWIP_HDR_PROT_AUTOIP_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* 169.254.0.0 */ +#define AUTOIP_NET 0xA9FE0000 +/* 169.254.1.0 */ +#define AUTOIP_RANGE_START (AUTOIP_NET | 0x0100) +/* 169.254.254.255 */ +#define AUTOIP_RANGE_END (AUTOIP_NET | 0xFEFF) + +/* RFC 3927 Constants */ +#define PROBE_WAIT 1 /* second (initial random delay) */ +#define PROBE_MIN 1 /* second (minimum delay till repeated probe) */ +#define PROBE_MAX 2 /* seconds (maximum delay till repeated probe) */ +#define PROBE_NUM 3 /* (number of probe packets) */ +#define ANNOUNCE_NUM 2 /* (number of announcement packets) */ +#define ANNOUNCE_INTERVAL 2 /* seconds (time between announcement packets) */ +#define ANNOUNCE_WAIT 2 /* seconds (delay before announcing) */ +#if ESP_LWIP +#define MAX_CONFLICTS LWIP_AUTOIP_MAX_CONFLICTS /* (max conflicts before rate limiting) */ +#define RATE_LIMIT_INTERVAL LWIP_AUTOIP_RATE_LIMIT_INTERVAL /* seconds (delay between successive attempts) */ +#else +#define MAX_CONFLICTS 10 /* (max conflicts before rate limiting) */ +#define RATE_LIMIT_INTERVAL 60 /* seconds (delay between successive attempts) */ +#endif +#define DEFEND_INTERVAL 10 /* seconds (min. wait between defensive ARPs) */ + +/* AutoIP client states */ +typedef enum { + AUTOIP_STATE_OFF = 0, + AUTOIP_STATE_PROBING = 1, + AUTOIP_STATE_ANNOUNCING = 2, + AUTOIP_STATE_BOUND = 3 +} autoip_state_enum_t; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_AUTOIP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/dhcp.h b/tools/sdk/include/lwip/lwip/prot/dhcp.h new file mode 100644 index 00000000000..036a33a895d --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/dhcp.h @@ -0,0 +1,195 @@ +/** + * @file + * DHCP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Leon Woestenberg + * Copyright (c) 2001-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Leon Woestenberg + * + */ +#ifndef LWIP_HDR_PROT_DHCP_H +#define LWIP_HDR_PROT_DHCP_H + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define DHCP_CLIENT_PORT 68 +#define DHCP_SERVER_PORT 67 + + + /* DHCP message item offsets and length */ +#define DHCP_CHADDR_LEN 16U +#define DHCP_SNAME_OFS 44U +#define DHCP_SNAME_LEN 64U +#define DHCP_FILE_OFS 108U +#define DHCP_FILE_LEN 128U +#define DHCP_MSG_LEN 236U +#define DHCP_OPTIONS_OFS (DHCP_MSG_LEN + 4U) /* 4 byte: cookie */ + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** minimum set of fields of any DHCP message */ +struct dhcp_msg +{ + PACK_STRUCT_FLD_8(u8_t op); + PACK_STRUCT_FLD_8(u8_t htype); + PACK_STRUCT_FLD_8(u8_t hlen); + PACK_STRUCT_FLD_8(u8_t hops); + PACK_STRUCT_FIELD(u32_t xid); + PACK_STRUCT_FIELD(u16_t secs); + PACK_STRUCT_FIELD(u16_t flags); + PACK_STRUCT_FLD_S(ip4_addr_p_t ciaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t yiaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t siaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t giaddr); + PACK_STRUCT_FLD_8(u8_t chaddr[DHCP_CHADDR_LEN]); + PACK_STRUCT_FLD_8(u8_t sname[DHCP_SNAME_LEN]); + PACK_STRUCT_FLD_8(u8_t file[DHCP_FILE_LEN]); + PACK_STRUCT_FIELD(u32_t cookie); +#define DHCP_MIN_OPTIONS_LEN 68U +/** make sure user does not configure this too small */ +#if ((defined(DHCP_OPTIONS_LEN)) && (DHCP_OPTIONS_LEN < DHCP_MIN_OPTIONS_LEN)) +# undef DHCP_OPTIONS_LEN +#endif +/** allow this to be configured in lwipopts.h, but not too small */ +#if (!defined(DHCP_OPTIONS_LEN)) +/** set this to be sufficient for your options in outgoing DHCP msgs */ +# define DHCP_OPTIONS_LEN DHCP_MIN_OPTIONS_LEN +#endif + PACK_STRUCT_FLD_8(u8_t options[DHCP_OPTIONS_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + + +/* DHCP client states */ +typedef enum { + DHCP_STATE_OFF = 0, + DHCP_STATE_REQUESTING = 1, + DHCP_STATE_INIT = 2, + DHCP_STATE_REBOOTING = 3, + DHCP_STATE_REBINDING = 4, + DHCP_STATE_RENEWING = 5, + DHCP_STATE_SELECTING = 6, + DHCP_STATE_INFORMING = 7, + DHCP_STATE_CHECKING = 8, + DHCP_STATE_PERMANENT = 9, /* not yet implemented */ + DHCP_STATE_BOUND = 10, + DHCP_STATE_RELEASING = 11, /* not yet implemented */ + DHCP_STATE_BACKING_OFF = 12 +} dhcp_state_enum_t; + +/* DHCP op codes */ +#define DHCP_BOOTREQUEST 1 +#define DHCP_BOOTREPLY 2 + +/* DHCP message types */ +#define DHCP_DISCOVER 1 +#define DHCP_OFFER 2 +#define DHCP_REQUEST 3 +#define DHCP_DECLINE 4 +#define DHCP_ACK 5 +#define DHCP_NAK 6 +#define DHCP_RELEASE 7 +#define DHCP_INFORM 8 + +/** DHCP hardware type, currently only ethernet is supported */ +#define DHCP_HTYPE_ETH 1 + +#define DHCP_MAGIC_COOKIE 0x63825363UL + +/* This is a list of options for BOOTP and DHCP, see RFC 2132 for descriptions */ + +/* BootP options */ +#define DHCP_OPTION_PAD 0 +#define DHCP_OPTION_SUBNET_MASK 1 /* RFC 2132 3.3 */ +#define DHCP_OPTION_ROUTER 3 +#define DHCP_OPTION_DNS_SERVER 6 +#define DHCP_OPTION_HOSTNAME 12 +#define DHCP_OPTION_IP_TTL 23 +#define DHCP_OPTION_MTU 26 +#define DHCP_OPTION_BROADCAST 28 +#define DHCP_OPTION_TCP_TTL 37 +#define DHCP_OPTION_NTP 42 +#define DHCP_OPTION_END 255 + +#if ESP_LWIP +/**add options for support more router by liuHan**/ +#define DHCP_OPTION_DOMAIN_NAME 15 +#define DHCP_OPTION_PRD 31 +#define DHCP_OPTION_STATIC_ROUTER 33 +#define DHCP_OPTION_VSN 43 +#define DHCP_OPTION_NB_TINS 44 +#define DHCP_OPTION_NB_TINT 46 +#define DHCP_OPTION_NB_TIS 47 +#define DHCP_OPTION_CLASSLESS_STATIC_ROUTER 121 +#endif + +/* DHCP options */ +#define DHCP_OPTION_REQUESTED_IP 50 /* RFC 2132 9.1, requested IP address */ +#define DHCP_OPTION_LEASE_TIME 51 /* RFC 2132 9.2, time in seconds, in 4 bytes */ +#define DHCP_OPTION_OVERLOAD 52 /* RFC2132 9.3, use file and/or sname field for options */ + +#define DHCP_OPTION_MESSAGE_TYPE 53 /* RFC 2132 9.6, important for DHCP */ +#define DHCP_OPTION_MESSAGE_TYPE_LEN 1 + +#define DHCP_OPTION_SERVER_ID 54 /* RFC 2132 9.7, server IP address */ +#define DHCP_OPTION_PARAMETER_REQUEST_LIST 55 /* RFC 2132 9.8, requested option types */ + +#define DHCP_OPTION_MAX_MSG_SIZE 57 /* RFC 2132 9.10, message size accepted >= 576 */ +#define DHCP_OPTION_MAX_MSG_SIZE_LEN 2 + +#define DHCP_OPTION_T1 58 /* T1 renewal time */ +#define DHCP_OPTION_T2 59 /* T2 rebinding time */ +#define DHCP_OPTION_US 60 +#define DHCP_OPTION_CLIENT_ID 61 +#define DHCP_OPTION_TFTP_SERVERNAME 66 +#define DHCP_OPTION_BOOTFILE 67 + +/* possible combinations of overloading the file and sname fields with options */ +#define DHCP_OVERLOAD_NONE 0 +#define DHCP_OVERLOAD_FILE 1 +#define DHCP_OVERLOAD_SNAME 2 +#define DHCP_OVERLOAD_SNAME_FILE 3 + + +#ifdef __cplusplus +} +#endif + +#endif /*LWIP_HDR_PROT_DHCP_H*/ diff --git a/tools/sdk/include/lwip/lwip/prot/dns.h b/tools/sdk/include/lwip/lwip/prot/dns.h new file mode 100644 index 00000000000..94782d6e9c1 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/dns.h @@ -0,0 +1,140 @@ +/** + * @file + * DNS - host name to IP address resolver. + */ + +/* + * Port to lwIP from uIP + * by Jim Pettinato April 2007 + * + * security fixes and more by Simon Goldschmidt + * + * uIP version Copyright (c) 2002-2003, Adam Dunkels. + * All rights reserved. + * + * 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. + */ + +#ifndef LWIP_HDR_PROT_DNS_H +#define LWIP_HDR_PROT_DNS_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** DNS server port address */ +#ifndef DNS_SERVER_PORT +#define DNS_SERVER_PORT 53 +#endif + +/* DNS field TYPE used for "Resource Records" */ +#define DNS_RRTYPE_A 1 /* a host address */ +#define DNS_RRTYPE_NS 2 /* an authoritative name server */ +#define DNS_RRTYPE_MD 3 /* a mail destination (Obsolete - use MX) */ +#define DNS_RRTYPE_MF 4 /* a mail forwarder (Obsolete - use MX) */ +#define DNS_RRTYPE_CNAME 5 /* the canonical name for an alias */ +#define DNS_RRTYPE_SOA 6 /* marks the start of a zone of authority */ +#define DNS_RRTYPE_MB 7 /* a mailbox domain name (EXPERIMENTAL) */ +#define DNS_RRTYPE_MG 8 /* a mail group member (EXPERIMENTAL) */ +#define DNS_RRTYPE_MR 9 /* a mail rename domain name (EXPERIMENTAL) */ +#define DNS_RRTYPE_NULL 10 /* a null RR (EXPERIMENTAL) */ +#define DNS_RRTYPE_WKS 11 /* a well known service description */ +#define DNS_RRTYPE_PTR 12 /* a domain name pointer */ +#define DNS_RRTYPE_HINFO 13 /* host information */ +#define DNS_RRTYPE_MINFO 14 /* mailbox or mail list information */ +#define DNS_RRTYPE_MX 15 /* mail exchange */ +#define DNS_RRTYPE_TXT 16 /* text strings */ +#define DNS_RRTYPE_AAAA 28 /* IPv6 address */ +#define DNS_RRTYPE_SRV 33 /* service location */ +#define DNS_RRTYPE_ANY 255 /* any type */ + +/* DNS field CLASS used for "Resource Records" */ +#define DNS_RRCLASS_IN 1 /* the Internet */ +#define DNS_RRCLASS_CS 2 /* the CSNET class (Obsolete - used only for examples in some obsolete RFCs) */ +#define DNS_RRCLASS_CH 3 /* the CHAOS class */ +#define DNS_RRCLASS_HS 4 /* Hesiod [Dyer 87] */ +#define DNS_RRCLASS_ANY 255 /* any class */ +#define DNS_RRCLASS_FLUSH 0x800 /* Flush bit */ + +/* DNS protocol flags */ +#define DNS_FLAG1_RESPONSE 0x80 +#define DNS_FLAG1_OPCODE_STATUS 0x10 +#define DNS_FLAG1_OPCODE_INVERSE 0x08 +#define DNS_FLAG1_OPCODE_STANDARD 0x00 +#define DNS_FLAG1_AUTHORATIVE 0x04 +#define DNS_FLAG1_TRUNC 0x02 +#define DNS_FLAG1_RD 0x01 +#define DNS_FLAG2_RA 0x80 +#define DNS_FLAG2_ERR_MASK 0x0f +#define DNS_FLAG2_ERR_NONE 0x00 +#define DNS_FLAG2_ERR_NAME 0x03 + +#define DNS_HDR_GET_OPCODE(hdr) ((((hdr)->flags1) >> 3) & 0xF) + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** DNS message header */ +struct dns_hdr { + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FLD_8(u8_t flags1); + PACK_STRUCT_FLD_8(u8_t flags2); + PACK_STRUCT_FIELD(u16_t numquestions); + PACK_STRUCT_FIELD(u16_t numanswers); + PACK_STRUCT_FIELD(u16_t numauthrr); + PACK_STRUCT_FIELD(u16_t numextrarr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +#define SIZEOF_DNS_HDR 12 + + +/* Multicast DNS definitions */ + +/** UDP port for multicast DNS queries */ +#ifndef DNS_MQUERY_PORT +#define DNS_MQUERY_PORT 5353 +#endif + +/* IPv4 group for multicast DNS queries: 224.0.0.251 */ +#ifndef DNS_MQUERY_IPV4_GROUP_INIT +#define DNS_MQUERY_IPV4_GROUP_INIT IPADDR4_INIT_BYTES(224,0,0,251) +#endif + +/* IPv6 group for multicast DNS queries: FF02::FB */ +#ifndef DNS_MQUERY_IPV6_GROUP_INIT +#define DNS_MQUERY_IPV6_GROUP_INIT IPADDR6_INIT_HOST(0xFF020000,0,0,0xFB) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_DNS_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/etharp.h b/tools/sdk/include/lwip/lwip/prot/etharp.h new file mode 100644 index 00000000000..ec78305b822 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/etharp.h @@ -0,0 +1,91 @@ +/** + * @file + * ARP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ETHARP_H +#define LWIP_HDR_PROT_ETHARP_H + +#include "lwip/arch.h" +#include "lwip/prot/ethernet.h" +#include "lwip/ip4_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef ETHARP_HWADDR_LEN +#define ETHARP_HWADDR_LEN ETH_HWADDR_LEN +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** the ARP message, see RFC 826 ("Packet format") */ +struct etharp_hdr { + PACK_STRUCT_FIELD(u16_t hwtype); + PACK_STRUCT_FIELD(u16_t proto); + PACK_STRUCT_FLD_8(u8_t hwlen); + PACK_STRUCT_FLD_8(u8_t protolen); + PACK_STRUCT_FIELD(u16_t opcode); + PACK_STRUCT_FLD_S(struct eth_addr shwaddr); + PACK_STRUCT_FLD_S(struct ip4_addr2 sipaddr); + PACK_STRUCT_FLD_S(struct eth_addr dhwaddr); + PACK_STRUCT_FLD_S(struct ip4_addr2 dipaddr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_ETHARP_HDR 28 + +/* ARP hwtype values */ +enum etharp_hwtype { + HWTYPE_ETHERNET = 1 + /* others not used */ +}; + +/* ARP message types (opcodes) */ +enum etharp_opcode { + ARP_REQUEST = 1, + ARP_REPLY = 2 +}; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ETHARP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/ethernet.h b/tools/sdk/include/lwip/lwip/prot/ethernet.h new file mode 100644 index 00000000000..e4baa29dc4d --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/ethernet.h @@ -0,0 +1,170 @@ +/** + * @file + * Ethernet protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ETHERNET_H +#define LWIP_HDR_PROT_ETHERNET_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef ETH_HWADDR_LEN +#ifdef ETHARP_HWADDR_LEN +#define ETH_HWADDR_LEN ETHARP_HWADDR_LEN /* compatibility mode */ +#else +#define ETH_HWADDR_LEN 6 +#endif +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct eth_addr { + PACK_STRUCT_FLD_8(u8_t addr[ETH_HWADDR_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** Ethernet header */ +struct eth_hdr { +#if ETH_PAD_SIZE + PACK_STRUCT_FLD_8(u8_t padding[ETH_PAD_SIZE]); +#endif + PACK_STRUCT_FLD_S(struct eth_addr dest); + PACK_STRUCT_FLD_S(struct eth_addr src); + PACK_STRUCT_FIELD(u16_t type); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_ETH_HDR (14 + ETH_PAD_SIZE) + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** VLAN header inserted between ethernet header and payload + * if 'type' in ethernet header is ETHTYPE_VLAN. + * See IEEE802.Q */ +struct eth_vlan_hdr { + PACK_STRUCT_FIELD(u16_t prio_vid); + PACK_STRUCT_FIELD(u16_t tpid); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_VLAN_HDR 4 +#define VLAN_ID(vlan_hdr) (lwip_htons((vlan_hdr)->prio_vid) & 0xFFF) + +/** + * @ingroup ethernet + * A list of often ethtypes (although lwIP does not use all of them): */ +enum eth_type { + /** Internet protocol v4 */ + ETHTYPE_IP = 0x0800U, + /** Address resolution protocol */ + ETHTYPE_ARP = 0x0806U, + /** Wake on lan */ + ETHTYPE_WOL = 0x0842U, + /** RARP */ + ETHTYPE_RARP = 0x8035U, + /** Virtual local area network */ + ETHTYPE_VLAN = 0x8100U, + /** Internet protocol v6 */ + ETHTYPE_IPV6 = 0x86DDU, + /** PPP Over Ethernet Discovery Stage */ + ETHTYPE_PPPOEDISC = 0x8863U, + /** PPP Over Ethernet Session Stage */ + ETHTYPE_PPPOE = 0x8864U, + /** Jumbo Frames */ + ETHTYPE_JUMBO = 0x8870U, + /** Process field network */ + ETHTYPE_PROFINET = 0x8892U, + /** Ethernet for control automation technology */ + ETHTYPE_ETHERCAT = 0x88A4U, + /** Link layer discovery protocol */ + ETHTYPE_LLDP = 0x88CCU, + /** Serial real-time communication system */ + ETHTYPE_SERCOS = 0x88CDU, + /** Media redundancy protocol */ + ETHTYPE_MRP = 0x88E3U, + /** Precision time protocol */ + ETHTYPE_PTP = 0x88F7U, + /** Q-in-Q, 802.1ad */ + ETHTYPE_QINQ = 0x9100U +}; + +/** The 24-bit IANA IPv4-multicast OUI is 01-00-5e: */ +#define LL_IP4_MULTICAST_ADDR_0 0x01 +#define LL_IP4_MULTICAST_ADDR_1 0x00 +#define LL_IP4_MULTICAST_ADDR_2 0x5e + +/** IPv6 multicast uses this prefix */ +#define LL_IP6_MULTICAST_ADDR_0 0x33 +#define LL_IP6_MULTICAST_ADDR_1 0x33 + +/** MEMCPY-like macro to copy to/from struct eth_addr's that are local variables + * or known to be 32-bit aligned within the protocol header. */ +#ifndef ETHADDR32_COPY +#define ETHADDR32_COPY(dst, src) SMEMCPY(dst, src, ETH_HWADDR_LEN) +#endif + +/** MEMCPY-like macro to copy to/from struct eth_addr's that are no local + * variables and known to be 16-bit aligned within the protocol header. */ +#ifndef ETHADDR16_COPY +#define ETHADDR16_COPY(dst, src) SMEMCPY(dst, src, ETH_HWADDR_LEN) +#endif + +#define eth_addr_cmp(addr1, addr2) (memcmp((addr1)->addr, (addr2)->addr, ETH_HWADDR_LEN) == 0) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ETHERNET_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/icmp.h b/tools/sdk/include/lwip/lwip/prot/icmp.h new file mode 100644 index 00000000000..7d19385c729 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/icmp.h @@ -0,0 +1,91 @@ +/** + * @file + * ICMP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ICMP_H +#define LWIP_HDR_PROT_ICMP_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ICMP_ER 0 /* echo reply */ +#define ICMP_DUR 3 /* destination unreachable */ +#define ICMP_SQ 4 /* source quench */ +#define ICMP_RD 5 /* redirect */ +#define ICMP_ECHO 8 /* echo */ +#define ICMP_TE 11 /* time exceeded */ +#define ICMP_PP 12 /* parameter problem */ +#define ICMP_TS 13 /* timestamp */ +#define ICMP_TSR 14 /* timestamp reply */ +#define ICMP_IRQ 15 /* information request */ +#define ICMP_IR 16 /* information reply */ +#define ICMP_AM 17 /* address mask request */ +#define ICMP_AMR 18 /* address mask reply */ + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +/** This is the standard ICMP header only that the u32_t data + * is split to two u16_t like ICMP echo needs it. + * This header is also used for other ICMP types that do not + * use the data part. + */ +PACK_STRUCT_BEGIN +struct icmp_echo_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FIELD(u16_t seqno); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Compatibility defines, old versions used to combine type and code to an u16_t */ +#define ICMPH_TYPE(hdr) ((hdr)->type) +#define ICMPH_CODE(hdr) ((hdr)->code) +#define ICMPH_TYPE_SET(hdr, t) ((hdr)->type = (t)) +#define ICMPH_CODE_SET(hdr, c) ((hdr)->code = (c)) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ICMP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/icmp6.h b/tools/sdk/include/lwip/lwip/prot/icmp6.h new file mode 100644 index 00000000000..3461120421e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/icmp6.h @@ -0,0 +1,170 @@ +/** + * @file + * ICMP6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ICMP6_H +#define LWIP_HDR_PROT_ICMP6_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** ICMP type */ +enum icmp6_type { + /** Destination unreachable */ + ICMP6_TYPE_DUR = 1, + /** Packet too big */ + ICMP6_TYPE_PTB = 2, + /** Time exceeded */ + ICMP6_TYPE_TE = 3, + /** Parameter problem */ + ICMP6_TYPE_PP = 4, + /** Private experimentation */ + ICMP6_TYPE_PE1 = 100, + /** Private experimentation */ + ICMP6_TYPE_PE2 = 101, + /** Reserved for expansion of error messages */ + ICMP6_TYPE_RSV_ERR = 127, + + /** Echo request */ + ICMP6_TYPE_EREQ = 128, + /** Echo reply */ + ICMP6_TYPE_EREP = 129, + /** Multicast listener query */ + ICMP6_TYPE_MLQ = 130, + /** Multicast listener report */ + ICMP6_TYPE_MLR = 131, + /** Multicast listener done */ + ICMP6_TYPE_MLD = 132, + /** Router solicitation */ + ICMP6_TYPE_RS = 133, + /** Router advertisement */ + ICMP6_TYPE_RA = 134, + /** Neighbor solicitation */ + ICMP6_TYPE_NS = 135, + /** Neighbor advertisement */ + ICMP6_TYPE_NA = 136, + /** Redirect */ + ICMP6_TYPE_RD = 137, + /** Multicast router advertisement */ + ICMP6_TYPE_MRA = 151, + /** Multicast router solicitation */ + ICMP6_TYPE_MRS = 152, + /** Multicast router termination */ + ICMP6_TYPE_MRT = 153, + /** Private experimentation */ + ICMP6_TYPE_PE3 = 200, + /** Private experimentation */ + ICMP6_TYPE_PE4 = 201, + /** Reserved for expansion of informational messages */ + ICMP6_TYPE_RSV_INF = 255 +}; + +/** ICMP destination unreachable codes */ +enum icmp6_dur_code { + /** No route to destination */ + ICMP6_DUR_NO_ROUTE = 0, + /** Communication with destination administratively prohibited */ + ICMP6_DUR_PROHIBITED = 1, + /** Beyond scope of source address */ + ICMP6_DUR_SCOPE = 2, + /** Address unreachable */ + ICMP6_DUR_ADDRESS = 3, + /** Port unreachable */ + ICMP6_DUR_PORT = 4, + /** Source address failed ingress/egress policy */ + ICMP6_DUR_POLICY = 5, + /** Reject route to destination */ + ICMP6_DUR_REJECT_ROUTE = 6 +}; + +/** ICMP time exceeded codes */ +enum icmp6_te_code { + /** Hop limit exceeded in transit */ + ICMP6_TE_HL = 0, + /** Fragment reassembly time exceeded */ + ICMP6_TE_FRAG = 1 +}; + +/** ICMP parameter code */ +enum icmp6_pp_code { + /** Erroneous header field encountered */ + ICMP6_PP_FIELD = 0, + /** Unrecognized next header type encountered */ + ICMP6_PP_HEADER = 1, + /** Unrecognized IPv6 option encountered */ + ICMP6_PP_OPTION = 2 +}; + +/** This is the standard ICMP6 header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct icmp6_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t data); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** This is the ICMP6 header adapted for echo req/resp. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct icmp6_echo_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FIELD(u16_t seqno); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ICMP6_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/igmp.h b/tools/sdk/include/lwip/lwip/prot/igmp.h new file mode 100644 index 00000000000..d60cb31ee7c --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/igmp.h @@ -0,0 +1,90 @@ +/** + * @file + * IGMP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IGMP_H +#define LWIP_HDR_PROT_IGMP_H + +#include "lwip/arch.h" +#include "lwip/ip4_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * IGMP constants + */ +#define IGMP_TTL 1 +#define IGMP_MINLEN 8 +#define ROUTER_ALERT 0x9404U +#define ROUTER_ALERTLEN 4 + +/* + * IGMP message types, including version number. + */ +#define IGMP_MEMB_QUERY 0x11 /* Membership query */ +#define IGMP_V1_MEMB_REPORT 0x12 /* Ver. 1 membership report */ +#define IGMP_V2_MEMB_REPORT 0x16 /* Ver. 2 membership report */ +#define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */ + +/* Group membership states */ +#define IGMP_GROUP_NON_MEMBER 0 +#define IGMP_GROUP_DELAYING_MEMBER 1 +#define IGMP_GROUP_IDLE_MEMBER 2 + +/** + * IGMP packet format. + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct igmp_msg { + PACK_STRUCT_FLD_8(u8_t igmp_msgtype); + PACK_STRUCT_FLD_8(u8_t igmp_maxresp); + PACK_STRUCT_FIELD(u16_t igmp_checksum); + PACK_STRUCT_FLD_S(ip4_addr_p_t igmp_group_address); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IGMP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/ip.h b/tools/sdk/include/lwip/lwip/prot/ip.h new file mode 100644 index 00000000000..bbfae367527 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/ip.h @@ -0,0 +1,51 @@ +/** + * @file + * IP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP_H +#define LWIP_HDR_PROT_IP_H + +#include "lwip/arch.h" + +#define IP_PROTO_ICMP 1 +#define IP_PROTO_IGMP 2 +#define IP_PROTO_UDP 17 +#define IP_PROTO_UDPLITE 136 +#define IP_PROTO_TCP 6 + +/** This operates on a void* by loading the first byte */ +#define IP_HDR_GET_VERSION(ptr) ((*(u8_t*)(ptr)) >> 4) + +#endif /* LWIP_HDR_PROT_IP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/ip4.h b/tools/sdk/include/lwip/lwip/prot/ip4.h new file mode 100644 index 00000000000..bd442c6892c --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/ip4.h @@ -0,0 +1,127 @@ +/** + * @file + * IPv4 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP4_H +#define LWIP_HDR_PROT_IP4_H + +#include "lwip/arch.h" +#include "lwip/ip4_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** This is the packed version of ip4_addr_t, + used in network headers that are itself packed */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip4_addr_packed { + PACK_STRUCT_FIELD(u32_t addr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +typedef struct ip4_addr_packed ip4_addr_p_t; + +/* Size of the IPv4 header. Same as 'sizeof(struct ip_hdr)'. */ +#define IP_HLEN 20 + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/* The IPv4 header */ +struct ip_hdr { + /* version / header length */ + PACK_STRUCT_FLD_8(u8_t _v_hl); + /* type of service */ + PACK_STRUCT_FLD_8(u8_t _tos); + /* total length */ + PACK_STRUCT_FIELD(u16_t _len); + /* identification */ + PACK_STRUCT_FIELD(u16_t _id); + /* fragment offset field */ + PACK_STRUCT_FIELD(u16_t _offset); +#define IP_RF 0x8000U /* reserved fragment flag */ +#define IP_DF 0x4000U /* don't fragment flag */ +#define IP_MF 0x2000U /* more fragments flag */ +#define IP_OFFMASK 0x1fffU /* mask for fragmenting bits */ + /* time to live */ + PACK_STRUCT_FLD_8(u8_t _ttl); + /* protocol*/ + PACK_STRUCT_FLD_8(u8_t _proto); + /* checksum */ + PACK_STRUCT_FIELD(u16_t _chksum); + /* source and destination IP addresses */ + PACK_STRUCT_FLD_S(ip4_addr_p_t src); + PACK_STRUCT_FLD_S(ip4_addr_p_t dest); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Macros to get struct ip_hdr fields: */ +#define IPH_V(hdr) ((hdr)->_v_hl >> 4) +#define IPH_HL(hdr) ((hdr)->_v_hl & 0x0f) +#define IPH_TOS(hdr) ((hdr)->_tos) +#define IPH_LEN(hdr) ((hdr)->_len) +#define IPH_ID(hdr) ((hdr)->_id) +#define IPH_OFFSET(hdr) ((hdr)->_offset) +#define IPH_TTL(hdr) ((hdr)->_ttl) +#define IPH_PROTO(hdr) ((hdr)->_proto) +#define IPH_CHKSUM(hdr) ((hdr)->_chksum) + +/* Macros to set struct ip_hdr fields: */ +#define IPH_VHL_SET(hdr, v, hl) (hdr)->_v_hl = (u8_t)((((v) << 4) | (hl))) +#define IPH_TOS_SET(hdr, tos) (hdr)->_tos = (tos) +#define IPH_LEN_SET(hdr, len) (hdr)->_len = (len) +#define IPH_ID_SET(hdr, id) (hdr)->_id = (id) +#define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off) +#define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl = (u8_t)(ttl) +#define IPH_PROTO_SET(hdr, proto) (hdr)->_proto = (u8_t)(proto) +#define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum) + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IP4_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/ip6.h b/tools/sdk/include/lwip/lwip/prot/ip6.h new file mode 100644 index 00000000000..6e1e2632bfc --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/ip6.h @@ -0,0 +1,169 @@ +/** + * @file + * IPv6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP6_H +#define LWIP_HDR_PROT_IP6_H + +#include "lwip/arch.h" +#include "lwip/ip6_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** This is the packed version of ip6_addr_t, + used in network headers that are itself packed */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_addr_packed { + PACK_STRUCT_FIELD(u32_t addr[4]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +typedef struct ip6_addr_packed ip6_addr_p_t; + +#define IP6_HLEN 40 + +#define IP6_NEXTH_HOPBYHOP 0 +#define IP6_NEXTH_TCP 6 +#define IP6_NEXTH_UDP 17 +#define IP6_NEXTH_ENCAPS 41 +#define IP6_NEXTH_ROUTING 43 +#define IP6_NEXTH_FRAGMENT 44 +#define IP6_NEXTH_ICMP6 58 +#define IP6_NEXTH_NONE 59 +#define IP6_NEXTH_DESTOPTS 60 +#define IP6_NEXTH_UDPLITE 136 + +/** The IPv6 header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_hdr { + /** version / traffic class / flow label */ + PACK_STRUCT_FIELD(u32_t _v_tc_fl); + /** payload length */ + PACK_STRUCT_FIELD(u16_t _plen); + /** next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /** hop limit */ + PACK_STRUCT_FLD_8(u8_t _hoplim); + /** source and destination IP addresses */ + PACK_STRUCT_FLD_S(ip6_addr_p_t src); + PACK_STRUCT_FLD_S(ip6_addr_p_t dest); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Hop-by-hop router alert option. */ +#define IP6_HBH_HLEN 8 +#define IP6_PAD1_OPTION 0 +#define IP6_PADN_ALERT_OPTION 1 +#define IP6_ROUTER_ALERT_OPTION 5 +#define IP6_ROUTER_ALERT_VALUE_MLD 0 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_hbh_hdr { + /* next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /* header length */ + PACK_STRUCT_FLD_8(u8_t _hlen); + /* router alert option type */ + PACK_STRUCT_FLD_8(u8_t _ra_opt_type); + /* router alert option data len */ + PACK_STRUCT_FLD_8(u8_t _ra_opt_dlen); + /* router alert option data */ + PACK_STRUCT_FIELD(u16_t _ra_opt_data); + /* PadN option type */ + PACK_STRUCT_FLD_8(u8_t _padn_opt_type); + /* PadN option data len */ + PACK_STRUCT_FLD_8(u8_t _padn_opt_dlen); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Fragment header. */ +#define IP6_FRAG_HLEN 8 +#define IP6_FRAG_OFFSET_MASK 0xfff8 +#define IP6_FRAG_MORE_FLAG 0x0001 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_frag_hdr { + /* next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /* reserved */ + PACK_STRUCT_FLD_8(u8_t reserved); + /* fragment offset */ + PACK_STRUCT_FIELD(u16_t _fragment_offset); + /* fragmented packet identification */ + PACK_STRUCT_FIELD(u32_t _identification); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define IP6H_V(hdr) ((lwip_ntohl((hdr)->_v_tc_fl) >> 28) & 0x0f) +#define IP6H_TC(hdr) ((lwip_ntohl((hdr)->_v_tc_fl) >> 20) & 0xff) +#define IP6H_FL(hdr) (lwip_ntohl((hdr)->_v_tc_fl) & 0x000fffff) +#define IP6H_PLEN(hdr) (lwip_ntohs((hdr)->_plen)) +#define IP6H_NEXTH(hdr) ((hdr)->_nexth) +#define IP6H_NEXTH_P(hdr) ((u8_t *)(hdr) + 6) +#define IP6H_HOPLIM(hdr) ((hdr)->_hoplim) + +#define IP6H_VTCFL_SET(hdr, v, tc, fl) (hdr)->_v_tc_fl = (lwip_htonl((((u32_t)(v)) << 28) | (((u32_t)(tc)) << 20) | (fl))) +#define IP6H_PLEN_SET(hdr, plen) (hdr)->_plen = lwip_htons(plen) +#define IP6H_NEXTH_SET(hdr, nexth) (hdr)->_nexth = (nexth) +#define IP6H_HOPLIM_SET(hdr, hl) (hdr)->_hoplim = (u8_t)(hl) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IP6_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/mld6.h b/tools/sdk/include/lwip/lwip/prot/mld6.h new file mode 100644 index 00000000000..be3a006af25 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/mld6.h @@ -0,0 +1,70 @@ +/** + * @file + * MLD6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_MLD6_H +#define LWIP_HDR_PROT_MLD6_H + +#include "lwip/arch.h" +#include "lwip/prot/ip6.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Multicast listener report/query/done message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct mld_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t max_resp_delay); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t multicast_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_MLD6_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/nd6.h b/tools/sdk/include/lwip/lwip/prot/nd6.h new file mode 100644 index 00000000000..2d4903d15b6 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/nd6.h @@ -0,0 +1,277 @@ +/** + * @file + * ND6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ND6_H +#define LWIP_HDR_PROT_ND6_H + +#include "lwip/arch.h" +#include "lwip/ip6_addr.h" +#include "lwip/prot/ip6.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Neighbor solicitation message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ns_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Neighbor advertisement message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct na_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FLD_8(u8_t reserved[3]); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +#define ND6_FLAG_ROUTER (0x80) +#define ND6_FLAG_SOLICITED (0x40) +#define ND6_FLAG_OVERRIDE (0x20) + +/** Router solicitation message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct rs_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Router advertisement message header. */ +#define ND6_RA_FLAG_MANAGED_ADDR_CONFIG (0x80) +#define ND6_RA_FLAG_OTHER_CONFIG (0x40) +#define ND6_RA_FLAG_HOME_AGENT (0x20) +#define ND6_RA_PREFERENCE_MASK (0x18) +#define ND6_RA_PREFERENCE_HIGH (0x08) +#define ND6_RA_PREFERENCE_MEDIUM (0x00) +#define ND6_RA_PREFERENCE_LOW (0x18) +#define ND6_RA_PREFERENCE_DISABLED (0x10) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ra_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FLD_8(u8_t current_hop_limit); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FIELD(u16_t router_lifetime); + PACK_STRUCT_FIELD(u32_t reachable_time); + PACK_STRUCT_FIELD(u32_t retrans_timer); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Redirect message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct redirect_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + PACK_STRUCT_FLD_S(ip6_addr_p_t destination_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Link-layer address option. */ +#define ND6_OPTION_TYPE_SOURCE_LLADDR (0x01) +#define ND6_OPTION_TYPE_TARGET_LLADDR (0x02) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct lladdr_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t addr[NETIF_MAX_HWADDR_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Prefix information option. */ +#define ND6_OPTION_TYPE_PREFIX_INFO (0x03) +#define ND6_PREFIX_FLAG_ON_LINK (0x80) +#define ND6_PREFIX_FLAG_AUTONOMOUS (0x40) +#define ND6_PREFIX_FLAG_ROUTER_ADDRESS (0x20) +#define ND6_PREFIX_FLAG_SITE_PREFIX (0x10) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct prefix_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t prefix_length); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FIELD(u32_t valid_lifetime); + PACK_STRUCT_FIELD(u32_t preferred_lifetime); + PACK_STRUCT_FLD_8(u8_t reserved2[3]); + PACK_STRUCT_FLD_8(u8_t site_prefix_length); + PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Redirected header option. */ +#define ND6_OPTION_TYPE_REDIR_HDR (0x04) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct redirected_header_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t reserved[6]); + /* Portion of redirected packet follows. */ + /* PACK_STRUCT_FLD_8(u8_t redirected[8]); */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** MTU option. */ +#define ND6_OPTION_TYPE_MTU (0x05) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct mtu_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FIELD(u32_t mtu); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Route information option. */ +#define ND6_OPTION_TYPE_ROUTE_INFO (24) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct route_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t prefix_length); + PACK_STRUCT_FLD_8(u8_t preference); + PACK_STRUCT_FIELD(u32_t route_lifetime); + PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Recursive DNS Server Option. */ +#if LWIP_ND6_RDNSS_MAX_DNS_SERVERS +#define LWIP_RDNSS_OPTION_MAX_SERVERS LWIP_ND6_RDNSS_MAX_DNS_SERVERS +#else +#define LWIP_RDNSS_OPTION_MAX_SERVERS 1 +#endif +#define ND6_OPTION_TYPE_RDNSS (25) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct rdnss_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FIELD(u32_t lifetime); + PACK_STRUCT_FLD_S(ip6_addr_p_t rdnss_address[LWIP_RDNSS_OPTION_MAX_SERVERS]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ND6_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/tcp.h b/tools/sdk/include/lwip/lwip/prot/tcp.h new file mode 100644 index 00000000000..67fe7b9e5fc --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/tcp.h @@ -0,0 +1,97 @@ +/** + * @file + * TCP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_TCP_H +#define LWIP_HDR_PROT_TCP_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Length of the TCP header, excluding options. */ +#define TCP_HLEN 20 + +/* Fields are (of course) in network byte order. + * Some fields are converted to host byte order in tcp_input(). + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct tcp_hdr { + PACK_STRUCT_FIELD(u16_t src); + PACK_STRUCT_FIELD(u16_t dest); + PACK_STRUCT_FIELD(u32_t seqno); + PACK_STRUCT_FIELD(u32_t ackno); + PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags); + PACK_STRUCT_FIELD(u16_t wnd); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t urgp); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* TCP header flags bits */ +#define TCP_FIN 0x01U +#define TCP_SYN 0x02U +#define TCP_RST 0x04U +#define TCP_PSH 0x08U +#define TCP_ACK 0x10U +#define TCP_URG 0x20U +#define TCP_ECE 0x40U +#define TCP_CWR 0x80U +/* Valid TCP header flags */ +#define TCP_FLAGS 0x3fU + +#define TCPH_HDRLEN(phdr) ((u16_t)(lwip_ntohs((phdr)->_hdrlen_rsvd_flags) >> 12)) +#define TCPH_FLAGS(phdr) ((u16_t)(lwip_ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS)) + +#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = lwip_htons(((len) << 12) | TCPH_FLAGS(phdr)) +#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = (((phdr)->_hdrlen_rsvd_flags & PP_HTONS(~TCP_FLAGS)) | lwip_htons(flags)) +#define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) (phdr)->_hdrlen_rsvd_flags = (u16_t)(lwip_htons((u16_t)((len) << 12) | (flags))) + +#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | lwip_htons(flags)) +#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags & ~lwip_htons(flags)) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_TCP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/udp.h b/tools/sdk/include/lwip/lwip/prot/udp.h new file mode 100644 index 00000000000..664f19a3e7b --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/udp.h @@ -0,0 +1,68 @@ +/** + * @file + * UDP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_UDP_H +#define LWIP_HDR_PROT_UDP_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define UDP_HLEN 8 + +/* Fields are (of course) in network byte order. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct udp_hdr { + PACK_STRUCT_FIELD(u16_t src); + PACK_STRUCT_FIELD(u16_t dest); /* src/dest UDP ports */ + PACK_STRUCT_FIELD(u16_t len); + PACK_STRUCT_FIELD(u16_t chksum); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_UDP_H */ diff --git a/tools/sdk/include/lwip/lwip/raw.h b/tools/sdk/include/lwip/lwip/raw.h old mode 100755 new mode 100644 index 474fdc15462..30aa1471096 --- a/tools/sdk/include/lwip/lwip/raw.h +++ b/tools/sdk/include/lwip/lwip/raw.h @@ -1,3 +1,9 @@ +/** + * @file + * raw API (to be used from TCPIP thread)\n + * See also @ref raw_raw + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -61,6 +67,7 @@ struct raw_pcb; typedef u8_t (*raw_recv_fn)(void *arg, struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *addr); +/** the RAW protocol control block */ struct raw_pcb { /* Common members of all PCB types */ IP_PCB; @@ -97,6 +104,8 @@ void raw_recv (struct raw_pcb *pcb, raw_recv_fn recv, void *re u8_t raw_input (struct pbuf *p, struct netif *inp); #define raw_init() /* Compatibility define, no init needed. */ +void raw_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr); + /* for compatibility with older implementation */ #define raw_new_ip6(proto) raw_new_ip_type(IPADDR_TYPE_V6, proto) diff --git a/tools/sdk/include/lwip/lwip/sio.h b/tools/sdk/include/lwip/lwip/sio.h old mode 100755 new mode 100644 index 09cf799abcb..7643e195697 --- a/tools/sdk/include/lwip/lwip/sio.h +++ b/tools/sdk/include/lwip/lwip/sio.h @@ -36,6 +36,7 @@ #define SIO_H #include "lwip/arch.h" +#include "lwip/opt.h" #ifdef __cplusplus extern "C" { diff --git a/tools/sdk/include/lwip/lwip/snmp.h b/tools/sdk/include/lwip/lwip/snmp.h old mode 100755 new mode 100644 index 07368cc68ab..8704d0b4d29 --- a/tools/sdk/include/lwip/lwip/snmp.h +++ b/tools/sdk/include/lwip/lwip/snmp.h @@ -1,7 +1,6 @@ /** * @file - * MIB2 callback functions called from throughout the stack to integrate a MIB2 - * into lwIP (together with MIB2_STATS). + * SNMP support API for implementing netifs and statitics for MIB2 */ /* @@ -48,9 +47,15 @@ extern "C" { struct udp_pcb; struct netif; +/** + * @defgroup netif_mib2 MIB2 statistics + * @ingroup netif + */ + /* MIB2 statistics functions */ #if MIB2_STATS /* don't build if not configured for use in lwipopts.h */ /** + * @ingroup netif_mib2 * @see RFC1213, "MIB-II, 6. Definitions" */ enum snmp_ifType { @@ -88,18 +93,31 @@ enum snmp_ifType { snmp_ifType_frame_relay }; -/* This macro has a precision of ~49 days because sys_now returns u32_t. #define your own if you want ~490 days. */ +/** This macro has a precision of ~49 days because sys_now returns u32_t. \#define your own if you want ~490 days. */ #ifndef MIB2_COPY_SYSUPTIME_TO #define MIB2_COPY_SYSUPTIME_TO(ptrToVal) (*(ptrToVal) = (sys_now() / 10)) #endif +/** + * @ingroup netif_mib2 + * Increment stats member for SNMP MIB2 stats (struct stats_mib2_netif_ctrs) + */ #define MIB2_STATS_NETIF_INC(n, x) do { ++(n)->mib2_counters.x; } while(0) +/** + * @ingroup netif_mib2 + * Add value to stats member for SNMP MIB2 stats (struct stats_mib2_netif_ctrs) + */ #define MIB2_STATS_NETIF_ADD(n, x, val) do { (n)->mib2_counters.x += (val); } while(0) +/** + * @ingroup netif_mib2 + * Init MIB2 statistic counters in netif + * @param netif Netif to init + * @param type one of enum @ref snmp_ifType + * @param speed your link speed here (units: bits per second) + */ #define MIB2_INIT_NETIF(netif, type, speed) do { \ - /* use "snmp_ifType" enum from snmp_mib2.h for "type", snmp_ifType_ethernet_csmacd by example */ \ (netif)->link_type = (type); \ - /* your link speed here (units: bits per second) */ \ (netif)->link_speed = (speed);\ (netif)->ts = 0; \ (netif)->mib2_counters.ifinoctets = 0; \ diff --git a/tools/sdk/include/lwip/lwip/sockets.h b/tools/sdk/include/lwip/lwip/sockets.h old mode 100755 new mode 100644 index d8e4c7ffbeb..eff3b42e46c --- a/tools/sdk/include/lwip/lwip/sockets.h +++ b/tools/sdk/include/lwip/lwip/sockets.h @@ -1,3 +1,8 @@ +/** + * @file + * Socket API (to be used from non-TCPIP threads) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,12 +43,10 @@ #if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ -#include /* for size_t */ -#include /* for FD_ZERO */ - #include "lwip/ip_addr.h" #include "lwip/err.h" #include "lwip/inet.h" +#include "lwip/errno.h" #ifdef __cplusplus extern "C" { @@ -191,6 +194,7 @@ struct msghdr { #define SO_CONTIMEO 0x1009 /* Unimplemented: connect timeout */ #define SO_NO_CHECK 0x100a /* don't create UDP checksum */ + /* * Structure used for manipulating linger option. */ @@ -250,11 +254,6 @@ struct linger { #define TCP_KEEPIDLE 0x03 /* set pcb->keep_idle - Same as TCP_KEEPALIVE, but use seconds for get/setsockopt */ #define TCP_KEEPINTVL 0x04 /* set pcb->keep_intvl - Use seconds for get/setsockopt */ #define TCP_KEEPCNT 0x05 /* set pcb->keep_cnt - Use number of probes sent for get/setsockopt */ -#if ESP_PER_SOC_TCP_WND -#define TCP_WINDOW 0x06 /* set pcb->per_soc_tcp_wnd */ -#define TCP_SNDBUF 0x07 /* set pcb->per_soc_tcp_snd_buf */ -#endif - #endif /* LWIP_TCP */ #if LWIP_IPV6 @@ -264,6 +263,7 @@ struct linger { #define IPV6_CHECKSUM 7 /* RFC3542: calculate and insert the ICMPv6 checksum for raw sockets. */ #define IPV6_V6ONLY 27 /* RFC3493: boolean control to restrict AF_INET6 sockets to IPv6 communications only. */ +#if ESP_LWIP #if LWIP_IPV6_MLD /* Socket options for IPV6 multicast, uses the MLD interface to manage group memberships. RFC2133. */ #define IPV6_MULTICAST_IF 0x300 @@ -283,6 +283,7 @@ typedef struct ip6_mreq { #define IPV6_LEAVE_GROUP IPV6_DROP_MEMBERSHIP #endif /* LWIP_IPV6_MLD */ +#endif #endif /* LWIP_IPV6 */ @@ -446,8 +447,6 @@ typedef struct fd_set unsigned char fd_bits [(FD_SETSIZE+7)/8]; } fd_set; -#elif LWIP_SOCKET_OFFSET -#error LWIP_SOCKET_OFFSET does not work with external FD_SET! #endif /* FD_SET */ /** LWIP_TIMEVAL_PRIVATE: if you want to use the struct timeval provided @@ -468,8 +467,6 @@ void lwip_socket_thread_init(void); /* LWIP_NETCONN_SEM_PER_THREAD==1: initializ void lwip_socket_thread_cleanup(void); /* LWIP_NETCONN_SEM_PER_THREAD==1: destroy thread-local semaphore */ #if LWIP_COMPAT_SOCKETS == 2 - - /* This helps code parsers/code completion by not having the COMPAT functions as defines */ #define lwip_accept accept #define lwip_bind bind @@ -543,6 +540,7 @@ int lwip_setsockopt_r (int s, int level, int optname, const void *optval, sockle int lwip_close_r(int s); int lwip_connect_r(int s, const struct sockaddr *name, socklen_t namelen); int lwip_listen_r(int s, int backlog); +int lwip_recvmsg_r(int s, struct msghdr *message, int flags); int lwip_recv_r(int s, void *mem, size_t len, int flags); int lwip_read_r(int s, void *mem, size_t len); int lwip_recvfrom_r(int s, void *mem, size_t len, int flags, @@ -579,6 +577,8 @@ static inline int connect(int s,const struct sockaddr *name,socklen_t namelen) { return lwip_connect_r(s,name,namelen); } static inline int listen(int s,int backlog) { return lwip_listen_r(s,backlog); } +static inline int recvmsg(int sockfd, struct msghdr *msg, int flags) +{ return lwip_recvmsg_r(sockfd, msg, flags); } static inline int recv(int s,void *mem,size_t len,int flags) { return lwip_recv_r(s,mem,len,flags); } static inline int recvfrom(int s,void *mem,size_t len,int flags,struct sockaddr *from,socklen_t *fromlen) @@ -591,8 +591,10 @@ static inline int sendto(int s,const void *dataptr,size_t size,int flags,const s { return lwip_sendto_r(s,dataptr,size,flags,to,tolen); } static inline int socket(int domain,int type,int protocol) { return lwip_socket(domain,type,protocol); } +#ifndef ESP_HAS_SELECT static inline int select(int maxfdp1,fd_set *readset,fd_set *writeset,fd_set *exceptset,struct timeval *timeout) { return lwip_select(maxfdp1,readset,writeset,exceptset,timeout); } +#endif /* ESP_HAS_SELECT */ static inline int ioctlsocket(int s,long cmd,void *argp) { return lwip_ioctl_r(s,cmd,argp); } @@ -609,69 +611,106 @@ static inline int fcntl(int s,int cmd,int val) { return lwip_fcntl_r(s,cmd,val); } static inline int ioctl(int s,long cmd,void *argp) { return lwip_ioctl_r(s,cmd,argp); } -#endif /* { RETURN LWIP_POSIX_SOCKETS_IO_NAMES */ +#endif /* LWIP_POSIX_SOCKETS_IO_NAMES */ #else -static inline int accept(int s,struct sockaddr *addr,socklen_t *addrlen) -{ return lwip_accept(s,addr,addrlen); } -static inline int bind(int s,const struct sockaddr *name,socklen_t namelen) -{ return lwip_bind(s,name,namelen); } -static inline int shutdown(int s,int how) -{ return lwip_shutdown(s,how); } -static inline int getpeername(int s,struct sockaddr *name,socklen_t *namelen) -{ return lwip_getpeername(s,name,namelen); } -static inline int getsockname(int s,struct sockaddr *name,socklen_t *namelen) -{ return lwip_getsockname(s,name,namelen); } -static inline int setsockopt(int s,int level,int optname,const void *opval,socklen_t optlen) -{ return lwip_setsockopt(s,level,optname,opval,optlen); } -static inline int getsockopt(int s,int level,int optname,void *opval,socklen_t *optlen) -{ return lwip_getsockopt(s,level,optname,opval,optlen); } -static inline int closesocket(int s) -{ return lwip_close(s); } -static inline int connect(int s,const struct sockaddr *name,socklen_t namelen) -{ return lwip_connect(s,name,namelen); } -static inline int listen(int s,int backlog) -{ return lwip_listen(s,backlog); } -static inline int recv(int s,void *mem,size_t len,int flags) -{ return lwip_recv(s,mem,len,flags); } -static inline int recvfrom(int s,void *mem,size_t len,int flags,struct sockaddr *from,socklen_t *fromlen) -{ return lwip_recvfrom(s,mem,len,flags,from,fromlen); } -static inline int send(int s,const void *dataptr,size_t size,int flags) -{ return lwip_send(s,dataptr,size,flags); } -static inline int sendmsg(int s,const struct msghdr *message,int flags) -{ return lwip_sendmsg(s,message,flags); } -static inline int sendto(int s,const void *dataptr,size_t size,int flags,const struct sockaddr *to,socklen_t tolen) -{ return lwip_sendto(s,dataptr,size,flags,to,tolen); } -static inline int socket(int domain,int type,int protocol) -{ return lwip_socket(domain,type,protocol); } -static inline int select(int maxfdp1,fd_set t*readset,fd_set *writeset,fd_set *exceptset,struct timeval *timeout) -{ return lwip_select(maxfdp1,readset,writeset,exceptset,timeout); } -static inline int ioctlsocket(int s,long cmd,void *argp) -{ return lwip_ioctl(s,cmd,argp); } +/** @ingroup socket */ +#define accept(s,addr,addrlen) lwip_accept(s,addr,addrlen) +/** @ingroup socket */ +#define bind(s,name,namelen) lwip_bind(s,name,namelen) +/** @ingroup socket */ +#define shutdown(s,how) lwip_shutdown(s,how) +/** @ingroup socket */ +#define getpeername(s,name,namelen) lwip_getpeername(s,name,namelen) +/** @ingroup socket */ +#define getsockname(s,name,namelen) lwip_getsockname(s,name,namelen) +/** @ingroup socket */ +#define setsockopt(s,level,optname,opval,optlen) lwip_setsockopt(s,level,optname,opval,optlen) +/** @ingroup socket */ +#define getsockopt(s,level,optname,opval,optlen) lwip_getsockopt(s,level,optname,opval,optlen) +/** @ingroup socket */ +#define closesocket(s) lwip_close(s) +/** @ingroup socket */ +#define connect(s,name,namelen) lwip_connect(s,name,namelen) +/** @ingroup socket */ +#define listen(s,backlog) lwip_listen(s,backlog) +/** @ingroup socket */ +#define recv(s,mem,len,flags) lwip_recv(s,mem,len,flags) +/** @ingroup socket */ +#define recvfrom(s,mem,len,flags,from,fromlen) lwip_recvfrom(s,mem,len,flags,from,fromlen) +/** @ingroup socket */ +#define send(s,dataptr,size,flags) lwip_send(s,dataptr,size,flags) +/** @ingroup socket */ +#define sendmsg(s,message,flags) lwip_sendmsg(s,message,flags) +/** @ingroup socket */ +#define sendto(s,dataptr,size,flags,to,tolen) lwip_sendto(s,dataptr,size,flags,to,tolen) +/** @ingroup socket */ +#define socket(domain,type,protocol) lwip_socket(domain,type,protocol) +/** @ingroup socket */ +#define select(maxfdp1,readset,writeset,exceptset,timeout) lwip_select(maxfdp1,readset,writeset,exceptset,timeout) +/** @ingroup socket */ +#define ioctlsocket(s,cmd,argp) lwip_ioctl(s,cmd,argp) #if LWIP_POSIX_SOCKETS_IO_NAMES -static inline int read(int s,void *mem,size_t len) -{ return lwip_read(s,mem,len); } -static inline int write(int s,const void *dataptr,size_t len) -{ return lwip_write(s,dataptr,len); } -static inline int writev(int s,const struct iovec *iov,int iovcnt) -{ return lwip_writev(s,iov,iovcnt); } -static inline int close(int s) -{ return lwip_close(s); } -static inline int fcntl(int s,long cmd,void *val) -{ return lwip_fcntl(s,cmd,val); } -static inline int ioctl(int s,int cmd,int argp) -{ return lwip_ioctl(s,cmd,argp); } +/** @ingroup socket */ +#define read(s,mem,len) lwip_read(s,mem,len) +/** @ingroup socket */ +#define write(s,dataptr,len) lwip_write(s,dataptr,len) +/** @ingroup socket */ +#define writev(s,iov,iovcnt) lwip_writev(s,iov,iovcnt) +/** @ingroup socket */ +#define close(s) lwip_close(s) +/** @ingroup socket */ +#define fcntl(s,cmd,val) lwip_fcntl(s,cmd,val) +/** @ingroup socket */ +#define ioctl(s,cmd,argp) lwip_ioctl(s,cmd,argp) #endif /* LWIP_POSIX_SOCKETS_IO_NAMES */ -#endif /* ESP_THREAD_SAFE */ +#endif /* ESP_THREAD_SAFE */ #endif /* LWIP_COMPAT_SOCKETS != 2 */ +#if ESP_LWIP +#if LWIP_IPV4 && LWIP_IPV6 +#define lwip_inet_ntop(af,src,dst,size) \ + (((af) == AF_INET6) ? ip6addr_ntoa_r((const ip6_addr_t*)(src),(dst),(size)) \ + : (((af) == AF_INET) ? ip4addr_ntoa_r((const ip4_addr_t*)(src),(dst),(size)) : NULL)) +#define lwip_inet_pton(af,src,dst) \ + (((af) == AF_INET6) ? ip6addr_aton((src),(ip6_addr_t*)(dst)) \ + : (((af) == AF_INET) ? ip4addr_aton((src),(ip4_addr_t*)(dst)) : 0)) +#elif LWIP_IPV4 /* LWIP_IPV4 && LWIP_IPV6 */ +#define lwip_inet_ntop(af,src,dst,size) \ + (((af) == AF_INET) ? ip4addr_ntoa_r((const ip4_addr_t*)(src),(dst),(size)) : NULL) +#define lwip_inet_pton(af,src,dst) \ + (((af) == AF_INET) ? ip4addr_aton((src),(ip4_addr_t*)(dst)) : 0) +#else /* LWIP_IPV4 && LWIP_IPV6 */ +#define lwip_inet_ntop(af,src,dst,size) \ + (((af) == AF_INET6) ? ip6addr_ntoa_r((const ip6_addr_t*)(src),(dst),(size)) : NULL) +#define lwip_inet_pton(af,src,dst) \ + (((af) == AF_INET6) ? ip6addr_aton((src),(ip6_addr_t*)(dst)) : 0) +#endif /* LWIP_IPV4 && LWIP_IPV6 */ + +#if LWIP_COMPAT_SOCKET_INET == 1 +/* Some libraries have problems with inet_... being macros, so please use this define + to declare normal functions */ +static inline const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) +{ lwip_inet_ntop(af, src, dst, size); return dst; } +static inline int inet_pton(int af, const char *src, void *dst) +{ lwip_inet_pton(af, src, dst); return 1; } +#else +/* By default fall back to original inet_... macros */ +# define inet_ntop(a,b,c,d) lwip_inet_ntop(a,b,c,d) +# define inet_pton(a,b,c) lwip_inet_pton(a,b,c) +#endif /* LWIP_COMPAT_SOCKET_INET */ + +#else /* ESP_LWIP*/ + #if LWIP_IPV4 && LWIP_IPV6 +/** @ingroup socket */ #define inet_ntop(af,src,dst,size) \ (((af) == AF_INET6) ? ip6addr_ntoa_r((const ip6_addr_t*)(src),(dst),(size)) \ : (((af) == AF_INET) ? ip4addr_ntoa_r((const ip4_addr_t*)(src),(dst),(size)) : NULL)) +/** @ingroup socket */ #define inet_pton(af,src,dst) \ (((af) == AF_INET6) ? ip6addr_aton((src),(ip6_addr_t*)(dst)) \ : (((af) == AF_INET) ? ip4addr_aton((src),(ip4_addr_t*)(dst)) : 0)) @@ -687,6 +726,7 @@ static inline int ioctl(int s,int cmd,int argp) (((af) == AF_INET6) ? ip6addr_aton((src),(ip6_addr_t*)(dst)) : 0) #endif /* LWIP_IPV4 && LWIP_IPV6 */ +#endif /* ESP_LWIP */ #endif /* LWIP_COMPAT_SOCKETS */ #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/lwip/stats.h b/tools/sdk/include/lwip/lwip/stats.h old mode 100755 new mode 100644 index a4c700b2c48..e883383feff --- a/tools/sdk/include/lwip/lwip/stats.h +++ b/tools/sdk/include/lwip/lwip/stats.h @@ -1,3 +1,8 @@ +/** + * @file + * Statistics API (to be used from TCPIP thread) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -55,6 +60,7 @@ extern "C" { #define STAT_COUNTER_F U16_F #endif +/** Protocol related stats */ struct stats_proto { STAT_COUNTER xmit; /* Transmitted packets. */ STAT_COUNTER recv; /* Received packets. */ @@ -70,6 +76,7 @@ struct stats_proto { STAT_COUNTER cachehit; }; +/** IGMP stats */ struct stats_igmp { STAT_COUNTER xmit; /* Transmitted packets. */ STAT_COUNTER recv; /* Received packets. */ @@ -87,10 +94,11 @@ struct stats_igmp { STAT_COUNTER tx_report; /* Sent reports. */ }; +/** Memory stats */ struct stats_mem { -#ifdef LWIP_DEBUG +#if defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY const char *name; -#endif /* LWIP_DEBUG */ +#endif /* defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY */ STAT_COUNTER err; mem_size_t avail; mem_size_t used; @@ -98,18 +106,21 @@ struct stats_mem { STAT_COUNTER illegal; }; +/** System element stats */ struct stats_syselem { STAT_COUNTER used; STAT_COUNTER max; STAT_COUNTER err; }; +/** System stats */ struct stats_sys { struct stats_syselem sem; struct stats_syselem mutex; struct stats_syselem mbox; }; +/** SNMP MIB2 stats */ struct stats_mib2 { /* IP */ u32_t ipinhdrerrors; @@ -168,51 +179,56 @@ struct stats_mib2 { u32_t icmpoutechoreps; }; +/** + * @ingroup netif_mib2 + * SNMP MIB2 interface stats + */ struct stats_mib2_netif_ctrs { - /* The total number of octets received on the interface, including framing characters */ + /** The total number of octets received on the interface, including framing characters */ u32_t ifinoctets; - /* The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were + /** The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were * not addressed to a multicast or broadcast address at this sub-layer */ u32_t ifinucastpkts; - /* The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were + /** The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were * addressed to a multicast or broadcast address at this sub-layer */ u32_t ifinnucastpkts; - /* The number of inbound packets which were chosen to be discarded even though no errors had - * been detected to prevent their being deliverable to a higher-layer protocol. One possible + /** The number of inbound packets which were chosen to be discarded even though no errors had + * been detected to prevent their being deliverable to a higher-layer protocol. One possible * reason for discarding such a packet could be to free up buffer space */ u32_t ifindiscards; - /* For packet-oriented interfaces, the number of inbound packets that contained errors + /** For packet-oriented interfaces, the number of inbound packets that contained errors * preventing them from being deliverable to a higher-layer protocol. For character- - * oriented or fixed-length interfaces, the number of inbound transmission units that + * oriented or fixed-length interfaces, the number of inbound transmission units that * contained errors preventing them from being deliverable to a higher-layer protocol. */ u32_t ifinerrors; - /* For packet-oriented interfaces, the number of packets received via the interface which + /** For packet-oriented interfaces, the number of packets received via the interface which * were discarded because of an unknown or unsupported protocol. For character-oriented * or fixed-length interfaces that support protocol multiplexing the number of transmission * units received via the interface which were discarded because of an unknown or unsupported * protocol. For any interface that does not support protocol multiplexing, this counter will * always be 0 */ u32_t ifinunknownprotos; - /* The total number of octets transmitted out of the interface, including framing characters. */ + /** The total number of octets transmitted out of the interface, including framing characters. */ u32_t ifoutoctets; - /* The total number of packets that higher-level protocols requested be transmitted, and + /** The total number of packets that higher-level protocols requested be transmitted, and * which were not addressed to a multicast or broadcast address at this sub-layer, including * those that were discarded or not sent. */ u32_t ifoutucastpkts; - /* The total number of packets that higher-level protocols requested be transmitted, and which + /** The total number of packets that higher-level protocols requested be transmitted, and which * were addressed to a multicast or broadcast address at this sub-layer, including * those that were discarded or not sent. */ u32_t ifoutnucastpkts; - /* The number of outbound packets which were chosen to be discarded even though no errors had + /** The number of outbound packets which were chosen to be discarded even though no errors had * been detected to prevent their being transmitted. One possible reason for discarding * such a packet could be to free up buffer space. */ u32_t ifoutdiscards; - /* For packet-oriented interfaces, the number of outbound packets that could not be transmitted + /** For packet-oriented interfaces, the number of outbound packets that could not be transmitted * because of errors. For character-oriented or fixed-length interfaces, the number of outbound * transmission units that could not be transmitted because of errors. */ u32_t ifouterrors; }; +#if ESP_STATS_DROP struct stats_esp { /* mbox post fail stats */ u32_t rx_rawmbox_post_fail; @@ -229,66 +245,88 @@ struct stats_esp { u32_t wlanif_input_pbuf_fail; u32_t wlanif_outut_pbuf_fail; }; +#endif +/** lwIP stats container */ struct stats_ { #if LINK_STATS + /** Link level */ struct stats_proto link; #endif #if ETHARP_STATS + /** ARP */ struct stats_proto etharp; #endif #if IPFRAG_STATS + /** Fragmentation */ struct stats_proto ip_frag; #endif #if IP_STATS + /** IP */ struct stats_proto ip; #endif #if ICMP_STATS + /** ICMP */ struct stats_proto icmp; #endif #if IGMP_STATS + /** IGMP */ struct stats_igmp igmp; #endif #if UDP_STATS + /** UDP */ struct stats_proto udp; #endif #if TCP_STATS + /** TCP */ struct stats_proto tcp; #endif #if MEM_STATS + /** Heap */ struct stats_mem mem; #endif #if MEMP_STATS - struct stats_mem memp[MEMP_MAX]; + /** Internal memory pools */ + struct stats_mem *memp[MEMP_MAX]; #endif #if SYS_STATS + /** System */ struct stats_sys sys; #endif #if IP6_STATS + /** IPv6 */ struct stats_proto ip6; #endif #if ICMP6_STATS + /** ICMP6 */ struct stats_proto icmp6; #endif #if IP6_FRAG_STATS + /** IPv6 fragmentation */ struct stats_proto ip6_frag; #endif #if MLD6_STATS + /** Multicast listener discovery */ struct stats_igmp mld6; #endif #if ND6_STATS + /** Neighbor discovery */ struct stats_proto nd6; #endif #if MIB2_STATS + /** SNMP MIB2 */ struct stats_mib2 mib2; #endif + #if ESP_STATS_DROP struct stats_esp esp; #endif }; +/** Global variable containing lwIP internal statistics. Add this to your debugger's watchlist. */ extern struct stats_ lwip_stats; +/** Init statistics */ void stats_init(void); #define STATS_INC(x) ++lwip_stats.x @@ -372,9 +410,9 @@ void stats_init(void); #if MEM_STATS #define MEM_STATS_AVAIL(x, y) lwip_stats.mem.x = y -#define MEM_STATS_INC(x) STATS_INC(mem.x) -#define MEM_STATS_INC_USED(x, y) STATS_INC_USED(mem, y) -#define MEM_STATS_DEC_USED(x, y) lwip_stats.mem.x -= y +#define MEM_STATS_INC(x) SYS_ARCH_INC(lwip_stats.mem.x, 1) +#define MEM_STATS_INC_USED(x, y) SYS_ARCH_INC(lwip_stats.mem.x, y) +#define MEM_STATS_DEC_USED(x, y) SYS_ARCH_DEC(lwip_stats.mem.x, y) #define MEM_STATS_DISPLAY() stats_display_mem(&lwip_stats.mem, "HEAP") #else #define MEM_STATS_AVAIL(x, y) @@ -384,18 +422,12 @@ void stats_init(void); #define MEM_STATS_DISPLAY() #endif -#if MEMP_STATS -#define MEMP_STATS_AVAIL(x, i, y) lwip_stats.memp[i].x = y -#define MEMP_STATS_INC(x, i) STATS_INC(memp[i].x) -#define MEMP_STATS_DEC(x, i) STATS_DEC(memp[i].x) -#define MEMP_STATS_INC_USED(x, i) STATS_INC_USED(memp[i], 1) -#define MEMP_STATS_DISPLAY(i) stats_display_memp(&lwip_stats.memp[i], i) -#define MEMP_STATS_GET(x, i) STATS_GET(memp[i].x) -#else -#define MEMP_STATS_AVAIL(x, i, y) -#define MEMP_STATS_INC(x, i) + #if MEMP_STATS +#define MEMP_STATS_DEC(x, i) STATS_DEC(memp[i]->x) +#define MEMP_STATS_DISPLAY(i) stats_display_memp(lwip_stats.memp[i], i) +#define MEMP_STATS_GET(x, i) STATS_GET(memp[i]->x) + #else #define MEMP_STATS_DEC(x, i) -#define MEMP_STATS_INC_USED(x, i) #define MEMP_STATS_DISPLAY(i) #define MEMP_STATS_GET(x, i) 0 #endif @@ -474,7 +506,10 @@ void stats_display_igmp(struct stats_igmp *igmp, const char *name); void stats_display_mem(struct stats_mem *mem, const char *name); void stats_display_memp(struct stats_mem *mem, int index); void stats_display_sys(struct stats_sys *sys); +#if ESP_STATS_DROP void stats_display_esp(struct stats_esp *esp); +#endif + #else /* LWIP_STATS_DISPLAY */ #define stats_display() #define stats_display_proto(proto, name) @@ -482,7 +517,10 @@ void stats_display_esp(struct stats_esp *esp); #define stats_display_mem(mem, name) #define stats_display_memp(mem, index) #define stats_display_sys(sys) +#if ESP_STATS_DROP #define stats_display_esp(esp) +#endif + #endif /* LWIP_STATS_DISPLAY */ #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/lwip/sys.h b/tools/sdk/include/lwip/lwip/sys.h old mode 100755 new mode 100644 index 86d0f3b336c..695cae49dca --- a/tools/sdk/include/lwip/lwip/sys.h +++ b/tools/sdk/include/lwip/lwip/sys.h @@ -1,3 +1,8 @@ +/** + * @file + * OS abstraction layer + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -27,8 +32,8 @@ * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels - * */ + #ifndef LWIP_HDR_SYS_H #define LWIP_HDR_SYS_H @@ -115,130 +120,226 @@ typedef void (*lwip_thread_fn)(void *arg); #else /* LWIP_COMPAT_MUTEX */ -/** Create a new mutex +/** + * @ingroup sys_mutex + * Create a new mutex. + * Note that mutexes are expected to not be taken recursively by the lwIP code, + * so both implementation types (recursive or non-recursive) should work. * @param mutex pointer to the mutex to create - * @return a new mutex */ + * @return ERR_OK if successful, another err_t otherwise + */ err_t sys_mutex_new(sys_mutex_t *mutex); -/** Lock a mutex - * @param mutex the mutex to lock */ +/** + * @ingroup sys_mutex + * Lock a mutex + * @param mutex the mutex to lock + */ void sys_mutex_lock(sys_mutex_t *mutex); -/** Unlock a mutex - * @param mutex the mutex to unlock */ +/** + * @ingroup sys_mutex + * Unlock a mutex + * @param mutex the mutex to unlock + */ void sys_mutex_unlock(sys_mutex_t *mutex); -/** Delete a semaphore - * @param mutex the mutex to delete */ +/** + * @ingroup sys_mutex + * Delete a semaphore + * @param mutex the mutex to delete + */ void sys_mutex_free(sys_mutex_t *mutex); #ifndef sys_mutex_valid -/** Check if a mutex is valid/allocated: return 1 for valid, 0 for invalid */ +/** + * @ingroup sys_mutex + * Check if a mutex is valid/allocated: return 1 for valid, 0 for invalid + */ int sys_mutex_valid(sys_mutex_t *mutex); #endif #ifndef sys_mutex_set_invalid -/** Set a mutex invalid so that sys_mutex_valid returns 0 */ +/** + * @ingroup sys_mutex + * Set a mutex invalid so that sys_mutex_valid returns 0 + */ void sys_mutex_set_invalid(sys_mutex_t *mutex); #endif #endif /* LWIP_COMPAT_MUTEX */ /* Semaphore functions: */ -/** Create a new semaphore +/** + * @ingroup sys_sem + * Create a new semaphore * @param sem pointer to the semaphore to create * @param count initial count of the semaphore - * @return ERR_OK if successful, another err_t otherwise */ + * @return ERR_OK if successful, another err_t otherwise + */ err_t sys_sem_new(sys_sem_t *sem, u8_t count); -/** Signals a semaphore - * @param sem the semaphore to signal */ +/** + * @ingroup sys_sem + * Signals a semaphore + * @param sem the semaphore to signal + */ void sys_sem_signal(sys_sem_t *sem); -/** Wait for a semaphore for the specified timeout + +#if ESP_LWIP +/** Signals a semaphore (ISR version) + * @param sem the semaphore to signal + * @return non-zero if a higher priority task has been woken */ +int sys_sem_signal_isr(sys_sem_t *sem); +#endif + +/** + * @ingroup sys_sem + * Wait for a semaphore for the specified timeout * @param sem the semaphore to wait for * @param timeout timeout in milliseconds to wait (0 = wait forever) * @return time (in milliseconds) waited for the semaphore - * or SYS_ARCH_TIMEOUT on timeout */ + * or SYS_ARCH_TIMEOUT on timeout + */ u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout); -/** Delete a semaphore - * @param sem semaphore to delete */ +/** + * @ingroup sys_sem + * Delete a semaphore + * @param sem semaphore to delete + */ void sys_sem_free(sys_sem_t *sem); /** Wait for a semaphore - forever/no timeout */ #define sys_sem_wait(sem) sys_arch_sem_wait(sem, 0) #ifndef sys_sem_valid -/** Check if a semaphore is valid/allocated: return 1 for valid, 0 for invalid */ +/** + * @ingroup sys_sem + * Check if a semaphore is valid/allocated: return 1 for valid, 0 for invalid + */ int sys_sem_valid(sys_sem_t *sem); #endif #ifndef sys_sem_set_invalid -/** Set a semaphore invalid so that sys_sem_valid returns 0 */ +/** + * @ingroup sys_sem + * Set a semaphore invalid so that sys_sem_valid returns 0 + */ void sys_sem_set_invalid(sys_sem_t *sem); #endif #ifndef sys_sem_valid_val -/** Same as sys_sem_valid() but taking a value, not a pointer */ +/** + * Same as sys_sem_valid() but taking a value, not a pointer + */ #define sys_sem_valid_val(sem) sys_sem_valid(&(sem)) #endif #ifndef sys_sem_set_invalid_val -/** Same as sys_sem_set_invalid() but taking a value, not a pointer */ +/** + * Same as sys_sem_set_invalid() but taking a value, not a pointer + */ #define sys_sem_set_invalid_val(sem) sys_sem_set_invalid(&(sem)) #endif -/* Time functions. */ #ifndef sys_msleep +/** + * @ingroup sys_misc + * Sleep for specified number of ms + */ void sys_msleep(u32_t ms); /* only has a (close to) 1 ms resolution. */ #endif /* Mailbox functions. */ -/** Create a new mbox of specified size +/** + * @ingroup sys_mbox + * Create a new mbox of specified size * @param mbox pointer to the mbox to create * @param size (minimum) number of messages in this mbox - * @return ERR_OK if successful, another err_t otherwise */ + * @return ERR_OK if successful, another err_t otherwise + */ err_t sys_mbox_new(sys_mbox_t *mbox, int size); -/** Post a message to an mbox - may not fail +/** + * @ingroup sys_mbox + * Post a message to an mbox - may not fail * -> blocks if full, only used from tasks not from ISR * @param mbox mbox to posts the message - * @param msg message to post (ATTENTION: can be NULL) */ + * @param msg message to post (ATTENTION: can be NULL) + */ void sys_mbox_post(sys_mbox_t *mbox, void *msg); -/** Try to post a message to an mbox - may fail if full or ISR +/** + * @ingroup sys_mbox + * Try to post a message to an mbox - may fail if full or ISR * @param mbox mbox to posts the message - * @param msg message to post (ATTENTION: can be NULL) */ + * @param msg message to post (ATTENTION: can be NULL) + */ err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg); -/** Wait for a new message to arrive in the mbox +/** + * @ingroup sys_mbox + * Wait for a new message to arrive in the mbox * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @param timeout maximum time (in milliseconds) to wait for a message (0 = wait forever) * @return time (in milliseconds) waited for a message, may be 0 if not waited or SYS_ARCH_TIMEOUT on timeout - * The returned time has to be accurate to prevent timer jitter! */ + * The returned time has to be accurate to prevent timer jitter! + */ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout); + +#if ESP_THREAD_SAFE +/** + * @ingroup sys_mbox + * Set the owner of the mbox + * @param mbox mbox to set the owner + * @param owner the owner of the mbox, it's a pointer to struct netconn + */ +void sys_mbox_set_owner(sys_mbox_t *mbox, void *owner); +#endif + /* Allow port to override with a macro, e.g. special timeout for sys_arch_mbox_fetch() */ #ifndef sys_arch_mbox_tryfetch -/** Wait for a new message to arrive in the mbox +/** + * @ingroup sys_mbox + * Wait for a new message to arrive in the mbox * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @return 0 (milliseconds) if a message has been received - * or SYS_MBOX_EMPTY if the mailbox is empty */ + * or SYS_MBOX_EMPTY if the mailbox is empty + */ u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg); #endif -/** For now, we map straight to sys_arch implementation. */ +/** + * For now, we map straight to sys_arch implementation. + */ #define sys_mbox_tryfetch(mbox, msg) sys_arch_mbox_tryfetch(mbox, msg) -/** Delete an mbox - * @param mbox mbox to delete */ +/** + * @ingroup sys_mbox + * Delete an mbox + * @param mbox mbox to delete + */ void sys_mbox_free(sys_mbox_t *mbox); #define sys_mbox_fetch(mbox, msg) sys_arch_mbox_fetch(mbox, msg, 0) #ifndef sys_mbox_valid -/** Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid */ +/** + * @ingroup sys_mbox + * Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid + */ int sys_mbox_valid(sys_mbox_t *mbox); #endif #ifndef sys_mbox_set_invalid -/** Set an mbox invalid so that sys_mbox_valid returns 0 */ +/** + * @ingroup sys_mbox + * Set an mbox invalid so that sys_mbox_valid returns 0 + */ void sys_mbox_set_invalid(sys_mbox_t *mbox); #endif #ifndef sys_mbox_valid_val -/** Same as sys_mbox_valid() but taking a value, not a pointer */ +/** + * Same as sys_mbox_valid() but taking a value, not a pointer + */ #define sys_mbox_valid_val(mbox) sys_mbox_valid(&(mbox)) #endif #ifndef sys_mbox_set_invalid_val -/** Same as sys_mbox_set_invalid() but taking a value, not a pointer */ +/** + * Same as sys_mbox_set_invalid() but taking a value, not a pointer + */ #define sys_mbox_set_invalid_val(mbox) sys_mbox_set_invalid(&(mbox)) #endif -/** The only thread function: +/** + * @ingroup sys_misc + * The only thread function: * Creates a new thread * ATTENTION: although this function returns a value, it MUST NOT FAIL (ports have to assert this!) * @param name human-readable name for the thread (used for debugging purposes) @@ -254,12 +355,17 @@ sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, void sys_init(void); #ifndef sys_jiffies -/** Ticks/jiffies since power up. */ +/** + * Ticks/jiffies since power up. + */ u32_t sys_jiffies(void); #endif -/** Returns the current time in milliseconds, - * may be the same as sys_jiffies or at least based on it. */ +/** + * @ingroup sys_time + * Returns the current time in milliseconds, + * may be the same as sys_jiffies or at least based on it. + */ u32_t sys_now(void); /* Critical Region Protection */ @@ -275,13 +381,17 @@ u32_t sys_now(void); */ #if SYS_LIGHTWEIGHT_PROT -/** SYS_ARCH_DECL_PROTECT +/** + * @ingroup sys_prot + * SYS_ARCH_DECL_PROTECT * declare a protection variable. This macro will default to defining a variable of * type sys_prot_t. If a particular port needs a different implementation, then * this macro may be defined in sys_arch.h. */ #define SYS_ARCH_DECL_PROTECT(lev) sys_prot_t lev -/** SYS_ARCH_PROTECT +/** + * @ingroup sys_prot + * SYS_ARCH_PROTECT * Perform a "fast" protect. This could be implemented by * disabling interrupts for an embedded system or by using a semaphore or * mutex. The implementation should allow calling SYS_ARCH_PROTECT when @@ -291,7 +401,9 @@ u32_t sys_now(void); * different implementation, then this macro may be defined in sys_arch.h */ #define SYS_ARCH_PROTECT(lev) lev = sys_arch_protect() -/** SYS_ARCH_UNPROTECT +/** + * @ingroup sys_prot + * SYS_ARCH_UNPROTECT * Perform a "fast" set of the protection level to "lev". This could be * implemented by setting the interrupt level to "lev" within the MACRO or by * using a semaphore or mutex. This macro will default to calling the diff --git a/tools/sdk/include/lwip/lwip/tcp.h b/tools/sdk/include/lwip/lwip/tcp.h old mode 100755 new mode 100644 index f7a46b2e830..30dbf147608 --- a/tools/sdk/include/lwip/lwip/tcp.h +++ b/tools/sdk/include/lwip/lwip/tcp.h @@ -1,3 +1,9 @@ +/** + * @file + * TCP API (to be used from TCPIP thread)\n + * See also @ref tcp_raw + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -117,7 +123,7 @@ typedef void (*tcp_err_fn)(void *arg, err_t err); * * @param arg Additional argument to pass to the callback function (@see tcp_arg()) * @param tpcb The connection pcb which is connected - * @param err An unused error code, always ERR_OK currently ;-) TODO! + * @param err An unused error code, always ERR_OK currently ;-) @todo! * Only return ERR_ABRT if you have called tcp_abort from within the * callback function! * @@ -129,15 +135,19 @@ typedef err_t (*tcp_connected_fn)(void *arg, struct tcp_pcb *tpcb, err_t err); #define RCV_WND_SCALE(pcb, wnd) (((wnd) >> (pcb)->rcv_scale)) #define SND_WND_SCALE(pcb, wnd) (((wnd) << (pcb)->snd_scale)) #define TCPWND16(x) ((u16_t)LWIP_MIN((x), 0xFFFF)) -#define TCP_WND_MAX(pcb) ((tcpwnd_size_t)(((pcb)->flags & TF_WND_SCALE) ? TCP_WND(pcb) : TCPWND16(TCP_WND(pcb)))) +#define TCP_WND_MAX(pcb) ((tcpwnd_size_t)(((pcb)->flags & TF_WND_SCALE) ? TCP_WND : TCPWND16(TCP_WND))) typedef u32_t tcpwnd_size_t; -typedef u16_t tcpflags_t; #else #define RCV_WND_SCALE(pcb, wnd) (wnd) #define SND_WND_SCALE(pcb, wnd) (wnd) #define TCPWND16(x) (x) -#define TCP_WND_MAX(pcb) TCP_WND(pcb) +#define TCP_WND_MAX(pcb) TCP_WND typedef u16_t tcpwnd_size_t; +#endif + +#if LWIP_WND_SCALE || TCP_LISTEN_BACKLOG || LWIP_TCP_TIMESTAMPS +typedef u16_t tcpflags_t; +#else typedef u8_t tcpflags_t; #endif @@ -155,34 +165,38 @@ enum tcp_state { TIME_WAIT = 10 }; -#if LWIP_CALLBACK_API - /* Function to call when a listener has been connected. - * @param arg user-supplied argument (tcp_pcb.callback_arg) - * @param pcb a new tcp_pcb that now is connected - * @param err an error argument (TODO: that is current always ERR_OK?) - * @return ERR_OK: accept the new connection, - * any other err_t aborts the new connection - */ -#define DEF_ACCEPT_CALLBACK tcp_accept_fn accept; -#else /* LWIP_CALLBACK_API */ -#define DEF_ACCEPT_CALLBACK -#endif /* LWIP_CALLBACK_API */ - /** * members common to struct tcp_pcb and struct tcp_listen_pcb */ #define TCP_PCB_COMMON(type) \ type *next; /* for the linked list */ \ void *callback_arg; \ - /* the accept callback for listen- and normal pcbs, if LWIP_CALLBACK_API */ \ - DEF_ACCEPT_CALLBACK \ enum tcp_state state; /* TCP state */ \ u8_t prio; \ /* ports are in host byte order */ \ u16_t local_port -/* the TCP protocol control block */ +/** the TCP protocol control block for listening pcbs */ +struct tcp_pcb_listen { +/** Common members of all PCB types */ + IP_PCB; +/** Protocol specific PCB members */ + TCP_PCB_COMMON(struct tcp_pcb_listen); + +#if LWIP_CALLBACK_API + /* Function to call when a listener has been connected. */ + tcp_accept_fn accept; +#endif /* LWIP_CALLBACK_API */ + +#if TCP_LISTEN_BACKLOG + u8_t backlog; + u8_t accepts_pending; +#endif /* TCP_LISTEN_BACKLOG */ +}; + + +/** the TCP protocol control block */ struct tcp_pcb { /** common PCB members */ IP_PCB; @@ -196,13 +210,19 @@ struct tcp_pcb { #define TF_ACK_DELAY 0x01U /* Delayed ACK. */ #define TF_ACK_NOW 0x02U /* Immediate ACK. */ #define TF_INFR 0x04U /* In fast recovery. */ -#define TF_TIMESTAMP 0x08U /* Timestamp option enabled */ +#define TF_CLOSEPEND 0x08U /* If this is set, tcp_close failed to enqueue the FIN (retried in tcp_tmr) */ #define TF_RXCLOSED 0x10U /* rx closed by tcp_shutdown */ #define TF_FIN 0x20U /* Connection was closed locally (FIN segment enqueued). */ #define TF_NODELAY 0x40U /* Disable Nagle algorithm */ #define TF_NAGLEMEMERR 0x80U /* nagle enabled, memerr, try to output to prevent delayed ACK to happen */ #if LWIP_WND_SCALE #define TF_WND_SCALE 0x0100U /* Window Scale option enabled */ +#endif +#if TCP_LISTEN_BACKLOG +#define TF_BACKLOGPEND 0x0200U /* If this is set, a connection pcb has increased the backlog on its listener */ +#endif +#if LWIP_TCP_TIMESTAMPS +#define TF_TIMESTAMP 0x0400U /* Timestamp option enabled */ #endif /* the rest of the fields are in host byte order @@ -236,11 +256,6 @@ struct tcp_pcb { u8_t dupacks; u32_t lastack; /* Highest acknowledged seqno. */ -#if ESP_PER_SOC_TCP_WND - tcpwnd_size_t per_soc_tcp_wnd; /* per tcp socket tcp window size */ - tcpwnd_size_t per_soc_tcp_snd_buf; /* per tcp socket tcp send buffer size */ -#endif - /* congestion avoidance/control variables */ tcpwnd_size_t cwnd; tcpwnd_size_t ssthresh; @@ -253,8 +268,6 @@ struct tcp_pcb { tcpwnd_size_t snd_wnd; /* sender window */ tcpwnd_size_t snd_wnd_max; /* the maximum sender window announced by the remote host */ - tcpwnd_size_t acked; - tcpwnd_size_t snd_buf; /* Available buffer space for sending (in bytes). */ #define TCP_SNDQUEUELEN_OVERFLOW (0xffffU-3) u16_t snd_queuelen; /* Number of pbufs currently in the send buffer. */ @@ -273,6 +286,10 @@ struct tcp_pcb { struct pbuf *refused_data; /* Data previously received but not yet taken by upper layer */ +#if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG + struct tcp_pcb_listen* listener; +#endif /* LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG */ + #if LWIP_CALLBACK_API /* Function to be called when more send buffer space is available. */ tcp_sent_fn sent; @@ -333,18 +350,6 @@ struct tcp_pcb { #define ESP_STATS_TCP_PCB(pcb) #endif -struct tcp_pcb_listen { -/* Common members of all PCB types */ - IP_PCB; -/* Protocol specific PCB members */ - TCP_PCB_COMMON(struct tcp_pcb_listen); - -#if TCP_LISTEN_BACKLOG - u8_t backlog; - u8_t accepts_pending; -#endif /* TCP_LISTEN_BACKLOG */ -}; - #if LWIP_EVENT_API enum lwip_event { @@ -369,30 +374,40 @@ struct tcp_pcb * tcp_new (void); struct tcp_pcb * tcp_new_ip_type (u8_t type); void tcp_arg (struct tcp_pcb *pcb, void *arg); -void tcp_accept (struct tcp_pcb *pcb, tcp_accept_fn accept); +#if LWIP_CALLBACK_API void tcp_recv (struct tcp_pcb *pcb, tcp_recv_fn recv); void tcp_sent (struct tcp_pcb *pcb, tcp_sent_fn sent); -void tcp_poll (struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval); void tcp_err (struct tcp_pcb *pcb, tcp_err_fn err); +void tcp_accept (struct tcp_pcb *pcb, tcp_accept_fn accept); +#endif /* LWIP_CALLBACK_API */ +void tcp_poll (struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval); +#if LWIP_TCP_TIMESTAMPS #define tcp_mss(pcb) (((pcb)->flags & TF_TIMESTAMP) ? ((pcb)->mss - 12) : (pcb)->mss) +#else /* LWIP_TCP_TIMESTAMPS */ +#define tcp_mss(pcb) ((pcb)->mss) +#endif /* LWIP_TCP_TIMESTAMPS */ #define tcp_sndbuf(pcb) (TCPWND16((pcb)->snd_buf)) #define tcp_sndqueuelen(pcb) ((pcb)->snd_queuelen) +/** @ingroup tcp_raw */ #define tcp_nagle_disable(pcb) ((pcb)->flags |= TF_NODELAY) +/** @ingroup tcp_raw */ #define tcp_nagle_enable(pcb) ((pcb)->flags = (tcpflags_t)((pcb)->flags & ~TF_NODELAY)) +/** @ingroup tcp_raw */ #define tcp_nagle_disabled(pcb) (((pcb)->flags & TF_NODELAY) != 0) #if TCP_LISTEN_BACKLOG -#define tcp_accepted(pcb) do { \ - LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", pcb->state == LISTEN); \ - (((struct tcp_pcb_listen *)(pcb))->accepts_pending--); } while(0) #define tcp_backlog_set(pcb, new_backlog) do { \ LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", (pcb)->state == LISTEN); \ ((struct tcp_pcb_listen *)(pcb))->backlog = ((new_backlog) ? (new_backlog) : 1); } while(0) +void tcp_backlog_delayed(struct tcp_pcb* pcb); +void tcp_backlog_accepted(struct tcp_pcb* pcb); #else /* TCP_LISTEN_BACKLOG */ -#define tcp_accepted(pcb) LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", \ - (pcb)->state == LISTEN) +#define tcp_backlog_set(pcb, new_backlog) +#define tcp_backlog_delayed(pcb) +#define tcp_backlog_accepted(pcb) #endif /* TCP_LISTEN_BACKLOG */ +#define tcp_accepted(pcb) /* compatibility define, not needed any more */ void tcp_recved (struct tcp_pcb *pcb, u16_t len); err_t tcp_bind (struct tcp_pcb *pcb, const ip_addr_t *ipaddr, @@ -400,7 +415,9 @@ err_t tcp_bind (struct tcp_pcb *pcb, const ip_addr_t *ipaddr, err_t tcp_connect (struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port, tcp_connected_fn connected); +struct tcp_pcb * tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err); struct tcp_pcb * tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog); +/** @ingroup tcp_raw */ #define tcp_listen(pcb) tcp_listen_with_backlog(pcb, TCP_DEFAULT_LISTEN_BACKLOG) void tcp_abort (struct tcp_pcb *pcb); @@ -428,10 +445,6 @@ const char* tcp_debug_state_str(enum tcp_state s); /* for compatibility with older implementation */ #define tcp_new_ip6() tcp_new_ip_type(IPADDR_TYPE_V6) -#if ESP_PER_SOC_TCP_WND -#define PER_SOC_WND(pcb) (pcb->per_soc_wnd) -#endif - #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/tcpip.h b/tools/sdk/include/lwip/lwip/tcpip.h old mode 100755 new mode 100644 index c1235865aec..f2f6b469f16 --- a/tools/sdk/include/lwip/lwip/tcpip.h +++ b/tools/sdk/include/lwip/lwip/tcpip.h @@ -1,3 +1,8 @@ +/** + * @file + * Functions to sync with TCPIP thread + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -37,13 +42,25 @@ #if !NO_SYS /* don't build if not configured for use in lwipopts.h */ #include "lwip/err.h" -#include "lwip/timers.h" +#include "lwip/timeouts.h" #include "lwip/netif.h" #ifdef __cplusplus extern "C" { #endif +#if LWIP_TCPIP_CORE_LOCKING +/** The global semaphore to lock the stack. */ +extern sys_mutex_t lock_tcpip_core; +/** Lock lwIP core mutex (needs @ref LWIP_TCPIP_CORE_LOCKING 1) */ +#define LOCK_TCPIP_CORE() sys_mutex_lock(&lock_tcpip_core) +/** Unlock lwIP core mutex (needs @ref LWIP_TCPIP_CORE_LOCKING 1) */ +#define UNLOCK_TCPIP_CORE() sys_mutex_unlock(&lock_tcpip_core) +#else /* LWIP_TCPIP_CORE_LOCKING */ +#define LOCK_TCPIP_CORE() +#define UNLOCK_TCPIP_CORE() +#endif /* LWIP_TCPIP_CORE_LOCKING */ + struct pbuf; struct netif; @@ -61,6 +78,10 @@ err_t tcpip_inpkt(struct pbuf *p, struct netif *inp, netif_input_fn input_fn); err_t tcpip_input(struct pbuf *p, struct netif *inp); err_t tcpip_callback_with_block(tcpip_callback_fn function, void *ctx, u8_t block); +/** + * @ingroup lwip_os + * @see tcpip_callback_with_block + */ #define tcpip_callback(f, ctx) tcpip_callback_with_block(f, ctx, 1) struct tcpip_callback_msg* tcpip_callbackmsg_new(tcpip_callback_fn function, void *ctx); @@ -71,10 +92,10 @@ err_t tcpip_trycallback(struct tcpip_callback_msg* msg); err_t pbuf_free_callback(struct pbuf *p); err_t mem_free_callback(void *m); -#if LWIP_TCPIP_TIMEOUT +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS err_t tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg); err_t tcpip_untimeout(sys_timeout_handler h, void *arg); -#endif /* LWIP_TCPIP_TIMEOUT */ +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/timeouts.h b/tools/sdk/include/lwip/lwip/timeouts.h new file mode 100644 index 00000000000..c9b93aa02ac --- /dev/null +++ b/tools/sdk/include/lwip/lwip/timeouts.h @@ -0,0 +1,121 @@ +/** + * @file + * Timer implementations + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * Simon Goldschmidt + * + */ +#ifndef LWIP_HDR_TIMEOUTS_H +#define LWIP_HDR_TIMEOUTS_H + +#include "lwip/opt.h" +#include "lwip/err.h" +#if !NO_SYS +#include "lwip/sys.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef LWIP_DEBUG_TIMERNAMES +#ifdef LWIP_DEBUG +#define LWIP_DEBUG_TIMERNAMES SYS_DEBUG +#else /* LWIP_DEBUG */ +#define LWIP_DEBUG_TIMERNAMES 0 +#endif /* LWIP_DEBUG*/ +#endif + +/** Function prototype for a stack-internal timer function that has to be + * called at a defined interval */ +typedef void (* lwip_cyclic_timer_handler)(void); + +/** This struct contains information about a stack-internal timer function + that has to be called at a defined interval */ +struct lwip_cyclic_timer { + u32_t interval_ms; + lwip_cyclic_timer_handler handler; +#if LWIP_DEBUG_TIMERNAMES + const char* handler_name; +#endif /* LWIP_DEBUG_TIMERNAMES */ +}; + +/** This array contains all stack-internal cyclic timers. To get the number of + * timers, use LWIP_ARRAYSIZE() */ +extern const struct lwip_cyclic_timer lwip_cyclic_timers[]; + +#if LWIP_TIMERS + +/** Function prototype for a timeout callback function. Register such a function + * using sys_timeout(). + * + * @param arg Additional argument to pass to the function - set up by sys_timeout() + */ +typedef void (* sys_timeout_handler)(void *arg); + +struct sys_timeo { + struct sys_timeo *next; + u32_t time; + sys_timeout_handler h; + void *arg; +#if LWIP_DEBUG_TIMERNAMES + const char* handler_name; +#endif /* LWIP_DEBUG_TIMERNAMES */ +}; + +void sys_timeouts_init(void); + +#if LWIP_DEBUG_TIMERNAMES +void sys_timeout_debug(u32_t msecs, sys_timeout_handler handler, void *arg, const char* handler_name); +#define sys_timeout(msecs, handler, arg) sys_timeout_debug(msecs, handler, arg, #handler) +#else /* LWIP_DEBUG_TIMERNAMES */ +void sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg); +#endif /* LWIP_DEBUG_TIMERNAMES */ + +void sys_untimeout(sys_timeout_handler handler, void *arg); +void sys_restart_timeouts(void); +#if NO_SYS +void sys_check_timeouts(void); +u32_t sys_timeouts_sleeptime(void); +#else /* NO_SYS */ +void sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg); +#endif /* NO_SYS */ + + +#endif /* LWIP_TIMERS */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_TIMEOUTS_H */ diff --git a/tools/sdk/include/lwip/lwip/timers.h b/tools/sdk/include/lwip/lwip/timers.h deleted file mode 100755 index d735392dde9..00000000000 --- a/tools/sdk/include/lwip/lwip/timers.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2001-2004 Swedish Institute of Computer Science. - * All rights reserved. - * - * 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. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * Simon Goldschmidt - * - */ -#ifndef LWIP_HDR_TIMERS_H -#define LWIP_HDR_TIMERS_H - -#include "lwip/opt.h" - -/* Timers are not supported when NO_SYS==1 and NO_SYS_NO_TIMERS==1 */ -#define LWIP_TIMERS (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) - -#if LWIP_TIMERS - -#include "lwip/err.h" -#if !NO_SYS -#include "lwip/sys.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef LWIP_DEBUG_TIMERNAMES -#ifdef LWIP_DEBUG -#define LWIP_DEBUG_TIMERNAMES SYS_DEBUG -#else /* LWIP_DEBUG */ -#define LWIP_DEBUG_TIMERNAMES 0 -#endif /* LWIP_DEBUG*/ -#endif - -/** Function prototype for a timeout callback function. Register such a function - * using sys_timeout(). - * - * @param arg Additional argument to pass to the function - set up by sys_timeout() - */ -typedef void (* sys_timeout_handler)(void *arg); - -struct sys_timeo { - struct sys_timeo *next; - u32_t time; - sys_timeout_handler h; - void *arg; -#if LWIP_DEBUG_TIMERNAMES - const char* handler_name; -#endif /* LWIP_DEBUG_TIMERNAMES */ -}; - -void sys_timeouts_init(void); - -#if LWIP_DEBUG_TIMERNAMES -void sys_timeout_debug(u32_t msecs, sys_timeout_handler handler, void *arg, const char* handler_name); -#define sys_timeout(msecs, handler, arg) sys_timeout_debug(msecs, handler, arg, #handler) -#else /* LWIP_DEBUG_TIMERNAMES */ -void sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg); -#endif /* LWIP_DEBUG_TIMERNAMES */ - -void sys_untimeout(sys_timeout_handler handler, void *arg); -#if NO_SYS -void sys_check_timeouts(void); -void sys_restart_timeouts(void); -u32_t sys_timeouts_sleeptime(void); -#else /* NO_SYS */ -void sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg); -#endif /* NO_SYS */ - - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_TIMERS */ -#endif /* LWIP_HDR_TIMERS_H */ diff --git a/tools/sdk/include/lwip/lwip/udp.h b/tools/sdk/include/lwip/lwip/udp.h old mode 100755 new mode 100644 index c2f6ed9df7f..b679a82ddc4 --- a/tools/sdk/include/lwip/lwip/udp.h +++ b/tools/sdk/include/lwip/lwip/udp.h @@ -1,3 +1,9 @@ +/** + * @file + * UDP API (to be used from TCPIP thread)\n + * See also @ref udp_raw + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -41,29 +47,12 @@ #include "lwip/ip_addr.h" #include "lwip/ip.h" #include "lwip/ip6_addr.h" +#include "lwip/prot/udp.h" #ifdef __cplusplus extern "C" { #endif -#define UDP_HLEN 8 - -/* Fields are (of course) in network byte order. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct udp_hdr { - PACK_STRUCT_FIELD(u16_t src); - PACK_STRUCT_FIELD(u16_t dest); /* src/dest UDP ports */ - PACK_STRUCT_FIELD(u16_t len); - PACK_STRUCT_FIELD(u16_t chksum); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - #define UDP_FLAGS_NOCHKSUM 0x01U #define UDP_FLAGS_UDPLITE 0x02U #define UDP_FLAGS_CONNECTED 0x04U @@ -88,8 +77,9 @@ struct udp_pcb; typedef void (*udp_recv_fn)(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port); +/** the UDP protocol control block */ struct udp_pcb { -/* Common members of all PCB types */ +/** Common members of all PCB types */ IP_PCB; /* Protocol specific PCB members */ @@ -174,10 +164,12 @@ void udp_init (void); #define udp_set_multicast_ttl(pcb, value) do { (pcb)->mcast_ttl = value; } while(0) #define udp_get_multicast_ttl(pcb) ((pcb)->mcast_ttl) +#if ESP_LWIP #if LWIP_IPV6_MLD #define udp_set_multicast_netif_ip6addr(pcb, ip6addr) ip_addr_copy_from_ip6((pcb)->multicast_ip, *(ip6addr)) #define udp_get_multicast_netif_ip6addr(pcb) ip_2_ip6(&(pcb)->multicast_ip) #endif +#endif #endif /* LWIP_MULTICAST_TX_OPTIONS */ @@ -187,9 +179,7 @@ void udp_debug_print(struct udp_hdr *udphdr); #define udp_debug_print(udphdr) #endif -#if LWIP_IPV4 -void udp_netif_ipv4_addr_changed(const ip4_addr_t* old_addr, const ip4_addr_t* new_addr); -#endif /* LWIP_IPV4 */ +void udp_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr); #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwipopts.h b/tools/sdk/include/lwip/lwipopts.h index 3e8d26ee3b8..13a3632d43a 100644 --- a/tools/sdk/include/lwip/lwipopts.h +++ b/tools/sdk/include/lwip/lwipopts.h @@ -38,10 +38,14 @@ #include #include #include +#include +#include #include "esp_task.h" #include "esp_system.h" #include "sdkconfig.h" +#include "netif/dhcp_state.h" + /* Enable all Espressif-only options */ /* @@ -218,6 +222,19 @@ */ #define DHCP_DOES_ARP_CHECK CONFIG_LWIP_DHCP_DOES_ARP_CHECK + +/** + * CONFIG_LWIP_DHCP_RESTORE_LAST_IP==1: Last valid IP address obtained from DHCP server + * is restored after reset/power-up. + */ +#if CONFIG_LWIP_DHCP_RESTORE_LAST_IP + +#define LWIP_DHCP_IP_ADDR_RESTORE() dhcp_ip_addr_restore(netif) +#define LWIP_DHCP_IP_ADDR_STORE() dhcp_ip_addr_store(netif) +#define LWIP_DHCP_IP_ADDR_ERASE() dhcp_ip_addr_erase(esp_netif[tcpip_if]) + +#endif + /* ------------------------------------ ---------- AUTOIP options ---------- @@ -294,6 +311,12 @@ */ #define TCP_QUEUE_OOSEQ CONFIG_TCP_QUEUE_OOSEQ +/** + * ESP_TCP_KEEP_CONNECTION_WHEN_IP_CHANGES==1: Keep TCP connection when IP changed + * scenario happens: 192.168.0.2 -> 0.0.0.0 -> 192.168.0.2 or 192.168.0.2 -> 0.0.0.0 + */ + +#define ESP_TCP_KEEP_CONNECTION_WHEN_IP_CHANGES CONFIG_ESP_TCP_KEEP_CONNECTION_WHEN_IP_CHANGES /* * LWIP_EVENT_API==1: The user defines lwip_tcp_event() to receive all * events (accept, sent, etc) that happen in the system. @@ -340,6 +363,19 @@ #error "One of CONFIG_TCP_OVERSIZE_xxx options should be set by sdkconfig" #endif +/** + * LWIP_WND_SCALE and TCP_RCV_SCALE: + * Set LWIP_WND_SCALE to 1 to enable window scaling. + * Set TCP_RCV_SCALE to the desired scaling factor (shift count in the + * range of [0..14]). + * When LWIP_WND_SCALE is enabled but TCP_RCV_SCALE is 0, we can use a large + * send window while having a small receive window only. + */ +#ifdef CONFIG_LWIP_WND_SCALE +#define LWIP_WND_SCALE 1 +#define TCP_RCV_SCALE CONFIG_TCP_RCV_SCALE +#endif + /* ---------------------------------- ---------- Pbuf options ---------- @@ -618,7 +654,6 @@ --------------------------------------- */ #define LWIP_HOOK_IP4_ROUTE_SRC ip4_route_src_hook - /* --------------------------------------- ---------- Debugging options ---------- @@ -698,18 +733,21 @@ */ #define LWIP_POSIX_SOCKETS_IO_NAMES 0 - /** - * Socket offset is also determined via the VFS layer at - * filesystem registration time (see port/vfs_lwip.c) + * FD_SETSIZE from sys/types.h is the maximum number of supported file + * descriptors and CONFIG_LWIP_MAX_SOCKETS defines the number of sockets; + * LWIP_SOCKET_OFFSET is configured to use the largest numbers of file + * descriptors for sockets. File descriptors from 0 to LWIP_SOCKET_OFFSET-1 + * are non-socket descriptors and from LWIP_SOCKET_OFFSET to FD_SETSIZE are + * socket descriptors. */ -#define LWIP_SOCKET_OFFSET lwip_socket_offset +#define LWIP_SOCKET_OFFSET (FD_SETSIZE - CONFIG_LWIP_MAX_SOCKETS) /* Enable all Espressif-only options */ #define ESP_LWIP 1 #define ESP_LWIP_ARP 1 -#define ESP_PER_SOC_TCP_WND 1 +#define ESP_PER_SOC_TCP_WND 0 #define ESP_THREAD_SAFE 1 #define ESP_THREAD_SAFE_DEBUG LWIP_DBG_OFF #define ESP_DHCP 1 @@ -724,8 +762,12 @@ #define ESP_STATS_DROP CONFIG_LWIP_STATS #define ESP_STATS_TCP 0 #define ESP_DHCP_TIMER 1 +#define ESP_DHCPS_TIMER 1 #define ESP_LWIP_LOGI(...) ESP_LOGI("lwip", __VA_ARGS__) #define ESP_PING 1 +#define ESP_HAS_SELECT 1 +#define ESP_AUTO_RECV 1 +#define ESP_GRATUITOUS_ARP CONFIG_ESP_GRATUITOUS_ARP #if CONFIG_LWIP_IRAM_OPTIMIZATION #define ESP_IRAM_ATTR IRAM_ATTR @@ -733,9 +775,6 @@ #define ESP_IRAM_ATTR #endif -#define TCP_WND_DEFAULT CONFIG_TCP_WND_DEFAULT -#define TCP_SND_BUF_DEFAULT CONFIG_TCP_SND_BUF_DEFAULT - #if ESP_PERF #define DBG_PERF_PATH_SET(dir, point) #define DBG_PERF_FILTER_LEN 1000 @@ -760,9 +799,18 @@ enum { #define DBG_PERF_FILTER_LEN 1000 #endif +#define TCP_SND_BUF CONFIG_TCP_SND_BUF_DEFAULT +#define TCP_WND CONFIG_TCP_WND_DEFAULT + #if ESP_PER_SOC_TCP_WND +#define TCP_WND_DEFAULT CONFIG_TCP_WND_DEFAULT +#define TCP_SND_BUF_DEFAULT CONFIG_TCP_SND_BUF_DEFAULT #define TCP_WND(pcb) (pcb->per_soc_tcp_wnd) #define TCP_SND_BUF(pcb) (pcb->per_soc_tcp_snd_buf) +#define TCP_SND_QUEUELEN(pcb) ((4 * (TCP_SND_BUF((pcb))) + (TCP_MSS - 1))/(TCP_MSS)) +#define TCP_SNDLOWAT(pcb) LWIP_MIN(LWIP_MAX(((TCP_SND_BUF((pcb)))/2), (2 * TCP_MSS) + 1), (TCP_SND_BUF((pcb))) - 1) +#define TCP_SNDQUEUELOWAT(pcb) LWIP_MAX(((TCP_SND_QUEUELEN((pcb)))/2), 5) +#define TCP_WND_UPDATE_THRESHOLD(pcb) LWIP_MIN((TCP_WND((pcb)) / 4), (TCP_MSS * 4)) #endif /** diff --git a/tools/sdk/include/lwip/netdb.h b/tools/sdk/include/lwip/netdb.h old mode 100755 new mode 100644 index 12d4c7f566c..363154f6889 --- a/tools/sdk/include/lwip/netdb.h +++ b/tools/sdk/include/lwip/netdb.h @@ -31,3 +31,10 @@ */ #include "lwip/netdb.h" + +#ifdef ESP_PLATFORM +int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, + char *host, socklen_t hostlen, + char *serv, socklen_t servlen, int flags); + +#endif diff --git a/tools/sdk/include/lwip/netif/dhcp_state.h b/tools/sdk/include/lwip/netif/dhcp_state.h new file mode 100644 index 00000000000..ffea1164011 --- /dev/null +++ b/tools/sdk/include/lwip/netif/dhcp_state.h @@ -0,0 +1,33 @@ +// 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 _DHCP_STATE_H_ +#define _DHCP_STATE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +bool dhcp_ip_addr_restore(void *netif); + +void dhcp_ip_addr_store(void *netif); + +void dhcp_ip_addr_erase(void *netif); + +#ifdef __cplusplus +} +#endif + +#endif /* _DHCP_STATE_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/lwip/netif/etharp.h b/tools/sdk/include/lwip/netif/etharp.h old mode 100755 new mode 100644 index 3e25c389d25..b536fd280fa --- a/tools/sdk/include/lwip/netif/etharp.h +++ b/tools/sdk/include/lwip/netif/etharp.h @@ -1,147 +1,3 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * Copyright (c) 2003-2004 Leon Woestenberg - * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. - * All rights reserved. - * - * 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. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * - */ - -#ifndef LWIP_HDR_NETIF_ETHARP_H -#define LWIP_HDR_NETIF_ETHARP_H - -#include "lwip/opt.h" - -#if LWIP_ARP || LWIP_ETHERNET /* don't build if not configured for use in lwipopts.h */ - -#include "lwip/pbuf.h" -#include "lwip/ip4_addr.h" -#include "lwip/netif.h" -#include "lwip/ip4.h" +/* ARP has been moved to core/ipv4, provide this #include for compatibility only */ +#include "lwip/etharp.h" #include "netif/ethernet.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if LWIP_IPV4 && LWIP_ARP /* don't build if not configured for use in lwipopts.h */ - -#ifndef ETHARP_HWADDR_LEN -#define ETHARP_HWADDR_LEN ETH_HWADDR_LEN -#endif - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -/** the ARP message, see RFC 826 ("Packet format") */ -struct etharp_hdr { - PACK_STRUCT_FIELD(u16_t hwtype); - PACK_STRUCT_FIELD(u16_t proto); - PACK_STRUCT_FLD_8(u8_t hwlen); - PACK_STRUCT_FLD_8(u8_t protolen); - PACK_STRUCT_FIELD(u16_t opcode); - PACK_STRUCT_FLD_S(struct eth_addr shwaddr); - PACK_STRUCT_FLD_S(struct ip4_addr2 sipaddr); - PACK_STRUCT_FLD_S(struct eth_addr dhwaddr); - PACK_STRUCT_FLD_S(struct ip4_addr2 dipaddr); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define SIZEOF_ETHARP_HDR 28 - -#define SIZEOF_ETHARP_PACKET (SIZEOF_ETH_HDR + SIZEOF_ETHARP_HDR) -#if ETHARP_SUPPORT_VLAN && defined(LWIP_HOOK_VLAN_SET) -#define SIZEOF_ETHARP_PACKET_TX (SIZEOF_ETHARP_PACKET + SIZEOF_VLAN_HDR) -#else /* ETHARP_SUPPORT_VLAN && defined(LWIP_HOOK_VLAN_SET) */ -#define SIZEOF_ETHARP_PACKET_TX SIZEOF_ETHARP_PACKET -#endif /* ETHARP_SUPPORT_VLAN && defined(LWIP_HOOK_VLAN_SET) */ - -/** 1 seconds period */ -#define ARP_TMR_INTERVAL 1000 - -/** ARP message types (opcodes) */ -#define ARP_REQUEST 1 -#define ARP_REPLY 2 - -#if ARP_QUEUEING -/** struct for queueing outgoing packets for unknown address - * defined here to be accessed by memp.h - */ -struct etharp_q_entry { - struct etharp_q_entry *next; - struct pbuf *p; -}; -#endif /* ARP_QUEUEING */ - -#define etharp_init() /* Compatibility define, no init needed. */ -void etharp_tmr(void); -s8_t etharp_find_addr(struct netif *netif, const ip4_addr_t *ipaddr, - struct eth_addr **eth_ret, const ip4_addr_t **ip_ret); -u8_t etharp_get_entry(u8_t i, ip4_addr_t **ipaddr, struct netif **netif, struct eth_addr **eth_ret); -err_t etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr); -err_t etharp_query(struct netif *netif, const ip4_addr_t *ipaddr, struct pbuf *q); -err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr); -/** For Ethernet network interfaces, we might want to send "gratuitous ARP"; - * this is an ARP packet sent by a node in order to spontaneously cause other - * nodes to update an entry in their ARP cache. - * From RFC 3220 "IP Mobility Support for IPv4" section 4.6. */ -#define etharp_gratuitous(netif) etharp_request((netif), netif_ip4_addr(netif)) -void etharp_cleanup_netif(struct netif *netif); - -#if ETHARP_SUPPORT_STATIC_ENTRIES -err_t etharp_add_static_entry(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr); -err_t etharp_remove_static_entry(const ip4_addr_t *ipaddr); -#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ - -#if LWIP_AUTOIP -err_t etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr, - const struct eth_addr *ethdst_addr, - const struct eth_addr *hwsrc_addr, const ip4_addr_t *ipsrc_addr, - const struct eth_addr *hwdst_addr, const ip4_addr_t *ipdst_addr, - const u16_t opcode); -#endif /* LWIP_AUTOIP */ - -#endif /* LWIP_IPV4 && LWIP_ARP */ - -void etharp_arp_input(struct netif *netif, struct eth_addr *ethaddr, struct pbuf *p); - -#if ETHARP_TRUST_IP_MAC -void etharp_ip_input(struct netif *netif, struct pbuf *p); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_ARP || LWIP_ETHERNET */ - -#endif /* LWIP_HDR_NETIF_ETHARP_H */ diff --git a/tools/sdk/include/lwip/netif/ethernet.h b/tools/sdk/include/lwip/netif/ethernet.h old mode 100755 new mode 100644 index 17623e4ad16..49649cbf8b2 --- a/tools/sdk/include/lwip/netif/ethernet.h +++ b/tools/sdk/include/lwip/netif/ethernet.h @@ -1,3 +1,9 @@ +/** + * @file + * Ethernet input function - handles INCOMING ethernet level traffic + * To be used in most low-level netif implementations + */ + /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * Copyright (c) 2003-2004 Leon Woestenberg @@ -39,111 +45,12 @@ #include "lwip/pbuf.h" #include "lwip/netif.h" +#include "lwip/prot/ethernet.h" #ifdef __cplusplus extern "C" { #endif -#ifndef ETH_HWADDR_LEN -#ifdef ETHARP_HWADDR_LEN -#define ETH_HWADDR_LEN ETHARP_HWADDR_LEN /* compatibility mode */ -#else -#define ETH_HWADDR_LEN 6 -#endif -#endif - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct eth_addr { - PACK_STRUCT_FLD_8(u8_t addr[ETH_HWADDR_LEN]); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -/** Ethernet header */ -struct eth_hdr { -#if ETH_PAD_SIZE - PACK_STRUCT_FLD_8(u8_t padding[ETH_PAD_SIZE]); -#endif - PACK_STRUCT_FLD_S(struct eth_addr dest); - PACK_STRUCT_FLD_S(struct eth_addr src); - PACK_STRUCT_FIELD(u16_t type); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define SIZEOF_ETH_HDR (14 + ETH_PAD_SIZE) - -#if ETHARP_SUPPORT_VLAN - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -/** VLAN header inserted between ethernet header and payload - * if 'type' in ethernet header is ETHTYPE_VLAN. - * See IEEE802.Q */ -struct eth_vlan_hdr { - PACK_STRUCT_FIELD(u16_t prio_vid); - PACK_STRUCT_FIELD(u16_t tpid); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define SIZEOF_VLAN_HDR 4 -#define VLAN_ID(vlan_hdr) (htons((vlan_hdr)->prio_vid) & 0xFFF) - -#endif /* ETHARP_SUPPORT_VLAN */ - -/* A list of often ethtypes (although lwIP does not use all of them): */ -#define ETHTYPE_IP 0x0800U /* Internet protocol v4 */ -#define ETHTYPE_ARP 0x0806U /* Address resolution protocol */ -#define ETHTYPE_WOL 0x0842U /* Wake on lan */ -#define ETHTYPE_VLAN 0x8100U /* Virtual local area network */ -#define ETHTYPE_IPV6 0x86DDU /* Internet protocol v6 */ -#define ETHTYPE_PPPOEDISC 0x8863U /* PPP Over Ethernet Discovery Stage */ -#define ETHTYPE_PPPOE 0x8864U /* PPP Over Ethernet Session Stage */ -#define ETHTYPE_JUMBO 0x8870U /* Jumbo Frames */ -#define ETHTYPE_PROFINET 0x8892U /* Process field network */ -#define ETHTYPE_ETHERCAT 0x88A4U /* Ethernet for control automation technology */ -#define ETHTYPE_LLDP 0x88CCU /* Link layer discovery protocol */ -#define ETHTYPE_SERCOS 0x88CDU /* Serial real-time communication system */ -#define ETHTYPE_PTP 0x88F7U /* Precision time protocol */ -#define ETHTYPE_QINQ 0x9100U /* Q-in-Q, 802.1ad */ - -/** The 24-bit IANA IPv4-multicast OUI is 01-00-5e: */ -#define LL_IP4_MULTICAST_ADDR_0 0x01 -#define LL_IP4_MULTICAST_ADDR_1 0x00 -#define LL_IP4_MULTICAST_ADDR_2 0x5e - -/** IPv6 multicast uses this prefix */ -#define LL_IP6_MULTICAST_ADDR_0 0x33 -#define LL_IP6_MULTICAST_ADDR_1 0x33 - -/** MEMCPY-like macro to copy to/from struct eth_addr's that are local variables - * or known to be 32-bit aligned within the protocol header. */ -#ifndef ETHADDR32_COPY -#define ETHADDR32_COPY(dst, src) SMEMCPY(dst, src, ETH_HWADDR_LEN) -#endif - -/** MEMCPY-like macro to copy to/from struct eth_addr's that are no local - * variables and known to be 16-bit aligned within the protocol header. */ -#ifndef ETHADDR16_COPY -#define ETHADDR16_COPY(dst, src) SMEMCPY(dst, src, ETH_HWADDR_LEN) -#endif - #if LWIP_ARP || LWIP_ETHERNET /** Define this to 1 and define LWIP_ARP_FILTER_NETIF_FN(pbuf, netif, type) @@ -157,8 +64,7 @@ PACK_STRUCT_END #endif err_t ethernet_input(struct pbuf *p, struct netif *netif); - -#define eth_addr_cmp(addr1, addr2) (memcmp((addr1)->addr, (addr2)->addr, ETH_HWADDR_LEN) == 0) +err_t ethernet_output(struct netif* netif, struct pbuf* p, const struct eth_addr* src, const struct eth_addr* dst, u16_t eth_type); extern const struct eth_addr ethbroadcast, ethzero; diff --git a/tools/sdk/include/lwip/netif/ethernetif.h b/tools/sdk/include/lwip/netif/ethernetif.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/lwip/netif/lowpan6.h b/tools/sdk/include/lwip/netif/lowpan6.h old mode 100755 new mode 100644 index 21552938990..4174644bb36 --- a/tools/sdk/include/lwip/netif/lowpan6.h +++ b/tools/sdk/include/lwip/netif/lowpan6.h @@ -73,7 +73,9 @@ err_t lowpan6_if_init(struct netif *netif); /* pan_id in network byte order. */ err_t lowpan6_set_pan_id(u16_t pan_id); +#if !NO_SYS err_t tcpip_6lowpan_input(struct pbuf *p, struct netif *inp); +#endif /* !NO_SYS */ #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/netif/lowpan6_opts.h b/tools/sdk/include/lwip/netif/lowpan6_opts.h old mode 100755 new mode 100644 index 6a769575934..fb93ea05de6 --- a/tools/sdk/include/lwip/netif/lowpan6_opts.h +++ b/tools/sdk/include/lwip/netif/lowpan6_opts.h @@ -1,3 +1,8 @@ +/** + * @file + * 6LowPAN options list + */ + /* * Copyright (c) 2015 Inico Technologies Ltd. * All rights reserved. diff --git a/tools/sdk/include/lwip/netif/ppp/ccp.h b/tools/sdk/include/lwip/netif/ppp/ccp.h old mode 100755 new mode 100644 index a8eab9c0af0..14dd65962c7 --- a/tools/sdk/include/lwip/netif/ppp/ccp.h +++ b/tools/sdk/include/lwip/netif/ppp/ccp.h @@ -30,7 +30,7 @@ * $Id: ccp.h,v 1.12 2004/11/04 10:02:26 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && CCP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef CCP_H diff --git a/tools/sdk/include/lwip/netif/ppp/chap-md5.h b/tools/sdk/include/lwip/netif/ppp/chap-md5.h old mode 100755 new mode 100644 index a05a157d06e..eb0269fe508 --- a/tools/sdk/include/lwip/netif/ppp/chap-md5.h +++ b/tools/sdk/include/lwip/netif/ppp/chap-md5.h @@ -28,7 +28,7 @@ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && CHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ extern const struct chap_digest_type md5_digest; diff --git a/tools/sdk/include/lwip/netif/ppp/chap-new.h b/tools/sdk/include/lwip/netif/ppp/chap-new.h old mode 100755 new mode 100644 index 9b7c048757b..64eae322029 --- a/tools/sdk/include/lwip/netif/ppp/chap-new.h +++ b/tools/sdk/include/lwip/netif/ppp/chap-new.h @@ -28,7 +28,7 @@ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && CHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef CHAP_H diff --git a/tools/sdk/include/lwip/netif/ppp/chap_ms.h b/tools/sdk/include/lwip/netif/ppp/chap_ms.h old mode 100755 new mode 100644 index 709bb89915d..0795291158f --- a/tools/sdk/include/lwip/netif/ppp/chap_ms.h +++ b/tools/sdk/include/lwip/netif/ppp/chap_ms.h @@ -30,15 +30,15 @@ * $Id: chap_ms.h,v 1.13 2004/11/15 22:13:26 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && MSCHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ -#ifndef __CHAPMS_INCLUDE__ +#ifndef CHAPMS_INCLUDE +#define CHAPMS_INCLUDE extern const struct chap_digest_type chapms_digest; extern const struct chap_digest_type chapms2_digest; -#define __CHAPMS_INCLUDE__ -#endif /* __CHAPMS_INCLUDE__ */ +#endif /* CHAPMS_INCLUDE */ #endif /* PPP_SUPPORT && MSCHAP_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/eap.h b/tools/sdk/include/lwip/netif/ppp/eap.h old mode 100755 new mode 100644 index 7dfd67636a3..3ee9aaf81ae --- a/tools/sdk/include/lwip/netif/ppp/eap.h +++ b/tools/sdk/include/lwip/netif/ppp/eap.h @@ -20,7 +20,7 @@ * $Id: eap.h,v 1.2 2003/06/11 23:56:26 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && EAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPP_EAP_H @@ -148,12 +148,12 @@ typedef struct eap_state { /* * Timeouts. */ -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ #define EAP_DEFTIMEOUT 3 /* Timeout (seconds) for rexmit */ #define EAP_DEFTRANSMITS 10 /* max # times to transmit */ #define EAP_DEFREQTIME 20 /* Time to wait for peer request */ #define EAP_DEFALLOWREQ 20 /* max # times to accept requests */ -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ void eap_authwithpeer(ppp_pcb *pcb, const char *localname); void eap_authpeer(ppp_pcb *pcb, const char *localname); diff --git a/tools/sdk/include/lwip/netif/ppp/ecp.h b/tools/sdk/include/lwip/netif/ppp/ecp.h old mode 100755 new mode 100644 index cba6678ed04..5cdce29d5b2 --- a/tools/sdk/include/lwip/netif/ppp/ecp.h +++ b/tools/sdk/include/lwip/netif/ppp/ecp.h @@ -31,7 +31,7 @@ * $Id: ecp.h,v 1.2 2003/01/10 07:12:36 fcusack Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && ECP_SUPPORT /* don't build if not configured for use in lwipopts.h */ typedef struct ecp_options { diff --git a/tools/sdk/include/lwip/netif/ppp/eui64.h b/tools/sdk/include/lwip/netif/ppp/eui64.h old mode 100755 new mode 100644 index dffb5e41502..20ac22eede7 --- a/tools/sdk/include/lwip/netif/ppp/eui64.h +++ b/tools/sdk/include/lwip/netif/ppp/eui64.h @@ -35,14 +35,14 @@ * $Id: eui64.h,v 1.6 2002/12/04 23:03:32 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPP_IPV6_SUPPORT /* don't build if not configured for use in lwipopts.h */ -#ifndef __EUI64_H__ -#define __EUI64_H__ +#ifndef EUI64_H +#define EUI64_H /* - * TODO: + * @todo: * * Maybe this should be done by processing struct in6_addr directly... */ @@ -84,11 +84,11 @@ typedef union #define eui64_set32(e, l) do { \ (e).e32[0] = 0; \ - (e).e32[1] = htonl(l); \ + (e).e32[1] = lwip_htonl(l); \ } while (0) #define eui64_setlo32(e, l) eui64_set32(e, l) char *eui64_ntoa(eui64_t); /* Returns ascii representation of id */ -#endif /* __EUI64_H__ */ +#endif /* EUI64_H */ #endif /* PPP_SUPPORT && PPP_IPV6_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/fsm.h b/tools/sdk/include/lwip/netif/ppp/fsm.h old mode 100755 new mode 100644 index fc0a4b1060d..b6915d3b807 --- a/tools/sdk/include/lwip/netif/ppp/fsm.h +++ b/tools/sdk/include/lwip/netif/ppp/fsm.h @@ -42,7 +42,7 @@ * $Id: fsm.h,v 1.10 2004/11/13 02:28:15 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef FSM_H @@ -150,12 +150,12 @@ typedef struct fsm_callbacks { /* * Timeouts. */ -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ #define DEFTIMEOUT 3 /* Timeout time in seconds */ #define DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ #define DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ #define DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ /* diff --git a/tools/sdk/include/lwip/netif/ppp/ipcp.h b/tools/sdk/include/lwip/netif/ppp/ipcp.h old mode 100755 new mode 100644 index 298f8dc66ca..45f46b31ff6 --- a/tools/sdk/include/lwip/netif/ppp/ipcp.h +++ b/tools/sdk/include/lwip/netif/ppp/ipcp.h @@ -42,7 +42,7 @@ * $Id: ipcp.h,v 1.14 2002/12/04 23:03:32 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPP_IPV4_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef IPCP_H diff --git a/tools/sdk/include/lwip/netif/ppp/ipv6cp.h b/tools/sdk/include/lwip/netif/ppp/ipv6cp.h old mode 100755 new mode 100644 index 540a7d180a2..07d1ae31867 --- a/tools/sdk/include/lwip/netif/ppp/ipv6cp.h +++ b/tools/sdk/include/lwip/netif/ppp/ipv6cp.h @@ -138,7 +138,7 @@ * $Id: ipv6cp.h,v 1.7 2002/12/04 23:03:32 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPP_IPV6_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef IPV6CP_H diff --git a/tools/sdk/include/lwip/netif/ppp/lcp.h b/tools/sdk/include/lwip/netif/ppp/lcp.h old mode 100755 new mode 100644 index 04970699ac6..12e2a05fc90 --- a/tools/sdk/include/lwip/netif/ppp/lcp.h +++ b/tools/sdk/include/lwip/netif/ppp/lcp.h @@ -42,7 +42,7 @@ * $Id: lcp.h,v 1.20 2004/11/14 22:53:42 carlsonj Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef LCP_H @@ -90,11 +90,11 @@ /* Value used as data for CI_CALLBACK option */ #define CBCP_OPT 6 /* Use callback control protocol */ -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ #define DEFMRU 1500 /* Try for this */ #define MINMRU 128 /* No MRUs below this */ #define MAXMRU 16384 /* Normally limit MRU to this */ -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ /* An endpoint discriminator, used with multilink. */ #define MAX_ENDP_LEN 20 /* maximum length of discriminator value */ @@ -110,7 +110,9 @@ struct epdisc { typedef struct lcp_options { unsigned int passive :1; /* Don't die if we don't get a response */ unsigned int silent :1; /* Wait for the other end to start first */ +#if 0 /* UNUSED */ unsigned int restart :1; /* Restart vs. exit after close */ +#endif /* UNUSED */ unsigned int neg_mru :1; /* Negotiate the MRU? */ unsigned int neg_asyncmap :1; /* Negotiate the async map? */ #if PAP_SUPPORT @@ -159,11 +161,11 @@ void lcp_sprotrej(ppp_pcb *pcb, u_char *p, int len); /* send protocol reject extern const struct protent lcp_protent; -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ /* Default number of times we receive our magic number from the peer before deciding the link is looped-back. */ #define DEFLOOPBACKFAIL 10 -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ #endif /* LCP_H */ #endif /* PPP_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/magic.h b/tools/sdk/include/lwip/netif/ppp/magic.h old mode 100755 new mode 100644 index 678ff724d54..a2a9b530e58 --- a/tools/sdk/include/lwip/netif/ppp/magic.h +++ b/tools/sdk/include/lwip/netif/ppp/magic.h @@ -74,7 +74,7 @@ * Extracted from avos. *****************************************************************************/ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef MAGIC_H diff --git a/tools/sdk/include/lwip/netif/ppp/mppe.h b/tools/sdk/include/lwip/netif/ppp/mppe.h old mode 100755 new mode 100644 index 93086955c49..1ae8a5d9247 --- a/tools/sdk/include/lwip/netif/ppp/mppe.h +++ b/tools/sdk/include/lwip/netif/ppp/mppe.h @@ -33,17 +33,13 @@ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && MPPE_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef MPPE_H #define MPPE_H -#if LWIP_INCLUDED_POLARSSL_ARC4 -#include "netif/ppp/polarssl/arc4.h" -#else -#include "polarssl/arc4.h" -#endif +#include "netif/ppp/pppcrypt.h" #define MPPE_PAD 4 /* MPPE growth per frame */ #define MPPE_MAX_KEY_LEN 16 /* largest key length (128-bit) */ @@ -63,7 +59,7 @@ * This is not nice ... the alternative is a bitfield struct though. * And unfortunately, we cannot share the same bits for the option * names above since C and H are the same bit. We could do a u_int32 - * but then we have to do a htonl() all the time and/or we still need + * but then we have to do a lwip_htonl() all the time and/or we still need * to know which octet is which. */ #define MPPE_C_BIT 0x01 /* MPPC */ @@ -152,7 +148,7 @@ static const u8_t mppe_sha1_pad2[SHA1_PAD_SIZE] = { * State for an MPPE (de)compressor. */ typedef struct ppp_mppe_state { - arc4_context arc4; + lwip_arc4_context arc4; u8_t master_key[MPPE_MAX_KEY_LEN]; u8_t session_key[MPPE_MAX_KEY_LEN]; u8_t keylen; /* key length in bytes */ diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/arc4.h b/tools/sdk/include/lwip/netif/ppp/polarssl/arc4.h old mode 100755 new mode 100644 index 95d9b34a93d..4af724cd900 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/arc4.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/arc4.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_ARC4 #ifndef LWIP_INCLUDED_POLARSSL_ARC4_H diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/des.h b/tools/sdk/include/lwip/netif/ppp/polarssl/des.h old mode 100755 new mode 100644 index d0858bd823f..e893890ed76 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/des.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/des.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_DES #ifndef LWIP_INCLUDED_POLARSSL_DES_H diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/md4.h b/tools/sdk/include/lwip/netif/ppp/polarssl/md4.h old mode 100755 new mode 100644 index a382f85a85c..570445687e1 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/md4.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/md4.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_MD4 #ifndef LWIP_INCLUDED_POLARSSL_MD4_H diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/md5.h b/tools/sdk/include/lwip/netif/ppp/polarssl/md5.h old mode 100755 new mode 100644 index a299d98cb5c..12440118906 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/md5.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/md5.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_MD5 #ifndef LWIP_INCLUDED_POLARSSL_MD5_H diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/sha1.h b/tools/sdk/include/lwip/netif/ppp/polarssl/sha1.h old mode 100755 new mode 100644 index 56d947c2643..a4c53e07c50 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/sha1.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/sha1.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_SHA1 #ifndef LWIP_INCLUDED_POLARSSL_SHA1_H diff --git a/tools/sdk/include/lwip/netif/ppp/ppp.h b/tools/sdk/include/lwip/netif/ppp/ppp.h old mode 100755 new mode 100644 index 4a50205476a..d9ea097efdb --- a/tools/sdk/include/lwip/netif/ppp/ppp.h +++ b/tools/sdk/include/lwip/netif/ppp/ppp.h @@ -31,7 +31,7 @@ * Original derived from BSD codes. *****************************************************************************/ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPP_H @@ -42,13 +42,12 @@ #include "lwip/mem.h" #include "lwip/netif.h" #include "lwip/sys.h" -#include "lwip/sio.h" -#include "lwip/timers.h" +#include "lwip/timeouts.h" #if PPP_IPV6_SUPPORT #include "lwip/ip6_addr.h" #endif /* PPP_IPV6_SUPPORT */ -/* Disable non-working or rarely used PPP feature, so rarely that we don't want to bloat opt.h with them */ +/* Disable non-working or rarely used PPP feature, so rarely that we don't want to bloat ppp_opts.h with them */ #ifndef PPP_OPTIONS #define PPP_OPTIONS 0 #endif @@ -111,18 +110,18 @@ * Values for phase. */ #define PPP_PHASE_DEAD 0 -#define PPP_PHASE_INITIALIZE 1 -#define PPP_PHASE_SERIALCONN 2 -#define PPP_PHASE_DORMANT 3 -#define PPP_PHASE_ESTABLISH 4 -#define PPP_PHASE_AUTHENTICATE 5 -#define PPP_PHASE_CALLBACK 6 -#define PPP_PHASE_NETWORK 7 -#define PPP_PHASE_RUNNING 8 -#define PPP_PHASE_TERMINATE 9 -#define PPP_PHASE_DISCONNECT 10 -#define PPP_PHASE_HOLDOFF 11 -#define PPP_PHASE_MASTER 12 +#define PPP_PHASE_MASTER 1 +#define PPP_PHASE_HOLDOFF 2 +#define PPP_PHASE_INITIALIZE 3 +#define PPP_PHASE_SERIALCONN 4 +#define PPP_PHASE_DORMANT 5 +#define PPP_PHASE_ESTABLISH 6 +#define PPP_PHASE_AUTHENTICATE 7 +#define PPP_PHASE_CALLBACK 8 +#define PPP_PHASE_NETWORK 9 +#define PPP_PHASE_RUNNING 10 +#define PPP_PHASE_TERMINATE 11 +#define PPP_PHASE_DISCONNECT 12 /* Error codes. */ #define PPPERR_NONE 0 /* No error. */ @@ -311,7 +310,6 @@ struct ppp_addrs { * PPP interface control block. */ struct ppp_pcb_s { - /* -- below are data that will NOT be cleared between two sessions */ ppp_settings settings; const struct link_callbacks *link_cb; void *link_ctx_cb; @@ -321,18 +319,12 @@ struct ppp_pcb_s { #endif /* PPP_NOTIFY_PHASE */ void *ctx_cb; /* Callbacks optional pointer */ struct netif *netif; /* PPP interface */ - - /* -- below are data that will be cleared between two sessions */ - - /* - * phase must be the first member of cleared members, because it is used to know - * which part must not be cleared. - */ u8_t phase; /* where the link is at */ u8_t err_code; /* Code indicating why interface is down. */ /* flags */ #if PPP_IPV4_SUPPORT + unsigned int ask_for_local :1; /* request our address from peer */ unsigned int ipcp_is_open :1; /* haven't called np_finished() */ unsigned int ipcp_is_up :1; /* have called ipcp_up() */ unsigned int if4_up :1; /* True when the IPv4 interface is up. */ @@ -432,7 +424,13 @@ struct ppp_pcb_s { ************************/ /* - * Set auth helper, optional, you can either fill ppp_pcb->settings. + * WARNING: For multi-threads environment, all ppp_set_* functions most + * only be called while the PPP is in the dead phase (i.e. disconnected). + */ + +#if PPP_AUTH_SUPPORT +/* + * Set PPP authentication. * * Warning: Using PPPAUTHTYPE_ANY might have security consequences. * RFC 1994 says: @@ -452,6 +450,7 @@ struct ppp_pcb_s { * circumstances, then distinct user names SHOULD be employed, each of * which identifies exactly one authentication method. * + * Default is none auth type, unset (NULL) user and passwd. */ #define PPPAUTHTYPE_NONE 0x00 #define PPPAUTHTYPE_PAP 0x01 @@ -462,6 +461,127 @@ struct ppp_pcb_s { #define PPPAUTHTYPE_ANY 0xff void ppp_set_auth(ppp_pcb *pcb, u8_t authtype, const char *user, const char *passwd); +/* + * If set, peer is required to authenticate. This is mostly necessary for PPP server support. + * + * Default is false. + */ +#define ppp_set_auth_required(ppp, boolval) (ppp->settings.auth_required = boolval) +#endif /* PPP_AUTH_SUPPORT */ + +#if PPP_IPV4_SUPPORT +/* + * Set PPP interface "our" and "his" IPv4 addresses. This is mostly necessary for PPP server + * support but it can also be used on a PPP link where each side choose its own IP address. + * + * Default is unset (0.0.0.0). + */ +#define ppp_set_ipcp_ouraddr(ppp, addr) do { ppp->ipcp_wantoptions.ouraddr = ip4_addr_get_u32(addr); \ + ppp->ask_for_local = ppp->ipcp_wantoptions.ouraddr != 0; } while(0) +#define ppp_set_ipcp_hisaddr(ppp, addr) (ppp->ipcp_wantoptions.hisaddr = ip4_addr_get_u32(addr)) +#if LWIP_DNS +/* + * Set DNS server addresses that are sent if the peer asks for them. This is mostly necessary + * for PPP server support. + * + * Default is unset (0.0.0.0). + */ +#define ppp_set_ipcp_dnsaddr(ppp, index, addr) (ppp->ipcp_allowoptions.dnsaddr[index] = ip4_addr_get_u32(addr)) + +/* + * If set, we ask the peer for up to 2 DNS server addresses. Received DNS server addresses are + * registered using the dns_setserver() function. + * + * Default is false. + */ +#define ppp_set_usepeerdns(ppp, boolval) (ppp->settings.usepeerdns = boolval) +#endif /* LWIP_DNS */ +#endif /* PPP_IPV4_SUPPORT */ + +#if MPPE_SUPPORT +/* Disable MPPE (Microsoft Point to Point Encryption). This parameter is exclusive. */ +#define PPP_MPPE_DISABLE 0x00 +/* Require the use of MPPE (Microsoft Point to Point Encryption). */ +#define PPP_MPPE_ENABLE 0x01 +/* Allow MPPE to use stateful mode. Stateless mode is still attempted first. */ +#define PPP_MPPE_ALLOW_STATEFUL 0x02 +/* Refuse the use of MPPE with 40-bit encryption. Conflict with PPP_MPPE_REFUSE_128. */ +#define PPP_MPPE_REFUSE_40 0x04 +/* Refuse the use of MPPE with 128-bit encryption. Conflict with PPP_MPPE_REFUSE_40. */ +#define PPP_MPPE_REFUSE_128 0x08 +/* + * Set MPPE configuration + * + * Default is disabled. + */ +void ppp_set_mppe(ppp_pcb *pcb, u8_t flags); +#endif /* MPPE_SUPPORT */ + +/* + * Wait for up to intval milliseconds for a valid PPP packet from the peer. + * At the end of this time, or when a valid PPP packet is received from the + * peer, we commence negotiation by sending our first LCP packet. + * + * Default is 0. + */ +#define ppp_set_listen_time(ppp, intval) (ppp->settings.listen_time = intval) + +/* + * If set, we will attempt to initiate a connection but if no reply is received from + * the peer, we will then just wait passively for a valid LCP packet from the peer. + * + * Default is false. + */ +#define ppp_set_passive(ppp, boolval) (ppp->lcp_wantoptions.passive = boolval) + +/* + * If set, we will not transmit LCP packets to initiate a connection until a valid + * LCP packet is received from the peer. This is what we usually call the server mode. + * + * Default is false. + */ +#define ppp_set_silent(ppp, boolval) (ppp->lcp_wantoptions.silent = boolval) + +/* + * If set, enable protocol field compression negotiation in both the receive and + * the transmit direction. + * + * Default is true. + */ +#define ppp_set_neg_pcomp(ppp, boolval) (ppp->lcp_wantoptions.neg_pcompression = \ + ppp->lcp_allowoptions.neg_pcompression = boolval) + +/* + * If set, enable Address/Control compression in both the receive and the transmit + * direction. + * + * Default is true. + */ +#define ppp_set_neg_accomp(ppp, boolval) (ppp->lcp_wantoptions.neg_accompression = \ + ppp->lcp_allowoptions.neg_accompression = boolval) + +/* + * If set, enable asyncmap negotiation. Otherwise forcing all control characters to + * be escaped for both the transmit and the receive direction. + * + * Default is true. + */ +#define ppp_set_neg_asyncmap(ppp, boolval) (ppp->lcp_wantoptions.neg_asyncmap = \ + ppp->lcp_allowoptions.neg_asyncmap = boolval) + +/* + * This option sets the Async-Control-Character-Map (ACCM) for this end of the link. + * The ACCM is a set of 32 bits, one for each of the ASCII control characters with + * values from 0 to 31, where a 1 bit indicates that the corresponding control + * character should not be used in PPP packets sent to this system. The map is + * an unsigned 32 bits integer where the least significant bit (00000001) represents + * character 0 and the most significant bit (80000000) represents character 31. + * We will then ask the peer to send these characters as a 2-byte escape sequence. + * + * Default is 0. + */ +#define ppp_set_asyncmap(ppp, intval) (ppp->lcp_wantoptions.asyncmap = intval) + /* * Set a PPP interface as the default network interface * (used to output all packets for which no specific route is found). @@ -498,13 +618,10 @@ err_t ppp_connect(ppp_pcb *pcb, u16_t holdoff); * * This can only be called if PPP is in the dead phase. * - * Local and remote interface IP addresses, as well as DNS are - * provided through a previously filled struct ppp_addrs. - * * If this port connects to a modem, the modem connection must be * established before calling this. */ -err_t ppp_listen(ppp_pcb *pcb, struct ppp_addrs *addrs); +err_t ppp_listen(ppp_pcb *pcb); #endif /* PPP_SERVER */ /* diff --git a/tools/sdk/include/lwip/netif/ppp/ppp_impl.h b/tools/sdk/include/lwip/netif/ppp/ppp_impl.h old mode 100755 new mode 100644 index 324f4b058db..1d4c7742f35 --- a/tools/sdk/include/lwip/netif/ppp/ppp_impl.h +++ b/tools/sdk/include/lwip/netif/ppp/ppp_impl.h @@ -33,7 +33,7 @@ #ifndef LWIP_HDR_PPP_IMPL_H #define LWIP_HDR_PPP_IMPL_H -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ @@ -48,7 +48,7 @@ #include "lwip/netif.h" #include "lwip/def.h" -#include "lwip/timers.h" +#include "lwip/timeouts.h" #include "ppp.h" #include "pppdebug.h" @@ -138,10 +138,10 @@ */ struct link_callbacks { /* Start a connection (e.g. Initiate discovery phase) */ - err_t (*connect) (ppp_pcb *pcb, void *ctx); + void (*connect) (ppp_pcb *pcb, void *ctx); #if PPP_SERVER /* Listen for an incoming connection (Passive mode) */ - err_t (*listen) (ppp_pcb *pcb, void *ctx, struct ppp_addrs *addrs); + void (*listen) (ppp_pcb *pcb, void *ctx); #endif /* PPP_SERVER */ /* End a connection (i.e. initiate disconnect phase) */ void (*disconnect) (ppp_pcb *pcb, void *ctx); @@ -378,6 +378,7 @@ struct pppd_stats { * PPP private functions */ + /* * Functions called from lwIP core. */ @@ -385,7 +386,6 @@ struct pppd_stats { /* initialize the PPP subsystem */ int ppp_init(void); - /* * Functions called from PPP link protocols. */ @@ -394,9 +394,6 @@ int ppp_init(void); ppp_pcb *ppp_new(struct netif *pppif, const struct link_callbacks *callbacks, void *link_ctx_cb, ppp_link_status_cb_fn link_status_cb, void *ctx_cb); -/* Set a PPP PCB to its initial state */ -void ppp_clear(ppp_pcb *pcb); - /* Initiate LCP open request */ void ppp_start(ppp_pcb *pcb); @@ -623,7 +620,7 @@ void ppp_warn(const char *fmt, ...); /* log a warning message */ void ppp_error(const char *fmt, ...); /* log an error message */ void ppp_fatal(const char *fmt, ...); /* log an error message and die(1) */ #if PRINTPKT_SUPPORT -void ppp_dump_packet(const char *tag, unsigned char *p, int len); +void ppp_dump_packet(ppp_pcb *pcb, const char *tag, unsigned char *p, int len); /* dump packet to debug log if interesting */ #endif /* PRINTPKT_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/ppp_opts.h b/tools/sdk/include/lwip/netif/ppp/ppp_opts.h new file mode 100644 index 00000000000..fa79c090f25 --- /dev/null +++ b/tools/sdk/include/lwip/netif/ppp/ppp_opts.h @@ -0,0 +1,593 @@ +/* + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#ifndef LWIP_PPP_OPTS_H +#define LWIP_PPP_OPTS_H + +#include "lwip/opt.h" + +/** + * PPP_SUPPORT==1: Enable PPP. + */ +#ifndef PPP_SUPPORT +#define PPP_SUPPORT 0 +#endif + +/** + * PPPOE_SUPPORT==1: Enable PPP Over Ethernet + */ +#ifndef PPPOE_SUPPORT +#define PPPOE_SUPPORT 0 +#endif + +/** + * PPPOL2TP_SUPPORT==1: Enable PPP Over L2TP + */ +#ifndef PPPOL2TP_SUPPORT +#define PPPOL2TP_SUPPORT 0 +#endif + +/** + * PPPOL2TP_AUTH_SUPPORT==1: Enable PPP Over L2TP Auth (enable MD5 support) + */ +#ifndef PPPOL2TP_AUTH_SUPPORT +#define PPPOL2TP_AUTH_SUPPORT PPPOL2TP_SUPPORT +#endif + +/** + * PPPOS_SUPPORT==1: Enable PPP Over Serial + */ +#ifndef PPPOS_SUPPORT +#define PPPOS_SUPPORT PPP_SUPPORT +#endif + +/** + * LWIP_PPP_API==1: Enable PPP API (in pppapi.c) + */ +#ifndef LWIP_PPP_API +#define LWIP_PPP_API (PPP_SUPPORT && (NO_SYS == 0)) +#endif + +/** + * MEMP_NUM_PPP_PCB: the number of simultaneously active PPP + * connections (requires the PPP_SUPPORT option) + */ +#ifndef MEMP_NUM_PPP_PCB +#define MEMP_NUM_PPP_PCB 1 +#endif + +#if PPP_SUPPORT + +/** + * MEMP_NUM_PPPOS_INTERFACES: the number of concurrently active PPPoS + * interfaces (only used with PPPOS_SUPPORT==1) + */ +#ifndef MEMP_NUM_PPPOS_INTERFACES +#define MEMP_NUM_PPPOS_INTERFACES MEMP_NUM_PPP_PCB +#endif + +/** + * MEMP_NUM_PPPOE_INTERFACES: the number of concurrently active PPPoE + * interfaces (only used with PPPOE_SUPPORT==1) + */ +#ifndef MEMP_NUM_PPPOE_INTERFACES +#define MEMP_NUM_PPPOE_INTERFACES 1 +#endif + +/** + * MEMP_NUM_PPPOL2TP_INTERFACES: the number of concurrently active PPPoL2TP + * interfaces (only used with PPPOL2TP_SUPPORT==1) + */ +#ifndef MEMP_NUM_PPPOL2TP_INTERFACES +#define MEMP_NUM_PPPOL2TP_INTERFACES 1 +#endif + +/** + * MEMP_NUM_PPP_API_MSG: Number of concurrent PPP API messages (in pppapi.c) + */ +#ifndef MEMP_NUM_PPP_API_MSG +#define MEMP_NUM_PPP_API_MSG 5 +#endif + +/** + * PPP_DEBUG: Enable debugging for PPP. + */ +#ifndef PPP_DEBUG +#define PPP_DEBUG LWIP_DBG_OFF +#endif + +/** + * PPP_INPROC_IRQ_SAFE==1 call pppos_input() using tcpip_callback(). + * + * Please read the "PPPoS input path" chapter in the PPP documentation about this option. + */ +#ifndef PPP_INPROC_IRQ_SAFE +#define PPP_INPROC_IRQ_SAFE 0 +#endif + +/** + * PRINTPKT_SUPPORT==1: Enable PPP print packet support + * + * Mandatory for debugging, it displays exchanged packet content in debug trace. + */ +#ifndef PRINTPKT_SUPPORT +#define PRINTPKT_SUPPORT 0 +#endif + +/** + * PPP_IPV4_SUPPORT==1: Enable PPP IPv4 support + */ +#ifndef PPP_IPV4_SUPPORT +#define PPP_IPV4_SUPPORT (LWIP_IPV4) +#endif + +/** + * PPP_IPV6_SUPPORT==1: Enable PPP IPv6 support + */ +#ifndef PPP_IPV6_SUPPORT +#define PPP_IPV6_SUPPORT (LWIP_IPV6) +#endif + +/** + * PPP_NOTIFY_PHASE==1: Support PPP notify phase support + * + * PPP notify phase support allows you to set a callback which is + * called on change of the internal PPP state machine. + * + * This can be used for example to set a LED pattern depending on the + * current phase of the PPP session. + */ +#ifndef PPP_NOTIFY_PHASE +#define PPP_NOTIFY_PHASE 0 +#endif + +/** + * pbuf_type PPP is using for LCP, PAP, CHAP, EAP, CCP, IPCP and IP6CP packets. + * + * Memory allocated must be single buffered for PPP to works, it requires pbuf + * that are not going to be chained when allocated. This requires setting + * PBUF_POOL_BUFSIZE to at least 512 bytes, which is quite huge for small systems. + * + * Setting PPP_USE_PBUF_RAM to 1 makes PPP use memory from heap where continuous + * buffers are required, allowing you to use a smaller PBUF_POOL_BUFSIZE. + */ +#ifndef PPP_USE_PBUF_RAM +#define PPP_USE_PBUF_RAM 0 +#endif + +/** + * PPP_FCS_TABLE: Keep a 256*2 byte table to speed up FCS calculation for PPPoS + */ +#ifndef PPP_FCS_TABLE +#define PPP_FCS_TABLE 1 +#endif + +/** + * PAP_SUPPORT==1: Support PAP. + */ +#ifndef PAP_SUPPORT +#define PAP_SUPPORT 0 +#endif + +/** + * CHAP_SUPPORT==1: Support CHAP. + */ +#ifndef CHAP_SUPPORT +#define CHAP_SUPPORT 0 +#endif + +/** + * MSCHAP_SUPPORT==1: Support MSCHAP. + */ +#ifndef MSCHAP_SUPPORT +#define MSCHAP_SUPPORT 0 +#endif +#if MSCHAP_SUPPORT +/* MSCHAP requires CHAP support */ +#undef CHAP_SUPPORT +#define CHAP_SUPPORT 1 +#endif /* MSCHAP_SUPPORT */ + +/** + * EAP_SUPPORT==1: Support EAP. + */ +#ifndef EAP_SUPPORT +#define EAP_SUPPORT 0 +#endif + +/** + * CCP_SUPPORT==1: Support CCP. + */ +#ifndef CCP_SUPPORT +#define CCP_SUPPORT 0 +#endif + +/** + * MPPE_SUPPORT==1: Support MPPE. + */ +#ifndef MPPE_SUPPORT +#define MPPE_SUPPORT 0 +#endif +#if MPPE_SUPPORT +/* MPPE requires CCP support */ +#undef CCP_SUPPORT +#define CCP_SUPPORT 1 +/* MPPE requires MSCHAP support */ +#undef MSCHAP_SUPPORT +#define MSCHAP_SUPPORT 1 +/* MSCHAP requires CHAP support */ +#undef CHAP_SUPPORT +#define CHAP_SUPPORT 1 +#endif /* MPPE_SUPPORT */ + +/** + * CBCP_SUPPORT==1: Support CBCP. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef CBCP_SUPPORT +#define CBCP_SUPPORT 0 +#endif + +/** + * ECP_SUPPORT==1: Support ECP. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef ECP_SUPPORT +#define ECP_SUPPORT 0 +#endif + +/** + * DEMAND_SUPPORT==1: Support dial on demand. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef DEMAND_SUPPORT +#define DEMAND_SUPPORT 0 +#endif + +/** + * LQR_SUPPORT==1: Support Link Quality Report. Do nothing except exchanging some LCP packets. + */ +#ifndef LQR_SUPPORT +#define LQR_SUPPORT 0 +#endif + +/** + * PPP_SERVER==1: Enable PPP server support (waiting for incoming PPP session). + * + * Currently only supported for PPPoS. + */ +#ifndef PPP_SERVER +#define PPP_SERVER 0 +#endif + +#if PPP_SERVER +/* + * PPP_OUR_NAME: Our name for authentication purposes + */ +#ifndef PPP_OUR_NAME +#define PPP_OUR_NAME "lwIP" +#endif +#endif /* PPP_SERVER */ + +/** + * VJ_SUPPORT==1: Support VJ header compression. + */ +#ifndef VJ_SUPPORT +#define VJ_SUPPORT 1 +#endif +/* VJ compression is only supported for TCP over IPv4 over PPPoS. */ +#if !PPPOS_SUPPORT || !PPP_IPV4_SUPPORT || !LWIP_TCP +#undef VJ_SUPPORT +#define VJ_SUPPORT 0 +#endif /* !PPPOS_SUPPORT */ + +/** + * PPP_MD5_RANDM==1: Use MD5 for better randomness. + * Enabled by default if CHAP, EAP, or L2TP AUTH support is enabled. + */ +#ifndef PPP_MD5_RANDM +#define PPP_MD5_RANDM (CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT) +#endif + +/** + * PolarSSL embedded library + * + * + * lwIP contains some files fetched from the latest BSD release of + * the PolarSSL project (PolarSSL 0.10.1-bsd) for ciphers and encryption + * methods we need for lwIP PPP support. + * + * The PolarSSL files were cleaned to contain only the necessary struct + * fields and functions needed for lwIP. + * + * The PolarSSL API was not changed at all, so if you are already using + * PolarSSL you can choose to skip the compilation of the included PolarSSL + * library into lwIP. + * + * If you are not using the embedded copy you must include external + * libraries into your arch/cc.h port file. + * + * Beware of the stack requirements which can be a lot larger if you are not + * using our cleaned PolarSSL library. + */ + +/** + * LWIP_USE_EXTERNAL_POLARSSL: Use external PolarSSL library + */ +#ifndef LWIP_USE_EXTERNAL_POLARSSL +#define LWIP_USE_EXTERNAL_POLARSSL 0 +#endif + +/** + * LWIP_USE_EXTERNAL_MBEDTLS: Use external mbed TLS library + */ +#ifndef LWIP_USE_EXTERNAL_MBEDTLS +#define LWIP_USE_EXTERNAL_MBEDTLS 0 +#endif + +/* + * PPP Timeouts + */ + +/** + * FSM_DEFTIMEOUT: Timeout time in seconds + */ +#ifndef FSM_DEFTIMEOUT +#define FSM_DEFTIMEOUT 6 +#endif + +/** + * FSM_DEFMAXTERMREQS: Maximum Terminate-Request transmissions + */ +#ifndef FSM_DEFMAXTERMREQS +#define FSM_DEFMAXTERMREQS 2 +#endif + +/** + * FSM_DEFMAXCONFREQS: Maximum Configure-Request transmissions + */ +#ifndef FSM_DEFMAXCONFREQS +#define FSM_DEFMAXCONFREQS 10 +#endif + +/** + * FSM_DEFMAXNAKLOOPS: Maximum number of nak loops + */ +#ifndef FSM_DEFMAXNAKLOOPS +#define FSM_DEFMAXNAKLOOPS 5 +#endif + +/** + * UPAP_DEFTIMEOUT: Timeout (seconds) for retransmitting req + */ +#ifndef UPAP_DEFTIMEOUT +#define UPAP_DEFTIMEOUT 6 +#endif + +/** + * UPAP_DEFTRANSMITS: Maximum number of auth-reqs to send + */ +#ifndef UPAP_DEFTRANSMITS +#define UPAP_DEFTRANSMITS 10 +#endif + +#if PPP_SERVER +/** + * UPAP_DEFREQTIME: Time to wait for auth-req from peer + */ +#ifndef UPAP_DEFREQTIME +#define UPAP_DEFREQTIME 30 +#endif +#endif /* PPP_SERVER */ + +/** + * CHAP_DEFTIMEOUT: Timeout (seconds) for retransmitting req + */ +#ifndef CHAP_DEFTIMEOUT +#define CHAP_DEFTIMEOUT 6 +#endif + +/** + * CHAP_DEFTRANSMITS: max # times to send challenge + */ +#ifndef CHAP_DEFTRANSMITS +#define CHAP_DEFTRANSMITS 10 +#endif + +#if PPP_SERVER +/** + * CHAP_DEFRECHALLENGETIME: If this option is > 0, rechallenge the peer every n seconds + */ +#ifndef CHAP_DEFRECHALLENGETIME +#define CHAP_DEFRECHALLENGETIME 0 +#endif +#endif /* PPP_SERVER */ + +/** + * EAP_DEFREQTIME: Time to wait for peer request + */ +#ifndef EAP_DEFREQTIME +#define EAP_DEFREQTIME 6 +#endif + +/** + * EAP_DEFALLOWREQ: max # times to accept requests + */ +#ifndef EAP_DEFALLOWREQ +#define EAP_DEFALLOWREQ 10 +#endif + +#if PPP_SERVER +/** + * EAP_DEFTIMEOUT: Timeout (seconds) for rexmit + */ +#ifndef EAP_DEFTIMEOUT +#define EAP_DEFTIMEOUT 6 +#endif + +/** + * EAP_DEFTRANSMITS: max # times to transmit + */ +#ifndef EAP_DEFTRANSMITS +#define EAP_DEFTRANSMITS 10 +#endif +#endif /* PPP_SERVER */ + +/** + * LCP_DEFLOOPBACKFAIL: Default number of times we receive our magic number from the peer + * before deciding the link is looped-back. + */ +#ifndef LCP_DEFLOOPBACKFAIL +#define LCP_DEFLOOPBACKFAIL 10 +#endif + +/** + * LCP_ECHOINTERVAL: Interval in seconds between keepalive echo requests, 0 to disable. + */ +#ifndef LCP_ECHOINTERVAL +#define LCP_ECHOINTERVAL 0 +#endif + +/** + * LCP_MAXECHOFAILS: Number of unanswered echo requests before failure. + */ +#ifndef LCP_MAXECHOFAILS +#define LCP_MAXECHOFAILS 3 +#endif + +/** + * PPP_MAXIDLEFLAG: Max Xmit idle time (in ms) before resend flag char. + */ +#ifndef PPP_MAXIDLEFLAG +#define PPP_MAXIDLEFLAG 100 +#endif + +/** + * PPP Packet sizes + */ + +/** + * PPP_MRU: Default MRU + */ +#ifndef PPP_MRU +#define PPP_MRU 1500 +#endif + +/** + * PPP_DEFMRU: Default MRU to try + */ +#ifndef PPP_DEFMRU +#define PPP_DEFMRU 1500 +#endif + +/** + * PPP_MAXMRU: Normally limit MRU to this (pppd default = 16384) + */ +#ifndef PPP_MAXMRU +#define PPP_MAXMRU 1500 +#endif + +/** + * PPP_MINMRU: No MRUs below this + */ +#ifndef PPP_MINMRU +#define PPP_MINMRU 128 +#endif + +/** + * PPPOL2TP_DEFMRU: Default MTU and MRU for L2TP + * Default = 1500 - PPPoE(6) - PPP Protocol(2) - IPv4 header(20) - UDP Header(8) + * - L2TP Header(6) - HDLC Header(2) - PPP Protocol(2) - MPPE Header(2) - PPP Protocol(2) + */ +#if PPPOL2TP_SUPPORT +#ifndef PPPOL2TP_DEFMRU +#define PPPOL2TP_DEFMRU 1450 +#endif +#endif /* PPPOL2TP_SUPPORT */ + +/** + * MAXNAMELEN: max length of hostname or name for auth + */ +#ifndef MAXNAMELEN +#define MAXNAMELEN 256 +#endif + +/** + * MAXSECRETLEN: max length of password or secret + */ +#ifndef MAXSECRETLEN +#define MAXSECRETLEN 256 +#endif + +/* ------------------------------------------------------------------------- */ + +/* + * Build triggers for embedded PolarSSL + */ +#if !LWIP_USE_EXTERNAL_POLARSSL && !LWIP_USE_EXTERNAL_MBEDTLS + +/* CHAP, EAP, L2TP AUTH and MD5 Random require MD5 support */ +#if CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM +#define LWIP_INCLUDED_POLARSSL_MD5 1 +#endif /* CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM */ + +#if MSCHAP_SUPPORT + +/* MSCHAP require MD4 support */ +#define LWIP_INCLUDED_POLARSSL_MD4 1 +/* MSCHAP require SHA1 support */ +#define LWIP_INCLUDED_POLARSSL_SHA1 1 +/* MSCHAP require DES support */ +#define LWIP_INCLUDED_POLARSSL_DES 1 + +/* MS-CHAP support is required for MPPE */ +#if MPPE_SUPPORT +/* MPPE require ARC4 support */ +#define LWIP_INCLUDED_POLARSSL_ARC4 1 +#endif /* MPPE_SUPPORT */ + +#endif /* MSCHAP_SUPPORT */ + +#endif /* !LWIP_USE_EXTERNAL_POLARSSL && !LWIP_USE_EXTERNAL_MBEDTLS */ + +/* Default value if unset */ +#ifndef LWIP_INCLUDED_POLARSSL_MD4 +#define LWIP_INCLUDED_POLARSSL_MD4 0 +#endif /* LWIP_INCLUDED_POLARSSL_MD4 */ +#ifndef LWIP_INCLUDED_POLARSSL_MD5 +#define LWIP_INCLUDED_POLARSSL_MD5 0 +#endif /* LWIP_INCLUDED_POLARSSL_MD5 */ +#ifndef LWIP_INCLUDED_POLARSSL_SHA1 +#define LWIP_INCLUDED_POLARSSL_SHA1 0 +#endif /* LWIP_INCLUDED_POLARSSL_SHA1 */ +#ifndef LWIP_INCLUDED_POLARSSL_DES +#define LWIP_INCLUDED_POLARSSL_DES 0 +#endif /* LWIP_INCLUDED_POLARSSL_DES */ +#ifndef LWIP_INCLUDED_POLARSSL_ARC4 +#define LWIP_INCLUDED_POLARSSL_ARC4 0 +#endif /* LWIP_INCLUDED_POLARSSL_ARC4 */ + +#endif /* PPP_SUPPORT */ + +#endif /* LWIP_PPP_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/pppapi.h b/tools/sdk/include/lwip/netif/ppp/pppapi.h old mode 100755 new mode 100644 similarity index 90% rename from tools/sdk/include/lwip/lwip/pppapi.h rename to tools/sdk/include/lwip/netif/ppp/pppapi.h index 3ddf3daf9af..9bda2a8cfd7 --- a/tools/sdk/include/lwip/lwip/pppapi.h +++ b/tools/sdk/include/lwip/netif/ppp/pppapi.h @@ -25,10 +25,10 @@ * */ -#ifndef __LWIP_PPPAPI_H__ -#define __LWIP_PPPAPI_H__ +#ifndef LWIP_PPPAPI_H +#define LWIP_PPPAPI_H -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_PPP_API /* don't build if not configured for use in lwipopts.h */ @@ -47,11 +47,13 @@ extern "C" { struct pppapi_msg_msg { ppp_pcb *ppp; union { +#if ESP_LWIP struct { u8_t authtype; const char *user; const char *passwd; } setauth; +#endif #if PPP_NOTIFY_PHASE struct { ppp_notify_phase_cb_fn notify_phase_cb; @@ -79,7 +81,7 @@ struct pppapi_msg_msg { struct { struct netif *pppif; struct netif *netif; - ip_addr_t *ipaddr; + API_MSG_M_DEF_C(ip_addr_t, ipaddr); u16_t port; #if PPPOL2TP_AUTH_SUPPORT const u8_t *secret; @@ -92,11 +94,6 @@ struct pppapi_msg_msg { struct { u16_t holdoff; } connect; -#if PPP_SERVER - struct { - struct ppp_addrs *addrs; - } listen; -#endif /* PPP_SERVER */ struct { u8_t nocarrier; } close; @@ -108,15 +105,17 @@ struct pppapi_msg_msg { }; struct pppapi_msg { - struct tcpip_api_call call; + struct tcpip_api_call_data call; struct pppapi_msg_msg msg; }; /* API for application */ -void pppapi_set_default(ppp_pcb *pcb); +err_t pppapi_set_default(ppp_pcb *pcb); +#if ESP_LWIP void pppapi_set_auth(ppp_pcb *pcb, u8_t authtype, const char *user, const char *passwd); +#endif #if PPP_NOTIFY_PHASE -void pppapi_set_notify_phase_callback(ppp_pcb *pcb, ppp_notify_phase_cb_fn notify_phase_cb); +err_t pppapi_set_notify_phase_callback(ppp_pcb *pcb, ppp_notify_phase_cb_fn notify_phase_cb); #endif /* PPP_NOTIFY_PHASE */ #if PPPOS_SUPPORT ppp_pcb *pppapi_pppos_create(struct netif *pppif, pppos_output_cb_fn output_cb, ppp_link_status_cb_fn link_status_cb, void *ctx_cb); @@ -133,7 +132,7 @@ ppp_pcb *pppapi_pppol2tp_create(struct netif *pppif, struct netif *netif, ip_add #endif /* PPPOL2TP_SUPPORT */ err_t pppapi_connect(ppp_pcb *pcb, u16_t holdoff); #if PPP_SERVER -err_t pppapi_listen(ppp_pcb *pcb, struct ppp_addrs *addrs); +err_t pppapi_listen(ppp_pcb *pcb); #endif /* PPP_SERVER */ err_t pppapi_close(ppp_pcb *pcb, u8_t nocarrier); err_t pppapi_free(ppp_pcb *pcb); @@ -145,4 +144,4 @@ err_t pppapi_ioctl(ppp_pcb *pcb, u8_t cmd, void *arg); #endif /* LWIP_PPP_API */ -#endif /* __LWIP_PPPAPI_H__ */ +#endif /* LWIP_PPPAPI_H */ diff --git a/tools/sdk/include/lwip/netif/ppp/pppcrypt.h b/tools/sdk/include/lwip/netif/ppp/pppcrypt.h old mode 100755 new mode 100644 index ef2e87de113..a7b2099f25e --- a/tools/sdk/include/lwip/netif/ppp/pppcrypt.h +++ b/tools/sdk/include/lwip/netif/ppp/pppcrypt.h @@ -30,14 +30,107 @@ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include "lwip/opt.h" -#if PPP_SUPPORT && MSCHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ +#include "netif/ppp/ppp_opts.h" +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +/* This header file is included in all PPP modules needing hashes and/or ciphers */ #ifndef PPPCRYPT_H #define PPPCRYPT_H +/* + * If included PolarSSL copy is not used, user is expected to include + * external libraries in arch/cc.h (which is included by lwip/arch.h). + */ +#include "lwip/arch.h" + +/* + * Map hashes and ciphers functions to PolarSSL + */ +#if !LWIP_USE_EXTERNAL_MBEDTLS + +#include "netif/ppp/polarssl/md4.h" +#define lwip_md4_context md4_context +#define lwip_md4_init(context) +#define lwip_md4_starts md4_starts +#define lwip_md4_update md4_update +#define lwip_md4_finish md4_finish +#define lwip_md4_free(context) + +#include "netif/ppp/polarssl/md5.h" +#define lwip_md5_context md5_context +#define lwip_md5_init(context) +#define lwip_md5_starts md5_starts +#define lwip_md5_update md5_update +#define lwip_md5_finish md5_finish +#define lwip_md5_free(context) + +#include "netif/ppp/polarssl/sha1.h" +#define lwip_sha1_context sha1_context +#define lwip_sha1_init(context) +#define lwip_sha1_starts sha1_starts +#define lwip_sha1_update sha1_update +#define lwip_sha1_finish sha1_finish +#define lwip_sha1_free(context) + +#include "netif/ppp/polarssl/des.h" +#define lwip_des_context des_context +#define lwip_des_init(context) +#define lwip_des_setkey_enc des_setkey_enc +#define lwip_des_crypt_ecb des_crypt_ecb +#define lwip_des_free(context) + +#include "netif/ppp/polarssl/arc4.h" +#define lwip_arc4_context arc4_context +#define lwip_arc4_init(context) +#define lwip_arc4_setup arc4_setup +#define lwip_arc4_crypt arc4_crypt +#define lwip_arc4_free(context) + +#endif /* !LWIP_USE_EXTERNAL_MBEDTLS */ + +/* + * Map hashes and ciphers functions to mbed TLS + */ +#if LWIP_USE_EXTERNAL_MBEDTLS + +#define lwip_md4_context mbedtls_md4_context +#define lwip_md4_init mbedtls_md4_init +#define lwip_md4_starts mbedtls_md4_starts +#define lwip_md4_update mbedtls_md4_update +#define lwip_md4_finish mbedtls_md4_finish +#define lwip_md4_free mbedtls_md4_free + +#define lwip_md5_context mbedtls_md5_context +#define lwip_md5_init mbedtls_md5_init +#define lwip_md5_starts mbedtls_md5_starts +#define lwip_md5_update mbedtls_md5_update +#define lwip_md5_finish mbedtls_md5_finish +#define lwip_md5_free mbedtls_md5_free + +#define lwip_sha1_context mbedtls_sha1_context +#define lwip_sha1_init mbedtls_sha1_init +#define lwip_sha1_starts mbedtls_sha1_starts +#define lwip_sha1_update mbedtls_sha1_update +#define lwip_sha1_finish mbedtls_sha1_finish +#define lwip_sha1_free mbedtls_sha1_free + +#define lwip_des_context mbedtls_des_context +#define lwip_des_init mbedtls_des_init +#define lwip_des_setkey_enc mbedtls_des_setkey_enc +#define lwip_des_crypt_ecb mbedtls_des_crypt_ecb +#define lwip_des_free mbedtls_des_free + +#define lwip_arc4_context mbedtls_arc4_context +#define lwip_arc4_init mbedtls_arc4_init +#define lwip_arc4_setup mbedtls_arc4_setup +#define lwip_arc4_crypt(context, buffer, length) mbedtls_arc4_crypt(context, length, buffer, buffer) +#define lwip_arc4_free mbedtls_arc4_free + +#endif /* LWIP_USE_EXTERNAL_MBEDTLS */ + void pppcrypt_56_to_64_bit_key(u_char *key, u_char *des_key); #endif /* PPPCRYPT_H */ -#endif /* PPP_SUPPORT && MSCHAP_SUPPORT */ +#endif /* PPP_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/pppdebug.h b/tools/sdk/include/lwip/netif/ppp/pppdebug.h old mode 100755 new mode 100644 index e35c8e090da..7ead0459104 --- a/tools/sdk/include/lwip/netif/ppp/pppdebug.h +++ b/tools/sdk/include/lwip/netif/ppp/pppdebug.h @@ -34,7 +34,7 @@ ***************************************************************************** */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPPDEBUG_H diff --git a/tools/sdk/include/lwip/netif/ppp/pppoe.h b/tools/sdk/include/lwip/netif/ppp/pppoe.h old mode 100755 new mode 100644 index b1dd2fd9c5c..9f8f2892b43 --- a/tools/sdk/include/lwip/netif/ppp/pppoe.h +++ b/tools/sdk/include/lwip/netif/ppp/pppoe.h @@ -67,14 +67,14 @@ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPPOE_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPP_OE_H #define PPP_OE_H #include "ppp.h" -#include "netif/etharp.h" +#include "lwip/etharp.h" #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" diff --git a/tools/sdk/include/lwip/netif/ppp/pppol2tp.h b/tools/sdk/include/lwip/netif/ppp/pppol2tp.h old mode 100755 new mode 100644 index 097b4d18911..f03950e65df --- a/tools/sdk/include/lwip/netif/ppp/pppol2tp.h +++ b/tools/sdk/include/lwip/netif/ppp/pppol2tp.h @@ -31,11 +31,11 @@ * */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPPOL2TP_SUPPORT /* don't build if not configured for use in lwipopts.h */ -#ifndef PPPOL2TP_H_ -#define PPPOL2TP_H_ +#ifndef PPPOL2TP_H +#define PPPOL2TP_H #include "ppp.h" @@ -193,9 +193,9 @@ struct pppol2tp_pcb_s { /* Create a new L2TP session. */ ppp_pcb *pppol2tp_create(struct netif *pppif, - struct netif *netif, ip_addr_t *ipaddr, u16_t port, + struct netif *netif, const ip_addr_t *ipaddr, u16_t port, const u8_t *secret, u8_t secret_len, ppp_link_status_cb_fn link_status_cb, void *ctx_cb); -#endif /* PPPOL2TP_H_ */ +#endif /* PPPOL2TP_H */ #endif /* PPP_SUPPORT && PPPOL2TP_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/pppos.h b/tools/sdk/include/lwip/netif/ppp/pppos.h old mode 100755 new mode 100644 index 39b2b7d0c3d..d924a9fc7ea --- a/tools/sdk/include/lwip/netif/ppp/pppos.h +++ b/tools/sdk/include/lwip/netif/ppp/pppos.h @@ -31,14 +31,13 @@ * */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPPOS_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPPOS_H #define PPPOS_H #include "lwip/sys.h" -#include "lwip/sio.h" #include "ppp.h" #include "vj.h" diff --git a/tools/sdk/include/lwip/netif/ppp/upap.h b/tools/sdk/include/lwip/netif/ppp/upap.h old mode 100755 new mode 100644 index bb9309bdb23..7da792ecc72 --- a/tools/sdk/include/lwip/netif/ppp/upap.h +++ b/tools/sdk/include/lwip/netif/ppp/upap.h @@ -42,7 +42,7 @@ * $Id: upap.h,v 1.8 2002/12/04 23:03:33 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef UPAP_H @@ -88,10 +88,10 @@ /* * Timeouts. */ -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ #define UPAP_DEFTIMEOUT 3 /* Timeout (seconds) for retransmitting req */ #define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ /* * Each interface is described by upap structure. diff --git a/tools/sdk/include/lwip/netif/ppp/vj.h b/tools/sdk/include/lwip/netif/ppp/vj.h old mode 100755 new mode 100644 index f2e1f8b4bf2..7f389c846f7 --- a/tools/sdk/include/lwip/netif/ppp/vj.h +++ b/tools/sdk/include/lwip/netif/ppp/vj.h @@ -22,7 +22,7 @@ * - Initial distribution. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && VJ_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef VJ_H diff --git a/tools/sdk/include/lwip/netif/slipif.h b/tools/sdk/include/lwip/netif/slipif.h old mode 100755 new mode 100644 index d164d448605..65ba31f835b --- a/tools/sdk/include/lwip/netif/slipif.h +++ b/tools/sdk/include/lwip/netif/slipif.h @@ -1,3 +1,9 @@ +/** + * @file + * + * SLIP netif API + */ + /* * Copyright (c) 2001, Swedish Institute of Computer Science. * All rights reserved. diff --git a/tools/sdk/include/lwip/netif/wlanif.h b/tools/sdk/include/lwip/netif/wlanif.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/lwip/perf.h b/tools/sdk/include/lwip/perf.h new file mode 100644 index 00000000000..089facac1df --- /dev/null +++ b/tools/sdk/include/lwip/perf.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __PERF_H__ +#define __PERF_H__ + +#define PERF_START /* null definition */ +#define PERF_STOP(x) /* null definition */ + +#endif /* __PERF_H__ */ diff --git a/tools/sdk/include/lwip/ping/ping.h b/tools/sdk/include/lwip/ping/ping.h new file mode 100644 index 00000000000..6e8eb24b2ad --- /dev/null +++ b/tools/sdk/include/lwip/ping/ping.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#ifndef LWIP_PING_H +#define LWIP_PING_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * PING_USE_SOCKETS: Set to 1 to use sockets, otherwise the raw api is used + */ +#ifndef PING_USE_SOCKETS +#define PING_USE_SOCKETS LWIP_SOCKET +#endif + + +int ping_init(void); + +#ifdef ESP_PING +void ping_deinit(void); +#endif + +#if !PING_USE_SOCKETS +void ping_send_now(void); +#endif /* !PING_USE_SOCKETS */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_PING_H */ diff --git a/tools/sdk/include/lwip/posix/errno.h b/tools/sdk/include/lwip/posix/errno.h new file mode 100644 index 00000000000..5917c75e24a --- /dev/null +++ b/tools/sdk/include/lwip/posix/errno.h @@ -0,0 +1,33 @@ +/** + * @file + * This file is a posix wrapper for lwip/errno.h. + */ + +/* + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/errno.h" diff --git a/tools/sdk/include/lwip/posix/netdb.h b/tools/sdk/include/lwip/posix/netdb.h new file mode 100644 index 00000000000..363154f6889 --- /dev/null +++ b/tools/sdk/include/lwip/posix/netdb.h @@ -0,0 +1,40 @@ +/** + * @file + * This file is a posix wrapper for lwip/netdb.h. + */ + +/* + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/netdb.h" + +#ifdef ESP_PLATFORM +int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, + char *host, socklen_t hostlen, + char *serv, socklen_t servlen, int flags); + +#endif diff --git a/tools/sdk/include/lwip/posix/sys/socket.h b/tools/sdk/include/lwip/posix/sys/socket.h new file mode 100644 index 00000000000..0ed9baf3d9f --- /dev/null +++ b/tools/sdk/include/lwip/posix/sys/socket.h @@ -0,0 +1,33 @@ +/** + * @file + * This file is a posix wrapper for lwip/sockets.h. + */ + +/* + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/sockets.h" diff --git a/tools/sdk/include/lwip/sys/socket.h b/tools/sdk/include/lwip/sys/socket.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/lwip/sys_arch.h b/tools/sdk/include/lwip/sys_arch.h new file mode 100644 index 00000000000..9638fdfd621 --- /dev/null +++ b/tools/sdk/include/lwip/sys_arch.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef __SYS_ARCH_H__ +#define __SYS_ARCH_H__ + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" +#include "arch/vfs_lwip.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef xSemaphoreHandle sys_sem_t; +typedef xSemaphoreHandle sys_mutex_t; +typedef xTaskHandle sys_thread_t; + +typedef struct sys_mbox_s { + xQueueHandle os_mbox; + void *owner; +}* sys_mbox_t; + + +#define LWIP_COMPAT_MUTEX 0 + +#if !LWIP_COMPAT_MUTEX +#define sys_mutex_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_mutex_set_invalid( x ) ( ( *x ) = NULL ) +#endif + +#define sys_mbox_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) + +/* Define the sys_mbox_set_invalid() to empty to support lock-free mbox in ESP LWIP. + * + * The basic idea about the lock-free mbox is that the mbox should always be valid unless + * no socket APIs are using the socket and the socket is closed. ESP LWIP achieves this by + * following two changes to official LWIP: + * 1. Postpone the deallocation of mbox to netconn_free(), in other words, free the mbox when + * no one is using the socket. + * 2. Define the sys_mbox_set_invalid() to empty if the mbox is not actually freed. + + * The second change is necessary. Consider a common scenario: the application task calls + * recv() to receive packets from the socket, the sys_mbox_valid() returns true. Because there + * is no lock for the mbox, the LWIP CORE can call sys_mbox_set_invalid() to set the mbox at + * anytime and the thread-safe issue may happen. + * + * However, if the sys_mbox_set_invalid() is not called after sys_mbox_free(), e.g. in netconn_alloc(), + * we need to initialize the mbox to invalid explicitly since sys_mbox_set_invalid() now is empty. + */ +#define sys_mbox_set_invalid( x ) + +#define sys_sem_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_sem_set_invalid( x ) ( ( *x ) = NULL ) + +void sys_delay_ms(uint32_t ms); +sys_sem_t* sys_thread_sem_init(void); +void sys_thread_sem_deinit(void); +sys_sem_t* sys_thread_sem_get(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __SYS_ARCH_H__ */ + diff --git a/tools/sdk/include/lwip/vfs_lwip.h b/tools/sdk/include/lwip/vfs_lwip.h new file mode 100644 index 00000000000..1957304b9f2 --- /dev/null +++ b/tools/sdk/include/lwip/vfs_lwip.h @@ -0,0 +1,23 @@ +// 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. + +#ifdef __cplusplus +extern "C" { +#endif + +void esp_vfs_lwip_sockets_register(); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/mbedtls/.gitignore b/tools/sdk/include/mbedtls/.gitignore deleted file mode 100644 index bf67d02ed8a..00000000000 --- a/tools/sdk/include/mbedtls/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -Makefile -*.sln -*.vcxproj -mbedtls/check_config diff --git a/tools/sdk/include/mbedtls/aes_alt.h b/tools/sdk/include/mbedtls/aes_alt.h new file mode 100644 index 00000000000..cf87ea5c152 --- /dev/null +++ b/tools/sdk/include/mbedtls/aes_alt.h @@ -0,0 +1,66 @@ +/** + * \file aes_alt.h + * + * \brief AES block cipher + * + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * + */ +#ifndef AES_ALT_H +#define AES_ALT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_AES_ALT) +#include "hwcrypto/aes.h" + +typedef esp_aes_context mbedtls_aes_context; + +#define mbedtls_aes_init esp_aes_init +#define mbedtls_aes_free esp_aes_free +#define mbedtls_aes_setkey_enc esp_aes_setkey +#define mbedtls_aes_setkey_dec esp_aes_setkey +#define mbedtls_aes_crypt_ecb esp_aes_crypt_ecb +#if defined(MBEDTLS_CIPHER_MODE_CBC) +#define mbedtls_aes_crypt_cbc esp_aes_crypt_cbc +#endif +#if defined(MBEDTLS_CIPHER_MODE_CFB) +#define mbedtls_aes_crypt_cfb128 esp_aes_crypt_cfb128 +#define mbedtls_aes_crypt_cfb8 esp_aes_crypt_cfb8 +#endif +#if defined(MBEDTLS_CIPHER_MODE_CTR) +#define mbedtls_aes_crypt_ctr esp_aes_crypt_ctr +#endif +#if defined(MBEDTLS_CIPHER_MODE_XTS) +typedef esp_aes_xts_context mbedtls_aes_xts_context; +#define mbedtls_aes_xts_init esp_aes_xts_init +#define mbedtls_aes_xts_free esp_aes_xts_free +#define mbedtls_aes_xts_setkey_enc esp_aes_xts_setkey_enc +#define mbedtls_aes_xts_setkey_dec esp_aes_xts_setkey_dec +#define mbedtls_aes_crypt_xts esp_aes_crypt_xts +#endif +#define mbedtls_internal_aes_encrypt esp_internal_aes_encrypt +#define mbedtls_internal_aes_decrypt esp_internal_aes_decrypt +#endif /* MBEDTLS_AES_ALT */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/mbedtls/esp_mem.h b/tools/sdk/include/mbedtls/esp_mem.h new file mode 100644 index 00000000000..da740830478 --- /dev/null +++ b/tools/sdk/include/mbedtls/esp_mem.h @@ -0,0 +1,20 @@ +// 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 + +void *esp_mbedtls_mem_calloc(size_t n, size_t size); +void esp_mbedtls_mem_free(void *ptr); diff --git a/tools/sdk/include/mbedtls/mbedtls/aes.h b/tools/sdk/include/mbedtls/mbedtls/aes.h index 1829f724026..4c8dab31519 100644 --- a/tools/sdk/include/mbedtls/mbedtls/aes.h +++ b/tools/sdk/include/mbedtls/mbedtls/aes.h @@ -1,9 +1,26 @@ /** * \file aes.h * - * \brief AES block cipher - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * \brief This file contains AES definitions and functions. + * + * The Advanced Encryption Standard (AES) specifies a FIPS-approved + * cryptographic algorithm that can be used to protect electronic + * data. + * + * The AES algorithm is a symmetric block cipher that can + * encrypt and decrypt information. For more information, see + * FIPS Publication 197: Advanced Encryption Standard and + * ISO/IEC 18033-2:2006: Information technology -- Security + * techniques -- Encryption algorithms -- Part 2: Asymmetric + * ciphers. + * + * The AES-XTS block mode is standardized by NIST SP 800-38E + * + * and described in detail by IEEE P1619 + * . + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +35,9 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_AES_H #define MBEDTLS_AES_H @@ -33,88 +51,191 @@ #include /* padlock.c and aesni.c rely on these values! */ -#define MBEDTLS_AES_ENCRYPT 1 -#define MBEDTLS_AES_DECRYPT 0 +#define MBEDTLS_AES_ENCRYPT 1 /**< AES encryption. */ +#define MBEDTLS_AES_DECRYPT 0 /**< AES decryption. */ +/* Error codes in range 0x0020-0x0022 */ #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */ #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */ +/* Error codes in range 0x0021-0x0025 */ +#define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */ +#define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */ +#define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */ + #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ !defined(inline) && !defined(__cplusplus) #define inline __inline #endif -#if !defined(MBEDTLS_AES_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_AES_ALT) +// Regular implementation +// + /** - * \brief AES context structure - * - * \note buf is able to hold 32 extra bytes, which can be used: - * - for alignment purposes if VIA padlock is used, and/or - * - to simplify key expansion in the 256-bit case by - * generating an extra round key + * \brief The AES context-type definition. */ -typedef struct +typedef struct mbedtls_aes_context { - int nr; /*!< number of rounds */ - uint32_t *rk; /*!< AES round keys */ - uint32_t buf[68]; /*!< unaligned data */ + int nr; /*!< The number of rounds. */ + uint32_t *rk; /*!< AES round keys. */ + uint32_t buf[68]; /*!< Unaligned data buffer. This buffer can + hold 32 extra Bytes, which can be used for + one of the following purposes: +
  • Alignment if VIA padlock is + used.
  • +
  • Simplifying key expansion in the 256-bit + case by generating an extra round key. +
*/ } mbedtls_aes_context; +#if defined(MBEDTLS_CIPHER_MODE_XTS) /** - * \brief Initialize AES context + * \brief The AES XTS context-type definition. + */ +typedef struct mbedtls_aes_xts_context +{ + mbedtls_aes_context crypt; /*!< The AES context to use for AES block + encryption or decryption. */ + mbedtls_aes_context tweak; /*!< The AES context used for tweak + computation. */ +} mbedtls_aes_xts_context; +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + +#else /* MBEDTLS_AES_ALT */ +#include "aes_alt.h" +#endif /* MBEDTLS_AES_ALT */ + +/** + * \brief This function initializes the specified AES context. + * + * It must be the first API called before using + * the context. * - * \param ctx AES context to be initialized + * \param ctx The AES context to initialize. */ void mbedtls_aes_init( mbedtls_aes_context *ctx ); /** - * \brief Clear AES context + * \brief This function releases and clears the specified AES context. * - * \param ctx AES context to be cleared + * \param ctx The AES context to clear. */ void mbedtls_aes_free( mbedtls_aes_context *ctx ); +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief This function initializes the specified AES XTS context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The AES XTS context to initialize. + */ +void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx ); + +/** + * \brief This function releases and clears the specified AES XTS context. + * + * \param ctx The AES XTS context to clear. + */ +void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + /** - * \brief AES key schedule (encryption) + * \brief This function sets the encryption key. * - * \param ctx AES context to be initialized - * \param key encryption key - * \param keybits must be 128, 192 or 256 + * \param ctx The AES context to which the key should be bound. + * \param key The encryption key. + * \param keybits The size of data passed in bits. Valid options are: + *
  • 128 bits
  • + *
  • 192 bits
  • + *
  • 256 bits
* - * \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ); /** - * \brief AES key schedule (decryption) + * \brief This function sets the decryption key. * - * \param ctx AES context to be initialized - * \param key decryption key - * \param keybits must be 128, 192 or 256 + * \param ctx The AES context to which the key should be bound. + * \param key The decryption key. + * \param keybits The size of data passed. Valid options are: + *
  • 128 bits
  • + *
  • 192 bits
  • + *
  • 256 bits
* - * \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ); +#if defined(MBEDTLS_CIPHER_MODE_XTS) /** - * \brief AES-ECB block encryption/decryption - * - * \param ctx AES context - * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT - * \param input 16-byte input block - * \param output 16-byte output block - * - * \return 0 if successful + * \brief This function prepares an XTS context for encryption and + * sets the encryption key. + * + * \param ctx The AES XTS context to which the key should be bound. + * \param key The encryption key. This is comprised of the XTS key1 + * concatenated with the XTS key2. + * \param keybits The size of \p key passed in bits. Valid options are: + *
  • 256 bits (each of key1 and key2 is a 128-bit key)
  • + *
  • 512 bits (each of key1 and key2 is a 256-bit key)
+ * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function prepares an XTS context for decryption and + * sets the decryption key. + * + * \param ctx The AES XTS context to which the key should be bound. + * \param key The decryption key. This is comprised of the XTS key1 + * concatenated with the XTS key2. + * \param keybits The size of \p key passed in bits. Valid options are: + *
  • 256 bits (each of key1 and key2 is a 128-bit key)
  • + *
  • 512 bits (each of key1 and key2 is a 256-bit key)
+ * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + +/** + * \brief This function performs an AES single-block encryption or + * decryption operation. + * + * It performs the operation defined in the \p mode parameter + * (encrypt or decrypt), on the input data buffer defined in + * the \p input parameter. + * + * mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or + * mbedtls_aes_setkey_dec() must be called before the first + * call to this API with the same context. + * + * \param ctx The AES context to use for encryption or decryption. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param input The 16-Byte buffer holding the input data. + * \param output The 16-Byte buffer holding the output data. + + * \return \c 0 on success. */ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, int mode, @@ -123,26 +244,41 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, #if defined(MBEDTLS_CIPHER_MODE_CBC) /** - * \brief AES-CBC buffer encryption/decryption - * Length should be a multiple of the block - * size (16 bytes) - * - * \note Upon exit, the content of the IV is updated so that you can - * call the function same function again on the following - * block(s) of data and get the same result as if it was - * encrypted in one call. This allows a "streaming" usage. - * If on the other hand you need to retain the contents of the - * IV, you should either save it manually or use the cipher - * module instead. - * - * \param ctx AES context - * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT - * \param length length of the input data - * \param iv initialization vector (updated after use) - * \param input buffer holding the input data - * \param output buffer holding the output data - * - * \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH + * \brief This function performs an AES-CBC encryption or decryption operation + * on full blocks. + * + * It performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer defined in + * the \p input parameter. + * + * It can be called as many times as needed, until all the input + * data is processed. mbedtls_aes_init(), and either + * mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called + * before the first call to this API with the same context. + * + * \note This function operates on aligned blocks, that is, the input size + * must be a multiple of the AES block size of 16 Bytes. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the IV, you should + * either save it manually or use the cipher module instead. + * + * + * \param ctx The AES context to use for encryption or decryption. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param length The length of the input data in Bytes. This must be a + * multiple of the block size (16 Bytes). + * \param iv Initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH + * on failure. */ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, int mode, @@ -152,31 +288,83 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CBC */ +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief This function performs an AES-XTS encryption or decryption + * operation for an entire XTS data unit. + * + * AES-XTS encrypts or decrypts blocks based on their location as + * defined by a data unit number. The data unit number must be + * provided by \p data_unit. + * + * NIST SP 800-38E limits the maximum size of a data unit to 2^20 + * AES blocks. If the data unit is larger than this, this function + * returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH. + * + * \param ctx The AES XTS context to use for AES XTS operations. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param length The length of a data unit in bytes. This can be any + * length between 16 bytes and 2^24 bytes inclusive + * (between 1 and 2^20 block cipher blocks). + * \param data_unit The address of the data unit encoded as an array of 16 + * bytes in little-endian format. For disk encryption, this + * is typically the index of the block device sector that + * contains the data. + * \param input The buffer holding the input data (which is an entire + * data unit). This function reads \p length bytes from \p + * input. + * \param output The buffer holding the output data (which is an entire + * data unit). This function writes \p length bytes to \p + * output. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \p length is + * smaller than an AES block in size (16 bytes) or if \p + * length is larger than 2^20 blocks (16 MiB). + */ +int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx, + int mode, + size_t length, + const unsigned char data_unit[16], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + #if defined(MBEDTLS_CIPHER_MODE_CFB) /** - * \brief AES-CFB128 buffer encryption/decryption. - * - * Note: Due to the nature of CFB you should use the same key schedule for - * both encryption and decryption. So a context initialized with - * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT. - * - * \note Upon exit, the content of the IV is updated so that you can - * call the function same function again on the following - * block(s) of data and get the same result as if it was - * encrypted in one call. This allows a "streaming" usage. - * If on the other hand you need to retain the contents of the - * IV, you should either save it manually or use the cipher - * module instead. - * - * \param ctx AES context - * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT - * \param length length of the input data - * \param iv_off offset in IV (updated after use) - * \param iv initialization vector (updated after use) - * \param input buffer holding the input data - * \param output buffer holding the output data - * - * \return 0 if successful + * \brief This function performs an AES-CFB128 encryption or decryption + * operation. + * + * It performs the operation defined in the \p mode + * parameter (encrypt or decrypt), on the input data buffer + * defined in the \p input parameter. + * + * For CFB, you must set up the context with mbedtls_aes_setkey_enc(), + * regardless of whether you are performing an encryption or decryption + * operation, that is, regardless of the \p mode parameter. This is + * because CFB mode uses the same key schedule for encryption and + * decryption. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the + * IV, you must either save it manually or use the cipher + * module instead. + * + * + * \param ctx The AES context to use for encryption or decryption. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param length The length of the input data. + * \param iv_off The offset in IV (updated after use). + * \param iv The initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. */ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx, int mode, @@ -187,28 +375,36 @@ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx, unsigned char *output ); /** - * \brief AES-CFB8 buffer encryption/decryption. - * - * Note: Due to the nature of CFB you should use the same key schedule for - * both encryption and decryption. So a context initialized with - * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT. - * - * \note Upon exit, the content of the IV is updated so that you can - * call the function same function again on the following - * block(s) of data and get the same result as if it was - * encrypted in one call. This allows a "streaming" usage. - * If on the other hand you need to retain the contents of the - * IV, you should either save it manually or use the cipher - * module instead. - * - * \param ctx AES context - * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT - * \param length length of the input data - * \param iv initialization vector (updated after use) - * \param input buffer holding the input data - * \param output buffer holding the output data - * - * \return 0 if successful + * \brief This function performs an AES-CFB8 encryption or decryption + * operation. + * + * It performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer defined + * in the \p input parameter. + * + * Due to the nature of CFB, you must use the same key schedule for + * both encryption and decryption operations. Therefore, you must + * use the context initialized with mbedtls_aes_setkey_enc() for + * both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the + * IV, you should either save it manually or use the cipher + * module instead. + * + * + * \param ctx The AES context to use for encryption or decryption. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT + * \param length The length of the input data. + * \param iv The initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. */ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, int mode, @@ -218,28 +414,126 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, unsigned char *output ); #endif /*MBEDTLS_CIPHER_MODE_CFB */ +#if defined(MBEDTLS_CIPHER_MODE_OFB) +/** + * \brief This function performs an AES-OFB (Output Feedback Mode) + * encryption or decryption operation. + * + * For OFB, you must set up the context with + * mbedtls_aes_setkey_enc(), regardless of whether you are + * performing an encryption or decryption operation. This is + * because OFB mode uses the same key schedule for encryption and + * decryption. + * + * The OFB operation is identical for encryption or decryption, + * therefore no operation mode needs to be specified. + * + * \note Upon exit, the content of iv, the Initialisation Vector, is + * updated so that you can call the same function again on the next + * block(s) of data and get the same result as if it was encrypted + * in one call. This allows a "streaming" usage, by initialising + * iv_off to 0 before the first call, and preserving its value + * between calls. + * + * For non-streaming use, the iv should be initialised on each call + * to a unique value, and iv_off set to 0 on each call. + * + * If you need to retain the contents of the initialisation vector, + * you must either save it manually or use the cipher module + * instead. + * + * \warning For the OFB mode, the initialisation vector must be unique + * every encryption operation. Reuse of an initialisation vector + * will compromise security. + * + * \param ctx The AES context to use for encryption or decryption. + * \param length The length of the input data. + * \param iv_off The offset in IV (updated after use). + * \param iv The initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + */ +int mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx, + size_t length, + size_t *iv_off, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); + +#endif /* MBEDTLS_CIPHER_MODE_OFB */ + #if defined(MBEDTLS_CIPHER_MODE_CTR) /** - * \brief AES-CTR buffer encryption/decryption - * - * Warning: You have to keep the maximum use of your counter in mind! - * - * Note: Due to the nature of CTR you should use the same key schedule for - * both encryption and decryption. So a context initialized with - * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT. - * - * \param ctx AES context - * \param length The length of the data - * \param nc_off The offset in the current stream_block (for resuming - * within current cipher stream). The offset pointer to - * should be 0 at the start of a stream. - * \param nonce_counter The 128-bit nonce and counter. - * \param stream_block The saved stream-block for resuming. Is overwritten - * by the function. - * \param input The input data stream - * \param output The output data stream - * - * \return 0 if successful + * \brief This function performs an AES-CTR encryption or decryption + * operation. + * + * This function performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer + * defined in the \p input parameter. + * + * Due to the nature of CTR, you must use the same key schedule + * for both encryption and decryption operations. Therefore, you + * must use the context initialized with mbedtls_aes_setkey_enc() + * for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. + * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that an AES block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * + * \param ctx The AES context to use for encryption or decryption. + * \param length The length of the input data. + * \param nc_off The offset in the current \p stream_block, for + * resuming within the current cipher stream. The + * offset pointer should be 0 at the start of a stream. + * \param nonce_counter The 128-bit nonce and counter. + * \param stream_block The saved stream block for resuming. This is + * overwritten by the function. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. */ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, size_t length, @@ -251,30 +545,30 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, #endif /* MBEDTLS_CIPHER_MODE_CTR */ /** - * \brief Internal AES block encryption function - * (Only exposed to allow overriding it, - * see MBEDTLS_AES_ENCRYPT_ALT) + * \brief Internal AES block encryption function. This is only + * exposed to allow overriding it using + * \c MBEDTLS_AES_ENCRYPT_ALT. * - * \param ctx AES context - * \param input Plaintext block - * \param output Output (ciphertext) block + * \param ctx The AES context to use for encryption. + * \param input The plaintext block. + * \param output The output (ciphertext) block. * - * \return 0 if successful + * \return \c 0 on success. */ int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); /** - * \brief Internal AES block decryption function - * (Only exposed to allow overriding it, - * see MBEDTLS_AES_DECRYPT_ALT) + * \brief Internal AES block decryption function. This is only + * exposed to allow overriding it using see + * \c MBEDTLS_AES_DECRYPT_ALT. * - * \param ctx AES context - * \param input Ciphertext block - * \param output Output (plaintext) block + * \param ctx The AES context to use for decryption. + * \param input The ciphertext block. + * \param output The output (plaintext) block. * - * \return 0 if successful + * \return \c 0 on success. */ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, const unsigned char input[16], @@ -290,11 +584,11 @@ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, * \brief Deprecated internal AES block encryption function * without return value. * - * \deprecated Superseded by mbedtls_aes_encrypt_ext() in 2.5.0 + * \deprecated Superseded by mbedtls_aes_encrypt_ext() in 2.5.0. * - * \param ctx AES context - * \param input Plaintext block - * \param output Output (ciphertext) block + * \param ctx The AES context to use for encryption. + * \param input Plaintext block. + * \param output Output (ciphertext) block. */ MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], @@ -304,11 +598,11 @@ MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, * \brief Deprecated internal AES block decryption function * without return value. * - * \deprecated Superseded by mbedtls_aes_decrypt_ext() in 2.5.0 + * \deprecated Superseded by mbedtls_aes_decrypt_ext() in 2.5.0. * - * \param ctx AES context - * \param input Ciphertext block - * \param output Output (plaintext) block + * \param ctx The AES context to use for decryption. + * \param input Ciphertext block. + * \param output Output (plaintext) block. */ MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, const unsigned char input[16], @@ -317,22 +611,11 @@ MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_AES_ALT */ -#include "aes_alt.h" -#endif /* MBEDTLS_AES_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** - * \brief Checkup routine + * \brief Checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_aes_self_test( int verbose ); diff --git a/tools/sdk/include/mbedtls/mbedtls/aesni.h b/tools/sdk/include/mbedtls/mbedtls/aesni.h index b1b7f1cdec6..746baa0e17f 100644 --- a/tools/sdk/include/mbedtls/mbedtls/aesni.h +++ b/tools/sdk/include/mbedtls/mbedtls/aesni.h @@ -2,7 +2,8 @@ * \file aesni.h * * \brief AES-NI for hardware AES acceleration on some Intel processors - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/arc4.h b/tools/sdk/include/mbedtls/mbedtls/arc4.h index 5fc5395a8c4..83a7461f3f2 100644 --- a/tools/sdk/include/mbedtls/mbedtls/arc4.h +++ b/tools/sdk/include/mbedtls/mbedtls/arc4.h @@ -3,6 +3,10 @@ * * \brief The ARCFOUR stream cipher * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers instead. + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -19,6 +23,7 @@ * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) + * */ #ifndef MBEDTLS_ARC4_H #define MBEDTLS_ARC4_H @@ -31,18 +36,24 @@ #include -#if !defined(MBEDTLS_ARC4_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED -0x0019 /**< ARC4 hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_ARC4_ALT) +// Regular implementation +// + /** - * \brief ARC4 context structure + * \brief ARC4 context structure + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers instead. + * */ -typedef struct +typedef struct mbedtls_arc4_context { int x; /*!< permutation index */ int y; /*!< permutation index */ @@ -50,10 +61,19 @@ typedef struct } mbedtls_arc4_context; +#else /* MBEDTLS_ARC4_ALT */ +#include "arc4_alt.h" +#endif /* MBEDTLS_ARC4_ALT */ + /** * \brief Initialize ARC4 context * * \param ctx ARC4 context to be initialized + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * */ void mbedtls_arc4_init( mbedtls_arc4_context *ctx ); @@ -61,6 +81,11 @@ void mbedtls_arc4_init( mbedtls_arc4_context *ctx ); * \brief Clear ARC4 context * * \param ctx ARC4 context to be cleared + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * */ void mbedtls_arc4_free( mbedtls_arc4_context *ctx ); @@ -70,6 +95,11 @@ void mbedtls_arc4_free( mbedtls_arc4_context *ctx ); * \param ctx ARC4 context to be setup * \param key the secret key * \param keylen length of the key, in bytes + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * */ void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key, unsigned int keylen ); @@ -83,26 +113,24 @@ void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key, * \param output buffer for the output data * * \return 0 if successful + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * */ int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input, unsigned char *output ); -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_ARC4_ALT */ -#include "arc4_alt.h" -#endif /* MBEDTLS_ARC4_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * */ int mbedtls_arc4_self_test( int verbose ); diff --git a/tools/sdk/include/mbedtls/mbedtls/aria.h b/tools/sdk/include/mbedtls/mbedtls/aria.h new file mode 100644 index 00000000000..4a79c13872e --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/aria.h @@ -0,0 +1,331 @@ +/** + * \file aria.h + * + * \brief ARIA block cipher + * + * The ARIA algorithm is a symmetric block cipher that can encrypt and + * decrypt information. It is defined by the Korean Agency for + * Technology and Standards (KATS) in KS X 1213:2004 (in + * Korean, but see http://210.104.33.10/ARIA/index-e.html in English) + * and also described by the IETF in RFC 5794. + */ +/* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_ARIA_H +#define MBEDTLS_ARIA_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_ARIA_ENCRYPT 1 /**< ARIA encryption. */ +#define MBEDTLS_ARIA_DECRYPT 0 /**< ARIA decryption. */ + +#define MBEDTLS_ARIA_BLOCKSIZE 16 /**< ARIA block size in bytes. */ +#define MBEDTLS_ARIA_MAX_ROUNDS 16 /**< Maxiumum number of rounds in ARIA. */ +#define MBEDTLS_ARIA_MAX_KEYSIZE 32 /**< Maximum size of an ARIA key in bytes. */ + +#define MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH -0x005C /**< Invalid key length. */ +#define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E /**< Invalid data input length. */ +#define MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE -0x005A /**< Feature not available. For example, an unsupported ARIA key size. */ +#define MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED -0x0058 /**< ARIA hardware accelerator failed. */ + +#if !defined(MBEDTLS_ARIA_ALT) +// Regular implementation +// + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief The ARIA context-type definition. + */ +typedef struct mbedtls_aria_context +{ + unsigned char nr; /*!< The number of rounds (12, 14 or 16) */ + /*! The ARIA round keys. */ + uint32_t rk[MBEDTLS_ARIA_MAX_ROUNDS + 1][MBEDTLS_ARIA_BLOCKSIZE / 4]; +} +mbedtls_aria_context; + +#else /* MBEDTLS_ARIA_ALT */ +#include "aria_alt.h" +#endif /* MBEDTLS_ARIA_ALT */ + +/** + * \brief This function initializes the specified ARIA context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The ARIA context to initialize. + */ +void mbedtls_aria_init( mbedtls_aria_context *ctx ); + +/** + * \brief This function releases and clears the specified ARIA context. + * + * \param ctx The ARIA context to clear. + */ +void mbedtls_aria_free( mbedtls_aria_context *ctx ); + +/** + * \brief This function sets the encryption key. + * + * \param ctx The ARIA context to which the key should be bound. + * \param key The encryption key. + * \param keybits The size of data passed in bits. Valid options are: + *
  • 128 bits
  • + *
  • 192 bits
  • + *
  • 256 bits
+ * + * \return \c 0 on success or #MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH + * on failure. + */ +int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function sets the decryption key. + * + * \param ctx The ARIA context to which the key should be bound. + * \param key The decryption key. + * \param keybits The size of data passed. Valid options are: + *
  • 128 bits
  • + *
  • 192 bits
  • + *
  • 256 bits
+ * + * \return \c 0 on success, or #MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function performs an ARIA single-block encryption or + * decryption operation. + * + * It performs encryption or decryption (depending on whether + * the key was set for encryption on decryption) on the input + * data buffer defined in the \p input parameter. + * + * mbedtls_aria_init(), and either mbedtls_aria_setkey_enc() or + * mbedtls_aria_setkey_dec() must be called before the first + * call to this API with the same context. + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param input The 16-Byte buffer holding the input data. + * \param output The 16-Byte buffer holding the output data. + + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx, + const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief This function performs an ARIA-CBC encryption or decryption operation + * on full blocks. + * + * It performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer defined in + * the \p input parameter. + * + * It can be called as many times as needed, until all the input + * data is processed. mbedtls_aria_init(), and either + * mbedtls_aria_setkey_enc() or mbedtls_aria_setkey_dec() must be called + * before the first call to this API with the same context. + * + * \note This function operates on aligned blocks, that is, the input size + * must be a multiple of the ARIA block size of 16 Bytes. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the IV, you should + * either save it manually or use the cipher module instead. + * + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param mode The ARIA operation: #MBEDTLS_ARIA_ENCRYPT or + * #MBEDTLS_ARIA_DECRYPT. + * \param length The length of the input data in Bytes. This must be a + * multiple of the block size (16 Bytes). + * \param iv Initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success, or #MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH + * on failure. + */ +int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx, + int mode, + size_t length, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +/** + * \brief This function performs an ARIA-CFB128 encryption or decryption + * operation. + * + * It performs the operation defined in the \p mode + * parameter (encrypt or decrypt), on the input data buffer + * defined in the \p input parameter. + * + * For CFB, you must set up the context with mbedtls_aria_setkey_enc(), + * regardless of whether you are performing an encryption or decryption + * operation, that is, regardless of the \p mode parameter. This is + * because CFB mode uses the same key schedule for encryption and + * decryption. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the + * IV, you must either save it manually or use the cipher + * module instead. + * + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param mode The ARIA operation: #MBEDTLS_ARIA_ENCRYPT or + * #MBEDTLS_ARIA_DECRYPT. + * \param length The length of the input data. + * \param iv_off The offset in IV (updated after use). + * \param iv The initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +/** + * \brief This function performs an ARIA-CTR encryption or decryption + * operation. + * + * This function performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer + * defined in the \p input parameter. + * + * Due to the nature of CTR, you must use the same key schedule + * for both encryption and decryption operations. Therefore, you + * must use the context initialized with mbedtls_aria_setkey_enc() + * for both #MBEDTLS_ARIA_ENCRYPT and #MBEDTLS_ARIA_DECRYPT. + * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that an ARIA block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param length The length of the input data. + * \param nc_off The offset in the current \p stream_block, for + * resuming within the current cipher stream. The + * offset pointer should be 0 at the start of a stream. + * \param nonce_counter The 128-bit nonce and counter. + * \param stream_block The saved stream block for resuming. This is + * overwritten by the function. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine. + * + * \return \c 0 on success, or \c 1 on failure. + */ +int mbedtls_aria_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* aria.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/asn1.h b/tools/sdk/include/mbedtls/mbedtls/asn1.h index 082832c87fd..96c1c9a8ab2 100644 --- a/tools/sdk/include/mbedtls/mbedtls/asn1.h +++ b/tools/sdk/include/mbedtls/mbedtls/asn1.h @@ -2,7 +2,8 @@ * \file asn1.h * * \brief Generic ASN.1 parsing - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -59,7 +60,7 @@ /** * \name DER constants - * These constants comply with DER encoded the ANS1 type tags. + * These constants comply with the DER encoded ASN.1 type tags. * DER encoding uses hexadecimal representation. * An example DER sequence is:\n * - 0x02 -- tag indicating INTEGER @@ -87,6 +88,21 @@ #define MBEDTLS_ASN1_PRIMITIVE 0x00 #define MBEDTLS_ASN1_CONSTRUCTED 0x20 #define MBEDTLS_ASN1_CONTEXT_SPECIFIC 0x80 + +/* + * Bit masks for each of the components of an ASN.1 tag as specified in + * ITU X.690 (08/2015), section 8.1 "General rules for encoding", + * paragraph 8.1.2.2: + * + * Bit 8 7 6 5 1 + * +-------+-----+------------+ + * | Class | P/C | Tag number | + * +-------+-----+------------+ + */ +#define MBEDTLS_ASN1_TAG_CLASS_MASK 0xC0 +#define MBEDTLS_ASN1_TAG_PC_MASK 0x20 +#define MBEDTLS_ASN1_TAG_VALUE_MASK 0x1F + /* \} name */ /* \} addtogroup asn1_module */ diff --git a/tools/sdk/include/mbedtls/mbedtls/asn1write.h b/tools/sdk/include/mbedtls/mbedtls/asn1write.h index 73ff32b6699..f76fc807d07 100644 --- a/tools/sdk/include/mbedtls/mbedtls/asn1write.h +++ b/tools/sdk/include/mbedtls/mbedtls/asn1write.h @@ -2,7 +2,8 @@ * \file asn1write.h * * \brief ASN.1 buffer writing functionality - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/base64.h b/tools/sdk/include/mbedtls/mbedtls/base64.h index 352c652db9e..7a64f521635 100644 --- a/tools/sdk/include/mbedtls/mbedtls/base64.h +++ b/tools/sdk/include/mbedtls/mbedtls/base64.h @@ -2,7 +2,8 @@ * \file base64.h * * \brief RFC 1521 base64 encoding/decoding - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/bignum.h b/tools/sdk/include/mbedtls/mbedtls/bignum.h index 2e021c9ba15..b267b23e926 100644 --- a/tools/sdk/include/mbedtls/mbedtls/bignum.h +++ b/tools/sdk/include/mbedtls/mbedtls/bignum.h @@ -1,8 +1,9 @@ /** * \file bignum.h * - * \brief Multi-precision integer library - * + * \brief Multi-precision integer library + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -70,7 +71,7 @@ * Maximum size of MPIs allowed in bits and bytes for user-MPIs. * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits ) * - * Note: Calculations can results temporarily in larger MPIs. So the number + * Note: Calculations can temporarily result in larger MPIs. So the number * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher. */ #define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */ @@ -178,7 +179,7 @@ extern "C" { /** * \brief MPI structure */ -typedef struct +typedef struct mbedtls_mpi { int s; /*!< integer sign */ size_t n; /*!< total # of limbs */ @@ -205,6 +206,8 @@ void mbedtls_mpi_free( mbedtls_mpi *X ); /** * \brief Enlarge to the specified number of limbs * + * This function does nothing if the MPI is already large enough. + * * \param X MPI to grow * \param nblimbs The target number of limbs * @@ -216,19 +219,23 @@ int mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs ); /** * \brief Resize down, keeping at least the specified number of limbs * + * If \c X is smaller than \c nblimbs, it is resized up + * instead. + * * \param X MPI to shrink * \param nblimbs The minimum number of limbs to keep * * \return 0 if successful, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * (this can only happen when resizing up). */ int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs ); /** * \brief Copy the contents of Y into X * - * \param X Destination MPI - * \param Y Source MPI + * \param X Destination MPI. It is enlarged if necessary. + * \param Y Source MPI. * * \return 0 if successful, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed @@ -685,6 +692,10 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi * * \return 0 if successful, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * + * \note The bytes obtained from the PRNG are interpreted + * as a big-endian representation of an MPI; this can + * be relevant in applications like deterministic ECDSA. */ int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size, int (*f_rng)(void *, unsigned char *, size_t), diff --git a/tools/sdk/include/mbedtls/mbedtls/blowfish.h b/tools/sdk/include/mbedtls/mbedtls/blowfish.h index 34626eef486..eea6882f75d 100644 --- a/tools/sdk/include/mbedtls/mbedtls/blowfish.h +++ b/tools/sdk/include/mbedtls/mbedtls/blowfish.h @@ -2,7 +2,8 @@ * \file blowfish.h * * \brief Blowfish block cipher - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -40,26 +41,31 @@ #define MBEDTLS_BLOWFISH_BLOCKSIZE 8 /* Blowfish uses 64 bit blocks */ #define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH -0x0016 /**< Invalid key length. */ +#define MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED -0x0017 /**< Blowfish hardware accelerator failed. */ #define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH -0x0018 /**< Invalid data input length. */ -#if !defined(MBEDTLS_BLOWFISH_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_BLOWFISH_ALT) +// Regular implementation +// + /** * \brief Blowfish context structure */ -typedef struct +typedef struct mbedtls_blowfish_context { uint32_t P[MBEDTLS_BLOWFISH_ROUNDS + 2]; /*!< Blowfish round keys */ uint32_t S[4][256]; /*!< key dependent S-boxes */ } mbedtls_blowfish_context; +#else /* MBEDTLS_BLOWFISH_ALT */ +#include "blowfish_alt.h" +#endif /* MBEDTLS_BLOWFISH_ALT */ + /** * \brief Initialize Blowfish context * @@ -168,7 +174,46 @@ int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx, /** * \brief Blowfish-CTR buffer encryption/decryption * - * Warning: You have to keep the maximum use of your counter in mind! + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**64 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 4 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 4 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**32 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. + * + * Note that for both stategies, sizes are measured in blocks and + * that a Blowfish block is 8 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. * * \param ctx Blowfish context * \param length The length of the data @@ -196,8 +241,4 @@ int mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx, } #endif -#else /* MBEDTLS_BLOWFISH_ALT */ -#include "blowfish_alt.h" -#endif /* MBEDTLS_BLOWFISH_ALT */ - #endif /* blowfish.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/bn_mul.h b/tools/sdk/include/mbedtls/mbedtls/bn_mul.h index cac3f145770..b587317d959 100644 --- a/tools/sdk/include/mbedtls/mbedtls/bn_mul.h +++ b/tools/sdk/include/mbedtls/mbedtls/bn_mul.h @@ -1,8 +1,9 @@ /** * \file bn_mul.h * - * \brief Multi-precision integer library - * + * \brief Multi-precision integer library + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -48,7 +49,14 @@ /* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */ #if defined(__GNUC__) && \ ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) -#if defined(__i386__) + +/* + * Disable use of the i386 assembly code below if option -O0, to disable all + * compiler optimisations, is passed, detected with __OPTIMIZE__ + * This is done as the number of registers used in the assembly code doesn't + * work with the -O0 option. + */ +#if defined(__i386__) && defined(__OPTIMIZE__) #define MULADDC_INIT \ asm( \ @@ -141,7 +149,7 @@ "movl %%esi, %3 \n\t" \ : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \ : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \ - : "eax", "ecx", "edx", "esi", "edi" \ + : "eax", "ebx", "ecx", "edx", "esi", "edi" \ ); #else @@ -153,7 +161,7 @@ "movl %%esi, %3 \n\t" \ : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \ : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \ - : "eax", "ecx", "edx", "esi", "edi" \ + : "eax", "ebx", "ecx", "edx", "esi", "edi" \ ); #endif /* SSE2 */ #endif /* i386 */ @@ -520,7 +528,7 @@ "swi r3, %2 \n\t" \ : "=m" (c), "=m" (d), "=m" (s) \ : "m" (s), "m" (d), "m" (c), "m" (b) \ - : "r3", "r4" "r5", "r6", "r7", "r8", \ + : "r3", "r4", "r5", "r6", "r7", "r8", \ "r9", "r10", "r11", "r12", "r13" \ ); diff --git a/tools/sdk/include/mbedtls/mbedtls/camellia.h b/tools/sdk/include/mbedtls/mbedtls/camellia.h index 0424d623fb3..fa1e05ee7fb 100644 --- a/tools/sdk/include/mbedtls/mbedtls/camellia.h +++ b/tools/sdk/include/mbedtls/mbedtls/camellia.h @@ -2,7 +2,8 @@ * \file camellia.h * * \brief Camellia block cipher - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -37,25 +38,30 @@ #define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH -0x0024 /**< Invalid key length. */ #define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH -0x0026 /**< Invalid data input length. */ - -#if !defined(MBEDTLS_CAMELLIA_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED -0x0027 /**< Camellia hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_CAMELLIA_ALT) +// Regular implementation +// + /** * \brief CAMELLIA context structure */ -typedef struct +typedef struct mbedtls_camellia_context { int nr; /*!< number of rounds */ uint32_t rk[68]; /*!< CAMELLIA round keys */ } mbedtls_camellia_context; +#else /* MBEDTLS_CAMELLIA_ALT */ +#include "camellia_alt.h" +#endif /* MBEDTLS_CAMELLIA_ALT */ + /** * \brief Initialize CAMELLIA context * @@ -181,12 +187,54 @@ int mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx, /** * \brief CAMELLIA-CTR buffer encryption/decryption * - * Warning: You have to keep the maximum use of your counter in mind! - * * Note: Due to the nature of CTR you should use the same key schedule for * both encryption and decryption. So a context initialized with * mbedtls_camellia_setkey_enc() for both MBEDTLS_CAMELLIA_ENCRYPT and MBEDTLS_CAMELLIA_DECRYPT. * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that a CAMELLIA block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * * \param ctx CAMELLIA context * \param length The length of the data * \param nc_off The offset in the current stream_block (for resuming @@ -209,18 +257,6 @@ int mbedtls_camellia_crypt_ctr( mbedtls_camellia_context *ctx, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CTR */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_CAMELLIA_ALT */ -#include "camellia_alt.h" -#endif /* MBEDTLS_CAMELLIA_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Checkup routine * diff --git a/tools/sdk/include/mbedtls/mbedtls/ccm.h b/tools/sdk/include/mbedtls/mbedtls/ccm.h index ef75839baa8..e1dc124b89f 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ccm.h +++ b/tools/sdk/include/mbedtls/mbedtls/ccm.h @@ -1,9 +1,34 @@ /** * \file ccm.h * - * \brief Counter with CBC-MAC (CCM) for 128-bit block ciphers + * \brief This file provides an API for the CCM authenticated encryption + * mode for block ciphers. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * CCM combines Counter mode encryption with CBC-MAC authentication + * for 128-bit block ciphers. + * + * Input to CCM includes the following elements: + *
  • Payload - data that is both authenticated and encrypted.
  • + *
  • Associated data (Adata) - data that is authenticated but not + * encrypted, For example, a header.
  • + *
  • Nonce - A unique value that is assigned to the payload and the + * associated data.
+ * + * Definition of CCM: + * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf + * RFC 3610 "Counter with CBC-MAC (CCM)" + * + * Related: + * RFC 5116 "An Interface and Algorithms for Authenticated Encryption" + * + * Definition of CCM*: + * IEEE 802.15.4 - IEEE Standard for Local and metropolitan area networks + * Integer representation is fixed most-significant-octet-first order and + * the representation of octets is most-significant-bit-first order. This is + * consistent with RFC 3610. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,46 +43,61 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_CCM_H #define MBEDTLS_CCM_H #include "cipher.h" -#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to function. */ -#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */ +#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to the function. */ +#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */ +#define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */ + #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_CCM_ALT) +// Regular implementation +// + /** - * \brief CCM context structure + * \brief The CCM context-type definition. The CCM context is passed + * to the APIs called. */ -typedef struct { - mbedtls_cipher_context_t cipher_ctx; /*!< cipher context used */ +typedef struct mbedtls_ccm_context +{ + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ } mbedtls_ccm_context; +#else /* MBEDTLS_CCM_ALT */ +#include "ccm_alt.h" +#endif /* MBEDTLS_CCM_ALT */ + /** - * \brief Initialize CCM context (just makes references valid) - * Makes the context ready for mbedtls_ccm_setkey() or - * mbedtls_ccm_free(). + * \brief This function initializes the specified CCM context, + * to make references valid, and prepare the context + * for mbedtls_ccm_setkey() or mbedtls_ccm_free(). * - * \param ctx CCM context to initialize + * \param ctx The CCM context to initialize. */ void mbedtls_ccm_init( mbedtls_ccm_context *ctx ); /** - * \brief CCM initialization (encryption and decryption) + * \brief This function initializes the CCM context set in the + * \p ctx parameter and sets the encryption key. * - * \param ctx CCM context to be initialized - * \param cipher cipher to use (a 128-bit block cipher) - * \param key encryption key - * \param keybits key size in bits (must be acceptable by the cipher) + * \param ctx The CCM context to initialize. + * \param cipher The 128-bit block cipher to use. + * \param key The encryption key. + * \param keybits The key size in bits. This must be acceptable by the cipher. * - * \return 0 if successful, or a cipher specific error code + * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. */ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx, mbedtls_cipher_id_t cipher, @@ -65,36 +105,40 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx, unsigned int keybits ); /** - * \brief Free a CCM context and underlying cipher sub-context + * \brief This function releases and clears the specified CCM context + * and underlying cipher sub-context. * - * \param ctx CCM context to free + * \param ctx The CCM context to clear. */ void mbedtls_ccm_free( mbedtls_ccm_context *ctx ); /** - * \brief CCM buffer encryption - * - * \param ctx CCM context - * \param length length of the input data in bytes - * \param iv nonce (initialization vector) - * \param iv_len length of IV in bytes - * must be 2, 3, 4, 5, 6, 7 or 8 - * \param add additional data - * \param add_len length of additional data in bytes - * must be less than 2^16 - 2^8 - * \param input buffer holding the input data - * \param output buffer for holding the output data - * must be at least 'length' bytes wide - * \param tag buffer for holding the tag - * \param tag_len length of the tag to generate in bytes - * must be 4, 6, 8, 10, 14 or 16 - * - * \note The tag is written to a separate buffer. To get the tag - * concatenated with the output as in the CCM spec, use - * tag = output + length and make sure the output buffer is - * at least length + tag_len wide. - * - * \return 0 if successful + * \brief This function encrypts a buffer using CCM. + * + * \note The tag is written to a separate buffer. To concatenate + * the \p tag with the \p output, as done in RFC-3610: + * Counter with CBC-MAC (CCM), use + * \p tag = \p output + \p length, and make sure that the + * output buffer is at least \p length + \p tag_len wide. + * + * \param ctx The CCM context to use for encryption. + * \param length The length of the input data in Bytes. + * \param iv Initialization vector (nonce). + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. + * \param add_len The length of additional data in Bytes. + * Must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * Must be at least \p length Bytes wide. + * \param tag The buffer holding the authentication field. + * \param tag_len The length of the authentication field to generate in Bytes: + * 4, 6, 8, 10, 12, 14 or 16. + * + * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. */ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, @@ -103,21 +147,69 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, unsigned char *tag, size_t tag_len ); /** - * \brief CCM buffer authenticated decryption - * - * \param ctx CCM context - * \param length length of the input data - * \param iv initialization vector - * \param iv_len length of IV - * \param add additional data - * \param add_len length of additional data - * \param input buffer holding the input data - * \param output buffer for holding the output data - * \param tag buffer holding the tag - * \param tag_len length of the tag - * - * \return 0 if successful and authenticated, - * MBEDTLS_ERR_CCM_AUTH_FAILED if tag does not match + * \brief This function encrypts a buffer using CCM*. + * + * \note The tag is written to a separate buffer. To concatenate + * the \p tag with the \p output, as done in RFC-3610: + * Counter with CBC-MAC (CCM), use + * \p tag = \p output + \p length, and make sure that the + * output buffer is at least \p length + \p tag_len wide. + * + * \note When using this function in a variable tag length context, + * the tag length has to be encoded into the \p iv passed to + * this function. + * + * \param ctx The CCM context to use for encryption. + * \param length The length of the input data in Bytes. + * \param iv Initialization vector (nonce). + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. + * \param add_len The length of additional data in Bytes. + * Must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * Must be at least \p length Bytes wide. + * \param tag The buffer holding the authentication field. + * \param tag_len The length of the authentication field to generate in Bytes: + * 0, 4, 6, 8, 10, 12, 14 or 16. + * + * \warning Passing 0 as \p tag_len means that the message is no + * longer authenticated. + * + * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. + */ +int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, + const unsigned char *iv, size_t iv_len, + const unsigned char *add, size_t add_len, + const unsigned char *input, unsigned char *output, + unsigned char *tag, size_t tag_len ); + +/** + * \brief This function performs a CCM authenticated decryption of a + * buffer. + * + * \param ctx The CCM context to use for decryption. + * \param length The length of the input data in Bytes. + * \param iv Initialization vector (nonce). + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. + * \param add_len The length of additional data in Bytes. + * Must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * Must be at least \p length Bytes wide. + * \param tag The buffer holding the authentication field. + * \param tag_len The length of the authentication field in Bytes. + * 4, 6, 8, 10, 12, 14 or 16. + * + * \return \c 0 on success. This indicates that the message is authentic. + * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match. + * \return A cipher-specific error code on calculation failure. */ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, @@ -125,11 +217,50 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, const unsigned char *input, unsigned char *output, const unsigned char *tag, size_t tag_len ); +/** + * \brief This function performs a CCM* authenticated decryption of a + * buffer. + * + * \note When using this function in a variable tag length context, + * the tag length has to be decoded from \p iv and passed to + * this function as \p tag_len. (\p tag needs to be adjusted + * accordingly.) + * + * \param ctx The CCM context to use for decryption. + * \param length The length of the input data in Bytes. + * \param iv Initialization vector (nonce). + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. + * \param add_len The length of additional data in Bytes. + * Must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * Must be at least \p length Bytes wide. + * \param tag The buffer holding the authentication field. + * \param tag_len The length of the authentication field in Bytes. + * 0, 4, 6, 8, 10, 12, 14 or 16. + * + * \warning Passing 0 as \p tag_len means that the message is no + * longer authenticated. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match. + * \return A cipher-specific error code on calculation failure. + */ +int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, + const unsigned char *iv, size_t iv_len, + const unsigned char *add, size_t add_len, + const unsigned char *input, unsigned char *output, + const unsigned char *tag, size_t tag_len ); + #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) /** - * \brief Checkup routine + * \brief The CCM checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_ccm_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ diff --git a/tools/sdk/include/mbedtls/mbedtls/certs.h b/tools/sdk/include/mbedtls/mbedtls/certs.h index ca49086e4f1..8dab7b5ce8c 100644 --- a/tools/sdk/include/mbedtls/mbedtls/certs.h +++ b/tools/sdk/include/mbedtls/mbedtls/certs.h @@ -2,7 +2,8 @@ * \file certs.h * * \brief Sample certificates and DHM parameters for testing - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/chacha20.h b/tools/sdk/include/mbedtls/mbedtls/chacha20.h new file mode 100644 index 00000000000..cfea40a5740 --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/chacha20.h @@ -0,0 +1,212 @@ +/** + * \file chacha20.h + * + * \brief This file contains ChaCha20 definitions and functions. + * + * ChaCha20 is a stream cipher that can encrypt and decrypt + * information. ChaCha was created by Daniel Bernstein as a variant of + * its Salsa cipher https://cr.yp.to/chacha/chacha-20080128.pdf + * ChaCha20 is the variant with 20 rounds, that was also standardized + * in RFC 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CHACHA20_H +#define MBEDTLS_CHACHA20_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA -0x0051 /**< Invalid input parameter(s). */ +#define MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE -0x0053 /**< Feature not available. For example, s part of the API is not implemented. */ +#define MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED -0x0055 /**< Chacha20 hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_CHACHA20_ALT) + +typedef struct mbedtls_chacha20_context +{ + uint32_t state[16]; /*! The state (before round operations). */ + uint8_t keystream8[64]; /*! Leftover keystream bytes. */ + size_t keystream_bytes_used; /*! Number of keystream bytes already used. */ +} +mbedtls_chacha20_context; + +#else /* MBEDTLS_CHACHA20_ALT */ +#include "chacha20_alt.h" +#endif /* MBEDTLS_CHACHA20_ALT */ + +/** + * \brief This function initializes the specified ChaCha20 context. + * + * It must be the first API called before using + * the context. + * + * It is usually followed by calls to + * \c mbedtls_chacha20_setkey() and + * \c mbedtls_chacha20_starts(), then one or more calls to + * to \c mbedtls_chacha20_update(), and finally to + * \c mbedtls_chacha20_free(). + * + * \param ctx The ChaCha20 context to initialize. + */ +void mbedtls_chacha20_init( mbedtls_chacha20_context *ctx ); + +/** + * \brief This function releases and clears the specified ChaCha20 context. + * + * \param ctx The ChaCha20 context to clear. + */ +void mbedtls_chacha20_free( mbedtls_chacha20_context *ctx ); + +/** + * \brief This function sets the encryption/decryption key. + * + * \note After using this function, you must also call + * \c mbedtls_chacha20_starts() to set a nonce before you + * start encrypting/decrypting data with + * \c mbedtls_chacha_update(). + * + * \param ctx The ChaCha20 context to which the key should be bound. + * \param key The encryption/decryption key. Must be 32 bytes in length. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or key is NULL. + */ +int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This function sets the nonce and initial counter value. + * + * \note A ChaCha20 context can be re-used with the same key by + * calling this function to change the nonce. + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality guarantees for the + * messages encrypted with the same nonce and key. + * + * \param ctx The ChaCha20 context to which the nonce should be bound. + * \param nonce The nonce. Must be 12 bytes in size. + * \param counter The initial counter value. This is usually 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or nonce is + * NULL. + */ +int mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx, + const unsigned char nonce[12], + uint32_t counter ); + +/** + * \brief This function encrypts or decrypts data. + * + * Since ChaCha20 is a stream cipher, the same operation is + * used for encrypting and decrypting data. + * + * \note The \p input and \p output pointers must either be equal or + * point to non-overlapping buffers. + * + * \note \c mbedtls_chacha20_setkey() and + * \c mbedtls_chacha20_starts() must be called at least once + * to setup the context before this function can be called. + * + * \note This function can be called multiple times in a row in + * order to encrypt of decrypt data piecewise with the same + * key and nonce. + * + * \param ctx The ChaCha20 context to use for encryption or decryption. + * \param size The length of the input data in bytes. + * \param input The buffer holding the input data. + * This pointer can be NULL if size == 0. + * \param output The buffer holding the output data. + * Must be able to hold \p size bytes. + * This pointer can be NULL if size == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if the ctx, input, or + * output pointers are NULL. + */ +int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx, + size_t size, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function encrypts or decrypts data with ChaCha20 and + * the given key and nonce. + * + * Since ChaCha20 is a stream cipher, the same operation is + * used for encrypting and decrypting data. + * + * \warning You must never use the same (key, nonce) pair more than + * once. This would void any confidentiality guarantees for + * the messages encrypted with the same nonce and key. + * + * \note The \p input and \p output pointers must either be equal or + * point to non-overlapping buffers. + * + * \param key The encryption/decryption key. Must be 32 bytes in length. + * \param nonce The nonce. Must be 12 bytes in size. + * \param counter The initial counter value. This is usually 0. + * \param size The length of the input data in bytes. + * \param input The buffer holding the input data. + * This pointer can be NULL if size == 0. + * \param output The buffer holding the output data. + * Must be able to hold \p size bytes. + * This pointer can be NULL if size == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if key, nonce, input, + * or output is NULL. + */ +int mbedtls_chacha20_crypt( const unsigned char key[32], + const unsigned char nonce[12], + uint32_t counter, + size_t size, + const unsigned char* input, + unsigned char* output ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The ChaCha20 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_chacha20_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CHACHA20_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/chachapoly.h b/tools/sdk/include/mbedtls/mbedtls/chachapoly.h new file mode 100644 index 00000000000..7de6f4e8c63 --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/chachapoly.h @@ -0,0 +1,355 @@ +/** + * \file chachapoly.h + * + * \brief This file contains the AEAD-ChaCha20-Poly1305 definitions and + * functions. + * + * ChaCha20-Poly1305 is an algorithm for Authenticated Encryption + * with Associated Data (AEAD) that can be used to encrypt and + * authenticate data. It is based on ChaCha20 and Poly1305 by Daniel + * Bernstein and was standardized in RFC 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CHACHAPOLY_H +#define MBEDTLS_CHACHAPOLY_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +/* for shared error codes */ +#include "poly1305.h" + +#define MBEDTLS_ERR_CHACHAPOLY_BAD_STATE -0x0054 /**< The requested operation is not permitted in the current state. */ +#define MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED -0x0056 /**< Authenticated decryption failed: data was not authentic. */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + MBEDTLS_CHACHAPOLY_ENCRYPT, /**< The mode value for performing encryption. */ + MBEDTLS_CHACHAPOLY_DECRYPT /**< The mode value for performing decryption. */ +} +mbedtls_chachapoly_mode_t; + +#if !defined(MBEDTLS_CHACHAPOLY_ALT) + +#include "chacha20.h" + +typedef struct mbedtls_chachapoly_context +{ + mbedtls_chacha20_context chacha20_ctx; /**< The ChaCha20 context. */ + mbedtls_poly1305_context poly1305_ctx; /**< The Poly1305 context. */ + uint64_t aad_len; /**< The length (bytes) of the Additional Authenticated Data. */ + uint64_t ciphertext_len; /**< The length (bytes) of the ciphertext. */ + int state; /**< The current state of the context. */ + mbedtls_chachapoly_mode_t mode; /**< Cipher mode (encrypt or decrypt). */ +} +mbedtls_chachapoly_context; + +#else /* !MBEDTLS_CHACHAPOLY_ALT */ +#include "chachapoly_alt.h" +#endif /* !MBEDTLS_CHACHAPOLY_ALT */ + +/** + * \brief This function initializes the specified ChaCha20-Poly1305 context. + * + * It must be the first API called before using + * the context. It must be followed by a call to + * \c mbedtls_chachapoly_setkey() before any operation can be + * done, and to \c mbedtls_chachapoly_free() once all + * operations with that context have been finished. + * + * In order to encrypt or decrypt full messages at once, for + * each message you should make a single call to + * \c mbedtls_chachapoly_crypt_and_tag() or + * \c mbedtls_chachapoly_auth_decrypt(). + * + * In order to encrypt messages piecewise, for each + * message you should make a call to + * \c mbedtls_chachapoly_starts(), then 0 or more calls to + * \c mbedtls_chachapoly_update_aad(), then 0 or more calls to + * \c mbedtls_chachapoly_update(), then one call to + * \c mbedtls_chachapoly_finish(). + * + * \warning Decryption with the piecewise API is discouraged! Always + * use \c mbedtls_chachapoly_auth_decrypt() when possible! + * + * If however this is not possible because the data is too + * large to fit in memory, you need to: + * + * - call \c mbedtls_chachapoly_starts() and (if needed) + * \c mbedtls_chachapoly_update_aad() as above, + * - call \c mbedtls_chachapoly_update() multiple times and + * ensure its output (the plaintext) is NOT used in any other + * way than placing it in temporary storage at this point, + * - call \c mbedtls_chachapoly_finish() to compute the + * authentication tag and compared it in constant time to the + * tag received with the ciphertext. + * + * If the tags are not equal, you must immediately discard + * all previous outputs of \c mbedtls_chachapoly_update(), + * otherwise you can now safely use the plaintext. + * + * \param ctx The ChachaPoly context to initialize. + */ +void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx ); + +/** + * \brief This function releases and clears the specified ChaCha20-Poly1305 context. + * + * \param ctx The ChachaPoly context to clear. + */ +void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx ); + +/** + * \brief This function sets the ChaCha20-Poly1305 symmetric encryption key. + * + * \param ctx The ChaCha20-Poly1305 context to which the key should be + * bound. + * \param key The 256-bit (32 bytes) key. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p key are NULL. + */ +int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This function starts a ChaCha20-Poly1305 encryption or + * decryption operation. + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality and authenticity + * guarantees for the messages encrypted with the same nonce + * and key. + * + * \note If the context is being used for AAD only (no data to + * encrypt or decrypt) then \p mode can be set to any value. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context. + * \param nonce The nonce/IV to use for the message. Must be 12 bytes. + * \param mode The operation to perform: #MBEDTLS_CHACHAPOLY_ENCRYPT or + * #MBEDTLS_CHACHAPOLY_DECRYPT (discouraged, see warning). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p mac are NULL. + */ +int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx, + const unsigned char nonce[12], + mbedtls_chachapoly_mode_t mode ); + +/** + * \brief This function feeds additional data to be authenticated + * into an ongoing ChaCha20-Poly1305 operation. + * + * The Additional Authenticated Data (AAD), also called + * Associated Data (AD) is only authenticated but not + * encrypted nor included in the encrypted output. It is + * usually transmitted separately from the ciphertext or + * computed locally by each party. + * + * \note This function is called before data is encrypted/decrypted. + * I.e. call this function to process the AAD before calling + * \c mbedtls_chachapoly_update(). + * + * You may call this function multiple times to process + * an arbitrary amount of AAD. It is permitted to call + * this function 0 times, if no AAD is used. + * + * This function cannot be called any more if data has + * been processed by \c mbedtls_chachapoly_update(), + * or if the context has been finished. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context to use. + * \param aad_len The length (in bytes) of the AAD. The length has no + * restrictions. + * \param aad Buffer containing the AAD. + * This pointer can be NULL if aad_len == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p aad are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operations has not been started or has been + * finished, or if the AAD has been finished. + */ +int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx, + const unsigned char *aad, + size_t aad_len ); + +/** + * \brief Thus function feeds data to be encrypted or decrypted + * into an on-going ChaCha20-Poly1305 + * operation. + * + * The direction (encryption or decryption) depends on the + * mode that was given when calling + * \c mbedtls_chachapoly_starts(). + * + * You may call this function multiple times to process + * an arbitrary amount of data. It is permitted to call + * this function 0 times, if no data is to be encrypted + * or decrypted. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context to use. + * \param len The length (in bytes) of the data to encrypt or decrypt. + * \param input The buffer containing the data to encrypt or decrypt. + * This pointer can be NULL if len == 0. + * \param output The buffer to where the encrypted or decrypted data is written. + * Must be able to hold \p len bytes. + * This pointer can be NULL if len == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx, \p input, or \p output are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operation has not been started or has been + * finished. + */ +int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx, + size_t len, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function finished the ChaCha20-Poly1305 operation and + * generates the MAC (authentication tag). + * + * \param ctx The ChaCha20-Poly1305 context to use. + * \param mac The buffer to where the 128-bit (16 bytes) MAC is written. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p mac are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operation has not been started or has been + * finished. + */ +int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx, + unsigned char mac[16] ); + +/** + * \brief This function performs a complete ChaCha20-Poly1305 + * authenticated encryption with the previously-set key. + * + * \note Before using this function, you must set the key with + * \c mbedtls_chachapoly_setkey(). + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality and authenticity + * guarantees for the messages encrypted with the same nonce + * and key. + * + * \param ctx The ChaCha20-Poly1305 context to use (holds the key). + * \param length The length (in bytes) of the data to encrypt or decrypt. + * \param nonce The 96-bit (12 bytes) nonce/IV to use. + * \param aad The buffer containing the additional authenticated data (AAD). + * This pointer can be NULL if aad_len == 0. + * \param aad_len The length (in bytes) of the AAD data to process. + * \param input The buffer containing the data to encrypt or decrypt. + * This pointer can be NULL if ilen == 0. + * \param output The buffer to where the encrypted or decrypted data is written. + * This pointer can be NULL if ilen == 0. + * \param tag The buffer to where the computed 128-bit (16 bytes) MAC is written. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if one or more of the required parameters are NULL. + */ +int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx, + size_t length, + const unsigned char nonce[12], + const unsigned char *aad, + size_t aad_len, + const unsigned char *input, + unsigned char *output, + unsigned char tag[16] ); + +/** + * \brief This function performs a complete ChaCha20-Poly1305 + * authenticated decryption with the previously-set key. + * + * \note Before using this function, you must set the key with + * \c mbedtls_chachapoly_setkey(). + * + * \param ctx The ChaCha20-Poly1305 context to use (holds the key). + * \param length The length (in bytes) of the data to decrypt. + * \param nonce The 96-bit (12 bytes) nonce/IV to use. + * \param aad The buffer containing the additional authenticated data (AAD). + * This pointer can be NULL if aad_len == 0. + * \param aad_len The length (in bytes) of the AAD data to process. + * \param tag The buffer holding the authentication tag. + * \param input The buffer containing the data to decrypt. + * This pointer can be NULL if ilen == 0. + * \param output The buffer to where the decrypted data is written. + * This pointer can be NULL if ilen == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if one or more of the required parameters are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED + * if the data was not authentic. + */ +int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx, + size_t length, + const unsigned char nonce[12], + const unsigned char *aad, + size_t aad_len, + const unsigned char tag[16], + const unsigned char *input, + unsigned char *output ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The ChaCha20-Poly1305 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_chachapoly_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CHACHAPOLY_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/check_config.h b/tools/sdk/include/mbedtls/mbedtls/check_config.h index fa72454e537..9e6bb8a46aa 100644 --- a/tools/sdk/include/mbedtls/mbedtls/check_config.h +++ b/tools/sdk/include/mbedtls/mbedtls/check_config.h @@ -2,8 +2,9 @@ * \file check_config.h * * \brief Consistency checks for configuration options - * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + */ +/* + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -77,11 +78,20 @@ #error "MBEDTLS_DHM_C defined, but not all prerequisites" #endif +#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) && !defined(MBEDTLS_SSL_TRUNCATED_HMAC) +#error "MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT defined, but not all prerequisites" +#endif + #if defined(MBEDTLS_CMAC_C) && \ !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C) #error "MBEDTLS_CMAC_C defined, but not all prerequisites" #endif +#if defined(MBEDTLS_NIST_KW_C) && \ + ( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) ) +#error "MBEDTLS_NIST_KW_C defined, but not all prerequisites" +#endif + #if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C) #error "MBEDTLS_ECDH_C defined, but not all prerequisites" #endif @@ -186,6 +196,10 @@ #error "MBEDTLS_HAVEGE_C defined, but not all prerequisites" #endif +#if defined(MBEDTLS_HKDF_C) && !defined(MBEDTLS_MD_C) +#error "MBEDTLS_HKDF_C defined, but not all prerequisites" +#endif + #if defined(MBEDTLS_HMAC_DRBG_C) && !defined(MBEDTLS_MD_C) #error "MBEDTLS_HMAC_DRBG_C defined, but not all prerequisites" #endif diff --git a/tools/sdk/include/mbedtls/mbedtls/cipher.h b/tools/sdk/include/mbedtls/mbedtls/cipher.h index b12e38843a0..dfb1541103c 100644 --- a/tools/sdk/include/mbedtls/mbedtls/cipher.h +++ b/tools/sdk/include/mbedtls/mbedtls/cipher.h @@ -1,11 +1,14 @@ /** * \file cipher.h * - * \brief Generic cipher wrapper. + * \brief This file contains an abstraction interface for use with the cipher + * primitives provided by the library. It provides a common interface to all of + * the available cipher operations. * * \author Adriaan de Jong - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -20,7 +23,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_CIPHER_H @@ -34,7 +37,7 @@ #include -#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C) #define MBEDTLS_CIPHER_MODE_AEAD #endif @@ -42,7 +45,8 @@ #define MBEDTLS_CIPHER_MODE_WITH_PADDING #endif -#if defined(MBEDTLS_ARC4_C) +#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \ + defined(MBEDTLS_CHACHA20_C) #define MBEDTLS_CIPHER_MODE_STREAM #endif @@ -51,104 +55,151 @@ #define inline __inline #endif -#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE -0x6080 /**< The selected feature is not available. */ -#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA -0x6100 /**< Bad input parameters to function. */ -#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED -0x6180 /**< Failed to allocate memory. */ -#define MBEDTLS_ERR_CIPHER_INVALID_PADDING -0x6200 /**< Input data contains invalid padding and is rejected. */ -#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED -0x6280 /**< Decryption of block requires a full block. */ -#define MBEDTLS_ERR_CIPHER_AUTH_FAILED -0x6300 /**< Authentication failed (for AEAD modes). */ -#define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT -0x6380 /**< The context is invalid, eg because it was free()ed. */ +#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE -0x6080 /**< The selected feature is not available. */ +#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA -0x6100 /**< Bad input parameters. */ +#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED -0x6180 /**< Failed to allocate memory. */ +#define MBEDTLS_ERR_CIPHER_INVALID_PADDING -0x6200 /**< Input data contains invalid padding and is rejected. */ +#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED -0x6280 /**< Decryption of block requires a full block. */ +#define MBEDTLS_ERR_CIPHER_AUTH_FAILED -0x6300 /**< Authentication failed (for AEAD modes). */ +#define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT -0x6380 /**< The context is invalid. For example, because it was freed. */ +#define MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED -0x6400 /**< Cipher hardware accelerator failed. */ -#define MBEDTLS_CIPHER_VARIABLE_IV_LEN 0x01 /**< Cipher accepts IVs of variable length */ -#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN 0x02 /**< Cipher accepts keys of variable length */ +#define MBEDTLS_CIPHER_VARIABLE_IV_LEN 0x01 /**< Cipher accepts IVs of variable length. */ +#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN 0x02 /**< Cipher accepts keys of variable length. */ #ifdef __cplusplus extern "C" { #endif +/** + * \brief Supported cipher types. + * + * \warning RC4 and DES are considered weak ciphers and their use + * constitutes a security risk. Arm recommends considering stronger + * ciphers instead. + */ typedef enum { - MBEDTLS_CIPHER_ID_NONE = 0, - MBEDTLS_CIPHER_ID_NULL, - MBEDTLS_CIPHER_ID_AES, - MBEDTLS_CIPHER_ID_DES, - MBEDTLS_CIPHER_ID_3DES, - MBEDTLS_CIPHER_ID_CAMELLIA, - MBEDTLS_CIPHER_ID_BLOWFISH, - MBEDTLS_CIPHER_ID_ARC4, + MBEDTLS_CIPHER_ID_NONE = 0, /**< Placeholder to mark the end of cipher ID lists. */ + MBEDTLS_CIPHER_ID_NULL, /**< The identity cipher, treated as a stream cipher. */ + MBEDTLS_CIPHER_ID_AES, /**< The AES cipher. */ + MBEDTLS_CIPHER_ID_DES, /**< The DES cipher. */ + MBEDTLS_CIPHER_ID_3DES, /**< The Triple DES cipher. */ + MBEDTLS_CIPHER_ID_CAMELLIA, /**< The Camellia cipher. */ + MBEDTLS_CIPHER_ID_BLOWFISH, /**< The Blowfish cipher. */ + MBEDTLS_CIPHER_ID_ARC4, /**< The RC4 cipher. */ + MBEDTLS_CIPHER_ID_ARIA, /**< The Aria cipher. */ + MBEDTLS_CIPHER_ID_CHACHA20, /**< The ChaCha20 cipher. */ } mbedtls_cipher_id_t; +/** + * \brief Supported {cipher type, cipher mode} pairs. + * + * \warning RC4 and DES are considered weak ciphers and their use + * constitutes a security risk. Arm recommends considering stronger + * ciphers instead. + */ typedef enum { - MBEDTLS_CIPHER_NONE = 0, - MBEDTLS_CIPHER_NULL, - MBEDTLS_CIPHER_AES_128_ECB, - MBEDTLS_CIPHER_AES_192_ECB, - MBEDTLS_CIPHER_AES_256_ECB, - MBEDTLS_CIPHER_AES_128_CBC, - MBEDTLS_CIPHER_AES_192_CBC, - MBEDTLS_CIPHER_AES_256_CBC, - MBEDTLS_CIPHER_AES_128_CFB128, - MBEDTLS_CIPHER_AES_192_CFB128, - MBEDTLS_CIPHER_AES_256_CFB128, - MBEDTLS_CIPHER_AES_128_CTR, - MBEDTLS_CIPHER_AES_192_CTR, - MBEDTLS_CIPHER_AES_256_CTR, - MBEDTLS_CIPHER_AES_128_GCM, - MBEDTLS_CIPHER_AES_192_GCM, - MBEDTLS_CIPHER_AES_256_GCM, - MBEDTLS_CIPHER_CAMELLIA_128_ECB, - MBEDTLS_CIPHER_CAMELLIA_192_ECB, - MBEDTLS_CIPHER_CAMELLIA_256_ECB, - MBEDTLS_CIPHER_CAMELLIA_128_CBC, - MBEDTLS_CIPHER_CAMELLIA_192_CBC, - MBEDTLS_CIPHER_CAMELLIA_256_CBC, - MBEDTLS_CIPHER_CAMELLIA_128_CFB128, - MBEDTLS_CIPHER_CAMELLIA_192_CFB128, - MBEDTLS_CIPHER_CAMELLIA_256_CFB128, - MBEDTLS_CIPHER_CAMELLIA_128_CTR, - MBEDTLS_CIPHER_CAMELLIA_192_CTR, - MBEDTLS_CIPHER_CAMELLIA_256_CTR, - MBEDTLS_CIPHER_CAMELLIA_128_GCM, - MBEDTLS_CIPHER_CAMELLIA_192_GCM, - MBEDTLS_CIPHER_CAMELLIA_256_GCM, - MBEDTLS_CIPHER_DES_ECB, - MBEDTLS_CIPHER_DES_CBC, - MBEDTLS_CIPHER_DES_EDE_ECB, - MBEDTLS_CIPHER_DES_EDE_CBC, - MBEDTLS_CIPHER_DES_EDE3_ECB, - MBEDTLS_CIPHER_DES_EDE3_CBC, - MBEDTLS_CIPHER_BLOWFISH_ECB, - MBEDTLS_CIPHER_BLOWFISH_CBC, - MBEDTLS_CIPHER_BLOWFISH_CFB64, - MBEDTLS_CIPHER_BLOWFISH_CTR, - MBEDTLS_CIPHER_ARC4_128, - MBEDTLS_CIPHER_AES_128_CCM, - MBEDTLS_CIPHER_AES_192_CCM, - MBEDTLS_CIPHER_AES_256_CCM, - MBEDTLS_CIPHER_CAMELLIA_128_CCM, - MBEDTLS_CIPHER_CAMELLIA_192_CCM, - MBEDTLS_CIPHER_CAMELLIA_256_CCM, + MBEDTLS_CIPHER_NONE = 0, /**< Placeholder to mark the end of cipher-pair lists. */ + MBEDTLS_CIPHER_NULL, /**< The identity stream cipher. */ + MBEDTLS_CIPHER_AES_128_ECB, /**< AES cipher with 128-bit ECB mode. */ + MBEDTLS_CIPHER_AES_192_ECB, /**< AES cipher with 192-bit ECB mode. */ + MBEDTLS_CIPHER_AES_256_ECB, /**< AES cipher with 256-bit ECB mode. */ + MBEDTLS_CIPHER_AES_128_CBC, /**< AES cipher with 128-bit CBC mode. */ + MBEDTLS_CIPHER_AES_192_CBC, /**< AES cipher with 192-bit CBC mode. */ + MBEDTLS_CIPHER_AES_256_CBC, /**< AES cipher with 256-bit CBC mode. */ + MBEDTLS_CIPHER_AES_128_CFB128, /**< AES cipher with 128-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_192_CFB128, /**< AES cipher with 192-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_256_CFB128, /**< AES cipher with 256-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_128_CTR, /**< AES cipher with 128-bit CTR mode. */ + MBEDTLS_CIPHER_AES_192_CTR, /**< AES cipher with 192-bit CTR mode. */ + MBEDTLS_CIPHER_AES_256_CTR, /**< AES cipher with 256-bit CTR mode. */ + MBEDTLS_CIPHER_AES_128_GCM, /**< AES cipher with 128-bit GCM mode. */ + MBEDTLS_CIPHER_AES_192_GCM, /**< AES cipher with 192-bit GCM mode. */ + MBEDTLS_CIPHER_AES_256_GCM, /**< AES cipher with 256-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_ECB, /**< Camellia cipher with 128-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_ECB, /**< Camellia cipher with 192-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_ECB, /**< Camellia cipher with 256-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CBC, /**< Camellia cipher with 128-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CBC, /**< Camellia cipher with 192-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CBC, /**< Camellia cipher with 256-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CFB128, /**< Camellia cipher with 128-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CFB128, /**< Camellia cipher with 192-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CFB128, /**< Camellia cipher with 256-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CTR, /**< Camellia cipher with 128-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CTR, /**< Camellia cipher with 192-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CTR, /**< Camellia cipher with 256-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_GCM, /**< Camellia cipher with 128-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_GCM, /**< Camellia cipher with 192-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_GCM, /**< Camellia cipher with 256-bit GCM mode. */ + MBEDTLS_CIPHER_DES_ECB, /**< DES cipher with ECB mode. */ + MBEDTLS_CIPHER_DES_CBC, /**< DES cipher with CBC mode. */ + MBEDTLS_CIPHER_DES_EDE_ECB, /**< DES cipher with EDE ECB mode. */ + MBEDTLS_CIPHER_DES_EDE_CBC, /**< DES cipher with EDE CBC mode. */ + MBEDTLS_CIPHER_DES_EDE3_ECB, /**< DES cipher with EDE3 ECB mode. */ + MBEDTLS_CIPHER_DES_EDE3_CBC, /**< DES cipher with EDE3 CBC mode. */ + MBEDTLS_CIPHER_BLOWFISH_ECB, /**< Blowfish cipher with ECB mode. */ + MBEDTLS_CIPHER_BLOWFISH_CBC, /**< Blowfish cipher with CBC mode. */ + MBEDTLS_CIPHER_BLOWFISH_CFB64, /**< Blowfish cipher with CFB64 mode. */ + MBEDTLS_CIPHER_BLOWFISH_CTR, /**< Blowfish cipher with CTR mode. */ + MBEDTLS_CIPHER_ARC4_128, /**< RC4 cipher with 128-bit mode. */ + MBEDTLS_CIPHER_AES_128_CCM, /**< AES cipher with 128-bit CCM mode. */ + MBEDTLS_CIPHER_AES_192_CCM, /**< AES cipher with 192-bit CCM mode. */ + MBEDTLS_CIPHER_AES_256_CCM, /**< AES cipher with 256-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CCM, /**< Camellia cipher with 128-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CCM, /**< Camellia cipher with 192-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CCM, /**< Camellia cipher with 256-bit CCM mode. */ + MBEDTLS_CIPHER_ARIA_128_ECB, /**< Aria cipher with 128-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_192_ECB, /**< Aria cipher with 192-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_256_ECB, /**< Aria cipher with 256-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_128_CBC, /**< Aria cipher with 128-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_192_CBC, /**< Aria cipher with 192-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_256_CBC, /**< Aria cipher with 256-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_128_CFB128, /**< Aria cipher with 128-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_192_CFB128, /**< Aria cipher with 192-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_256_CFB128, /**< Aria cipher with 256-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_128_CTR, /**< Aria cipher with 128-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_192_CTR, /**< Aria cipher with 192-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_256_CTR, /**< Aria cipher with 256-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_128_GCM, /**< Aria cipher with 128-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_192_GCM, /**< Aria cipher with 192-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_256_GCM, /**< Aria cipher with 256-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_128_CCM, /**< Aria cipher with 128-bit key and CCM mode. */ + MBEDTLS_CIPHER_ARIA_192_CCM, /**< Aria cipher with 192-bit key and CCM mode. */ + MBEDTLS_CIPHER_ARIA_256_CCM, /**< Aria cipher with 256-bit key and CCM mode. */ + MBEDTLS_CIPHER_AES_128_OFB, /**< AES 128-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_192_OFB, /**< AES 192-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_256_OFB, /**< AES 256-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_128_XTS, /**< AES 128-bit cipher in XTS block mode. */ + MBEDTLS_CIPHER_AES_256_XTS, /**< AES 256-bit cipher in XTS block mode. */ + MBEDTLS_CIPHER_CHACHA20, /**< ChaCha20 stream cipher. */ + MBEDTLS_CIPHER_CHACHA20_POLY1305, /**< ChaCha20-Poly1305 AEAD cipher. */ } mbedtls_cipher_type_t; +/** Supported cipher modes. */ typedef enum { - MBEDTLS_MODE_NONE = 0, - MBEDTLS_MODE_ECB, - MBEDTLS_MODE_CBC, - MBEDTLS_MODE_CFB, - MBEDTLS_MODE_OFB, /* Unused! */ - MBEDTLS_MODE_CTR, - MBEDTLS_MODE_GCM, - MBEDTLS_MODE_STREAM, - MBEDTLS_MODE_CCM, + MBEDTLS_MODE_NONE = 0, /**< None. */ + MBEDTLS_MODE_ECB, /**< The ECB cipher mode. */ + MBEDTLS_MODE_CBC, /**< The CBC cipher mode. */ + MBEDTLS_MODE_CFB, /**< The CFB cipher mode. */ + MBEDTLS_MODE_OFB, /**< The OFB cipher mode. */ + MBEDTLS_MODE_CTR, /**< The CTR cipher mode. */ + MBEDTLS_MODE_GCM, /**< The GCM cipher mode. */ + MBEDTLS_MODE_STREAM, /**< The stream cipher mode. */ + MBEDTLS_MODE_CCM, /**< The CCM cipher mode. */ + MBEDTLS_MODE_XTS, /**< The XTS cipher mode. */ + MBEDTLS_MODE_CHACHAPOLY, /**< The ChaCha-Poly cipher mode. */ } mbedtls_cipher_mode_t; +/** Supported cipher padding types. */ typedef enum { - MBEDTLS_PADDING_PKCS7 = 0, /**< PKCS7 padding (default) */ - MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding */ - MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding */ - MBEDTLS_PADDING_ZEROS, /**< zero padding (not reversible!) */ - MBEDTLS_PADDING_NONE, /**< never pad (full blocks only) */ + MBEDTLS_PADDING_PKCS7 = 0, /**< PKCS7 padding (default). */ + MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding. */ + MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding. */ + MBEDTLS_PADDING_ZEROS, /**< Zero padding (not reversible). */ + MBEDTLS_PADDING_NONE, /**< Never pad (full blocks only). */ } mbedtls_cipher_padding_t; +/** Type of operation. */ typedef enum { MBEDTLS_OPERATION_NONE = -1, MBEDTLS_DECRYPT = 0, @@ -156,19 +207,19 @@ typedef enum { } mbedtls_operation_t; enum { - /** Undefined key length */ + /** Undefined key length. */ MBEDTLS_KEY_LENGTH_NONE = 0, - /** Key length, in bits (including parity), for DES keys */ + /** Key length, in bits (including parity), for DES keys. */ MBEDTLS_KEY_LENGTH_DES = 64, - /** Key length, in bits (including parity), for DES in two key EDE */ + /** Key length in bits, including parity, for DES in two-key EDE. */ MBEDTLS_KEY_LENGTH_DES_EDE = 128, - /** Key length, in bits (including parity), for DES in three-key EDE */ + /** Key length in bits, including parity, for DES in three-key EDE. */ MBEDTLS_KEY_LENGTH_DES_EDE3 = 192, }; -/** Maximum length of any IV, in bytes */ +/** Maximum length of any IV, in Bytes. */ #define MBEDTLS_MAX_IV_LENGTH 16 -/** Maximum block size of any cipher, in bytes */ +/** Maximum block size of any cipher, in Bytes. */ #define MBEDTLS_MAX_BLOCK_LENGTH 16 /** @@ -182,33 +233,44 @@ typedef struct mbedtls_cipher_base_t mbedtls_cipher_base_t; typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t; /** - * Cipher information. Allows cipher functions to be called in a generic way. + * Cipher information. Allows calling cipher functions + * in a generic way. */ -typedef struct { - /** Full cipher identifier (e.g. MBEDTLS_CIPHER_AES_256_CBC) */ +typedef struct mbedtls_cipher_info_t +{ + /** Full cipher identifier. For example, + * MBEDTLS_CIPHER_AES_256_CBC. + */ mbedtls_cipher_type_t type; - /** Cipher mode (e.g. MBEDTLS_MODE_CBC) */ + /** The cipher mode. For example, MBEDTLS_MODE_CBC. */ mbedtls_cipher_mode_t mode; - /** Cipher key length, in bits (default length for variable sized ciphers) - * (Includes parity bits for ciphers like DES) */ + /** The cipher key length, in bits. This is the + * default length for variable sized ciphers. + * Includes parity bits for ciphers like DES. + */ unsigned int key_bitlen; - /** Name of the cipher */ + /** Name of the cipher. */ const char * name; - /** IV/NONCE size, in bytes. - * For cipher that accept many sizes: recommended size */ + /** IV or nonce size, in Bytes. + * For ciphers that accept variable IV sizes, + * this is the recommended size. + */ unsigned int iv_size; - /** Flags for variable IV size, variable key size, etc. */ + /** Bitflag comprised of MBEDTLS_CIPHER_VARIABLE_IV_LEN and + * MBEDTLS_CIPHER_VARIABLE_KEY_LEN indicating whether the + * cipher supports variable IV or variable key sizes, respectively. + */ int flags; - /** block size, in bytes */ + /** The block size, in Bytes. */ unsigned int block_size; - /** Base cipher information and functions */ + /** Struct for base cipher information and functions. */ const mbedtls_cipher_base_t *base; } mbedtls_cipher_info_t; @@ -216,126 +278,140 @@ typedef struct { /** * Generic cipher context. */ -typedef struct { - /** Information about the associated cipher */ +typedef struct mbedtls_cipher_context_t +{ + /** Information about the associated cipher. */ const mbedtls_cipher_info_t *cipher_info; - /** Key length to use */ + /** Key length to use. */ int key_bitlen; - /** Operation that the context's key has been initialised for */ + /** Operation that the key of the context has been + * initialized for. + */ mbedtls_operation_t operation; #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) - /** Padding functions to use, if relevant for cipher mode */ + /** Padding functions to use, if relevant for + * the specific cipher mode. + */ void (*add_padding)( unsigned char *output, size_t olen, size_t data_len ); int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len ); #endif - /** Buffer for data that hasn't been encrypted yet */ + /** Buffer for input that has not been processed yet. */ unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH]; - /** Number of bytes that still need processing */ + /** Number of Bytes that have not been processed yet. */ size_t unprocessed_len; - /** Current IV or NONCE_COUNTER for CTR-mode */ + /** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number + * for XTS-mode. */ unsigned char iv[MBEDTLS_MAX_IV_LENGTH]; - /** IV size in bytes (for ciphers with variable-length IVs) */ + /** IV size in Bytes, for ciphers with variable-length IVs. */ size_t iv_size; - /** Cipher-specific context */ + /** The cipher-specific context. */ void *cipher_ctx; #if defined(MBEDTLS_CMAC_C) - /** CMAC Specific context */ + /** CMAC-specific context. */ mbedtls_cmac_context_t *cmac_ctx; #endif } mbedtls_cipher_context_t; /** - * \brief Returns the list of ciphers supported by the generic cipher module. + * \brief This function retrieves the list of ciphers supported by the generic + * cipher module. * - * \return a statically allocated array of ciphers, the last entry - * is 0. + * \return A statically-allocated array of ciphers. The last entry + * is zero. */ const int *mbedtls_cipher_list( void ); /** - * \brief Returns the cipher information structure associated - * with the given cipher name. + * \brief This function retrieves the cipher-information + * structure associated with the given cipher name. * * \param cipher_name Name of the cipher to search for. * - * \return the cipher information structure associated with the - * given cipher_name, or NULL if not found. + * \return The cipher information structure associated with the + * given \p cipher_name. + * \return NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name ); /** - * \brief Returns the cipher information structure associated - * with the given cipher type. + * \brief This function retrieves the cipher-information + * structure associated with the given cipher type. * * \param cipher_type Type of the cipher to search for. * - * \return the cipher information structure associated with the - * given cipher_type, or NULL if not found. + * \return The cipher information structure associated with the + * given \p cipher_type. + * \return NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type ); /** - * \brief Returns the cipher information structure associated - * with the given cipher id, key size and mode. - * - * \param cipher_id Id of the cipher to search for - * (e.g. MBEDTLS_CIPHER_ID_AES) - * \param key_bitlen Length of the key in bits - * \param mode Cipher mode (e.g. MBEDTLS_MODE_CBC) - * - * \return the cipher information structure associated with the - * given cipher_type, or NULL if not found. + * \brief This function retrieves the cipher-information + * structure associated with the given cipher ID, + * key size and mode. + * + * \param cipher_id The ID of the cipher to search for. For example, + * #MBEDTLS_CIPHER_ID_AES. + * \param key_bitlen The length of the key in bits. + * \param mode The cipher mode. For example, #MBEDTLS_MODE_CBC. + * + * \return The cipher information structure associated with the + * given \p cipher_id. + * \return NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id, int key_bitlen, const mbedtls_cipher_mode_t mode ); /** - * \brief Initialize a cipher_context (as NONE) + * \brief This function initializes a \p cipher_context as NONE. */ void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx ); /** - * \brief Free and clear the cipher-specific context of ctx. - * Freeing ctx itself remains the responsibility of the - * caller. + * \brief This function frees and clears the cipher-specific + * context of \p ctx. Freeing \p ctx itself remains the + * responsibility of the caller. */ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ); + /** - * \brief Initialises and fills the cipher context structure with - * the appropriate values. - * - * \note Currently also clears structure. In future versions you - * will be required to call mbedtls_cipher_init() on the structure - * first. - * - * \param ctx context to initialise. May not be NULL. - * \param cipher_info cipher to use. - * - * \return 0 on success, - * MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on parameter failure, - * MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the - * cipher-specific context failed. + * \brief This function initializes and fills the cipher-context + * structure with the appropriate values. It also clears + * the structure. + * + * \param ctx The context to initialize. May not be NULL. + * \param cipher_info The cipher to use. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the + * cipher-specific context fails. + * + * \internal Currently, the function also clears the structure. + * In future versions, the caller will be required to call + * mbedtls_cipher_init() on the structure first. */ int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info ); /** - * \brief Returns the block size of the given cipher. + * \brief This function returns the block size of the given cipher. * - * \param ctx cipher's context. Must have been initialised. + * \param ctx The context of the cipher. Must be initialized. * - * \return size of the cipher's blocks, or 0 if ctx has not been - * initialised. + * \return The size of the blocks of the cipher. + * \return 0 if \p ctx has not been initialized. */ static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_context_t *ctx ) { @@ -346,13 +422,13 @@ static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_c } /** - * \brief Returns the mode of operation for the cipher. - * (e.g. MBEDTLS_MODE_CBC) + * \brief This function returns the mode of operation for + * the cipher. For example, MBEDTLS_MODE_CBC. * - * \param ctx cipher's context. Must have been initialised. + * \param ctx The context of the cipher. Must be initialized. * - * \return mode of operation, or MBEDTLS_MODE_NONE if ctx - * has not been initialised. + * \return The mode of operation. + * \return #MBEDTLS_MODE_NONE if \p ctx has not been initialized. */ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtls_cipher_context_t *ctx ) { @@ -363,13 +439,14 @@ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtl } /** - * \brief Returns the size of the cipher's IV/NONCE in bytes. + * \brief This function returns the size of the IV or nonce + * of the cipher, in Bytes. * - * \param ctx cipher's context. Must have been initialised. + * \param ctx The context of the cipher. Must be initialized. * - * \return If IV has not been set yet: (recommended) IV size - * (0 for ciphers not using IV/NONCE). - * If IV has already been set: actual size. + * \return The recommended IV size if no IV has been set. + * \return \c 0 for ciphers not using an IV or a nonce. + * \return The actual size if an IV has been set. */ static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ctx ) { @@ -383,12 +460,12 @@ static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ct } /** - * \brief Returns the type of the given cipher. + * \brief This function returns the type of the given cipher. * - * \param ctx cipher's context. Must have been initialised. + * \param ctx The context of the cipher. Must be initialized. * - * \return type of the cipher, or MBEDTLS_CIPHER_NONE if ctx has - * not been initialised. + * \return The type of the cipher. + * \return #MBEDTLS_CIPHER_NONE if \p ctx has not been initialized. */ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_cipher_context_t *ctx ) { @@ -399,11 +476,13 @@ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_ciphe } /** - * \brief Returns the name of the given cipher, as a string. + * \brief This function returns the name of the given cipher + * as a string. * - * \param ctx cipher's context. Must have been initialised. + * \param ctx The context of the cipher. Must be initialized. * - * \return name of the cipher, or NULL if ctx was not initialised. + * \return The name of the cipher. + * \return NULL if \p ctx has not been not initialized. */ static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_t *ctx ) { @@ -414,13 +493,13 @@ static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_ } /** - * \brief Returns the key length of the cipher. + * \brief This function returns the key length of the cipher. * - * \param ctx cipher's context. Must have been initialised. + * \param ctx The context of the cipher. Must be initialized. * - * \return cipher's key length, in bits, or - * MBEDTLS_KEY_LENGTH_NONE if ctx has not been - * initialised. + * \return The key length of the cipher in bits. + * \return #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been + * initialized. */ static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t *ctx ) { @@ -431,13 +510,12 @@ static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t } /** - * \brief Returns the operation of the given cipher. + * \brief This function returns the operation of the given cipher. * - * \param ctx cipher's context. Must have been initialised. + * \param ctx The context of the cipher. Must be initialized. * - * \return operation (MBEDTLS_ENCRYPT or MBEDTLS_DECRYPT), - * or MBEDTLS_OPERATION_NONE if ctx has not been - * initialised. + * \return The type of operation: #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. + * \return #MBEDTLS_OPERATION_NONE if \p ctx has not been initialized. */ static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_cipher_context_t *ctx ) { @@ -448,189 +526,206 @@ static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_ci } /** - * \brief Set the key to use with the given context. + * \brief This function sets the key to use with the given context. * - * \param ctx generic cipher context. May not be NULL. Must have been - * initialised using cipher_context_from_type or - * cipher_context_from_string. + * \param ctx The generic cipher context. May not be NULL. Must have + * been initialized using mbedtls_cipher_info_from_type() + * or mbedtls_cipher_info_from_string(). * \param key The key to use. - * \param key_bitlen key length to use, in bits. - * \param operation Operation that the key will be used for, either - * MBEDTLS_ENCRYPT or MBEDTLS_DECRYPT. - * - * \returns 0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if - * parameter verification fails or a cipher specific - * error code. + * \param key_bitlen The key length to use, in bits. + * \param operation The operation that the key will be used for: + * #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key, int key_bitlen, const mbedtls_operation_t operation ); #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) /** - * \brief Set padding mode, for cipher modes that use padding. - * (Default: PKCS7 padding.) + * \brief This function sets the padding mode, for cipher modes + * that use padding. + * + * The default passing mode is PKCS7 padding. * - * \param ctx generic cipher context - * \param mode padding mode + * \param ctx The generic cipher context. + * \param mode The padding mode. * - * \returns 0 on success, MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE - * if selected padding mode is not supported, or - * MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE + * if the selected padding mode is not supported. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode * does not support padding. */ int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode ); #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */ /** - * \brief Set the initialization vector (IV) or nonce + * \brief This function sets the initialization vector (IV) + * or nonce. * - * \param ctx generic cipher context - * \param iv IV to use (or NONCE_COUNTER for CTR-mode ciphers) - * \param iv_len IV length for ciphers with variable-size IV; - * discarded by ciphers with fixed-size IV. + * \note Some ciphers do not use IVs nor nonce. For these + * ciphers, this function has no effect. * - * \returns 0 on success, or MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA + * \param ctx The generic cipher context. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size IV. * - * \note Some ciphers don't use IVs nor NONCE. For these - * ciphers, this function has no effect. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. */ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len ); /** - * \brief Finish preparation of the given context + * \brief This function resets the cipher state. * - * \param ctx generic cipher context + * \param ctx The generic cipher context. * - * \returns 0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA - * if parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. */ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ); -#if defined(MBEDTLS_GCM_C) +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) /** - * \brief Add additional data (for AEAD ciphers). - * Currently only supported with GCM. + * \brief This function adds additional data for AEAD ciphers. + * Currently supported with GCM and ChaCha20+Poly1305. * Must be called exactly once, after mbedtls_cipher_reset(). * - * \param ctx generic cipher context - * \param ad Additional data to use. - * \param ad_len Length of ad. + * \param ctx The generic cipher context. + * \param ad The additional data to use. + * \param ad_len the Length of \p ad. * - * \return 0 on success, or a specific error code. + * \return \c 0 on success. + * \return A specific error code on failure. */ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, const unsigned char *ad, size_t ad_len ); -#endif /* MBEDTLS_GCM_C */ - -/** - * \brief Generic cipher update function. Encrypts/decrypts - * using the given cipher context. Writes as many block - * size'd blocks of data as possible to output. Any data - * that cannot be written immediately will either be added - * to the next block, or flushed when cipher_final is - * called. - * Exception: for MBEDTLS_MODE_ECB, expects single block - * in size (e.g. 16 bytes for AES) - * - * \param ctx generic cipher context - * \param input buffer holding the input data - * \param ilen length of the input data - * \param output buffer for the output data. Should be able to hold at - * least ilen + block_size. Cannot be the same buffer as - * input! - * \param olen length of the output data, will be filled with the - * actual number of bytes written. - * - * \returns 0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if - * parameter verification fails, - * MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an - * unsupported mode for a cipher or a cipher specific - * error code. - * - * \note If the underlying cipher is GCM, all calls to this - * function, except the last one before mbedtls_cipher_finish(), - * must have ilen a multiple of the block size. +#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ + +/** + * \brief The generic cipher update function. It encrypts or + * decrypts using the given cipher context. Writes as + * many block-sized blocks of data as possible to output. + * Any data that cannot be written immediately is either + * added to the next block, or flushed when + * mbedtls_cipher_finish() is called. + * Exception: For MBEDTLS_MODE_ECB, expects a single block + * in size. For example, 16 Bytes for AES. + * + * \note If the underlying cipher is used in GCM mode, all calls + * to this function, except for the last one before + * mbedtls_cipher_finish(), must have \p ilen as a + * multiple of the block size of the cipher. + * + * \param ctx The generic cipher context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The buffer for the output data. Must be able to hold at + * least \p ilen + block_size. Must not be the same buffer + * as input. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an + * unsupported mode for a cipher. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen ); /** - * \brief Generic cipher finalisation function. If data still - * needs to be flushed from an incomplete block, data - * contained within it will be padded with the size of - * the last block, and written to the output buffer. - * - * \param ctx Generic cipher context - * \param output buffer to write data to. Needs block_size available. - * \param olen length of the data written to the output buffer. - * - * \returns 0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if - * parameter verification fails, - * MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption - * expected a full block but was not provided one, - * MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding - * while decrypting or a cipher specific error code. + * \brief The generic cipher finalization function. If data still + * needs to be flushed from an incomplete block, the data + * contained in it is padded to the size of + * the last block, and written to the \p output buffer. + * + * \param ctx The generic cipher context. + * \param output The buffer to write data to. Needs block_size available. + * \param olen The length of the data written to the \p output buffer. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption + * expecting a full block but not receiving one. + * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding + * while decrypting. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, unsigned char *output, size_t *olen ); -#if defined(MBEDTLS_GCM_C) +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) /** - * \brief Write tag for AEAD ciphers. - * Currently only supported with GCM. + * \brief This function writes a tag for AEAD ciphers. + * Currently supported with GCM and ChaCha20+Poly1305. * Must be called after mbedtls_cipher_finish(). * - * \param ctx Generic cipher context - * \param tag buffer to write the tag - * \param tag_len Length of the tag to write + * \param ctx The generic cipher context. + * \param tag The buffer to write the tag to. + * \param tag_len The length of the tag to write. * - * \return 0 on success, or a specific error code. + * \return \c 0 on success. + * \return A specific error code on failure. */ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, unsigned char *tag, size_t tag_len ); /** - * \brief Check tag for AEAD ciphers. - * Currently only supported with GCM. + * \brief This function checks the tag for AEAD ciphers. + * Currently supported with GCM and ChaCha20+Poly1305. * Must be called after mbedtls_cipher_finish(). * - * \param ctx Generic cipher context - * \param tag Buffer holding the tag - * \param tag_len Length of the tag to check + * \param ctx The generic cipher context. + * \param tag The buffer holding the tag. + * \param tag_len The length of the tag to check. * - * \return 0 on success, or a specific error code. + * \return \c 0 on success. + * \return A specific error code on failure. */ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, const unsigned char *tag, size_t tag_len ); -#endif /* MBEDTLS_GCM_C */ - -/** - * \brief Generic all-in-one encryption/decryption - * (for all ciphers except AEAD constructs). - * - * \param ctx generic cipher context - * \param iv IV to use (or NONCE_COUNTER for CTR-mode ciphers) - * \param iv_len IV length for ciphers with variable-size IV; - * discarded by ciphers with fixed-size IV. - * \param input buffer holding the input data - * \param ilen length of the input data - * \param output buffer for the output data. Should be able to hold at - * least ilen + block_size. Cannot be the same buffer as - * input! - * \param olen length of the output data, will be filled with the - * actual number of bytes written. - * - * \note Some ciphers don't use IVs nor NONCE. For these - * ciphers, use iv = NULL and iv_len = 0. - * - * \returns 0 on success, or - * MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or - * MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption - * expected a full block but was not provided one, or - * MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding - * while decrypting, or - * a cipher specific error code. +#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ + +/** + * \brief The generic all-in-one encryption/decryption function, + * for all ciphers except AEAD constructs. + * + * \param ctx The generic cipher context. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size + * IV. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The buffer for the output data. Must be able to hold at + * least \p ilen + block_size. Must not be the same buffer + * as input. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. + * + * \note Some ciphers do not use IVs nor nonce. For these + * ciphers, use \p iv = NULL and \p iv_len = 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption + * expecting a full block but not receiving one. + * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding + * while decrypting. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, @@ -639,26 +734,27 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, #if defined(MBEDTLS_CIPHER_MODE_AEAD) /** - * \brief Generic autenticated encryption (AEAD ciphers). - * - * \param ctx generic cipher context - * \param iv IV to use (or NONCE_COUNTER for CTR-mode ciphers) - * \param iv_len IV length for ciphers with variable-size IV; - * discarded by ciphers with fixed-size IV. - * \param ad Additional data to authenticate. - * \param ad_len Length of ad. - * \param input buffer holding the input data - * \param ilen length of the input data - * \param output buffer for the output data. - * Should be able to hold at least ilen. - * \param olen length of the output data, will be filled with the - * actual number of bytes written. - * \param tag buffer for the authentication tag - * \param tag_len desired tag length - * - * \returns 0 on success, or - * MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or - * a cipher specific error code. + * \brief The generic autenticated encryption (AEAD) function. + * + * \param ctx The generic cipher context. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size IV. + * \param ad The additional data to authenticate. + * \param ad_len The length of \p ad. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The buffer for the output data. + * Must be able to hold at least \p ilen. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. + * \param tag The buffer for the authentication tag. + * \param tag_len The desired length of the authentication tag. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, @@ -668,31 +764,32 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, unsigned char *tag, size_t tag_len ); /** - * \brief Generic autenticated decryption (AEAD ciphers). - * - * \param ctx generic cipher context - * \param iv IV to use (or NONCE_COUNTER for CTR-mode ciphers) - * \param iv_len IV length for ciphers with variable-size IV; - * discarded by ciphers with fixed-size IV. - * \param ad Additional data to be authenticated. - * \param ad_len Length of ad. - * \param input buffer holding the input data - * \param ilen length of the input data - * \param output buffer for the output data. - * Should be able to hold at least ilen. - * \param olen length of the output data, will be filled with the - * actual number of bytes written. - * \param tag buffer holding the authentication tag - * \param tag_len length of the authentication tag - * - * \returns 0 on success, or - * MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or - * MBEDTLS_ERR_CIPHER_AUTH_FAILED if data isn't authentic, - * or a cipher specific error code. + * \brief The generic autenticated decryption (AEAD) function. * * \note If the data is not authentic, then the output buffer - * is zeroed out to prevent the unauthentic plaintext to - * be used by mistake, making this interface safer. + * is zeroed out to prevent the unauthentic plaintext being + * used, making this interface safer. + * + * \param ctx The generic cipher context. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size IV. + * \param ad The additional data to be authenticated. + * \param ad_len The length of \p ad. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The buffer for the output data. + * Must be able to hold at least \p ilen. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. + * \param tag The buffer holding the authentication tag. + * \param tag_len The length of the authentication tag. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, diff --git a/tools/sdk/include/mbedtls/mbedtls/cipher_internal.h b/tools/sdk/include/mbedtls/mbedtls/cipher_internal.h index 6c58bcc5253..c6def0bef75 100644 --- a/tools/sdk/include/mbedtls/mbedtls/cipher_internal.h +++ b/tools/sdk/include/mbedtls/mbedtls/cipher_internal.h @@ -4,7 +4,8 @@ * \brief Cipher wrappers. * * \author Adriaan de Jong - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -63,6 +64,14 @@ struct mbedtls_cipher_base_t unsigned char *output ); #endif +#if defined(MBEDTLS_CIPHER_MODE_OFB) + /** Encrypt using OFB (Full length) */ + int (*ofb_func)( void *ctx, size_t length, size_t *iv_off, + unsigned char *iv, + const unsigned char *input, + unsigned char *output ); +#endif + #if defined(MBEDTLS_CIPHER_MODE_CTR) /** Encrypt using CTR */ int (*ctr_func)( void *ctx, size_t length, size_t *nc_off, @@ -70,6 +79,13 @@ struct mbedtls_cipher_base_t const unsigned char *input, unsigned char *output ); #endif +#if defined(MBEDTLS_CIPHER_MODE_XTS) + /** Encrypt or decrypt using XTS. */ + int (*xts_func)( void *ctx, mbedtls_operation_t mode, size_t length, + const unsigned char data_unit[16], + const unsigned char *input, unsigned char *output ); +#endif + #if defined(MBEDTLS_CIPHER_MODE_STREAM) /** Encrypt using STREAM */ int (*stream_func)( void *ctx, size_t length, diff --git a/tools/sdk/include/mbedtls/mbedtls/cmac.h b/tools/sdk/include/mbedtls/mbedtls/cmac.h index 9a2b96bc925..a4fd5525655 100644 --- a/tools/sdk/include/mbedtls/mbedtls/cmac.h +++ b/tools/sdk/include/mbedtls/mbedtls/cmac.h @@ -1,10 +1,13 @@ /** * \file cmac.h * - * \brief Cipher-based Message Authentication Code (CMAC) Mode for - * Authentication + * \brief This file contains CMAC definitions and functions. * - * Copyright (C) 2015-2016, ARM Limited, All Rights Reserved + * The Cipher-based Message Authentication Code (CMAC) Mode for + * Authentication is defined in RFC-4493: The AES-CMAC Algorithm. + */ +/* + * Copyright (C) 2015-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,117 +22,144 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_CMAC_H #define MBEDTLS_CMAC_H -#include "mbedtls/cipher.h" +#include "cipher.h" #ifdef __cplusplus extern "C" { #endif +#define MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED -0x007A /**< CMAC hardware accelerator failed. */ + #define MBEDTLS_AES_BLOCK_SIZE 16 #define MBEDTLS_DES3_BLOCK_SIZE 8 #if defined(MBEDTLS_AES_C) -#define MBEDTLS_CIPHER_BLKSIZE_MAX 16 /* longest used by CMAC is AES */ +#define MBEDTLS_CIPHER_BLKSIZE_MAX 16 /**< The longest block used by CMAC is that of AES. */ #else -#define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /* longest used by CMAC is 3DES */ +#define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /**< The longest block used by CMAC is that of 3DES. */ #endif +#if !defined(MBEDTLS_CMAC_ALT) + /** - * CMAC context structure - Contains internal state information only + * The CMAC context structure. */ struct mbedtls_cmac_context_t { - /** Internal state of the CMAC algorithm */ + /** The internal state of the CMAC algorithm. */ unsigned char state[MBEDTLS_CIPHER_BLKSIZE_MAX]; /** Unprocessed data - either data that was not block aligned and is still - * pending to be processed, or the final block */ + * pending processing, or the final block. */ unsigned char unprocessed_block[MBEDTLS_CIPHER_BLKSIZE_MAX]; - /** Length of data pending to be processed */ + /** The length of data pending processing. */ size_t unprocessed_len; }; +#else /* !MBEDTLS_CMAC_ALT */ +#include "cmac_alt.h" +#endif /* !MBEDTLS_CMAC_ALT */ + /** - * \brief Set the CMAC key and prepare to authenticate the input - * data. - * Should be called with an initialized cipher context. - * - * \param ctx Cipher context. This should be a cipher context, - * initialized to be one of the following types: - * MBEDTLS_CIPHER_AES_128_ECB, MBEDTLS_CIPHER_AES_192_ECB, - * MBEDTLS_CIPHER_AES_256_ECB or - * MBEDTLS_CIPHER_DES_EDE3_ECB. - * \param key CMAC key - * \param keybits length of the CMAC key in bits - * (must be acceptable by the cipher) - * - * \return 0 if successful, or a cipher specific error code + * \brief This function sets the CMAC key, and prepares to authenticate + * the input data. + * Must be called with an initialized cipher context. + * + * \param ctx The cipher context used for the CMAC operation, initialized + * as one of the following types: MBEDTLS_CIPHER_AES_128_ECB, + * MBEDTLS_CIPHER_AES_192_ECB, MBEDTLS_CIPHER_AES_256_ECB, + * or MBEDTLS_CIPHER_DES_EDE3_ECB. + * \param key The CMAC key. + * \param keybits The length of the CMAC key in bits. + * Must be supported by the cipher. + * + * \return \c 0 on success. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx, const unsigned char *key, size_t keybits ); /** - * \brief Generic CMAC process buffer. - * Called between mbedtls_cipher_cmac_starts() or - * mbedtls_cipher_cmac_reset() and - * mbedtls_cipher_cmac_finish(). - * May be called repeatedly. - * - * \param ctx CMAC context - * \param input buffer holding the data - * \param ilen length of the input data - * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \brief This function feeds an input buffer into an ongoing CMAC + * computation. + * + * It is called between mbedtls_cipher_cmac_starts() or + * mbedtls_cipher_cmac_reset(), and mbedtls_cipher_cmac_finish(). + * Can be called repeatedly. + * + * \param ctx The cipher context used for the CMAC operation. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. */ int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, size_t ilen ); /** - * \brief Output CMAC. - * Called after mbedtls_cipher_cmac_update(). - * Usually followed by mbedtls_cipher_cmac_reset(), then - * mbedtls_cipher_cmac_starts(), or mbedtls_cipher_free(). + * \brief This function finishes the CMAC operation, and writes + * the result to the output buffer. * - * \param ctx CMAC context - * \param output Generic CMAC checksum result + * It is called after mbedtls_cipher_cmac_update(). + * It can be followed by mbedtls_cipher_cmac_reset() and + * mbedtls_cipher_cmac_update(), or mbedtls_cipher_free(). * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \param ctx The cipher context used for the CMAC operation. + * \param output The output buffer for the CMAC checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. */ int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx, unsigned char *output ); /** - * \brief Prepare to authenticate a new message with the same key. - * Called after mbedtls_cipher_cmac_finish() and before - * mbedtls_cipher_cmac_update(). + * \brief This function prepares the authentication of another + * message with the same key as the previous CMAC + * operation. + * + * It is called after mbedtls_cipher_cmac_finish() + * and before mbedtls_cipher_cmac_update(). * - * \param ctx CMAC context to be reset + * \param ctx The cipher context used for the CMAC operation. * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. */ int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx ); /** - * \brief Output = Generic_CMAC( cmac key, input buffer ) + * \brief This function calculates the full generic CMAC + * on the input buffer with the provided key. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The CMAC result is calculated as + * output = generic CMAC(cmac key, input buffer). * - * \param cipher_info message digest info - * \param key CMAC key - * \param keylen length of the CMAC key in bits - * \param input buffer holding the data - * \param ilen length of the input data - * \param output Generic CMAC-result * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \param cipher_info The cipher information. + * \param key The CMAC key. + * \param keylen The length of the CMAC key in bits. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The buffer for the generic CMAC result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. */ int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info, const unsigned char *key, size_t keylen, @@ -138,16 +168,21 @@ int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info, #if defined(MBEDTLS_AES_C) /** - * \brief AES-CMAC-128-PRF - * Implementation of (AES-CMAC-PRF-128), as defined in RFC 4615 - * - * \param key PRF key - * \param key_len PRF key length in bytes - * \param input buffer holding the input data - * \param in_len length of the input data in bytes - * \param output buffer holding the generated pseudorandom output (16 bytes) - * - * \return 0 if successful + * \brief This function implements the AES-CMAC-PRF-128 pseudorandom + * function, as defined in + * RFC-4615: The Advanced Encryption Standard-Cipher-based + * Message Authentication Code-Pseudo-Random Function-128 + * (AES-CMAC-PRF-128) Algorithm for the Internet Key + * Exchange Protocol (IKE). + * + * \param key The key to use. + * \param key_len The key length in Bytes. + * \param input The buffer holding the input data. + * \param in_len The length of the input data in Bytes. + * \param output The buffer holding the generated 16 Bytes of + * pseudorandom output. + * + * \return \c 0 on success. */ int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len, const unsigned char *input, size_t in_len, @@ -156,9 +191,10 @@ int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len, #if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) ) /** - * \brief Checkup routine + * \brief The CMAC checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_cmac_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */ diff --git a/tools/sdk/include/mbedtls/mbedtls/compat-1.3.h b/tools/sdk/include/mbedtls/mbedtls/compat-1.3.h index bba1d2c247d..213b6914035 100644 --- a/tools/sdk/include/mbedtls/mbedtls/compat-1.3.h +++ b/tools/sdk/include/mbedtls/mbedtls/compat-1.3.h @@ -5,7 +5,8 @@ * for the PolarSSL naming conventions. * * \deprecated Use the new names directly instead - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -1377,7 +1378,8 @@ #define SSL_ANTI_REPLAY_ENABLED MBEDTLS_SSL_ANTI_REPLAY_ENABLED #define SSL_ARC4_DISABLED MBEDTLS_SSL_ARC4_DISABLED #define SSL_ARC4_ENABLED MBEDTLS_SSL_ARC4_ENABLED -#define SSL_BUFFER_LEN MBEDTLS_SSL_BUFFER_LEN +#define SSL_BUFFER_LEN ( ( ( MBEDTLS_SSL_IN_BUFFER_LEN ) < ( MBEDTLS_SSL_OUT_BUFFER_LEN ) ) \ + ? ( MBEDTLS_SSL_IN_BUFFER_LEN ) : ( MBEDTLS_SSL_OUT_BUFFER_LEN ) ) #define SSL_CACHE_DEFAULT_MAX_ENTRIES MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES #define SSL_CACHE_DEFAULT_TIMEOUT MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT #define SSL_CBC_RECORD_SPLITTING_DISABLED MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED diff --git a/tools/sdk/include/mbedtls/mbedtls/config.h b/tools/sdk/include/mbedtls/mbedtls/config.h index 47c7196402f..81438c5b1b9 100644 --- a/tools/sdk/include/mbedtls/mbedtls/config.h +++ b/tools/sdk/include/mbedtls/mbedtls/config.h @@ -6,8 +6,9 @@ * This set of compile-time options may be used to enable * or disable features selectively, and reduce the global * memory footprint. - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + */ +/* + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -47,10 +48,14 @@ * Requires support for asm() in compiler. * * Used in: + * library/aria.c * library/timing.c - * library/padlock.c * include/mbedtls/bn_mul.h * + * Required by: + * MBEDTLS_AESNI_C + * MBEDTLS_PADLOCK_C + * * Comment to disable the use of assembly code. */ #define MBEDTLS_HAVE_ASM @@ -83,6 +88,28 @@ */ //#define MBEDTLS_NO_UDBL_DIVISION +/** + * \def MBEDTLS_NO_64BIT_MULTIPLICATION + * + * The platform lacks support for 32x32 -> 64-bit multiplication. + * + * Used in: + * library/poly1305.c + * + * Some parts of the library may use multiplication of two unsigned 32-bit + * operands with a 64-bit result in order to speed up computations. On some + * platforms, this is not available in hardware and has to be implemented in + * software, usually in a library provided by the toolchain. + * + * Sometimes it is not desirable to have to link to that library. This option + * removes the dependency of that library on platforms that lack a hardware + * 64-bit multiplier by embedding a software implementation in Mbed TLS. + * + * Note that depending on the compiler, this may decrease performance compared + * to using the library function provided by the toolchain. + */ +//#define MBEDTLS_NO_64BIT_MULTIPLICATION + /** * \def MBEDTLS_HAVE_SSE2 * @@ -110,12 +137,21 @@ /** * \def MBEDTLS_HAVE_TIME_DATE * - * System has time.h and time(), gmtime() and the clock is correct. + * System has time.h, time(), and an implementation for + * mbedtls_platform_gmtime_r() (see below). * The time needs to be correct (not necesarily very accurate, but at least * the date should be correct). This is used to verify the validity period of * X.509 certificates. * * Comment if your system does not have a correct clock. + * + * \note mbedtls_platform_gmtime_r() is an abstraction in platform_util.h that + * behaves similarly to the gmtime_r() function from the C standard. Refer to + * the documentation for mbedtls_platform_gmtime_r() for more information. + * + * \note It is possible to configure an implementation for + * mbedtls_platform_gmtime_r() at compile-time by using the macro + * MBEDTLS_PLATFORM_GMTIME_R_ALT. */ #define MBEDTLS_HAVE_TIME_DATE @@ -261,20 +297,38 @@ * * Uncomment a macro to enable alternate implementation of the corresponding * module. + * + * \warning MD2, MD4, MD5, ARC4, DES and SHA-1 are considered weak and their + * use constitutes a security risk. If possible, we recommend + * avoiding dependencies on them, and considering stronger message + * digests and ciphers instead. + * */ //#define MBEDTLS_AES_ALT //#define MBEDTLS_ARC4_ALT +//#define MBEDTLS_ARIA_ALT //#define MBEDTLS_BLOWFISH_ALT //#define MBEDTLS_CAMELLIA_ALT +//#define MBEDTLS_CCM_ALT +//#define MBEDTLS_CHACHA20_ALT +//#define MBEDTLS_CHACHAPOLY_ALT +//#define MBEDTLS_CMAC_ALT //#define MBEDTLS_DES_ALT -//#define MBEDTLS_XTEA_ALT +//#define MBEDTLS_DHM_ALT +//#define MBEDTLS_ECJPAKE_ALT +//#define MBEDTLS_GCM_ALT +//#define MBEDTLS_NIST_KW_ALT //#define MBEDTLS_MD2_ALT //#define MBEDTLS_MD4_ALT //#define MBEDTLS_MD5_ALT +//#define MBEDTLS_POLY1305_ALT //#define MBEDTLS_RIPEMD160_ALT +//#define MBEDTLS_RSA_ALT //#define MBEDTLS_SHA1_ALT //#define MBEDTLS_SHA256_ALT //#define MBEDTLS_SHA512_ALT +//#define MBEDTLS_XTEA_ALT + /* * When replacing the elliptic curve module, pleace consider, that it is * implemented with two .c files: @@ -314,6 +368,12 @@ * * Uncomment a macro to enable alternate implementation of the corresponding * function. + * + * \warning MD2, MD4, MD5, DES and SHA-1 are considered weak and their use + * constitutes a security risk. If possible, we recommend avoiding + * dependencies on them, and considering stronger message digests + * and ciphers instead. + * */ //#define MBEDTLS_MD2_PROCESS_ALT //#define MBEDTLS_MD4_PROCESS_ALT @@ -329,6 +389,11 @@ //#define MBEDTLS_AES_SETKEY_DEC_ALT //#define MBEDTLS_AES_ENCRYPT_ALT //#define MBEDTLS_AES_DECRYPT_ALT +//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT +//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT +//#define MBEDTLS_ECDSA_VERIFY_ALT +//#define MBEDTLS_ECDSA_SIGN_ALT +//#define MBEDTLS_ECDSA_GENKEY_ALT /** * \def MBEDTLS_ECP_INTERNAL_ALT @@ -416,12 +481,45 @@ /** * \def MBEDTLS_AES_ROM_TABLES * - * Store the AES tables in ROM. + * Use precomputed AES tables stored in ROM. + * + * Uncomment this macro to use precomputed AES tables stored in ROM. + * Comment this macro to generate AES tables in RAM at runtime. + * + * Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb + * (or ~2kb if \c MBEDTLS_AES_FEWER_TABLES is used) and reduces the + * initialization time before the first AES operation can be performed. + * It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \c + * MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded + * performance if ROM access is slower than RAM access. + * + * This option is independent of \c MBEDTLS_AES_FEWER_TABLES. * - * Uncomment this macro to store the AES tables in ROM. */ //#define MBEDTLS_AES_ROM_TABLES +/** + * \def MBEDTLS_AES_FEWER_TABLES + * + * Use less ROM/RAM for AES tables. + * + * Uncommenting this macro omits 75% of the AES tables from + * ROM / RAM (depending on the value of \c MBEDTLS_AES_ROM_TABLES) + * by computing their values on the fly during operations + * (the tables are entry-wise rotations of one another). + * + * Tradeoff: Uncommenting this reduces the RAM / ROM footprint + * by ~6kb but at the cost of more arithmetic operations during + * runtime. Specifically, one has to compare 4 accesses within + * different tables to 4 accesses with additional arithmetic + * operations within the same table. The performance gain/loss + * depends on the system and memory details. + * + * This option is independent of \c MBEDTLS_AES_ROM_TABLES. + * + */ +//#define MBEDTLS_AES_FEWER_TABLES + /** * \def MBEDTLS_CAMELLIA_SMALL_MEMORY * @@ -452,6 +550,20 @@ */ #define MBEDTLS_CIPHER_MODE_CTR +/** + * \def MBEDTLS_CIPHER_MODE_OFB + * + * Enable Output Feedback mode (OFB) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_OFB + +/** + * \def MBEDTLS_CIPHER_MODE_XTS + * + * Enable Xor-encrypt-xor with ciphertext stealing mode (XTS) for AES. + */ +#define MBEDTLS_CIPHER_MODE_XTS + /** * \def MBEDTLS_CIPHER_NULL_CIPHER * @@ -513,6 +625,9 @@ * MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA * * Uncomment this macro to enable weak ciphersuites + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers instead. */ //#define MBEDTLS_ENABLE_WEAK_CIPHERSUITES @@ -549,6 +664,7 @@ #define MBEDTLS_ECP_DP_BP384R1_ENABLED #define MBEDTLS_ECP_DP_BP512R1_ENABLED #define MBEDTLS_ECP_DP_CURVE25519_ENABLED +#define MBEDTLS_ECP_DP_CURVE448_ENABLED /** * \def MBEDTLS_ECP_NIST_OPTIM @@ -618,6 +734,13 @@ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * */ #define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED @@ -717,6 +840,13 @@ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * */ #define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED @@ -1008,7 +1138,8 @@ /** * \def MBEDTLS_RSA_NO_CRT * - * Do not use the Chinese Remainder Theorem for the RSA private operation. + * Do not use the Chinese Remainder Theorem + * for the RSA private operation. * * Uncomment this macro to disable the use of CRT in RSA. * @@ -1052,6 +1183,17 @@ */ #define MBEDTLS_SSL_ALL_ALERT_MESSAGES +/** + * \def MBEDTLS_SSL_ASYNC_PRIVATE + * + * Enable asynchronous external private key operations in SSL. This allows + * you to configure an SSL connection to call an external cryptographic + * module to perform private key operations instead of performing the + * operation inside the library. + * + */ +//#define MBEDTLS_SSL_ASYNC_PRIVATE + /** * \def MBEDTLS_SSL_DEBUG_ALL * @@ -1155,6 +1297,13 @@ * misuse/misunderstand. * * Comment this to disable support for renegotiation. + * + * \note Even if this option is disabled, both client and server are aware + * of the Renegotiation Indication Extension (RFC 5746) used to + * prevent the SSL renegotiation attack (see RFC 5746 Sect. 1). + * (See \c mbedtls_ssl_conf_legacy_renegotiation for the + * configuration of this extension). + * */ #define MBEDTLS_SSL_RENEGOTIATION @@ -1363,6 +1512,30 @@ */ #define MBEDTLS_SSL_TRUNCATED_HMAC +/** + * \def MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT + * + * Fallback to old (pre-2.7), non-conforming implementation of the truncated + * HMAC extension which also truncates the HMAC key. Note that this option is + * only meant for a transitory upgrade period and is likely to be removed in + * a future version of the library. + * + * \warning The old implementation is non-compliant and has a security weakness + * (2^80 brute force attack on the HMAC key used for a single, + * uninterrupted connection). This should only be enabled temporarily + * when (1) the use of truncated HMAC is essential in order to save + * bandwidth, and (2) the peer is an Mbed TLS stack that doesn't use + * the fixed implementation yet (pre-2.7). + * + * \deprecated This option is deprecated and will likely be removed in a + * future version of Mbed TLS. + * + * Uncomment to fallback to old, non-compliant truncated HMAC implementation. + * + * Requires: MBEDTLS_SSL_TRUNCATED_HMAC + */ +//#define MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT + /** * \def MBEDTLS_THREADING_ALT * @@ -1469,6 +1642,9 @@ * * \note Currently compression can't be used with DTLS. * + * \deprecated This feature is deprecated and will be removed + * in the next major revision of the library. + * * Used in: library/ssl_tls.c * library/ssl_cli.c * library/ssl_srv.c @@ -1507,7 +1683,7 @@ * Enable the AES block cipher. * * Module: library/aes.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * library/pem.c * library/ctr_drbg.c * @@ -1582,7 +1758,7 @@ * Enable the ARCFOUR stream cipher. * * Module: library/arc4.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -1596,6 +1772,11 @@ * MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 * MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA * MBEDTLS_TLS_PSK_WITH_RC4_128_SHA + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. If possible, we recommend avoidng dependencies on + * it, and considering stronger ciphers instead. + * */ #define MBEDTLS_ARC4_C @@ -1649,6 +1830,7 @@ * library/ecp.c * library/ecdsa.c * library/rsa.c + * library/rsa_internal.c * library/ssl_tls.c * * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support. @@ -1670,7 +1852,7 @@ * Enable the Camellia block cipher. * * Module: library/camellia.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -1719,6 +1901,58 @@ */ #define MBEDTLS_CAMELLIA_C +/** + * \def MBEDTLS_ARIA_C + * + * Enable the ARIA block cipher. + * + * Module: library/aria.c + * Caller: library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * + * MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 + */ +//#define MBEDTLS_ARIA_C + /** * \def MBEDTLS_CCM_C * @@ -1745,6 +1979,26 @@ */ #define MBEDTLS_CERTS_C +/** + * \def MBEDTLS_CHACHA20_C + * + * Enable the ChaCha20 stream cipher. + * + * Module: library/chacha20.c + */ +#define MBEDTLS_CHACHA20_C + +/** + * \def MBEDTLS_CHACHAPOLY_C + * + * Enable the ChaCha20-Poly1305 AEAD algorithm. + * + * Module: library/chachapoly.c + * + * This module requires: MBEDTLS_CHACHA20_C, MBEDTLS_POLY1305_C + */ +#define MBEDTLS_CHACHAPOLY_C + /** * \def MBEDTLS_CIPHER_C * @@ -1805,7 +2059,7 @@ * * Module: library/des.c * Caller: library/pem.c - * library/ssl_tls.c + * library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -1821,6 +2075,9 @@ * MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA * * PEM_PARSE uses DES/3DES for decrypting encrypted keys. + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers instead. */ #define MBEDTLS_DES_C @@ -1835,6 +2092,13 @@ * * This module is used by the following key exchanges: * DHE-RSA, DHE-PSK + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * */ #define MBEDTLS_DHM_C @@ -1965,6 +2229,21 @@ */ //#define MBEDTLS_HAVEGE_C +/** + * \def MBEDTLS_HKDF_C + * + * Enable the HKDF algorithm (RFC 5869). + * + * Module: library/hkdf.c + * Caller: + * + * Requires: MBEDTLS_MD_C + * + * This module adds support for the Hashed Message Authentication Code + * (HMAC)-based key derivation function (HKDF). + */ +#define MBEDTLS_HKDF_C + /** * \def MBEDTLS_HMAC_DRBG_C * @@ -1979,6 +2258,19 @@ */ #define MBEDTLS_HMAC_DRBG_C +/** + * \def MBEDTLS_NIST_KW_C + * + * Enable the Key Wrapping mode for 128-bit block ciphers, + * as defined in NIST SP 800-38F. Only KW and KWP modes + * are supported. At the moment, only AES is approved by NIST. + * + * Module: library/nist_kw.c + * + * Requires: MBEDTLS_AES_C and MBEDTLS_CIPHER_C + */ +//#define MBEDTLS_NIST_KW_C + /** * \def MBEDTLS_MD_C * @@ -2000,6 +2292,11 @@ * Caller: * * Uncomment to enable support for (rare) MD2-signed X.509 certs. + * + * \warning MD2 is considered a weak message digest and its use constitutes a + * security risk. If possible, we recommend avoiding dependencies on + * it, and considering stronger message digests instead. + * */ //#define MBEDTLS_MD2_C @@ -2012,6 +2309,11 @@ * Caller: * * Uncomment to enable support for (rare) MD4-signed X.509 certs. + * + * \warning MD4 is considered a weak message digest and its use constitutes a + * security risk. If possible, we recommend avoiding dependencies on + * it, and considering stronger message digests instead. + * */ //#define MBEDTLS_MD4_C @@ -2025,8 +2327,15 @@ * library/pem.c * library/ssl_tls.c * - * This module is required for SSL/TLS and X.509. - * PEM_PARSE uses MD5 for decrypting encrypted keys. + * This module is required for SSL/TLS up to version 1.1, and for TLS 1.2 + * depending on the handshake parameters. Further, it is used for checking + * MD5-signed certificates, and for PBKDF1 when decrypting PEM-encoded + * encrypted keys. + * + * \warning MD5 is considered a weak message digest and its use constitutes a + * security risk. If possible, we recommend avoiding dependencies on + * it, and considering stronger message digests instead. + * */ #define MBEDTLS_MD5_C @@ -2245,6 +2554,16 @@ */ #define MBEDTLS_PLATFORM_C +/** + * \def MBEDTLS_POLY1305_C + * + * Enable the Poly1305 MAC algorithm. + * + * Module: library/poly1305.c + * Caller: library/chachapoly.c + */ +#define MBEDTLS_POLY1305_C + /** * \def MBEDTLS_RIPEMD160_C * @@ -2262,6 +2581,7 @@ * Enable the RSA public-key cryptosystem. * * Module: library/rsa.c + * library/rsa_internal.c * Caller: library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c @@ -2288,6 +2608,11 @@ * * This module is required for SSL/TLS up to version 1.1, for TLS 1.2 * depending on the handshake parameters, and for SHA1-signed certificates. + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. If possible, we recommend avoiding dependencies + * on it, and considering stronger message digests instead. + * */ #define MBEDTLS_SHA1_C @@ -2649,7 +2974,68 @@ //#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */ /* SSL options */ -//#define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 /**< Maxium fragment length in bytes, determines the size of each of the two internal I/O buffers */ + +/** \def MBEDTLS_SSL_MAX_CONTENT_LEN + * + * Maximum fragment length in bytes. + * + * Determines the size of both the incoming and outgoing TLS I/O buffers. + * + * Uncommenting MBEDTLS_SSL_IN_CONTENT_LEN and/or MBEDTLS_SSL_OUT_CONTENT_LEN + * will override this length by setting maximum incoming and/or outgoing + * fragment length, respectively. + */ +//#define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_IN_CONTENT_LEN + * + * Maximum incoming fragment length in bytes. + * + * Uncomment to set the size of the inward TLS buffer independently of the + * outward buffer. + */ +//#define MBEDTLS_SSL_IN_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_OUT_CONTENT_LEN + * + * Maximum outgoing fragment length in bytes. + * + * Uncomment to set the size of the outward TLS buffer independently of the + * inward buffer. + * + * It is possible to save RAM by setting a smaller outward buffer, while keeping + * the default inward 16384 byte buffer to conform to the TLS specification. + * + * The minimum required outward buffer size is determined by the handshake + * protocol's usage. Handshaking will fail if the outward buffer is too small. + * The specific size requirement depends on the configured ciphers and any + * certificate data which is sent during the handshake. + * + * For absolute minimum RAM usage, it's best to enable + * MBEDTLS_SSL_MAX_FRAGMENT_LENGTH and reduce MBEDTLS_SSL_MAX_CONTENT_LEN. This + * reduces both incoming and outgoing buffer sizes. However this is only + * guaranteed if the other end of the connection also supports the TLS + * max_fragment_len extension. Otherwise the connection may fail. + */ +//#define MBEDTLS_SSL_OUT_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_DTLS_MAX_BUFFERING + * + * Maximum number of heap-allocated bytes for the purpose of + * DTLS handshake message reassembly and future message buffering. + * + * This should be at least 9/8 * MBEDTLSSL_IN_CONTENT_LEN + * to account for a reassembled handshake message of maximum size, + * together with its reassembly bitmap. + * + * A value of 2 * MBEDTLS_SSL_IN_CONTENT_LEN (32768 by default) + * should be sufficient for all practical situations as it allows + * to reassembly a large handshake message (such as a certificate) + * while buffering multiple smaller handshake messages. + * + */ +//#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768 + //#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME 86400 /**< Lifetime of session tickets (if enabled) */ //#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */ //#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ @@ -2676,8 +3062,13 @@ * Allow SHA-1 in the default TLS configuration for certificate signing. * Without this build-time option, SHA-1 support must be activated explicitly * through mbedtls_ssl_conf_cert_profile. Turning on this option is not - * recommended because of it is possible to generte SHA-1 collisions, however + * recommended because of it is possible to generate SHA-1 collisions, however * this may be safe for legacy infrastructure where additional controls apply. + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. If possible, we recommend avoiding dependencies + * on it, and considering stronger message digests instead. + * */ // #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES @@ -2688,14 +3079,59 @@ * The use of SHA-1 in TLS <= 1.1 and in HMAC-SHA-1 is always allowed by * default. At the time of writing, there is no practical attack on the use * of SHA-1 in handshake signatures, hence this option is turned on by default - * for compatibility with existing peers. + * to preserve compatibility with existing peers, but the general + * warning applies nonetheless: + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. If possible, we recommend avoiding dependencies + * on it, and considering stronger message digests instead. + * */ #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE +/** + * Uncomment the macro to let mbed TLS use your alternate implementation of + * mbedtls_platform_zeroize(). This replaces the default implementation in + * platform_util.c. + * + * mbedtls_platform_zeroize() is a widely used function across the library to + * zero a block of memory. The implementation is expected to be secure in the + * sense that it has been written to prevent the compiler from removing calls + * to mbedtls_platform_zeroize() as part of redundant code elimination + * optimizations. However, it is difficult to guarantee that calls to + * mbedtls_platform_zeroize() will not be optimized by the compiler as older + * versions of the C language standards do not provide a secure implementation + * of memset(). Therefore, MBEDTLS_PLATFORM_ZEROIZE_ALT enables users to + * configure their own implementation of mbedtls_platform_zeroize(), for + * example by using directives specific to their compiler, features from newer + * C standards (e.g using memset_s() in C11) or calling a secure memset() from + * their system (e.g explicit_bzero() in BSD). + */ +//#define MBEDTLS_PLATFORM_ZEROIZE_ALT + +/** + * Uncomment the macro to let Mbed TLS use your alternate implementation of + * mbedtls_platform_gmtime_r(). This replaces the default implementation in + * platform_util.c. + * + * gmtime() is not a thread-safe function as defined in the C standard. The + * library will try to use safer implementations of this function, such as + * gmtime_r() when available. However, if Mbed TLS cannot identify the target + * system, the implementation of mbedtls_platform_gmtime_r() will default to + * using the standard gmtime(). In this case, calls from the library to + * gmtime() will be guarded by the global mutex mbedtls_threading_gmtime_mutex + * if MBEDTLS_THREADING_C is enabled. We recommend that calls from outside the + * library are also guarded with this mutex to avoid race conditions. However, + * if the macro MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, Mbed TLS will + * unconditionally use the implementation for mbedtls_platform_gmtime_r() + * supplied at compile time. + */ +//#define MBEDTLS_PLATFORM_GMTIME_R_ALT + /* \} name SECTION: Customisation configuration options */ /* Target and application specific configurations */ -//#define YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE "mbedtls/target_config.h" +//#define YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE "target_config.h" #if defined(TARGET_LIKE_MBED) && defined(YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE) #include YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE diff --git a/tools/sdk/include/mbedtls/mbedtls/ctr_drbg.h b/tools/sdk/include/mbedtls/mbedtls/ctr_drbg.h index 059d3c5c9af..3a4b7f3f13d 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ctr_drbg.h +++ b/tools/sdk/include/mbedtls/mbedtls/ctr_drbg.h @@ -1,9 +1,18 @@ /** * \file ctr_drbg.h * - * \brief CTR_DRBG based on AES-256 (NIST SP 800-90) + * \brief This file contains CTR_DRBG definitions and functions. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * CTR_DRBG is a standardized way of building a PRNG from a block-cipher + * in counter mode operation, as defined in NIST SP 800-90A: + * Recommendation for Random Number Generation Using Deterministic Random + * Bit Generators. + * + * The Mbed TLS implementation of CTR_DRBG uses AES-256 as the underlying + * block cipher. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,90 +27,108 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_CTR_DRBG_H #define MBEDTLS_CTR_DRBG_H #include "aes.h" #if defined(MBEDTLS_THREADING_C) -#include "mbedtls/threading.h" +#include "threading.h" #endif #define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED -0x0034 /**< The entropy source failed. */ -#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG -0x0036 /**< Too many random requested in single call. */ -#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG -0x0038 /**< Input too large (Entropy + additional). */ -#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR -0x003A /**< Read/write error in file. */ +#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG -0x0036 /**< The requested random buffer length is too big. */ +#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG -0x0038 /**< The input (entropy + additional data) is too large. */ +#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR -0x003A /**< Read or write error in file. */ -#define MBEDTLS_CTR_DRBG_BLOCKSIZE 16 /**< Block size used by the cipher */ -#define MBEDTLS_CTR_DRBG_KEYSIZE 32 /**< Key size used by the cipher */ -#define MBEDTLS_CTR_DRBG_KEYBITS ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) -#define MBEDTLS_CTR_DRBG_SEEDLEN ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE ) - /**< The seed length (counter + AES key) */ +#define MBEDTLS_CTR_DRBG_BLOCKSIZE 16 /**< The block size used by the cipher. */ +#define MBEDTLS_CTR_DRBG_KEYSIZE 32 /**< The key size used by the cipher. */ +#define MBEDTLS_CTR_DRBG_KEYBITS ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) /**< The key size for the DRBG operation, in bits. */ +#define MBEDTLS_CTR_DRBG_SEEDLEN ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE ) /**< The seed length, calculated as (counter + AES key). */ /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. - * Either change them in config.h or define them on the compiler command line. + * Either change them in config.h or define them using the compiler command + * line. * \{ */ #if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) -#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */ +#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 +/**< The amount of entropy used per seed by default: + *
  • 48 with SHA-512.
  • + *
  • 32 with SHA-256.
+ */ #else -#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 32 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */ +#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 32 +/**< Amount of entropy used per seed by default: + *
  • 48 with SHA-512.
  • + *
  • 32 with SHA-256.
+ */ #endif #endif #if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL) -#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ +#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 +/**< The interval before reseed is performed by default. */ #endif #if !defined(MBEDTLS_CTR_DRBG_MAX_INPUT) -#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ +#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 +/**< The maximum number of additional input Bytes. */ #endif #if !defined(MBEDTLS_CTR_DRBG_MAX_REQUEST) -#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ +#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 +/**< The maximum number of requested Bytes per call. */ #endif #if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT) -#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ +#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 +/**< The maximum size of seed or reseed buffer. */ #endif /* \} name SECTION: Module settings */ -#define MBEDTLS_CTR_DRBG_PR_OFF 0 /**< No prediction resistance */ -#define MBEDTLS_CTR_DRBG_PR_ON 1 /**< Prediction resistance enabled */ +#define MBEDTLS_CTR_DRBG_PR_OFF 0 +/**< Prediction resistance is disabled. */ +#define MBEDTLS_CTR_DRBG_PR_ON 1 +/**< Prediction resistance is enabled. */ #ifdef __cplusplus extern "C" { #endif /** - * \brief CTR_DRBG context structure + * \brief The CTR_DRBG context structure. */ -typedef struct +typedef struct mbedtls_ctr_drbg_context { - unsigned char counter[16]; /*!< counter (V) */ - int reseed_counter; /*!< reseed counter */ - int prediction_resistance; /*!< enable prediction resistance (Automatic - reseed before every random generation) */ - size_t entropy_len; /*!< amount of entropy grabbed on each - (re)seed */ - int reseed_interval; /*!< reseed interval */ - - mbedtls_aes_context aes_ctx; /*!< AES context */ + unsigned char counter[16]; /*!< The counter (V). */ + int reseed_counter; /*!< The reseed counter. */ + int prediction_resistance; /*!< This determines whether prediction + resistance is enabled, that is + whether to systematically reseed before + each random generation. */ + size_t entropy_len; /*!< The amount of entropy grabbed on each + seed or reseed operation. */ + int reseed_interval; /*!< The reseed interval. */ + + mbedtls_aes_context aes_ctx; /*!< The AES context. */ /* * Callbacks (Entropy) */ int (*f_entropy)(void *, unsigned char *, size_t); + /*!< The entropy callback function. */ - void *p_entropy; /*!< context for the entropy function */ + void *p_entropy; /*!< The context for the entropy function. */ #if defined(MBEDTLS_THREADING_C) mbedtls_threading_mutex_t mutex; @@ -110,31 +137,32 @@ typedef struct mbedtls_ctr_drbg_context; /** - * \brief CTR_DRBG context initialization - * Makes the context ready for mbedtls_ctr_drbg_seed() or - * mbedtls_ctr_drbg_free(). + * \brief This function initializes the CTR_DRBG context, + * and prepares it for mbedtls_ctr_drbg_seed() + * or mbedtls_ctr_drbg_free(). * - * \param ctx CTR_DRBG context to be initialized + * \param ctx The CTR_DRBG context to initialize. */ void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx ); /** - * \brief CTR_DRBG initial seeding - * Seed and setup entropy source for future reseeds. - * - * Note: Personalization data can be provided in addition to the more generic - * entropy source to make this instantiation as unique as possible. - * - * \param ctx CTR_DRBG context to be seeded - * \param f_entropy Entropy callback (p_entropy, buffer to fill, buffer - * length) - * \param p_entropy Entropy context - * \param custom Personalization data (Device specific identifiers) - * (Can be NULL) - * \param len Length of personalization data - * - * \return 0 if successful, or - * MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED + * \brief This function seeds and sets up the CTR_DRBG + * entropy source for future reseeds. + * + * \note Personalization data can be provided in addition to the more generic + * entropy source, to make this instantiation as unique as possible. + * + * \param ctx The CTR_DRBG context to seed. + * \param f_entropy The entropy callback, taking as arguments the + * \p p_entropy context, the buffer to fill, and the + length of the buffer. + * \param p_entropy The entropy context. + * \param custom Personalization data, that is device-specific + identifiers. Can be NULL. + * \param len The length of the personalization data. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure. */ int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx, int (*f_entropy)(void *, unsigned char *, size_t), @@ -143,138 +171,150 @@ int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx, size_t len ); /** - * \brief Clear CTR_CRBG context data + * \brief This function clears CTR_CRBG context data. * - * \param ctx CTR_DRBG context to clear + * \param ctx The CTR_DRBG context to clear. */ void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx ); /** - * \brief Enable / disable prediction resistance (Default: Off) + * \brief This function turns prediction resistance on or off. + * The default value is off. * - * Note: If enabled, entropy is used for ctx->entropy_len before each call! - * Only use this if you have ample supply of good entropy! + * \note If enabled, entropy is gathered at the beginning of + * every call to mbedtls_ctr_drbg_random_with_add(). + * Only use this if your entropy source has sufficient + * throughput. * - * \param ctx CTR_DRBG context - * \param resistance MBEDTLS_CTR_DRBG_PR_ON or MBEDTLS_CTR_DRBG_PR_OFF + * \param ctx The CTR_DRBG context. + * \param resistance #MBEDTLS_CTR_DRBG_PR_ON or #MBEDTLS_CTR_DRBG_PR_OFF. */ void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx, int resistance ); /** - * \brief Set the amount of entropy grabbed on each (re)seed - * (Default: MBEDTLS_CTR_DRBG_ENTROPY_LEN) + * \brief This function sets the amount of entropy grabbed on each + * seed or reseed. The default value is + * #MBEDTLS_CTR_DRBG_ENTROPY_LEN. * - * \param ctx CTR_DRBG context - * \param len Amount of entropy to grab + * \param ctx The CTR_DRBG context. + * \param len The amount of entropy to grab. */ void mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx, size_t len ); /** - * \brief Set the reseed interval - * (Default: MBEDTLS_CTR_DRBG_RESEED_INTERVAL) + * \brief This function sets the reseed interval. + * The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL. * - * \param ctx CTR_DRBG context - * \param interval Reseed interval + * \param ctx The CTR_DRBG context. + * \param interval The reseed interval. */ void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx, int interval ); /** - * \brief CTR_DRBG reseeding (extracts data from entropy source) + * \brief This function reseeds the CTR_DRBG context, that is + * extracts data from the entropy source. * - * \param ctx CTR_DRBG context - * \param additional Additional data to add to state (Can be NULL) - * \param len Length of additional data + * \param ctx The CTR_DRBG context. + * \param additional Additional data to add to the state. Can be NULL. + * \param len The length of the additional data. * - * \return 0 if successful, or - * MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure. */ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx, const unsigned char *additional, size_t len ); /** - * \brief CTR_DRBG update state + * \brief This function updates the state of the CTR_DRBG context. + * + * \note If \p add_len is greater than + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT, only the first + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT Bytes are used. + * The remaining Bytes are silently discarded. * - * \param ctx CTR_DRBG context - * \param additional Additional data to update state with - * \param add_len Length of additional data + * \param ctx The CTR_DRBG context. + * \param additional The data to update the state with. + * \param add_len Length of \p additional data. * - * \note If add_len is greater than MBEDTLS_CTR_DRBG_MAX_SEED_INPUT, - * only the first MBEDTLS_CTR_DRBG_MAX_SEED_INPUT bytes are used, - * the remaining ones are silently discarded. */ void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx, const unsigned char *additional, size_t add_len ); /** - * \brief CTR_DRBG generate random with additional update input + * \brief This function updates a CTR_DRBG instance with additional + * data and uses it to generate random data. * - * Note: Automatically reseeds if reseed_counter is reached. + * \note The function automatically reseeds if the reseed counter is exceeded. * - * \param p_rng CTR_DRBG context - * \param output Buffer to fill - * \param output_len Length of the buffer - * \param additional Additional data to update with (Can be NULL) - * \param add_len Length of additional data + * \param p_rng The CTR_DRBG context. This must be a pointer to a + * #mbedtls_ctr_drbg_context structure. + * \param output The buffer to fill. + * \param output_len The length of the buffer. + * \param additional Additional data to update. Can be NULL. + * \param add_len The length of the additional data. * - * \return 0 if successful, or - * MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or - * MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or + * #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure. */ int mbedtls_ctr_drbg_random_with_add( void *p_rng, unsigned char *output, size_t output_len, const unsigned char *additional, size_t add_len ); /** - * \brief CTR_DRBG generate random + * \brief This function uses CTR_DRBG to generate random data. * - * Note: Automatically reseeds if reseed_counter is reached. + * \note The function automatically reseeds if the reseed counter is exceeded. * - * \param p_rng CTR_DRBG context - * \param output Buffer to fill - * \param output_len Length of the buffer + * \param p_rng The CTR_DRBG context. This must be a pointer to a + * #mbedtls_ctr_drbg_context structure. + * \param output The buffer to fill. + * \param output_len The length of the buffer. * - * \return 0 if successful, or - * MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or - * MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or + * #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure. */ int mbedtls_ctr_drbg_random( void *p_rng, unsigned char *output, size_t output_len ); #if defined(MBEDTLS_FS_IO) /** - * \brief Write a seed file + * \brief This function writes a seed file. * - * \param ctx CTR_DRBG context - * \param path Name of the file + * \param ctx The CTR_DRBG context. + * \param path The name of the file. * - * \return 0 if successful, - * MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, or - * MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on + * failure. */ int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path ); /** - * \brief Read and update a seed file. Seed is added to this - * instance + * \brief This function reads and updates a seed file. The seed + * is added to this instance. * - * \param ctx CTR_DRBG context - * \param path Name of the file + * \param ctx The CTR_DRBG context. + * \param path The name of the file. * - * \return 0 if successful, - * MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, - * MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or - * MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or + * #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG on failure. */ int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path ); #endif /* MBEDTLS_FS_IO */ /** - * \brief Checkup routine + * \brief The CTR_DRBG checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_ctr_drbg_self_test( int verbose ); diff --git a/tools/sdk/include/mbedtls/mbedtls/debug.h b/tools/sdk/include/mbedtls/mbedtls/debug.h index 29579964076..ef8db67ff11 100644 --- a/tools/sdk/include/mbedtls/mbedtls/debug.h +++ b/tools/sdk/include/mbedtls/mbedtls/debug.h @@ -2,7 +2,8 @@ * \file debug.h * * \brief Functions for controlling and providing debug output from the library. - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/des.h b/tools/sdk/include/mbedtls/mbedtls/des.h index 5ca2ecf2e09..91d16b6fb48 100644 --- a/tools/sdk/include/mbedtls/mbedtls/des.h +++ b/tools/sdk/include/mbedtls/mbedtls/des.h @@ -3,6 +3,11 @@ * * \brief DES block cipher * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -19,6 +24,7 @@ * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) + * */ #ifndef MBEDTLS_DES_H #define MBEDTLS_DES_H @@ -36,21 +42,26 @@ #define MBEDTLS_DES_DECRYPT 0 #define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH -0x0032 /**< The data input has an invalid length. */ +#define MBEDTLS_ERR_DES_HW_ACCEL_FAILED -0x0033 /**< DES hardware accelerator failed. */ #define MBEDTLS_DES_KEY_SIZE 8 -#if !defined(MBEDTLS_DES_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_DES_ALT) +// Regular implementation +// + /** * \brief DES context structure + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ -typedef struct +typedef struct mbedtls_des_context { uint32_t sk[32]; /*!< DES subkeys */ } @@ -59,16 +70,24 @@ mbedtls_des_context; /** * \brief Triple-DES context structure */ -typedef struct +typedef struct mbedtls_des3_context { uint32_t sk[96]; /*!< 3DES subkeys */ } mbedtls_des3_context; +#else /* MBEDTLS_DES_ALT */ +#include "des_alt.h" +#endif /* MBEDTLS_DES_ALT */ + /** * \brief Initialize DES context * * \param ctx DES context to be initialized + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ void mbedtls_des_init( mbedtls_des_context *ctx ); @@ -76,6 +95,10 @@ void mbedtls_des_init( mbedtls_des_context *ctx ); * \brief Clear DES context * * \param ctx DES context to be cleared + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ void mbedtls_des_free( mbedtls_des_context *ctx ); @@ -100,6 +123,10 @@ void mbedtls_des3_free( mbedtls_des3_context *ctx ); * a parity bit to allow verification. * * \param key 8-byte secret key + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] ); @@ -112,6 +139,10 @@ void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] ); * \param key 8-byte secret key * * \return 0 is parity was ok, 1 if parity was not correct. + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); @@ -121,6 +152,10 @@ int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SI * \param key 8-byte secret key * * \return 0 if no weak key was found, 1 if a weak key was identified. + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); @@ -131,6 +166,10 @@ int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); * \param key 8-byte secret key * * \return 0 + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); @@ -141,6 +180,10 @@ int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MB * \param key 8-byte secret key * * \return 0 + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); @@ -196,6 +239,10 @@ int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx, * \param output 64-bit output block * * \return 0 if successful + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx, const unsigned char input[8], @@ -219,6 +266,10 @@ int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx, * \param iv initialization vector (updated after use) * \param input buffer holding the input data * \param output buffer holding the output data + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx, int mode, @@ -277,20 +328,13 @@ int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx, * * \param SK Round keys * \param key Base key + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. */ void mbedtls_des_setkey( uint32_t SK[32], const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_DES_ALT */ -#include "des_alt.h" -#endif /* MBEDTLS_DES_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif /** * \brief Checkup routine diff --git a/tools/sdk/include/mbedtls/mbedtls/dhm.h b/tools/sdk/include/mbedtls/mbedtls/dhm.h index d7ab1522ec1..3e1178940a4 100644 --- a/tools/sdk/include/mbedtls/mbedtls/dhm.h +++ b/tools/sdk/include/mbedtls/mbedtls/dhm.h @@ -1,9 +1,50 @@ /** * \file dhm.h * - * \brief Diffie-Hellman-Merkle key exchange + * \brief This file contains Diffie-Hellman-Merkle (DHM) key exchange + * definitions and functions. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Diffie-Hellman-Merkle (DHM) key exchange is defined in + * RFC-2631: Diffie-Hellman Key Agreement Method and + * Public-Key Cryptography Standards (PKCS) #3: Diffie + * Hellman Key Agreement Standard. + * + * RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for + * Internet Key Exchange (IKE) defines a number of standardized + * Diffie-Hellman groups for IKE. + * + * RFC-5114: Additional Diffie-Hellman Groups for Use with IETF + * Standards defines a number of standardized Diffie-Hellman + * groups that can be used. + * + * \warning The security of the DHM key exchange relies on the proper choice + * of prime modulus - optimally, it should be a safe prime. The usage + * of non-safe primes both decreases the difficulty of the underlying + * discrete logarithm problem and can lead to small subgroup attacks + * leaking private exponent bits when invalid public keys are used + * and not detected. This is especially relevant if the same DHM + * parameters are reused for multiple key exchanges as in static DHM, + * while the criticality of small-subgroup attacks is lower for + * ephemeral DHM. + * + * \warning For performance reasons, the code does neither perform primality + * nor safe primality tests, nor the expensive checks for invalid + * subgroups. Moreover, even if these were performed, non-standardized + * primes cannot be trusted because of the possibility of backdoors + * that can't be effectively checked for. + * + * \warning Diffie-Hellman-Merkle is therefore a security risk when not using + * standardized primes generated using a trustworthy ("nothing up + * my sleeve") method, such as the RFC 3526 / 7919 primes. In the TLS + * protocol, DH parameters need to be negotiated, so using the default + * primes systematically is not always an option. If possible, use + * Elliptic Curve Diffie-Hellman (ECDH), which has better performance, + * and for which the TLS protocol mandates the use of standard + * parameters. + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,17 +59,23 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_DHM_H #define MBEDTLS_DHM_H +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif #include "bignum.h" /* * DHM Error codes */ -#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA -0x3080 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA -0x3080 /**< Bad input parameters. */ #define MBEDTLS_ERR_DHM_READ_PARAMS_FAILED -0x3100 /**< Reading of the DHM parameters failed. */ #define MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED -0x3180 /**< Making of the DHM parameters failed. */ #define MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED -0x3200 /**< Reading of the public values failed. */ @@ -36,167 +83,91 @@ #define MBEDTLS_ERR_DHM_CALC_SECRET_FAILED -0x3300 /**< Calculation of the DHM secret failed. */ #define MBEDTLS_ERR_DHM_INVALID_FORMAT -0x3380 /**< The ASN.1 data is not formatted correctly. */ #define MBEDTLS_ERR_DHM_ALLOC_FAILED -0x3400 /**< Allocation of memory failed. */ -#define MBEDTLS_ERR_DHM_FILE_IO_ERROR -0x3480 /**< Read/write of file failed. */ - -/** - * RFC 3526 defines a number of standardized Diffie-Hellman groups - * for IKE. - * RFC 5114 defines a number of standardized Diffie-Hellman groups - * that can be used. - * - * Some are included here for convenience. - * - * Included are: - * RFC 3526 3. 2048-bit MODP Group - * RFC 3526 4. 3072-bit MODP Group - * RFC 3526 5. 4096-bit MODP Group - * RFC 5114 2.2. 2048-bit MODP Group with 224-bit Prime Order Subgroup - */ -#define MBEDTLS_DHM_RFC3526_MODP_2048_P \ - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ - "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ - "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ - "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ - "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ - "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ - "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ - "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ - "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ - "15728E5A8AACAA68FFFFFFFFFFFFFFFF" - -#define MBEDTLS_DHM_RFC3526_MODP_2048_G "02" - -#define MBEDTLS_DHM_RFC3526_MODP_3072_P \ - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ - "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ - "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ - "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ - "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ - "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ - "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ - "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ - "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ - "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ - "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ - "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ - "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ - "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" - -#define MBEDTLS_DHM_RFC3526_MODP_3072_G "02" - -#define MBEDTLS_DHM_RFC3526_MODP_4096_P \ - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ - "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ - "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ - "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ - "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ - "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ - "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ - "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ - "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ - "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ - "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ - "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ - "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ - "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ - "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ - "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ - "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ - "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ - "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \ - "FFFFFFFFFFFFFFFF" - -#define MBEDTLS_DHM_RFC3526_MODP_4096_G "02" - -#define MBEDTLS_DHM_RFC5114_MODP_2048_P \ - "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1" \ - "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15" \ - "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212" \ - "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207" \ - "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708" \ - "B3BF8A317091883681286130BC8985DB1602E714415D9330" \ - "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D" \ - "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8" \ - "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763" \ - "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71" \ - "CF9DE5384E71B81C0AC4DFFE0C10E64F" - -#define MBEDTLS_DHM_RFC5114_MODP_2048_G \ - "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF"\ - "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA"\ - "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7"\ - "C17669101999024AF4D027275AC1348BB8A762D0521BC98A"\ - "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE"\ - "F180EB34118E98D119529A45D6F834566E3025E316A330EF"\ - "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB"\ - "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381"\ - "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269"\ - "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179"\ - "81BC087F2A7065B384B890D3191F2BFA" +#define MBEDTLS_ERR_DHM_FILE_IO_ERROR -0x3480 /**< Read or write of file failed. */ +#define MBEDTLS_ERR_DHM_HW_ACCEL_FAILED -0x3500 /**< DHM hardware accelerator failed. */ +#define MBEDTLS_ERR_DHM_SET_GROUP_FAILED -0x3580 /**< Setting the modulus and generator failed. */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_DHM_ALT) + /** - * \brief DHM context structure + * \brief The DHM context structure. */ -typedef struct +typedef struct mbedtls_dhm_context { - size_t len; /*!< size(P) in chars */ - mbedtls_mpi P; /*!< prime modulus */ - mbedtls_mpi G; /*!< generator */ - mbedtls_mpi X; /*!< secret value */ - mbedtls_mpi GX; /*!< self = G^X mod P */ - mbedtls_mpi GY; /*!< peer = G^Y mod P */ - mbedtls_mpi K; /*!< key = GY^X mod P */ - mbedtls_mpi RP; /*!< cached R^2 mod P */ - mbedtls_mpi Vi; /*!< blinding value */ - mbedtls_mpi Vf; /*!< un-blinding value */ - mbedtls_mpi pX; /*!< previous X */ + size_t len; /*!< The size of \p P in Bytes. */ + mbedtls_mpi P; /*!< The prime modulus. */ + mbedtls_mpi G; /*!< The generator. */ + mbedtls_mpi X; /*!< Our secret value. */ + mbedtls_mpi GX; /*!< Our public key = \c G^X mod \c P. */ + mbedtls_mpi GY; /*!< The public key of the peer = \c G^Y mod \c P. */ + mbedtls_mpi K; /*!< The shared secret = \c G^(XY) mod \c P. */ + mbedtls_mpi RP; /*!< The cached value = \c R^2 mod \c P. */ + mbedtls_mpi Vi; /*!< The blinding value. */ + mbedtls_mpi Vf; /*!< The unblinding value. */ + mbedtls_mpi pX; /*!< The previous \c X. */ } mbedtls_dhm_context; +#else /* MBEDTLS_DHM_ALT */ +#include "dhm_alt.h" +#endif /* MBEDTLS_DHM_ALT */ + /** - * \brief Initialize DHM context + * \brief This function initializes the DHM context. * - * \param ctx DHM context to be initialized + * \param ctx The DHM context to initialize. */ void mbedtls_dhm_init( mbedtls_dhm_context *ctx ); /** - * \brief Parse the ServerKeyExchange parameters + * \brief This function parses the ServerKeyExchange parameters. * - * \param ctx DHM context - * \param p &(start of input buffer) - * \param end end of buffer + * \param ctx The DHM context. + * \param p On input, *p must be the start of the input buffer. + * On output, *p is updated to point to the end of the data + * that has been read. On success, this is the first byte + * past the end of the ServerKeyExchange parameters. + * On error, this is the point at which an error has been + * detected, which is usually not useful except to debug + * failures. + * \param end The end of the input buffer. * - * \return 0 if successful, or an MBEDTLS_ERR_DHM_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx, unsigned char **p, const unsigned char *end ); /** - * \brief Setup and write the ServerKeyExchange parameters + * \brief This function sets up and writes the ServerKeyExchange + * parameters. + * + * \note The destination buffer must be large enough to hold + * the reduced binary presentation of the modulus, the generator + * and the public key, each wrapped with a 2-byte length field. + * It is the responsibility of the caller to ensure that enough + * space is available. Refer to \c mbedtls_mpi_size to computing + * the byte-size of an MPI. * - * \param ctx DHM context - * \param x_size private value size in bytes - * \param output destination buffer - * \param olen number of chars written - * \param f_rng RNG function - * \param p_rng RNG parameter + * \note This function assumes that \c ctx->P and \c ctx->G + * have already been properly set. For that, use + * mbedtls_dhm_set_group() below in conjunction with + * mbedtls_mpi_read_binary() and mbedtls_mpi_read_string(). * - * \note This function assumes that ctx->P and ctx->G - * have already been properly set (for example - * using mbedtls_mpi_read_string or mbedtls_mpi_read_binary). + * \param ctx The DHM context. + * \param x_size The private key size in Bytes. + * \param olen The number of characters written. + * \param output The destination buffer. + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \return 0 if successful, or an MBEDTLS_ERR_DHM_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size, unsigned char *output, size_t *olen, @@ -204,28 +175,54 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size, void *p_rng ); /** - * \brief Import the peer's public value G^Y + * \brief This function sets the prime modulus and generator. + * + * \note This function can be used to set \p P, \p G + * in preparation for mbedtls_dhm_make_params(). + * + * \param ctx The DHM context. + * \param P The MPI holding the DHM prime modulus. + * \param G The MPI holding the DHM generator. + * + * \return \c 0 if successful. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. + */ +int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx, + const mbedtls_mpi *P, + const mbedtls_mpi *G ); + +/** + * \brief This function imports the public value of the peer, G^Y. * - * \param ctx DHM context - * \param input input buffer - * \param ilen size of buffer + * \param ctx The DHM context. + * \param input The input buffer containing the G^Y value of the peer. + * \param ilen The size of the input buffer. * - * \return 0 if successful, or an MBEDTLS_ERR_DHM_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx, const unsigned char *input, size_t ilen ); /** - * \brief Create own private value X and export G^X + * \brief This function creates its own private key, \c X, and + * exports \c G^X. * - * \param ctx DHM context - * \param x_size private value size in bytes - * \param output destination buffer - * \param olen must be at least equal to the size of P, ctx->len - * \param f_rng RNG function - * \param p_rng RNG parameter + * \note The destination buffer is always fully written + * so as to contain a big-endian representation of G^X mod P. + * If it is larger than ctx->len, it is padded accordingly + * with zero-bytes at the beginning. * - * \return 0 if successful, or an MBEDTLS_ERR_DHM_XXX error code + * \param ctx The DHM context. + * \param x_size The private key size in Bytes. + * \param output The destination buffer. + * \param olen The length of the destination buffer. Must be at least + * equal to ctx->len (the size of \c P). + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size, unsigned char *output, size_t olen, @@ -233,22 +230,25 @@ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size, void *p_rng ); /** - * \brief Derive and export the shared secret (G^Y)^X mod P - * - * \param ctx DHM context - * \param output destination buffer - * \param output_size size of the destination buffer - * \param olen on exit, holds the actual number of bytes written - * \param f_rng RNG function, for blinding purposes - * \param p_rng RNG parameter - * - * \return 0 if successful, or an MBEDTLS_ERR_DHM_XXX error code - * - * \note If non-NULL, f_rng is used to blind the input as - * countermeasure against timing attacks. Blinding is - * automatically used if and only if our secret value X is - * re-used and costs nothing otherwise, so it is recommended - * to always pass a non-NULL f_rng argument. + * \brief This function derives and exports the shared secret + * \c (G^Y)^X mod \c P. + * + * \note If \p f_rng is not NULL, it is used to blind the input as + * a countermeasure against timing attacks. Blinding is used + * only if our private key \c X is re-used, and not used + * otherwise. We recommend always passing a non-NULL + * \p f_rng argument. + * + * \param ctx The DHM context. + * \param output The destination buffer. + * \param output_size The size of the destination buffer. Must be at least + * the size of ctx->len (the size of \c P). + * \param olen On exit, holds the actual number of Bytes written. + * \param f_rng The RNG function, for blinding purposes. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx, unsigned char *output, size_t output_size, size_t *olen, @@ -256,23 +256,25 @@ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx, void *p_rng ); /** - * \brief Free and clear the components of a DHM key + * \brief This function frees and clears the components of a DHM context. * - * \param ctx DHM context to free and clear + * \param ctx The DHM context to free and clear. */ void mbedtls_dhm_free( mbedtls_dhm_context *ctx ); #if defined(MBEDTLS_ASN1_PARSE_C) /** \ingroup x509_module */ /** - * \brief Parse DHM parameters in PEM or DER format + * \brief This function parses DHM parameters in PEM or DER format. * - * \param dhm DHM context to be initialized - * \param dhmin input buffer - * \param dhminlen size of the buffer - * (including the terminating null byte for PEM data) + * \param dhm The DHM context to initialize. + * \param dhmin The input buffer. + * \param dhminlen The size of the buffer, including the terminating null + * Byte for PEM data. * - * \return 0 if successful, or a specific DHM or PEM error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX error code + * error code on failure. */ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin, size_t dhminlen ); @@ -280,21 +282,24 @@ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin, #if defined(MBEDTLS_FS_IO) /** \ingroup x509_module */ /** - * \brief Load and parse DHM parameters + * \brief This function loads and parses DHM parameters from a file. * - * \param dhm DHM context to be initialized - * \param path filename to read the DHM Parameters from + * \param dhm The DHM context to load the parameters to. + * \param path The filename to read the DHM parameters from. * - * \return 0 if successful, or a specific DHM or PEM error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX error code + * error code on failure. */ int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path ); #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_ASN1_PARSE_C */ /** - * \brief Checkup routine + * \brief The DMH checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_dhm_self_test( int verbose ); @@ -302,4 +307,757 @@ int mbedtls_dhm_self_test( int verbose ); } #endif +/** + * RFC 3526, RFC 5114 and RFC 7919 standardize a number of + * Diffie-Hellman groups, some of which are included here + * for use within the SSL/TLS module and the user's convenience + * when configuring the Diffie-Hellman parameters by hand + * through \c mbedtls_ssl_conf_dh_param. + * + * The following lists the source of the above groups in the standards: + * - RFC 5114 section 2.2: 2048-bit MODP Group with 224-bit Prime Order Subgroup + * - RFC 3526 section 3: 2048-bit MODP Group + * - RFC 3526 section 4: 3072-bit MODP Group + * - RFC 3526 section 5: 4096-bit MODP Group + * - RFC 7919 section A.1: ffdhe2048 + * - RFC 7919 section A.2: ffdhe3072 + * - RFC 7919 section A.3: ffdhe4096 + * - RFC 7919 section A.4: ffdhe6144 + * - RFC 7919 section A.5: ffdhe8192 + * + * The constants with suffix "_p" denote the chosen prime moduli, while + * the constants with suffix "_g" denote the chosen generator + * of the associated prime field. + * + * The constants further suffixed with "_bin" are provided in binary format, + * while all other constants represent null-terminated strings holding the + * hexadecimal presentation of the respective numbers. + * + * The primes from RFC 3526 and RFC 7919 have been generating by the following + * trust-worthy procedure: + * - Fix N in { 2048, 3072, 4096, 6144, 8192 } and consider the N-bit number + * the first and last 64 bits are all 1, and the remaining N - 128 bits of + * which are 0x7ff...ff. + * - Add the smallest multiple of the first N - 129 bits of the binary expansion + * of pi (for RFC 5236) or e (for RFC 7919) to this intermediate bit-string + * such that the resulting integer is a safe-prime. + * - The result is the respective RFC 3526 / 7919 prime, and the corresponding + * generator is always chosen to be 2 (which is a square for these prime, + * hence the corresponding subgroup has order (p-1)/2 and avoids leaking a + * bit in the private exponent). + * + */ + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) + +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +MBEDTLS_DEPRECATED typedef char const * mbedtls_deprecated_constant_t; +#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) \ + ( (mbedtls_deprecated_constant_t) ( VAL ) ) +#else +#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) VAL +#endif /* ! MBEDTLS_DEPRECATED_WARNING */ + +/** + * \warning The origin of the primes in RFC 5114 is not documented and + * their use therefore constitutes a security risk! + * + * \deprecated The hex-encoded primes from RFC 5114 are deprecated and are + * likely to be removed in a future version of the library without + * replacement. + */ + +/** + * The hexadecimal presentation of the prime underlying the + * 2048-bit MODP Group with 224-bit Prime Order Subgroup, as defined + * in RFC-5114: Additional Diffie-Hellman Groups for Use with + * IETF Standards. + */ +#define MBEDTLS_DHM_RFC5114_MODP_2048_P \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1" \ + "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15" \ + "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212" \ + "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207" \ + "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708" \ + "B3BF8A317091883681286130BC8985DB1602E714415D9330" \ + "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D" \ + "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8" \ + "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763" \ + "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71" \ + "CF9DE5384E71B81C0AC4DFFE0C10E64F" ) + +/** + * The hexadecimal presentation of the chosen generator of the 2048-bit MODP + * Group with 224-bit Prime Order Subgroup, as defined in RFC-5114: + * Additional Diffie-Hellman Groups for Use with IETF Standards. + */ +#define MBEDTLS_DHM_RFC5114_MODP_2048_G \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF" \ + "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA" \ + "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7" \ + "C17669101999024AF4D027275AC1348BB8A762D0521BC98A" \ + "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE" \ + "F180EB34118E98D119529A45D6F834566E3025E316A330EF" \ + "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB" \ + "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381" \ + "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269" \ + "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179" \ + "81BC087F2A7065B384B890D3191F2BFA" ) + +/** + * The hexadecimal presentation of the prime underlying the 2048-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + * + * \deprecated The hex-encoded primes from RFC 3625 are deprecated and + * superseded by the corresponding macros providing them as + * binary constants. Their hex-encoded constants are likely + * to be removed in a future version of the library. + * + */ +#define MBEDTLS_DHM_RFC3526_MODP_2048_P \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AACAA68FFFFFFFFFFFFFFFF" ) + +/** + * The hexadecimal presentation of the chosen generator of the 2048-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_2048_G \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) + +/** + * The hexadecimal presentation of the prime underlying the 3072-bit MODP + * Group, as defined in RFC-3072: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_3072_P \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" ) + +/** + * The hexadecimal presentation of the chosen generator of the 3072-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_3072_G \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) + +/** + * The hexadecimal presentation of the prime underlying the 4096-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_4096_P \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \ + "FFFFFFFFFFFFFFFF" ) + +/** + * The hexadecimal presentation of the chosen generator of the 4096-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_4096_G \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) + +#endif /* MBEDTLS_DEPRECATED_REMOVED */ + +/* + * Trustworthy DHM parameters in binary form + */ + +#define MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ + 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ + 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ + 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ + 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ + 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ + 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ + 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ + 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ + 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ + 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ + 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ + 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ + 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ + 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ + 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ + 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ + 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ + 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ + 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ + 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ + 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ + 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ + 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ + 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ + 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ + 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ + 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ + 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC3526_MODP_3072_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ + 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ + 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ + 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ + 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ + 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ + 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ + 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ + 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ + 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ + 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ + 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ + 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ + 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ + 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ + 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ + 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ + 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ + 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ + 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ + 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ + 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ + 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ + 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ + 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ + 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ + 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ + 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ + 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \ + 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \ + 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \ + 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \ + 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \ + 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \ + 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \ + 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \ + 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \ + 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \ + 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \ + 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \ + 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \ + 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \ + 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \ + 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \ + 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x3A, 0xD2, 0xCA, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC3526_MODP_3072_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC3526_MODP_4096_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ + 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ + 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ + 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ + 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ + 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ + 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ + 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ + 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ + 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ + 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ + 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ + 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ + 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ + 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ + 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ + 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ + 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ + 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ + 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ + 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ + 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ + 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ + 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ + 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ + 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ + 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ + 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ + 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \ + 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \ + 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \ + 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \ + 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \ + 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \ + 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \ + 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \ + 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \ + 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \ + 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \ + 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \ + 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \ + 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \ + 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \ + 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \ + 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01, \ + 0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7, \ + 0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26, \ + 0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C, \ + 0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA, \ + 0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8, \ + 0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9, \ + 0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6, \ + 0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D, \ + 0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2, \ + 0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED, \ + 0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF, \ + 0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C, \ + 0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9, \ + 0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1, \ + 0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F, \ + 0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC3526_MODP_4096_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE2048_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, } + +#define MBEDTLS_DHM_RFC7919_FFDHE2048_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE3072_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ + 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ + 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ + 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ + 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ + 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ + 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ + 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ + 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ + 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ + 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ + 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ + 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ + 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ + 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ + 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ + 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC7919_FFDHE3072_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE4096_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ + 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ + 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ + 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ + 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ + 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ + 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ + 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ + 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ + 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ + 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ + 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ + 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ + 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ + 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ + 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ + 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ + 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ + 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ + 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ + 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ + 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ + 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ + 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ + 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ + 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ + 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ + 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ + 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ + 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ + 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ + 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ + 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC7919_FFDHE4096_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE6144_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ + 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ + 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ + 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ + 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ + 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ + 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ + 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ + 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ + 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ + 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ + 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ + 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ + 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ + 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ + 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ + 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ + 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ + 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ + 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ + 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ + 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ + 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ + 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ + 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ + 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ + 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ + 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ + 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ + 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ + 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ + 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ + 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \ + 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \ + 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \ + 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \ + 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \ + 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \ + 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \ + 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \ + 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \ + 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \ + 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \ + 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \ + 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \ + 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \ + 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \ + 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \ + 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \ + 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \ + 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \ + 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \ + 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \ + 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \ + 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \ + 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \ + 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \ + 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \ + 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \ + 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \ + 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \ + 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \ + 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \ + 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \ + 0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC7919_FFDHE6144_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE8192_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ + 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ + 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ + 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ + 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ + 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ + 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ + 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ + 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ + 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ + 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ + 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ + 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ + 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ + 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ + 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ + 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ + 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ + 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ + 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ + 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ + 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ + 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ + 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ + 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ + 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ + 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ + 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ + 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ + 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ + 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ + 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ + 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \ + 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \ + 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \ + 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \ + 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \ + 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \ + 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \ + 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \ + 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \ + 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \ + 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \ + 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \ + 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \ + 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \ + 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \ + 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \ + 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \ + 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \ + 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \ + 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \ + 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \ + 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \ + 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \ + 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \ + 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \ + 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \ + 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \ + 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \ + 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \ + 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \ + 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \ + 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \ + 0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA, \ + 0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38, \ + 0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64, \ + 0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43, \ + 0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E, \ + 0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF, \ + 0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29, \ + 0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65, \ + 0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02, \ + 0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4, \ + 0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82, \ + 0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C, \ + 0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51, \ + 0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22, \ + 0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74, \ + 0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE, \ + 0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C, \ + 0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC, \ + 0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B, \ + 0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9, \ + 0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0, \ + 0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31, \ + 0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57, \ + 0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8, \ + 0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E, \ + 0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30, \ + 0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E, \ + 0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE, \ + 0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D, \ + 0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D, \ + 0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E, \ + 0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C, \ + 0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC7919_FFDHE8192_G_BIN { 0x02 } + #endif /* dhm.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/ecdh.h b/tools/sdk/include/mbedtls/mbedtls/ecdh.h index 625a2819234..95f39805c6d 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ecdh.h +++ b/tools/sdk/include/mbedtls/mbedtls/ecdh.h @@ -1,9 +1,19 @@ /** * \file ecdh.h * - * \brief Elliptic curve Diffie-Hellman + * \brief This file contains ECDH definitions and functions. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous + * key agreement protocol allowing two parties to establish a shared + * secret over an insecure channel. Each party must have an + * elliptic-curve public–private key pair. + * + * For more information, see NIST SP 800-56A Rev. 2: Recommendation for + * Pair-Wise Key Establishment Schemes Using Discrete Logarithm + * Cryptography. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +28,9 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_ECDH_H #define MBEDTLS_ECDH_H @@ -30,65 +41,79 @@ extern "C" { #endif /** - * When importing from an EC key, select if it is our key or the peer's key + * Defines the source of the imported EC key. */ typedef enum { - MBEDTLS_ECDH_OURS, - MBEDTLS_ECDH_THEIRS, + MBEDTLS_ECDH_OURS, /**< Our key. */ + MBEDTLS_ECDH_THEIRS, /**< The key of the peer. */ } mbedtls_ecdh_side; /** - * \brief ECDH context structure + * \brief The ECDH context structure. */ -typedef struct +typedef struct mbedtls_ecdh_context { - mbedtls_ecp_group grp; /*!< elliptic curve used */ - mbedtls_mpi d; /*!< our secret value (private key) */ - mbedtls_ecp_point Q; /*!< our public value (public key) */ - mbedtls_ecp_point Qp; /*!< peer's public value (public key) */ - mbedtls_mpi z; /*!< shared secret */ - int point_format; /*!< format for point export in TLS messages */ - mbedtls_ecp_point Vi; /*!< blinding value (for later) */ - mbedtls_ecp_point Vf; /*!< un-blinding value (for later) */ - mbedtls_mpi _d; /*!< previous d (for later) */ + mbedtls_ecp_group grp; /*!< The elliptic curve used. */ + mbedtls_mpi d; /*!< The private key. */ + mbedtls_ecp_point Q; /*!< The public key. */ + mbedtls_ecp_point Qp; /*!< The value of the public key of the peer. */ + mbedtls_mpi z; /*!< The shared secret. */ + int point_format; /*!< The format of point export in TLS messages. */ + mbedtls_ecp_point Vi; /*!< The blinding value. */ + mbedtls_ecp_point Vf; /*!< The unblinding value. */ + mbedtls_mpi _d; /*!< The previous \p d. */ } mbedtls_ecdh_context; /** - * \brief Generate a public key. - * Raw function that only does the core computation. + * \brief This function generates an ECDH keypair on an elliptic + * curve. + * + * This function performs the first of two core computations + * implemented during the ECDH key exchange. The second core + * computation is performed by mbedtls_ecdh_compute_shared(). * - * \param grp ECP group - * \param d Destination MPI (secret exponent, aka private key) - * \param Q Destination point (public key) - * \param f_rng RNG function - * \param p_rng RNG parameter + * \see ecp.h + * + * \param grp The ECP group. + * \param d The destination MPI (private key). + * \param Q The destination point (public key). + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or + * \c MBEDTLS_MPI_XXX error code on failure. * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code */ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** - * \brief Compute shared secret - * Raw function that only does the core computation. - * - * \param grp ECP group - * \param z Destination MPI (shared secret) - * \param Q Public key from other party - * \param d Our secret exponent (private key) - * \param f_rng RNG function (see notes) - * \param p_rng RNG parameter - * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code - * - * \note If f_rng is not NULL, it is used to implement - * countermeasures against potential elaborate timing - * attacks, see \c mbedtls_ecp_mul() for details. + * \brief This function computes the shared secret. + * + * This function performs the second of two core computations + * implemented during the ECDH key exchange. The first core + * computation is performed by mbedtls_ecdh_gen_public(). + * + * \see ecp.h + * + * \note If \p f_rng is not NULL, it is used to implement + * countermeasures against side-channel attacks. + * For more information, see mbedtls_ecp_mul(). + * + * \param grp The ECP group. + * \param z The destination MPI (shared secret). + * \param Q The public key from another party. + * \param d Our secret exponent (private key). + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or + * \c MBEDTLS_MPI_XXX error code on failure. */ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, const mbedtls_ecp_point *Q, const mbedtls_mpi *d, @@ -96,34 +121,41 @@ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, void *p_rng ); /** - * \brief Initialize context + * \brief This function initializes an ECDH context. * - * \param ctx Context to initialize + * \param ctx The ECDH context to initialize. */ void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx ); /** - * \brief Free context + * \brief This function frees a context. * - * \param ctx Context to free + * \param ctx The context to free. */ void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx ); /** - * \brief Generate a public key and a TLS ServerKeyExchange payload. - * (First function used by a TLS server for ECDHE.) + * \brief This function generates a public key and a TLS + * ServerKeyExchange payload. + * + * This is the first function used by a TLS server for ECDHE + * ciphersuites. + * + * \note This function assumes that the ECP group (grp) of the + * \p ctx context has already been properly set, + * for example, using mbedtls_ecp_group_load(). * - * \param ctx ECDH context - * \param olen number of chars written - * \param buf destination buffer - * \param blen length of buffer - * \param f_rng RNG function - * \param p_rng RNG parameter + * \see ecp.h * - * \note This function assumes that ctx->grp has already been - * properly set (for example using mbedtls_ecp_group_load). + * \param ctx The ECDH context. + * \param olen The number of characters written. + * \param buf The destination buffer. + * \param blen The length of the destination buffer. + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, @@ -131,45 +163,64 @@ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, void *p_rng ); /** - * \brief Parse and procress a TLS ServerKeyExhange payload. - * (First function used by a TLS client for ECDHE.) + * \brief This function parses and processes a TLS ServerKeyExhange + * payload. * - * \param ctx ECDH context - * \param buf pointer to start of input buffer - * \param end one past end of buffer + * This is the first function used by a TLS client for ECDHE + * ciphersuites. + * + * \see ecp.h + * + * \param ctx The ECDH context. + * \param buf The pointer to the start of the input buffer. + * \param end The address for one Byte past the end of the buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. * - * \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code */ int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx, const unsigned char **buf, const unsigned char *end ); /** - * \brief Setup an ECDH context from an EC key. - * (Used by clients and servers in place of the - * ServerKeyEchange for static ECDH: import ECDH parameters - * from a certificate's EC key information.) + * \brief This function sets up an ECDH context from an EC key. + * + * It is used by clients and servers in place of the + * ServerKeyEchange for static ECDH, and imports ECDH + * parameters from the EC key information of a certificate. * - * \param ctx ECDH constext to set - * \param key EC key to use - * \param side Is it our key (1) or the peer's key (0) ? + * \see ecp.h + * + * \param ctx The ECDH context to set up. + * \param key The EC key to use. + * \param side Defines the source of the key: 1: Our key, or + * 0: The key of the peer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. * - * \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code */ int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key, mbedtls_ecdh_side side ); /** - * \brief Generate a public key and a TLS ClientKeyExchange payload. - * (Second function used by a TLS client for ECDH(E).) + * \brief This function generates a public key and a TLS + * ClientKeyExchange payload. + * + * This is the second function used by a TLS client for ECDH(E) + * ciphersuites. * - * \param ctx ECDH context - * \param olen number of bytes actually written - * \param buf destination buffer - * \param blen size of destination buffer - * \param f_rng RNG function - * \param p_rng RNG parameter + * \see ecp.h * - * \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code + * \param ctx The ECDH context. + * \param olen The number of Bytes written. + * \param buf The destination buffer. + * \param blen The size of the destination buffer. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, @@ -177,30 +228,45 @@ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen, void *p_rng ); /** - * \brief Parse and process a TLS ClientKeyExchange payload. - * (Second function used by a TLS server for ECDH(E).) + * \brief This function parses and processes a TLS ClientKeyExchange + * payload. + * + * This is the second function used by a TLS server for ECDH(E) + * ciphersuites. + * + * \see ecp.h * - * \param ctx ECDH context - * \param buf start of input buffer - * \param blen length of input buffer + * \param ctx The ECDH context. + * \param buf The start of the input buffer. + * \param blen The length of the input buffer. * - * \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx, const unsigned char *buf, size_t blen ); /** - * \brief Derive and export the shared secret. - * (Last function used by both TLS client en servers.) + * \brief This function derives and exports the shared secret. + * + * This is the last function used by both TLS client + * and servers. + * + * \note If \p f_rng is not NULL, it is used to implement + * countermeasures against side-channel attacks. + * For more information, see mbedtls_ecp_mul(). + * + * \see ecp.h * - * \param ctx ECDH context - * \param olen number of bytes written - * \param buf destination buffer - * \param blen buffer length - * \param f_rng RNG function, see notes for \c mbedtls_ecdh_compute_shared() - * \param p_rng RNG parameter + * \param ctx The ECDH context. + * \param olen The number of Bytes written. + * \param buf The destination buffer. + * \param blen The length of the destination buffer. + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \return 0 if successful, or an MBEDTLS_ERR_ECP_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, diff --git a/tools/sdk/include/mbedtls/mbedtls/ecdsa.h b/tools/sdk/include/mbedtls/mbedtls/ecdsa.h index a277715b3dc..ce1a03d7913 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ecdsa.h +++ b/tools/sdk/include/mbedtls/mbedtls/ecdsa.h @@ -1,9 +1,17 @@ /** * \file ecdsa.h * - * \brief Elliptic curve DSA + * \brief This file contains ECDSA definitions and functions. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * The Elliptic Curve Digital Signature Algorithm (ECDSA) is defined in + * Standards for Efficient Cryptography Group (SECG): + * SEC1 Elliptic Curve Cryptography. + * The use of ECDSA for TLS is defined in RFC-4492: Elliptic Curve + * Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS). + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +26,9 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_ECDSA_H #define MBEDTLS_ECDSA_H @@ -27,7 +36,7 @@ #include "md.h" /* - * RFC 4492 page 20: + * RFC-4492 page 20: * * Ecdsa-Sig-Value ::= SEQUENCE { * r INTEGER, @@ -43,11 +52,11 @@ #if MBEDTLS_ECP_MAX_BYTES > 124 #error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN" #endif -/** Maximum size of an ECDSA signature in bytes */ +/** The maximal size of an ECDSA signature in Bytes. */ #define MBEDTLS_ECDSA_MAX_LEN ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) ) /** - * \brief ECDSA context structure + * \brief The ECDSA context structure. */ typedef mbedtls_ecp_keypair mbedtls_ecdsa_context; @@ -56,25 +65,31 @@ extern "C" { #endif /** - * \brief Compute ECDSA signature of a previously hashed message - * - * \note The deterministic version is usually prefered. + * \brief This function computes the ECDSA signature of a + * previously-hashed message. * - * \param grp ECP group - * \param r First output integer - * \param s Second output integer - * \param d Private signing key - * \param buf Message hash - * \param blen Length of buf - * \param f_rng RNG function - * \param p_rng RNG parameter + * \note The deterministic version is usually preferred. * * \note If the bitlength of the message hash is larger than the - * bitlength of the group order, then the hash is truncated as - * prescribed by SEC1 4.1.3 step 5. - * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * bitlength of the group order, then the hash is truncated + * as defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \see ecp.h + * + * \param grp The ECP group. + * \param r The first output integer. + * \param s The second output integer. + * \param d The private signing key. + * \param buf The message hash. + * \param blen The length of \p buf. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX + * or \c MBEDTLS_MPI_XXX error code on failure. */ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, @@ -82,23 +97,32 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, #if defined(MBEDTLS_ECDSA_DETERMINISTIC) /** - * \brief Compute ECDSA signature of a previously hashed message, - * deterministic version (RFC 6979). + * \brief This function computes the ECDSA signature of a + * previously-hashed message, deterministic version. * - * \param grp ECP group - * \param r First output integer - * \param s Second output integer - * \param d Private signing key - * \param buf Message hash - * \param blen Length of buf - * \param md_alg MD algorithm used to hash the message + * For more information, see RFC-6979: Deterministic + * Usage of the Digital Signature Algorithm (DSA) and Elliptic + * Curve Digital Signature Algorithm (ECDSA). * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as - * prescribed by SEC1 4.1.3 step 5. - * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \see ecp.h + * + * \param grp The ECP group. + * \param r The first output integer. + * \param s The second output integer. + * \param d The private signing key. + * \param buf The message hash. + * \param blen The length of \p buf. + * \param md_alg The MD algorithm used to hash the message. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX + * error code on failure. */ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, @@ -106,55 +130,74 @@ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ /** - * \brief Verify ECDSA signature of a previously hashed message - * - * \param grp ECP group - * \param buf Message hash - * \param blen Length of buf - * \param Q Public key to use for verification - * \param r First integer of the signature - * \param s Second integer of the signature + * \brief This function verifies the ECDSA signature of a + * previously-hashed message. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as - * prescribed by SEC1 4.1.4 step 3. - * - * \return 0 if successful, - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.4, step 3. + * + * \see ecp.h + * + * \param grp The ECP group. + * \param buf The message hash. + * \param blen The length of \p buf. + * \param Q The public key to use for verification. + * \param r The first integer of the signature. + * \param s The second integer of the signature. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the signature + * is invalid. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX + * error code on failure for any other reason. */ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, const unsigned char *buf, size_t blen, const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s); /** - * \brief Compute ECDSA signature and write it to buffer, - * serialized as defined in RFC 4492 page 20. - * (Not thread-safe to use same context in multiple threads) - * - * \note The deterministic version (RFC 6979) is used if - * MBEDTLS_ECDSA_DETERMINISTIC is defined. - * - * \param ctx ECDSA context - * \param md_alg Algorithm that was used to hash the message - * \param hash Message hash - * \param hlen Length of hash - * \param sig Buffer that will hold the signature - * \param slen Length of the signature written - * \param f_rng RNG function - * \param p_rng RNG parameter - * - * \note The "sig" buffer must be at least as large as twice the - * size of the curve used, plus 9 (eg. 73 bytes if a 256-bit - * curve is used). MBEDTLS_ECDSA_MAX_LEN is always safe. + * \brief This function computes the ECDSA signature and writes it + * to a buffer, serialized as defined in RFC-4492: + * Elliptic Curve Cryptography (ECC) Cipher Suites for + * Transport Layer Security (TLS). + * + * \warning It is not thread-safe to use the same context in + * multiple threads. + * + * \note The deterministic version is used if + * #MBEDTLS_ECDSA_DETERMINISTIC is defined. For more + * information, see RFC-6979: Deterministic Usage + * of the Digital Signature Algorithm (DSA) and Elliptic + * Curve Digital Signature Algorithm (ECDSA). + * + * \note The \p sig buffer must be at least twice as large as the + * size of the curve used, plus 9. For example, 73 Bytes if + * a 256-bit curve is used. A buffer length of + * #MBEDTLS_ECDSA_MAX_LEN is always safe. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as - * prescribed by SEC1 4.1.3 step 5. - * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX, MBEDTLS_ERR_MPI_XXX or - * MBEDTLS_ERR_ASN1_XXX error code + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \see ecp.h + * + * \param ctx The ECDSA context. + * \param md_alg The message digest that was used to hash the message. + * \param hash The message hash. + * \param hlen The length of the hash. + * \param sig The buffer that holds the signature. + * \param slen The length of the signature written. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or + * \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, @@ -170,31 +213,44 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t #define MBEDTLS_DEPRECATED #endif /** - * \brief Compute ECDSA signature and write it to buffer, - * serialized as defined in RFC 4492 page 20. - * Deterministic version, RFC 6979. - * (Not thread-safe to use same context in multiple threads) + * \brief This function computes an ECDSA signature and writes + * it to a buffer, serialized as defined in RFC-4492: + * Elliptic Curve Cryptography (ECC) Cipher Suites for + * Transport Layer Security (TLS). * - * \deprecated Superseded by mbedtls_ecdsa_write_signature() in 2.0.0 + * The deterministic version is defined in RFC-6979: + * Deterministic Usage of the Digital Signature Algorithm (DSA) + * and Elliptic Curve Digital Signature Algorithm (ECDSA). * - * \param ctx ECDSA context - * \param hash Message hash - * \param hlen Length of hash - * \param sig Buffer that will hold the signature - * \param slen Length of the signature written - * \param md_alg MD algorithm used to hash the message + * \warning It is not thread-safe to use the same context in + * multiple threads. * - * \note The "sig" buffer must be at least as large as twice the - * size of the curve used, plus 9 (eg. 73 bytes if a 256-bit - * curve is used). MBEDTLS_ECDSA_MAX_LEN is always safe. + * \note The \p sig buffer must be at least twice as large as the + * size of the curve used, plus 9. For example, 73 Bytes if a + * 256-bit curve is used. A buffer length of + * #MBEDTLS_ECDSA_MAX_LEN is always safe. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as - * prescribed by SEC1 4.1.3 step 5. + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \see ecp.h + * + * \deprecated Superseded by mbedtls_ecdsa_write_signature() in + * Mbed TLS version 2.0 and later. * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX, MBEDTLS_ERR_MPI_XXX or - * MBEDTLS_ERR_ASN1_XXX error code + * \param ctx The ECDSA context. + * \param hash The message hash. + * \param hlen The length of the hash. + * \param sig The buffer that holds the signature. + * \param slen The length of the signature written. + * \param md_alg The MD algorithm used to hash the message. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or + * \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, @@ -205,63 +261,74 @@ int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ /** - * \brief Read and verify an ECDSA signature - * - * \param ctx ECDSA context - * \param hash Message hash - * \param hlen Size of hash - * \param sig Signature to read and verify - * \param slen Size of sig + * \brief This function reads and verifies an ECDSA signature. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as - * prescribed by SEC1 4.1.4 step 3. - * - * \return 0 if successful, - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid, - * MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if the signature is - * valid but its actual length is less than siglen, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_ERR_MPI_XXX error code + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.4, step 3. + * + * \see ecp.h + * + * \param ctx The ECDSA context. + * \param hash The message hash. + * \param hlen The size of the hash. + * \param sig The signature to read and verify. + * \param slen The size of \p sig. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid. + * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid + * signature in \p sig, but its length is less than \p siglen. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX + * error code on failure for any other reason. */ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen ); /** - * \brief Generate an ECDSA keypair on the given curve + * \brief This function generates an ECDSA keypair on the given curve. * - * \param ctx ECDSA context in which the keypair should be stored - * \param gid Group (elliptic curve) to use. One of the various - * MBEDTLS_ECP_DP_XXX macros depending on configuration. - * \param f_rng RNG function - * \param p_rng RNG parameter + * \see ecp.h * - * \return 0 on success, or a MBEDTLS_ERR_ECP_XXX code. + * \param ctx The ECDSA context to store the keypair in. + * \param gid The elliptic curve to use. One of the various + * \c MBEDTLS_ECP_DP_XXX macros depending on configuration. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX code on failure. */ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** - * \brief Set an ECDSA context from an EC key pair + * \brief This function sets an ECDSA context from an EC key pair. + * + * \see ecp.h * - * \param ctx ECDSA context to set - * \param key EC key to use + * \param ctx The ECDSA context to set. + * \param key The EC key to use. * - * \return 0 on success, or a MBEDTLS_ERR_ECP_XXX code. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX code on failure. */ int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key ); /** - * \brief Initialize context + * \brief This function initializes an ECDSA context. * - * \param ctx Context to initialize + * \param ctx The ECDSA context to initialize. */ void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx ); /** - * \brief Free context + * \brief This function frees an ECDSA context. * - * \param ctx Context to free + * \param ctx The ECDSA context to free. */ void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx ); diff --git a/tools/sdk/include/mbedtls/mbedtls/ecjpake.h b/tools/sdk/include/mbedtls/mbedtls/ecjpake.h index 161a5b213fe..59d12f080fd 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ecjpake.h +++ b/tools/sdk/include/mbedtls/mbedtls/ecjpake.h @@ -2,7 +2,8 @@ * \file ecjpake.h * * \brief Elliptic curve J-PAKE - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -55,6 +56,7 @@ typedef enum { MBEDTLS_ECJPAKE_SERVER, /**< Server */ } mbedtls_ecjpake_role; +#if !defined(MBEDTLS_ECJPAKE_ALT) /** * EC J-PAKE context structure. * @@ -66,7 +68,7 @@ typedef enum { * convetion from the Thread v1.0 spec. Correspondance is indicated in the * description as a pair C: client name, S: server name */ -typedef struct +typedef struct mbedtls_ecjpake_context { const mbedtls_md_info_t *md_info; /**< Hash to use */ mbedtls_ecp_group grp; /**< Elliptic curve */ @@ -85,6 +87,10 @@ typedef struct mbedtls_mpi s; /**< Pre-shared secret (passphrase) */ } mbedtls_ecjpake_context; +#else /* MBEDTLS_ECJPAKE_ALT */ +#include "ecjpake_alt.h" +#endif /* MBEDTLS_ECJPAKE_ALT */ + /** * \brief Initialize a context * (just makes it ready for setup() or free()). @@ -222,17 +228,22 @@ int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx, */ void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx ); + + #if defined(MBEDTLS_SELF_TEST) + /** * \brief Checkup routine * * \return 0 if successful, or 1 if a test failed */ int mbedtls_ecjpake_self_test( int verbose ); -#endif + +#endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif + #endif /* ecjpake.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/ecp.h b/tools/sdk/include/mbedtls/mbedtls/ecp.h index dad9aef002c..ed1b9d73681 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ecp.h +++ b/tools/sdk/include/mbedtls/mbedtls/ecp.h @@ -1,9 +1,21 @@ /** * \file ecp.h * - * \brief Elliptic curves over GF(p) + * \brief This file provides an API for Elliptic Curves over GF(P) (ECP). * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * The use of ECP in cryptography and TLS is defined in + * Standards for Efficient Cryptography Group (SECG): SEC1 + * Elliptic Curve Cryptography and + * RFC-4492: Elliptic Curve Cryptography (ECC) Cipher Suites + * for Transport Layer Security (TLS). + * + * RFC-2409: The Internet Key Exchange (IKE) defines ECP + * group types. + * + */ + +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +30,9 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_ECP_H #define MBEDTLS_ECP_H @@ -30,159 +43,157 @@ */ #define MBEDTLS_ERR_ECP_BAD_INPUT_DATA -0x4F80 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL -0x4F00 /**< The buffer is too small to write to. */ -#define MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE -0x4E80 /**< Requested curve not available. */ +#define MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE -0x4E80 /**< The requested feature is not available, for example, the requested curve is not supported. */ #define MBEDTLS_ERR_ECP_VERIFY_FAILED -0x4E00 /**< The signature is not valid. */ #define MBEDTLS_ERR_ECP_ALLOC_FAILED -0x4D80 /**< Memory allocation failed. */ -#define MBEDTLS_ERR_ECP_RANDOM_FAILED -0x4D00 /**< Generation of random value, such as (ephemeral) key, failed. */ +#define MBEDTLS_ERR_ECP_RANDOM_FAILED -0x4D00 /**< Generation of random value, such as ephemeral key, failed. */ #define MBEDTLS_ERR_ECP_INVALID_KEY -0x4C80 /**< Invalid private or public key. */ -#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH -0x4C00 /**< Signature is valid but shorter than the user-supplied length. */ - -#if !defined(MBEDTLS_ECP_ALT) -/* - * default mbed TLS elliptic curve arithmetic implementation - * - * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an - * alternative implementation for the whole module and it will replace this - * one.) - */ +#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH -0x4C00 /**< The buffer contains a valid signature followed by more data. */ +#define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED -0x4B80 /**< The ECP hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif /** - * Domain parameters (curve, subgroup and generator) identifiers. + * Domain-parameter identifiers: curve, subgroup, and generator. * - * Only curves over prime fields are supported. + * \note Only curves over prime fields are supported. * * \warning This library does not support validation of arbitrary domain - * parameters. Therefore, only well-known domain parameters from trusted + * parameters. Therefore, only standardized domain parameters from trusted * sources should be used. See mbedtls_ecp_group_load(). */ typedef enum { - MBEDTLS_ECP_DP_NONE = 0, - MBEDTLS_ECP_DP_SECP192R1, /*!< 192-bits NIST curve */ - MBEDTLS_ECP_DP_SECP224R1, /*!< 224-bits NIST curve */ - MBEDTLS_ECP_DP_SECP256R1, /*!< 256-bits NIST curve */ - MBEDTLS_ECP_DP_SECP384R1, /*!< 384-bits NIST curve */ - MBEDTLS_ECP_DP_SECP521R1, /*!< 521-bits NIST curve */ - MBEDTLS_ECP_DP_BP256R1, /*!< 256-bits Brainpool curve */ - MBEDTLS_ECP_DP_BP384R1, /*!< 384-bits Brainpool curve */ - MBEDTLS_ECP_DP_BP512R1, /*!< 512-bits Brainpool curve */ - MBEDTLS_ECP_DP_CURVE25519, /*!< Curve25519 */ - MBEDTLS_ECP_DP_SECP192K1, /*!< 192-bits "Koblitz" curve */ - MBEDTLS_ECP_DP_SECP224K1, /*!< 224-bits "Koblitz" curve */ - MBEDTLS_ECP_DP_SECP256K1, /*!< 256-bits "Koblitz" curve */ + MBEDTLS_ECP_DP_NONE = 0, /*!< Curve not defined. */ + MBEDTLS_ECP_DP_SECP192R1, /*!< Domain parameters for the 192-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP224R1, /*!< Domain parameters for the 224-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP256R1, /*!< Domain parameters for the 256-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP384R1, /*!< Domain parameters for the 384-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP521R1, /*!< Domain parameters for the 521-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_BP256R1, /*!< Domain parameters for 256-bit Brainpool curve. */ + MBEDTLS_ECP_DP_BP384R1, /*!< Domain parameters for 384-bit Brainpool curve. */ + MBEDTLS_ECP_DP_BP512R1, /*!< Domain parameters for 512-bit Brainpool curve. */ + MBEDTLS_ECP_DP_CURVE25519, /*!< Domain parameters for Curve25519. */ + MBEDTLS_ECP_DP_SECP192K1, /*!< Domain parameters for 192-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_SECP224K1, /*!< Domain parameters for 224-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_SECP256K1, /*!< Domain parameters for 256-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_CURVE448, /*!< Domain parameters for Curve448. */ } mbedtls_ecp_group_id; /** - * Number of supported curves (plus one for NONE). + * The number of supported curves, plus one for #MBEDTLS_ECP_DP_NONE. * - * (Montgomery curves excluded for now.) + * \note Montgomery curves are currently excluded. */ #define MBEDTLS_ECP_DP_MAX 12 /** - * Curve information for use by other modules + * Curve information, for use by other modules. */ -typedef struct +typedef struct mbedtls_ecp_curve_info { - mbedtls_ecp_group_id grp_id; /*!< Internal identifier */ - uint16_t tls_id; /*!< TLS NamedCurve identifier */ - uint16_t bit_size; /*!< Curve size in bits */ - const char *name; /*!< Human-friendly name */ + mbedtls_ecp_group_id grp_id; /*!< An internal identifier. */ + uint16_t tls_id; /*!< The TLS NamedCurve identifier. */ + uint16_t bit_size; /*!< The curve size in bits. */ + const char *name; /*!< A human-friendly name. */ } mbedtls_ecp_curve_info; /** - * \brief ECP point structure (jacobian coordinates) + * \brief The ECP point structure, in Jacobian coordinates. * * \note All functions expect and return points satisfying - * the following condition: Z == 0 or Z == 1. (Other - * values of Z are used by internal functions only.) - * The point is zero, or "at infinity", if Z == 0. - * Otherwise, X and Y are its standard (affine) coordinates. - */ -typedef struct + * the following condition: Z == 0 or + * Z == 1. Other values of \p Z are + * used only by internal functions. + * The point is zero, or "at infinity", if Z == 0. + * Otherwise, \p X and \p Y are its standard (affine) + * coordinates. + */ +typedef struct mbedtls_ecp_point { - mbedtls_mpi X; /*!< the point's X coordinate */ - mbedtls_mpi Y; /*!< the point's Y coordinate */ - mbedtls_mpi Z; /*!< the point's Z coordinate */ + mbedtls_mpi X; /*!< The X coordinate of the ECP point. */ + mbedtls_mpi Y; /*!< The Y coordinate of the ECP point. */ + mbedtls_mpi Z; /*!< The Z coordinate of the ECP point. */ } mbedtls_ecp_point; -/** - * \brief ECP group structure - * - * We consider two types of curves equations: - * 1. Short Weierstrass y^2 = x^3 + A x + B mod P (SEC1 + RFC 4492) - * 2. Montgomery, y^2 = x^3 + A x^2 + x mod P (Curve25519 + draft) - * In both cases, a generator G for a prime-order subgroup is fixed. In the - * short weierstrass, this subgroup is actually the whole curve, and its - * cardinal is denoted by N. - * - * In the case of Short Weierstrass curves, our code requires that N is an odd - * prime. (Use odd in mbedtls_ecp_mul() and prime in mbedtls_ecdsa_sign() for blinding.) - * - * In the case of Montgomery curves, we don't store A but (A + 2) / 4 which is - * the quantity actually used in the formulas. Also, nbits is not the size of N - * but the required size for private keys. +#if !defined(MBEDTLS_ECP_ALT) +/* + * default mbed TLS elliptic curve arithmetic implementation * - * If modp is NULL, reduction modulo P is done using a generic algorithm. - * Otherwise, it must point to a function that takes an mbedtls_mpi in the range - * 0..2^(2*pbits)-1 and transforms it in-place in an integer of little more - * than pbits, so that the integer may be efficiently brought in the 0..P-1 - * range by a few additions or substractions. It must return 0 on success and - * non-zero on failure. + * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an + * alternative implementation for the whole module and it will replace this + * one.) */ -typedef struct -{ - mbedtls_ecp_group_id id; /*!< internal group identifier */ - mbedtls_mpi P; /*!< prime modulus of the base field */ - mbedtls_mpi A; /*!< 1. A in the equation, or 2. (A + 2) / 4 */ - mbedtls_mpi B; /*!< 1. B in the equation, or 2. unused */ - mbedtls_ecp_point G; /*!< generator of the (sub)group used */ - mbedtls_mpi N; /*!< 1. the order of G, or 2. unused */ - size_t pbits; /*!< number of bits in P */ - size_t nbits; /*!< number of bits in 1. P, or 2. private keys */ - unsigned int h; /*!< internal: 1 if the constants are static */ - int (*modp)(mbedtls_mpi *); /*!< function for fast reduction mod P */ - int (*t_pre)(mbedtls_ecp_point *, void *); /*!< unused */ - int (*t_post)(mbedtls_ecp_point *, void *); /*!< unused */ - void *t_data; /*!< unused */ - mbedtls_ecp_point *T; /*!< pre-computed points for ecp_mul_comb() */ - size_t T_size; /*!< number for pre-computed points */ -} -mbedtls_ecp_group; /** - * \brief ECP key pair structure + * \brief The ECP group structure. * - * A generic key pair that could be used for ECDSA, fixed ECDH, etc. + * We consider two types of curve equations: + *
  • Short Weierstrass: y^2 = x^3 + A x + B mod P + * (SEC1 + RFC-4492)
  • + *
  • Montgomery: y^2 = x^3 + A x^2 + x mod P (Curve25519, + * Curve448)
+ * In both cases, the generator (\p G) for a prime-order subgroup is fixed. + * + * For Short Weierstrass, this subgroup is the whole curve, and its + * cardinality is denoted by \p N. Our code requires that \p N is an + * odd prime as mbedtls_ecp_mul() requires an odd number, and + * mbedtls_ecdsa_sign() requires that it is prime for blinding purposes. + * + * For Montgomery curves, we do not store \p A, but (A + 2) / 4, + * which is the quantity used in the formulas. Additionally, \p nbits is + * not the size of \p N but the required size for private keys. + * + * If \p modp is NULL, reduction modulo \p P is done using a generic algorithm. + * Otherwise, \p modp must point to a function that takes an \p mbedtls_mpi in the + * range of 0..2^(2*pbits)-1, and transforms it in-place to an integer + * which is congruent mod \p P to the given MPI, and is close enough to \p pbits + * in size, so that it may be efficiently brought in the 0..P-1 range by a few + * additions or subtractions. Therefore, it is only an approximative modular + * reduction. It must return 0 on success and non-zero on failure. * - * \note Members purposefully in the same order as struc mbedtls_ecdsa_context. */ -typedef struct +typedef struct mbedtls_ecp_group { - mbedtls_ecp_group grp; /*!< Elliptic curve and base point */ - mbedtls_mpi d; /*!< our secret value */ - mbedtls_ecp_point Q; /*!< our public value */ + mbedtls_ecp_group_id id; /*!< An internal group identifier. */ + mbedtls_mpi P; /*!< The prime modulus of the base field. */ + mbedtls_mpi A; /*!< For Short Weierstrass: \p A in the equation. For + Montgomery curves: (A + 2) / 4. */ + mbedtls_mpi B; /*!< For Short Weierstrass: \p B in the equation. + For Montgomery curves: unused. */ + mbedtls_ecp_point G; /*!< The generator of the subgroup used. */ + mbedtls_mpi N; /*!< The order of \p G. */ + size_t pbits; /*!< The number of bits in \p P.*/ + size_t nbits; /*!< For Short Weierstrass: The number of bits in \p P. + For Montgomery curves: the number of bits in the + private keys. */ + unsigned int h; /*!< \internal 1 if the constants are static. */ + int (*modp)(mbedtls_mpi *); /*!< The function for fast pseudo-reduction + mod \p P (see above).*/ + int (*t_pre)(mbedtls_ecp_point *, void *); /*!< Unused. */ + int (*t_post)(mbedtls_ecp_point *, void *); /*!< Unused. */ + void *t_data; /*!< Unused. */ + mbedtls_ecp_point *T; /*!< Pre-computed points for ecp_mul_comb(). */ + size_t T_size; /*!< The number of pre-computed points. */ } -mbedtls_ecp_keypair; +mbedtls_ecp_group; /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. - * Either change them in config.h or define them on the compiler command line. + * Either change them in config.h, or define them using the compiler command line. * \{ */ #if !defined(MBEDTLS_ECP_MAX_BITS) /** - * Maximum size of the groups (that is, of N and P) + * The maximum size of the groups, that is, of \c N and \c P. */ -#define MBEDTLS_ECP_MAX_BITS 521 /**< Maximum bit size of groups */ +#define MBEDTLS_ECP_MAX_BITS 521 /**< The maximum size of groups, in bits. */ #endif #define MBEDTLS_ECP_MAX_BYTES ( ( MBEDTLS_ECP_MAX_BITS + 7 ) / 8 ) @@ -205,11 +216,10 @@ mbedtls_ecp_keypair; * 521 145 141 135 120 97 * 384 214 209 198 177 146 * 256 320 320 303 262 226 - * 224 475 475 453 398 342 * 192 640 640 633 587 476 */ -#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< Maximum window size used */ +#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< The maximum window size used. */ #endif /* MBEDTLS_ECP_WINDOW_SIZE */ #if !defined(MBEDTLS_ECP_FIXED_POINT_OPTIM) @@ -224,33 +234,55 @@ mbedtls_ecp_keypair; * * Change this value to 0 to reduce peak memory usage. */ -#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up */ +#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up. */ #endif /* MBEDTLS_ECP_FIXED_POINT_OPTIM */ /* \} name SECTION: Module settings */ +#else /* MBEDTLS_ECP_ALT */ +#include "ecp_alt.h" +#endif /* MBEDTLS_ECP_ALT */ + +/** + * \brief The ECP key-pair structure. + * + * A generic key-pair that may be used for ECDSA and fixed ECDH, for example. + * + * \note Members are deliberately in the same order as in the + * ::mbedtls_ecdsa_context structure. + */ +typedef struct mbedtls_ecp_keypair +{ + mbedtls_ecp_group grp; /*!< Elliptic curve and base point */ + mbedtls_mpi d; /*!< our secret value */ + mbedtls_ecp_point Q; /*!< our public value */ +} +mbedtls_ecp_keypair; + /* * Point formats, from RFC 4492's enum ECPointFormat */ -#define MBEDTLS_ECP_PF_UNCOMPRESSED 0 /**< Uncompressed point format */ -#define MBEDTLS_ECP_PF_COMPRESSED 1 /**< Compressed point format */ +#define MBEDTLS_ECP_PF_UNCOMPRESSED 0 /**< Uncompressed point format. */ +#define MBEDTLS_ECP_PF_COMPRESSED 1 /**< Compressed point format. */ /* * Some other constants from RFC 4492 */ -#define MBEDTLS_ECP_TLS_NAMED_CURVE 3 /**< ECCurveType's named_curve */ +#define MBEDTLS_ECP_TLS_NAMED_CURVE 3 /**< The named_curve of ECCurveType. */ /** - * \brief Get the list of supported curves in order of preferrence - * (full information) + * \brief This function retrieves the information defined in + * mbedtls_ecp_curve_info() for all supported curves in order + * of preference. * - * \return A statically allocated array, the last entry is 0. + * \return A statically allocated array. The last entry is 0. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void ); /** - * \brief Get the list of supported curves in order of preferrence - * (grp_id only) + * \brief This function retrieves the list of internal group + * identifiers of all supported curves in the order of + * preference. * * \return A statically allocated array, * terminated with MBEDTLS_ECP_DP_NONE. @@ -258,357 +290,400 @@ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void ); const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void ); /** - * \brief Get curve information from an internal group identifier + * \brief This function retrieves curve information from an internal + * group identifier. * - * \param grp_id A MBEDTLS_ECP_DP_XXX value + * \param grp_id An \c MBEDTLS_ECP_DP_XXX value. * - * \return The associated curve information or NULL + * \return The associated curve information on success. + * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id ); /** - * \brief Get curve information from a TLS NamedCurve value + * \brief This function retrieves curve information from a TLS + * NamedCurve value. * - * \param tls_id A MBEDTLS_ECP_DP_XXX value + * \param tls_id An \c MBEDTLS_ECP_DP_XXX value. * - * \return The associated curve information or NULL + * \return The associated curve information on success. + * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id ); /** - * \brief Get curve information from a human-readable name + * \brief This function retrieves curve information from a + * human-readable name. * - * \param name The name + * \param name The human-readable name. * - * \return The associated curve information or NULL + * \return The associated curve information on success. + * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name ); /** - * \brief Initialize a point (as zero) + * \brief This function initializes a point as zero. + * + * \param pt The point to initialize. */ void mbedtls_ecp_point_init( mbedtls_ecp_point *pt ); /** - * \brief Initialize a group (to something meaningless) + * \brief This function initializes an ECP group context + * without loading any domain parameters. + * + * \note After this function is called, domain parameters + * for various ECP groups can be loaded through the + * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group() + * functions. */ void mbedtls_ecp_group_init( mbedtls_ecp_group *grp ); /** - * \brief Initialize a key pair (as an invalid one) + * \brief This function initializes a key pair as an invalid one. + * + * \param key The key pair to initialize. */ void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key ); /** - * \brief Free the components of a point + * \brief This function frees the components of a point. + * + * \param pt The point to free. */ void mbedtls_ecp_point_free( mbedtls_ecp_point *pt ); /** - * \brief Free the components of an ECP group + * \brief This function frees the components of an ECP group. + * \param grp The group to free. */ void mbedtls_ecp_group_free( mbedtls_ecp_group *grp ); /** - * \brief Free the components of a key pair + * \brief This function frees the components of a key pair. + * \param key The key pair to free. */ void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key ); /** - * \brief Copy the contents of point Q into P + * \brief This function copies the contents of point \p Q into + * point \p P. * - * \param P Destination point - * \param Q Source point + * \param P The destination point. + * \param Q The source point. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ); /** - * \brief Copy the contents of a group object + * \brief This function copies the contents of group \p src into + * group \p dst. * - * \param dst Destination group - * \param src Source group + * \param dst The destination group. + * \param src The source group. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src ); /** - * \brief Set a point to zero + * \brief This function sets a point to zero. * - * \param pt Destination point + * \param pt The point to set. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_set_zero( mbedtls_ecp_point *pt ); /** - * \brief Tell if a point is zero + * \brief This function checks if a point is zero. * - * \param pt Point to test + * \param pt The point to test. * - * \return 1 if point is zero, 0 otherwise + * \return \c 1 if the point is zero. + * \return \c 0 if the point is non-zero. */ int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt ); /** - * \brief Compare two points + * \brief This function compares two points. * - * \note This assumes the points are normalized. Otherwise, + * \note This assumes that the points are normalized. Otherwise, * they may compare as "not equal" even if they are. * - * \param P First point to compare - * \param Q Second point to compare + * \param P The first point to compare. + * \param Q The second point to compare. * - * \return 0 if the points are equal, - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA otherwise + * \return \c 0 if the points are equal. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the points are not equal. */ int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ); /** - * \brief Import a non-zero point from two ASCII strings + * \brief This function imports a non-zero point from two ASCII + * strings. * - * \param P Destination point - * \param radix Input numeric base - * \param x First affine coordinate as a null-terminated string - * \param y Second affine coordinate as a null-terminated string + * \param P The destination point. + * \param radix The numeric base of the input. + * \param x The first affine coordinate, as a null-terminated string. + * \param y The second affine coordinate, as a null-terminated string. * - * \return 0 if successful, or a MBEDTLS_ERR_MPI_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_MPI_XXX error code on failure. */ int mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix, const char *x, const char *y ); /** - * \brief Export a point into unsigned binary data + * \brief This function exports a point into unsigned binary data. * - * \param grp Group to which the point should belong - * \param P Point to export - * \param format Point format, should be a MBEDTLS_ECP_PF_XXX macro - * \param olen Length of the actual output - * \param buf Output buffer - * \param buflen Length of the output buffer + * \param grp The group to which the point should belong. + * \param P The point to export. + * \param format The point format. Should be an \c MBEDTLS_ECP_PF_XXX macro. + * \param olen The length of the output. + * \param buf The output buffer. + * \param buflen The length of the output buffer. * - * \return 0 if successful, - * or MBEDTLS_ERR_ECP_BAD_INPUT_DATA - * or MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA + * or #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure. */ int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *P, int format, size_t *olen, unsigned char *buf, size_t buflen ); /** - * \brief Import a point from unsigned binary data + * \brief This function imports a point from unsigned binary data. * - * \param grp Group to which the point should belong - * \param P Point to import - * \param buf Input buffer - * \param ilen Actual length of input + * \note This function does not check that the point actually + * belongs to the given group, see mbedtls_ecp_check_pubkey() + * for that. * - * \return 0 if successful, - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed, - * MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format + * \param grp The group to which the point should belong. + * \param P The point to import. + * \param buf The input buffer. + * \param ilen The length of the input. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format * is not implemented. * - * \note This function does NOT check that the point actually - * belongs to the given group, see mbedtls_ecp_check_pubkey() for - * that. */ int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P, const unsigned char *buf, size_t ilen ); /** - * \brief Import a point from a TLS ECPoint record + * \brief This function imports a point from a TLS ECPoint record. * - * \param grp ECP group used - * \param pt Destination point - * \param buf $(Start of input buffer) - * \param len Buffer length + * \note On function return, \p buf is updated to point to immediately + * after the ECPoint record. * - * \note buf is updated to point right after the ECPoint on exit + * \param grp The ECP group used. + * \param pt The destination point. + * \param buf The address of the pointer to the start of the input buffer. + * \param len The length of the buffer. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_XXX if initialization failed - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization failure. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. */ int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt, const unsigned char **buf, size_t len ); /** - * \brief Export a point as a TLS ECPoint record + * \brief This function exports a point as a TLS ECPoint record. * - * \param grp ECP group used - * \param pt Point to export - * \param format Export format - * \param olen length of data written - * \param buf Buffer to write to - * \param blen Buffer length + * \param grp The ECP group used. + * \param pt The point format to export to. The point format is an + * \c MBEDTLS_ECP_PF_XXX constant. + * \param format The export format. + * \param olen The length of the data written. + * \param buf The buffer to write to. + * \param blen The length of the buffer. * - * \return 0 if successful, - * or MBEDTLS_ERR_ECP_BAD_INPUT_DATA - * or MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA or + * #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure. */ int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt, int format, size_t *olen, unsigned char *buf, size_t blen ); /** - * \brief Set a group using well-known domain parameters + * \brief This function sets a group using standardized domain parameters. * - * \param grp Destination group - * \param id Index in the list of well-known domain parameters + * \note The index should be a value of the NamedCurve enum, + * as defined in RFC-4492: Elliptic Curve Cryptography + * (ECC) Cipher Suites for Transport Layer Security (TLS), + * usually in the form of an \c MBEDTLS_ECP_DP_XXX macro. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_XXX if initialization failed - * MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE for unkownn groups + * \param grp The destination group. + * \param id The identifier of the domain parameter set to load. * - * \note Index should be a value of RFC 4492's enum NamedCurve, - * usually in the form of a MBEDTLS_ECP_DP_XXX macro. + * \return \c 0 on success, + * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization failure. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE for unkownn groups. + */ int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id ); /** - * \brief Set a group from a TLS ECParameters record + * \brief This function sets a group from a TLS ECParameters record. * - * \param grp Destination group - * \param buf &(Start of input buffer) - * \param len Buffer length + * \note \p buf is updated to point right after the ECParameters record + * on exit. * - * \note buf is updated to point right after ECParameters on exit + * \param grp The destination group. + * \param buf The address of the pointer to the start of the input buffer. + * \param len The length of the buffer. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_XXX if initialization failed - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization failure. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. */ int mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp, const unsigned char **buf, size_t len ); /** - * \brief Write the TLS ECParameters record for a group + * \brief This function writes the TLS ECParameters record for a group. * - * \param grp ECP group used - * \param olen Number of bytes actually written - * \param buf Buffer to write to - * \param blen Buffer length + * \param grp The ECP group used. + * \param olen The number of Bytes written. + * \param buf The buffer to write to. + * \param blen The length of the buffer. * - * \return 0 if successful, - * or MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure. */ int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen, unsigned char *buf, size_t blen ); /** - * \brief Multiplication by an integer: R = m * P - * (Not thread-safe to use same group in multiple threads) + * \brief This function performs multiplication of a point by + * an integer: \p R = \p m * \p P. * - * \note In order to prevent timing attacks, this function - * executes the exact same sequence of (base field) - * operations for any valid m. It avoids any if-branch or - * array index depending on the value of m. + * It is not thread-safe to use same group in multiple threads. * - * \note If f_rng is not NULL, it is used to randomize intermediate - * results in order to prevent potential timing attacks - * targeting these results. It is recommended to always - * provide a non-NULL f_rng (the overhead is negligible). + * \note To prevent timing attacks, this function + * executes the exact same sequence of base-field + * operations for any valid \p m. It avoids any if-branch or + * array index depending on the value of \p m. * - * \param grp ECP group - * \param R Destination point - * \param m Integer by which to multiply - * \param P Point to multiply - * \param f_rng RNG function (see notes) - * \param p_rng RNG parameter + * \note If \p f_rng is not NULL, it is used to randomize + * intermediate results to prevent potential timing attacks + * targeting these results. We recommend always providing + * a non-NULL \p f_rng. The overhead is negligible. * - * \return 0 if successful, - * MBEDTLS_ERR_ECP_INVALID_KEY if m is not a valid privkey - * or P is not a valid pubkey, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \param grp The ECP group. + * \param R The destination point. + * \param m The integer by which to multiply. + * \param P The point to multiply. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private + * key, or \p P is not a valid public key. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** - * \brief Multiplication and addition of two points by integers: - * R = m * P + n * Q - * (Not thread-safe to use same group in multiple threads) + * \brief This function performs multiplication and addition of two + * points by integers: \p R = \p m * \p P + \p n * \p Q + * + * It is not thread-safe to use same group in multiple threads. * - * \note In contrast to mbedtls_ecp_mul(), this function does not guarantee - * a constant execution flow and timing. + * \note In contrast to mbedtls_ecp_mul(), this function does not + * guarantee a constant execution flow and timing. * - * \param grp ECP group - * \param R Destination point - * \param m Integer by which to multiply P - * \param P Point to multiply by m - * \param n Integer by which to multiply Q - * \param Q Point to be multiplied by n + * \param grp The ECP group. + * \param R The destination point. + * \param m The integer by which to multiply \p P. + * \param P The point to multiply by \p m. + * \param n The integer by which to multiply \p Q. + * \param Q The point to be multiplied by \p n. * - * \return 0 if successful, - * MBEDTLS_ERR_ECP_INVALID_KEY if m or n is not a valid privkey - * or P or Q is not a valid pubkey, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not + * valid private keys, or \p P or \p Q are not valid public + * keys. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, const mbedtls_mpi *n, const mbedtls_ecp_point *Q ); /** - * \brief Check that a point is a valid public key on this curve + * \brief This function checks that a point is a valid public key + * on this curve. * - * \param grp Curve/group the point should belong to - * \param pt Point to check + * It only checks that the point is non-zero, has + * valid coordinates and lies on the curve. It does not verify + * that it is indeed a multiple of \p G. This additional + * check is computationally more expensive, is not required + * by standards, and should not be necessary if the group + * used has a small cofactor. In particular, it is useless for + * the NIST groups which all have a cofactor of 1. * - * \return 0 if point is a valid public key, - * MBEDTLS_ERR_ECP_INVALID_KEY otherwise. + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure, to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. * - * \note This function only checks the point is non-zero, has valid - * coordinates and lies on the curve, but not that it is - * indeed a multiple of G. This is additional check is more - * expensive, isn't required by standards, and shouldn't be - * necessary if the group used has a small cofactor. In - * particular, it is useless for the NIST groups which all - * have a cofactor of 1. + * \param grp The curve the point should lie on. + * \param pt The point to check. * - * \note Uses bare components rather than an mbedtls_ecp_keypair structure - * in order to ease use with other structures such as - * mbedtls_ecdh_context of mbedtls_ecdsa_context. + * \return \c 0 if the point is a valid public key. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY on failure. */ int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt ); /** - * \brief Check that an mbedtls_mpi is a valid private key for this curve + * \brief This function checks that an \p mbedtls_mpi is a valid private + * key for this curve. * - * \param grp Group used - * \param d Integer to check + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. * - * \return 0 if point is a valid private key, - * MBEDTLS_ERR_ECP_INVALID_KEY otherwise. + * \param grp The group used. + * \param d The integer to check. * - * \note Uses bare components rather than an mbedtls_ecp_keypair structure - * in order to ease use with other structures such as - * mbedtls_ecdh_context of mbedtls_ecdsa_context. + * \return \c 0 if the point is a valid private key. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY on failure. */ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi *d ); /** - * \brief Generate a keypair with configurable base point + * \brief This function generates a keypair with a configurable base + * point. * - * \param grp ECP group - * \param G Chosen base point - * \param d Destination MPI (secret part) - * \param Q Destination point (public part) - * \param f_rng RNG function - * \param p_rng RNG parameter + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * \param grp The ECP group. + * \param G The chosen base point. + * \param d The destination MPI (secret part). + * \param Q The destination point (public part). + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \note Uses bare components rather than an mbedtls_ecp_keypair structure - * in order to ease use with other structures such as - * mbedtls_ecdh_context of mbedtls_ecdsa_context. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. */ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, const mbedtls_ecp_point *G, @@ -617,57 +692,66 @@ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, void *p_rng ); /** - * \brief Generate a keypair + * \brief This function generates an ECP keypair. * - * \param grp ECP group - * \param d Destination MPI (secret part) - * \param Q Destination point (public part) - * \param f_rng RNG function - * \param p_rng RNG parameter + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * \param grp The ECP group. + * \param d The destination MPI (secret part). + * \param Q The destination point (public part). + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \note Uses bare components rather than an mbedtls_ecp_keypair structure - * in order to ease use with other structures such as - * mbedtls_ecdh_context of mbedtls_ecdsa_context. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. */ int mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** - * \brief Generate a keypair + * \brief This function generates an ECP key. * - * \param grp_id ECP group identifier - * \param key Destination keypair - * \param f_rng RNG function - * \param p_rng RNG parameter + * \param grp_id The ECP group identifier. + * \param key The destination key. + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. */ int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** - * \brief Check a public-private key pair + * \brief This function checks that the keypair objects + * \p pub and \p prv have the same group and the + * same public point, and that the private key in + * \p prv is consistent with the public key. * - * \param pub Keypair structure holding a public key - * \param prv Keypair structure holding a private (plus public) key + * \param pub The keypair structure holding the public key. + * If it contains a private key, that part is ignored. + * \param prv The keypair structure holding the full keypair. * - * \return 0 if successful (keys are valid and match), or - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA, or - * a MBEDTLS_ERR_ECP_XXX or MBEDTLS_ERR_MPI_XXX code. + * \return \c 0 on success, meaning that the keys are valid and match. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the keys are invalid or do not match. + * \return An \c MBEDTLS_ERR_ECP_XXX or an \c MBEDTLS_ERR_MPI_XXX + * error code on calculation failure. */ int mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv ); #if defined(MBEDTLS_SELF_TEST) /** - * \brief Checkup routine + * \brief The ECP checkup routine. * - * \return 0 if successful, or 1 if a test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_ecp_self_test( int verbose ); @@ -677,8 +761,4 @@ int mbedtls_ecp_self_test( int verbose ); } #endif -#else /* MBEDTLS_ECP_ALT */ -#include "ecp_alt.h" -#endif /* MBEDTLS_ECP_ALT */ - #endif /* ecp.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/ecp_internal.h b/tools/sdk/include/mbedtls/mbedtls/ecp_internal.h index 2991e26dd9b..18040697adf 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ecp_internal.h +++ b/tools/sdk/include/mbedtls/mbedtls/ecp_internal.h @@ -3,7 +3,8 @@ * * \brief Function declarations for alternative implementation of elliptic curve * point arithmetic. - * + */ +/* * Copyright (C) 2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -47,7 +48,7 @@ * [6] Digital Signature Standard (DSS), FIPS 186-4. * * - * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer + * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer * Security (TLS), RFC 4492. * * diff --git a/tools/sdk/include/mbedtls/mbedtls/entropy.h b/tools/sdk/include/mbedtls/mbedtls/entropy.h index 747aca4dfaa..ca06dc3c58e 100644 --- a/tools/sdk/include/mbedtls/mbedtls/entropy.h +++ b/tools/sdk/include/mbedtls/mbedtls/entropy.h @@ -2,7 +2,8 @@ * \file entropy.h * * \brief Entropy accumulator implementation - * + */ +/* * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -106,7 +107,7 @@ typedef int (*mbedtls_entropy_f_source_ptr)(void *data, unsigned char *output, s /** * \brief Entropy source state */ -typedef struct +typedef struct mbedtls_entropy_source_state { mbedtls_entropy_f_source_ptr f_source; /**< The entropy source callback */ void * p_source; /**< The callback data pointer */ @@ -119,8 +120,9 @@ mbedtls_entropy_source_state; /** * \brief Entropy context structure */ -typedef struct +typedef struct mbedtls_entropy_context { + int accumulator_started; #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) mbedtls_sha512_context accumulator; #else @@ -164,7 +166,7 @@ void mbedtls_entropy_free( mbedtls_entropy_context *ctx ); * \param threshold Minimum required from source before entropy is released * ( with mbedtls_entropy_func() ) (in bytes) * \param strong MBEDTLS_ENTROPY_SOURCE_STRONG or - * MBEDTSL_ENTROPY_SOURCE_WEAK. + * MBEDTLS_ENTROPY_SOURCE_WEAK. * At least one strong source needs to be added. * Weaker sources (such as the cycle counter) can be used as * a complement. diff --git a/tools/sdk/include/mbedtls/mbedtls/entropy_poll.h b/tools/sdk/include/mbedtls/mbedtls/entropy_poll.h index 81258d5f396..94dd657eb95 100644 --- a/tools/sdk/include/mbedtls/mbedtls/entropy_poll.h +++ b/tools/sdk/include/mbedtls/mbedtls/entropy_poll.h @@ -2,7 +2,8 @@ * \file entropy_poll.h * * \brief Platform-specific and custom entropy polling functions - * + */ +/* * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/error.h b/tools/sdk/include/mbedtls/mbedtls/error.h index 31591e2d643..6b82d4fbbe8 100644 --- a/tools/sdk/include/mbedtls/mbedtls/error.h +++ b/tools/sdk/include/mbedtls/mbedtls/error.h @@ -2,8 +2,9 @@ * \file error.h * * \brief Error to string translation - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + */ +/* + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -49,23 +50,36 @@ * * Module Nr Codes assigned * MPI 7 0x0002-0x0010 - * GCM 2 0x0012-0x0014 - * BLOWFISH 2 0x0016-0x0018 + * GCM 3 0x0012-0x0014 0x0013-0x0013 + * BLOWFISH 3 0x0016-0x0018 0x0017-0x0017 * THREADING 3 0x001A-0x001E - * AES 2 0x0020-0x0022 - * CAMELLIA 2 0x0024-0x0026 - * XTEA 1 0x0028-0x0028 + * AES 5 0x0020-0x0022 0x0021-0x0025 + * CAMELLIA 3 0x0024-0x0026 0x0027-0x0027 + * XTEA 2 0x0028-0x0028 0x0029-0x0029 * BASE64 2 0x002A-0x002C * OID 1 0x002E-0x002E 0x000B-0x000B * PADLOCK 1 0x0030-0x0030 - * DES 1 0x0032-0x0032 + * DES 2 0x0032-0x0032 0x0033-0x0033 * CTR_DBRG 4 0x0034-0x003A * ENTROPY 3 0x003C-0x0040 0x003D-0x003F - * NET 11 0x0042-0x0052 0x0043-0x0045 + * NET 13 0x0042-0x0052 0x0043-0x0049 + * ARIA 4 0x0058-0x005E * ASN1 7 0x0060-0x006C + * CMAC 1 0x007A-0x007A * PBKDF2 1 0x007C-0x007C - * HMAC_DRBG 4 0x0003-0x0009 - * CCM 2 0x000D-0x000F + * HMAC_DRBG 4 0x0003-0x0009 + * CCM 3 0x000D-0x0011 + * ARC4 1 0x0019-0x0019 + * MD2 1 0x002B-0x002B + * MD4 1 0x002D-0x002D + * MD5 1 0x002F-0x002F + * RIPEMD160 1 0x0031-0x0031 + * SHA1 1 0x0035-0x0035 + * SHA256 1 0x0037-0x0037 + * SHA512 1 0x0039-0x0039 + * CHACHA20 3 0x0051-0x0055 + * POLY1305 3 0x0057-0x005B + * CHACHAPOLY 2 0x0054-0x0056 * * High-level module nr (3 bits - 0x0...-0x7...) * Name ID Nr of Errors @@ -73,13 +87,14 @@ * PKCS#12 1 4 (Started from top) * X509 2 20 * PKCS5 2 4 (Started from top) - * DHM 3 9 - * PK 3 14 (Started from top) - * RSA 4 9 - * ECP 4 8 (Started from top) - * MD 5 4 - * CIPHER 6 6 - * SSL 6 17 (Started from top) + * DHM 3 11 + * PK 3 15 (Started from top) + * RSA 4 11 + * ECP 4 9 (Started from top) + * MD 5 5 + * HKDF 5 1 (Started from top) + * CIPHER 6 8 + * SSL 6 22 (Started from top) * SSL 7 31 * * Module dependent error code (5 bits 0x.00.-0x.F8.) diff --git a/tools/sdk/include/mbedtls_port/mbedtls/esp_config.h b/tools/sdk/include/mbedtls/mbedtls/esp_config.h similarity index 97% rename from tools/sdk/include/mbedtls_port/mbedtls/esp_config.h rename to tools/sdk/include/mbedtls/mbedtls/esp_config.h index c81bf1a06e2..89cdef8927c 100644 --- a/tools/sdk/include/mbedtls_port/mbedtls/esp_config.h +++ b/tools/sdk/include/mbedtls/mbedtls/esp_config.h @@ -114,7 +114,14 @@ * * Enable this layer to allow use of alternative memory allocators. */ -//#define MBEDTLS_PLATFORM_MEMORY +#define MBEDTLS_PLATFORM_MEMORY + +/** Override calloc(), free() except for case where memory allocation scheme is not set to custom */ +#ifndef CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC +#include "esp_mem.h" +#define MBEDTLS_PLATFORM_STD_CALLOC esp_mbedtls_mem_calloc +#define MBEDTLS_PLATFORM_STD_FREE esp_mbedtls_mem_free +#endif /** * \def MBEDTLS_PLATFORM_NO_STD_FUNCTIONS @@ -355,6 +362,13 @@ */ #define MBEDTLS_CIPHER_MODE_CTR +/** + * \def MBEDTLS_CIPHER_MODE_XTS + * + * Enable Xor-encrypt-xor with ciphertext stealing mode (XTS) for AES. + */ +#define MBEDTLS_CIPHER_MODE_XTS + /** * \def MBEDTLS_CIPHER_NULL_CIPHER * @@ -2609,8 +2623,46 @@ //#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */ /* SSL options */ +#ifndef CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN #define MBEDTLS_SSL_MAX_CONTENT_LEN CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN /**< Maxium fragment length in bytes, determines the size of each of the two internal I/O buffers */ + +#else + +/** \def MBEDTLS_SSL_IN_CONTENT_LEN + * + * Maximum incoming fragment length in bytes. + * + * Uncomment to set the size of the inward TLS buffer independently of the + * outward buffer. + */ +#define MBEDTLS_SSL_IN_CONTENT_LEN CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN + +/** \def MBEDTLS_SSL_OUT_CONTENT_LEN + * + * Maximum outgoing fragment length in bytes. + * + * Uncomment to set the size of the outward TLS buffer independently of the + * inward buffer. + * + * It is possible to save RAM by setting a smaller outward buffer, while keeping + * the default inward 16384 byte buffer to conform to the TLS specification. + * + * The minimum required outward buffer size is determined by the handshake + * protocol's usage. Handshaking will fail if the outward buffer is too small. + * The specific size requirement depends on the configured ciphers and any + * certificate data which is sent during the handshake. + * + * For absolute minimum RAM usage, it's best to enable + * MBEDTLS_SSL_MAX_FRAGMENT_LENGTH and reduce MBEDTLS_SSL_MAX_CONTENT_LEN. This + * reduces both incoming and outgoing buffer sizes. However this is only + * guaranteed if the other end of the connection also supports the TLS + * max_fragment_len extension. Otherwise the connection may fail. + */ +#define MBEDTLS_SSL_OUT_CONTENT_LEN CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN + +#endif /* !CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN */ + //#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME 86400 /**< Lifetime of session tickets (if enabled) */ //#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */ //#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ diff --git a/tools/sdk/include/mbedtls_port/mbedtls/esp_debug.h b/tools/sdk/include/mbedtls/mbedtls/esp_debug.h similarity index 100% rename from tools/sdk/include/mbedtls_port/mbedtls/esp_debug.h rename to tools/sdk/include/mbedtls/mbedtls/esp_debug.h diff --git a/tools/sdk/include/mbedtls/mbedtls/gcm.h b/tools/sdk/include/mbedtls/mbedtls/gcm.h index 1b77aaedd48..d2098eb9f90 100644 --- a/tools/sdk/include/mbedtls/mbedtls/gcm.h +++ b/tools/sdk/include/mbedtls/mbedtls/gcm.h @@ -1,9 +1,18 @@ /** * \file gcm.h * - * \brief Galois/Counter mode for 128-bit block ciphers + * \brief This file contains GCM definitions and functions. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * The Galois/Counter Mode (GCM) for 128-bit block ciphers is defined + * in D. McGrew, J. Viega, The Galois/Counter Mode of Operation + * (GCM), Natl. Inst. Stand. Technol. + * + * For more information on GCM, see NIST SP 800-38D: Recommendation for + * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC. + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +27,9 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_GCM_H #define MBEDTLS_GCM_H @@ -31,46 +41,65 @@ #define MBEDTLS_GCM_DECRYPT 0 #define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */ +#define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED -0x0013 /**< GCM hardware accelerator failed. */ #define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_GCM_ALT) + /** - * \brief GCM context structure + * \brief The GCM context structure. */ -typedef struct { - mbedtls_cipher_context_t cipher_ctx;/*!< cipher context used */ - uint64_t HL[16]; /*!< Precalculated HTable */ - uint64_t HH[16]; /*!< Precalculated HTable */ - uint64_t len; /*!< Total data length */ - uint64_t add_len; /*!< Total add length */ - unsigned char base_ectr[16];/*!< First ECTR for tag */ - unsigned char y[16]; /*!< Y working value */ - unsigned char buf[16]; /*!< buf working value */ - int mode; /*!< Encrypt or Decrypt */ +typedef struct mbedtls_gcm_context +{ + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ + uint64_t HL[16]; /*!< Precalculated HTable low. */ + uint64_t HH[16]; /*!< Precalculated HTable high. */ + uint64_t len; /*!< The total length of the encrypted data. */ + uint64_t add_len; /*!< The total length of the additional data. */ + unsigned char base_ectr[16]; /*!< The first ECTR for tag. */ + unsigned char y[16]; /*!< The Y working value. */ + unsigned char buf[16]; /*!< The buf working value. */ + int mode; /*!< The operation to perform: + #MBEDTLS_GCM_ENCRYPT or + #MBEDTLS_GCM_DECRYPT. */ } mbedtls_gcm_context; +#else /* !MBEDTLS_GCM_ALT */ +#include "gcm_alt.h" +#endif /* !MBEDTLS_GCM_ALT */ + /** - * \brief Initialize GCM context (just makes references valid) - * Makes the context ready for mbedtls_gcm_setkey() or - * mbedtls_gcm_free(). + * \brief This function initializes the specified GCM context, + * to make references valid, and prepares the context + * for mbedtls_gcm_setkey() or mbedtls_gcm_free(). + * + * The function does not bind the GCM context to a particular + * cipher, nor set the key. For this purpose, use + * mbedtls_gcm_setkey(). * - * \param ctx GCM context to initialize + * \param ctx The GCM context to initialize. */ void mbedtls_gcm_init( mbedtls_gcm_context *ctx ); /** - * \brief GCM initialization (encryption) + * \brief This function associates a GCM context with a + * cipher algorithm and a key. * - * \param ctx GCM context to be initialized - * \param cipher cipher to use (a 128-bit block cipher) - * \param key encryption key - * \param keybits must be 128, 192 or 256 + * \param ctx The GCM context to initialize. + * \param cipher The 128-bit block cipher to use. + * \param key The encryption key. + * \param keybits The key size in bits. Valid options are: + *
  • 128 bits
  • + *
  • 192 bits
  • + *
  • 256 bits
* - * \return 0 if successful, or a cipher specific error code + * \return \c 0 on success. + * \return A cipher-specific error code on failure. */ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, mbedtls_cipher_id_t cipher, @@ -78,26 +107,48 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, unsigned int keybits ); /** - * \brief GCM buffer encryption/decryption using a block cipher - * - * \note On encryption, the output buffer can be the same as the input buffer. - * On decryption, the output buffer cannot be the same as input buffer. - * If buffers overlap, the output buffer must trail at least 8 bytes - * behind the input buffer. - * - * \param ctx GCM context - * \param mode MBEDTLS_GCM_ENCRYPT or MBEDTLS_GCM_DECRYPT - * \param length length of the input data - * \param iv initialization vector - * \param iv_len length of IV - * \param add additional data - * \param add_len length of additional data - * \param input buffer holding the input data - * \param output buffer for holding the output data - * \param tag_len length of the tag to generate - * \param tag buffer for holding the tag - * - * \return 0 if successful + * \brief This function performs GCM encryption or decryption of a buffer. + * + * \note For encryption, the output buffer can be the same as the + * input buffer. For decryption, the output buffer cannot be + * the same as input buffer. If the buffers overlap, the output + * buffer must trail at least 8 Bytes behind the input buffer. + * + * \warning When this function performs a decryption, it outputs the + * authentication tag and does not verify that the data is + * authentic. You should use this function to perform encryption + * only. For decryption, use mbedtls_gcm_auth_decrypt() instead. + * + * \param ctx The GCM context to use for encryption or decryption. + * \param mode The operation to perform: + * - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption. + * The ciphertext is written to \p output and the + * authentication tag is written to \p tag. + * - #MBEDTLS_GCM_DECRYPT to perform decryption. + * The plaintext is written to \p output and the + * authentication tag is written to \p tag. + * Note that this mode is not recommended, because it does + * not verify the authenticity of the data. For this reason, + * you should use mbedtls_gcm_auth_decrypt() instead of + * calling this function in decryption mode. + * \param length The length of the input data, which is equal to the length + * of the output data. + * \param iv The initialization vector. + * \param iv_len The length of the IV. + * \param add The buffer holding the additional data. + * \param add_len The length of the additional data. + * \param input The buffer holding the input data. Its size is \b length. + * \param output The buffer for holding the output data. It must have room + * for \b length bytes. + * \param tag_len The length of the tag to generate. + * \param tag The buffer for holding the tag. + * + * \return \c 0 if the encryption or decryption was performed + * successfully. Note that in #MBEDTLS_GCM_DECRYPT mode, + * this does not indicate that the data is authentic. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid. + * \return #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific + * error code if the encryption or decryption failed. */ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, int mode, @@ -112,25 +163,31 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, unsigned char *tag ); /** - * \brief GCM buffer authenticated decryption using a block cipher - * - * \note On decryption, the output buffer cannot be the same as input buffer. - * If buffers overlap, the output buffer must trail at least 8 bytes - * behind the input buffer. - * - * \param ctx GCM context - * \param length length of the input data - * \param iv initialization vector - * \param iv_len length of IV - * \param add additional data - * \param add_len length of additional data - * \param tag buffer holding the tag - * \param tag_len length of the tag - * \param input buffer holding the input data - * \param output buffer for holding the output data - * - * \return 0 if successful and authenticated, - * MBEDTLS_ERR_GCM_AUTH_FAILED if tag does not match + * \brief This function performs a GCM authenticated decryption of a + * buffer. + * + * \note For decryption, the output buffer cannot be the same as + * input buffer. If the buffers overlap, the output buffer + * must trail at least 8 Bytes behind the input buffer. + * + * \param ctx The GCM context. + * \param length The length of the ciphertext to decrypt, which is also + * the length of the decrypted plaintext. + * \param iv The initialization vector. + * \param iv_len The length of the IV. + * \param add The buffer holding the additional data. + * \param add_len The length of the additional data. + * \param tag The buffer holding the tag to verify. + * \param tag_len The length of the tag to verify. + * \param input The buffer holding the ciphertext. Its size is \b length. + * \param output The buffer for holding the decrypted plaintext. It must + * have room for \b length bytes. + * + * \return \c 0 if successful and authenticated. + * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid. + * \return #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific + * error code if the decryption failed. */ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, size_t length, @@ -144,16 +201,20 @@ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, unsigned char *output ); /** - * \brief Generic GCM stream start function + * \brief This function starts a GCM encryption or decryption + * operation. * - * \param ctx GCM context - * \param mode MBEDTLS_GCM_ENCRYPT or MBEDTLS_GCM_DECRYPT - * \param iv initialization vector - * \param iv_len length of IV - * \param add additional data (or NULL if length is 0) - * \param add_len length of additional data + * \param ctx The GCM context. + * \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or + * #MBEDTLS_GCM_DECRYPT. + * \param iv The initialization vector. + * \param iv_len The length of the IV. + * \param add The buffer holding the additional data, or NULL + * if \p add_len is 0. + * \param add_len The length of the additional data. If 0, + * \p add is NULL. * - * \return 0 if successful + * \return \c 0 on success. */ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx, int mode, @@ -163,21 +224,25 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx, size_t add_len ); /** - * \brief Generic GCM update function. Encrypts/decrypts using the - * given GCM context. Expects input to be a multiple of 16 - * bytes! Only the last call before mbedtls_gcm_finish() can be less - * than 16 bytes! + * \brief This function feeds an input buffer into an ongoing GCM + * encryption or decryption operation. + * + * ` The function expects input to be a multiple of 16 + * Bytes. Only the last call before calling + * mbedtls_gcm_finish() can be less than 16 Bytes. * - * \note On decryption, the output buffer cannot be the same as input buffer. - * If buffers overlap, the output buffer must trail at least 8 bytes - * behind the input buffer. + * \note For decryption, the output buffer cannot be the same as + * input buffer. If the buffers overlap, the output buffer + * must trail at least 8 Bytes behind the input buffer. * - * \param ctx GCM context - * \param length length of the input data - * \param input buffer holding the input data - * \param output buffer for holding the output data + * \param ctx The GCM context. + * \param length The length of the input data. This must be a multiple of + * 16 except in the last call before mbedtls_gcm_finish(). + * \param input The buffer holding the input data. + * \param output The buffer for holding the output data. * - * \return 0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT + * \return \c 0 on success. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. */ int mbedtls_gcm_update( mbedtls_gcm_context *ctx, size_t length, @@ -185,31 +250,36 @@ int mbedtls_gcm_update( mbedtls_gcm_context *ctx, unsigned char *output ); /** - * \brief Generic GCM finalisation function. Wraps up the GCM stream - * and generates the tag. The tag can have a maximum length of - * 16 bytes. + * \brief This function finishes the GCM operation and generates + * the authentication tag. * - * \param ctx GCM context - * \param tag buffer for holding the tag - * \param tag_len length of the tag to generate (must be at least 4) + * It wraps up the GCM stream, and generates the + * tag. The tag can have a maximum length of 16 Bytes. * - * \return 0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT + * \param ctx The GCM context. + * \param tag The buffer for holding the tag. + * \param tag_len The length of the tag to generate. Must be at least four. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. */ int mbedtls_gcm_finish( mbedtls_gcm_context *ctx, unsigned char *tag, size_t tag_len ); /** - * \brief Free a GCM context and underlying cipher sub-context + * \brief This function clears a GCM context and the underlying + * cipher sub-context. * - * \param ctx GCM context to free + * \param ctx The GCM context to clear. */ void mbedtls_gcm_free( mbedtls_gcm_context *ctx ); /** - * \brief Checkup routine + * \brief The GCM checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_gcm_self_test( int verbose ); @@ -217,4 +287,5 @@ int mbedtls_gcm_self_test( int verbose ); } #endif + #endif /* gcm.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/havege.h b/tools/sdk/include/mbedtls/mbedtls/havege.h index dac5d311381..57e8c409431 100644 --- a/tools/sdk/include/mbedtls/mbedtls/havege.h +++ b/tools/sdk/include/mbedtls/mbedtls/havege.h @@ -2,7 +2,8 @@ * \file havege.h * * \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -34,7 +35,7 @@ extern "C" { /** * \brief HAVEGE state structure */ -typedef struct +typedef struct mbedtls_havege_state { int PT1, PT2, offset[2]; int pool[MBEDTLS_HAVEGE_COLLECT_SIZE]; diff --git a/tools/sdk/include/mbedtls/mbedtls/hkdf.h b/tools/sdk/include/mbedtls/mbedtls/hkdf.h new file mode 100644 index 00000000000..e6ed7cde97c --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/hkdf.h @@ -0,0 +1,135 @@ +/** + * \file hkdf.h + * + * \brief This file contains the HKDF interface. + * + * The HMAC-based Extract-and-Expand Key Derivation Function (HKDF) is + * specified by RFC 5869. + */ +/* + * Copyright (C) 2016-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_HKDF_H +#define MBEDTLS_HKDF_H + +#include "md.h" + +/** + * \name HKDF Error codes + * \{ + */ +#define MBEDTLS_ERR_HKDF_BAD_INPUT_DATA -0x5F80 /**< Bad input parameters to function. */ +/* \} name */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief This is the HMAC-based Extract-and-Expand Key Derivation Function + * (HKDF). + * + * \param md A hash function; md.size denotes the length of the hash + * function output in bytes. + * \param salt An optional salt value (a non-secret random value); + * if the salt is not provided, a string of all zeros of + * md.size length is used as the salt. + * \param salt_len The length in bytes of the optional \p salt. + * \param ikm The input keying material. + * \param ikm_len The length in bytes of \p ikm. + * \param info An optional context and application specific information + * string. This can be a zero-length string. + * \param info_len The length of \p info in bytes. + * \param okm The output keying material of \p okm_len bytes. + * \param okm_len The length of the output keying material in bytes. This + * must be less than or equal to 255 * md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt, + size_t salt_len, const unsigned char *ikm, size_t ikm_len, + const unsigned char *info, size_t info_len, + unsigned char *okm, size_t okm_len ); + +/** + * \brief Take the input keying material \p ikm and extract from it a + * fixed-length pseudorandom key \p prk. + * + * \warning This function should only be used if the security of it has been + * studied and established in that particular context (eg. TLS 1.3 + * key schedule). For standard HKDF security guarantees use + * \c mbedtls_hkdf instead. + * + * \param md A hash function; md.size denotes the length of the + * hash function output in bytes. + * \param salt An optional salt value (a non-secret random value); + * if the salt is not provided, a string of all zeros + * of md.size length is used as the salt. + * \param salt_len The length in bytes of the optional \p salt. + * \param ikm The input keying material. + * \param ikm_len The length in bytes of \p ikm. + * \param[out] prk A pseudorandom key of at least md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf_extract( const mbedtls_md_info_t *md, + const unsigned char *salt, size_t salt_len, + const unsigned char *ikm, size_t ikm_len, + unsigned char *prk ); + +/** + * \brief Expand the supplied \p prk into several additional pseudorandom + * keys, which is the output of the HKDF. + * + * \warning This function should only be used if the security of it has been + * studied and established in that particular context (eg. TLS 1.3 + * key schedule). For standard HKDF security guarantees use + * \c mbedtls_hkdf instead. + * + * \param md A hash function; md.size denotes the length of the hash + * function output in bytes. + * \param prk A pseudorandom key of at least md.size bytes. \p prk is + * usually the output from the HKDF extract step. + * \param prk_len The length in bytes of \p prk. + * \param info An optional context and application specific information + * string. This can be a zero-length string. + * \param info_len The length of \p info in bytes. + * \param okm The output keying material of \p okm_len bytes. + * \param okm_len The length of the output keying material in bytes. This + * must be less than or equal to 255 * md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk, + size_t prk_len, const unsigned char *info, + size_t info_len, unsigned char *okm, size_t okm_len ); + +#ifdef __cplusplus +} +#endif + +#endif /* hkdf.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/hmac_drbg.h b/tools/sdk/include/mbedtls/mbedtls/hmac_drbg.h index e0105580287..3bc675ec7c7 100644 --- a/tools/sdk/include/mbedtls/mbedtls/hmac_drbg.h +++ b/tools/sdk/include/mbedtls/mbedtls/hmac_drbg.h @@ -2,7 +2,8 @@ * \file hmac_drbg.h * * \brief HMAC_DRBG (NIST SP 800-90A) - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -26,7 +27,7 @@ #include "md.h" #if defined(MBEDTLS_THREADING_C) -#include "mbedtls/threading.h" +#include "threading.h" #endif /* @@ -73,7 +74,7 @@ extern "C" { /** * HMAC_DRBG context. */ -typedef struct +typedef struct mbedtls_hmac_drbg_context { /* Working state: the key K is not stored explicitely, * but is implied by the HMAC context */ diff --git a/tools/sdk/include/mbedtls/mbedtls/md.h b/tools/sdk/include/mbedtls/mbedtls/md.h index 9b996a951bb..bf29524983c 100644 --- a/tools/sdk/include/mbedtls/mbedtls/md.h +++ b/tools/sdk/include/mbedtls/mbedtls/md.h @@ -1,11 +1,12 @@ -/** + /** * \file md.h * - * \brief Generic message digest wrapper + * \brief This file contains the generic message-digest wrapper. * * \author Adriaan de Jong - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -20,33 +21,49 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_MD_H #define MBEDTLS_MD_H #include +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + #define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /**< The selected feature is not available. */ #define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */ #define MBEDTLS_ERR_MD_FILE_IO_ERROR -0x5200 /**< Opening or reading of file failed. */ +#define MBEDTLS_ERR_MD_HW_ACCEL_FAILED -0x5280 /**< MD hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif +/** + * \brief Supported message digests. + * + * \warning MD2, MD4, MD5 and SHA-1 are considered weak message digests and + * their use constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ typedef enum { - MBEDTLS_MD_NONE=0, - MBEDTLS_MD_MD2, - MBEDTLS_MD_MD4, - MBEDTLS_MD_MD5, - MBEDTLS_MD_SHA1, - MBEDTLS_MD_SHA224, - MBEDTLS_MD_SHA256, - MBEDTLS_MD_SHA384, - MBEDTLS_MD_SHA512, - MBEDTLS_MD_RIPEMD160, + MBEDTLS_MD_NONE=0, /**< None. */ + MBEDTLS_MD_MD2, /**< The MD2 message digest. */ + MBEDTLS_MD_MD4, /**< The MD4 message digest. */ + MBEDTLS_MD_MD5, /**< The MD5 message digest. */ + MBEDTLS_MD_SHA1, /**< The SHA-1 message digest. */ + MBEDTLS_MD_SHA224, /**< The SHA-224 message digest. */ + MBEDTLS_MD_SHA256, /**< The SHA-256 message digest. */ + MBEDTLS_MD_SHA384, /**< The SHA-384 message digest. */ + MBEDTLS_MD_SHA512, /**< The SHA-512 message digest. */ + MBEDTLS_MD_RIPEMD160, /**< The RIPEMD-160 message digest. */ } mbedtls_md_type_t; #if defined(MBEDTLS_SHA512_C) @@ -56,65 +73,80 @@ typedef enum { #endif /** - * Opaque struct defined in md_internal.h + * Opaque struct defined in md_internal.h. */ typedef struct mbedtls_md_info_t mbedtls_md_info_t; /** - * Generic message digest context. + * The generic message-digest context. */ -typedef struct { - /** Information about the associated message digest */ +typedef struct mbedtls_md_context_t +{ + /** Information about the associated message digest. */ const mbedtls_md_info_t *md_info; - /** Digest-specific context */ + /** The digest-specific context. */ void *md_ctx; - /** HMAC part of the context */ + /** The HMAC part of the context. */ void *hmac_ctx; } mbedtls_md_context_t; /** - * \brief Returns the list of digests supported by the generic digest module. + * \brief This function returns the list of digests supported by the + * generic digest module. * - * \return a statically allocated array of digests, the last entry - * is 0. + * \return A statically allocated array of digests. Each element + * in the returned list is an integer belonging to the + * message-digest enumeration #mbedtls_md_type_t. + * The last entry is 0. */ const int *mbedtls_md_list( void ); /** - * \brief Returns the message digest information associated with the - * given digest name. + * \brief This function returns the message-digest information + * associated with the given digest name. * - * \param md_name Name of the digest to search for. + * \param md_name The name of the digest to search for. * - * \return The message digest information associated with md_name or - * NULL if not found. + * \return The message-digest information associated with \p md_name. + * \return NULL if the associated message-digest information is not found. */ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name ); /** - * \brief Returns the message digest information associated with the - * given digest type. + * \brief This function returns the message-digest information + * associated with the given digest type. * - * \param md_type type of digest to search for. + * \param md_type The type of digest to search for. * - * \return The message digest information associated with md_type or - * NULL if not found. + * \return The message-digest information associated with \p md_type. + * \return NULL if the associated message-digest information is not found. */ const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type ); /** - * \brief Initialize a md_context (as NONE) - * This should always be called first. - * Prepares the context for mbedtls_md_setup() or mbedtls_md_free(). + * \brief This function initializes a message-digest context without + * binding it to a particular message-digest algorithm. + * + * This function should always be called first. It prepares the + * context for mbedtls_md_setup() for binding it to a + * message-digest algorithm. */ void mbedtls_md_init( mbedtls_md_context_t *ctx ); /** - * \brief Free and clear the internal structures of ctx. - * Can be called at any time after mbedtls_md_init(). - * Mandatory once mbedtls_md_setup() has been called. + * \brief This function clears the internal structure of \p ctx and + * frees any embedded internal structure, but does not free + * \p ctx itself. + * + * If you have called mbedtls_md_setup() on \p ctx, you must + * call mbedtls_md_free() when you are no longer using the + * context. + * Calling this function if you have previously + * called mbedtls_md_init() and nothing else is optional. + * You must not call this function if you have not called + * mbedtls_md_init(). */ void mbedtls_md_free( mbedtls_md_context_t *ctx ); @@ -125,220 +157,300 @@ void mbedtls_md_free( mbedtls_md_context_t *ctx ); #define MBEDTLS_DEPRECATED #endif /** - * \brief Select MD to use and allocate internal structures. - * Should be called after mbedtls_md_init() or mbedtls_md_free(). + * \brief This function selects the message digest algorithm to use, + * and allocates internal structures. + * + * It should be called after mbedtls_md_init() or mbedtls_md_free(). * Makes it necessary to call mbedtls_md_free() later. * * \deprecated Superseded by mbedtls_md_setup() in 2.0.0 * - * \param ctx Context to set up. - * \param md_info Message digest to use. + * \param ctx The context to set up. + * \param md_info The information structure of the message-digest algorithm + * to use. * - * \returns \c 0 on success, - * \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure, - * \c MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED; #undef MBEDTLS_DEPRECATED #endif /* MBEDTLS_DEPRECATED_REMOVED */ /** - * \brief Select MD to use and allocate internal structures. - * Should be called after mbedtls_md_init() or mbedtls_md_free(). - * Makes it necessary to call mbedtls_md_free() later. - * - * \param ctx Context to set up. - * \param md_info Message digest to use. - * \param hmac 0 to save some memory if HMAC will not be used, - * non-zero is HMAC is going to be used with this context. - * - * \returns \c 0 on success, - * \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure, - * \c MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure. + * \brief This function selects the message digest algorithm to use, + * and allocates internal structures. + * + * It should be called after mbedtls_md_init() or + * mbedtls_md_free(). Makes it necessary to call + * mbedtls_md_free() later. + * + * \param ctx The context to set up. + * \param md_info The information structure of the message-digest algorithm + * to use. + * \param hmac Defines if HMAC is used. 0: HMAC is not used (saves some memory), + * or non-zero: HMAC is used with this context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac ); /** - * \brief Clone the state of an MD context + * \brief This function clones the state of an message-digest + * context. + * + * \note You must call mbedtls_md_setup() on \c dst before calling + * this function. * - * \note The two contexts must have been setup to the same type - * (cloning from SHA-256 to SHA-512 make no sense). + * \note The two contexts must have the same type, + * for example, both are SHA-256. * - * \warning Only clones the MD state, not the HMAC state! (for now) + * \warning This function clones the message-digest state, not the + * HMAC state. * - * \param dst The destination context - * \param src The context to be cloned + * \param dst The destination context. + * \param src The context to be cloned. * - * \return \c 0 on success, - * \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification failure. */ int mbedtls_md_clone( mbedtls_md_context_t *dst, const mbedtls_md_context_t *src ); /** - * \brief Returns the size of the message digest output. + * \brief This function extracts the message-digest size from the + * message-digest information structure. * - * \param md_info message digest info + * \param md_info The information structure of the message-digest algorithm + * to use. * - * \return size of the message digest output in bytes. + * \return The size of the message-digest output in Bytes. */ unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info ); /** - * \brief Returns the type of the message digest output. + * \brief This function extracts the message-digest type from the + * message-digest information structure. * - * \param md_info message digest info + * \param md_info The information structure of the message-digest algorithm + * to use. * - * \return type of the message digest output. + * \return The type of the message digest. */ mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info ); /** - * \brief Returns the name of the message digest output. + * \brief This function extracts the message-digest name from the + * message-digest information structure. * - * \param md_info message digest info + * \param md_info The information structure of the message-digest algorithm + * to use. * - * \return name of the message digest output. + * \return The name of the message digest. */ const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info ); /** - * \brief Prepare the context to digest a new message. - * Generally called after mbedtls_md_setup() or mbedtls_md_finish(). - * Followed by mbedtls_md_update(). + * \brief This function starts a message-digest computation. * - * \param ctx generic message digest context. + * You must call this function after setting up the context + * with mbedtls_md_setup(), and before passing data with + * mbedtls_md_update(). * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \param ctx The generic message-digest context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_starts( mbedtls_md_context_t *ctx ); /** - * \brief Generic message digest process buffer - * Called between mbedtls_md_starts() and mbedtls_md_finish(). - * May be called repeatedly. + * \brief This function feeds an input buffer into an ongoing + * message-digest computation. + * + * You must call mbedtls_md_starts() before calling this + * function. You may call this function multiple times. + * Afterwards, call mbedtls_md_finish(). * - * \param ctx Generic message digest context - * \param input buffer holding the datal - * \param ilen length of the input data + * \param ctx The generic message-digest context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ); /** - * \brief Generic message digest final digest - * Called after mbedtls_md_update(). - * Usually followed by mbedtls_md_free() or mbedtls_md_starts(). - * - * \param ctx Generic message digest context - * \param output Generic message digest checksum result - * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \brief This function finishes the digest operation, + * and writes the result to the output buffer. + * + * Call this function after a call to mbedtls_md_starts(), + * followed by any number of calls to mbedtls_md_update(). + * Afterwards, you may either clear the context with + * mbedtls_md_free(), or call mbedtls_md_starts() to reuse + * the context for another digest operation with the same + * algorithm. + * + * \param ctx The generic message-digest context. + * \param output The buffer for the generic message-digest checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output ); /** - * \brief Output = message_digest( input buffer ) - * - * \param md_info message digest info - * \param input buffer holding the data - * \param ilen length of the input data - * \param output Generic message digest checksum result - * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \brief This function calculates the message-digest of a buffer, + * with respect to a configurable message-digest algorithm + * in a single call. + * + * The result is calculated as + * Output = message_digest(input buffer). + * + * \param md_info The information structure of the message-digest algorithm + * to use. + * \param input The buffer holding the data. + * \param ilen The length of the input data. + * \param output The generic message-digest checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen, unsigned char *output ); #if defined(MBEDTLS_FS_IO) /** - * \brief Output = message_digest( file contents ) + * \brief This function calculates the message-digest checksum + * result of the contents of the provided file. * - * \param md_info message digest info - * \param path input file name - * \param output generic message digest checksum result + * The result is calculated as + * Output = message_digest(file contents). * - * \return 0 if successful, - * MBEDTLS_ERR_MD_FILE_IO_ERROR if file input failed, - * MBEDTLS_ERR_MD_BAD_INPUT_DATA if md_info was NULL. + * \param md_info The information structure of the message-digest algorithm + * to use. + * \param path The input file name. + * \param output The generic message-digest checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_FILE_IO_ERROR on an I/O error accessing + * the file pointed by \p path. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL. */ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigned char *output ); #endif /* MBEDTLS_FS_IO */ /** - * \brief Set HMAC key and prepare to authenticate a new message. - * Usually called after mbedtls_md_setup() or mbedtls_md_hmac_finish(). - * - * \param ctx HMAC context - * \param key HMAC secret key - * \param keylen length of the HMAC key in bytes - * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \brief This function sets the HMAC key and prepares to + * authenticate a new message. + * + * Call this function after mbedtls_md_setup(), to use + * the MD context for an HMAC calculation, then call + * mbedtls_md_hmac_update() to provide the input data, and + * mbedtls_md_hmac_finish() to get the HMAC value. + * + * \param ctx The message digest context containing an embedded HMAC + * context. + * \param key The HMAC secret key. + * \param keylen The length of the HMAC key in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen ); /** - * \brief Generic HMAC process buffer. - * Called between mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset() - * and mbedtls_md_hmac_finish(). - * May be called repeatedly. - * - * \param ctx HMAC context - * \param input buffer holding the data - * \param ilen length of the input data - * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \brief This function feeds an input buffer into an ongoing HMAC + * computation. + * + * Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset() + * before calling this function. + * You may call this function multiple times to pass the + * input piecewise. + * Afterwards, call mbedtls_md_hmac_finish(). + * + * \param ctx The message digest context containing an embedded HMAC + * context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ); /** - * \brief Output HMAC. - * Called after mbedtls_md_hmac_update(). - * Usually followed by mbedtls_md_hmac_reset(), - * mbedtls_md_hmac_starts(), or mbedtls_md_free(). - * - * \param ctx HMAC context - * \param output Generic HMAC checksum result - * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \brief This function finishes the HMAC operation, and writes + * the result to the output buffer. + * + * Call this function after mbedtls_md_hmac_starts() and + * mbedtls_md_hmac_update() to get the HMAC value. Afterwards + * you may either call mbedtls_md_free() to clear the context, + * or call mbedtls_md_hmac_reset() to reuse the context with + * the same HMAC key. + * + * \param ctx The message digest context containing an embedded HMAC + * context. + * \param output The generic HMAC checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output); /** - * \brief Prepare to authenticate a new message with the same key. - * Called after mbedtls_md_hmac_finish() and before - * mbedtls_md_hmac_update(). + * \brief This function prepares to authenticate a new message with + * the same key as the previous HMAC operation. + * + * You may call this function after mbedtls_md_hmac_finish(). + * Afterwards call mbedtls_md_hmac_update() to pass the new + * input. * - * \param ctx HMAC context to be reset + * \param ctx The message digest context containing an embedded HMAC + * context. * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx ); /** - * \brief Output = Generic_HMAC( hmac key, input buffer ) - * - * \param md_info message digest info - * \param key HMAC secret key - * \param keylen length of the HMAC key in bytes - * \param input buffer holding the data - * \param ilen length of the input data - * \param output Generic HMAC-result - * - * \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. + * \brief This function calculates the full generic HMAC + * on the input buffer with the provided key. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The HMAC result is calculated as + * output = generic HMAC(hmac key, input buffer). + * + * \param md_info The information structure of the message-digest algorithm + * to use. + * \param key The HMAC secret key. + * \param keylen The length of the HMAC secret key in Bytes. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The generic HMAC result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen, const unsigned char *input, size_t ilen, diff --git a/tools/sdk/include/mbedtls/mbedtls/md2.h b/tools/sdk/include/mbedtls/mbedtls/md2.h index 0f93fbf427d..a46bddb74b1 100644 --- a/tools/sdk/include/mbedtls/mbedtls/md2.h +++ b/tools/sdk/include/mbedtls/mbedtls/md2.h @@ -3,6 +3,11 @@ * * \brief MD2 message digest algorithm (hash function) * + * \warning MD2 is considered a weak message digest and its use constitutes a + * security risk. We recommend considering stronger message digests + * instead. + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -19,6 +24,7 @@ * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) + * */ #ifndef MBEDTLS_MD2_H #define MBEDTLS_MD2_H @@ -31,18 +37,25 @@ #include -#if !defined(MBEDTLS_MD2_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_MD2_HW_ACCEL_FAILED -0x002B /**< MD2 hardware accelerator failed */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_MD2_ALT) +// Regular implementation +// + /** * \brief MD2 context structure + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -typedef struct +typedef struct mbedtls_md2_context { unsigned char cksum[16]; /*!< checksum of the data block */ unsigned char state[48]; /*!< intermediate digest state */ @@ -51,10 +64,19 @@ typedef struct } mbedtls_md2_context; +#else /* MBEDTLS_MD2_ALT */ +#include "md2_alt.h" +#endif /* MBEDTLS_MD2_ALT */ + /** * \brief Initialize MD2 context * * \param ctx MD2 context to be initialized + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md2_init( mbedtls_md2_context *ctx ); @@ -62,6 +84,11 @@ void mbedtls_md2_init( mbedtls_md2_context *ctx ); * \brief Clear MD2 context * * \param ctx MD2 context to be cleared + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md2_free( mbedtls_md2_context *ctx ); @@ -70,6 +97,11 @@ void mbedtls_md2_free( mbedtls_md2_context *ctx ); * * \param dst The destination context * \param src The context to be cloned + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md2_clone( mbedtls_md2_context *dst, const mbedtls_md2_context *src ); @@ -78,57 +110,190 @@ void mbedtls_md2_clone( mbedtls_md2_context *dst, * \brief MD2 context setup * * \param ctx context to be initialized + * + * \return 0 if successful + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md2_starts( mbedtls_md2_context *ctx ); +int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx ); /** * \brief MD2 process buffer * * \param ctx MD2 context - * \param input buffer holding the data + * \param input buffer holding the data * \param ilen length of the input data + * + * \return 0 if successful + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md2_update( mbedtls_md2_context *ctx, const unsigned char *input, size_t ilen ); +int mbedtls_md2_update_ret( mbedtls_md2_context *ctx, + const unsigned char *input, + size_t ilen ); /** * \brief MD2 final digest * * \param ctx MD2 context * \param output MD2 checksum result + * + * \return 0 if successful + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md2_finish( mbedtls_md2_context *ctx, unsigned char output[16] ); +int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx, + unsigned char output[16] ); -#ifdef __cplusplus -} +/** + * \brief MD2 process data block (internal use only) + * + * \param ctx MD2 context + * + * \return 0 if successful + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_internal_md2_process( mbedtls_md2_context *ctx ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED #endif +/** + * \brief MD2 context setup + * + * \deprecated Superseded by mbedtls_md2_starts_ret() in 2.7.0 + * + * \param ctx context to be initialized + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2_starts( mbedtls_md2_context *ctx ); -#else /* MBEDTLS_MD2_ALT */ -#include "md2_alt.h" -#endif /* MBEDTLS_MD2_ALT */ +/** + * \brief MD2 process buffer + * + * \deprecated Superseded by mbedtls_md2_update_ret() in 2.7.0 + * + * \param ctx MD2 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2_update( mbedtls_md2_context *ctx, + const unsigned char *input, + size_t ilen ); -#ifdef __cplusplus -extern "C" { -#endif +/** + * \brief MD2 final digest + * + * \deprecated Superseded by mbedtls_md2_finish_ret() in 2.7.0 + * + * \param ctx MD2 context + * \param output MD2 checksum result + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2_finish( mbedtls_md2_context *ctx, + unsigned char output[16] ); + +/** + * \brief MD2 process data block (internal use only) + * + * \deprecated Superseded by mbedtls_internal_md2_process() in 2.7.0 + * + * \param ctx MD2 context + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2_process( mbedtls_md2_context *ctx ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief Output = MD2( input buffer ) * - * \param input buffer holding the data + * \param input buffer holding the data * \param ilen length of the input data * \param output MD2 checksum result + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md2( const unsigned char *input, size_t ilen, unsigned char output[16] ); +int mbedtls_md2_ret( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Output = MD2( input buffer ) + * + * \deprecated Superseded by mbedtls_md2_ret() in 2.7.0 + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD2 checksum result + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ int mbedtls_md2_self_test( int verbose ); -/* Internal use */ -void mbedtls_md2_process( mbedtls_md2_context *ctx ); - #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/mbedtls/mbedtls/md4.h b/tools/sdk/include/mbedtls/mbedtls/md4.h index 45214d41d9f..1672e9074ef 100644 --- a/tools/sdk/include/mbedtls/mbedtls/md4.h +++ b/tools/sdk/include/mbedtls/mbedtls/md4.h @@ -3,6 +3,11 @@ * * \brief MD4 message digest algorithm (hash function) * + * \warning MD4 is considered a weak message digest and its use constitutes a + * security risk. We recommend considering stronger message digests + * instead. + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -19,6 +24,7 @@ * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) + * */ #ifndef MBEDTLS_MD4_H #define MBEDTLS_MD4_H @@ -32,18 +38,25 @@ #include #include -#if !defined(MBEDTLS_MD4_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_MD4_HW_ACCEL_FAILED -0x002D /**< MD4 hardware accelerator failed */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_MD4_ALT) +// Regular implementation +// + /** * \brief MD4 context structure + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -typedef struct +typedef struct mbedtls_md4_context { uint32_t total[2]; /*!< number of bytes processed */ uint32_t state[4]; /*!< intermediate digest state */ @@ -51,10 +64,19 @@ typedef struct } mbedtls_md4_context; +#else /* MBEDTLS_MD4_ALT */ +#include "md4_alt.h" +#endif /* MBEDTLS_MD4_ALT */ + /** * \brief Initialize MD4 context * * \param ctx MD4 context to be initialized + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md4_init( mbedtls_md4_context *ctx ); @@ -62,6 +84,11 @@ void mbedtls_md4_init( mbedtls_md4_context *ctx ); * \brief Clear MD4 context * * \param ctx MD4 context to be cleared + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md4_free( mbedtls_md4_context *ctx ); @@ -70,6 +97,11 @@ void mbedtls_md4_free( mbedtls_md4_context *ctx ); * * \param dst The destination context * \param src The context to be cloned + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md4_clone( mbedtls_md4_context *dst, const mbedtls_md4_context *src ); @@ -78,57 +110,195 @@ void mbedtls_md4_clone( mbedtls_md4_context *dst, * \brief MD4 context setup * * \param ctx context to be initialized + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. */ -void mbedtls_md4_starts( mbedtls_md4_context *ctx ); +int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx ); /** * \brief MD4 process buffer * * \param ctx MD4 context - * \param input buffer holding the data + * \param input buffer holding the data * \param ilen length of the input data + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md4_update( mbedtls_md4_context *ctx, const unsigned char *input, size_t ilen ); +int mbedtls_md4_update_ret( mbedtls_md4_context *ctx, + const unsigned char *input, + size_t ilen ); /** * \brief MD4 final digest * * \param ctx MD4 context * \param output MD4 checksum result + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md4_finish( mbedtls_md4_context *ctx, unsigned char output[16] ); +int mbedtls_md4_finish_ret( mbedtls_md4_context *ctx, + unsigned char output[16] ); -#ifdef __cplusplus -} +/** + * \brief MD4 process data block (internal use only) + * + * \param ctx MD4 context + * \param data buffer holding one block of data + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_internal_md4_process( mbedtls_md4_context *ctx, + const unsigned char data[64] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED #endif +/** + * \brief MD4 context setup + * + * \deprecated Superseded by mbedtls_md4_starts_ret() in 2.7.0 + * + * \param ctx context to be initialized + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4_starts( mbedtls_md4_context *ctx ); -#else /* MBEDTLS_MD4_ALT */ -#include "md4_alt.h" -#endif /* MBEDTLS_MD4_ALT */ +/** + * \brief MD4 process buffer + * + * \deprecated Superseded by mbedtls_md4_update_ret() in 2.7.0 + * + * \param ctx MD4 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4_update( mbedtls_md4_context *ctx, + const unsigned char *input, + size_t ilen ); -#ifdef __cplusplus -extern "C" { -#endif +/** + * \brief MD4 final digest + * + * \deprecated Superseded by mbedtls_md4_finish_ret() in 2.7.0 + * + * \param ctx MD4 context + * \param output MD4 checksum result + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4_finish( mbedtls_md4_context *ctx, + unsigned char output[16] ); + +/** + * \brief MD4 process data block (internal use only) + * + * \deprecated Superseded by mbedtls_internal_md4_process() in 2.7.0 + * + * \param ctx MD4 context + * \param data buffer holding one block of data + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4_process( mbedtls_md4_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief Output = MD4( input buffer ) * - * \param input buffer holding the data + * \param input buffer holding the data * \param ilen length of the input data * \param output MD4 checksum result + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md4( const unsigned char *input, size_t ilen, unsigned char output[16] ); +int mbedtls_md4_ret( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Output = MD4( input buffer ) + * + * \deprecated Superseded by mbedtls_md4_ret() in 2.7.0 + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD4 checksum result + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ int mbedtls_md4_self_test( int verbose ); -/* Internal use */ -void mbedtls_md4_process( mbedtls_md4_context *ctx, const unsigned char data[64] ); - #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/mbedtls/mbedtls/md5.h b/tools/sdk/include/mbedtls/mbedtls/md5.h index 5a64061aa0c..4c9509010b6 100644 --- a/tools/sdk/include/mbedtls/mbedtls/md5.h +++ b/tools/sdk/include/mbedtls/mbedtls/md5.h @@ -3,6 +3,11 @@ * * \brief MD5 message digest algorithm (hash function) * + * \warning MD5 is considered a weak message digest and its use constitutes a + * security risk. We recommend considering stronger message + * digests instead. + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -32,18 +37,25 @@ #include #include -#if !defined(MBEDTLS_MD5_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED -0x002F /**< MD5 hardware accelerator failed */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_MD5_ALT) +// Regular implementation +// + /** * \brief MD5 context structure + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -typedef struct +typedef struct mbedtls_md5_context { uint32_t total[2]; /*!< number of bytes processed */ uint32_t state[4]; /*!< intermediate digest state */ @@ -51,10 +63,19 @@ typedef struct } mbedtls_md5_context; +#else /* MBEDTLS_MD5_ALT */ +#include "md5_alt.h" +#endif /* MBEDTLS_MD5_ALT */ + /** * \brief Initialize MD5 context * * \param ctx MD5 context to be initialized + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md5_init( mbedtls_md5_context *ctx ); @@ -62,6 +83,11 @@ void mbedtls_md5_init( mbedtls_md5_context *ctx ); * \brief Clear MD5 context * * \param ctx MD5 context to be cleared + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md5_free( mbedtls_md5_context *ctx ); @@ -70,6 +96,11 @@ void mbedtls_md5_free( mbedtls_md5_context *ctx ); * * \param dst The destination context * \param src The context to be cloned + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ void mbedtls_md5_clone( mbedtls_md5_context *dst, const mbedtls_md5_context *src ); @@ -78,54 +109,193 @@ void mbedtls_md5_clone( mbedtls_md5_context *dst, * \brief MD5 context setup * * \param ctx context to be initialized + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md5_starts( mbedtls_md5_context *ctx ); +int mbedtls_md5_starts_ret( mbedtls_md5_context *ctx ); /** * \brief MD5 process buffer * * \param ctx MD5 context - * \param input buffer holding the data + * \param input buffer holding the data * \param ilen length of the input data + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md5_update( mbedtls_md5_context *ctx, const unsigned char *input, size_t ilen ); +int mbedtls_md5_update_ret( mbedtls_md5_context *ctx, + const unsigned char *input, + size_t ilen ); /** * \brief MD5 final digest * * \param ctx MD5 context * \param output MD5 checksum result + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md5_finish( mbedtls_md5_context *ctx, unsigned char output[16] ); +int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx, + unsigned char output[16] ); -/* Internal use */ -void mbedtls_md5_process( mbedtls_md5_context *ctx, const unsigned char data[64] ); +/** + * \brief MD5 process data block (internal use only) + * + * \param ctx MD5 context + * \param data buffer holding one block of data + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_internal_md5_process( mbedtls_md5_context *ctx, + const unsigned char data[64] ); -#ifdef __cplusplus -} +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED #endif +/** + * \brief MD5 context setup + * + * \deprecated Superseded by mbedtls_md5_starts_ret() in 2.7.0 + * + * \param ctx context to be initialized + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5_starts( mbedtls_md5_context *ctx ); -#else /* MBEDTLS_MD5_ALT */ -#include "md5_alt.h" -#endif /* MBEDTLS_MD5_ALT */ +/** + * \brief MD5 process buffer + * + * \deprecated Superseded by mbedtls_md5_update_ret() in 2.7.0 + * + * \param ctx MD5 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5_update( mbedtls_md5_context *ctx, + const unsigned char *input, + size_t ilen ); -#ifdef __cplusplus -extern "C" { -#endif +/** + * \brief MD5 final digest + * + * \deprecated Superseded by mbedtls_md5_finish_ret() in 2.7.0 + * + * \param ctx MD5 context + * \param output MD5 checksum result + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5_finish( mbedtls_md5_context *ctx, + unsigned char output[16] ); +/** + * \brief MD5 process data block (internal use only) + * + * \deprecated Superseded by mbedtls_internal_md5_process() in 2.7.0 + * + * \param ctx MD5 context + * \param data buffer holding one block of data + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5_process( mbedtls_md5_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Output = MD5( input buffer ) + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD5 checksum result + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md5_ret( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif /** * \brief Output = MD5( input buffer ) * - * \param input buffer holding the data + * \deprecated Superseded by mbedtls_md5_ret() in 2.7.0 + * + * \param input buffer holding the data * \param ilen length of the input data * \param output MD5 checksum result + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -void mbedtls_md5( const unsigned char *input, size_t ilen, unsigned char output[16] ); +MBEDTLS_DEPRECATED void mbedtls_md5( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ int mbedtls_md5_self_test( int verbose ); diff --git a/tools/sdk/include/mbedtls/mbedtls/md_internal.h b/tools/sdk/include/mbedtls/mbedtls/md_internal.h index e2441bbc49d..04de4829184 100644 --- a/tools/sdk/include/mbedtls/mbedtls/md_internal.h +++ b/tools/sdk/include/mbedtls/mbedtls/md_internal.h @@ -6,7 +6,8 @@ * \warning This in an internal header. Do not include directly. * * \author Adriaan de Jong - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -58,17 +59,17 @@ struct mbedtls_md_info_t int block_size; /** Digest initialisation function */ - void (*starts_func)( void *ctx ); + int (*starts_func)( void *ctx ); /** Digest update function */ - void (*update_func)( void *ctx, const unsigned char *input, size_t ilen ); + int (*update_func)( void *ctx, const unsigned char *input, size_t ilen ); /** Digest finalisation function */ - void (*finish_func)( void *ctx, unsigned char *output ); + int (*finish_func)( void *ctx, unsigned char *output ); /** Generic digest function */ - void (*digest_func)( const unsigned char *input, size_t ilen, - unsigned char *output ); + int (*digest_func)( const unsigned char *input, size_t ilen, + unsigned char *output ); /** Allocate a new context */ void * (*ctx_alloc_func)( void ); @@ -80,7 +81,7 @@ struct mbedtls_md_info_t void (*clone_func)( void *dst, const void *src ); /** Internal use only */ - void (*process_func)( void *ctx, const unsigned char *input ); + int (*process_func)( void *ctx, const unsigned char *input ); }; #if defined(MBEDTLS_MD2_C) diff --git a/tools/sdk/include/mbedtls/mbedtls/memory_buffer_alloc.h b/tools/sdk/include/mbedtls/mbedtls/memory_buffer_alloc.h index d5df316fdd7..705f9a63690 100644 --- a/tools/sdk/include/mbedtls/mbedtls/memory_buffer_alloc.h +++ b/tools/sdk/include/mbedtls/mbedtls/memory_buffer_alloc.h @@ -2,7 +2,8 @@ * \file memory_buffer_alloc.h * * \brief Buffer-based memory allocator - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/net.h b/tools/sdk/include/mbedtls/mbedtls/net.h index 774559b3cf6..6c13b53fb93 100644 --- a/tools/sdk/include/mbedtls/mbedtls/net.h +++ b/tools/sdk/include/mbedtls/mbedtls/net.h @@ -1,8 +1,11 @@ /** * \file net.h * - * \brief Deprecated header file that includes mbedtls/net_sockets.h + * \brief Deprecated header file that includes net_sockets.h * + * \deprecated Superseded by mbedtls/net_sockets.h + */ +/* * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -19,12 +22,10 @@ * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) - * - * \deprecated Superseded by mbedtls/net_sockets.h */ #if !defined(MBEDTLS_DEPRECATED_REMOVED) -#include "mbedtls/net_sockets.h" +#include "net_sockets.h" #if defined(MBEDTLS_DEPRECATED_WARNING) #warning "Deprecated header file: Superseded by mbedtls/net_sockets.h" #endif /* MBEDTLS_DEPRECATED_WARNING */ diff --git a/tools/sdk/include/mbedtls/mbedtls/net_sockets.h b/tools/sdk/include/mbedtls/mbedtls/net_sockets.h index de335526fe9..4c7ef00fe66 100644 --- a/tools/sdk/include/mbedtls/mbedtls/net_sockets.h +++ b/tools/sdk/include/mbedtls/mbedtls/net_sockets.h @@ -1,8 +1,25 @@ /** * \file net_sockets.h * - * \brief Network communication functions + * \brief Network sockets abstraction layer to integrate Mbed TLS into a + * BSD-style sockets API. * + * The network sockets module provides an example integration of the + * Mbed TLS library into a BSD sockets implementation. The module is + * intended to be an example of how Mbed TLS can be integrated into a + * networking stack, as well as to be Mbed TLS's network integration + * for its supported platforms. + * + * The module is intended only to be used with the Mbed TLS library and + * is not intended to be used by third party application software + * directly. + * + * The supported platforms are as follows: + * * Microsoft Windows and Windows CE + * * POSIX/Unix platforms including Linux, OS X + * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -45,12 +62,17 @@ #define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 /**< Failed to get an IP address for the given hostname. */ #define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043 /**< Buffer is too small to hold the data. */ #define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 /**< The context is invalid, eg because it was free()ed. */ +#define MBEDTLS_ERR_NET_POLL_FAILED -0x0047 /**< Polling the net context failed. */ +#define MBEDTLS_ERR_NET_BAD_INPUT_DATA -0x0049 /**< Input invalid. */ #define MBEDTLS_NET_LISTEN_BACKLOG 10 /**< The backlog that listen() should use. */ #define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */ #define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */ +#define MBEDTLS_NET_POLL_READ 1 /**< Used in \c mbedtls_net_poll to check for pending data */ +#define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \c mbedtls_net_poll to check if write possible */ + #ifdef __cplusplus extern "C" { #endif @@ -62,7 +84,7 @@ extern "C" { * (eg two file descriptors for combined IPv4 + IPv6 support, or additional * structures for hand-made UDP demultiplexing). */ -typedef struct +typedef struct mbedtls_net_context { int fd; /**< The underlying file descriptor */ } @@ -117,9 +139,10 @@ int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char * * \param bind_ctx Relevant socket * \param client_ctx Will contain the connected client socket - * \param client_ip Will contain the client IP address + * \param client_ip Will contain the client IP address, can be NULL * \param buf_size Size of the client_ip buffer - * \param ip_len Will receive the size of the client IP written + * \param ip_len Will receive the size of the client IP written, + * can be NULL if client_ip is null * * \return 0 if successful, or * MBEDTLS_ERR_NET_ACCEPT_FAILED, or @@ -131,6 +154,29 @@ int mbedtls_net_accept( mbedtls_net_context *bind_ctx, mbedtls_net_context *client_ctx, void *client_ip, size_t buf_size, size_t *ip_len ); +/** + * \brief Check and wait for the context to be ready for read/write + * + * \param ctx Socket to check + * \param rw Bitflag composed of MBEDTLS_NET_POLL_READ and + * MBEDTLS_NET_POLL_WRITE specifying the events + * to wait for: + * - If MBEDTLS_NET_POLL_READ is set, the function + * will return as soon as the net context is available + * for reading. + * - If MBEDTLS_NET_POLL_WRITE is set, the function + * will return as soon as the net context is available + * for writing. + * \param timeout Maximal amount of time to wait before returning, + * in milliseconds. If \c timeout is zero, the + * function returns immediately. If \c timeout is + * -1u, the function blocks potentially indefinitely. + * + * \return Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE + * on success or timeout, or a negative return code otherwise. + */ +int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout ); + /** * \brief Set the socket blocking * diff --git a/tools/sdk/include/mbedtls/mbedtls/nist_kw.h b/tools/sdk/include/mbedtls/mbedtls/nist_kw.h new file mode 100644 index 00000000000..5a0f656a8f5 --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/nist_kw.h @@ -0,0 +1,178 @@ +/** + * \file nist_kw.h + * + * \brief This file provides an API for key wrapping (KW) and key wrapping with + * padding (KWP) as defined in NIST SP 800-38F. + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf + * + * Key wrapping specifies a deterministic authenticated-encryption mode + * of operation, according to NIST SP 800-38F: Recommendation for + * Block Cipher Modes of Operation: Methods for Key Wrapping. Its + * purpose is to protect cryptographic keys. + * + * Its equivalent is RFC 3394 for KW, and RFC 5649 for KWP. + * https://tools.ietf.org/html/rfc3394 + * https://tools.ietf.org/html/rfc5649 + * + */ +/* + * Copyright (C) 2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_NIST_KW_H +#define MBEDTLS_NIST_KW_H + +#include "cipher.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + MBEDTLS_KW_MODE_KW = 0, + MBEDTLS_KW_MODE_KWP = 1 +} mbedtls_nist_kw_mode_t; + +#if !defined(MBEDTLS_NIST_KW_ALT) +// Regular implementation +// + +/** + * \brief The key wrapping context-type definition. The key wrapping context is passed + * to the APIs called. + * + * \note The definition of this type may change in future library versions. + * Don't make any assumptions on this context! + */ +typedef struct { + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ +} mbedtls_nist_kw_context; + +#else /* MBEDTLS_NIST_key wrapping_ALT */ +#include "nist_kw_alt.h" +#endif /* MBEDTLS_NIST_KW_ALT */ + +/** + * \brief This function initializes the specified key wrapping context + * to make references valid and prepare the context + * for mbedtls_nist_kw_setkey() or mbedtls_nist_kw_free(). + * + * \param ctx The key wrapping context to initialize. + * + */ +void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx ); + +/** + * \brief This function initializes the key wrapping context set in the + * \p ctx parameter and sets the encryption key. + * + * \param ctx The key wrapping context. + * \param cipher The 128-bit block cipher to use. Only AES is supported. + * \param key The Key Encryption Key (KEK). + * \param keybits The KEK size in bits. This must be acceptable by the cipher. + * \param is_wrap Specify whether the operation within the context is wrapping or unwrapping + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for any invalid input. + * \return \c MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE for 128-bit block ciphers + * which are not supported. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx, + mbedtls_cipher_id_t cipher, + const unsigned char *key, + unsigned int keybits, + const int is_wrap ); + +/** + * \brief This function releases and clears the specified key wrapping context + * and underlying cipher sub-context. + * + * \param ctx The key wrapping context to clear. + */ +void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx ); + +/** + * \brief This function encrypts a buffer using key wrapping. + * + * \param ctx The key wrapping context to use for encryption. + * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP) + * \param input The buffer holding the input data. + * \param in_len The length of the input data in Bytes. + * The input uses units of 8 Bytes called semiblocks. + *
  • For KW mode: a multiple of 8 bytes between 16 and 2^57-8 inclusive.
  • + *
  • For KWP mode: any length between 1 and 2^32-1 inclusive.
+ * \param[out] output The buffer holding the output data. + *
  • For KW mode: Must be at least 8 bytes larger than \p in_len.
  • + *
  • For KWP mode: Must be at least 8 bytes larger rounded up to a multiple of + * 8 bytes for KWP (15 bytes at most).
+ * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure. + * \param[in] out_size The capacity of the output buffer. + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, + const unsigned char *input, size_t in_len, + unsigned char *output, size_t* out_len, size_t out_size ); + +/** + * \brief This function decrypts a buffer using key wrapping. + * + * \param ctx The key wrapping context to use for decryption. + * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP) + * \param input The buffer holding the input data. + * \param in_len The length of the input data in Bytes. + * The input uses units of 8 Bytes called semiblocks. + * The input must be a multiple of semiblocks. + *
  • For KW mode: a multiple of 8 bytes between 24 and 2^57 inclusive.
  • + *
  • For KWP mode: a multiple of 8 bytes between 16 and 2^32 inclusive.
+ * \param[out] output The buffer holding the output data. + * The output buffer's minimal length is 8 bytes shorter than \p in_len. + * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure. + * For KWP mode, the length could be up to 15 bytes shorter than \p in_len, + * depending on how much padding was added to the data. + * \param[in] out_size The capacity of the output buffer. + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length. + * \return \c MBEDTLS_ERR_CIPHER_AUTH_FAILED for verification failure of the ciphertext. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, + const unsigned char *input, size_t in_len, + unsigned char *output, size_t* out_len, size_t out_size); + + +#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) +/** + * \brief The key wrapping checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_nist_kw_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_NIST_KW_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/oid.h b/tools/sdk/include/mbedtls/mbedtls/oid.h index fcecdafdcac..6fbd018aaa1 100644 --- a/tools/sdk/include/mbedtls/mbedtls/oid.h +++ b/tools/sdk/include/mbedtls/mbedtls/oid.h @@ -2,7 +2,8 @@ * \file oid.h * * \brief Object Identifier (OID) database - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -96,6 +97,8 @@ /* ISO arc for standard certificate and CRL extensions */ #define MBEDTLS_OID_ID_CE MBEDTLS_OID_ISO_CCITT_DS "\x1D" /**< id-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29} */ +#define MBEDTLS_OID_NIST_ALG MBEDTLS_OID_GOV "\x03\x04" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */ + /** * Private Internet Extensions * { iso(1) identified-organization(3) dod(6) internet(1) @@ -218,21 +221,42 @@ #define MBEDTLS_OID_DIGEST_ALG_MD4 MBEDTLS_OID_RSA_COMPANY "\x02\x04" /**< id-mbedtls_md4 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 4 } */ #define MBEDTLS_OID_DIGEST_ALG_MD5 MBEDTLS_OID_RSA_COMPANY "\x02\x05" /**< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA1 MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_SHA1 /**< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */ -#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_GOV "\x03\x04\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */ -#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_GOV "\x03\x04\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_NIST_ALG "\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_NIST_ALG "\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */ -#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_GOV "\x03\x04\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_NIST_ALG "\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */ -#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_GOV "\x03\x04\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_NIST_ALG "\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */ #define MBEDTLS_OID_HMAC_SHA1 MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */ +#define MBEDTLS_OID_HMAC_SHA224 MBEDTLS_OID_RSA_COMPANY "\x02\x08" /**< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */ + +#define MBEDTLS_OID_HMAC_SHA256 MBEDTLS_OID_RSA_COMPANY "\x02\x09" /**< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */ + +#define MBEDTLS_OID_HMAC_SHA384 MBEDTLS_OID_RSA_COMPANY "\x02\x0A" /**< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */ + +#define MBEDTLS_OID_HMAC_SHA512 MBEDTLS_OID_RSA_COMPANY "\x02\x0B" /**< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */ + /* * Encryption algorithms */ #define MBEDTLS_OID_DES_CBC MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_ALG "\x07" /**< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */ #define MBEDTLS_OID_DES_EDE3_CBC MBEDTLS_OID_RSA_COMPANY "\x03\x07" /**< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */ +#define MBEDTLS_OID_AES MBEDTLS_OID_NIST_ALG "\x01" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */ +/* + * Key Wrapping algorithms + */ +/* + * RFC 5649 + */ +#define MBEDTLS_OID_AES128_KW MBEDTLS_OID_AES "\x05" /** id-aes128-wrap OBJECT IDENTIFIER ::= { aes 5 } */ +#define MBEDTLS_OID_AES128_KWP MBEDTLS_OID_AES "\x08" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */ +#define MBEDTLS_OID_AES192_KW MBEDTLS_OID_AES "\x19" /** id-aes192-wrap OBJECT IDENTIFIER ::= { aes 25 } */ +#define MBEDTLS_OID_AES192_KWP MBEDTLS_OID_AES "\x1c" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */ +#define MBEDTLS_OID_AES256_KW MBEDTLS_OID_AES "\x2d" /** id-aes256-wrap OBJECT IDENTIFIER ::= { aes 45 } */ +#define MBEDTLS_OID_AES256_KWP MBEDTLS_OID_AES "\x30" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */ /* * PKCS#5 OIDs */ @@ -379,7 +403,8 @@ extern "C" { /** * \brief Base OID descriptor structure */ -typedef struct { +typedef struct mbedtls_oid_descriptor_t +{ const char *asn1; /*!< OID ASN.1 representation */ size_t asn1_len; /*!< length of asn1 */ const char *name; /*!< official name (e.g. from RFC) */ @@ -513,6 +538,16 @@ int mbedtls_oid_get_oid_by_sig_alg( mbedtls_pk_type_t pk_alg, mbedtls_md_type_t * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg ); + +/** + * \brief Translate hmac algorithm OID into md_type + * + * \param oid OID to use + * \param md_hmac place to store message hmac algorithm + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac ); #endif /* MBEDTLS_MD_C */ /** diff --git a/tools/sdk/include/mbedtls/mbedtls/padlock.h b/tools/sdk/include/mbedtls/mbedtls/padlock.h index 2045a5ab642..677936ebf86 100644 --- a/tools/sdk/include/mbedtls/mbedtls/padlock.h +++ b/tools/sdk/include/mbedtls/mbedtls/padlock.h @@ -3,7 +3,8 @@ * * \brief VIA PadLock ACE for HW encryption/decryption supported by some * processors - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/pem.h b/tools/sdk/include/mbedtls/mbedtls/pem.h index 54dc02d7cdc..fa82f7bdbd8 100644 --- a/tools/sdk/include/mbedtls/mbedtls/pem.h +++ b/tools/sdk/include/mbedtls/mbedtls/pem.h @@ -2,7 +2,8 @@ * \file pem.h * * \brief Privacy Enhanced Mail (PEM) decoding - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -50,7 +51,7 @@ extern "C" { /** * \brief PEM context structure */ -typedef struct +typedef struct mbedtls_pem_context { unsigned char *buf; /*!< buffer for decoded data */ size_t buflen; /*!< length of the buffer */ diff --git a/tools/sdk/include/mbedtls/mbedtls/pk.h b/tools/sdk/include/mbedtls/mbedtls/pk.h index f9f9b9bb096..db54c6a6ef5 100644 --- a/tools/sdk/include/mbedtls/mbedtls/pk.h +++ b/tools/sdk/include/mbedtls/mbedtls/pk.h @@ -2,7 +2,8 @@ * \file pk.h * * \brief Public Key abstraction layer - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -62,7 +63,8 @@ #define MBEDTLS_ERR_PK_INVALID_ALG -0x3A80 /**< The algorithm tag or value is invalid. */ #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00 /**< Elliptic curve is unsupported (only NIST curves are supported). */ #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980 /**< Unavailable feature, e.g. RSA disabled for RSA key. */ -#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The signature is valid but its length is less than expected. */ +#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The buffer contains a valid signature followed by more data. */ +#define MBEDTLS_ERR_PK_HW_ACCEL_FAILED -0x3880 /**< PK hardware accelerator failed. */ #ifdef __cplusplus extern "C" { @@ -85,7 +87,7 @@ typedef enum { * \brief Options for RSASSA-PSS signature verification. * See \c mbedtls_rsa_rsassa_pss_verify_ext() */ -typedef struct +typedef struct mbedtls_pk_rsassa_pss_options { mbedtls_md_type_t mgf1_hash_id; int expected_salt_len; @@ -105,7 +107,7 @@ typedef enum /** * \brief Item to send to the debug module */ -typedef struct +typedef struct mbedtls_pk_debug_item { mbedtls_pk_debug_type type; const char *name; @@ -123,7 +125,7 @@ typedef struct mbedtls_pk_info_t mbedtls_pk_info_t; /** * \brief Public key container */ -typedef struct +typedef struct mbedtls_pk_context { const mbedtls_pk_info_t * pk_info; /**< Public key informations */ void * pk_ctx; /**< Underlying public key context */ @@ -267,8 +269,8 @@ int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type ); * \param sig_len Signature length * * \return 0 on success (signature is valid), - * MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is - * valid but its actual length is less than sig_len, + * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid + * signature in sig but its length is less than \p siglen, * or a specific error code. * * \note For RSA keys, the default padding type is PKCS#1 v1.5. @@ -298,10 +300,10 @@ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, * \param sig_len Signature length * * \return 0 on success (signature is valid), - * MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be + * #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be * used for this type of signatures, - * MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is - * valid but its actual length is less than sig_len, + * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid + * signature in sig but its length is less than \p siglen, * or a specific error code. * * \note If hash_len is 0, then the length associated with md_alg diff --git a/tools/sdk/include/mbedtls/mbedtls/pk_internal.h b/tools/sdk/include/mbedtls/mbedtls/pk_internal.h index 01d0f214bca..3dae0fc5b27 100644 --- a/tools/sdk/include/mbedtls/mbedtls/pk_internal.h +++ b/tools/sdk/include/mbedtls/mbedtls/pk_internal.h @@ -1,8 +1,9 @@ /** - * \file pk.h + * \file pk_internal.h * * \brief Public Key abstraction layer: wrapper functions - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/pkcs11.h b/tools/sdk/include/mbedtls/mbedtls/pkcs11.h index 2e88928137c..02427ddc1e9 100644 --- a/tools/sdk/include/mbedtls/mbedtls/pkcs11.h +++ b/tools/sdk/include/mbedtls/mbedtls/pkcs11.h @@ -4,7 +4,8 @@ * \brief Wrapper for PKCS#11 library libpkcs11-helper * * \author Adriaan de Jong - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -49,7 +50,8 @@ extern "C" { /** * Context for PKCS #11 private keys. */ -typedef struct { +typedef struct mbedtls_pkcs11_context +{ pkcs11h_certificate_t pkcs11h_cert; int len; } mbedtls_pkcs11_context; diff --git a/tools/sdk/include/mbedtls/mbedtls/pkcs12.h b/tools/sdk/include/mbedtls/mbedtls/pkcs12.h index 9b2d9045911..a621ef5b15e 100644 --- a/tools/sdk/include/mbedtls/mbedtls/pkcs12.h +++ b/tools/sdk/include/mbedtls/mbedtls/pkcs12.h @@ -2,7 +2,8 @@ * \file pkcs12.h * * \brief PKCS#12 Personal Information Exchange Syntax - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/pkcs5.h b/tools/sdk/include/mbedtls/mbedtls/pkcs5.h index ec5cb9e7443..9a3c9fddcc9 100644 --- a/tools/sdk/include/mbedtls/mbedtls/pkcs5.h +++ b/tools/sdk/include/mbedtls/mbedtls/pkcs5.h @@ -4,7 +4,8 @@ * \brief PKCS#5 functions * * \author Mathias Olsson - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/platform.h b/tools/sdk/include/mbedtls/mbedtls/platform.h index 35010f88522..a40a64f9c6b 100644 --- a/tools/sdk/include/mbedtls/mbedtls/platform.h +++ b/tools/sdk/include/mbedtls/mbedtls/platform.h @@ -1,9 +1,19 @@ /** * \file platform.h * - * \brief mbed TLS Platform abstraction layer + * \brief This file contains the definitions and functions of the + * Mbed TLS platform abstraction layer. * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * The platform abstraction layer removes the need for the library + * to directly link to standard C library functions or operating + * system services, making the library easier to port and embed. + * Application developers and users of the library can provide their own + * implementations of these functions, or implementations specific to + * their platform, which can be statically linked to the library or + * dynamically configured at runtime. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,7 +28,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_PLATFORM_H #define MBEDTLS_PLATFORM_H @@ -30,7 +40,7 @@ #endif #if defined(MBEDTLS_HAVE_TIME) -#include "mbedtls/platform_time.h" +#include "platform_time.h" #endif #ifdef __cplusplus @@ -51,34 +61,34 @@ extern "C" { #include #if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF) #if defined(_WIN32) -#define MBEDTLS_PLATFORM_STD_SNPRINTF mbedtls_platform_win32_snprintf /**< Default snprintf to use */ +#define MBEDTLS_PLATFORM_STD_SNPRINTF mbedtls_platform_win32_snprintf /**< The default \c snprintf function to use. */ #else -#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use */ +#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< The default \c snprintf function to use. */ #endif #endif #if !defined(MBEDTLS_PLATFORM_STD_PRINTF) -#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use */ +#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< The default \c printf function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_FPRINTF) -#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use */ +#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< The default \c fprintf function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_CALLOC) -#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< Default allocator to use */ +#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< The default \c calloc function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_FREE) -#define MBEDTLS_PLATFORM_STD_FREE free /**< Default free to use */ +#define MBEDTLS_PLATFORM_STD_FREE free /**< The default \c free function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_EXIT) -#define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use */ +#define MBEDTLS_PLATFORM_STD_EXIT exit /**< The default \c exit function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_TIME) -#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use */ +#define MBEDTLS_PLATFORM_STD_TIME time /**< The default \c time function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS) -#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS EXIT_SUCCESS /**< Default exit value to use */ +#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS EXIT_SUCCESS /**< The default exit value to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE) -#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE EXIT_FAILURE /**< Default exit value to use */ +#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE EXIT_FAILURE /**< The default exit value to use. */ #endif #if defined(MBEDTLS_FS_IO) #if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) @@ -101,7 +111,7 @@ extern "C" { /* \} name SECTION: Module settings */ /* - * The function pointers for calloc and free + * The function pointers for calloc and free. */ #if defined(MBEDTLS_PLATFORM_MEMORY) #if defined(MBEDTLS_PLATFORM_FREE_MACRO) && \ @@ -111,16 +121,17 @@ extern "C" { #else /* For size_t */ #include -extern void * (*mbedtls_calloc)( size_t n, size_t size ); -extern void (*mbedtls_free)( void *ptr ); +extern void *mbedtls_calloc( size_t n, size_t size ); +extern void mbedtls_free( void *ptr ); /** - * \brief Set your own memory implementation function pointers + * \brief This function dynamically sets the memory-management + * functions used by the library, during runtime. * - * \param calloc_func the calloc function implementation - * \param free_func the free function implementation + * \param calloc_func The \c calloc function implementation. + * \param free_func The \c free function implementation. * - * \return 0 if successful + * \return \c 0. */ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ), void (*free_func)( void * ) ); @@ -139,11 +150,13 @@ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ), extern int (*mbedtls_fprintf)( FILE *stream, const char *format, ... ); /** - * \brief Set your own fprintf function pointer + * \brief This function dynamically configures the fprintf + * function that is called when the + * mbedtls_fprintf() function is invoked by the library. * - * \param fprintf_func the fprintf function implementation + * \param fprintf_func The \c fprintf function implementation. * - * \return 0 + * \return \c 0. */ int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *, ... ) ); @@ -162,11 +175,13 @@ int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char extern int (*mbedtls_printf)( const char *format, ... ); /** - * \brief Set your own printf function pointer + * \brief This function dynamically configures the snprintf + * function that is called when the mbedtls_snprintf() + * function is invoked by the library. * - * \param printf_func the printf function implementation + * \param printf_func The \c printf function implementation. * - * \return 0 + * \return \c 0 on success. */ int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) ); #else /* !MBEDTLS_PLATFORM_PRINTF_ALT */ @@ -195,11 +210,12 @@ int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... ); extern int (*mbedtls_snprintf)( char * s, size_t n, const char * format, ... ); /** - * \brief Set your own snprintf function pointer + * \brief This function allows configuring a custom + * \c snprintf function pointer. * - * \param snprintf_func the snprintf function implementation + * \param snprintf_func The \c snprintf function implementation. * - * \return 0 + * \return \c 0 on success. */ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n, const char * format, ... ) ); @@ -207,7 +223,7 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n, #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) #define mbedtls_snprintf MBEDTLS_PLATFORM_SNPRINTF_MACRO #else -#define mbedtls_snprintf snprintf +#define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF #endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */ #endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */ @@ -218,11 +234,13 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n, extern void (*mbedtls_exit)( int status ); /** - * \brief Set your own exit function pointer + * \brief This function dynamically configures the exit + * function that is called when the mbedtls_exit() + * function is invoked by the library. * - * \param exit_func the exit function implementation + * \param exit_func The \c exit function implementation. * - * \return 0 + * \return \c 0 on success. */ int mbedtls_platform_set_exit( void (*exit_func)( int status ) ); #else @@ -265,12 +283,13 @@ extern int (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len ); extern int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len ); /** - * \brief Set your own seed file writing/reading functions + * \brief This function allows configuring custom seed file writing and + * reading functions. * - * \param nv_seed_read_func the seed reading function implementation - * \param nv_seed_write_func the seed writing function implementation + * \param nv_seed_read_func The seed reading function implementation. + * \param nv_seed_write_func The seed writing function implementation. * - * \return 0 + * \return \c 0 on success. */ int mbedtls_platform_set_nv_seed( int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ), @@ -291,13 +310,14 @@ int mbedtls_platform_set_nv_seed( #if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT) /** - * \brief Platform context structure + * \brief The platform context structure. * * \note This structure may be used to assist platform-specific - * setup/teardown operations. + * setup or teardown operations. */ -typedef struct { - char dummy; /**< Placeholder member as empty structs are not portable */ +typedef struct mbedtls_platform_context +{ + char dummy; /**< A placeholder member, as empty structs are not portable. */ } mbedtls_platform_context; @@ -306,33 +326,34 @@ mbedtls_platform_context; #endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */ /** - * \brief Perform any platform initialisation operations + * \brief This function performs any platform-specific initialization + * operations. + * + * \note This function should be called before any other library functions. * - * \param ctx mbed TLS context + * Its implementation is platform-specific, and unless + * platform-specific code is provided, it does nothing. * - * \return 0 if successful + * \note The usage and necessity of this function is dependent on the platform. * - * \note This function is intended to allow platform specific initialisation, - * and should be called before any other library functions. Its - * implementation is platform specific, and by default, unless platform - * specific code is provided, it does nothing. + * \param ctx The platform context. * - * Its use and whether its necessary to be called is dependent on the - * platform. + * \return \c 0 on success. */ int mbedtls_platform_setup( mbedtls_platform_context *ctx ); /** - * \brief Perform any platform teardown operations + * \brief This function performs any platform teardown operations. + * + * \note This function should be called after every other Mbed TLS module + * has been correctly freed using the appropriate free function. + * + * Its implementation is platform-specific, and unless + * platform-specific code is provided, it does nothing. * - * \param ctx mbed TLS context + * \note The usage and necessity of this function is dependent on the platform. * - * \note This function should be called after every other mbed TLS module has - * been correctly freed using the appropriate free function. - * Its implementation is platform specific, and by default, unless - * platform specific code is provided, it does nothing. + * \param ctx The platform context. * - * Its use and whether its necessary to be called is dependent on the - * platform. */ void mbedtls_platform_teardown( mbedtls_platform_context *ctx ); diff --git a/tools/sdk/include/mbedtls/mbedtls/platform_time.h b/tools/sdk/include/mbedtls/mbedtls/platform_time.h index abb3431420f..2ed36f56c9e 100644 --- a/tools/sdk/include/mbedtls/mbedtls/platform_time.h +++ b/tools/sdk/include/mbedtls/mbedtls/platform_time.h @@ -2,7 +2,8 @@ * \file platform_time.h * * \brief mbed TLS Platform time abstraction - * + */ +/* * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/platform_util.h b/tools/sdk/include/mbedtls/mbedtls/platform_util.h new file mode 100644 index 00000000000..164a1a05f9d --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/platform_util.h @@ -0,0 +1,103 @@ +/** + * \file platform_util.h + * + * \brief Common and shared functions used by multiple modules in the Mbed TLS + * library. + */ +/* + * Copyright (C) 2018, Arm Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PLATFORM_UTIL_H +#define MBEDTLS_PLATFORM_UTIL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#if defined(MBEDTLS_HAVE_TIME_DATE) +#include "mbedtls/platform_time.h" +#include +#endif /* MBEDTLS_HAVE_TIME_DATE */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Securely zeroize a buffer + * + * The function is meant to wipe the data contained in a buffer so + * that it can no longer be recovered even if the program memory + * is later compromised. Call this function on sensitive data + * stored on the stack before returning from a function, and on + * sensitive data stored on the heap before freeing the heap + * object. + * + * It is extremely difficult to guarantee that calls to + * mbedtls_platform_zeroize() are not removed by aggressive + * compiler optimizations in a portable way. For this reason, Mbed + * TLS provides the configuration option + * MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure + * mbedtls_platform_zeroize() to use a suitable implementation for + * their platform and needs + * + * \param buf Buffer to be zeroized + * \param len Length of the buffer in bytes + * + */ +void mbedtls_platform_zeroize( void *buf, size_t len ); + +#if defined(MBEDTLS_HAVE_TIME_DATE) +/** + * \brief Platform-specific implementation of gmtime_r() + * + * The function is a thread-safe abstraction that behaves + * similarly to the gmtime_r() function from Unix/POSIX. + * + * Mbed TLS will try to identify the underlying platform and + * make use of an appropriate underlying implementation (e.g. + * gmtime_r() for POSIX and gmtime_s() for Windows). If this is + * not possible, then gmtime() will be used. In this case, calls + * from the library to gmtime() will be guarded by the mutex + * mbedtls_threading_gmtime_mutex if MBEDTLS_THREADING_C is + * enabled. It is recommended that calls from outside the library + * are also guarded by this mutex. + * + * If MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, then Mbed TLS will + * unconditionally use the alternative implementation for + * mbedtls_platform_gmtime_r() supplied by the user at compile time. + * + * \param tt Pointer to an object containing time (in seconds) since the + * epoch to be converted + * \param tm_buf Pointer to an object where the results will be stored + * + * \return Pointer to an object of type struct tm on success, otherwise + * NULL + */ +struct tm *mbedtls_platform_gmtime_r( const mbedtls_time_t *tt, + struct tm *tm_buf ); +#endif /* MBEDTLS_HAVE_TIME_DATE */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_PLATFORM_UTIL_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/poly1305.h b/tools/sdk/include/mbedtls/mbedtls/poly1305.h new file mode 100644 index 00000000000..c490cdf2bd1 --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/poly1305.h @@ -0,0 +1,181 @@ +/** + * \file poly1305.h + * + * \brief This file contains Poly1305 definitions and functions. + * + * Poly1305 is a one-time message authenticator that can be used to + * authenticate messages. Poly1305-AES was created by Daniel + * Bernstein https://cr.yp.to/mac/poly1305-20050329.pdf The generic + * Poly1305 algorithm (not tied to AES) was also standardized in RFC + * 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_POLY1305_H +#define MBEDTLS_POLY1305_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA -0x0057 /**< Invalid input parameter(s). */ +#define MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE -0x0059 /**< Feature not available. For example, s part of the API is not implemented. */ +#define MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED -0x005B /**< Poly1305 hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_POLY1305_ALT) + +typedef struct mbedtls_poly1305_context +{ + uint32_t r[4]; /** The value for 'r' (low 128 bits of the key). */ + uint32_t s[4]; /** The value for 's' (high 128 bits of the key). */ + uint32_t acc[5]; /** The accumulator number. */ + uint8_t queue[16]; /** The current partial block of data. */ + size_t queue_len; /** The number of bytes stored in 'queue'. */ +} +mbedtls_poly1305_context; + +#else /* MBEDTLS_POLY1305_ALT */ +#include "poly1305_alt.h" +#endif /* MBEDTLS_POLY1305_ALT */ + +/** + * \brief This function initializes the specified Poly1305 context. + * + * It must be the first API called before using + * the context. + * + * It is usually followed by a call to + * \c mbedtls_poly1305_starts(), then one or more calls to + * \c mbedtls_poly1305_update(), then one call to + * \c mbedtls_poly1305_finish(), then finally + * \c mbedtls_poly1305_free(). + * + * \param ctx The Poly1305 context to initialize. + */ +void mbedtls_poly1305_init( mbedtls_poly1305_context *ctx ); + +/** + * \brief This function releases and clears the specified Poly1305 context. + * + * \param ctx The Poly1305 context to clear. + */ +void mbedtls_poly1305_free( mbedtls_poly1305_context *ctx ); + +/** + * \brief This function sets the one-time authentication key. + * + * \warning The key must be unique and unpredictable for each + * invocation of Poly1305. + * + * \param ctx The Poly1305 context to which the key should be bound. + * \param key The buffer containing the 256-bit key. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if ctx or key are NULL. + */ +int mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This functions feeds an input buffer into an ongoing + * Poly1305 computation. + * + * It is called between \c mbedtls_cipher_poly1305_starts() and + * \c mbedtls_cipher_poly1305_finish(). + * It can be called repeatedly to process a stream of data. + * + * \param ctx The Poly1305 context to use for the Poly1305 operation. + * \param ilen The length of the input data (in bytes). Any value is accepted. + * \param input The buffer holding the input data. + * This pointer can be NULL if ilen == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if ctx or input are NULL. + */ +int mbedtls_poly1305_update( mbedtls_poly1305_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function generates the Poly1305 Message + * Authentication Code (MAC). + * + * \param ctx The Poly1305 context to use for the Poly1305 operation. + * \param mac The buffer to where the MAC is written. Must be big enough + * to hold the 16-byte MAC. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if ctx or mac are NULL. + */ +int mbedtls_poly1305_finish( mbedtls_poly1305_context *ctx, + unsigned char mac[16] ); + +/** + * \brief This function calculates the Poly1305 MAC of the input + * buffer with the provided key. + * + * \warning The key must be unique and unpredictable for each + * invocation of Poly1305. + * + * \param key The buffer containing the 256-bit key. + * \param ilen The length of the input data (in bytes). Any value is accepted. + * \param input The buffer holding the input data. + * This pointer can be NULL if ilen == 0. + * \param mac The buffer to where the MAC is written. Must be big enough + * to hold the 16-byte MAC. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if key, input, or mac are NULL. + */ +int mbedtls_poly1305_mac( const unsigned char key[32], + const unsigned char *input, + size_t ilen, + unsigned char mac[16] ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The Poly1305 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_poly1305_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_POLY1305_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/ripemd160.h b/tools/sdk/include/mbedtls/mbedtls/ripemd160.h index 7083fc8599f..0c8e568b9ec 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ripemd160.h +++ b/tools/sdk/include/mbedtls/mbedtls/ripemd160.h @@ -2,7 +2,8 @@ * \file ripemd160.h * * \brief RIPE MD-160 message digest - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -32,18 +33,20 @@ #include #include -#if !defined(MBEDTLS_RIPEMD160_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED -0x0031 /**< RIPEMD160 hardware accelerator failed */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_RIPEMD160_ALT) +// Regular implementation +// + /** * \brief RIPEMD-160 context structure */ -typedef struct +typedef struct mbedtls_ripemd160_context { uint32_t total[2]; /*!< number of bytes processed */ uint32_t state[5]; /*!< intermediate digest state */ @@ -51,6 +54,10 @@ typedef struct } mbedtls_ripemd160_context; +#else /* MBEDTLS_RIPEMD160_ALT */ +#include "ripemd160.h" +#endif /* MBEDTLS_RIPEMD160_ALT */ + /** * \brief Initialize RIPEMD-160 context * @@ -78,51 +85,137 @@ void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst, * \brief RIPEMD-160 context setup * * \param ctx context to be initialized + * + * \return 0 if successful */ -void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx ); +int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx ); /** * \brief RIPEMD-160 process buffer * * \param ctx RIPEMD-160 context - * \param input buffer holding the data + * \param input buffer holding the data * \param ilen length of the input data + * + * \return 0 if successful */ -void mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx, - const unsigned char *input, size_t ilen ); +int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx, + const unsigned char *input, + size_t ilen ); /** * \brief RIPEMD-160 final digest * * \param ctx RIPEMD-160 context * \param output RIPEMD-160 checksum result + * + * \return 0 if successful */ -void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx, unsigned char output[20] ); +int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx, + unsigned char output[20] ); -/* Internal use */ -void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx, const unsigned char data[64] ); +/** + * \brief RIPEMD-160 process data block (internal use only) + * + * \param ctx RIPEMD-160 context + * \param data buffer holding one block of data + * + * \return 0 if successful + */ +int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx, + const unsigned char data[64] ); -#ifdef __cplusplus -} +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED #endif +/** + * \brief RIPEMD-160 context setup + * + * \deprecated Superseded by mbedtls_ripemd160_starts_ret() in 2.7.0 + * + * \param ctx context to be initialized + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160_starts( + mbedtls_ripemd160_context *ctx ); -#else /* MBEDTLS_RIPEMD160_ALT */ -#include "ripemd160.h" -#endif /* MBEDTLS_RIPEMD160_ALT */ +/** + * \brief RIPEMD-160 process buffer + * + * \deprecated Superseded by mbedtls_ripemd160_update_ret() in 2.7.0 + * + * \param ctx RIPEMD-160 context + * \param input buffer holding the data + * \param ilen length of the input data + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160_update( + mbedtls_ripemd160_context *ctx, + const unsigned char *input, + size_t ilen ); -#ifdef __cplusplus -extern "C" { -#endif +/** + * \brief RIPEMD-160 final digest + * + * \deprecated Superseded by mbedtls_ripemd160_finish_ret() in 2.7.0 + * + * \param ctx RIPEMD-160 context + * \param output RIPEMD-160 checksum result + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160_finish( + mbedtls_ripemd160_context *ctx, + unsigned char output[20] ); + +/** + * \brief RIPEMD-160 process data block (internal use only) + * + * \deprecated Superseded by mbedtls_internal_ripemd160_process() in 2.7.0 + * + * \param ctx RIPEMD-160 context + * \param data buffer holding one block of data + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160_process( + mbedtls_ripemd160_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief Output = RIPEMD-160( input buffer ) * - * \param input buffer holding the data + * \param input buffer holding the data * \param ilen length of the input data * \param output RIPEMD-160 checksum result + * + * \return 0 if successful */ -void mbedtls_ripemd160( const unsigned char *input, size_t ilen, - unsigned char output[20] ); +int mbedtls_ripemd160_ret( const unsigned char *input, + size_t ilen, + unsigned char output[20] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Output = RIPEMD-160( input buffer ) + * + * \deprecated Superseded by mbedtls_ripemd160_ret() in 2.7.0 + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output RIPEMD-160 checksum result + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160( const unsigned char *input, + size_t ilen, + unsigned char output[20] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief Checkup routine diff --git a/tools/sdk/include/mbedtls/mbedtls/rsa.h b/tools/sdk/include/mbedtls/mbedtls/rsa.h index 7d7469d509e..6eea5af2f09 100644 --- a/tools/sdk/include/mbedtls/mbedtls/rsa.h +++ b/tools/sdk/include/mbedtls/mbedtls/rsa.h @@ -1,9 +1,16 @@ /** * \file rsa.h * - * \brief The RSA public-key cryptosystem + * \brief This file provides an API for the RSA public-key cryptosystem. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * The RSA public-key cryptosystem is defined in Public-Key + * Cryptography Standards (PKCS) #1 v1.5: RSA Encryption + * and Public-Key Cryptography Standards (PKCS) #1 v2.1: + * RSA Cryptography Specifications. + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,7 +25,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_RSA_H #define MBEDTLS_RSA_H @@ -42,24 +49,26 @@ #define MBEDTLS_ERR_RSA_BAD_INPUT_DATA -0x4080 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_RSA_INVALID_PADDING -0x4100 /**< Input data contains invalid padding and is rejected. */ #define MBEDTLS_ERR_RSA_KEY_GEN_FAILED -0x4180 /**< Something failed during generation of a key. */ -#define MBEDTLS_ERR_RSA_KEY_CHECK_FAILED -0x4200 /**< Key failed to pass the library's validity check. */ +#define MBEDTLS_ERR_RSA_KEY_CHECK_FAILED -0x4200 /**< Key failed to pass the validity check of the library. */ #define MBEDTLS_ERR_RSA_PUBLIC_FAILED -0x4280 /**< The public key operation failed. */ #define MBEDTLS_ERR_RSA_PRIVATE_FAILED -0x4300 /**< The private key operation failed. */ #define MBEDTLS_ERR_RSA_VERIFY_FAILED -0x4380 /**< The PKCS#1 verification failed. */ #define MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE -0x4400 /**< The output buffer for decryption is not large enough. */ #define MBEDTLS_ERR_RSA_RNG_FAILED -0x4480 /**< The random generator failed to generate non-zeros. */ +#define MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION -0x4500 /**< The implementation does not offer the requested operation, for example, because of security violations or lack of functionality. */ +#define MBEDTLS_ERR_RSA_HW_ACCEL_FAILED -0x4580 /**< RSA hardware accelerator failed. */ /* * RSA constants */ -#define MBEDTLS_RSA_PUBLIC 0 -#define MBEDTLS_RSA_PRIVATE 1 +#define MBEDTLS_RSA_PUBLIC 0 /**< Request private key operation. */ +#define MBEDTLS_RSA_PRIVATE 1 /**< Request public key operation. */ -#define MBEDTLS_RSA_PKCS_V15 0 -#define MBEDTLS_RSA_PKCS_V21 1 +#define MBEDTLS_RSA_PKCS_V15 0 /**< Use PKCS#1 v1.5 encoding. */ +#define MBEDTLS_RSA_PKCS_V21 1 /**< Use PKCS#1 v2.1 encoding. */ -#define MBEDTLS_RSA_SIGN 1 -#define MBEDTLS_RSA_CRYPT 2 +#define MBEDTLS_RSA_SIGN 1 /**< Identifier for RSA signature operations. */ +#define MBEDTLS_RSA_CRYPT 2 /**< Identifier for RSA encryption and decryption operations. */ #define MBEDTLS_RSA_SALT_LEN_ANY -1 @@ -67,168 +76,469 @@ * The above constants may be used even if the RSA module is compile out, * eg for alternative (PKCS#11) RSA implemenations in the PK layers. */ -#if defined(MBEDTLS_RSA_C) #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_RSA_ALT) +// Regular implementation +// + /** - * \brief RSA context structure + * \brief The RSA context structure. + * + * \note Direct manipulation of the members of this structure + * is deprecated. All manipulation should instead be done through + * the public interface functions. */ -typedef struct +typedef struct mbedtls_rsa_context { - int ver; /*!< always 0 */ - size_t len; /*!< size(N) in chars */ - - mbedtls_mpi N; /*!< public modulus */ - mbedtls_mpi E; /*!< public exponent */ - - mbedtls_mpi D; /*!< private exponent */ - mbedtls_mpi P; /*!< 1st prime factor */ - mbedtls_mpi Q; /*!< 2nd prime factor */ - mbedtls_mpi DP; /*!< D % (P - 1) */ - mbedtls_mpi DQ; /*!< D % (Q - 1) */ - mbedtls_mpi QP; /*!< 1 / (Q % P) */ - - mbedtls_mpi RN; /*!< cached R^2 mod N */ - mbedtls_mpi RP; /*!< cached R^2 mod P */ - mbedtls_mpi RQ; /*!< cached R^2 mod Q */ - - mbedtls_mpi Vi; /*!< cached blinding value */ - mbedtls_mpi Vf; /*!< cached un-blinding value */ - - int padding; /*!< MBEDTLS_RSA_PKCS_V15 for 1.5 padding and - MBEDTLS_RSA_PKCS_v21 for OAEP/PSS */ - int hash_id; /*!< Hash identifier of mbedtls_md_type_t as - specified in the mbedtls_md.h header file - for the EME-OAEP and EMSA-PSS - encoding */ + int ver; /*!< Always 0.*/ + size_t len; /*!< The size of \p N in Bytes. */ + + mbedtls_mpi N; /*!< The public modulus. */ + mbedtls_mpi E; /*!< The public exponent. */ + + mbedtls_mpi D; /*!< The private exponent. */ + mbedtls_mpi P; /*!< The first prime factor. */ + mbedtls_mpi Q; /*!< The second prime factor. */ + + mbedtls_mpi DP; /*!< D % (P - 1). */ + mbedtls_mpi DQ; /*!< D % (Q - 1). */ + mbedtls_mpi QP; /*!< 1 / (Q % P). */ + + mbedtls_mpi RN; /*!< cached R^2 mod N. */ + + mbedtls_mpi RP; /*!< cached R^2 mod P. */ + mbedtls_mpi RQ; /*!< cached R^2 mod Q. */ + + mbedtls_mpi Vi; /*!< The cached blinding value. */ + mbedtls_mpi Vf; /*!< The cached un-blinding value. */ + + int padding; /*!< Selects padding mode: + #MBEDTLS_RSA_PKCS_V15 for 1.5 padding and + #MBEDTLS_RSA_PKCS_V21 for OAEP or PSS. */ + int hash_id; /*!< Hash identifier of mbedtls_md_type_t type, + as specified in md.h for use in the MGF + mask generating function used in the + EME-OAEP and EMSA-PSS encodings. */ #if defined(MBEDTLS_THREADING_C) - mbedtls_threading_mutex_t mutex; /*!< Thread-safety mutex */ + mbedtls_threading_mutex_t mutex; /*!< Thread-safety mutex. */ #endif } mbedtls_rsa_context; +#else /* MBEDTLS_RSA_ALT */ +#include "rsa_alt.h" +#endif /* MBEDTLS_RSA_ALT */ + /** - * \brief Initialize an RSA context + * \brief This function initializes an RSA context. * - * Note: Set padding to MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP + * \note Set padding to #MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP * encryption scheme and the RSASSA-PSS signature scheme. * - * \param ctx RSA context to be initialized - * \param padding MBEDTLS_RSA_PKCS_V15 or MBEDTLS_RSA_PKCS_V21 - * \param hash_id MBEDTLS_RSA_PKCS_V21 hash identifier - * - * \note The hash_id parameter is actually ignored - * when using MBEDTLS_RSA_PKCS_V15 padding. + * \note The \p hash_id parameter is ignored when using + * #MBEDTLS_RSA_PKCS_V15 padding. * - * \note Choice of padding mode is strictly enforced for private key + * \note The choice of padding mode is strictly enforced for private key * operations, since there might be security concerns in - * mixing padding modes. For public key operations it's merely + * mixing padding modes. For public key operations it is * a default value, which can be overriden by calling specific - * rsa_rsaes_xxx or rsa_rsassa_xxx functions. - * - * \note The chosen hash is always used for OEAP encryption. - * For PSS signatures, it's always used for making signatures, - * but can be overriden (and always is, if set to - * MBEDTLS_MD_NONE) for verifying them. + * \c rsa_rsaes_xxx or \c rsa_rsassa_xxx functions. + * + * \note The hash selected in \p hash_id is always used for OEAP + * encryption. For PSS signatures, it is always used for + * making signatures, but can be overriden for verifying them. + * If set to #MBEDTLS_MD_NONE, it is always overriden. + * + * \param ctx The RSA context to initialize. + * \param padding Selects padding mode: #MBEDTLS_RSA_PKCS_V15 or + * #MBEDTLS_RSA_PKCS_V21. + * \param hash_id The hash identifier of #mbedtls_md_type_t type, if + * \p padding is #MBEDTLS_RSA_PKCS_V21. */ void mbedtls_rsa_init( mbedtls_rsa_context *ctx, - int padding, - int hash_id); + int padding, + int hash_id); /** - * \brief Set padding for an already initialized RSA context - * See \c mbedtls_rsa_init() for details. + * \brief This function imports a set of core parameters into an + * RSA context. + * + * \note This function can be called multiple times for successive + * imports, if the parameters are not simultaneously present. * - * \param ctx RSA context to be set - * \param padding MBEDTLS_RSA_PKCS_V15 or MBEDTLS_RSA_PKCS_V21 - * \param hash_id MBEDTLS_RSA_PKCS_V21 hash identifier + * Any sequence of calls to this function should be followed + * by a call to mbedtls_rsa_complete(), which checks and + * completes the provided information to a ready-for-use + * public or private RSA key. + * + * \note See mbedtls_rsa_complete() for more information on which + * parameters are necessary to set up a private or public + * RSA key. + * + * \note The imported parameters are copied and need not be preserved + * for the lifetime of the RSA context being set up. + * + * \param ctx The initialized RSA context to store the parameters in. + * \param N The RSA modulus, or NULL. + * \param P The first prime factor of \p N, or NULL. + * \param Q The second prime factor of \p N, or NULL. + * \param D The private exponent, or NULL. + * \param E The public exponent, or NULL. + * + * \return \c 0 on success. + * \return A non-zero error code on failure. */ -void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id); +int mbedtls_rsa_import( mbedtls_rsa_context *ctx, + const mbedtls_mpi *N, + const mbedtls_mpi *P, const mbedtls_mpi *Q, + const mbedtls_mpi *D, const mbedtls_mpi *E ); /** - * \brief Generate an RSA keypair + * \brief This function imports core RSA parameters, in raw big-endian + * binary format, into an RSA context. + * + * \note This function can be called multiple times for successive + * imports, if the parameters are not simultaneously present. + * + * Any sequence of calls to this function should be followed + * by a call to mbedtls_rsa_complete(), which checks and + * completes the provided information to a ready-for-use + * public or private RSA key. + * + * \note See mbedtls_rsa_complete() for more information on which + * parameters are necessary to set up a private or public + * RSA key. + * + * \note The imported parameters are copied and need not be preserved + * for the lifetime of the RSA context being set up. + * + * \param ctx The initialized RSA context to store the parameters in. + * \param N The RSA modulus, or NULL. + * \param N_len The Byte length of \p N, ignored if \p N == NULL. + * \param P The first prime factor of \p N, or NULL. + * \param P_len The Byte length of \p P, ignored if \p P == NULL. + * \param Q The second prime factor of \p N, or NULL. + * \param Q_len The Byte length of \p Q, ignored if \p Q == NULL. + * \param D The private exponent, or NULL. + * \param D_len The Byte length of \p D, ignored if \p D == NULL. + * \param E The public exponent, or NULL. + * \param E_len The Byte length of \p E, ignored if \p E == NULL. + * + * \return \c 0 on success. + * \return A non-zero error code on failure. + */ +int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx, + unsigned char const *N, size_t N_len, + unsigned char const *P, size_t P_len, + unsigned char const *Q, size_t Q_len, + unsigned char const *D, size_t D_len, + unsigned char const *E, size_t E_len ); + +/** + * \brief This function completes an RSA context from + * a set of imported core parameters. + * + * To setup an RSA public key, precisely \p N and \p E + * must have been imported. * - * \param ctx RSA context that will hold the key - * \param f_rng RNG function - * \param p_rng RNG parameter - * \param nbits size of the public key in bits - * \param exponent public exponent (e.g., 65537) + * To setup an RSA private key, sufficient information must + * be present for the other parameters to be derivable. * - * \note mbedtls_rsa_init() must be called beforehand to setup - * the RSA context. + * The default implementation supports the following: + *
  • Derive \p P, \p Q from \p N, \p D, \p E.
  • + *
  • Derive \p N, \p D from \p P, \p Q, \p E.
+ * Alternative implementations need not support these. + * + * If this function runs successfully, it guarantees that + * the RSA context can be used for RSA operations without + * the risk of failure or crash. + * + * \warning This function need not perform consistency checks + * for the imported parameters. In particular, parameters that + * are not needed by the implementation might be silently + * discarded and left unchecked. To check the consistency + * of the key material, see mbedtls_rsa_check_privkey(). + * + * \param ctx The initialized RSA context holding imported parameters. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_RSA_BAD_INPUT_DATA if the attempted derivations + * failed. * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code */ -int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - unsigned int nbits, int exponent ); +int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ); /** - * \brief Check a public RSA key + * \brief This function exports the core parameters of an RSA key. + * + * If this function runs successfully, the non-NULL buffers + * pointed to by \p N, \p P, \p Q, \p D, and \p E are fully + * written, with additional unused space filled leading by + * zero Bytes. + * + * Possible reasons for returning + * #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
    + *
  • An alternative RSA implementation is in use, which + * stores the key externally, and either cannot or should + * not export it into RAM.
  • + *
  • A SW or HW implementation might not support a certain + * deduction. For example, \p P, \p Q from \p N, \p D, + * and \p E if the former are not part of the + * implementation.
+ * + * If the function fails due to an unsupported operation, + * the RSA context stays intact and remains usable. + * + * \param ctx The initialized RSA context. + * \param N The MPI to hold the RSA modulus, or NULL. + * \param P The MPI to hold the first prime factor of \p N, or NULL. + * \param Q The MPI to hold the second prime factor of \p N, or NULL. + * \param D The MPI to hold the private exponent, or NULL. + * \param E The MPI to hold the public exponent, or NULL. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the + * requested parameters cannot be done due to missing + * functionality or because of security policies. + * \return A non-zero return code on any other failure. * - * \param ctx RSA context to be checked + */ +int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, + mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q, + mbedtls_mpi *D, mbedtls_mpi *E ); + +/** + * \brief This function exports core parameters of an RSA key + * in raw big-endian binary format. + * + * If this function runs successfully, the non-NULL buffers + * pointed to by \p N, \p P, \p Q, \p D, and \p E are fully + * written, with additional unused space filled leading by + * zero Bytes. + * + * Possible reasons for returning + * #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
    + *
  • An alternative RSA implementation is in use, which + * stores the key externally, and either cannot or should + * not export it into RAM.
  • + *
  • A SW or HW implementation might not support a certain + * deduction. For example, \p P, \p Q from \p N, \p D, + * and \p E if the former are not part of the + * implementation.
+ * If the function fails due to an unsupported operation, + * the RSA context stays intact and remains usable. + * + * \note The length parameters are ignored if the corresponding + * buffer pointers are NULL. + * + * \param ctx The initialized RSA context. + * \param N The Byte array to store the RSA modulus, or NULL. + * \param N_len The size of the buffer for the modulus. + * \param P The Byte array to hold the first prime factor of \p N, or + * NULL. + * \param P_len The size of the buffer for the first prime factor. + * \param Q The Byte array to hold the second prime factor of \p N, or + * NULL. + * \param Q_len The size of the buffer for the second prime factor. + * \param D The Byte array to hold the private exponent, or NULL. + * \param D_len The size of the buffer for the private exponent. + * \param E The Byte array to hold the public exponent, or NULL. + * \param E_len The size of the buffer for the public exponent. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the + * requested parameters cannot be done due to missing + * functionality or because of security policies. + * \return A non-zero return code on any other failure. + */ +int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx, + unsigned char *N, size_t N_len, + unsigned char *P, size_t P_len, + unsigned char *Q, size_t Q_len, + unsigned char *D, size_t D_len, + unsigned char *E, size_t E_len ); + +/** + * \brief This function exports CRT parameters of a private RSA key. + * + * \note Alternative RSA implementations not using CRT-parameters + * internally can implement this function based on + * mbedtls_rsa_deduce_opt(). + * + * \param ctx The initialized RSA context. + * \param DP The MPI to hold D modulo P-1, or NULL. + * \param DQ The MPI to hold D modulo Q-1, or NULL. + * \param QP The MPI to hold modular inverse of Q modulo P, or NULL. + * + * \return \c 0 on success. + * \return A non-zero error code on failure. * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code */ -int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ); +int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx, + mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ); + +/** + * \brief This function sets padding for an already initialized RSA + * context. See mbedtls_rsa_init() for details. + * + * \param ctx The RSA context to be set. + * \param padding Selects padding mode: #MBEDTLS_RSA_PKCS_V15 or + * #MBEDTLS_RSA_PKCS_V21. + * \param hash_id The #MBEDTLS_RSA_PKCS_V21 hash identifier. + */ +void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, + int hash_id); /** - * \brief Check a private RSA key + * \brief This function retrieves the length of RSA modulus in Bytes. + * + * \param ctx The initialized RSA context. * - * \param ctx RSA context to be checked + * \return The length of the RSA modulus in Bytes. * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code */ -int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ); +size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx ); /** - * \brief Check a public-private RSA key pair. - * Check each of the contexts, and make sure they match. + * \brief This function generates an RSA keypair. + * + * \note mbedtls_rsa_init() must be called before this function, + * to set up the RSA context. * - * \param pub RSA context holding the public key - * \param prv RSA context holding the private key + * \param ctx The RSA context used to hold the key. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * \param nbits The size of the public key in bits. + * \param exponent The public exponent. For example, 65537. * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ -int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv ); +int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + unsigned int nbits, int exponent ); + +/** + * \brief This function checks if a context contains at least an RSA + * public key. + * + * If the function runs successfully, it is guaranteed that + * enough information is present to perform an RSA public key + * operation using mbedtls_rsa_public(). + * + * \param ctx The RSA context to check. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + * + */ +int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ); + +/** + * \brief This function checks if a context contains an RSA private key + * and perform basic consistency checks. + * + * \note The consistency checks performed by this function not only + * ensure that mbedtls_rsa_private() can be called successfully + * on the given context, but that the various parameters are + * mutually consistent with high probability, in the sense that + * mbedtls_rsa_public() and mbedtls_rsa_private() are inverses. + * + * \warning This function should catch accidental misconfigurations + * like swapping of parameters, but it cannot establish full + * trust in neither the quality nor the consistency of the key + * material that was used to setup the given RSA context: + *
  • Consistency: Imported parameters that are irrelevant + * for the implementation might be silently dropped. If dropped, + * the current function does not have access to them, + * and therefore cannot check them. See mbedtls_rsa_complete(). + * If you want to check the consistency of the entire + * content of an PKCS1-encoded RSA private key, for example, you + * should use mbedtls_rsa_validate_params() before setting + * up the RSA context. + * Additionally, if the implementation performs empirical checks, + * these checks substantiate but do not guarantee consistency.
  • + *
  • Quality: This function is not expected to perform + * extended quality assessments like checking that the prime + * factors are safe. Additionally, it is the responsibility of the + * user to ensure the trustworthiness of the source of his RSA + * parameters, which goes beyond what is effectively checkable + * by the library.
+ * + * \param ctx The RSA context to check. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ); /** - * \brief Do an RSA public key operation + * \brief This function checks a public-private RSA key pair. * - * \param ctx RSA context - * \param input input buffer - * \param output output buffer + * It checks each of the contexts, and makes sure they match. * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code + * \param pub The RSA context holding the public key. + * \param prv The RSA context holding the private key. * - * \note This function does NOT take care of message - * padding. Also, be sure to set input[0] = 0 or ensure that - * input is smaller than N. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, + const mbedtls_rsa_context *prv ); + +/** + * \brief This function performs an RSA public key operation. + * + * \note This function does not handle message padding. + * + * \note Make sure to set \p input[0] = 0 or ensure that + * input is smaller than \p N. * * \note The input and output buffers must be large - * enough (eg. 128 bytes if RSA-1024 is used). + * enough. For example, 128 Bytes if RSA-1024 is used. + * + * \param ctx The RSA context. + * \param input The input buffer. + * \param output The output buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_public( mbedtls_rsa_context *ctx, const unsigned char *input, unsigned char *output ); /** - * \brief Do an RSA private key operation + * \brief This function performs an RSA private key operation. + * + * \note The input and output buffers must be large + * enough. For example, 128 Bytes if RSA-1024 is used. * - * \param ctx RSA context - * \param f_rng RNG function (Needed for blinding) - * \param p_rng RNG parameter - * \param input input buffer - * \param output output buffer + * \note Blinding is used if and only if a PRNG is provided. * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code + * \note If blinding is used, both the base of exponentation + * and the exponent are blinded, providing protection + * against some side-channel attacks. + * + * \warning It is deprecated and a security risk to not provide + * a PRNG here and thereby prevent the use of blinding. + * Future versions of the library may enforce the presence + * of a PRNG. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for blinding. + * \param p_rng The RNG context. + * \param input The input buffer. + * \param output The output buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. * - * \note The input and output buffers must be large - * enough (eg. 128 bytes if RSA-1024 is used). */ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -237,23 +547,35 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, unsigned char *output ); /** - * \brief Generic wrapper to perform a PKCS#1 encryption using the - * mode from the context. Add the message padding, then do an - * RSA operation. - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for padding and PKCS#1 v2.1 encoding - * and MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param ilen contains the plaintext length - * \param input buffer holding the data to be encrypted - * \param output buffer that will hold the ciphertext - * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). + * \brief This function adds the message padding, then performs an RSA + * operation. + * + * It is the generic wrapper for performing a PKCS#1 encryption + * operation using the \p mode from the context. + * + * \note The input and output buffers must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for padding, PKCS#1 v2.1 + * encoding, and #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param ilen The length of the plaintext. + * \param input The buffer holding the data to encrypt. + * \param output The buffer used to hold the ciphertext. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -263,20 +585,32 @@ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, unsigned char *output ); /** - * \brief Perform a PKCS#1 v1.5 encryption (RSAES-PKCS1-v1_5-ENCRYPT) - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for padding and MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param ilen contains the plaintext length - * \param input buffer holding the data to be encrypted - * \param output buffer that will hold the ciphertext - * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code + * \brief This function performs a PKCS#1 v1.5 encryption operation + * (RSAES-PKCS1-v1_5-ENCRYPT). * * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for padding and + * #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param ilen The length of the plaintext. + * \param input The buffer holding the data to encrypt. + * \param output The buffer used to hold the ciphertext. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -286,23 +620,34 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, unsigned char *output ); /** - * \brief Perform a PKCS#1 v2.1 OAEP encryption (RSAES-OAEP-ENCRYPT) - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for padding and PKCS#1 v2.1 encoding - * and MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param label buffer holding the custom label to use - * \param label_len contains the label length - * \param ilen contains the plaintext length - * \param input buffer holding the data to be encrypted - * \param output buffer that will hold the ciphertext - * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). + * \brief This function performs a PKCS#1 v2.1 OAEP encryption + * operation (RSAES-OAEP-ENCRYPT). + * + * \note The output buffer must be as large as the size + * of ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for padding and PKCS#1 v2.1 + * encoding and #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param label The buffer holding the custom label to use. + * \param label_len The length of the label. + * \param ilen The length of the plaintext. + * \param input The buffer holding the data to encrypt. + * \param output The buffer used to hold the ciphertext. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -314,30 +659,42 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, unsigned char *output ); /** - * \brief Generic wrapper to perform a PKCS#1 decryption using the - * mode from the context. Do an RSA operation, then remove - * the message padding - * - * \param ctx RSA context - * \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param olen will contain the plaintext length - * \param input buffer holding the encrypted data - * \param output buffer that will hold the plaintext - * \param output_max_len maximum length of the output buffer + * \brief This function performs an RSA operation, then removes the + * message padding. * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code + * It is the generic wrapper for performing a PKCS#1 decryption + * operation using the \p mode from the context. * * \note The output buffer length \c output_max_len should be - * as large as the size ctx->len of ctx->N (eg. 128 bytes - * if RSA-1024 is used) to be able to hold an arbitrary - * decrypted message. If it is not large enough to hold - * the decryption of the particular ciphertext provided, - * the function will return MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * as large as the size \p ctx->len of \p ctx->N (for example, + * 128 Bytes if RSA-1024 is used) to be able to hold an + * arbitrary decrypted message. If it is not large enough to + * hold the decryption of the particular ciphertext provided, + * the function returns \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. * * \note The input buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param olen The length of the plaintext. + * \param input The buffer holding the encrypted data. + * \param output The buffer used to hold the plaintext. + * \param output_max_len The maximum length of the output buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -348,28 +705,40 @@ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, size_t output_max_len ); /** - * \brief Perform a PKCS#1 v1.5 decryption (RSAES-PKCS1-v1_5-DECRYPT) - * - * \param ctx RSA context - * \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param olen will contain the plaintext length - * \param input buffer holding the encrypted data - * \param output buffer that will hold the plaintext - * \param output_max_len maximum length of the output buffer - * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code + * \brief This function performs a PKCS#1 v1.5 decryption + * operation (RSAES-PKCS1-v1_5-DECRYPT). * * \note The output buffer length \c output_max_len should be - * as large as the size ctx->len of ctx->N (eg. 128 bytes - * if RSA-1024 is used) to be able to hold an arbitrary - * decrypted message. If it is not large enough to hold - * the decryption of the particular ciphertext provided, - * the function will return MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * as large as the size \p ctx->len of \p ctx->N, for example, + * 128 Bytes if RSA-1024 is used, to be able to hold an + * arbitrary decrypted message. If it is not large enough to + * hold the decryption of the particular ciphertext provided, + * the function returns #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. * * \note The input buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param olen The length of the plaintext. + * \param input The buffer holding the encrypted data. + * \param output The buffer to hold the plaintext. + * \param output_max_len The maximum length of the output buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + * */ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -380,30 +749,42 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, size_t output_max_len ); /** - * \brief Perform a PKCS#1 v2.1 OAEP decryption (RSAES-OAEP-DECRYPT) - * - * \param ctx RSA context - * \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param label buffer holding the custom label to use - * \param label_len contains the label length - * \param olen will contain the plaintext length - * \param input buffer holding the encrypted data - * \param output buffer that will hold the plaintext - * \param output_max_len maximum length of the output buffer - * - * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The output buffer length \c output_max_len should be - * as large as the size ctx->len of ctx->N (eg. 128 bytes - * if RSA-1024 is used) to be able to hold an arbitrary - * decrypted message. If it is not large enough to hold - * the decryption of the particular ciphertext provided, - * the function will return MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. - * - * \note The input buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). + * \brief This function performs a PKCS#1 v2.1 OAEP decryption + * operation (RSAES-OAEP-DECRYPT). + * + * \note The output buffer length \c output_max_len should be + * as large as the size \p ctx->len of \p ctx->N, for + * example, 128 Bytes if RSA-1024 is used, to be able to + * hold an arbitrary decrypted message. If it is not + * large enough to hold the decryption of the particular + * ciphertext provided, the function returns + * #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * + * \note The input buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param label The buffer holding the custom label to use. + * \param label_len The length of the label. + * \param olen The length of the plaintext. + * \param input The buffer holding the encrypted data. + * \param output The buffer to hold the plaintext. + * \param output_max_len The maximum length of the output buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -416,28 +797,41 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, size_t output_max_len ); /** - * \brief Generic wrapper to perform a PKCS#1 signature using the - * mode from the context. Do a private RSA operation to sign - * a message digest - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for PKCS#1 v2.1 encoding and for - * MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) - * \param hashlen message digest length (for MBEDTLS_MD_NONE only) - * \param hash buffer holding the message digest - * \param sig buffer that will hold the ciphertext - * - * \return 0 if the signing operation was successful, - * or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note In case of PKCS#1 v2.1 encoding, see comments on - * \note \c mbedtls_rsa_rsassa_pss_sign() for details on md_alg and hash_id. + * \brief This function performs a private RSA operation to sign + * a message digest using PKCS#1. + * + * It is the generic wrapper for performing a PKCS#1 + * signature using the \p mode from the context. + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note For PKCS#1 v2.1 encoding, see comments on + * mbedtls_rsa_rsassa_pss_sign() for details on + * \p md_alg and \p hash_id. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for PKCS#1 v2.1 encoding and for + * #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer to hold the ciphertext. + * + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -449,22 +843,33 @@ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, unsigned char *sig ); /** - * \brief Perform a PKCS#1 v1.5 signature (RSASSA-PKCS1-v1_5-SIGN) - * - * \param ctx RSA context - * \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) - * \param hashlen message digest length (for MBEDTLS_MD_NONE only) - * \param hash buffer holding the message digest - * \param sig buffer that will hold the ciphertext - * - * \return 0 if the signing operation was successful, - * or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). + * \brief This function performs a PKCS#1 v1.5 signature + * operation (RSASSA-PKCS1-v1_5-SIGN). + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer to hold the ciphertext. + * + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -476,28 +881,41 @@ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, unsigned char *sig ); /** - * \brief Perform a PKCS#1 v2.1 PSS signature (RSASSA-PSS-SIGN) - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for PKCS#1 v2.1 encoding and for - * MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) - * \param hashlen message digest length (for MBEDTLS_MD_NONE only) - * \param hash buffer holding the message digest - * \param sig buffer that will hold the ciphertext - * - * \return 0 if the signing operation was successful, - * or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note The hash_id in the RSA context is the one used for the - * encoding. md_alg in the function call is the type of hash - * that is encoded. According to RFC 3447 it is advised to - * keep both hashes the same. + * \brief This function performs a PKCS#1 v2.1 PSS signature + * operation (RSASSA-PSS-SIGN). + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note The \p hash_id in the RSA context is the one used for the + * encoding. \p md_alg in the function call is the type of hash + * that is encoded. According to RFC-3447: Public-Key + * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography + * Specifications it is advised to keep both hashes the + * same. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for PKCS#1 v2.1 encoding and for + * #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer to hold the ciphertext. + * + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -509,27 +927,40 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, unsigned char *sig ); /** - * \brief Generic wrapper to perform a PKCS#1 verification using the - * mode from the context. Do a public RSA operation and check - * the message digest - * - * \param ctx points to an RSA public key - * \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) - * \param hashlen message digest length (for MBEDTLS_MD_NONE only) - * \param hash buffer holding the message digest - * \param sig buffer holding the ciphertext - * - * \return 0 if the verify operation was successful, - * or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note In case of PKCS#1 v2.1 encoding, see comments on - * \c mbedtls_rsa_rsassa_pss_verify() about md_alg and hash_id. + * \brief This function performs a public RSA operation and checks + * the message digest. + * + * This is the generic wrapper for performing a PKCS#1 + * verification using the mode from the context. + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note For PKCS#1 v2.1 encoding, see comments on + * mbedtls_rsa_rsassa_pss_verify() about \p md_alg and + * \p hash_id. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA public key context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer holding the ciphertext. + * + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -541,22 +972,33 @@ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, const unsigned char *sig ); /** - * \brief Perform a PKCS#1 v1.5 verification (RSASSA-PKCS1-v1_5-VERIFY) - * - * \param ctx points to an RSA public key - * \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) - * \param hashlen message digest length (for MBEDTLS_MD_NONE only) - * \param hash buffer holding the message digest - * \param sig buffer holding the ciphertext - * - * \return 0 if the verify operation was successful, - * or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). + * \brief This function performs a PKCS#1 v1.5 verification + * operation (RSASSA-PKCS1-v1_5-VERIFY). + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA public key context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer holding the ciphertext. + * + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -568,29 +1010,44 @@ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, const unsigned char *sig ); /** - * \brief Perform a PKCS#1 v2.1 PSS verification (RSASSA-PSS-VERIFY) - * (This is the "simple" version.) - * - * \param ctx points to an RSA public key - * \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) - * \param hashlen message digest length (for MBEDTLS_MD_NONE only) - * \param hash buffer holding the message digest - * \param sig buffer holding the ciphertext - * - * \return 0 if the verify operation was successful, - * or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note The hash_id in the RSA context is the one used for the - * verification. md_alg in the function call is the type of - * hash that is verified. According to RFC 3447 it is advised to - * keep both hashes the same. If hash_id in the RSA context is - * unset, the md_alg from the function call is used. + * \brief This function performs a PKCS#1 v2.1 PSS verification + * operation (RSASSA-PSS-VERIFY). + * + * The hash function for the MGF mask generating function + * is that specified in the RSA context. + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note The \p hash_id in the RSA context is the one used for the + * verification. \p md_alg in the function call is the type of + * hash that is verified. According to RFC-3447: Public-Key + * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography + * Specifications it is advised to keep both hashes the + * same. If \p hash_id in the RSA context is unset, + * the \p md_alg from the function call is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * + * \param ctx The RSA public key context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer holding the ciphertext. + * + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -602,28 +1059,33 @@ int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, const unsigned char *sig ); /** - * \brief Perform a PKCS#1 v2.1 PSS verification (RSASSA-PSS-VERIFY) - * (This is the version with "full" options.) - * - * \param ctx points to an RSA public key - * \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) - * \param p_rng RNG parameter - * \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE - * \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) - * \param hashlen message digest length (for MBEDTLS_MD_NONE only) - * \param hash buffer holding the message digest - * \param mgf1_hash_id message digest used for mask generation - * \param expected_salt_len Length of the salt used in padding, use - * MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length - * \param sig buffer holding the ciphertext - * - * \return 0 if the verify operation was successful, - * or an MBEDTLS_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note The hash_id in the RSA context is ignored. + * \brief This function performs a PKCS#1 v2.1 PSS verification + * operation (RSASSA-PSS-VERIFY). + * + * The hash function for the MGF mask generating function + * is that specified in \p mgf1_hash_id. + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note The \p hash_id in the RSA context is ignored. + * + * \param ctx The RSA public key context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is + * #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param mgf1_hash_id The message digest used for mask generation. + * \param expected_salt_len The length of the salt used in padding. Use + * #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length. + * \param sig The buffer holding the ciphertext. + * + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -637,27 +1099,28 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, const unsigned char *sig ); /** - * \brief Copy the components of an RSA context + * \brief This function copies the components of an RSA context. * - * \param dst Destination context - * \param src Source context + * \param dst The destination context. + * \param src The source context. * - * \return 0 on success, - * MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure. */ int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src ); /** - * \brief Free the components of an RSA key + * \brief This function frees the components of an RSA key. * - * \param ctx RSA Context to free + * \param ctx The RSA Context to free. */ void mbedtls_rsa_free( mbedtls_rsa_context *ctx ); /** - * \brief Checkup routine + * \brief The RSA checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_rsa_self_test( int verbose ); @@ -665,6 +1128,4 @@ int mbedtls_rsa_self_test( int verbose ); } #endif -#endif /* MBEDTLS_RSA_C */ - #endif /* rsa.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/rsa_internal.h b/tools/sdk/include/mbedtls/mbedtls/rsa_internal.h new file mode 100644 index 00000000000..53abd3c5b0e --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/rsa_internal.h @@ -0,0 +1,226 @@ +/** + * \file rsa_internal.h + * + * \brief Context-independent RSA helper functions + * + * This module declares some RSA-related helper functions useful when + * implementing the RSA interface. These functions are provided in a separate + * compilation unit in order to make it easy for designers of alternative RSA + * implementations to use them in their own code, as it is conceived that the + * functionality they provide will be necessary for most complete + * implementations. + * + * End-users of Mbed TLS who are not providing their own alternative RSA + * implementations should not use these functions directly, and should instead + * use only the functions declared in rsa.h. + * + * The interface provided by this module will be maintained through LTS (Long + * Term Support) branches of Mbed TLS, but may otherwise be subject to change, + * and must be considered an internal interface of the library. + * + * There are two classes of helper functions: + * + * (1) Parameter-generating helpers. These are: + * - mbedtls_rsa_deduce_primes + * - mbedtls_rsa_deduce_private_exponent + * - mbedtls_rsa_deduce_crt + * Each of these functions takes a set of core RSA parameters and + * generates some other, or CRT related parameters. + * + * (2) Parameter-checking helpers. These are: + * - mbedtls_rsa_validate_params + * - mbedtls_rsa_validate_crt + * They take a set of core or CRT related RSA parameters and check their + * validity. + * + */ +/* + * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + * + */ + +#ifndef MBEDTLS_RSA_INTERNAL_H +#define MBEDTLS_RSA_INTERNAL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "bignum.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * \brief Compute RSA prime moduli P, Q from public modulus N=PQ + * and a pair of private and public key. + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param N RSA modulus N = PQ, with P, Q to be found + * \param E RSA public exponent + * \param D RSA private exponent + * \param P Pointer to MPI holding first prime factor of N on success + * \param Q Pointer to MPI holding second prime factor of N on success + * + * \return + * - 0 if successful. In this case, P and Q constitute a + * factorization of N. + * - A non-zero error code otherwise. + * + * \note It is neither checked that P, Q are prime nor that + * D, E are modular inverses wrt. P-1 and Q-1. For that, + * use the helper function \c mbedtls_rsa_validate_params. + * + */ +int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E, + mbedtls_mpi const *D, + mbedtls_mpi *P, mbedtls_mpi *Q ); + +/** + * \brief Compute RSA private exponent from + * prime moduli and public key. + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param P First prime factor of RSA modulus + * \param Q Second prime factor of RSA modulus + * \param E RSA public exponent + * \param D Pointer to MPI holding the private exponent on success. + * + * \return + * - 0 if successful. In this case, D is set to a simultaneous + * modular inverse of E modulo both P-1 and Q-1. + * - A non-zero error code otherwise. + * + * \note This function does not check whether P and Q are primes. + * + */ +int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P, + mbedtls_mpi const *Q, + mbedtls_mpi const *E, + mbedtls_mpi *D ); + + +/** + * \brief Generate RSA-CRT parameters + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param P First prime factor of N + * \param Q Second prime factor of N + * \param D RSA private exponent + * \param DP Output variable for D modulo P-1 + * \param DQ Output variable for D modulo Q-1 + * \param QP Output variable for the modular inverse of Q modulo P. + * + * \return 0 on success, non-zero error code otherwise. + * + * \note This function does not check whether P, Q are + * prime and whether D is a valid private exponent. + * + */ +int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, + const mbedtls_mpi *D, mbedtls_mpi *DP, + mbedtls_mpi *DQ, mbedtls_mpi *QP ); + + +/** + * \brief Check validity of core RSA parameters + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param N RSA modulus N = PQ + * \param P First prime factor of N + * \param Q Second prime factor of N + * \param D RSA private exponent + * \param E RSA public exponent + * \param f_rng PRNG to be used for primality check, or NULL + * \param p_rng PRNG context for f_rng, or NULL + * + * \return + * - 0 if the following conditions are satisfied + * if all relevant parameters are provided: + * - P prime if f_rng != NULL (%) + * - Q prime if f_rng != NULL (%) + * - 1 < N = P * Q + * - 1 < D, E < N + * - D and E are modular inverses modulo P-1 and Q-1 + * (%) This is only done if MBEDTLS_GENPRIME is defined. + * - A non-zero error code otherwise. + * + * \note The function can be used with a restricted set of arguments + * to perform specific checks only. E.g., calling it with + * (-,P,-,-,-) and a PRNG amounts to a primality check for P. + */ +int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P, + const mbedtls_mpi *Q, const mbedtls_mpi *D, + const mbedtls_mpi *E, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief Check validity of RSA CRT parameters + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param P First prime factor of RSA modulus + * \param Q Second prime factor of RSA modulus + * \param D RSA private exponent + * \param DP MPI to check for D modulo P-1 + * \param DQ MPI to check for D modulo P-1 + * \param QP MPI to check for the modular inverse of Q modulo P. + * + * \return + * - 0 if the following conditions are satisfied: + * - D = DP mod P-1 if P, D, DP != NULL + * - Q = DQ mod P-1 if P, D, DQ != NULL + * - QP = Q^-1 mod P if P, Q, QP != NULL + * - \c MBEDTLS_ERR_RSA_KEY_CHECK_FAILED if check failed, + * potentially including \c MBEDTLS_ERR_MPI_XXX if some + * MPI calculations failed. + * - \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if insufficient + * data was provided to check DP, DQ or QP. + * + * \note The function can be used with a restricted set of arguments + * to perform specific checks only. E.g., calling it with the + * parameters (P, -, D, DP, -, -) will check DP = D mod P-1. + */ +int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, + const mbedtls_mpi *D, const mbedtls_mpi *DP, + const mbedtls_mpi *DQ, const mbedtls_mpi *QP ); + +#ifdef __cplusplus +} +#endif + +#endif /* rsa_internal.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/sha1.h b/tools/sdk/include/mbedtls/mbedtls/sha1.h index 7a67c6c1fb1..7a19da0a485 100644 --- a/tools/sdk/include/mbedtls/mbedtls/sha1.h +++ b/tools/sdk/include/mbedtls/mbedtls/sha1.h @@ -1,9 +1,17 @@ /** * \file sha1.h * - * \brief SHA-1 cryptographic hash function + * \brief This file contains SHA-1 definitions and functions. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in + * FIPS 180-4: Secure Hash Standard (SHS). + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. We recommend considering stronger message + * digests instead. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,7 +26,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_SHA1_H #define MBEDTLS_SHA1_H @@ -32,100 +40,280 @@ #include #include -#if !defined(MBEDTLS_SHA1_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED -0x0035 /**< SHA-1 hardware accelerator failed */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_SHA1_ALT) +// Regular implementation +// + /** - * \brief SHA-1 context structure + * \brief The SHA-1 context structure. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * */ -typedef struct +typedef struct mbedtls_sha1_context { - uint32_t total[2]; /*!< number of bytes processed */ - uint32_t state[5]; /*!< intermediate digest state */ - unsigned char buffer[64]; /*!< data block being processed */ + uint32_t total[2]; /*!< The number of Bytes processed. */ + uint32_t state[5]; /*!< The intermediate digest state. */ + unsigned char buffer[64]; /*!< The data block being processed. */ } mbedtls_sha1_context; +#else /* MBEDTLS_SHA1_ALT */ +#include "sha1_alt.h" +#endif /* MBEDTLS_SHA1_ALT */ + /** - * \brief Initialize SHA-1 context + * \brief This function initializes a SHA-1 context. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context to initialize. * - * \param ctx SHA-1 context to be initialized */ void mbedtls_sha1_init( mbedtls_sha1_context *ctx ); /** - * \brief Clear SHA-1 context + * \brief This function clears a SHA-1 context. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context to clear. * - * \param ctx SHA-1 context to be cleared */ void mbedtls_sha1_free( mbedtls_sha1_context *ctx ); /** - * \brief Clone (the state of) a SHA-1 context + * \brief This function clones the state of a SHA-1 context. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param dst The SHA-1 context to clone to. + * \param src The SHA-1 context to clone from. * - * \param dst The destination context - * \param src The context to be cloned */ void mbedtls_sha1_clone( mbedtls_sha1_context *dst, const mbedtls_sha1_context *src ); /** - * \brief SHA-1 context setup + * \brief This function starts a SHA-1 checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context to initialize. + * + * \return \c 0 on success. * - * \param ctx context to be initialized */ -void mbedtls_sha1_starts( mbedtls_sha1_context *ctx ); +int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx ); /** - * \brief SHA-1 process buffer + * \brief This function feeds an input buffer into an ongoing SHA-1 + * checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. * - * \param ctx SHA-1 context - * \param input buffer holding the data - * \param ilen length of the input data + * \param ctx The SHA-1 context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + * \return \c 0 on success. */ -void mbedtls_sha1_update( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen ); +int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx, + const unsigned char *input, + size_t ilen ); /** - * \brief SHA-1 final digest + * \brief This function finishes the SHA-1 operation, and writes + * the result to the output buffer. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context. + * \param output The SHA-1 checksum result. * - * \param ctx SHA-1 context - * \param output SHA-1 checksum result + * \return \c 0 on success. */ -void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, unsigned char output[20] ); +int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx, + unsigned char output[20] ); -/* Internal use */ -void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] ); +/** + * \brief SHA-1 process data block (internal use only). + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context. + * \param data The data block being processed. + * + * \return \c 0 on success. + * + */ +int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx, + const unsigned char data[64] ); -#ifdef __cplusplus -} +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED #endif +/** + * \brief This function starts a SHA-1 checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_sha1_starts_ret() in 2.7.0. + * + * \param ctx The SHA-1 context to initialize. + * + */ +MBEDTLS_DEPRECATED void mbedtls_sha1_starts( mbedtls_sha1_context *ctx ); -#else /* MBEDTLS_SHA1_ALT */ -#include "sha1_alt.h" -#endif /* MBEDTLS_SHA1_ALT */ +/** + * \brief This function feeds an input buffer into an ongoing SHA-1 + * checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_sha1_update_ret() in 2.7.0. + * + * \param ctx The SHA-1 context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + */ +MBEDTLS_DEPRECATED void mbedtls_sha1_update( mbedtls_sha1_context *ctx, + const unsigned char *input, + size_t ilen ); -#ifdef __cplusplus -extern "C" { -#endif +/** + * \brief This function finishes the SHA-1 operation, and writes + * the result to the output buffer. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_sha1_finish_ret() in 2.7.0. + * + * \param ctx The SHA-1 context. + * \param output The SHA-1 checksum result. + * + */ +MBEDTLS_DEPRECATED void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, + unsigned char output[20] ); + +/** + * \brief SHA-1 process data block (internal use only). + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_internal_sha1_process() in 2.7.0. + * + * \param ctx The SHA-1 context. + * \param data The data block being processed. + * + */ +MBEDTLS_DEPRECATED void mbedtls_sha1_process( mbedtls_sha1_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief This function calculates the SHA-1 checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-1 result is calculated as + * output = SHA-1(input buffer). + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The SHA-1 checksum result. + * + * \return \c 0 on success. + * + */ +int mbedtls_sha1_ret( const unsigned char *input, + size_t ilen, + unsigned char output[20] ); +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif /** - * \brief Output = SHA-1( input buffer ) + * \brief This function calculates the SHA-1 checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-1 result is calculated as + * output = SHA-1(input buffer). + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_sha1_ret() in 2.7.0 + * + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The SHA-1 checksum result. * - * \param input buffer holding the data - * \param ilen length of the input data - * \param output SHA-1 checksum result */ -void mbedtls_sha1( const unsigned char *input, size_t ilen, unsigned char output[20] ); +MBEDTLS_DEPRECATED void mbedtls_sha1( const unsigned char *input, + size_t ilen, + unsigned char output[20] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** - * \brief Checkup routine + * \brief The SHA-1 checkup routine. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \return \c 0 on success. + * \return \c 1 on failure. * - * \return 0 if successful, or 1 if the test failed */ int mbedtls_sha1_self_test( int verbose ); diff --git a/tools/sdk/include/mbedtls/mbedtls/sha256.h b/tools/sdk/include/mbedtls/mbedtls/sha256.h index f8041adf082..33aff28314a 100644 --- a/tools/sdk/include/mbedtls/mbedtls/sha256.h +++ b/tools/sdk/include/mbedtls/mbedtls/sha256.h @@ -1,9 +1,13 @@ /** * \file sha256.h * - * \brief SHA-224 and SHA-256 cryptographic hash function + * \brief This file contains SHA-224 and SHA-256 definitions and functions. * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic + * hash functions are defined in FIPS 180-4: Secure Hash Standard (SHS). + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,7 +22,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_SHA256_H #define MBEDTLS_SHA256_H @@ -32,105 +36,232 @@ #include #include -#if !defined(MBEDTLS_SHA256_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED -0x0037 /**< SHA-256 hardware accelerator failed */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_SHA256_ALT) +// Regular implementation +// + /** - * \brief SHA-256 context structure + * \brief The SHA-256 context structure. + * + * The structure is used both for SHA-256 and for SHA-224 + * checksum calculations. The choice between these two is + * made in the call to mbedtls_sha256_starts_ret(). */ -typedef struct +typedef struct mbedtls_sha256_context { - uint32_t total[2]; /*!< number of bytes processed */ - uint32_t state[8]; /*!< intermediate digest state */ - unsigned char buffer[64]; /*!< data block being processed */ - int is224; /*!< 0 => SHA-256, else SHA-224 */ + uint32_t total[2]; /*!< The number of Bytes processed. */ + uint32_t state[8]; /*!< The intermediate digest state. */ + unsigned char buffer[64]; /*!< The data block being processed. */ + int is224; /*!< Determines which function to use: + 0: Use SHA-256, or 1: Use SHA-224. */ } mbedtls_sha256_context; +#else /* MBEDTLS_SHA256_ALT */ +#include "sha256_alt.h" +#endif /* MBEDTLS_SHA256_ALT */ + /** - * \brief Initialize SHA-256 context + * \brief This function initializes a SHA-256 context. * - * \param ctx SHA-256 context to be initialized + * \param ctx The SHA-256 context to initialize. */ void mbedtls_sha256_init( mbedtls_sha256_context *ctx ); /** - * \brief Clear SHA-256 context + * \brief This function clears a SHA-256 context. * - * \param ctx SHA-256 context to be cleared + * \param ctx The SHA-256 context to clear. */ void mbedtls_sha256_free( mbedtls_sha256_context *ctx ); /** - * \brief Clone (the state of) a SHA-256 context + * \brief This function clones the state of a SHA-256 context. * - * \param dst The destination context - * \param src The context to be cloned + * \param dst The destination context. + * \param src The context to clone. */ void mbedtls_sha256_clone( mbedtls_sha256_context *dst, const mbedtls_sha256_context *src ); /** - * \brief SHA-256 context setup + * \brief This function starts a SHA-224 or SHA-256 checksum + * calculation. + * + * \param ctx The context to initialize. + * \param is224 Determines which function to use: + * 0: Use SHA-256, or 1: Use SHA-224. * - * \param ctx context to be initialized - * \param is224 0 = use SHA256, 1 = use SHA224 + * \return \c 0 on success. */ -void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 ); +int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 ); /** - * \brief SHA-256 process buffer + * \brief This function feeds an input buffer into an ongoing + * SHA-256 checksum calculation. + * + * \param ctx The SHA-256 context. + * \param input The buffer holding the data. + * \param ilen The length of the input data. * - * \param ctx SHA-256 context - * \param input buffer holding the data - * \param ilen length of the input data + * \return \c 0 on success. */ -void mbedtls_sha256_update( mbedtls_sha256_context *ctx, const unsigned char *input, - size_t ilen ); +int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx, + const unsigned char *input, + size_t ilen ); /** - * \brief SHA-256 final digest + * \brief This function finishes the SHA-256 operation, and writes + * the result to the output buffer. * - * \param ctx SHA-256 context - * \param output SHA-224/256 checksum result + * \param ctx The SHA-256 context. + * \param output The SHA-224 or SHA-256 checksum result. + * + * \return \c 0 on success. */ -void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, unsigned char output[32] ); +int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx, + unsigned char output[32] ); -/* Internal use */ -void mbedtls_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] ); +/** + * \brief This function processes a single data block within + * the ongoing SHA-256 computation. This function is for + * internal use only. + * + * \param ctx The SHA-256 context. + * \param data The buffer holding one block of data. + * + * \return \c 0 on success. + */ +int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx, + const unsigned char data[64] ); -#ifdef __cplusplus -} +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED #endif +/** + * \brief This function starts a SHA-224 or SHA-256 checksum + * calculation. + * + * + * \deprecated Superseded by mbedtls_sha256_starts_ret() in 2.7.0. + * + * \param ctx The context to initialize. + * \param is224 Determines which function to use: + * 0: Use SHA-256, or 1: Use SHA-224. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, + int is224 ); -#else /* MBEDTLS_SHA256_ALT */ -#include "sha256_alt.h" -#endif /* MBEDTLS_SHA256_ALT */ +/** + * \brief This function feeds an input buffer into an ongoing + * SHA-256 checksum calculation. + * + * \deprecated Superseded by mbedtls_sha256_update_ret() in 2.7.0. + * + * \param ctx The SHA-256 context to initialize. + * \param input The buffer holding the data. + * \param ilen The length of the input data. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256_update( mbedtls_sha256_context *ctx, + const unsigned char *input, + size_t ilen ); -#ifdef __cplusplus -extern "C" { +/** + * \brief This function finishes the SHA-256 operation, and writes + * the result to the output buffer. + * + * \deprecated Superseded by mbedtls_sha256_finish_ret() in 2.7.0. + * + * \param ctx The SHA-256 context. + * \param output The SHA-224 or SHA-256 checksum result. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, + unsigned char output[32] ); + +/** + * \brief This function processes a single data block within + * the ongoing SHA-256 computation. This function is for + * internal use only. + * + * \deprecated Superseded by mbedtls_internal_sha256_process() in 2.7.0. + * + * \param ctx The SHA-256 context. + * \param data The buffer holding one block of data. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256_process( mbedtls_sha256_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief This function calculates the SHA-224 or SHA-256 + * checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-256 result is calculated as + * output = SHA-256(input buffer). + * + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The SHA-224 or SHA-256 checksum result. + * \param is224 Determines which function to use: + * 0: Use SHA-256, or 1: Use SHA-224. + */ +int mbedtls_sha256_ret( const unsigned char *input, + size_t ilen, + unsigned char output[32], + int is224 ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED #endif /** - * \brief Output = SHA-256( input buffer ) + * \brief This function calculates the SHA-224 or SHA-256 checksum + * of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. * - * \param input buffer holding the data - * \param ilen length of the input data - * \param output SHA-224/256 checksum result - * \param is224 0 = use SHA256, 1 = use SHA224 + * The SHA-256 result is calculated as + * output = SHA-256(input buffer). + * + * \deprecated Superseded by mbedtls_sha256_ret() in 2.7.0. + * + * \param input The buffer holding the data. + * \param ilen The length of the input data. + * \param output The SHA-224 or SHA-256 checksum result. + * \param is224 Determines which function to use: + * 0: Use SHA-256, or 1: Use SHA-224. */ -void mbedtls_sha256( const unsigned char *input, size_t ilen, - unsigned char output[32], int is224 ); +MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input, + size_t ilen, + unsigned char output[32], + int is224 ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** - * \brief Checkup routine + * \brief The SHA-224 and SHA-256 checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_sha256_self_test( int verbose ); diff --git a/tools/sdk/include/mbedtls/mbedtls/sha512.h b/tools/sdk/include/mbedtls/mbedtls/sha512.h index 12f4fab4f16..0145890424f 100644 --- a/tools/sdk/include/mbedtls/mbedtls/sha512.h +++ b/tools/sdk/include/mbedtls/mbedtls/sha512.h @@ -1,9 +1,12 @@ /** * \file sha512.h + * \brief This file contains SHA-384 and SHA-512 definitions and functions. * - * \brief SHA-384 and SHA-512 cryptographic hash function - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * The Secure Hash Algorithms 384 and 512 (SHA-384 and SHA-512) cryptographic + * hash functions are defined in FIPS 180-4: Secure Hash Standard (SHS). + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,7 +21,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_SHA512_H #define MBEDTLS_SHA512_H @@ -32,105 +35,231 @@ #include #include -#if !defined(MBEDTLS_SHA512_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED -0x0039 /**< SHA-512 hardware accelerator failed */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_SHA512_ALT) +// Regular implementation +// + /** - * \brief SHA-512 context structure + * \brief The SHA-512 context structure. + * + * The structure is used both for SHA-384 and for SHA-512 + * checksum calculations. The choice between these two is + * made in the call to mbedtls_sha512_starts_ret(). */ -typedef struct +typedef struct mbedtls_sha512_context { - uint64_t total[2]; /*!< number of bytes processed */ - uint64_t state[8]; /*!< intermediate digest state */ - unsigned char buffer[128]; /*!< data block being processed */ - int is384; /*!< 0 => SHA-512, else SHA-384 */ + uint64_t total[2]; /*!< The number of Bytes processed. */ + uint64_t state[8]; /*!< The intermediate digest state. */ + unsigned char buffer[128]; /*!< The data block being processed. */ + int is384; /*!< Determines which function to use: + 0: Use SHA-512, or 1: Use SHA-384. */ } mbedtls_sha512_context; +#else /* MBEDTLS_SHA512_ALT */ +#include "sha512_alt.h" +#endif /* MBEDTLS_SHA512_ALT */ + /** - * \brief Initialize SHA-512 context + * \brief This function initializes a SHA-512 context. * - * \param ctx SHA-512 context to be initialized + * \param ctx The SHA-512 context to initialize. */ void mbedtls_sha512_init( mbedtls_sha512_context *ctx ); /** - * \brief Clear SHA-512 context + * \brief This function clears a SHA-512 context. * - * \param ctx SHA-512 context to be cleared + * \param ctx The SHA-512 context to clear. */ void mbedtls_sha512_free( mbedtls_sha512_context *ctx ); /** - * \brief Clone (the state of) a SHA-512 context + * \brief This function clones the state of a SHA-512 context. * - * \param dst The destination context - * \param src The context to be cloned + * \param dst The destination context. + * \param src The context to clone. */ void mbedtls_sha512_clone( mbedtls_sha512_context *dst, const mbedtls_sha512_context *src ); /** - * \brief SHA-512 context setup + * \brief This function starts a SHA-384 or SHA-512 checksum + * calculation. + * + * \param ctx The SHA-512 context to initialize. + * \param is384 Determines which function to use: + * 0: Use SHA-512, or 1: Use SHA-384. * - * \param ctx context to be initialized - * \param is384 0 = use SHA512, 1 = use SHA384 + * \return \c 0 on success. */ -void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, int is384 ); +int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 ); /** - * \brief SHA-512 process buffer + * \brief This function feeds an input buffer into an ongoing + * SHA-512 checksum calculation. * - * \param ctx SHA-512 context - * \param input buffer holding the data - * \param ilen length of the input data + * \param ctx The SHA-512 context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + * \return \c 0 on success. */ -void mbedtls_sha512_update( mbedtls_sha512_context *ctx, const unsigned char *input, +int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx, + const unsigned char *input, size_t ilen ); /** - * \brief SHA-512 final digest + * \brief This function finishes the SHA-512 operation, and writes + * the result to the output buffer. This function is for + * internal use only. + * + * \param ctx The SHA-512 context. + * \param output The SHA-384 or SHA-512 checksum result. * - * \param ctx SHA-512 context - * \param output SHA-384/512 checksum result + * \return \c 0 on success. */ -void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, unsigned char output[64] ); +int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx, + unsigned char output[64] ); -/* Internal use */ -void mbedtls_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] ); - -#ifdef __cplusplus -} +/** + * \brief This function processes a single data block within + * the ongoing SHA-512 computation. + * + * \param ctx The SHA-512 context. + * \param data The buffer holding one block of data. + * + * \return \c 0 on success. + */ +int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx, + const unsigned char data[128] ); +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED #endif +/** + * \brief This function starts a SHA-384 or SHA-512 checksum + * calculation. + * + * \deprecated Superseded by mbedtls_sha512_starts_ret() in 2.7.0 + * + * \param ctx The SHA-512 context to initialize. + * \param is384 Determines which function to use: + * 0: Use SHA-512, or 1: Use SHA-384. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, + int is384 ); -#else /* MBEDTLS_SHA512_ALT */ -#include "sha512_alt.h" -#endif /* MBEDTLS_SHA512_ALT */ +/** + * \brief This function feeds an input buffer into an ongoing + * SHA-512 checksum calculation. + * + * \deprecated Superseded by mbedtls_sha512_update_ret() in 2.7.0. + * + * \param ctx The SHA-512 context. + * \param input The buffer holding the data. + * \param ilen The length of the input data. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512_update( mbedtls_sha512_context *ctx, + const unsigned char *input, + size_t ilen ); -#ifdef __cplusplus -extern "C" { -#endif +/** + * \brief This function finishes the SHA-512 operation, and writes + * the result to the output buffer. + * + * \deprecated Superseded by mbedtls_sha512_finish_ret() in 2.7.0. + * + * \param ctx The SHA-512 context. + * \param output The SHA-384 or SHA-512 checksum result. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, + unsigned char output[64] ); + +/** + * \brief This function processes a single data block within + * the ongoing SHA-512 computation. This function is for + * internal use only. + * + * \deprecated Superseded by mbedtls_internal_sha512_process() in 2.7.0. + * + * \param ctx The SHA-512 context. + * \param data The buffer holding one block of data. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512_process( + mbedtls_sha512_context *ctx, + const unsigned char data[128] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** - * \brief Output = SHA-512( input buffer ) + * \brief This function calculates the SHA-512 or SHA-384 + * checksum of a buffer. * - * \param input buffer holding the data - * \param ilen length of the input data - * \param output SHA-384/512 checksum result - * \param is384 0 = use SHA512, 1 = use SHA384 + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-512 result is calculated as + * output = SHA-512(input buffer). + * + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The SHA-384 or SHA-512 checksum result. + * \param is384 Determines which function to use: + * 0: Use SHA-512, or 1: Use SHA-384. + * + * \return \c 0 on success. */ -void mbedtls_sha512( const unsigned char *input, size_t ilen, - unsigned char output[64], int is384 ); +int mbedtls_sha512_ret( const unsigned char *input, + size_t ilen, + unsigned char output[64], + int is384 ); +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif /** - * \brief Checkup routine + * \brief This function calculates the SHA-512 or SHA-384 + * checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-512 result is calculated as + * output = SHA-512(input buffer). + * + * \deprecated Superseded by mbedtls_sha512_ret() in 2.7.0 + * + * \param input The buffer holding the data. + * \param ilen The length of the input data. + * \param output The SHA-384 or SHA-512 checksum result. + * \param is384 Determines which function to use: + * 0: Use SHA-512, or 1: Use SHA-384. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512( const unsigned char *input, + size_t ilen, + unsigned char output[64], + int is384 ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + /** + * \brief The SHA-384 or SHA-512 checkup routine. * - * \return 0 if successful, or 1 if the test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_sha512_self_test( int verbose ); diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl.h b/tools/sdk/include/mbedtls/mbedtls/ssl.h index cc000700628..83849a56450 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl.h @@ -2,7 +2,8 @@ * \file ssl.h * * \brief SSL/TLS functions. - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -48,11 +49,20 @@ #endif #if defined(MBEDTLS_ZLIB_SUPPORT) + +#if defined(MBEDTLS_DEPRECATED_WARNING) +#warning "Record compression support via MBEDTLS_ZLIB_SUPPORT is deprecated and will be removed in the next major revision of the library" +#endif + +#if defined(MBEDTLS_DEPRECATED_REMOVED) +#error "Record compression support via MBEDTLS_ZLIB_SUPPORT is deprecated and cannot be used if MBEDTLS_DEPRECATED_REMOVED is set" +#endif + #include "zlib.h" #endif #if defined(MBEDTLS_HAVE_TIME) -#include "mbedtls/platform_time.h" +#include "platform_time.h" #endif /* @@ -102,13 +112,16 @@ #define MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED -0x6A80 /**< DTLS client must retry for hello verification */ #define MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL -0x6A00 /**< A buffer is too small to receive or write a message */ #define MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE -0x6980 /**< None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages). */ -#define MBEDTLS_ERR_SSL_WANT_READ -0x6900 /**< Connection requires a read call. */ +#define MBEDTLS_ERR_SSL_WANT_READ -0x6900 /**< No data of requested type currently available on underlying transport. */ #define MBEDTLS_ERR_SSL_WANT_WRITE -0x6880 /**< Connection requires a write call. */ #define MBEDTLS_ERR_SSL_TIMEOUT -0x6800 /**< The operation timed out. */ #define MBEDTLS_ERR_SSL_CLIENT_RECONNECT -0x6780 /**< The client initiated a reconnect from the same port. */ #define MBEDTLS_ERR_SSL_UNEXPECTED_RECORD -0x6700 /**< Record header looks valid but is not expected. */ #define MBEDTLS_ERR_SSL_NON_FATAL -0x6680 /**< The alert message received indicates a non-fatal error. */ #define MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH -0x6600 /**< Couldn't set the hash for verifying CertificateVerify */ +#define MBEDTLS_ERR_SSL_CONTINUE_PROCESSING -0x6580 /**< Internal-only message signaling that further message-processing should be done */ +#define MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS -0x6500 /**< The asynchronous operation is not completed yet. */ +#define MBEDTLS_ERR_SSL_EARLY_MESSAGE -0x6480 /**< Internal-only message signaling that a message arrived early. */ /* * Various constants @@ -208,7 +221,7 @@ #endif /* - * Maxium fragment length in bytes, + * Maximum fragment length in bytes, * determines the size of each of the two internal I/O buffers. * * Note: the RFC defines the default size of SSL / TLS messages. If you @@ -222,6 +235,22 @@ #define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 /**< Size of the input / output buffer */ #endif +#if !defined(MBEDTLS_SSL_IN_CONTENT_LEN) +#define MBEDTLS_SSL_IN_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN +#endif + +#if !defined(MBEDTLS_SSL_OUT_CONTENT_LEN) +#define MBEDTLS_SSL_OUT_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN +#endif + +/* + * Maximum number of heap-allocated bytes for the purpose of + * DTLS handshake message reassembly and future message buffering. + */ +#if !defined(MBEDTLS_SSL_DTLS_MAX_BUFFERING) +#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768 +#endif + /* \} name SECTION: Module settings */ /* @@ -525,7 +554,6 @@ typedef void mbedtls_ssl_set_timer_t( void * ctx, */ typedef int mbedtls_ssl_get_timer_t( void * ctx ); - /* Defined below */ typedef struct mbedtls_ssl_session mbedtls_ssl_session; typedef struct mbedtls_ssl_context mbedtls_ssl_context; @@ -542,6 +570,218 @@ typedef struct mbedtls_ssl_key_cert mbedtls_ssl_key_cert; typedef struct mbedtls_ssl_flight_item mbedtls_ssl_flight_item; #endif +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * \brief Callback type: start external signature operation. + * + * This callback is called during an SSL handshake to start + * a signature decryption operation using an + * external processor. The parameter \p cert contains + * the public key; it is up to the callback function to + * determine how to access the associated private key. + * + * This function typically sends or enqueues a request, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * The parameters \p ssl and \p cert are guaranteed to remain + * valid throughout the handshake. On the other hand, this + * function must save the contents of \p hash if the value + * is needed for later processing, because the \p hash buffer + * is no longer valid after this function returns. + * + * This function may call mbedtls_ssl_set_async_operation_data() + * to store an operation context for later retrieval + * by the resume or cancel callback. + * + * \note For RSA signatures, this function must produce output + * that is consistent with PKCS#1 v1.5 in the same way as + * mbedtls_rsa_pkcs1_sign(). Before the private key operation, + * apply the padding steps described in RFC 8017, section 9.2 + * "EMSA-PKCS1-v1_5" as follows. + * - If \p md_alg is #MBEDTLS_MD_NONE, apply the PKCS#1 v1.5 + * encoding, treating \p hash as the DigestInfo to be + * padded. In other words, apply EMSA-PKCS1-v1_5 starting + * from step 3, with `T = hash` and `tLen = hash_len`. + * - If `md_alg != MBEDTLS_MD_NONE`, apply the PKCS#1 v1.5 + * encoding, treating \p hash as the hash to be encoded and + * padded. In other words, apply EMSA-PKCS1-v1_5 starting + * from step 2, with `digestAlgorithm` obtained by calling + * mbedtls_oid_get_oid_by_md() on \p md_alg. + * + * \note For ECDSA signatures, the output format is the DER encoding + * `Ecdsa-Sig-Value` defined in + * [RFC 4492 section 5.4](https://tools.ietf.org/html/rfc4492#section-5.4). + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param cert Certificate containing the public key. + * In simple cases, this is one of the pointers passed to + * mbedtls_ssl_conf_own_cert() when configuring the SSL + * connection. However, if other callbacks are used, this + * property may not hold. For example, if an SNI callback + * is registered with mbedtls_ssl_conf_sni(), then + * this callback determines what certificate is used. + * \param md_alg Hash algorithm. + * \param hash Buffer containing the hash. This buffer is + * no longer valid when the function returns. + * \param hash_len Size of the \c hash buffer in bytes. + * + * \return 0 if the operation was started successfully and the SSL + * stack should call the resume callback immediately. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * was started successfully and the SSL stack should return + * immediately without calling the resume callback yet. + * \return #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external + * processor does not support this key. The SSL stack will + * use the private key object instead. + * \return Any other error indicates a fatal failure and is + * propagated up the call chain. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_sign_t( mbedtls_ssl_context *ssl, + mbedtls_x509_crt *cert, + mbedtls_md_type_t md_alg, + const unsigned char *hash, + size_t hash_len ); + +/** + * \brief Callback type: start external decryption operation. + * + * This callback is called during an SSL handshake to start + * an RSA decryption operation using an + * external processor. The parameter \p cert contains + * the public key; it is up to the callback function to + * determine how to access the associated private key. + * + * This function typically sends or enqueues a request, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * The parameters \p ssl and \p cert are guaranteed to remain + * valid throughout the handshake. On the other hand, this + * function must save the contents of \p input if the value + * is needed for later processing, because the \p input buffer + * is no longer valid after this function returns. + * + * This function may call mbedtls_ssl_set_async_operation_data() + * to store an operation context for later retrieval + * by the resume or cancel callback. + * + * \warning RSA decryption as used in TLS is subject to a potential + * timing side channel attack first discovered by Bleichenbacher + * in 1998. This attack can be remotely exploitable + * in practice. To avoid this attack, you must ensure that + * if the callback performs an RSA decryption, the time it + * takes to execute and return the result does not depend + * on whether the RSA decryption succeeded or reported + * invalid padding. + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param cert Certificate containing the public key. + * In simple cases, this is one of the pointers passed to + * mbedtls_ssl_conf_own_cert() when configuring the SSL + * connection. However, if other callbacks are used, this + * property may not hold. For example, if an SNI callback + * is registered with mbedtls_ssl_conf_sni(), then + * this callback determines what certificate is used. + * \param input Buffer containing the input ciphertext. This buffer + * is no longer valid when the function returns. + * \param input_len Size of the \p input buffer in bytes. + * + * \return 0 if the operation was started successfully and the SSL + * stack should call the resume callback immediately. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * was started successfully and the SSL stack should return + * immediately without calling the resume callback yet. + * \return #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external + * processor does not support this key. The SSL stack will + * use the private key object instead. + * \return Any other error indicates a fatal failure and is + * propagated up the call chain. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_decrypt_t( mbedtls_ssl_context *ssl, + mbedtls_x509_crt *cert, + const unsigned char *input, + size_t input_len ); +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +/** + * \brief Callback type: resume external operation. + * + * This callback is called during an SSL handshake to resume + * an external operation started by the + * ::mbedtls_ssl_async_sign_t or + * ::mbedtls_ssl_async_decrypt_t callback. + * + * This function typically checks the status of a pending + * request or causes the request queue to make progress, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * This function may call mbedtls_ssl_get_async_operation_data() + * to retrieve an operation context set by the start callback. + * It may call mbedtls_ssl_set_async_operation_data() to modify + * this context. + * + * Note that when this function returns a status other than + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, it must free any + * resources associated with the operation. + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param output Buffer containing the output (signature or decrypted + * data) on success. + * \param output_len On success, number of bytes written to \p output. + * \param output_size Size of the \p output buffer in bytes. + * + * \return 0 if output of the operation is available in the + * \p output buffer. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * is still in progress. Subsequent requests for progress + * on the SSL connection will call the resume callback + * again. + * \return Any other error means that the operation is aborted. + * The SSL handshake is aborted. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_resume_t( mbedtls_ssl_context *ssl, + unsigned char *output, + size_t *output_len, + size_t output_size ); + +/** + * \brief Callback type: cancel external operation. + * + * This callback is called if an SSL connection is closed + * while an asynchronous operation is in progress. Note that + * this callback is not called if the + * ::mbedtls_ssl_async_resume_t callback has run and has + * returned a value other than + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, since in that case + * the asynchronous operation has already completed. + * + * This function may call mbedtls_ssl_get_async_operation_data() + * to retrieve an operation context set by the start callback. + * + * \param ssl The SSL connection instance. It should not be + * modified. + */ +typedef void mbedtls_ssl_async_cancel_t( mbedtls_ssl_context *ssl ); +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + /* * This structure is used for storing current session data. */ @@ -658,6 +898,16 @@ struct mbedtls_ssl_config mbedtls_x509_crl *ca_crl; /*!< trusted CAs CRLs */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +#if defined(MBEDTLS_X509_CRT_PARSE_C) + mbedtls_ssl_async_sign_t *f_async_sign_start; /*!< start asynchronous signature operation */ + mbedtls_ssl_async_decrypt_t *f_async_decrypt_start; /*!< start asynchronous decryption operation */ +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + mbedtls_ssl_async_resume_t *f_async_resume; /*!< resume asynchronous operation */ + mbedtls_ssl_async_cancel_t *f_async_cancel; /*!< cancel asynchronous operation */ + void *p_async_config_data; /*!< Configuration data set by mbedtls_ssl_conf_async_private_cb(). */ +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) const int *sig_hashes; /*!< allowed signature hashes */ #endif @@ -672,10 +922,18 @@ struct mbedtls_ssl_config #endif #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) - unsigned char *psk; /*!< pre-shared key */ - size_t psk_len; /*!< length of the pre-shared key */ - unsigned char *psk_identity; /*!< identity for PSK negotiation */ - size_t psk_identity_len;/*!< length of identity */ + unsigned char *psk; /*!< pre-shared key. This field should + only be set via + mbedtls_ssl_conf_psk() */ + size_t psk_len; /*!< length of the pre-shared key. This + field should only be set via + mbedtls_ssl_conf_psk() */ + unsigned char *psk_identity; /*!< identity for PSK negotiation. This + field should only be set via + mbedtls_ssl_conf_psk() */ + size_t psk_identity_len;/*!< length of identity. This field should + only be set via + mbedtls_ssl_conf_psk() */ #endif #if defined(MBEDTLS_SSL_ALPN) @@ -773,14 +1031,14 @@ struct mbedtls_ssl_context int renego_records_seen; /*!< Records since renego request, or with DTLS, number of retransmissions of request if renego_max_records is < 0 */ -#endif +#endif /* MBEDTLS_SSL_RENEGOTIATION */ int major_ver; /*!< equal to MBEDTLS_SSL_MAJOR_VERSION_3 */ int minor_ver; /*!< either 0 (SSL3) or 1 (TLS1.0) */ #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) unsigned badmac_seen; /*!< records with a bad MAC received */ -#endif +#endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ mbedtls_ssl_send_t *f_send; /*!< Callback for network send */ mbedtls_ssl_recv_t *f_recv; /*!< Callback for network receive */ @@ -836,11 +1094,11 @@ struct mbedtls_ssl_context uint16_t in_epoch; /*!< DTLS epoch for incoming records */ size_t next_record_offset; /*!< offset of the next record in datagram (equal to in_left if none) */ -#endif +#endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) uint64_t in_window_top; /*!< last validated record seq_num */ uint64_t in_window; /*!< bitmask for replay detection */ -#endif +#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ size_t in_hslen; /*!< current handshake message length, including the handshake header */ @@ -849,6 +1107,11 @@ struct mbedtls_ssl_context int keep_current_message; /*!< drop or reuse current message on next call to record layer? */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + uint8_t disable_datagram_packing; /*!< Disable packing multiple records + * within a single datagram. */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + /* * Record layer (outgoing data) */ @@ -863,12 +1126,18 @@ struct mbedtls_ssl_context size_t out_msglen; /*!< record header: message length */ size_t out_left; /*!< amount of data not yet written */ + unsigned char cur_out_ctr[8]; /*!< Outgoing record sequence number. */ + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + uint16_t mtu; /*!< path mtu, used to fragment outgoing messages */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + #if defined(MBEDTLS_ZLIB_SUPPORT) unsigned char *compress_buf; /*!< zlib data buffer */ -#endif +#endif /* MBEDTLS_ZLIB_SUPPORT */ #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) signed char split_done; /*!< current record already splitted? */ -#endif +#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ /* * PKI layer @@ -881,11 +1150,11 @@ struct mbedtls_ssl_context #if defined(MBEDTLS_X509_CRT_PARSE_C) char *hostname; /*!< expected peer CN for verification (and SNI if available) */ -#endif +#endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_ALPN) const char *alpn_chosen; /*!< negotiated protocol */ -#endif +#endif /* MBEDTLS_SSL_ALPN */ /* * Information for DTLS hello verify @@ -893,7 +1162,7 @@ struct mbedtls_ssl_context #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) unsigned char *cli_id; /*!< transport-level ID of the client */ size_t cli_id_len; /*!< length of cli_id */ -#endif +#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */ /* * Secure renegotiation @@ -905,7 +1174,7 @@ struct mbedtls_ssl_context size_t verify_data_len; /*!< length of verify data stored */ char own_verify_data[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!< previous handshake verify data */ char peer_verify_data[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!< previous handshake verify data */ -#endif +#endif /* MBEDTLS_SSL_RENEGOTIATION */ }; #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) @@ -927,14 +1196,6 @@ extern int (*mbedtls_ssl_hw_record_read)(mbedtls_ssl_context *ssl); extern int (*mbedtls_ssl_hw_record_finish)(mbedtls_ssl_context *ssl); #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ -/** - * \brief Returns the list of ciphersuites supported by the SSL/TLS module. - * - * \return a statically allocated array of ciphersuites, the last - * entry is 0. - */ -const int *mbedtls_ssl_list_ciphersuites( void ); - /** * \brief Return the name of the ciphersuite associated with the * given ID @@ -970,8 +1231,13 @@ void mbedtls_ssl_init( mbedtls_ssl_context *ssl ); * \note No copy of the configuration context is made, it can be * shared by many mbedtls_ssl_context structures. * - * \warning Modifying the conf structure after it has been used in this - * function is unsupported! + * \warning The conf structure will be accessed during the session. + * It must not be modified or freed as long as the session + * is active. + * + * \warning This function must be called exactly once per context. + * Calling mbedtls_ssl_setup again is not supported, even + * if no session is active. * * \param ssl SSL context * \param conf SSL configuration to use @@ -1128,6 +1394,52 @@ void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl, mbedtls_ssl_recv_t *f_recv, mbedtls_ssl_recv_timeout_t *f_recv_timeout ); +#if defined(MBEDTLS_SSL_PROTO_DTLS) +/** + * \brief Set the Maximum Tranport Unit (MTU). + * Special value: 0 means unset (no limit). + * This represents the maximum size of a datagram payload + * handled by the transport layer (usually UDP) as determined + * by the network link and stack. In practice, this controls + * the maximum size datagram the DTLS layer will pass to the + * \c f_send() callback set using \c mbedtls_ssl_set_bio(). + * + * \note The limit on datagram size is converted to a limit on + * record payload by subtracting the current overhead of + * encapsulation and encryption/authentication if any. + * + * \note This can be called at any point during the connection, for + * example when a Path Maximum Transfer Unit (PMTU) + * estimate becomes available from other sources, + * such as lower (or higher) protocol layers. + * + * \note This setting only controls the size of the packets we send, + * and does not restrict the size of the datagrams we're + * willing to receive. Client-side, you can request the + * server to use smaller records with \c + * mbedtls_ssl_conf_max_frag_len(). + * + * \note If both a MTU and a maximum fragment length have been + * configured (or negotiated with the peer), the resulting + * lower limit on record payload (see first note) is used. + * + * \note This can only be used to decrease the maximum size + * of datagrams (hence records, see first note) sent. It + * cannot be used to increase the maximum size of records over + * the limit set by #MBEDTLS_SSL_OUT_CONTENT_LEN. + * + * \note Values lower than the current record layer expansion will + * result in an error when trying to send data. + * + * \note Using record compression together with a non-zero MTU value + * will result in an error when trying to send data. + * + * \param ssl SSL context + * \param mtu Value of the path MTU in bytes + */ +void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu ); +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + /** * \brief Set the timeout period for mbedtls_ssl_read() * (Default: no timeout.) @@ -1291,6 +1603,85 @@ void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf, void *p_export_keys ); #endif /* MBEDTLS_SSL_EXPORT_KEYS */ +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +/** + * \brief Configure asynchronous private key operation callbacks. + * + * \param conf SSL configuration context + * \param f_async_sign Callback to start a signature operation. See + * the description of ::mbedtls_ssl_async_sign_t + * for more information. This may be \c NULL if the + * external processor does not support any signature + * operation; in this case the private key object + * associated with the certificate will be used. + * \param f_async_decrypt Callback to start a decryption operation. See + * the description of ::mbedtls_ssl_async_decrypt_t + * for more information. This may be \c NULL if the + * external processor does not support any decryption + * operation; in this case the private key object + * associated with the certificate will be used. + * \param f_async_resume Callback to resume an asynchronous operation. See + * the description of ::mbedtls_ssl_async_resume_t + * for more information. This may not be \c NULL unless + * \p f_async_sign and \p f_async_decrypt are both + * \c NULL. + * \param f_async_cancel Callback to cancel an asynchronous operation. See + * the description of ::mbedtls_ssl_async_cancel_t + * for more information. This may be \c NULL if + * no cleanup is needed. + * \param config_data A pointer to configuration data which can be + * retrieved with + * mbedtls_ssl_conf_get_async_config_data(). The + * library stores this value without dereferencing it. + */ +void mbedtls_ssl_conf_async_private_cb( mbedtls_ssl_config *conf, + mbedtls_ssl_async_sign_t *f_async_sign, + mbedtls_ssl_async_decrypt_t *f_async_decrypt, + mbedtls_ssl_async_resume_t *f_async_resume, + mbedtls_ssl_async_cancel_t *f_async_cancel, + void *config_data ); + +/** + * \brief Retrieve the configuration data set by + * mbedtls_ssl_conf_async_private_cb(). + * + * \param conf SSL configuration context + * \return The configuration data set by + * mbedtls_ssl_conf_async_private_cb(). + */ +void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf ); + +/** + * \brief Retrieve the asynchronous operation user context. + * + * \note This function may only be called while a handshake + * is in progress. + * + * \param ssl The SSL context to access. + * + * \return The asynchronous operation user context that was last + * set during the current handshake. If + * mbedtls_ssl_set_async_operation_data() has not yet been + * called during the current handshake, this function returns + * \c NULL. + */ +void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl ); + +/** + * \brief Retrieve the asynchronous operation user context. + * + * \note This function may only be called while a handshake + * is in progress. + * + * \param ssl The SSL context to access. + * \param ctx The new value of the asynchronous operation user context. + * Call mbedtls_ssl_get_async_operation_data() later during the + * same handshake to retrieve this value. + */ +void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl, + void *ctx ); +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + /** * \brief Callback type: generate a cookie * @@ -1432,6 +1823,38 @@ void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limi #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ #if defined(MBEDTLS_SSL_PROTO_DTLS) + +/** + * \brief Allow or disallow packing of multiple handshake records + * within a single datagram. + * + * \param ssl The SSL context to configure. + * \param allow_packing This determines whether datagram packing may + * be used or not. A value of \c 0 means that every + * record will be sent in a separate datagram; a + * value of \c 1 means that, if space permits, + * multiple handshake messages (including CCS) belonging to + * a single flight may be packed within a single datagram. + * + * \note This is enabled by default and should only be disabled + * for test purposes, or if datagram packing causes + * interoperability issues with peers that don't support it. + * + * \note Allowing datagram packing reduces the network load since + * there's less overhead if multiple messages share the same + * datagram. Also, it increases the handshake efficiency + * since messages belonging to a single datagram will not + * be reordered in transit, and so future message buffering + * or flight retransmission (if no buffering is used) as + * means to deal with reordering are needed less frequently. + * + * \note Application records are not affected by this option and + * are currently always sent in separate datagrams. + * + */ +void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl, + unsigned allow_packing ); + /** * \brief Set retransmit timeout values for the DTLS handshake. * (DTLS only, no effect on TLS.) @@ -1586,6 +2009,10 @@ void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf, /** * \brief Set the data required to verify peer certificate * + * \note See \c mbedtls_x509_crt_verify() for notes regarding the + * parameters ca_chain (maps to trust_ca for that function) + * and ca_crl. + * * \param conf SSL configuration * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs) * \param ca_crl trusted CA CRLs @@ -1699,18 +2126,50 @@ void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf, #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) + +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif + /** * \brief Set the Diffie-Hellman public P and G values, * read as hexadecimal strings (server-side only) - * (Default: MBEDTLS_DHM_RFC5114_MODP_2048_[PG]) + * (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]) * * \param conf SSL configuration * \param dhm_P Diffie-Hellman-Merkle modulus * \param dhm_G Diffie-Hellman-Merkle generator * + * \deprecated Superseded by \c mbedtls_ssl_conf_dh_param_bin. + * * \return 0 if successful */ -int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G ); +MBEDTLS_DEPRECATED int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, + const char *dhm_P, + const char *dhm_G ); + +#endif /* MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Set the Diffie-Hellman public P and G values + * from big-endian binary presentations. + * (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]_BIN) + * + * \param conf SSL configuration + * \param dhm_P Diffie-Hellman-Merkle modulus in big-endian binary form + * \param P_len Length of DHM modulus + * \param dhm_G Diffie-Hellman-Merkle generator in big-endian binary form + * \param G_len Length of DHM generator + * + * \return 0 if successful + */ +int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf, + const unsigned char *dhm_P, size_t P_len, + const unsigned char *dhm_G, size_t G_len ); /** * \brief Set the Diffie-Hellman public P and G values, @@ -1794,15 +2253,22 @@ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf, #if defined(MBEDTLS_X509_CRT_PARSE_C) /** - * \brief Set the hostname to check against the received server - * certificate. It sets the ServerName TLS extension too, - * if the extension is enabled. - * (client-side only) + * \brief Set or reset the hostname to check against the received + * server certificate. It sets the ServerName TLS extension, + * too, if that extension is enabled. (client-side only) * * \param ssl SSL context - * \param hostname the server hostname + * \param hostname the server hostname, may be NULL to clear hostname + + * \note Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN. * - * \return 0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED + * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on + * allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on + * too long input hostname. + * + * Hostname set to the one provided on success (cleared + * when NULL). On allocation failure hostname is cleared. + * On too long input failure, old hostname is unchanged. */ int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ); #endif /* MBEDTLS_X509_CRT_PARSE_C */ @@ -2058,12 +2524,25 @@ void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf, #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) /** * \brief Set the maximum fragment length to emit and/or negotiate - * (Default: MBEDTLS_SSL_MAX_CONTENT_LEN, usually 2^14 bytes) + * (Default: the smaller of MBEDTLS_SSL_IN_CONTENT_LEN and + * MBEDTLS_SSL_OUT_CONTENT_LEN, usually 2^14 bytes) * (Server: set maximum fragment length to emit, * usually negotiated by the client during handshake * (Client: set maximum fragment length to emit *and* * negotiate with the server during handshake) * + * \note With TLS, this currently only affects ApplicationData (sent + * with \c mbedtls_ssl_read()), not handshake messages. + * With DTLS, this affects both ApplicationData and handshake. + * + * \note This sets the maximum length for a record's payload, + * excluding record overhead that will be added to it, see + * \c mbedtls_ssl_get_record_expansion(). + * + * \note For DTLS, it is also possible to set a limit for the total + * size of daragrams passed to the transport layer, including + * record overhead, see \c mbedtls_ssl_set_mtu(). + * * \param conf SSL configuration * \param mfl_code Code for maximum fragment length (allowed values: * MBEDTLS_SSL_MAX_FRAG_LEN_512, MBEDTLS_SSL_MAX_FRAG_LEN_1024, @@ -2235,11 +2714,59 @@ void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf, #endif /* MBEDTLS_SSL_RENEGOTIATION */ /** - * \brief Return the number of data bytes available to read + * \brief Check if there is data already read from the + * underlying transport but not yet processed. + * + * \param ssl SSL context + * + * \return 0 if nothing's pending, 1 otherwise. + * + * \note This is different in purpose and behaviour from + * \c mbedtls_ssl_get_bytes_avail in that it considers + * any kind of unprocessed data, not only unread + * application data. If \c mbedtls_ssl_get_bytes + * returns a non-zero value, this function will + * also signal pending data, but the converse does + * not hold. For example, in DTLS there might be + * further records waiting to be processed from + * the current underlying transport's datagram. + * + * \note If this function returns 1 (data pending), this + * does not imply that a subsequent call to + * \c mbedtls_ssl_read will provide any data; + * e.g., the unprocessed data might turn out + * to be an alert or a handshake message. + * + * \note This function is useful in the following situation: + * If the SSL/TLS module successfully returns from an + * operation - e.g. a handshake or an application record + * read - and you're awaiting incoming data next, you + * must not immediately idle on the underlying transport + * to have data ready, but you need to check the value + * of this function first. The reason is that the desired + * data might already be read but not yet processed. + * If, in contrast, a previous call to the SSL/TLS module + * returned MBEDTLS_ERR_SSL_WANT_READ, it is not necessary + * to call this function, as the latter error code entails + * that all internal data has been processed. + * + */ +int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl ); + +/** + * \brief Return the number of application data bytes + * remaining to be read from the current record. * * \param ssl SSL context * - * \return how many bytes are available in the read buffer + * \return How many bytes are available in the application + * data record read buffer. + * + * \note When working over a datagram transport, this is + * useful to detect the current datagram's boundary + * in case \c mbedtls_ssl_read has written the maximal + * amount of data fitting into the input buffer. + * */ size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ); @@ -2278,6 +2805,9 @@ const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl ); * \brief Return the (maximum) number of bytes added by the record * layer: header + encryption/MAC overhead (inc. padding) * + * \note This function is not available (always returns an error) + * when record compression is enabled. + * * \param ssl SSL context * * \return Current maximum record expansion in bytes, or @@ -2292,6 +2822,23 @@ int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl ); * This is the value negotiated with peer if any, * or the locally configured value. * + * \sa mbedtls_ssl_conf_max_frag_len() + * \sa mbedtls_ssl_get_max_record_payload() + * + * \param ssl SSL context + * + * \return Current maximum fragment length. + */ +size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl ); +#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ + +/** + * \brief Return the current maximum outgoing record payload in bytes. + * This takes into account the config.h setting \c + * MBEDTLS_SSL_OUT_CONTENT_LEN, the configured and negotiated + * max fragment length extension if used, and for DTLS the + * path MTU as configured and current record expansion. + * * \note With DTLS, \c mbedtls_ssl_write() will return an error if * called with a larger length value. * With TLS, \c mbedtls_ssl_write() will fragment the input if @@ -2299,12 +2846,19 @@ int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl ); * to the caller to call \c mbedtls_ssl_write() again in * order to send the remaining bytes if any. * + * \note This function is not available (always returns an error) + * when record compression is enabled. + * + * \sa mbedtls_ssl_set_mtu() + * \sa mbedtls_ssl_get_max_frag_len() + * \sa mbedtls_ssl_get_record_expansion() + * * \param ssl SSL context * - * \return Current maximum fragment length. + * \return Current maximum payload for an outgoing record, + * or a negative error code. */ -size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl ); -#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ +int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl ); #if defined(MBEDTLS_X509_CRT_PARSE_C) /** @@ -2329,7 +2883,6 @@ const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ss * \brief Save session in order to resume it later (client-side only) * Session data is copied to presented session structure. * - * \warning Currently, peer certificate is lost in the operation. * * \param ssl SSL context * \param session session context @@ -2337,7 +2890,18 @@ const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ss * \return 0 if successful, * MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed, * MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or - * arguments are otherwise invalid + * arguments are otherwise invalid. + * + * \note Only the server certificate is copied, and not the full chain, + * so you should not attempt to validate the certificate again + * by calling \c mbedtls_x509_crt_verify() on it. + * Instead, you should use the results from the verification + * in the original handshake by calling \c mbedtls_ssl_get_verify_result() + * after loading the session again into a new SSL context + * using \c mbedtls_ssl_set_session(). + * + * \note Once the session object is not needed anymore, you should + * free it by calling \c mbedtls_ssl_session_free(). * * \sa mbedtls_ssl_set_session() */ @@ -2354,11 +2918,25 @@ int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session * MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED (see below), or * a specific SSL error code. * + * If this function returns MBEDTLS_ERR_SSL_WANT_READ, the + * handshake is unfinished and no further data is available + * from the underlying transport. In this case, you must call + * the function again at some later stage. + * + * \note Remarks regarding event-driven DTLS: + * If the function returns MBEDTLS_ERR_SSL_WANT_READ, no datagram + * from the underlying transport layer is currently being processed, + * and it is safe to idle until the timer or the underlying transport + * signal a new event. This is not true for a successful handshake, + * in which case the datagram of the underlying transport that is + * currently being processed might or might not contain further + * DTLS records. + * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. * * \note If DTLS is in use, then you may choose to handle * MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging @@ -2375,10 +2953,10 @@ int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ); * call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER. * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. * * \param ssl SSL context * @@ -2402,10 +2980,10 @@ int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ); * value. * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. */ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); #endif /* MBEDTLS_SSL_RENEGOTIATION */ @@ -2417,20 +2995,20 @@ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); * \param buf buffer that will hold the data * \param len maximum number of bytes to read * - * \return the number of bytes read, or - * 0 for EOF, or - * MBEDTLS_ERR_SSL_WANT_READ or MBEDTLS_ERR_SSL_WANT_WRITE, or - * MBEDTLS_ERR_SSL_CLIENT_RECONNECT (see below), or - * another negative error code. + * \return One of the following: + * - 0 if the read end of the underlying transport was closed, + * - the (positive) number of bytes read, or + * - a negative error code on failure. + * + * If MBEDTLS_ERR_SSL_WANT_READ is returned, no application data + * is available from the underlying transport. In this case, + * the function needs to be called again at some later stage. * - * \note If this function returns something other than a positive - * value or MBEDTLS_ERR_SSL_WANT_READ/WRITE or - * MBEDTLS_ERR_SSL_CLIENT_RECONNECT, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * If MBEDTLS_ERR_SSL_WANT_WRITE is returned, a write is pending + * but the underlying transport isn't available for writing. In this + * case, the function needs to be called again at some later stage. * - * \note When this function return MBEDTLS_ERR_SSL_CLIENT_RECONNECT + * When this function return MBEDTLS_ERR_SSL_CLIENT_RECONNECT * (which can only happen server-side), it means that a client * is initiating a new connection using the same source port. * You can either treat that as a connection close and wait @@ -2443,6 +3021,28 @@ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); * again. WARNING: not validating the identity of the client * again, or not transmitting the new identity to the * application layer, would allow authentication bypass! + * + * \note If this function returns something other than a positive value + * or MBEDTLS_ERR_SSL_WANT_READ/WRITE or MBEDTLS_ERR_SSL_CLIENT_RECONNECT, + * you must stop using the SSL context for reading or writing, + * and either free it or call \c mbedtls_ssl_session_reset() on it + * before re-using it for a new connection; the current connection + * must be closed. + * + * \note Remarks regarding event-driven DTLS: + * - If the function returns MBEDTLS_ERR_SSL_WANT_READ, no datagram + * from the underlying transport layer is currently being processed, + * and it is safe to idle until the timer or the underlying transport + * signal a new event. + * - This function may return MBEDTLS_ERR_SSL_WANT_READ even if data was + * initially available on the underlying transport, as this data may have + * been only e.g. duplicated messages or a renegotiation request. + * Therefore, you must be prepared to receive MBEDTLS_ERR_SSL_WANT_READ even + * when reacting to an incoming-data event from the underlying transport. + * - On success, the datagram of the underlying transport that is currently + * being processed may contain further DTLS records. You should call + * \c mbedtls_ssl_check_pending to check for remaining records. + * */ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ); @@ -2463,15 +3063,19 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) * or MBEDTLS_ERR_SSL_WANT_WRITE or MBEDTLS_ERR_SSL_WANT_READ, * or another negative error code. * - * \note If this function returns something other than a positive - * value or MBEDTLS_ERR_SSL_WANT_READ/WRITE, the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * \note If this function returns something other than 0, a positive + * value or MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop + * using the SSL context for reading or writing, and either + * free it or call \c mbedtls_ssl_session_reset() on it before + * re-using it for a new connection; the current connection + * must be closed. * * \note When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ, * it must be called later with the *same* arguments, - * until it returns a positive value. + * until it returns a value greater that or equal to 0. When + * the function returns MBEDTLS_ERR_SSL_WANT_WRITE there may be + * some partial data in the output buffer, however this is not + * yet sent. * * \note If the requested length is greater than the maximum * fragment length (either the built-in limit or the one set @@ -2480,6 +3084,9 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) * - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned. * \c mbedtls_ssl_get_max_frag_len() may be used to query the * active maximum fragment length. + * + * \note Attempting to write 0 bytes will result in an empty TLS + * application record being sent. */ int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ); @@ -2494,10 +3101,10 @@ int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_ * \return 0 if successful, or a specific SSL error code. * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. */ int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, unsigned char level, @@ -2510,10 +3117,10 @@ int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, * \return 0 if successful, or a specific SSL error code. * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. */ int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl ); @@ -2572,6 +3179,9 @@ void mbedtls_ssl_session_init( mbedtls_ssl_session *session ); * \brief Free referenced items in an SSL session including the * peer certificate and clear memory * + * \note A session object can be freed even if the SSL context + * that was used to retrieve the session is still in use. + * * \param session SSL session */ void mbedtls_ssl_session_free( mbedtls_ssl_session *session ); diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl_cache.h b/tools/sdk/include/mbedtls/mbedtls/ssl_cache.h index 3734bb7274a..ec081e6d244 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl_cache.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl_cache.h @@ -2,7 +2,8 @@ * \file ssl_cache.h * * \brief SSL session cache implementation - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl_ciphersuites.h b/tools/sdk/include/mbedtls/mbedtls/ssl_ciphersuites.h index 9101d9cc7c4..cda8b4835b6 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl_ciphersuites.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl_ciphersuites.h @@ -2,7 +2,8 @@ * \file ssl_ciphersuites.h * * \brief SSL Ciphersuites for mbed TLS - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -168,6 +169,45 @@ extern "C" { #define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 0xC03A /**< Weak! No SSL3! */ #define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 0xC03B /**< Weak! No SSL3! */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 0xC03C /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 0xC03D /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC044 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC045 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC048 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC049 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC04A /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC04B /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC04C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC04D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 0xC04E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 0xC04F /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 0xC050 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 0xC051 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC052 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC053 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC060 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC061 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0xC062 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0xC063 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 0xC064 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 0xC065 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC066 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC067 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 0xC068 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 0xC069 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 0xC06A /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 0xC06B /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0xC06C /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0xC06D /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0xC06E /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0xC06F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC070 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC071 /**< TLS 1.2 */ + #define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC072 /**< Not in SSL3! */ #define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC073 /**< Not in SSL3! */ #define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC074 /**< Not in SSL3! */ @@ -231,6 +271,15 @@ extern "C" { #define MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 0xC0FF /**< experimental */ +/* RFC 7905 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAB /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAC /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAD /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAE /**< TLS 1.2 */ + /* Reminder: update mbedtls_ssl_premaster_secret when adding a new key exchange. * Reminder: update MBEDTLS_KEY_EXCHANGE__xxx below */ @@ -266,7 +315,7 @@ typedef enum { defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \ - defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) #define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED #endif diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl_cookie.h b/tools/sdk/include/mbedtls/mbedtls/ssl_cookie.h index 037e1c31125..6a0ad4fa96d 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl_cookie.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl_cookie.h @@ -2,7 +2,8 @@ * \file ssl_cookie.h * * \brief DTLS cookie callbacks implementation - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -49,7 +50,7 @@ extern "C" { /** * \brief Context for the default cookie functions. */ -typedef struct +typedef struct mbedtls_ssl_cookie_ctx { mbedtls_md_context_t hmac_ctx; /*!< context for the HMAC portion */ #if !defined(MBEDTLS_HAVE_TIME) diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl_internal.h b/tools/sdk/include/mbedtls/mbedtls/ssl_internal.h index 756360b1817..4b4417a5fae 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl_internal.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl_internal.h @@ -1,8 +1,9 @@ /** - * \file ssl_ticket.h + * \file ssl_internal.h * * \brief Internal functions shared by the SSL modules - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -24,6 +25,7 @@ #define MBEDTLS_SSL_INTERNAL_H #include "ssl.h" +#include "cipher.h" #if defined(MBEDTLS_MD5_C) #include "md5.h" @@ -69,6 +71,9 @@ #endif /* MBEDTLS_SSL_PROTO_TLS1 */ #endif /* MBEDTLS_SSL_PROTO_SSL3 */ +#define MBEDTLS_SSL_MIN_VALID_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1 +#define MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3 + /* Determine maximum supported version */ #define MBEDTLS_SSL_MAX_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3 @@ -138,12 +143,76 @@ #define MBEDTLS_SSL_PADDING_ADD 0 #endif -#define MBEDTLS_SSL_BUFFER_LEN ( MBEDTLS_SSL_MAX_CONTENT_LEN \ - + MBEDTLS_SSL_COMPRESSION_ADD \ - + 29 /* counter + header + IV */ \ - + MBEDTLS_SSL_MAC_ADD \ - + MBEDTLS_SSL_PADDING_ADD \ - ) +#define MBEDTLS_SSL_PAYLOAD_OVERHEAD ( MBEDTLS_SSL_COMPRESSION_ADD + \ + MBEDTLS_MAX_IV_LENGTH + \ + MBEDTLS_SSL_MAC_ADD + \ + MBEDTLS_SSL_PADDING_ADD \ + ) + +#define MBEDTLS_SSL_IN_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \ + ( MBEDTLS_SSL_IN_CONTENT_LEN ) ) + +#define MBEDTLS_SSL_OUT_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \ + ( MBEDTLS_SSL_OUT_CONTENT_LEN ) ) + +/* The maximum number of buffered handshake messages. */ +#define MBEDTLS_SSL_MAX_BUFFERED_HS 4 + +/* Maximum length we can advertise as our max content length for + RFC 6066 max_fragment_length extension negotiation purposes + (the lesser of both sizes, if they are unequal.) + */ +#define MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ( \ + (MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_OUT_CONTENT_LEN) \ + ? ( MBEDTLS_SSL_OUT_CONTENT_LEN ) \ + : ( MBEDTLS_SSL_IN_CONTENT_LEN ) \ + ) + +/* + * Check that we obey the standard's message size bounds + */ + +#if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384 +#error "Bad configuration - record content too large." +#endif + +#if MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN +#error "Bad configuration - incoming record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN." +#endif + +#if MBEDTLS_SSL_OUT_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN +#error "Bad configuration - outgoing record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN." +#endif + +#if MBEDTLS_SSL_IN_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048 +#error "Bad configuration - incoming protected record payload too large." +#endif + +#if MBEDTLS_SSL_OUT_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048 +#error "Bad configuration - outgoing protected record payload too large." +#endif + +/* Calculate buffer sizes */ + +/* Note: Even though the TLS record header is only 5 bytes + long, we're internally using 8 bytes to store the + implicit sequence number. */ +#define MBEDTLS_SSL_HEADER_LEN 13 + +#define MBEDTLS_SSL_IN_BUFFER_LEN \ + ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) ) + +#define MBEDTLS_SSL_OUT_BUFFER_LEN \ + ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) ) + +#ifdef MBEDTLS_ZLIB_SUPPORT +/* Compression buffer holds both IN and OUT buffers, so should be size of the larger */ +#define MBEDTLS_SSL_COMPRESS_BUFFER_LEN ( \ + ( MBEDTLS_SSL_IN_BUFFER_LEN > MBEDTLS_SSL_OUT_BUFFER_LEN ) \ + ? MBEDTLS_SSL_IN_BUFFER_LEN \ + : MBEDTLS_SSL_OUT_BUFFER_LEN \ + ) +#endif /* * TLS extension flags (for extensions with outgoing ServerHello content @@ -218,6 +287,7 @@ struct mbedtls_ssl_handshake_params mbedtls_x509_crl *sni_ca_crl; /*!< trusted CAs CRLs from SNI */ #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ + #if defined(MBEDTLS_SSL_PROTO_DTLS) unsigned int out_msg_seq; /*!< Outgoing handshake sequence number */ unsigned int in_msg_seq; /*!< Incoming handshake sequence number */ @@ -227,18 +297,45 @@ struct mbedtls_ssl_handshake_params unsigned char verify_cookie_len; /*!< Cli: cookie length Srv: flag for sending a cookie */ - unsigned char *hs_msg; /*!< Reassembled handshake message */ - uint32_t retransmit_timeout; /*!< Current value of timeout */ unsigned char retransmit_state; /*!< Retransmission state */ - mbedtls_ssl_flight_item *flight; /*!< Current outgoing flight */ - mbedtls_ssl_flight_item *cur_msg; /*!< Current message in flight */ + mbedtls_ssl_flight_item *flight; /*!< Current outgoing flight */ + mbedtls_ssl_flight_item *cur_msg; /*!< Current message in flight */ + unsigned char *cur_msg_p; /*!< Position in current message */ unsigned int in_flight_start_seq; /*!< Minimum message sequence in the flight being received */ mbedtls_ssl_transform *alt_transform_out; /*!< Alternative transform for resending messages */ unsigned char alt_out_ctr[8]; /*!< Alternative record epoch/counter for resending messages */ + + struct + { + size_t total_bytes_buffered; /*!< Cumulative size of heap allocated + * buffers used for message buffering. */ + + uint8_t seen_ccs; /*!< Indicates if a CCS message has + * been seen in the current flight. */ + + struct mbedtls_ssl_hs_buffer + { + unsigned is_valid : 1; + unsigned is_fragmented : 1; + unsigned is_complete : 1; + unsigned char *data; + size_t data_len; + } hs[MBEDTLS_SSL_MAX_BUFFERED_HS]; + + struct + { + unsigned char *data; + size_t len; + unsigned epoch; + } future_record; + + } buffering; + + uint16_t mtu; /*!< Handshake mtu, used to fragment outgoing messages */ #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* @@ -282,8 +379,23 @@ struct mbedtls_ssl_handshake_params #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) int extended_ms; /*!< use Extended Master Secret? */ #endif + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) + unsigned int async_in_progress : 1; /*!< an asynchronous operation is in progress */ +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) + /** Asynchronous operation context. This field is meant for use by the + * asynchronous operation callbacks (mbedtls_ssl_config::f_async_sign_start, + * mbedtls_ssl_config::f_async_decrypt_start, + * mbedtls_ssl_config::f_async_resume, mbedtls_ssl_config::f_async_cancel). + * The library does not use it internally. */ + void *user_async_ctx; +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ }; +typedef struct mbedtls_ssl_hs_buffer mbedtls_ssl_hs_buffer; + /* * This structure contains a full set of runtime transform parameters * either in negotiation or active. @@ -385,9 +497,9 @@ void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ); * \brief Free referenced items in an SSL handshake context and clear * memory * - * \param handshake SSL handshake context + * \param ssl SSL context */ -void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake ); +void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ); int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl ); int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl ); @@ -398,7 +510,6 @@ int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl ); void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl ); int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ); -int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl ); int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ); int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ); void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ); @@ -410,7 +521,10 @@ void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ); * of the logic of (D)TLS from the implementation * of the secure transport. * - * \param ssl SSL context to use + * \param ssl The SSL context to use. + * \param update_hs_digest This indicates if the handshake digest + * should be automatically updated in case + * a handshake message is found. * * \return 0 or non-zero error code. * @@ -476,10 +590,12 @@ void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ); * following the above definition. * */ -int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl, + unsigned update_hs_digest ); int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ); -int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush ); int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ); int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ); @@ -588,6 +704,7 @@ static inline size_t mbedtls_ssl_hs_hdr_len( const mbedtls_ssl_context *ssl ) void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl ); void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl ); int mbedtls_ssl_resend( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl ); #endif /* Visible for testing purposes only */ @@ -600,16 +717,39 @@ void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl ); static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n ) { size_t i; - const unsigned char *A = (const unsigned char *) a; - const unsigned char *B = (const unsigned char *) b; - unsigned char diff = 0; + volatile const unsigned char *A = (volatile const unsigned char *) a; + volatile const unsigned char *B = (volatile const unsigned char *) b; + volatile unsigned char diff = 0; for( i = 0; i < n; i++ ) - diff |= A[i] ^ B[i]; + { + /* Read volatile data in order before computing diff. + * This avoids IAR compiler warning: + * 'the order of volatile accesses is undefined ..' */ + unsigned char x = A[i], y = B[i]; + diff |= x ^ y; + } return( diff ); } +#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_1) +int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl, + unsigned char *output, + unsigned char *data, size_t data_len ); +#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ + MBEDTLS_SSL_PROTO_TLS1_1 */ + +#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) +int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl, + unsigned char *hash, size_t *hashlen, + unsigned char *data, size_t data_len, + mbedtls_md_type_t md_alg ); +#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ + MBEDTLS_SSL_PROTO_TLS1_2 */ + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl_ticket.h b/tools/sdk/include/mbedtls/mbedtls/ssl_ticket.h index 7c6bc61bfb7..b2686df09f4 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl_ticket.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl_ticket.h @@ -2,7 +2,8 @@ * \file ssl_ticket.h * * \brief TLS server ticket callbacks implementation - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -43,7 +44,7 @@ extern "C" { /** * \brief Information for session ticket protection */ -typedef struct +typedef struct mbedtls_ssl_ticket_key { unsigned char name[4]; /*!< random key identifier */ uint32_t generation_time; /*!< key generation timestamp (seconds) */ @@ -54,7 +55,7 @@ mbedtls_ssl_ticket_key; /** * \brief Context for session ticket handling functions */ -typedef struct +typedef struct mbedtls_ssl_ticket_context { mbedtls_ssl_ticket_key keys[2]; /*!< ticket protection keys */ unsigned char active; /*!< index of the currently active key */ diff --git a/tools/sdk/include/mbedtls/mbedtls/threading.h b/tools/sdk/include/mbedtls/mbedtls/threading.h index b0c34ecc741..75298bf8a38 100644 --- a/tools/sdk/include/mbedtls/mbedtls/threading.h +++ b/tools/sdk/include/mbedtls/mbedtls/threading.h @@ -2,7 +2,8 @@ * \file threading.h * * \brief Threading abstraction layer - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -41,7 +42,7 @@ extern "C" { #if defined(MBEDTLS_THREADING_PTHREAD) #include -typedef struct +typedef struct mbedtls_threading_mutex_t { pthread_mutex_t mutex; char is_valid; @@ -95,8 +96,20 @@ extern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex ); /* * Global mutexes */ +#if defined(MBEDTLS_FS_IO) extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex; +#endif + +#if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT) +/* This mutex may or may not be used in the default definition of + * mbedtls_platform_gmtime_r(), but in order to determine that, + * we need to check POSIX features, hence modify _POSIX_C_SOURCE. + * With the current approach, this declaration is orphaned, lacking + * an accompanying definition, in case mbedtls_platform_gmtime_r() + * doesn't need it, but that's not a problem. */ extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex; +#endif /* MBEDTLS_HAVE_TIME_DATE && !MBEDTLS_PLATFORM_GMTIME_R_ALT */ + #endif /* MBEDTLS_THREADING_C */ #ifdef __cplusplus diff --git a/tools/sdk/include/mbedtls/mbedtls/timing.h b/tools/sdk/include/mbedtls/mbedtls/timing.h index ae7a713e7a7..a965fe0d355 100644 --- a/tools/sdk/include/mbedtls/mbedtls/timing.h +++ b/tools/sdk/include/mbedtls/mbedtls/timing.h @@ -1,8 +1,9 @@ /** * \file timing.h * - * \brief Portable interface to the CPU cycle counter - * + * \brief Portable interface to timeouts and to the CPU cycle counter + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -29,16 +30,16 @@ #include MBEDTLS_CONFIG_FILE #endif -#if !defined(MBEDTLS_TIMING_ALT) -// Regular implementation -// - #include #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_TIMING_ALT) +// Regular implementation +// + /** * \brief timer structure */ @@ -50,13 +51,17 @@ struct mbedtls_timing_hr_time /** * \brief Context for mbedtls_timing_set/get_delay() */ -typedef struct +typedef struct mbedtls_timing_delay_context { struct mbedtls_timing_hr_time timer; uint32_t int_ms; uint32_t fin_ms; } mbedtls_timing_delay_context; +#else /* MBEDTLS_TIMING_ALT */ +#include "timing_alt.h" +#endif /* MBEDTLS_TIMING_ALT */ + extern volatile int mbedtls_timing_alarmed; /** @@ -65,6 +70,9 @@ extern volatile int mbedtls_timing_alarmed; * \warning This is only a best effort! Do not rely on this! * In particular, it is known to be unreliable on virtual * machines. + * + * \note This value starts at an unspecified origin and + * may wrap around. */ unsigned long mbedtls_timing_hardclock( void ); @@ -72,7 +80,18 @@ unsigned long mbedtls_timing_hardclock( void ); * \brief Return the elapsed time in milliseconds * * \param val points to a timer structure - * \param reset if set to 1, the timer is restarted + * \param reset If 0, query the elapsed time. Otherwise (re)start the timer. + * + * \return Elapsed time since the previous reset in ms. When + * restarting, this is always 0. + * + * \note To initialize a timer, call this function with reset=1. + * + * Determining the elapsed time and resetting the timer is not + * atomic on all platforms, so after the sequence + * `{ get_timer(1); ...; time1 = get_timer(1); ...; time2 = + * get_timer(0) }` the value time1+time2 is only approximately + * the delay since the first reset. */ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset ); @@ -80,6 +99,7 @@ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int * \brief Setup an alarm clock * * \param seconds delay before the "mbedtls_timing_alarmed" flag is set + * (must be >=0) * * \warning Only one alarm at a time is supported. In a threaded * context, this means one for the whole process, not one per @@ -91,11 +111,15 @@ void mbedtls_set_alarm( int seconds ); * \brief Set a pair of delays to watch * (See \c mbedtls_timing_get_delay().) * - * \param data Pointer to timing data + * \param data Pointer to timing data. * Must point to a valid \c mbedtls_timing_delay_context struct. * \param int_ms First (intermediate) delay in milliseconds. + * The effect if int_ms > fin_ms is unspecified. * \param fin_ms Second (final) delay in milliseconds. * Pass 0 to cancel the current delay. + * + * \note To set a single delay, either use \c mbedtls_timing_set_timer + * directly or use this function with int_ms == fin_ms. */ void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms ); @@ -106,25 +130,13 @@ void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms ); * \param data Pointer to timing data * Must point to a valid \c mbedtls_timing_delay_context struct. * - * \return -1 if cancelled (fin_ms = 0) + * \return -1 if cancelled (fin_ms = 0), * 0 if none of the delays are passed, * 1 if only the intermediate delay is passed, * 2 if the final delay is passed. */ int mbedtls_timing_get_delay( void *data ); -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_TIMING_ALT */ -#include "timing_alt.h" -#endif /* MBEDTLS_TIMING_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine diff --git a/tools/sdk/include/mbedtls/mbedtls/version.h b/tools/sdk/include/mbedtls/mbedtls/version.h index 3b209a6b072..326b8bd4516 100644 --- a/tools/sdk/include/mbedtls/mbedtls/version.h +++ b/tools/sdk/include/mbedtls/mbedtls/version.h @@ -2,7 +2,8 @@ * \file version.h * * \brief Run-time version information - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -38,17 +39,17 @@ * Major, Minor, Patchlevel */ #define MBEDTLS_VERSION_MAJOR 2 -#define MBEDTLS_VERSION_MINOR 6 -#define MBEDTLS_VERSION_PATCH 0 +#define MBEDTLS_VERSION_MINOR 13 +#define MBEDTLS_VERSION_PATCH 1 /** * The single version number has the following structure: * MMNNPP00 * Major version | Minor version | Patch version */ -#define MBEDTLS_VERSION_NUMBER 0x02060000 -#define MBEDTLS_VERSION_STRING "2.6.0" -#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.6.0" +#define MBEDTLS_VERSION_NUMBER 0x020D0100 +#define MBEDTLS_VERSION_STRING "2.13.1" +#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.13.1" #if defined(MBEDTLS_VERSION_C) diff --git a/tools/sdk/include/mbedtls/mbedtls/x509.h b/tools/sdk/include/mbedtls/mbedtls/x509.h index d7e318dfdc4..d6db9c6e373 100644 --- a/tools/sdk/include/mbedtls/mbedtls/x509.h +++ b/tools/sdk/include/mbedtls/mbedtls/x509.h @@ -2,7 +2,8 @@ * \file x509.h * * \brief X.509 generic defines and structures - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/x509_crl.h b/tools/sdk/include/mbedtls/mbedtls/x509_crl.h index 79884399003..08a4283a674 100644 --- a/tools/sdk/include/mbedtls/mbedtls/x509_crl.h +++ b/tools/sdk/include/mbedtls/mbedtls/x509_crl.h @@ -2,7 +2,8 @@ * \file x509_crl.h * * \brief X.509 certificate revocation list parsing - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/x509_crt.h b/tools/sdk/include/mbedtls/mbedtls/x509_crt.h index 06166d8b186..d41ec93a66e 100644 --- a/tools/sdk/include/mbedtls/mbedtls/x509_crt.h +++ b/tools/sdk/include/mbedtls/mbedtls/x509_crt.h @@ -2,7 +2,8 @@ * \file x509_crt.h * * \brief X.509 certificate parsing and writing - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -104,7 +105,7 @@ mbedtls_x509_crt; * * All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG(). */ -typedef struct +typedef struct mbedtls_x509_crt_profile { uint32_t allowed_mds; /**< MDs for signatures */ uint32_t allowed_pks; /**< PK algs for signatures */ @@ -286,8 +287,15 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix, * used to sign the certificate, CRL verification is skipped * silently, that is *without* setting any flag. * + * \note The \c trust_ca list can contain two types of certificates: + * (1) those of trusted root CAs, so that certificates + * chaining up to those CAs will be trusted, and (2) + * self-signed end-entity certificates to be trusted (for + * specific peers you know) - in that case, the self-signed + * certificate doesn't need to have the CA bit set. + * * \param crt a certificate (chain) to be verified - * \param trust_ca the list of trusted CAs + * \param trust_ca the list of trusted CAs (see note above) * \param ca_crl the list of CRLs for trusted CAs (see note above) * \param cn expected Common Name (can be set to * NULL if the CN must not be verified) @@ -373,21 +381,22 @@ int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt, #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) /** - * \brief Check usage of certificate against extentedJeyUsage. + * \brief Check usage of certificate against extendedKeyUsage. * - * \param crt Leaf certificate used. - * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or MBEDTLS_OID_CLIENT_AUTH). + * \param crt Leaf certificate used. + * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or + * MBEDTLS_OID_CLIENT_AUTH). * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()). * - * \return 0 if this use of the certificate is allowed, - * MBEDTLS_ERR_X509_BAD_INPUT_DATA if not. + * \return 0 if this use of the certificate is allowed, + * MBEDTLS_ERR_X509_BAD_INPUT_DATA if not. * - * \note Usually only makes sense on leaf certificates. + * \note Usually only makes sense on leaf certificates. */ int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt, - const char *usage_oid, - size_t usage_len ); -#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) */ + const char *usage_oid, + size_t usage_len ); +#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ #if defined(MBEDTLS_X509_CRL_PARSE_C) /** diff --git a/tools/sdk/include/mbedtls/mbedtls/x509_csr.h b/tools/sdk/include/mbedtls/mbedtls/x509_csr.h index fe9843cb545..0c6ccad78da 100644 --- a/tools/sdk/include/mbedtls/mbedtls/x509_csr.h +++ b/tools/sdk/include/mbedtls/mbedtls/x509_csr.h @@ -2,7 +2,8 @@ * \file x509_csr.h * * \brief X.509 certificate signing request parsing and writing - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * diff --git a/tools/sdk/include/mbedtls/mbedtls/xtea.h b/tools/sdk/include/mbedtls/mbedtls/xtea.h index b073f84efa0..c70c3fe2654 100644 --- a/tools/sdk/include/mbedtls/mbedtls/xtea.h +++ b/tools/sdk/include/mbedtls/mbedtls/xtea.h @@ -2,7 +2,8 @@ * \file xtea.h * * \brief XTEA block cipher (32-bit) - * + */ +/* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * @@ -36,24 +37,29 @@ #define MBEDTLS_XTEA_DECRYPT 0 #define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH -0x0028 /**< The data input has an invalid length. */ - -#if !defined(MBEDTLS_XTEA_ALT) -// Regular implementation -// +#define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED -0x0029 /**< XTEA hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_XTEA_ALT) +// Regular implementation +// + /** * \brief XTEA context structure */ -typedef struct +typedef struct mbedtls_xtea_context { uint32_t k[4]; /*!< key */ } mbedtls_xtea_context; +#else /* MBEDTLS_XTEA_ALT */ +#include "xtea_alt.h" +#endif /* MBEDTLS_XTEA_ALT */ + /** * \brief Initialize XTEA context * @@ -113,18 +119,6 @@ int mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx, unsigned char *output); #endif /* MBEDTLS_CIPHER_MODE_CBC */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_XTEA_ALT */ -#include "xtea_alt.h" -#endif /* MBEDTLS_XTEA_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Checkup routine * diff --git a/tools/sdk/include/mbedtls/sha1_alt.h b/tools/sdk/include/mbedtls/sha1_alt.h new file mode 100644 index 00000000000..54b77408780 --- /dev/null +++ b/tools/sdk/include/mbedtls/sha1_alt.h @@ -0,0 +1,57 @@ +/* + * SHA-1 implementation with hardware ESP32 support added. + * Uses mbedTLS software implementation for failover when concurrent + * SHA operations are in use. + * + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Additions Copyright (C) 2016, Espressif Systems (Shanghai) PTE LTD + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef _SHA1_ALT_H_ +#define _SHA1_ALT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_SHA1_ALT) + +typedef enum { + ESP_MBEDTLS_SHA1_UNUSED, /* first block hasn't been processed yet */ + ESP_MBEDTLS_SHA1_HARDWARE, /* using hardware SHA engine */ + ESP_MBEDTLS_SHA1_SOFTWARE, /* using software SHA */ +} esp_mbedtls_sha1_mode; + +/** + * \brief SHA-1 context structure + */ +typedef struct +{ + uint32_t total[2]; /*!< number of bytes processed */ + uint32_t state[5]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ + esp_mbedtls_sha1_mode mode; +} +mbedtls_sha1_context; + +#endif + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/tools/sdk/include/mbedtls/sha256_alt.h b/tools/sdk/include/mbedtls/sha256_alt.h new file mode 100644 index 00000000000..436f5324c8c --- /dev/null +++ b/tools/sdk/include/mbedtls/sha256_alt.h @@ -0,0 +1,57 @@ +/* + * SHA-256 implementation with hardware ESP32 support added. + * Uses mbedTLS software implementation for failover when concurrent + * SHA operations are in use. + * + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Additions Copyright (C) 2016, Espressif Systems (Shanghai) PTE LTD + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef _SHA256_ALT_H_ +#define _SHA256_ALT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_SHA256_ALT) + +typedef enum { + ESP_MBEDTLS_SHA256_UNUSED, /* first block hasn't been processed yet */ + ESP_MBEDTLS_SHA256_HARDWARE, /* using hardware SHA engine */ + ESP_MBEDTLS_SHA256_SOFTWARE, /* using software SHA */ +} esp_mbedtls_sha256_mode; + +/** + * \brief SHA-256 context structure + */ +typedef struct +{ + uint32_t total[2]; /*!< number of bytes processed */ + uint32_t state[8]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ + int is224; /*!< 0 => SHA-256, else SHA-224 */ + esp_mbedtls_sha256_mode mode; +} +mbedtls_sha256_context; + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/mbedtls/sha512_alt.h b/tools/sdk/include/mbedtls/sha512_alt.h new file mode 100644 index 00000000000..36b8fc9d244 --- /dev/null +++ b/tools/sdk/include/mbedtls/sha512_alt.h @@ -0,0 +1,57 @@ +/* + * SHA-512 implementation with hardware ESP32 support added. + * Uses mbedTLS software implementation for failover when concurrent + * SHA operations are in use. + * + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Additions Copyright (C) 2016, Espressif Systems (Shanghai) PTE LTD + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef _SHA512_ALT_H_ +#define _SHA512_ALT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_SHA512_ALT) + +typedef enum { + ESP_MBEDTLS_SHA512_UNUSED, /* first block hasn't been processed yet */ + ESP_MBEDTLS_SHA512_HARDWARE, /* using hardware SHA engine */ + ESP_MBEDTLS_SHA512_SOFTWARE, /* using software SHA */ +} esp_mbedtls_sha512_mode; + +/** + * \brief SHA-512 context structure + */ +typedef struct +{ + uint64_t total[2]; /*!< number of bytes processed */ + uint64_t state[8]; /*!< intermediate digest state */ + unsigned char buffer[128]; /*!< data block being processed */ + int is384; /*!< 0 => SHA-512, else SHA-384 */ + esp_mbedtls_sha512_mode mode; +} +mbedtls_sha512_context; + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/mbedtls_port/aes_alt.h b/tools/sdk/include/mbedtls_port/aes_alt.h deleted file mode 100644 index a4d0b70c3a1..00000000000 --- a/tools/sdk/include/mbedtls_port/aes_alt.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - * \file aes_alt.h - * - * \brief AES block cipher - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * - */ -#ifndef AES_ALT_H -#define AES_ALT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(MBEDTLS_AES_ALT) -#include "hwcrypto/aes.h" - -typedef esp_aes_context mbedtls_aes_context; - -#define mbedtls_aes_init esp_aes_init -#define mbedtls_aes_free esp_aes_free -#define mbedtls_aes_setkey_enc esp_aes_setkey -#define mbedtls_aes_setkey_dec esp_aes_setkey -#define mbedtls_aes_crypt_ecb esp_aes_crypt_ecb -#if defined(MBEDTLS_CIPHER_MODE_CBC) -#define mbedtls_aes_crypt_cbc esp_aes_crypt_cbc -#endif -#if defined(MBEDTLS_CIPHER_MODE_CFB) -#define mbedtls_aes_crypt_cfb128 esp_aes_crypt_cfb128 -#define mbedtls_aes_crypt_cfb8 esp_aes_crypt_cfb8 -#endif -#if defined(MBEDTLS_CIPHER_MODE_CTR) -#define mbedtls_aes_crypt_ctr esp_aes_crypt_ctr -#endif -#define mbedtls_aes_encrypt esp_aes_encrypt -#define mbedtls_aes_decrypt esp_aes_decrypt -#endif /* MBEDTLS_AES_ALT */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/mbedtls_port/mbedtls/bignum.h b/tools/sdk/include/mbedtls_port/mbedtls/bignum.h deleted file mode 100644 index 23cd56348a7..00000000000 --- a/tools/sdk/include/mbedtls_port/mbedtls/bignum.h +++ /dev/null @@ -1,78 +0,0 @@ -// 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_MBEDTLS_BIGNUM_H__ -#define __ESP_MBEDTLS_BIGNUM_H__ - -#include_next "mbedtls/bignum.h" - -/** - * This is a wrapper for the main mbedtls/bignum.h. This wrapper - * provides a few additional ESP32-only functions. - * - * This is because we don't set MBEDTLS_BIGNUM_ALT in the same way we - * do for AES, SHA, etc. Because we still use most of the bignum.h - * implementation and just replace a few hardware accelerated - * functions (see MBEDTLS_MPI_EXP_MOD_ALT & MBEDTLS_MPI_MUL_MPI_ALT in - * esp_config.h). - * - * @note Unlike the other hardware accelerator support functions in esp32/hwcrypto, there is no - * generic "hwcrypto/bignum.h" header for using these functions without mbedTLS. The reason for this - * is that all of the function implementations depend strongly upon the mbedTLS MPI implementation. - */ - -/** - * @brief Lock access to RSA Accelerator (MPI/bignum operations) - * - * RSA Accelerator hardware unit can only be used by one - * consumer at a time. - * - * @note This function is non-recursive (do not call it twice from the - * same task.) - * - * @note You do not need to call this if you are using the mbedTLS bignum.h - * API or esp_mpi_xxx functions. This function is only needed if you - * want to call ROM RSA functions or access the registers directly. - * - */ -void esp_mpi_acquire_hardware(void); - -/** - * @brief Unlock access to RSA Accelerator (MPI/bignum operations) - * - * Has to be called once for each call to esp_mpi_acquire_hardware(). - * - * @note You do not need to call this if you are using the mbedTLS bignum.h - * API or esp_mpi_xxx functions. This function is only needed if you - * want to call ROM RSA functions or access the registers directly. - */ -void esp_mpi_release_hardware(void); - -/* @brief MPI modular mupltiplication function - * - * Calculates Z = (X * Y) mod M using MPI hardware acceleration. - * - * This is not part of the standard mbedTLS bignum API. - * - * @note All of X, Y & Z should be less than 4096 bit long or an error is returned. - * - * @param Z Result bignum, should be pre-initialised with mbedtls_mpi_init(). - * @param X First multiplication argument. - * @param Y Second multiplication argument. - * @param M Modulus value for result. - * - * @return 0 on success, mbedTLS MPI error codes on failure. - */ -int esp_mpi_mul_mpi_mod(mbedtls_mpi *Z, const mbedtls_mpi *X, const mbedtls_mpi *Y, const mbedtls_mpi *M); - -#endif diff --git a/tools/sdk/include/mbedtls_port/mbedtls/config.h b/tools/sdk/include/mbedtls_port/mbedtls/config.h deleted file mode 100644 index cf3d904de02..00000000000 --- a/tools/sdk/include/mbedtls_port/mbedtls/config.h +++ /dev/null @@ -1,9 +0,0 @@ -/* This shim header is added so that any application code - which includes "mbedtls/config.h" directly gets the correct - config. */ -#pragma once -#if !defined(MBEDTLS_CONFIG_FILE) -#include_next "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif diff --git a/tools/sdk/include/mbedtls_port/sha1_alt.h b/tools/sdk/include/mbedtls_port/sha1_alt.h deleted file mode 100644 index fbe740c7e02..00000000000 --- a/tools/sdk/include/mbedtls_port/sha1_alt.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * SHA-1 implementation with hardware ESP32 support added. - * Uses mbedTLS software implementation for failover when concurrent - * SHA operations are in use. - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * Additions Copyright (C) 2016, Espressif Systems (Shanghai) PTE LTD - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -#ifndef _SHA1_ALT_H_ -#define _SHA1_ALT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(MBEDTLS_SHA1_ALT) - -typedef enum { - ESP_MBEDTLS_SHA1_UNUSED, /* first block hasn't been processed yet */ - ESP_MBEDTLS_SHA1_HARDWARE, /* using hardware SHA engine */ - ESP_MBEDTLS_SHA1_SOFTWARE, /* using software SHA */ -} esp_mbedtls_sha1_mode; - -/** - * \brief SHA-1 context structure - */ -typedef struct -{ - uint32_t total[2]; /*!< number of bytes processed */ - uint32_t state[5]; /*!< intermediate digest state */ - unsigned char buffer[64]; /*!< data block being processed */ - esp_mbedtls_sha1_mode mode; -} -mbedtls_sha1_context; - -/** - * \brief Initialize SHA-1 context - * - * \param ctx SHA-1 context to be initialized - */ -void mbedtls_sha1_init( mbedtls_sha1_context *ctx ); - -/** - * \brief Clear SHA-1 context - * - * \param ctx SHA-1 context to be cleared - */ -void mbedtls_sha1_free( mbedtls_sha1_context *ctx ); - -/** - * \brief Clone (the state of) a SHA-1 context - * - * \param dst The destination context - * \param src The context to be cloned - */ -void mbedtls_sha1_clone( mbedtls_sha1_context *dst, - const mbedtls_sha1_context *src ); - -/** - * \brief SHA-1 context setup - * - * \param ctx context to be initialized - */ -void mbedtls_sha1_starts( mbedtls_sha1_context *ctx ); - -/** - * \brief SHA-1 process buffer - * - * \param ctx SHA-1 context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void mbedtls_sha1_update( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief SHA-1 final digest - * - * \param ctx SHA-1 context - * \param output SHA-1 checksum result - */ -void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, unsigned char output[20] ); - -/* Internal use */ -void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] ); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/tools/sdk/include/mbedtls_port/sha256_alt.h b/tools/sdk/include/mbedtls_port/sha256_alt.h deleted file mode 100644 index cc87333aaa1..00000000000 --- a/tools/sdk/include/mbedtls_port/sha256_alt.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SHA-256 implementation with hardware ESP32 support added. - * Uses mbedTLS software implementation for failover when concurrent - * SHA operations are in use. - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * Additions Copyright (C) 2016, Espressif Systems (Shanghai) PTE LTD - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -#ifndef _SHA256_ALT_H_ -#define _SHA256_ALT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(MBEDTLS_SHA256_ALT) - -typedef enum { - ESP_MBEDTLS_SHA256_UNUSED, /* first block hasn't been processed yet */ - ESP_MBEDTLS_SHA256_HARDWARE, /* using hardware SHA engine */ - ESP_MBEDTLS_SHA256_SOFTWARE, /* using software SHA */ -} esp_mbedtls_sha256_mode; - -/** - * \brief SHA-256 context structure - */ -typedef struct -{ - uint32_t total[2]; /*!< number of bytes processed */ - uint32_t state[8]; /*!< intermediate digest state */ - unsigned char buffer[64]; /*!< data block being processed */ - int is224; /*!< 0 => SHA-256, else SHA-224 */ - esp_mbedtls_sha256_mode mode; -} -mbedtls_sha256_context; - -/** - * \brief Initialize SHA-256 context - * - * \param ctx SHA-256 context to be initialized - */ -void mbedtls_sha256_init( mbedtls_sha256_context *ctx ); - -/** - * \brief Clear SHA-256 context - * - * \param ctx SHA-256 context to be cleared - */ -void mbedtls_sha256_free( mbedtls_sha256_context *ctx ); - -/** - * \brief Clone (the state of) a SHA-256 context - * - * \param dst The destination context - * \param src The context to be cloned - */ -void mbedtls_sha256_clone( mbedtls_sha256_context *dst, - const mbedtls_sha256_context *src ); - -/** - * \brief SHA-256 context setup - * - * \param ctx context to be initialized - * \param is224 0 = use SHA256, 1 = use SHA224 - */ -void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 ); - -/** - * \brief SHA-256 process buffer - * - * \param ctx SHA-256 context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void mbedtls_sha256_update( mbedtls_sha256_context *ctx, const unsigned char *input, - size_t ilen ); - -/** - * \brief SHA-256 final digest - * - * \param ctx SHA-256 context - * \param output SHA-224/256 checksum result - */ -void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, unsigned char output[32] ); - -/* Internal use */ -void mbedtls_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] ); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/mbedtls_port/sha512_alt.h b/tools/sdk/include/mbedtls_port/sha512_alt.h deleted file mode 100644 index 70ae24e1665..00000000000 --- a/tools/sdk/include/mbedtls_port/sha512_alt.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SHA-512 implementation with hardware ESP32 support added. - * Uses mbedTLS software implementation for failover when concurrent - * SHA operations are in use. - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * Additions Copyright (C) 2016, Espressif Systems (Shanghai) PTE LTD - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -#ifndef _SHA512_ALT_H_ -#define _SHA512_ALT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(MBEDTLS_SHA512_ALT) - -typedef enum { - ESP_MBEDTLS_SHA512_UNUSED, /* first block hasn't been processed yet */ - ESP_MBEDTLS_SHA512_HARDWARE, /* using hardware SHA engine */ - ESP_MBEDTLS_SHA512_SOFTWARE, /* using software SHA */ -} esp_mbedtls_sha512_mode; - -/** - * \brief SHA-512 context structure - */ -typedef struct -{ - uint64_t total[2]; /*!< number of bytes processed */ - uint64_t state[8]; /*!< intermediate digest state */ - unsigned char buffer[128]; /*!< data block being processed */ - int is384; /*!< 0 => SHA-512, else SHA-384 */ - esp_mbedtls_sha512_mode mode; -} -mbedtls_sha512_context; - -/** - * \brief Initialize SHA-512 context - * - * \param ctx SHA-512 context to be initialized - */ -void mbedtls_sha512_init( mbedtls_sha512_context *ctx ); - -/** - * \brief Clear SHA-512 context - * - * \param ctx SHA-512 context to be cleared - */ -void mbedtls_sha512_free( mbedtls_sha512_context *ctx ); - -/** - * \brief Clone (the state of) a SHA-512 context - * - * \param dst The destination context - * \param src The context to be cloned - */ -void mbedtls_sha512_clone( mbedtls_sha512_context *dst, - const mbedtls_sha512_context *src ); - -/** - * \brief SHA-512 context setup - * - * \param ctx context to be initialized - * \param is384 0 = use SHA512, 1 = use SHA384 - */ -void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, int is384 ); - -/** - * \brief SHA-512 process buffer - * - * \param ctx SHA-512 context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void mbedtls_sha512_update( mbedtls_sha512_context *ctx, const unsigned char *input, - size_t ilen ); - -/** - * \brief SHA-512 final digest - * - * \param ctx SHA-512 context - * \param output SHA-384/512 checksum result - */ -void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, unsigned char output[64] ); - -/* Internal use */ -void mbedtls_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] ); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/sdk/include/mdns/mdns.h b/tools/sdk/include/mdns/mdns.h index db0e3b522a2..a5ebb809f6b 100644 --- a/tools/sdk/include/mdns/mdns.h +++ b/tools/sdk/include/mdns/mdns.h @@ -18,12 +18,8 @@ extern "C" { #endif -#ifndef MDNS_TEST_MODE #include #include "esp_event.h" -#else -#include "esp32_compat.h" -#endif #define MDNS_TYPE_A 0x0001 #define MDNS_TYPE_PTR 0x000C diff --git a/tools/sdk/include/micro-ecc/types.h b/tools/sdk/include/micro-ecc/types.h new file mode 100644 index 00000000000..9ee81438fac --- /dev/null +++ b/tools/sdk/include/micro-ecc/types.h @@ -0,0 +1,108 @@ +/* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */ + +#ifndef _UECC_TYPES_H_ +#define _UECC_TYPES_H_ + +#ifndef uECC_PLATFORM + #if __AVR__ + #define uECC_PLATFORM uECC_avr + #elif defined(__thumb2__) || defined(_M_ARMT) /* I think MSVC only supports Thumb-2 targets */ + #define uECC_PLATFORM uECC_arm_thumb2 + #elif defined(__thumb__) + #define uECC_PLATFORM uECC_arm_thumb + #elif defined(__arm__) || defined(_M_ARM) + #define uECC_PLATFORM uECC_arm + #elif defined(__aarch64__) + #define uECC_PLATFORM uECC_arm64 + #elif defined(__i386__) || defined(_M_IX86) || defined(_X86_) || defined(__I86__) + #define uECC_PLATFORM uECC_x86 + #elif defined(__amd64__) || defined(_M_X64) + #define uECC_PLATFORM uECC_x86_64 + #else + #define uECC_PLATFORM uECC_arch_other + #endif +#endif + +#ifndef uECC_ARM_USE_UMAAL + #if (uECC_PLATFORM == uECC_arm) && (__ARM_ARCH >= 6) + #define uECC_ARM_USE_UMAAL 1 + #elif (uECC_PLATFORM == uECC_arm_thumb2) && (__ARM_ARCH >= 6) && !__ARM_ARCH_7M__ + #define uECC_ARM_USE_UMAAL 1 + #else + #define uECC_ARM_USE_UMAAL 0 + #endif +#endif + +#ifndef uECC_WORD_SIZE + #if uECC_PLATFORM == uECC_avr + #define uECC_WORD_SIZE 1 + #elif (uECC_PLATFORM == uECC_x86_64 || uECC_PLATFORM == uECC_arm64) + #define uECC_WORD_SIZE 8 + #else + #define uECC_WORD_SIZE 4 + #endif +#endif + +#if (uECC_WORD_SIZE != 1) && (uECC_WORD_SIZE != 4) && (uECC_WORD_SIZE != 8) + #error "Unsupported value for uECC_WORD_SIZE" +#endif + +#if ((uECC_PLATFORM == uECC_avr) && (uECC_WORD_SIZE != 1)) + #pragma message ("uECC_WORD_SIZE must be 1 for AVR") + #undef uECC_WORD_SIZE + #define uECC_WORD_SIZE 1 +#endif + +#if ((uECC_PLATFORM == uECC_arm || uECC_PLATFORM == uECC_arm_thumb || \ + uECC_PLATFORM == uECC_arm_thumb2) && \ + (uECC_WORD_SIZE != 4)) + #pragma message ("uECC_WORD_SIZE must be 4 for ARM") + #undef uECC_WORD_SIZE + #define uECC_WORD_SIZE 4 +#endif + +#if defined(__SIZEOF_INT128__) || ((__clang_major__ * 100 + __clang_minor__) >= 302) + #define SUPPORTS_INT128 1 +#else + #define SUPPORTS_INT128 0 +#endif + +typedef int8_t wordcount_t; +typedef int16_t bitcount_t; +typedef int8_t cmpresult_t; + +#if (uECC_WORD_SIZE == 1) + +typedef uint8_t uECC_word_t; +typedef uint16_t uECC_dword_t; + +#define HIGH_BIT_SET 0x80 +#define uECC_WORD_BITS 8 +#define uECC_WORD_BITS_SHIFT 3 +#define uECC_WORD_BITS_MASK 0x07 + +#elif (uECC_WORD_SIZE == 4) + +typedef uint32_t uECC_word_t; +typedef uint64_t uECC_dword_t; + +#define HIGH_BIT_SET 0x80000000 +#define uECC_WORD_BITS 32 +#define uECC_WORD_BITS_SHIFT 5 +#define uECC_WORD_BITS_MASK 0x01F + +#elif (uECC_WORD_SIZE == 8) + +typedef uint64_t uECC_word_t; +#if SUPPORTS_INT128 +typedef unsigned __int128 uECC_dword_t; +#endif + +#define HIGH_BIT_SET 0x8000000000000000ull +#define uECC_WORD_BITS 64 +#define uECC_WORD_BITS_SHIFT 6 +#define uECC_WORD_BITS_MASK 0x03F + +#endif /* uECC_WORD_SIZE */ + +#endif /* _UECC_TYPES_H_ */ diff --git a/tools/sdk/include/micro-ecc/uECC.h b/tools/sdk/include/micro-ecc/uECC.h new file mode 100644 index 00000000000..43a19d63cb2 --- /dev/null +++ b/tools/sdk/include/micro-ecc/uECC.h @@ -0,0 +1,365 @@ +/* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */ + +#ifndef _UECC_H_ +#define _UECC_H_ + +#include + +/* Platform selection options. +If uECC_PLATFORM is not defined, the code will try to guess it based on compiler macros. +Possible values for uECC_PLATFORM are defined below: */ +#define uECC_arch_other 0 +#define uECC_x86 1 +#define uECC_x86_64 2 +#define uECC_arm 3 +#define uECC_arm_thumb 4 +#define uECC_arm_thumb2 5 +#define uECC_arm64 6 +#define uECC_avr 7 + +/* If desired, you can define uECC_WORD_SIZE as appropriate for your platform (1, 4, or 8 bytes). +If uECC_WORD_SIZE is not explicitly defined then it will be automatically set based on your +platform. */ + +/* Optimization level; trade speed for code size. + Larger values produce code that is faster but larger. + Currently supported values are 0 - 4; 0 is unusably slow for most applications. + Optimization level 4 currently only has an effect ARM platforms where more than one + curve is enabled. */ +#ifndef uECC_OPTIMIZATION_LEVEL + #define uECC_OPTIMIZATION_LEVEL 2 +#endif + +/* uECC_SQUARE_FUNC - If enabled (defined as nonzero), this will cause a specific function to be +used for (scalar) squaring instead of the generic multiplication function. This can make things +faster somewhat faster, but increases the code size. */ +#ifndef uECC_SQUARE_FUNC + #define uECC_SQUARE_FUNC 0 +#endif + +/* uECC_VLI_NATIVE_LITTLE_ENDIAN - If enabled (defined as nonzero), this will switch to native +little-endian format for *all* arrays passed in and out of the public API. This includes public +and private keys, shared secrets, signatures and message hashes. +Using this switch reduces the amount of call stack memory used by uECC, since less intermediate +translations are required. +Note that this will *only* work on native little-endian processors and it will treat the uint8_t +arrays passed into the public API as word arrays, therefore requiring the provided byte arrays +to be word aligned on architectures that do not support unaligned accesses. +IMPORTANT: Keys and signatures generated with uECC_VLI_NATIVE_LITTLE_ENDIAN=1 are incompatible +with keys and signatures generated with uECC_VLI_NATIVE_LITTLE_ENDIAN=0; all parties must use +the same endianness. */ +#ifndef uECC_VLI_NATIVE_LITTLE_ENDIAN + #define uECC_VLI_NATIVE_LITTLE_ENDIAN 0 +#endif + +/* Curve support selection. Set to 0 to remove that curve. */ +#ifndef uECC_SUPPORTS_secp160r1 + #define uECC_SUPPORTS_secp160r1 1 +#endif +#ifndef uECC_SUPPORTS_secp192r1 + #define uECC_SUPPORTS_secp192r1 1 +#endif +#ifndef uECC_SUPPORTS_secp224r1 + #define uECC_SUPPORTS_secp224r1 1 +#endif +#ifndef uECC_SUPPORTS_secp256r1 + #define uECC_SUPPORTS_secp256r1 1 +#endif +#ifndef uECC_SUPPORTS_secp256k1 + #define uECC_SUPPORTS_secp256k1 1 +#endif + +/* Specifies whether compressed point format is supported. + Set to 0 to disable point compression/decompression functions. */ +#ifndef uECC_SUPPORT_COMPRESSED_POINT + #define uECC_SUPPORT_COMPRESSED_POINT 1 +#endif + +struct uECC_Curve_t; +typedef const struct uECC_Curve_t * uECC_Curve; + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if uECC_SUPPORTS_secp160r1 +uECC_Curve uECC_secp160r1(void); +#endif +#if uECC_SUPPORTS_secp192r1 +uECC_Curve uECC_secp192r1(void); +#endif +#if uECC_SUPPORTS_secp224r1 +uECC_Curve uECC_secp224r1(void); +#endif +#if uECC_SUPPORTS_secp256r1 +uECC_Curve uECC_secp256r1(void); +#endif +#if uECC_SUPPORTS_secp256k1 +uECC_Curve uECC_secp256k1(void); +#endif + +/* uECC_RNG_Function type +The RNG function should fill 'size' random bytes into 'dest'. It should return 1 if +'dest' was filled with random data, or 0 if the random data could not be generated. +The filled-in values should be either truly random, or from a cryptographically-secure PRNG. + +A correctly functioning RNG function must be set (using uECC_set_rng()) before calling +uECC_make_key() or uECC_sign(). + +Setting a correctly functioning RNG function improves the resistance to side-channel attacks +for uECC_shared_secret() and uECC_sign_deterministic(). + +A correct RNG function is set by default when building for Windows, Linux, or OS X. +If you are building on another POSIX-compliant system that supports /dev/random or /dev/urandom, +you can define uECC_POSIX to use the predefined RNG. For embedded platforms there is no predefined +RNG function; you must provide your own. +*/ +typedef int (*uECC_RNG_Function)(uint8_t *dest, unsigned size); + +/* uECC_set_rng() function. +Set the function that will be used to generate random bytes. The RNG function should +return 1 if the random data was generated, or 0 if the random data could not be generated. + +On platforms where there is no predefined RNG function (eg embedded platforms), this must +be called before uECC_make_key() or uECC_sign() are used. + +Inputs: + rng_function - The function that will be used to generate random bytes. +*/ +void uECC_set_rng(uECC_RNG_Function rng_function); + +/* uECC_get_rng() function. + +Returns the function that will be used to generate random bytes. +*/ +uECC_RNG_Function uECC_get_rng(void); + +/* uECC_curve_private_key_size() function. + +Returns the size of a private key for the curve in bytes. +*/ +int uECC_curve_private_key_size(uECC_Curve curve); + +/* uECC_curve_public_key_size() function. + +Returns the size of a public key for the curve in bytes. +*/ +int uECC_curve_public_key_size(uECC_Curve curve); + +/* uECC_make_key() function. +Create a public/private key pair. + +Outputs: + public_key - Will be filled in with the public key. Must be at least 2 * the curve size + (in bytes) long. For example, if the curve is secp256r1, public_key must be 64 + bytes long. + private_key - Will be filled in with the private key. Must be as long as the curve order; this + is typically the same as the curve size, except for secp160r1. For example, if the + curve is secp256r1, private_key must be 32 bytes long. + + For secp160r1, private_key must be 21 bytes long! Note that the first byte will + almost always be 0 (there is about a 1 in 2^80 chance of it being non-zero). + +Returns 1 if the key pair was generated successfully, 0 if an error occurred. +*/ +int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve); + +/* uECC_shared_secret() function. +Compute a shared secret given your secret key and someone else's public key. +Note: It is recommended that you hash the result of uECC_shared_secret() before using it for +symmetric encryption or HMAC. + +Inputs: + public_key - The public key of the remote party. + private_key - Your private key. + +Outputs: + secret - Will be filled in with the shared secret value. Must be the same size as the + curve size; for example, if the curve is secp256r1, secret must be 32 bytes long. + +Returns 1 if the shared secret was generated successfully, 0 if an error occurred. +*/ +int uECC_shared_secret(const uint8_t *public_key, + const uint8_t *private_key, + uint8_t *secret, + uECC_Curve curve); + +#if uECC_SUPPORT_COMPRESSED_POINT +/* uECC_compress() function. +Compress a public key. + +Inputs: + public_key - The public key to compress. + +Outputs: + compressed - Will be filled in with the compressed public key. Must be at least + (curve size + 1) bytes long; for example, if the curve is secp256r1, + compressed must be 33 bytes long. +*/ +void uECC_compress(const uint8_t *public_key, uint8_t *compressed, uECC_Curve curve); + +/* uECC_decompress() function. +Decompress a compressed public key. + +Inputs: + compressed - The compressed public key. + +Outputs: + public_key - Will be filled in with the decompressed public key. +*/ +void uECC_decompress(const uint8_t *compressed, uint8_t *public_key, uECC_Curve curve); +#endif /* uECC_SUPPORT_COMPRESSED_POINT */ + +/* uECC_valid_public_key() function. +Check to see if a public key is valid. + +Note that you are not required to check for a valid public key before using any other uECC +functions. However, you may wish to avoid spending CPU time computing a shared secret or +verifying a signature using an invalid public key. + +Inputs: + public_key - The public key to check. + +Returns 1 if the public key is valid, 0 if it is invalid. +*/ +int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve); + +/* uECC_compute_public_key() function. +Compute the corresponding public key for a private key. + +Inputs: + private_key - The private key to compute the public key for + +Outputs: + public_key - Will be filled in with the corresponding public key + +Returns 1 if the key was computed successfully, 0 if an error occurred. +*/ +int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key, uECC_Curve curve); + +/* uECC_sign() function. +Generate an ECDSA signature for a given hash value. + +Usage: Compute a hash of the data you wish to sign (SHA-2 is recommended) and pass it in to +this function along with your private key. + +Inputs: + private_key - Your private key. + message_hash - The hash of the message to sign. + hash_size - The size of message_hash in bytes. + +Outputs: + signature - Will be filled in with the signature value. Must be at least 2 * curve size long. + For example, if the curve is secp256r1, signature must be 64 bytes long. + +Returns 1 if the signature generated successfully, 0 if an error occurred. +*/ +int uECC_sign(const uint8_t *private_key, + const uint8_t *message_hash, + unsigned hash_size, + uint8_t *signature, + uECC_Curve curve); + +/* uECC_HashContext structure. +This is used to pass in an arbitrary hash function to uECC_sign_deterministic(). +The structure will be used for multiple hash computations; each time a new hash +is computed, init_hash() will be called, followed by one or more calls to +update_hash(), and finally a call to finish_hash() to produce the resulting hash. + +The intention is that you will create a structure that includes uECC_HashContext +followed by any hash-specific data. For example: + +typedef struct SHA256_HashContext { + uECC_HashContext uECC; + SHA256_CTX ctx; +} SHA256_HashContext; + +void init_SHA256(uECC_HashContext *base) { + SHA256_HashContext *context = (SHA256_HashContext *)base; + SHA256_Init(&context->ctx); +} + +void update_SHA256(uECC_HashContext *base, + const uint8_t *message, + unsigned message_size) { + SHA256_HashContext *context = (SHA256_HashContext *)base; + SHA256_Update(&context->ctx, message, message_size); +} + +void finish_SHA256(uECC_HashContext *base, uint8_t *hash_result) { + SHA256_HashContext *context = (SHA256_HashContext *)base; + SHA256_Final(hash_result, &context->ctx); +} + +... when signing ... +{ + uint8_t tmp[32 + 32 + 64]; + SHA256_HashContext ctx = {{&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp}}; + uECC_sign_deterministic(key, message_hash, &ctx.uECC, signature); +} +*/ +typedef struct uECC_HashContext { + void (*init_hash)(const struct uECC_HashContext *context); + void (*update_hash)(const struct uECC_HashContext *context, + const uint8_t *message, + unsigned message_size); + void (*finish_hash)(const struct uECC_HashContext *context, uint8_t *hash_result); + unsigned block_size; /* Hash function block size in bytes, eg 64 for SHA-256. */ + unsigned result_size; /* Hash function result size in bytes, eg 32 for SHA-256. */ + uint8_t *tmp; /* Must point to a buffer of at least (2 * result_size + block_size) bytes. */ +} uECC_HashContext; + +/* uECC_sign_deterministic() function. +Generate an ECDSA signature for a given hash value, using a deterministic algorithm +(see RFC 6979). You do not need to set the RNG using uECC_set_rng() before calling +this function; however, if the RNG is defined it will improve resistance to side-channel +attacks. + +Usage: Compute a hash of the data you wish to sign (SHA-2 is recommended) and pass it to +this function along with your private key and a hash context. Note that the message_hash +does not need to be computed with the same hash function used by hash_context. + +Inputs: + private_key - Your private key. + message_hash - The hash of the message to sign. + hash_size - The size of message_hash in bytes. + hash_context - A hash context to use. + +Outputs: + signature - Will be filled in with the signature value. + +Returns 1 if the signature generated successfully, 0 if an error occurred. +*/ +int uECC_sign_deterministic(const uint8_t *private_key, + const uint8_t *message_hash, + unsigned hash_size, + const uECC_HashContext *hash_context, + uint8_t *signature, + uECC_Curve curve); + +/* uECC_verify() function. +Verify an ECDSA signature. + +Usage: Compute the hash of the signed data using the same hash as the signer and +pass it to this function along with the signer's public key and the signature values (r and s). + +Inputs: + public_key - The signer's public key. + message_hash - The hash of the signed data. + hash_size - The size of message_hash in bytes. + signature - The signature value. + +Returns 1 if the signature is valid, 0 if it is invalid. +*/ +int uECC_verify(const uint8_t *public_key, + const uint8_t *message_hash, + unsigned hash_size, + const uint8_t *signature, + uECC_Curve curve); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* _UECC_H_ */ diff --git a/tools/sdk/include/micro-ecc/uECC_vli.h b/tools/sdk/include/micro-ecc/uECC_vli.h new file mode 100644 index 00000000000..864cc333569 --- /dev/null +++ b/tools/sdk/include/micro-ecc/uECC_vli.h @@ -0,0 +1,172 @@ +/* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */ + +#ifndef _UECC_VLI_H_ +#define _UECC_VLI_H_ + +#include "uECC.h" +#include "types.h" + +/* Functions for raw large-integer manipulation. These are only available + if uECC.c is compiled with uECC_ENABLE_VLI_API defined to 1. */ +#ifndef uECC_ENABLE_VLI_API + #define uECC_ENABLE_VLI_API 0 +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if uECC_ENABLE_VLI_API + +void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words); + +/* Constant-time comparison to zero - secure way to compare long integers */ +/* Returns 1 if vli == 0, 0 otherwise. */ +uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words); + +/* Returns nonzero if bit 'bit' of vli is set. */ +uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit); + +/* Counts the number of bits required to represent vli. */ +bitcount_t uECC_vli_numBits(const uECC_word_t *vli, const wordcount_t max_words); + +/* Sets dest = src. */ +void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, wordcount_t num_words); + +/* Constant-time comparison function - secure way to compare long integers */ +/* Returns one if left == right, zero otherwise */ +uECC_word_t uECC_vli_equal(const uECC_word_t *left, + const uECC_word_t *right, + wordcount_t num_words); + +/* Constant-time comparison function - secure way to compare long integers */ +/* Returns sign of left - right, in constant time. */ +cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words); + +/* Computes vli = vli >> 1. */ +void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words); + +/* Computes result = left + right, returning carry. Can modify in place. */ +uECC_word_t uECC_vli_add(uECC_word_t *result, + const uECC_word_t *left, + const uECC_word_t *right, + wordcount_t num_words); + +/* Computes result = left - right, returning borrow. Can modify in place. */ +uECC_word_t uECC_vli_sub(uECC_word_t *result, + const uECC_word_t *left, + const uECC_word_t *right, + wordcount_t num_words); + +/* Computes result = left * right. Result must be 2 * num_words long. */ +void uECC_vli_mult(uECC_word_t *result, + const uECC_word_t *left, + const uECC_word_t *right, + wordcount_t num_words); + +/* Computes result = left^2. Result must be 2 * num_words long. */ +void uECC_vli_square(uECC_word_t *result, const uECC_word_t *left, wordcount_t num_words); + +/* Computes result = (left + right) % mod. + Assumes that left < mod and right < mod, and that result does not overlap mod. */ +void uECC_vli_modAdd(uECC_word_t *result, + const uECC_word_t *left, + const uECC_word_t *right, + const uECC_word_t *mod, + wordcount_t num_words); + +/* Computes result = (left - right) % mod. + Assumes that left < mod and right < mod, and that result does not overlap mod. */ +void uECC_vli_modSub(uECC_word_t *result, + const uECC_word_t *left, + const uECC_word_t *right, + const uECC_word_t *mod, + wordcount_t num_words); + +/* Computes result = product % mod, where product is 2N words long. + Currently only designed to work for mod == curve->p or curve_n. */ +void uECC_vli_mmod(uECC_word_t *result, + uECC_word_t *product, + const uECC_word_t *mod, + wordcount_t num_words); + +/* Calculates result = product (mod curve->p), where product is up to + 2 * curve->num_words long. */ +void uECC_vli_mmod_fast(uECC_word_t *result, uECC_word_t *product, uECC_Curve curve); + +/* Computes result = (left * right) % mod. + Currently only designed to work for mod == curve->p or curve_n. */ +void uECC_vli_modMult(uECC_word_t *result, + const uECC_word_t *left, + const uECC_word_t *right, + const uECC_word_t *mod, + wordcount_t num_words); + +/* Computes result = (left * right) % curve->p. */ +void uECC_vli_modMult_fast(uECC_word_t *result, + const uECC_word_t *left, + const uECC_word_t *right, + uECC_Curve curve); + +/* Computes result = left^2 % mod. + Currently only designed to work for mod == curve->p or curve_n. */ +void uECC_vli_modSquare(uECC_word_t *result, + const uECC_word_t *left, + const uECC_word_t *mod, + wordcount_t num_words); + +/* Computes result = left^2 % curve->p. */ +void uECC_vli_modSquare_fast(uECC_word_t *result, const uECC_word_t *left, uECC_Curve curve); + +/* Computes result = (1 / input) % mod.*/ +void uECC_vli_modInv(uECC_word_t *result, + const uECC_word_t *input, + const uECC_word_t *mod, + wordcount_t num_words); + +#if uECC_SUPPORT_COMPRESSED_POINT +/* Calculates a = sqrt(a) (mod curve->p) */ +void uECC_vli_mod_sqrt(uECC_word_t *a, uECC_Curve curve); +#endif + +/* Converts an integer in uECC native format to big-endian bytes. */ +void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes, const uECC_word_t *native); +/* Converts big-endian bytes to an integer in uECC native format. */ +void uECC_vli_bytesToNative(uECC_word_t *native, const uint8_t *bytes, int num_bytes); + +unsigned uECC_curve_num_words(uECC_Curve curve); +unsigned uECC_curve_num_bytes(uECC_Curve curve); +unsigned uECC_curve_num_bits(uECC_Curve curve); +unsigned uECC_curve_num_n_words(uECC_Curve curve); +unsigned uECC_curve_num_n_bytes(uECC_Curve curve); +unsigned uECC_curve_num_n_bits(uECC_Curve curve); + +const uECC_word_t *uECC_curve_p(uECC_Curve curve); +const uECC_word_t *uECC_curve_n(uECC_Curve curve); +const uECC_word_t *uECC_curve_G(uECC_Curve curve); +const uECC_word_t *uECC_curve_b(uECC_Curve curve); + +int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve); + +/* Multiplies a point by a scalar. Points are represented by the X coordinate followed by + the Y coordinate in the same array, both coordinates are curve->num_words long. Note + that scalar must be curve->num_n_words long (NOT curve->num_words). */ +void uECC_point_mult(uECC_word_t *result, + const uECC_word_t *point, + const uECC_word_t *scalar, + uECC_Curve curve); + +/* Generates a random integer in the range 0 < random < top. + Both random and top have num_words words. */ +int uECC_generate_random_int(uECC_word_t *random, + const uECC_word_t *top, + wordcount_t num_words); + +#endif /* uECC_ENABLE_VLI_API */ + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* _UECC_VLI_H_ */ diff --git a/tools/sdk/include/mqtt/mqtt_client.h b/tools/sdk/include/mqtt/mqtt_client.h new file mode 100644 index 00000000000..cb061328406 --- /dev/null +++ b/tools/sdk/include/mqtt/mqtt_client.h @@ -0,0 +1,244 @@ +/* + * This file is subject to the terms and conditions defined in + * file 'LICENSE', which is part of this source code package. + * Tuan PM + */ + +#ifndef _MQTT_CLIENT_H_ +#define _MQTT_CLIENT_H_ + +#include +#include +#include +#include "esp_err.h" + +#include "mqtt_config.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct esp_mqtt_client *esp_mqtt_client_handle_t; + +/** + * @brief MQTT event types. + * + * User event handler receives context data in `esp_mqtt_event_t` structure with + * - `user_context` - user data from `esp_mqtt_client_config_t` + * - `client` - mqtt client handle + * - various other data depending on event type + * + */ +typedef enum { + MQTT_EVENT_ERROR = 0, + MQTT_EVENT_CONNECTED, /*!< connected event, additional context: session_present flag */ + MQTT_EVENT_DISCONNECTED, /*!< disconnected event */ + MQTT_EVENT_SUBSCRIBED, /*!< subscribed event, additional context: msg_id */ + MQTT_EVENT_UNSUBSCRIBED, /*!< unsubscribed event */ + MQTT_EVENT_PUBLISHED, /*!< published event, additional context: msg_id */ + MQTT_EVENT_DATA, /*!< data event, additional context: + - msg_id message id + - topic pointer to the received topic + - topic_len length of the topic + - data pointer to the received data + - data_len length of the data for this event + - current_data_offset offset of the current data for this event + - total_data_len total length of the data received + Note: Multiple MQTT_EVENT_DATA could be fired for one message, if it is + longer than internal buffer. In that case only first event contains topic + pointer and length, other contain data only with current data length + and current data offset updating. + */ + MQTT_EVENT_BEFORE_CONNECT, /*!< The event occurs before connecting */ +} esp_mqtt_event_id_t; + +typedef enum { + MQTT_TRANSPORT_UNKNOWN = 0x0, + MQTT_TRANSPORT_OVER_TCP, /*!< MQTT over TCP, using scheme: ``mqtt`` */ + MQTT_TRANSPORT_OVER_SSL, /*!< MQTT over SSL, using scheme: ``mqtts`` */ + MQTT_TRANSPORT_OVER_WS, /*!< MQTT over Websocket, using scheme:: ``ws`` */ + MQTT_TRANSPORT_OVER_WSS /*!< MQTT over Websocket Secure, using scheme: ``wss`` */ +} esp_mqtt_transport_t; + +/** + * MQTT event configuration structure + */ +typedef struct { + esp_mqtt_event_id_t event_id; /*!< MQTT event type */ + esp_mqtt_client_handle_t client; /*!< MQTT client handle for this event */ + void *user_context; /*!< User context passed from MQTT client config */ + char *data; /*!< Data asociated with this event */ + int data_len; /*!< Lenght of the data for this event */ + int total_data_len; /*!< Total length of the data (longer data are supplied with multiple events) */ + int current_data_offset; /*!< Actual offset for the data asociated with this event */ + char *topic; /*!< Topic asociated with this event */ + int topic_len; /*!< Length of the topic for this event asociated with this event */ + int msg_id; /*!< MQTT messaged id of message */ + int session_present; /*!< MQTT session_present flag for connection event */ +} esp_mqtt_event_t; + +typedef esp_mqtt_event_t *esp_mqtt_event_handle_t; + +typedef esp_err_t (* mqtt_event_callback_t)(esp_mqtt_event_handle_t event); + +/** + * MQTT client configuration structure + */ +typedef struct { + mqtt_event_callback_t event_handle; /*!< handle for MQTT events */ + const char *host; /*!< MQTT server domain (ipv4 as string) */ + const char *uri; /*!< Complete MQTT broker URI */ + uint32_t port; /*!< MQTT server port */ + const char *client_id; /*!< default client id is ``ESP32_%CHIPID%`` where %CHIPID% are last 3 bytes of MAC address in hex format */ + const char *username; /*!< MQTT username */ + const char *password; /*!< MQTT password */ + const char *lwt_topic; /*!< LWT (Last Will and Testament) message topic (NULL by default) */ + const char *lwt_msg; /*!< LWT message (NULL by default) */ + int lwt_qos; /*!< LWT message qos */ + int lwt_retain; /*!< LWT retained message flag */ + int lwt_msg_len; /*!< LWT message length */ + int disable_clean_session; /*!< mqtt clean session, default clean_session is true */ + int keepalive; /*!< mqtt keepalive, default is 120 seconds */ + bool disable_auto_reconnect; /*!< this mqtt client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to disable */ + void *user_context; /*!< pass user context to this option, then can receive that context in ``event->user_context`` */ + int task_prio; /*!< MQTT task priority, default is 5, can be changed in ``make menuconfig`` */ + int task_stack; /*!< MQTT task stack size, default is 6144 bytes, can be changed in ``make menuconfig`` */ + int buffer_size; /*!< size of MQTT send/receive buffer, default is 1024 */ + const char *cert_pem; /*!< Pointer to certificate data in PEM format for server verify (with SSL), default is NULL, not required to verify the server */ + const char *client_cert_pem; /*!< Pointer to certificate data in PEM format for SSL mutual authentication, default is NULL, not required if mutual authentication is not needed. If it is not NULL, also `client_key_pem` has to be provided. */ + const char *client_key_pem; /*!< Pointer to private key data in PEM format for SSL mutual authentication, default is NULL, not required if mutual authentication is not needed. If it is not NULL, also `client_cert_pem` has to be provided. */ + esp_mqtt_transport_t transport; /*!< overrides URI transport */ + int refresh_connection_after_ms; /*!< Refresh connection after this value (in milliseconds) */ +} esp_mqtt_client_config_t; + +/** + * @brief Creates mqtt client handle based on the configuration + * + * @param config mqtt configuration structure + * + * @return mqtt_client_handle if successfully created, NULL on error + */ +esp_mqtt_client_handle_t esp_mqtt_client_init(const esp_mqtt_client_config_t *config); + +/** + * @brief Sets mqtt connection URI. This API is usually used to overrides the URI + * configured in esp_mqtt_client_init + * + * @param client mqtt client hanlde + * @param uri + * + * @return ESP_FAIL if URI parse error, ESP_OK on success + */ +esp_err_t esp_mqtt_client_set_uri(esp_mqtt_client_handle_t client, const char *uri); + +/** + * @brief Starts mqtt client with already created client handle + * + * @param client mqtt client handle + * + * @return ESP_OK on success + * ESP_ERR_INVALID_ARG on wrong initialization + * ESP_FAIL on other error + */ +esp_err_t esp_mqtt_client_start(esp_mqtt_client_handle_t client); + +/** + * @brief This api is typically used to force reconnection upon a specific event + * + * @param client mqtt client handle + * + * @return ESP_OK on success + * ESP_FAIL if client is in invalid state + */ +esp_err_t esp_mqtt_client_reconnect(esp_mqtt_client_handle_t client); + +/** + * @brief Stops mqtt client tasks + * + * @param client mqtt client handle + * + * @return ESP_OK on success + * ESP_FAIL if client is in invalid state + */ +esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client); + +/** + * @brief Subscribe the client to defined topic with defined qos + * + * Notes: + * - Client must be connected to send subscribe message + * - This API is could be executed from a user task or + * from a mqtt event callback i.e. internal mqtt task + * (API is protected by internal mutex, so it might block + * if a longer data receive operation is in progress. + * + * @param client mqtt client handle + * @param topic + * @param qos + * + * @return message_id of the subscribe message on success + * -1 on failure + */ +int esp_mqtt_client_subscribe(esp_mqtt_client_handle_t client, const char *topic, int qos); + +/** + * @brief Unsubscribe the client from defined topic + * + * Notes: + * - Client must be connected to send unsubscribe message + * - It is thread safe, please refer to `esp_mqtt_client_subscribe` for details + * + * @param client mqtt client handle + * @param topic + * + * @return message_id of the subscribe message on success + * -1 on failure + */ +int esp_mqtt_client_unsubscribe(esp_mqtt_client_handle_t client, const char *topic); + +/** + * @brief Client to send a publish message to the broker + * + * Notes: + * - Client doesn't have to be connected to send publish message + * (although it would drop all qos=0 messages, qos>1 messages would be enqueued) + * - It is thread safe, please refer to `esp_mqtt_client_subscribe` for details + * + * @param client mqtt client handle + * @param topic topic string + * @param data payload string (set to NULL, sending empty payload message) + * @param len data length, if set to 0, length is calculated from payload string + * @param qos qos of publish message + * @param retain ratain flag + * + * @return message_id of the subscribe message on success + * 0 if cannot publish + */ +int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain); + +/** + * @brief Destroys the client handle + * + * @param client mqtt client handle + * + * @return ESP_OK + */ +esp_err_t esp_mqtt_client_destroy(esp_mqtt_client_handle_t client); + +/** + * @brief Set configuration structure, typically used when updating the config (i.e. on "before_connect" event + * + * @param client mqtt client handle + * + * @param config mqtt configuration structure + * + * @return ESP_ERR_NO_MEM if failed to allocate + * ESP_OK on success + */ +esp_err_t esp_mqtt_set_config(esp_mqtt_client_handle_t client, const esp_mqtt_client_config_t *config); + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif diff --git a/tools/sdk/include/mqtt/mqtt_config.h b/tools/sdk/include/mqtt/mqtt_config.h new file mode 100644 index 00000000000..033fc0a732a --- /dev/null +++ b/tools/sdk/include/mqtt/mqtt_config.h @@ -0,0 +1,86 @@ +/* + * This file is subject to the terms and conditions defined in + * file 'LICENSE', which is part of this source code package. + * Tuan PM + */ +#ifndef _MQTT_CONFIG_H_ +#define _MQTT_CONFIG_H_ + +#include "sdkconfig.h" + +#define MQTT_PROTOCOL_311 CONFIG_MQTT_PROTOCOL_311 +#define MQTT_RECONNECT_TIMEOUT_MS (10*1000) +#define MQTT_POLL_READ_TIMEOUT_MS (1000) + +#if CONFIG_MQTT_BUFFER_SIZE +#define MQTT_BUFFER_SIZE_BYTE CONFIG_MQTT_BUFFER_SIZE +#else +#define MQTT_BUFFER_SIZE_BYTE 1024 +#endif + +#define MQTT_MAX_HOST_LEN 64 +#define MQTT_MAX_CLIENT_LEN 32 +#define MQTT_MAX_USERNAME_LEN 32 +#define MQTT_MAX_PASSWORD_LEN 65 +#define MQTT_MAX_LWT_TOPIC 32 +#define MQTT_MAX_LWT_MSG 128 +#define MQTT_TASK_PRIORITY 5 + +#if CONFIG_MQTT_TASK_STACK_SIZE +#define MQTT_TASK_STACK CONFIG_MQTT_TASK_STACK_SIZE +#else +#define MQTT_TASK_STACK (6*1024) +#endif + +#define MQTT_KEEPALIVE_TICK (120) +#define MQTT_CMD_QUEUE_SIZE (10) +#define MQTT_NETWORK_TIMEOUT_MS (10000) + +#ifdef CONFIG_MQTT_TCP_DEFAULT_PORT +#define MQTT_TCP_DEFAULT_PORT CONFIG_MQTT_TCP_DEFAULT_PORT +#else +#define MQTT_TCP_DEFAULT_PORT 1883 +#endif + +#ifdef CONFIG_MQTT_SSL_DEFAULT_PORT +#define MQTT_SSL_DEFAULT_PORT CONFIG_MQTT_SSL_DEFAULT_PORT +#else +#define MQTT_SSL_DEFAULT_PORT 8883 +#endif + +#ifdef CONFIG_MQTT_WS_DEFAULT_PORT +#define MQTT_WS_DEFAULT_PORT CONFIG_MQTT_WS_DEFAULT_PORT +#else +#define MQTT_WS_DEFAULT_PORT 80 +#endif + +#ifdef MQTT_WSS_DEFAULT_PORT +#define MQTT_WSS_DEFAULT_PORT CONFIG_MQTT_WSS_DEFAULT_PORT +#else +#define MQTT_WSS_DEFAULT_PORT 443 +#endif + +#define MQTT_CORE_SELECTION_ENABLED CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED + +#ifdef CONFIG_MQTT_DISABLE_API_LOCKS +#define MQTT_DISABLE_API_LOCKS CONFIG_MQTT_DISABLE_API_LOCKS +#endif + +#ifdef CONFIG_MQTT_USE_CORE_0 +#define MQTT_TASK_CORE 0 +#else +#ifdef CONFIG_MQTT_USE_CORE_1 +#define MQTT_TASK_CORE 1 +#else +#define MQTT_TASK_CORE 0 +#endif +#endif + + +#define MQTT_ENABLE_SSL CONFIG_MQTT_TRANSPORT_SSL +#define MQTT_ENABLE_WS CONFIG_MQTT_TRANSPORT_WEBSOCKET +#define MQTT_ENABLE_WSS CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE + +#define OUTBOX_EXPIRED_TIMEOUT_MS (30*1000) +#define OUTBOX_MAX_SIZE (4*1024) +#endif diff --git a/tools/sdk/include/newlib/assert.h b/tools/sdk/include/newlib/assert.h index afbea986edc..df46c030b28 100644 --- a/tools/sdk/include/newlib/assert.h +++ b/tools/sdk/include/newlib/assert.h @@ -1,28 +1,50 @@ -// 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. - - -/* This header file wraps newlib's own unmodified assert.h and adds - support for silent assertion failure. +/* + assert.h */ -#pragma once -#include -#include -#include_next +#ifdef __cplusplus +extern "C" { +#endif + +#include "_ansi.h" -#if defined(CONFIG_OPTIMIZATION_ASSERTIONS_SILENT) && !defined(NDEBUG) #undef assert -#define assert(__e) ((__e) ? (void)0 : abort()) + +#ifdef NDEBUG /* required by ANSI standard */ +# define assert(__e) ((void) sizeof(__e)) +#else +# define assert(__e) ((__e) ? (void)0 : __assert_func (__FILE__, __LINE__, \ + __ASSERT_FUNC, #__e)) + +# ifndef __ASSERT_FUNC + /* Use g++'s demangled names in C++. */ +# if defined __cplusplus && defined __GNUC__ +# define __ASSERT_FUNC __PRETTY_FUNCTION__ + + /* C99 requires the use of __func__. */ +# elif __STDC_VERSION__ >= 199901L +# define __ASSERT_FUNC __func__ + + /* Older versions of gcc don't have __func__ but can use __FUNCTION__. */ +# elif __GNUC__ >= 2 +# define __ASSERT_FUNC __FUNCTION__ + + /* failed to detect __func__ support. */ +# else +# define __ASSERT_FUNC ((char *) 0) +# endif +# endif /* !__ASSERT_FUNC */ +#endif /* !NDEBUG */ + +void _EXFUN(__assert, (const char *, int, const char *) + _ATTRIBUTE ((__noreturn__))); +void _EXFUN(__assert_func, (const char *, int, const char *, const char *) + _ATTRIBUTE ((__noreturn__))); + +#if __STDC_VERSION__ >= 201112L && !defined __cplusplus +# define static_assert _Static_assert +#endif + +#ifdef __cplusplus +} #endif diff --git a/tools/sdk/include/newlib/esp_newlib.h b/tools/sdk/include/newlib/esp_newlib.h index 192844393b0..31adf7d8473 100644 --- a/tools/sdk/include/newlib/esp_newlib.h +++ b/tools/sdk/include/newlib/esp_newlib.h @@ -38,4 +38,9 @@ void esp_setup_syscall_table(); */ void esp_set_time_from_rtc(); +/* + * Sync counters RTC and FRC. Update boot_time. + */ +void esp_sync_counters_rtc_and_frc(); + #endif //__ESP_NEWLIB_H__ diff --git a/tools/sdk/include/newlib/net/if.h b/tools/sdk/include/newlib/net/if.h new file mode 100644 index 00000000000..8760bb156ee --- /dev/null +++ b/tools/sdk/include/newlib/net/if.h @@ -0,0 +1,45 @@ +// 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_PLATFORM_NET_IF_H_ +#define _ESP_PLATFORM_NET_IF_H_ + +#define MSG_DONTROUTE 0x4 /* send without using routing tables */ +#define SOCK_SEQPACKET 5 /* sequenced packet stream */ +#define MSG_EOR 0x8 /* data completes record */ +#define SOCK_SEQPACKET 5 /* sequenced packet stream */ +#define SOMAXCONN 128 + +#define IF_NAMESIZE 16 + +#define IPV6_UNICAST_HOPS 4 /* int; IP6 hops */ + +#define NI_MAXHOST 1025 +#define NI_MAXSERV 32 +#define NI_NUMERICSERV 0x00000008 +#define NI_DGRAM 0x00000010 + + +struct ipv6_mreq { + struct in6_addr ipv6mr_multiaddr; + unsigned int ipv6mr_interface; +}; + +typedef u32_t socklen_t; + + +unsigned int if_nametoindex(const char *ifname); + +char *if_indextoname(unsigned int ifindex, char *ifname); + +#endif // _ESP_PLATFORM_NET_IF_H_ diff --git a/tools/sdk/include/newlib/sys/poll.h b/tools/sdk/include/newlib/sys/poll.h new file mode 100644 index 00000000000..030da6bf480 --- /dev/null +++ b/tools/sdk/include/newlib/sys/poll.h @@ -0,0 +1,48 @@ +// Copyright 2018-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_PLATFORM_SYS_POLL_H_ +#define _ESP_PLATFORM_SYS_POLL_H_ + +#define POLLIN (1u << 0) /* data other than high-priority may be read without blocking */ +#define POLLRDNORM (1u << 1) /* normal data may be read without blocking */ +#define POLLRDBAND (1u << 2) /* priority data may be read without blocking */ +#define POLLPRI (POLLRDBAND) /* high-priority data may be read without blocking */ +// Note: POLLPRI is made equivalent to POLLRDBAND in order to fit all these events into one byte +#define POLLOUT (1u << 3) /* normal data may be written without blocking */ +#define POLLWRNORM (POLLOUT) /* equivalent to POLLOUT */ +#define POLLWRBAND (1u << 4) /* priority data my be written */ +#define POLLERR (1u << 5) /* some poll error occurred */ +#define POLLHUP (1u << 6) /* file descriptor was "hung up" */ +#define POLLNVAL (1u << 7) /* the specified file descriptor is invalid */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct pollfd { + int fd; /* The descriptor. */ + short events; /* The event(s) is/are specified here. */ + short revents; /* Events found are returned here. */ +}; + +typedef unsigned int nfds_t; + +int poll(struct pollfd *fds, nfds_t nfds, int timeout); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // _ESP_PLATFORM_SYS_POLL_H_ diff --git a/tools/sdk/include/newlib/sys/random.h b/tools/sdk/include/newlib/sys/random.h new file mode 100644 index 00000000000..afbf4dfd036 --- /dev/null +++ b/tools/sdk/include/newlib/sys/random.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. + +#ifndef __SYS_RANDOM__ +#define __SYS_RANDOM__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +ssize_t getrandom(void *buf, size_t buflen, unsigned int flags); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif //__SYS_RANDOM__ diff --git a/tools/sdk/include/newlib/sys/reent.h b/tools/sdk/include/newlib/sys/reent.h index bb52ae65f13..b35595a7d4a 100644 --- a/tools/sdk/include/newlib/sys/reent.h +++ b/tools/sdk/include/newlib/sys/reent.h @@ -402,7 +402,7 @@ struct _reent char *_asctime_buf; /* signal info */ - void (**(_sig_func))(int); + void (**_sig_func)(int); # ifndef _REENT_GLOBAL_ATEXIT /* atexit stuff */ @@ -446,6 +446,7 @@ extern const struct __sFILE_fake __sf_fake_stderr; _NULL \ } +#ifndef ESP_PLATFORM #define _REENT_INIT_PTR(var) \ { memset((var), 0, sizeof(*(var))); \ (var)->_stdin = (__FILE *)&__sf_fake_stdin; \ @@ -453,6 +454,10 @@ extern const struct __sFILE_fake __sf_fake_stderr; (var)->_stderr = (__FILE *)&__sf_fake_stderr; \ (var)->_current_locale = "C"; \ } +#else +extern void esp_reent_init(struct _reent* reent); +#define _REENT_INIT_PTR(var) esp_reent_init(var) +#endif /* Only built the assert() calls if we are built with debugging. */ #if DEBUG diff --git a/tools/sdk/include/newlib/sys/select.h b/tools/sdk/include/newlib/sys/select.h new file mode 100644 index 00000000000..199d48144d3 --- /dev/null +++ b/tools/sdk/include/newlib/sys/select.h @@ -0,0 +1,31 @@ +// 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_SYS_SELECT_H__ +#define __ESP_SYS_SELECT_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif //__ESP_SYS_SELECT_H__ diff --git a/tools/sdk/include/newlib/sys/termios.h b/tools/sdk/include/newlib/sys/termios.h new file mode 100644 index 00000000000..fd0eb5ca884 --- /dev/null +++ b/tools/sdk/include/newlib/sys/termios.h @@ -0,0 +1,296 @@ +// 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. +// +// This header file is based on the termios header of +// "The Single UNIX (r) Specification, Version 2, Copyright (c) 1997 The Open Group". + +#ifndef __ESP_SYS_TERMIOS_H__ +#define __ESP_SYS_TERMIOS_H__ + +// ESP-IDF NOTE: This header provides only a compatibility layer for macros and functions defined in sys/termios.h. +// Not everything has a defined meaning for ESP-IDF (e.g. process leader IDs) and therefore are likely to be stubbed +// in actual implementations. + + +#include +#include +#include "sdkconfig.h" + +#ifdef CONFIG_SUPPORT_TERMIOS + +// subscripts for the array c_cc: +#define VEOF 0 /** EOF character */ +#define VEOL 1 /** EOL character */ +#define VERASE 2 /** ERASE character */ +#define VINTR 3 /** INTR character */ +#define VKILL 4 /** KILL character */ +#define VMIN 5 /** MIN value */ +#define VQUIT 6 /** QUIT character */ +#define VSTART 7 /** START character */ +#define VSTOP 8 /** STOP character */ +#define VSUSP 9 /** SUSP character */ +#define VTIME 10 /** TIME value */ +#define NCCS (VTIME + 1) /** Size of the array c_cc for control characters */ + +// input modes for use as flags in the c_iflag field +#define BRKINT (1u << 0) /** Signal interrupt on break. */ +#define ICRNL (1u << 1) /** Map CR to NL on input. */ +#define IGNBRK (1u << 2) /** Ignore break condition. */ +#define IGNCR (1u << 3) /** Ignore CR. */ +#define IGNPAR (1u << 4) /** Ignore characters with parity errors. */ +#define INLCR (1u << 5) /** Map NL to CR on input. */ +#define INPCK (1u << 6) /** Enable input parity check. */ +#define ISTRIP (1u << 7) /** Strip character. */ +#define IUCLC (1u << 8) /** Map upper-case to lower-case on input (LEGACY). */ +#define IXANY (1u << 9) /** Enable any character to restart output. */ +#define IXOFF (1u << 10) /** Enable start/stop input control. */ +#define IXON (1u << 11) /** Enable start/stop output control. */ +#define PARMRK (1u << 12) /** Mark parity errors. */ + +// output Modes for use as flags in the c_oflag field +#define OPOST (1u << 0) /** Post-process output */ +#define OLCUC (1u << 1) /** Map lower-case to upper-case on output (LEGACY). */ +#define ONLCR (1u << 2) /** Map NL to CR-NL on output. */ +#define OCRNL (1u << 3) /** Map CR to NL on output. */ +#define ONOCR (1u << 4) /** No CR output at column 0. */ +#define ONLRET (1u << 5) /** NL performs CR function. */ +#define OFILL (1u << 6) /** Use fill characters for delay. */ +#define NLDLY (1u << 7) /** Select newline delays: */ +#define NL0 (0u << 7) /** Newline character type 0. */ +#define NL1 (1u << 7) /** Newline character type 1. */ +#define CRDLY (3u << 8) /** Select carriage-return delays: */ +#define CR0 (0u << 8) /** Carriage-return delay type 0. */ +#define CR1 (1u << 8) /** Carriage-return delay type 1. */ +#define CR2 (2u << 8) /** Carriage-return delay type 2. */ +#define CR3 (3u << 8) /** Carriage-return delay type 3. */ +#define TABDLY (3u << 10) /** Select horizontal-tab delays: */ +#define TAB0 (0u << 10) /** Horizontal-tab delay type 0. */ +#define TAB1 (1u << 10) /** Horizontal-tab delay type 1. */ +#define TAB2 (2u << 10) /** Horizontal-tab delay type 2. */ +#define TAB3 (3u << 10) /** Expand tabs to spaces. */ +#define BSDLY (1u << 12) /** Select backspace delays: */ +#define BS0 (0u << 12) /** Backspace-delay type 0. */ +#define BS1 (1u << 12) /** Backspace-delay type 1. */ +#define VTDLY (1u << 13) /** Select vertical-tab delays: */ +#define VT0 (0u << 13) /** Vertical-tab delay type 0. */ +#define VT1 (1u << 13) /** Vertical-tab delay type 1. */ +#define FFDLY (1u << 14) /** Select form-feed delays: */ +#define FF0 (0u << 14) /** Form-feed delay type 0. */ +#define FF1 (1u << 14) /** Form-feed delay type 1. */ + +// Baud Rate Selection. Valid values for objects of type speed_t: +// CBAUD range B0 - B38400 +#define B0 0 /** Hang up */ +#define B50 1 +#define B75 2 +#define B110 3 +#define B134 4 +#define B150 5 +#define B200 6 +#define B300 7 +#define B600 8 +#define B1200 9 +#define B1800 10 +#define B2400 11 +#define B4800 12 +#define B9600 13 +#define B19200 14 +#define B38400 15 +// CBAUDEX range B57600 - B4000000 +#define B57600 16 +#define B115200 17 +#define B230400 18 +#define B460800 19 +#define B500000 20 +#define B576000 21 +#define B921600 22 +#define B1000000 23 +#define B1152000 24 +#define B1500000 25 +#define B2000000 26 +#define B2500000 27 +#define B3000000 28 +#define B3500000 29 +#define B4000000 30 + +// Control Modes for the c_cflag field: +#define CSIZE (3u << 0) /* Character size: */ +#define CS5 (0u << 0) /** 5 bits. */ +#define CS6 (1u << 0) /** 6 bits. */ +#define CS7 (2u << 0) /** 7 bits. */ +#define CS8 (3u << 0) /** 8 bits. */ +#define CSTOPB (1u << 2) /** Send two stop bits, else one. */ +#define CREAD (1u << 3) /** Enable receiver. */ +#define PARENB (1u << 4) /** Parity enable. */ +#define PARODD (1u << 5) /** Odd parity, else even. */ +#define HUPCL (1u << 6) /** Hang up on last close. */ +#define CLOCAL (1u << 7) /** Ignore modem status lines. */ +#define CBAUD (1u << 8) /** Use baud rates defined by B0-B38400 macros. */ +#define CBAUDEX (1u << 9) /** Use baud rates defined by B57600-B4000000 macros. */ +#define BOTHER (1u << 10) /** Use custom baud rates */ + +// Local Modes for c_lflag field: +#define ECHO (1u << 0) /** Enable echo. */ +#define ECHOE (1u << 1) /** Echo erase character as error-correcting backspace. */ +#define ECHOK (1u << 2) /** Echo KILL. */ +#define ECHONL (1u << 3) /** Echo NL. */ +#define ICANON (1u << 4) /** Canonical input (erase and kill processing). */ +#define IEXTEN (1u << 5) /** Enable extended input character processing. */ +#define ISIG (1u << 6) /** Enable signals. */ +#define NOFLSH (1u << 7) /** Disable flush after interrupt or quit. */ +#define TOSTOP (1u << 8) /** Send SIGTTOU for background output. */ +#define XCASE (1u << 9) /** Canonical upper/lower presentation (LEGACY). */ + +// Attribute Selection constants for use with tcsetattr(): +#define TCSANOW 0 /** Change attributes immediately. */ +#define TCSADRAIN 1 /** Change attributes when output has drained. */ +#define TCSAFLUSH 2 /** Change attributes when output has drained; also flush pending input. */ + +// Line Control constants for use with tcflush(): +#define TCIFLUSH 0 /** Flush pending input. Flush untransmitted output. */ +#define TCIOFLUSH 1 /** Flush both pending input and untransmitted output. */ +#define TCOFLUSH 2 /** Flush untransmitted output. */ + +// constants for use with tcflow(): +#define TCIOFF 0 /** Transmit a STOP character, intended to suspend input data. */ +#define TCION 1 /** Transmit a START character, intended to restart input data. */ +#define TCOOFF 2 /** Suspend output. */ +#define TCOON 3 /** Restart output. */ + +typedef uint8_t cc_t; +typedef uint32_t speed_t; +typedef uint16_t tcflag_t; + +struct termios +{ + tcflag_t c_iflag; /** Input modes */ + tcflag_t c_oflag; /** Output modes */ + tcflag_t c_cflag; /** Control modes */ + tcflag_t c_lflag; /** Local modes */ + cc_t c_cc[NCCS]; /** Control characters */ + speed_t c_ispeed; /** input baud rate */ + speed_t c_ospeed; /** output baud rate */ +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Extracts the input baud rate from the input structure exactly (without interpretation). + * + * @param p input termios structure + * @return input baud rate + */ +speed_t cfgetispeed(const struct termios *p); + +/** + * @brief Extracts the output baud rate from the input structure exactly (without interpretation). + * + * @param p input termios structure + * @return output baud rate + */ +speed_t cfgetospeed(const struct termios *p); + +/** + * @brief Set input baud rate in the termios structure + * + * There is no effect in hardware until a subsequent call of tcsetattr(). + * + * @param p input termios structure + * @param sp input baud rate + * @return 0 when successful, -1 otherwise with errno set + */ +int cfsetispeed(struct termios *p, speed_t sp); + +/** + * @brief Set output baud rate in the termios structure + * + * There is no effect in hardware until a subsequent call of tcsetattr(). + * + * @param p input termios structure + * @param sp output baud rate + * @return 0 when successful, -1 otherwise with errno set + */ +int cfsetospeed(struct termios *p, speed_t sp); + +/** + * @brief Wait for transmission of output + * + * @param fd file descriptor of the terminal + * @return 0 when successful, -1 otherwise with errno set + */ +int tcdrain(int fd); + +/** + * @brief Suspend or restart the transmission or reception of data + * + * @param fd file descriptor of the terminal + * @param action selects actions to do + * @return 0 when successful, -1 otherwise with errno set + */ +int tcflow(int fd, int action); + +/** + * @brief Flush non-transmitted output data and non-read input data + * + * @param fd file descriptor of the terminal + * @param select selects what should be flushed + * @return 0 when successful, -1 otherwise with errno set + */ +int tcflush(int fd, int select); + +/** + * @brief Gets the parameters of the terminal + * + * @param fd file descriptor of the terminal + * @param p output termios structure + * @return 0 when successful, -1 otherwise with errno set + */ +int tcgetattr(int fd, struct termios *p); + +/** + * @brief Get process group ID for session leader for controlling terminal + * + * @param fd file descriptor of the terminal + * @return process group ID when successful, -1 otherwise with errno set + */ +pid_t tcgetsid(int fd); + +/** + * @brief Send a break for a specific duration + * + * @param fd file descriptor of the terminal + * @param duration duration of break + * @return 0 when successful, -1 otherwise with errno set + */ +int tcsendbreak(int fd, int duration); + +/** + * @brief Sets the parameters of the terminal + * + * @param fd file descriptor of the terminal + * @param optional_actions optional actions + * @param p input termios structure + * @return 0 when successful, -1 otherwise with errno set + */ +int tcsetattr(int fd, int optional_actions, const struct termios *p); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // CONFIG_SUPPORT_TERMIOS + +#endif //__ESP_SYS_TERMIOS_H__ diff --git a/tools/sdk/include/newlib/sys/types.h b/tools/sdk/include/newlib/sys/types.h index 446946a36be..ed33e0a617e 100644 --- a/tools/sdk/include/newlib/sys/types.h +++ b/tools/sdk/include/newlib/sys/types.h @@ -221,9 +221,6 @@ typedef unsigned int mode_t _ST_INT32; typedef unsigned short nlink_t; -/* FD_SET and friends are still LWIP only */ -# if !defined(ESP_PLATFORM) - /* We don't define fd_set and friends if we are compiling POSIX source, or if we have included (or may include as indicated by __USE_W32_SOCKETS) the W32api winsock[2].h header which @@ -269,7 +266,6 @@ typedef struct _types_fd_set { })) # endif /* !(defined (_POSIX_SOURCE) || defined (_WINSOCK_H) || defined (_WINSOCKAPI_) || defined (__USE_W32_SOCKETS)) */ -#endif /* !defined(ESP_PLATFORM) */ #undef __MS_types__ #undef _ST_INT32 diff --git a/tools/sdk/include/newlib/sys/uio.h b/tools/sdk/include/newlib/sys/uio.h new file mode 100644 index 00000000000..ede27b23513 --- /dev/null +++ b/tools/sdk/include/newlib/sys/uio.h @@ -0,0 +1,21 @@ +// 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_PLATFORM_SYS_UIO_H_ +#define _ESP_PLATFORM_SYS_UIO_H_ + +int writev(int s, const struct iovec *iov, int iovcnt); + +ssize_t readv(int fd, const struct iovec *iov, int iovcnt); + +#endif // _ESP_PLATFORM_SYS_UIO_H_ diff --git a/tools/sdk/include/newlib/sys/un.h b/tools/sdk/include/newlib/sys/un.h new file mode 100644 index 00000000000..a99b1832593 --- /dev/null +++ b/tools/sdk/include/newlib/sys/un.h @@ -0,0 +1,24 @@ +// 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_PLATFORM_SYS_UN_H_ +#define _ESP_PLATFORM_SYS_UN_H_ + +#define AF_UNIX 1 /* local to host (pipes) */ + +struct sockaddr_un { + short sun_family; /*AF_UNIX*/ + char sun_path[108]; /*path name */ +}; + +#endif // _ESP_PLATFORM_SYS_UN_H_ diff --git a/tools/sdk/include/nghttp/nghttp2/asio_http2.h b/tools/sdk/include/nghttp/nghttp2/asio_http2.h deleted file mode 100644 index 57e55e1fe3b..00000000000 --- a/tools/sdk/include/nghttp/nghttp2/asio_http2.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * nghttp2 - HTTP/2 C Library - * - * Copyright (c) 2014 Tatsuhiro Tsujikawa - * - * 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 ASIO_HTTP2_H -#define ASIO_HTTP2_H - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include - -namespace nghttp2 { - -namespace asio_http2 { - -struct header_value { - // header field value - std::string value; - // true if the header field value is sensitive information, such as - // authorization information or short length secret cookies. If - // true, those header fields are not indexed by HPACK (but still - // huffman-encoded), which results in lesser compression. - bool sensitive; -}; - -// header fields. The header field name must be lower-cased. -using header_map = std::multimap; - -const boost::system::error_category &nghttp2_category() noexcept; - -struct uri_ref { - std::string scheme; - std::string host; - // form after percent-encoding decoded - std::string path; - // original path, percent-encoded - std::string raw_path; - // original query, percent-encoded - std::string raw_query; - std::string fragment; -}; - -// Callback function when data is arrived. EOF is indicated by -// passing 0 to the second parameter. -typedef std::function data_cb; -typedef std::function void_cb; -typedef std::function error_cb; -// Callback function when request and response are finished. The -// parameter indicates the cause of closure. -typedef std::function close_cb; - -// Callback function to generate response body. This function has the -// same semantics with nghttp2_data_source_read_callback. Just source -// and user_data parameters are removed. -// -// Basically, write at most |len| bytes to |data| and returns the -// number of bytes written. If there is no data left to send, set -// NGHTTP2_DATA_FLAG_EOF to *data_flags (e.g., *data_flags |= -// NGHTTP2_DATA_FLAG_EOF). If there is still data to send but they -// are not available right now, return NGHTTP2_ERR_DEFERRED. In case -// of the error and request/response must be closed, return -// NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE. -typedef std::function - generator_cb; - -// Convenient function to create function to read file denoted by -// |path|. This can be passed to response::end(). -generator_cb file_generator(const std::string &path); - -// Like file_generator(const std::string&), but it takes opened file -// descriptor. The passed descriptor will be closed when returned -// function object is destroyed. -generator_cb file_generator_from_fd(int fd); - -// Validates path so that it does not contain directory traversal -// vector. Returns true if path is safe. The |path| must start with -// "/" otherwise returns false. This function should be called after -// percent-decode was performed. -bool check_path(const std::string &path); - -// Performs percent-decode against string |s|. -std::string percent_decode(const std::string &s); - -// Returns HTTP date representation of current posix time |t|. -std::string http_date(int64_t t); - -// Parses |uri| and extract scheme, host and service. The service is -// port component of URI (e.g., "8443") if available, otherwise it is -// scheme (e.g., "https"). -boost::system::error_code host_service_from_uri(boost::system::error_code &ec, - std::string &scheme, - std::string &host, - std::string &service, - const std::string &uri); - -enum nghttp2_asio_error { - NGHTTP2_ASIO_ERR_NO_ERROR = 0, - NGHTTP2_ASIO_ERR_TLS_NO_APP_PROTO_NEGOTIATED = 1, -}; - -} // namespace asio_http2 - -} // namespace nghttp2 - -namespace boost { - -namespace system { - -template <> struct is_error_code_enum { - BOOST_STATIC_CONSTANT(bool, value = true); -}; - -template <> struct is_error_code_enum { - BOOST_STATIC_CONSTANT(bool, value = true); -}; - -} // namespace system - -} // namespace boost - -#endif // ASIO_HTTP2_H diff --git a/tools/sdk/include/nghttp/nghttp2/asio_http2_client.h b/tools/sdk/include/nghttp/nghttp2/asio_http2_client.h deleted file mode 100644 index c6c1947bfdb..00000000000 --- a/tools/sdk/include/nghttp/nghttp2/asio_http2_client.h +++ /dev/null @@ -1,241 +0,0 @@ -/* - * nghttp2 - HTTP/2 C Library - * - * Copyright (c) 2015 Tatsuhiro Tsujikawa - * - * 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 ASIO_HTTP2_CLIENT_H -#define ASIO_HTTP2_CLIENT_H - -#include - -namespace nghttp2 { - -namespace asio_http2 { - -namespace client { - -class response_impl; - -class response { -public: - // Application must not call this directly. - response(); - ~response(); - - // Sets callback which is invoked when chunk of response body is - // received. - void on_data(data_cb cb) const; - - // Returns status code. - int status_code() const; - - // Returns content-length. -1 if it is unknown. - int64_t content_length() const; - - // Returns the response header fields. The pusedo header fields, - // which start with colon (:), are exluced from this list. - const header_map &header() const; - - // Application must not call this directly. - response_impl &impl() const; - -private: - std::unique_ptr impl_; -}; - -class request; - -using response_cb = std::function; -using request_cb = std::function; -using connect_cb = - std::function; - -class request_impl; - -class request { -public: - // Application must not call this directly. - request(); - ~request(); - - // Sets callback which is invoked when response header is received. - void on_response(response_cb cb) const; - - // Sets callback which is invoked when push request header is - // received. - void on_push(request_cb cb) const; - - // Sets callback which is invoked when this request and response are - // finished. After the invocation of this callback, the application - // must not access request and response object. - void on_close(close_cb cb) const; - - // Write trailer part. This must be called after setting both - // NGHTTP2_DATA_FLAG_EOF and NGHTTP2_DATA_FLAG_NO_END_STREAM set in - // *data_flag parameter in generator_cb passed to session::submit() - // function. - void write_trailer(header_map h) const; - - // Cancels this request and response with given error code. - void cancel(uint32_t error_code = NGHTTP2_INTERNAL_ERROR) const; - - // Resumes deferred uploading. - void resume() const; - - // Returns method (e.g., GET). - const std::string &method() const; - - // Returns request URI, split into components. - const uri_ref &uri() const; - - // Returns request header fields. The pusedo header fields, which - // start with colon (:), are exluced from this list. - const header_map &header() const; - - // Application must not call this directly. - request_impl &impl() const; - -private: - std::unique_ptr impl_; -}; - -// Wrapper around an nghttp2_priority_spec. -class priority_spec { -public: - // The default ctor is used only by sentinel values. - priority_spec() = default; - - // Create a priority spec with the given priority settings. - explicit priority_spec(const int32_t stream_id, const int32_t weight, - const bool exclusive = false); - - // Return a pointer to a valid nghttp2 priority spec, or null. - const nghttp2_priority_spec *get() const; - - // Indicates whether or not this spec is valid (i.e. was constructed with - // values). - const bool valid() const; - -private: - nghttp2_priority_spec spec_; - bool valid_ = false; -}; - -class session_impl; - -class session { -public: - // Starts HTTP/2 session by connecting to |host| and |service| - // (e.g., "80") using clear text TCP connection with connect timeout - // 60 seconds. - session(boost::asio::io_service &io_service, const std::string &host, - const std::string &service); - - // Starts HTTP/2 session by connecting to |host| and |service| - // (e.g., "80") using clear text TCP connection with given connect - // timeout. - session(boost::asio::io_service &io_service, const std::string &host, - const std::string &service, - const boost::posix_time::time_duration &connect_timeout); - - // Starts HTTP/2 session by connecting to |host| and |service| - // (e.g., "443") using encrypted SSL/TLS connection with connect - // timeout 60 seconds. - session(boost::asio::io_service &io_service, - boost::asio::ssl::context &tls_context, const std::string &host, - const std::string &service); - - // Starts HTTP/2 session by connecting to |host| and |service| - // (e.g., "443") using encrypted SSL/TLS connection with given - // connect timeout. - session(boost::asio::io_service &io_service, - boost::asio::ssl::context &tls_context, const std::string &host, - const std::string &service, - const boost::posix_time::time_duration &connect_timeout); - - ~session(); - - session(session &&other) noexcept; - session &operator=(session &&other) noexcept; - - // Sets callback which is invoked after connection is established. - void on_connect(connect_cb cb) const; - - // Sets callback which is invoked there is connection level error - // and session is terminated. - void on_error(error_cb cb) const; - - // Sets read timeout, which defaults to 60 seconds. - void read_timeout(const boost::posix_time::time_duration &t); - - // Shutdowns connection. - void shutdown() const; - - // Returns underlying io_service object. - boost::asio::io_service &io_service() const; - - // Submits request to server using |method| (e.g., "GET"), |uri| - // (e.g., "http://localhost/") and optionally additional header - // fields. This function returns pointer to request object if it - // succeeds, or nullptr and |ec| contains error message. - const request *submit(boost::system::error_code &ec, - const std::string &method, const std::string &uri, - header_map h = header_map{}, - priority_spec prio = priority_spec()) const; - - // Submits request to server using |method| (e.g., "GET"), |uri| - // (e.g., "http://localhost/") and optionally additional header - // fields. The |data| is request body. This function returns - // pointer to request object if it succeeds, or nullptr and |ec| - // contains error message. - const request *submit(boost::system::error_code &ec, - const std::string &method, const std::string &uri, - std::string data, header_map h = header_map{}, - priority_spec prio = priority_spec()) const; - - // Submits request to server using |method| (e.g., "GET"), |uri| - // (e.g., "http://localhost/") and optionally additional header - // fields. The |cb| is used to generate request body. This - // function returns pointer to request object if it succeeds, or - // nullptr and |ec| contains error message. - const request *submit(boost::system::error_code &ec, - const std::string &method, const std::string &uri, - generator_cb cb, header_map h = header_map{}, - priority_spec prio = priority_spec()) const; - -private: - std::shared_ptr impl_; -}; - -// configure |tls_ctx| for client use. Currently, we just set NPN -// callback for HTTP/2. -boost::system::error_code -configure_tls_context(boost::system::error_code &ec, - boost::asio::ssl::context &tls_ctx); - -} // namespace client - -} // namespace asio_http2 - -} // namespace nghttp2 - -#endif // ASIO_HTTP2_CLIENT_H diff --git a/tools/sdk/include/nghttp/nghttp2/asio_http2_server.h b/tools/sdk/include/nghttp/nghttp2/asio_http2_server.h deleted file mode 100644 index 5818e301be3..00000000000 --- a/tools/sdk/include/nghttp/nghttp2/asio_http2_server.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * nghttp2 - HTTP/2 C Library - * - * Copyright (c) 2015 Tatsuhiro Tsujikawa - * - * 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 ASIO_HTTP2_SERVER_H -#define ASIO_HTTP2_SERVER_H - -#include - -namespace nghttp2 { - -namespace asio_http2 { - -namespace server { - -class request_impl; -class response_impl; - -class request { -public: - // Application must not call this directly. - request(); - ~request(); - - // Returns request header fields. The pusedo header fields, which - // start with colon (:), are exluced from this list. - const header_map &header() const; - - // Returns method (e.g., GET). - const std::string &method() const; - - // Returns request URI, split into components. - const uri_ref &uri() const; - - // Sets callback which is invoked when chunk of request body is - // received. - void on_data(data_cb cb) const; - - // Application must not call this directly. - request_impl &impl() const; - - // Returns the remote endpoint of the request - const boost::asio::ip::tcp::endpoint &remote_endpoint() const; - -private: - std::unique_ptr impl_; -}; - -class response { -public: - // Application must not call this directly. - response(); - ~response(); - - // Write response header using |status_code| (e.g., 200) and - // additional header fields in |h|. - void write_head(unsigned int status_code, header_map h = header_map{}) const; - - // Sends |data| as request body. No further call of end() is - // allowed. - void end(std::string data = "") const; - - // Sets callback as a generator of the response body. No further - // call of end() is allowed. - void end(generator_cb cb) const; - - // Write trailer part. This must be called after setting both - // NGHTTP2_DATA_FLAG_EOF and NGHTTP2_DATA_FLAG_NO_END_STREAM set in - // *data_flag parameter in generator_cb passed to end() function. - void write_trailer(header_map h) const; - - // Sets callback which is invoked when this request and response are - // finished. After the invocation of this callback, the application - // must not access request and response object. - void on_close(close_cb cb) const; - - // Cancels this request and response with given error code. - void cancel(uint32_t error_code = NGHTTP2_INTERNAL_ERROR) const; - - // Resumes deferred response. - void resume() const; - - // Pushes resource denoted by |raw_path_query| using |method|. The - // additional header fields can be given in |h|. This function - // returns pointer to response object for promised stream, otherwise - // nullptr and error code is filled in |ec|. Be aware that the - // header field name given in |h| must be lower-cased. - const response *push(boost::system::error_code &ec, std::string method, - std::string raw_path_query, - header_map h = header_map{}) const; - - // Returns status code. - unsigned int status_code() const; - - // Returns boost::asio::io_service this response is running on. - boost::asio::io_service &io_service() const; - - // Application must not call this directly. - response_impl &impl() const; - -private: - std::unique_ptr impl_; -}; - -// This is so called request callback. Called every time request is -// received. The life time of |request| and |response| objects end -// when callback set by response::on_close() is called. After that, -// the application must not access to those objects. -typedef std::function request_cb; - -class http2_impl; - -class http2 { -public: - http2(); - ~http2(); - - http2(http2 &&other) noexcept; - http2 &operator=(http2 &&other) noexcept; - - // Starts listening connection on given address and port and serves - // incoming requests in cleartext TCP connection. If |asynchronous| - // is false, this function blocks forever unless there is an error. - // If it is true, after server has started, this function returns - // immediately, and the caller should call join() to shutdown server - // gracefully. - boost::system::error_code listen_and_serve(boost::system::error_code &ec, - const std::string &address, - const std::string &port, - bool asynchronous = false); - - // Starts listening connection on given address and port and serves - // incoming requests in SSL/TLS encrypted connection. For - // |asynchronous| parameter, see cleartext version - // |listen_and_serve|. - boost::system::error_code - listen_and_serve(boost::system::error_code &ec, - boost::asio::ssl::context &tls_context, - const std::string &address, const std::string &port, - bool asynchronous = false); - - // Registers request handler |cb| with path pattern |pattern|. This - // function will fail and returns false if same pattern has been - // already registered or |pattern| is empty string. Otherwise - // returns true. The pattern match rule is the same as - // net/http/ServeMux in golang. Quoted from golang manual - // (http://golang.org/pkg/net/http/#ServeMux): - // - // Patterns name fixed, rooted paths, like "/favicon.ico", or - // rooted subtrees, like "/images/" (note the trailing - // slash). Longer patterns take precedence over shorter ones, so - // that if there are handlers registered for both "/images/" and - // "/images/thumbnails/", the latter handler will be called for - // paths beginning "/images/thumbnails/" and the former will - // receive requests for any other paths in the "/images/" subtree. - // - // Note that since a pattern ending in a slash names a rooted - // subtree, the pattern "/" matches all paths not matched by other - // registered patterns, not just the URL with Path == "/". - // - // Patterns may optionally begin with a host name, restricting - // matches to URLs on that host only. Host-specific patterns take - // precedence over general patterns, so that a handler might - // register for the two patterns "/codesearch" and - // "codesearch.google.com/" without also taking over requests for - // "http://www.google.com/". - // - // Just like ServeMux in golang, URL request path is sanitized and - // if they contains . or .. elements, they are redirected to an - // equivalent .- and ..-free URL. - bool handle(std::string pattern, request_cb cb); - - // Sets number of native threads to handle incoming HTTP request. - // It defaults to 1. - void num_threads(size_t num_threads); - - // Sets the maximum length to which the queue of pending - // connections. - void backlog(int backlog); - - // Sets TLS handshake timeout, which defaults to 60 seconds. - void tls_handshake_timeout(const boost::posix_time::time_duration &t); - - // Sets read timeout, which defaults to 60 seconds. - void read_timeout(const boost::posix_time::time_duration &t); - - // Gracefully stop http2 server - void stop(); - - // Join on http2 server and wait for it to fully stop - void join(); - - // Get access to the io_service objects. - const std::vector> & - io_services() const; - -private: - std::unique_ptr impl_; -}; - -// Configures |tls_context| for server use. This function sets couple -// of OpenSSL options (disables SSLv2 and SSLv3 and compression) and -// enables ECDHE ciphers. NPN callback is also configured. -boost::system::error_code -configure_tls_context_easy(boost::system::error_code &ec, - boost::asio::ssl::context &tls_context); - -// Returns request handler to do redirect to |uri| using -// |status_code|. The |uri| appears in "location" header field as is. -request_cb redirect_handler(int status_code, std::string uri); - -// Returns request handler to reply with given |status_code| and HTML -// including message about status code. -request_cb status_handler(int status_code); - -} // namespace server - -} // namespace asio_http2 - -} // namespace nghttp2 - -#endif // ASIO_HTTP2_SERVER_H diff --git a/tools/sdk/include/nghttp/nghttp2/nghttp2.h b/tools/sdk/include/nghttp/nghttp2/nghttp2.h new file mode 100644 index 00000000000..1c74b35c667 --- /dev/null +++ b/tools/sdk/include/nghttp/nghttp2/nghttp2.h @@ -0,0 +1,5296 @@ +/* + * nghttp2 - HTTP/2 C Library + * + * Copyright (c) 2013, 2014 Tatsuhiro Tsujikawa + * + * 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 NGHTTP2_H +#define NGHTTP2_H + +/* Define WIN32 when build target is Win32 API (borrowed from + libcurl) */ +#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32) +#define WIN32 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#if defined(_MSC_VER) && (_MSC_VER < 1800) +/* MSVC < 2013 does not have inttypes.h because it is not C99 + compliant. See compiler macros and version number in + https://sourceforge.net/p/predef/wiki/Compilers/ */ +#include +#else /* !defined(_MSC_VER) || (_MSC_VER >= 1800) */ +#include +#endif /* !defined(_MSC_VER) || (_MSC_VER >= 1800) */ +#include +#include + +#include + +#ifdef NGHTTP2_STATICLIB +#define NGHTTP2_EXTERN +#elif defined(WIN32) +#ifdef BUILDING_NGHTTP2 +#define NGHTTP2_EXTERN __declspec(dllexport) +#else /* !BUILDING_NGHTTP2 */ +#define NGHTTP2_EXTERN __declspec(dllimport) +#endif /* !BUILDING_NGHTTP2 */ +#else /* !defined(WIN32) */ +#ifdef BUILDING_NGHTTP2 +#define NGHTTP2_EXTERN __attribute__((visibility("default"))) +#else /* !BUILDING_NGHTTP2 */ +#define NGHTTP2_EXTERN +#endif /* !BUILDING_NGHTTP2 */ +#endif /* !defined(WIN32) */ + +/** + * @macro + * + * The protocol version identification string of this library + * supports. This identifier is used if HTTP/2 is used over TLS. + */ +#define NGHTTP2_PROTO_VERSION_ID "h2" +/** + * @macro + * + * The length of :macro:`NGHTTP2_PROTO_VERSION_ID`. + */ +#define NGHTTP2_PROTO_VERSION_ID_LEN 2 + +/** + * @macro + * + * The serialized form of ALPN protocol identifier this library + * supports. Notice that first byte is the length of following + * protocol identifier. This is the same wire format of `TLS ALPN + * extension `_. This is useful + * to process incoming ALPN tokens in wire format. + */ +#define NGHTTP2_PROTO_ALPN "\x2h2" + +/** + * @macro + * + * The length of :macro:`NGHTTP2_PROTO_ALPN`. + */ +#define NGHTTP2_PROTO_ALPN_LEN (sizeof(NGHTTP2_PROTO_ALPN) - 1) + +/** + * @macro + * + * The protocol version identification string of this library + * supports. This identifier is used if HTTP/2 is used over cleartext + * TCP. + */ +#define NGHTTP2_CLEARTEXT_PROTO_VERSION_ID "h2c" + +/** + * @macro + * + * The length of :macro:`NGHTTP2_CLEARTEXT_PROTO_VERSION_ID`. + */ +#define NGHTTP2_CLEARTEXT_PROTO_VERSION_ID_LEN 3 + +struct nghttp2_session; +/** + * @struct + * + * The primary structure to hold the resources needed for a HTTP/2 + * session. The details of this structure are intentionally hidden + * from the public API. + */ +typedef struct nghttp2_session nghttp2_session; + +/** + * @macro + * + * The age of :type:`nghttp2_info` + */ +#define NGHTTP2_VERSION_AGE 1 + +/** + * @struct + * + * This struct is what `nghttp2_version()` returns. It holds + * information about the particular nghttp2 version. + */ +typedef struct { + /** + * Age of this struct. This instance of nghttp2 sets it to + * :macro:`NGHTTP2_VERSION_AGE` but a future version may bump it and + * add more struct fields at the bottom + */ + int age; + /** + * the :macro:`NGHTTP2_VERSION_NUM` number (since age ==1) + */ + int version_num; + /** + * points to the :macro:`NGHTTP2_VERSION` string (since age ==1) + */ + const char *version_str; + /** + * points to the :macro:`NGHTTP2_PROTO_VERSION_ID` string this + * instance implements (since age ==1) + */ + const char *proto_str; + /* -------- the above fields all exist when age == 1 */ +} nghttp2_info; + +/** + * @macro + * + * The default weight of stream dependency. + */ +#define NGHTTP2_DEFAULT_WEIGHT 16 + +/** + * @macro + * + * The maximum weight of stream dependency. + */ +#define NGHTTP2_MAX_WEIGHT 256 + +/** + * @macro + * + * The minimum weight of stream dependency. + */ +#define NGHTTP2_MIN_WEIGHT 1 + +/** + * @macro + * + * The maximum window size + */ +#define NGHTTP2_MAX_WINDOW_SIZE ((int32_t)((1U << 31) - 1)) + +/** + * @macro + * + * The initial window size for stream level flow control. + */ +#define NGHTTP2_INITIAL_WINDOW_SIZE ((1 << 16) - 1) +/** + * @macro + * + * The initial window size for connection level flow control. + */ +#define NGHTTP2_INITIAL_CONNECTION_WINDOW_SIZE ((1 << 16) - 1) + +/** + * @macro + * + * The default header table size. + */ +#define NGHTTP2_DEFAULT_HEADER_TABLE_SIZE (1 << 12) + +/** + * @macro + * + * The client magic string, which is the first 24 bytes byte string of + * client connection preface. + */ +#define NGHTTP2_CLIENT_MAGIC "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" + +/** + * @macro + * + * The length of :macro:`NGHTTP2_CLIENT_MAGIC`. + */ +#define NGHTTP2_CLIENT_MAGIC_LEN 24 + +/** + * @enum + * + * Error codes used in this library. The code range is [-999, -500], + * inclusive. The following values are defined: + */ +typedef enum { + /** + * Invalid argument passed. + */ + NGHTTP2_ERR_INVALID_ARGUMENT = -501, + /** + * Out of buffer space. + */ + NGHTTP2_ERR_BUFFER_ERROR = -502, + /** + * The specified protocol version is not supported. + */ + NGHTTP2_ERR_UNSUPPORTED_VERSION = -503, + /** + * Used as a return value from :type:`nghttp2_send_callback`, + * :type:`nghttp2_recv_callback` and + * :type:`nghttp2_send_data_callback` to indicate that the operation + * would block. + */ + NGHTTP2_ERR_WOULDBLOCK = -504, + /** + * General protocol error + */ + NGHTTP2_ERR_PROTO = -505, + /** + * The frame is invalid. + */ + NGHTTP2_ERR_INVALID_FRAME = -506, + /** + * The peer performed a shutdown on the connection. + */ + NGHTTP2_ERR_EOF = -507, + /** + * Used as a return value from + * :func:`nghttp2_data_source_read_callback` to indicate that data + * transfer is postponed. See + * :func:`nghttp2_data_source_read_callback` for details. + */ + NGHTTP2_ERR_DEFERRED = -508, + /** + * Stream ID has reached the maximum value. Therefore no stream ID + * is available. + */ + NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE = -509, + /** + * The stream is already closed; or the stream ID is invalid. + */ + NGHTTP2_ERR_STREAM_CLOSED = -510, + /** + * RST_STREAM has been added to the outbound queue. The stream is + * in closing state. + */ + NGHTTP2_ERR_STREAM_CLOSING = -511, + /** + * The transmission is not allowed for this stream (e.g., a frame + * with END_STREAM flag set has already sent). + */ + NGHTTP2_ERR_STREAM_SHUT_WR = -512, + /** + * The stream ID is invalid. + */ + NGHTTP2_ERR_INVALID_STREAM_ID = -513, + /** + * The state of the stream is not valid (e.g., DATA cannot be sent + * to the stream if response HEADERS has not been sent). + */ + NGHTTP2_ERR_INVALID_STREAM_STATE = -514, + /** + * Another DATA frame has already been deferred. + */ + NGHTTP2_ERR_DEFERRED_DATA_EXIST = -515, + /** + * Starting new stream is not allowed (e.g., GOAWAY has been sent + * and/or received). + */ + NGHTTP2_ERR_START_STREAM_NOT_ALLOWED = -516, + /** + * GOAWAY has already been sent. + */ + NGHTTP2_ERR_GOAWAY_ALREADY_SENT = -517, + /** + * The received frame contains the invalid header block (e.g., There + * are duplicate header names; or the header names are not encoded + * in US-ASCII character set and not lower cased; or the header name + * is zero-length string; or the header value contains multiple + * in-sequence NUL bytes). + */ + NGHTTP2_ERR_INVALID_HEADER_BLOCK = -518, + /** + * Indicates that the context is not suitable to perform the + * requested operation. + */ + NGHTTP2_ERR_INVALID_STATE = -519, + /** + * The user callback function failed due to the temporal error. + */ + NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE = -521, + /** + * The length of the frame is invalid, either too large or too small. + */ + NGHTTP2_ERR_FRAME_SIZE_ERROR = -522, + /** + * Header block inflate/deflate error. + */ + NGHTTP2_ERR_HEADER_COMP = -523, + /** + * Flow control error + */ + NGHTTP2_ERR_FLOW_CONTROL = -524, + /** + * Insufficient buffer size given to function. + */ + NGHTTP2_ERR_INSUFF_BUFSIZE = -525, + /** + * Callback was paused by the application + */ + NGHTTP2_ERR_PAUSE = -526, + /** + * There are too many in-flight SETTING frame and no more + * transmission of SETTINGS is allowed. + */ + NGHTTP2_ERR_TOO_MANY_INFLIGHT_SETTINGS = -527, + /** + * The server push is disabled. + */ + NGHTTP2_ERR_PUSH_DISABLED = -528, + /** + * DATA or HEADERS frame for a given stream has been already + * submitted and has not been fully processed yet. Application + * should wait for the transmission of the previously submitted + * frame before submitting another. + */ + NGHTTP2_ERR_DATA_EXIST = -529, + /** + * The current session is closing due to a connection error or + * `nghttp2_session_terminate_session()` is called. + */ + NGHTTP2_ERR_SESSION_CLOSING = -530, + /** + * Invalid HTTP header field was received and stream is going to be + * closed. + */ + NGHTTP2_ERR_HTTP_HEADER = -531, + /** + * Violation in HTTP messaging rule. + */ + NGHTTP2_ERR_HTTP_MESSAGING = -532, + /** + * Stream was refused. + */ + NGHTTP2_ERR_REFUSED_STREAM = -533, + /** + * Unexpected internal error, but recovered. + */ + NGHTTP2_ERR_INTERNAL = -534, + /** + * Indicates that a processing was canceled. + */ + NGHTTP2_ERR_CANCEL = -535, + /** + * The errors < :enum:`NGHTTP2_ERR_FATAL` mean that the library is + * under unexpected condition and processing was terminated (e.g., + * out of memory). If application receives this error code, it must + * stop using that :type:`nghttp2_session` object and only allowed + * operation for that object is deallocate it using + * `nghttp2_session_del()`. + */ + NGHTTP2_ERR_FATAL = -900, + /** + * Out of memory. This is a fatal error. + */ + NGHTTP2_ERR_NOMEM = -901, + /** + * The user callback function failed. This is a fatal error. + */ + NGHTTP2_ERR_CALLBACK_FAILURE = -902, + /** + * Invalid client magic (see :macro:`NGHTTP2_CLIENT_MAGIC`) was + * received and further processing is not possible. + */ + NGHTTP2_ERR_BAD_CLIENT_MAGIC = -903, + /** + * Possible flooding by peer was detected in this HTTP/2 session. + * Flooding is measured by how many PING and SETTINGS frames with + * ACK flag set are queued for transmission. These frames are + * response for the peer initiated frames, and peer can cause memory + * exhaustion on server side to send these frames forever and does + * not read network. + */ + NGHTTP2_ERR_FLOODED = -904 +} nghttp2_error; + +/** + * @struct + * + * The object representing single contiguous buffer. + */ +typedef struct { + /** + * The pointer to the buffer. + */ + uint8_t *base; + /** + * The length of the buffer. + */ + size_t len; +} nghttp2_vec; + +struct nghttp2_rcbuf; + +/** + * @struct + * + * The object representing reference counted buffer. The details of + * this structure are intentionally hidden from the public API. + */ +typedef struct nghttp2_rcbuf nghttp2_rcbuf; + +/** + * @function + * + * Increments the reference count of |rcbuf| by 1. + */ +NGHTTP2_EXTERN void nghttp2_rcbuf_incref(nghttp2_rcbuf *rcbuf); + +/** + * @function + * + * Decrements the reference count of |rcbuf| by 1. If the reference + * count becomes zero, the object pointed by |rcbuf| will be freed. + * In this case, application must not use |rcbuf| again. + */ +NGHTTP2_EXTERN void nghttp2_rcbuf_decref(nghttp2_rcbuf *rcbuf); + +/** + * @function + * + * Returns the underlying buffer managed by |rcbuf|. + */ +NGHTTP2_EXTERN nghttp2_vec nghttp2_rcbuf_get_buf(nghttp2_rcbuf *rcbuf); + +/** + * @enum + * + * The flags for header field name/value pair. + */ +typedef enum { + /** + * No flag set. + */ + NGHTTP2_NV_FLAG_NONE = 0, + /** + * Indicates that this name/value pair must not be indexed ("Literal + * Header Field never Indexed" representation must be used in HPACK + * encoding). Other implementation calls this bit as "sensitive". + */ + NGHTTP2_NV_FLAG_NO_INDEX = 0x01, + /** + * This flag is set solely by application. If this flag is set, the + * library does not make a copy of header field name. This could + * improve performance. + */ + NGHTTP2_NV_FLAG_NO_COPY_NAME = 0x02, + /** + * This flag is set solely by application. If this flag is set, the + * library does not make a copy of header field value. This could + * improve performance. + */ + NGHTTP2_NV_FLAG_NO_COPY_VALUE = 0x04 +} nghttp2_nv_flag; + +/** + * @struct + * + * The name/value pair, which mainly used to represent header fields. + */ +typedef struct { + /** + * The |name| byte string. If this struct is presented from library + * (e.g., :type:`nghttp2_on_frame_recv_callback`), |name| is + * guaranteed to be NULL-terminated. For some callbacks + * (:type:`nghttp2_before_frame_send_callback`, + * :type:`nghttp2_on_frame_send_callback`, and + * :type:`nghttp2_on_frame_not_send_callback`), it may not be + * NULL-terminated if header field is passed from application with + * the flag :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME`). When application + * is constructing this struct, |name| is not required to be + * NULL-terminated. + */ + uint8_t *name; + /** + * The |value| byte string. If this struct is presented from + * library (e.g., :type:`nghttp2_on_frame_recv_callback`), |value| + * is guaranteed to be NULL-terminated. For some callbacks + * (:type:`nghttp2_before_frame_send_callback`, + * :type:`nghttp2_on_frame_send_callback`, and + * :type:`nghttp2_on_frame_not_send_callback`), it may not be + * NULL-terminated if header field is passed from application with + * the flag :enum:`NGHTTP2_NV_FLAG_NO_COPY_VALUE`). When + * application is constructing this struct, |value| is not required + * to be NULL-terminated. + */ + uint8_t *value; + /** + * The length of the |name|, excluding terminating NULL. + */ + size_t namelen; + /** + * The length of the |value|, excluding terminating NULL. + */ + size_t valuelen; + /** + * Bitwise OR of one or more of :type:`nghttp2_nv_flag`. + */ + uint8_t flags; +} nghttp2_nv; + +/** + * @enum + * + * The frame types in HTTP/2 specification. + */ +typedef enum { + /** + * The DATA frame. + */ + NGHTTP2_DATA = 0, + /** + * The HEADERS frame. + */ + NGHTTP2_HEADERS = 0x01, + /** + * The PRIORITY frame. + */ + NGHTTP2_PRIORITY = 0x02, + /** + * The RST_STREAM frame. + */ + NGHTTP2_RST_STREAM = 0x03, + /** + * The SETTINGS frame. + */ + NGHTTP2_SETTINGS = 0x04, + /** + * The PUSH_PROMISE frame. + */ + NGHTTP2_PUSH_PROMISE = 0x05, + /** + * The PING frame. + */ + NGHTTP2_PING = 0x06, + /** + * The GOAWAY frame. + */ + NGHTTP2_GOAWAY = 0x07, + /** + * The WINDOW_UPDATE frame. + */ + NGHTTP2_WINDOW_UPDATE = 0x08, + /** + * The CONTINUATION frame. This frame type won't be passed to any + * callbacks because the library processes this frame type and its + * preceding HEADERS/PUSH_PROMISE as a single frame. + */ + NGHTTP2_CONTINUATION = 0x09, + /** + * The ALTSVC frame, which is defined in `RFC 7383 + * `_. + */ + NGHTTP2_ALTSVC = 0x0a +} nghttp2_frame_type; + +/** + * @enum + * + * The flags for HTTP/2 frames. This enum defines all flags for all + * frames. + */ +typedef enum { + /** + * No flag set. + */ + NGHTTP2_FLAG_NONE = 0, + /** + * The END_STREAM flag. + */ + NGHTTP2_FLAG_END_STREAM = 0x01, + /** + * The END_HEADERS flag. + */ + NGHTTP2_FLAG_END_HEADERS = 0x04, + /** + * The ACK flag. + */ + NGHTTP2_FLAG_ACK = 0x01, + /** + * The PADDED flag. + */ + NGHTTP2_FLAG_PADDED = 0x08, + /** + * The PRIORITY flag. + */ + NGHTTP2_FLAG_PRIORITY = 0x20 +} nghttp2_flag; + +/** + * @enum + * The SETTINGS ID. + */ +typedef enum { + /** + * SETTINGS_HEADER_TABLE_SIZE + */ + NGHTTP2_SETTINGS_HEADER_TABLE_SIZE = 0x01, + /** + * SETTINGS_ENABLE_PUSH + */ + NGHTTP2_SETTINGS_ENABLE_PUSH = 0x02, + /** + * SETTINGS_MAX_CONCURRENT_STREAMS + */ + NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS = 0x03, + /** + * SETTINGS_INITIAL_WINDOW_SIZE + */ + NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE = 0x04, + /** + * SETTINGS_MAX_FRAME_SIZE + */ + NGHTTP2_SETTINGS_MAX_FRAME_SIZE = 0x05, + /** + * SETTINGS_MAX_HEADER_LIST_SIZE + */ + NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE = 0x06 +} nghttp2_settings_id; +/* Note: If we add SETTINGS, update the capacity of + NGHTTP2_INBOUND_NUM_IV as well */ + +/** + * @macro + * + * .. warning:: + * + * Deprecated. The initial max concurrent streams is 0xffffffffu. + * + * Default maximum number of incoming concurrent streams. Use + * `nghttp2_submit_settings()` with + * :enum:`NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS` to change the + * maximum number of incoming concurrent streams. + * + * .. note:: + * + * The maximum number of outgoing concurrent streams is 100 by + * default. + */ +#define NGHTTP2_INITIAL_MAX_CONCURRENT_STREAMS ((1U << 31) - 1) + +/** + * @enum + * The status codes for the RST_STREAM and GOAWAY frames. + */ +typedef enum { + /** + * No errors. + */ + NGHTTP2_NO_ERROR = 0x00, + /** + * PROTOCOL_ERROR + */ + NGHTTP2_PROTOCOL_ERROR = 0x01, + /** + * INTERNAL_ERROR + */ + NGHTTP2_INTERNAL_ERROR = 0x02, + /** + * FLOW_CONTROL_ERROR + */ + NGHTTP2_FLOW_CONTROL_ERROR = 0x03, + /** + * SETTINGS_TIMEOUT + */ + NGHTTP2_SETTINGS_TIMEOUT = 0x04, + /** + * STREAM_CLOSED + */ + NGHTTP2_STREAM_CLOSED = 0x05, + /** + * FRAME_SIZE_ERROR + */ + NGHTTP2_FRAME_SIZE_ERROR = 0x06, + /** + * REFUSED_STREAM + */ + NGHTTP2_REFUSED_STREAM = 0x07, + /** + * CANCEL + */ + NGHTTP2_CANCEL = 0x08, + /** + * COMPRESSION_ERROR + */ + NGHTTP2_COMPRESSION_ERROR = 0x09, + /** + * CONNECT_ERROR + */ + NGHTTP2_CONNECT_ERROR = 0x0a, + /** + * ENHANCE_YOUR_CALM + */ + NGHTTP2_ENHANCE_YOUR_CALM = 0x0b, + /** + * INADEQUATE_SECURITY + */ + NGHTTP2_INADEQUATE_SECURITY = 0x0c, + /** + * HTTP_1_1_REQUIRED + */ + NGHTTP2_HTTP_1_1_REQUIRED = 0x0d +} nghttp2_error_code; + +/** + * @struct + * The frame header. + */ +typedef struct { + /** + * The length field of this frame, excluding frame header. + */ + size_t length; + /** + * The stream identifier (aka, stream ID) + */ + int32_t stream_id; + /** + * The type of this frame. See `nghttp2_frame_type`. + */ + uint8_t type; + /** + * The flags. + */ + uint8_t flags; + /** + * Reserved bit in frame header. Currently, this is always set to 0 + * and application should not expect something useful in here. + */ + uint8_t reserved; +} nghttp2_frame_hd; + +/** + * @union + * + * This union represents the some kind of data source passed to + * :type:`nghttp2_data_source_read_callback`. + */ +typedef union { + /** + * The integer field, suitable for a file descriptor. + */ + int fd; + /** + * The pointer to an arbitrary object. + */ + void *ptr; +} nghttp2_data_source; + +/** + * @enum + * + * The flags used to set in |data_flags| output parameter in + * :type:`nghttp2_data_source_read_callback`. + */ +typedef enum { + /** + * No flag set. + */ + NGHTTP2_DATA_FLAG_NONE = 0, + /** + * Indicates EOF was sensed. + */ + NGHTTP2_DATA_FLAG_EOF = 0x01, + /** + * Indicates that END_STREAM flag must not be set even if + * NGHTTP2_DATA_FLAG_EOF is set. Usually this flag is used to send + * trailer fields with `nghttp2_submit_request()` or + * `nghttp2_submit_response()`. + */ + NGHTTP2_DATA_FLAG_NO_END_STREAM = 0x02, + /** + * Indicates that application will send complete DATA frame in + * :type:`nghttp2_send_data_callback`. + */ + NGHTTP2_DATA_FLAG_NO_COPY = 0x04 +} nghttp2_data_flag; + +/** + * @functypedef + * + * Callback function invoked when the library wants to read data from + * the |source|. The read data is sent in the stream |stream_id|. + * The implementation of this function must read at most |length| + * bytes of data from |source| (or possibly other places) and store + * them in |buf| and return number of data stored in |buf|. If EOF is + * reached, set :enum:`NGHTTP2_DATA_FLAG_EOF` flag in |*data_flags|. + * + * Sometime it is desirable to avoid copying data into |buf| and let + * application to send data directly. To achieve this, set + * :enum:`NGHTTP2_DATA_FLAG_NO_COPY` to |*data_flags| (and possibly + * other flags, just like when we do copy), and return the number of + * bytes to send without copying data into |buf|. The library, seeing + * :enum:`NGHTTP2_DATA_FLAG_NO_COPY`, will invoke + * :type:`nghttp2_send_data_callback`. The application must send + * complete DATA frame in that callback. + * + * If this callback is set by `nghttp2_submit_request()`, + * `nghttp2_submit_response()` or `nghttp2_submit_headers()` and + * `nghttp2_submit_data()` with flag parameter + * :enum:`NGHTTP2_FLAG_END_STREAM` set, and + * :enum:`NGHTTP2_DATA_FLAG_EOF` flag is set to |*data_flags|, DATA + * frame will have END_STREAM flag set. Usually, this is expected + * behaviour and all are fine. One exception is send trailer fields. + * You cannot send trailer fields after sending frame with END_STREAM + * set. To avoid this problem, one can set + * :enum:`NGHTTP2_DATA_FLAG_NO_END_STREAM` along with + * :enum:`NGHTTP2_DATA_FLAG_EOF` to signal the library not to set + * END_STREAM in DATA frame. Then application can use + * `nghttp2_submit_trailer()` to send trailer fields. + * `nghttp2_submit_trailer()` can be called inside this callback. + * + * If the application wants to postpone DATA frames (e.g., + * asynchronous I/O, or reading data blocks for long time), it is + * achieved by returning :enum:`NGHTTP2_ERR_DEFERRED` without reading + * any data in this invocation. The library removes DATA frame from + * the outgoing queue temporarily. To move back deferred DATA frame + * to outgoing queue, call `nghttp2_session_resume_data()`. + * + * By default, |length| is limited to 16KiB at maximum. If peer + * allows larger frames, application can enlarge transmission buffer + * size. See :type:`nghttp2_data_source_read_length_callback` for + * more details. + * + * If the application just wants to return from + * `nghttp2_session_send()` or `nghttp2_session_mem_send()` without + * sending anything, return :enum:`NGHTTP2_ERR_PAUSE`. + * + * In case of error, there are 2 choices. Returning + * :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE` will close the stream + * by issuing RST_STREAM with :enum:`NGHTTP2_INTERNAL_ERROR`. If a + * different error code is desirable, use + * `nghttp2_submit_rst_stream()` with a desired error code and then + * return :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`. Returning + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` will signal the entire session + * failure. + */ +typedef ssize_t (*nghttp2_data_source_read_callback)( + nghttp2_session *session, int32_t stream_id, uint8_t *buf, size_t length, + uint32_t *data_flags, nghttp2_data_source *source, void *user_data); + +/** + * @struct + * + * This struct represents the data source and the way to read a chunk + * of data from it. + */ +typedef struct { + /** + * The data source. + */ + nghttp2_data_source source; + /** + * The callback function to read a chunk of data from the |source|. + */ + nghttp2_data_source_read_callback read_callback; +} nghttp2_data_provider; + +/** + * @struct + * + * The DATA frame. The received data is delivered via + * :type:`nghttp2_on_data_chunk_recv_callback`. + */ +typedef struct { + nghttp2_frame_hd hd; + /** + * The length of the padding in this frame. This includes PAD_HIGH + * and PAD_LOW. + */ + size_t padlen; +} nghttp2_data; + +/** + * @enum + * + * The category of HEADERS, which indicates the role of the frame. In + * HTTP/2 spec, request, response, push response and other arbitrary + * headers (e.g., trailer fields) are all called just HEADERS. To + * give the application the role of incoming HEADERS frame, we define + * several categories. + */ +typedef enum { + /** + * The HEADERS frame is opening new stream, which is analogous to + * SYN_STREAM in SPDY. + */ + NGHTTP2_HCAT_REQUEST = 0, + /** + * The HEADERS frame is the first response headers, which is + * analogous to SYN_REPLY in SPDY. + */ + NGHTTP2_HCAT_RESPONSE = 1, + /** + * The HEADERS frame is the first headers sent against reserved + * stream. + */ + NGHTTP2_HCAT_PUSH_RESPONSE = 2, + /** + * The HEADERS frame which does not apply for the above categories, + * which is analogous to HEADERS in SPDY. If non-final response + * (e.g., status 1xx) is used, final response HEADERS frame will be + * categorized here. + */ + NGHTTP2_HCAT_HEADERS = 3 +} nghttp2_headers_category; + +/** + * @struct + * + * The structure to specify stream dependency. + */ +typedef struct { + /** + * The stream ID of the stream to depend on. Specifying 0 makes + * stream not depend any other stream. + */ + int32_t stream_id; + /** + * The weight of this dependency. + */ + int32_t weight; + /** + * nonzero means exclusive dependency + */ + uint8_t exclusive; +} nghttp2_priority_spec; + +/** + * @struct + * + * The HEADERS frame. It has the following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The length of the padding in this frame. This includes PAD_HIGH + * and PAD_LOW. + */ + size_t padlen; + /** + * The priority specification + */ + nghttp2_priority_spec pri_spec; + /** + * The name/value pairs. + */ + nghttp2_nv *nva; + /** + * The number of name/value pairs in |nva|. + */ + size_t nvlen; + /** + * The category of this HEADERS frame. + */ + nghttp2_headers_category cat; +} nghttp2_headers; + +/** + * @struct + * + * The PRIORITY frame. It has the following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The priority specification. + */ + nghttp2_priority_spec pri_spec; +} nghttp2_priority; + +/** + * @struct + * + * The RST_STREAM frame. It has the following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The error code. See :type:`nghttp2_error_code`. + */ + uint32_t error_code; +} nghttp2_rst_stream; + +/** + * @struct + * + * The SETTINGS ID/Value pair. It has the following members: + */ +typedef struct { + /** + * The SETTINGS ID. See :type:`nghttp2_settings_id`. + */ + int32_t settings_id; + /** + * The value of this entry. + */ + uint32_t value; +} nghttp2_settings_entry; + +/** + * @struct + * + * The SETTINGS frame. It has the following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The number of SETTINGS ID/Value pairs in |iv|. + */ + size_t niv; + /** + * The pointer to the array of SETTINGS ID/Value pair. + */ + nghttp2_settings_entry *iv; +} nghttp2_settings; + +/** + * @struct + * + * The PUSH_PROMISE frame. It has the following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The length of the padding in this frame. This includes PAD_HIGH + * and PAD_LOW. + */ + size_t padlen; + /** + * The name/value pairs. + */ + nghttp2_nv *nva; + /** + * The number of name/value pairs in |nva|. + */ + size_t nvlen; + /** + * The promised stream ID + */ + int32_t promised_stream_id; + /** + * Reserved bit. Currently this is always set to 0 and application + * should not expect something useful in here. + */ + uint8_t reserved; +} nghttp2_push_promise; + +/** + * @struct + * + * The PING frame. It has the following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The opaque data + */ + uint8_t opaque_data[8]; +} nghttp2_ping; + +/** + * @struct + * + * The GOAWAY frame. It has the following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The last stream stream ID. + */ + int32_t last_stream_id; + /** + * The error code. See :type:`nghttp2_error_code`. + */ + uint32_t error_code; + /** + * The additional debug data + */ + uint8_t *opaque_data; + /** + * The length of |opaque_data| member. + */ + size_t opaque_data_len; + /** + * Reserved bit. Currently this is always set to 0 and application + * should not expect something useful in here. + */ + uint8_t reserved; +} nghttp2_goaway; + +/** + * @struct + * + * The WINDOW_UPDATE frame. It has the following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The window size increment. + */ + int32_t window_size_increment; + /** + * Reserved bit. Currently this is always set to 0 and application + * should not expect something useful in here. + */ + uint8_t reserved; +} nghttp2_window_update; + +/** + * @struct + * + * The extension frame. It has following members: + */ +typedef struct { + /** + * The frame header. + */ + nghttp2_frame_hd hd; + /** + * The pointer to extension payload. The exact pointer type is + * determined by hd.type. + * + * Currently, no extension is supported. This is a place holder for + * the future extensions. + */ + void *payload; +} nghttp2_extension; + +/** + * @union + * + * This union includes all frames to pass them to various function + * calls as nghttp2_frame type. The CONTINUATION frame is omitted + * from here because the library deals with it internally. + */ +typedef union { + /** + * The frame header, which is convenient to inspect frame header. + */ + nghttp2_frame_hd hd; + /** + * The DATA frame. + */ + nghttp2_data data; + /** + * The HEADERS frame. + */ + nghttp2_headers headers; + /** + * The PRIORITY frame. + */ + nghttp2_priority priority; + /** + * The RST_STREAM frame. + */ + nghttp2_rst_stream rst_stream; + /** + * The SETTINGS frame. + */ + nghttp2_settings settings; + /** + * The PUSH_PROMISE frame. + */ + nghttp2_push_promise push_promise; + /** + * The PING frame. + */ + nghttp2_ping ping; + /** + * The GOAWAY frame. + */ + nghttp2_goaway goaway; + /** + * The WINDOW_UPDATE frame. + */ + nghttp2_window_update window_update; + /** + * The extension frame. + */ + nghttp2_extension ext; +} nghttp2_frame; + +/** + * @functypedef + * + * Callback function invoked when |session| wants to send data to the + * remote peer. The implementation of this function must send at most + * |length| bytes of data stored in |data|. The |flags| is currently + * not used and always 0. It must return the number of bytes sent if + * it succeeds. If it cannot send any single byte without blocking, + * it must return :enum:`NGHTTP2_ERR_WOULDBLOCK`. For other errors, + * it must return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. The + * |user_data| pointer is the third argument passed in to the call to + * `nghttp2_session_client_new()` or `nghttp2_session_server_new()`. + * + * This callback is required if the application uses + * `nghttp2_session_send()` to send data to the remote endpoint. If + * the application uses solely `nghttp2_session_mem_send()` instead, + * this callback function is unnecessary. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_send_callback()`. + * + * .. note:: + * + * The |length| may be very small. If that is the case, and + * application disables Nagle algorithm (``TCP_NODELAY``), then just + * writing |data| to the network stack leads to very small packet, + * and it is very inefficient. An application should be responsible + * to buffer up small chunks of data as necessary to avoid this + * situation. + */ +typedef ssize_t (*nghttp2_send_callback)(nghttp2_session *session, + const uint8_t *data, size_t length, + int flags, void *user_data); + +/** + * @functypedef + * + * Callback function invoked when :enum:`NGHTTP2_DATA_FLAG_NO_COPY` is + * used in :type:`nghttp2_data_source_read_callback` to send complete + * DATA frame. + * + * The |frame| is a DATA frame to send. The |framehd| is the + * serialized frame header (9 bytes). The |length| is the length of + * application data to send (this does not include padding). The + * |source| is the same pointer passed to + * :type:`nghttp2_data_source_read_callback`. + * + * The application first must send frame header |framehd| of length 9 + * bytes. If ``frame->data.padlen > 0``, send 1 byte of value + * ``frame->data.padlen - 1``. Then send exactly |length| bytes of + * application data. Finally, if ``frame->data.padlen > 1``, send + * ``frame->data.padlen - 1`` bytes of zero as padding. + * + * The application has to send complete DATA frame in this callback. + * If all data were written successfully, return 0. + * + * If it cannot send any data at all, just return + * :enum:`NGHTTP2_ERR_WOULDBLOCK`; the library will call this callback + * with the same parameters later (It is recommended to send complete + * DATA frame at once in this function to deal with error; if partial + * frame data has already sent, it is impossible to send another data + * in that state, and all we can do is tear down connection). When + * data is fully processed, but application wants to make + * `nghttp2_session_mem_send()` or `nghttp2_session_send()` return + * immediately without processing next frames, return + * :enum:`NGHTTP2_ERR_PAUSE`. If application decided to reset this + * stream, return :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`, then + * the library will send RST_STREAM with INTERNAL_ERROR as error code. + * The application can also return + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`, which will result in + * connection closure. Returning any other value is treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` is returned. + */ +typedef int (*nghttp2_send_data_callback)(nghttp2_session *session, + nghttp2_frame *frame, + const uint8_t *framehd, size_t length, + nghttp2_data_source *source, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when |session| wants to receive data from + * the remote peer. The implementation of this function must read at + * most |length| bytes of data and store it in |buf|. The |flags| is + * currently not used and always 0. It must return the number of + * bytes written in |buf| if it succeeds. If it cannot read any + * single byte without blocking, it must return + * :enum:`NGHTTP2_ERR_WOULDBLOCK`. If it gets EOF before it reads any + * single byte, it must return :enum:`NGHTTP2_ERR_EOF`. For other + * errors, it must return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * Returning 0 is treated as :enum:`NGHTTP2_ERR_WOULDBLOCK`. The + * |user_data| pointer is the third argument passed in to the call to + * `nghttp2_session_client_new()` or `nghttp2_session_server_new()`. + * + * This callback is required if the application uses + * `nghttp2_session_recv()` to receive data from the remote endpoint. + * If the application uses solely `nghttp2_session_mem_recv()` + * instead, this callback function is unnecessary. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_recv_callback()`. + */ +typedef ssize_t (*nghttp2_recv_callback)(nghttp2_session *session, uint8_t *buf, + size_t length, int flags, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked by `nghttp2_session_recv()` and + * `nghttp2_session_mem_recv()` when a frame is received. The + * |user_data| pointer is the third argument passed in to the call to + * `nghttp2_session_client_new()` or `nghttp2_session_server_new()`. + * + * If frame is HEADERS or PUSH_PROMISE, the ``nva`` and ``nvlen`` + * member of their data structure are always ``NULL`` and 0 + * respectively. The header name/value pairs are emitted via + * :type:`nghttp2_on_header_callback`. + * + * For HEADERS, PUSH_PROMISE and DATA frames, this callback may be + * called after stream is closed (see + * :type:`nghttp2_on_stream_close_callback`). The application should + * check that stream is still alive using its own stream management or + * :func:`nghttp2_session_get_stream_user_data()`. + * + * Only HEADERS and DATA frame can signal the end of incoming data. + * If ``frame->hd.flags & NGHTTP2_FLAG_END_STREAM`` is nonzero, the + * |frame| is the last frame from the remote peer in this stream. + * + * This callback won't be called for CONTINUATION frames. + * HEADERS/PUSH_PROMISE + CONTINUATIONs are treated as single frame. + * + * The implementation of this function must return 0 if it succeeds. + * If nonzero value is returned, it is treated as fatal error and + * `nghttp2_session_recv()` and `nghttp2_session_mem_recv()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_frame_recv_callback()`. + */ +typedef int (*nghttp2_on_frame_recv_callback)(nghttp2_session *session, + const nghttp2_frame *frame, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked by `nghttp2_session_recv()` and + * `nghttp2_session_mem_recv()` when an invalid non-DATA frame is + * received. The error is indicated by the |lib_error_code|, which is + * one of the values defined in :type:`nghttp2_error`. When this + * callback function is invoked, the library automatically submits + * either RST_STREAM or GOAWAY frame. The |user_data| pointer is the + * third argument passed in to the call to + * `nghttp2_session_client_new()` or `nghttp2_session_server_new()`. + * + * If frame is HEADERS or PUSH_PROMISE, the ``nva`` and ``nvlen`` + * member of their data structure are always ``NULL`` and 0 + * respectively. + * + * The implementation of this function must return 0 if it succeeds. + * If nonzero is returned, it is treated as fatal error and + * `nghttp2_session_recv()` and `nghttp2_session_mem_recv()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_invalid_frame_recv_callback()`. + */ +typedef int (*nghttp2_on_invalid_frame_recv_callback)( + nghttp2_session *session, const nghttp2_frame *frame, int lib_error_code, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when a chunk of data in DATA frame is + * received. The |stream_id| is the stream ID this DATA frame belongs + * to. The |flags| is the flags of DATA frame which this data chunk + * is contained. ``(flags & NGHTTP2_FLAG_END_STREAM) != 0`` does not + * necessarily mean this chunk of data is the last one in the stream. + * You should use :type:`nghttp2_on_frame_recv_callback` to know all + * data frames are received. The |user_data| pointer is the third + * argument passed in to the call to `nghttp2_session_client_new()` or + * `nghttp2_session_server_new()`. + * + * If the application uses `nghttp2_session_mem_recv()`, it can return + * :enum:`NGHTTP2_ERR_PAUSE` to make `nghttp2_session_mem_recv()` + * return without processing further input bytes. The memory by + * pointed by the |data| is retained until + * `nghttp2_session_mem_recv()` or `nghttp2_session_recv()` is called. + * The application must retain the input bytes which was used to + * produce the |data| parameter, because it may refer to the memory + * region included in the input bytes. + * + * The implementation of this function must return 0 if it succeeds. + * If nonzero is returned, it is treated as fatal error, and + * `nghttp2_session_recv()` and `nghttp2_session_mem_recv()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_data_chunk_recv_callback()`. + */ +typedef int (*nghttp2_on_data_chunk_recv_callback)(nghttp2_session *session, + uint8_t flags, + int32_t stream_id, + const uint8_t *data, + size_t len, void *user_data); + +/** + * @functypedef + * + * Callback function invoked just before the non-DATA frame |frame| is + * sent. The |user_data| pointer is the third argument passed in to + * the call to `nghttp2_session_client_new()` or + * `nghttp2_session_server_new()`. + * + * The implementation of this function must return 0 if it succeeds. + * It can also return :enum:`NGHTTP2_ERR_CANCEL` to cancel the + * transmission of the given frame. + * + * If there is a fatal error while executing this callback, the + * implementation should return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`, + * which makes `nghttp2_session_send()` and + * `nghttp2_session_mem_send()` functions immediately return + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * If the other value is returned, it is treated as if + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` is returned. But the + * implementation should not rely on this since the library may define + * new return value to extend its capability. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_before_frame_send_callback()`. + */ +typedef int (*nghttp2_before_frame_send_callback)(nghttp2_session *session, + const nghttp2_frame *frame, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked after the frame |frame| is sent. The + * |user_data| pointer is the third argument passed in to the call to + * `nghttp2_session_client_new()` or `nghttp2_session_server_new()`. + * + * The implementation of this function must return 0 if it succeeds. + * If nonzero is returned, it is treated as fatal error and + * `nghttp2_session_send()` and `nghttp2_session_mem_send()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_frame_send_callback()`. + */ +typedef int (*nghttp2_on_frame_send_callback)(nghttp2_session *session, + const nghttp2_frame *frame, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked after the non-DATA frame |frame| is not + * sent because of the error. The error is indicated by the + * |lib_error_code|, which is one of the values defined in + * :type:`nghttp2_error`. The |user_data| pointer is the third + * argument passed in to the call to `nghttp2_session_client_new()` or + * `nghttp2_session_server_new()`. + * + * The implementation of this function must return 0 if it succeeds. + * If nonzero is returned, it is treated as fatal error and + * `nghttp2_session_send()` and `nghttp2_session_mem_send()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * `nghttp2_session_get_stream_user_data()` can be used to get + * associated data. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_frame_not_send_callback()`. + */ +typedef int (*nghttp2_on_frame_not_send_callback)(nghttp2_session *session, + const nghttp2_frame *frame, + int lib_error_code, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when the stream |stream_id| is closed. + * The reason of closure is indicated by the |error_code|. The + * |error_code| is usually one of :enum:`nghttp2_error_code`, but that + * is not guaranteed. The stream_user_data, which was specified in + * `nghttp2_submit_request()` or `nghttp2_submit_headers()`, is still + * available in this function. The |user_data| pointer is the third + * argument passed in to the call to `nghttp2_session_client_new()` or + * `nghttp2_session_server_new()`. + * + * This function is also called for a stream in reserved state. + * + * The implementation of this function must return 0 if it succeeds. + * If nonzero is returned, it is treated as fatal error and + * `nghttp2_session_recv()`, `nghttp2_session_mem_recv()`, + * `nghttp2_session_send()`, and `nghttp2_session_mem_send()` + * functions immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_stream_close_callback()`. + */ +typedef int (*nghttp2_on_stream_close_callback)(nghttp2_session *session, + int32_t stream_id, + uint32_t error_code, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when the reception of header block in + * HEADERS or PUSH_PROMISE is started. Each header name/value pair + * will be emitted by :type:`nghttp2_on_header_callback`. + * + * The ``frame->hd.flags`` may not have + * :enum:`NGHTTP2_FLAG_END_HEADERS` flag set, which indicates that one + * or more CONTINUATION frames are involved. But the application does + * not need to care about that because the header name/value pairs are + * emitted transparently regardless of CONTINUATION frames. + * + * The server applications probably create an object to store + * information about new stream if ``frame->hd.type == + * NGHTTP2_HEADERS`` and ``frame->headers.cat == + * NGHTTP2_HCAT_REQUEST``. If |session| is configured as server side, + * ``frame->headers.cat`` is either ``NGHTTP2_HCAT_REQUEST`` + * containing request headers or ``NGHTTP2_HCAT_HEADERS`` containing + * trailer fields and never get PUSH_PROMISE in this callback. + * + * For the client applications, ``frame->hd.type`` is either + * ``NGHTTP2_HEADERS`` or ``NGHTTP2_PUSH_PROMISE``. In case of + * ``NGHTTP2_HEADERS``, ``frame->headers.cat == + * NGHTTP2_HCAT_RESPONSE`` means that it is the first response + * headers, but it may be non-final response which is indicated by 1xx + * status code. In this case, there may be zero or more HEADERS frame + * with ``frame->headers.cat == NGHTTP2_HCAT_HEADERS`` which has + * non-final response code and finally client gets exactly one HEADERS + * frame with ``frame->headers.cat == NGHTTP2_HCAT_HEADERS`` + * containing final response headers (non-1xx status code). The + * trailer fields also has ``frame->headers.cat == + * NGHTTP2_HCAT_HEADERS`` which does not contain any status code. + * + * Returning :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE` will close + * the stream (promised stream if frame is PUSH_PROMISE) by issuing + * RST_STREAM with :enum:`NGHTTP2_INTERNAL_ERROR`. In this case, + * :type:`nghttp2_on_header_callback` and + * :type:`nghttp2_on_frame_recv_callback` will not be invoked. If a + * different error code is desirable, use + * `nghttp2_submit_rst_stream()` with a desired error code and then + * return :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`. Again, use + * ``frame->push_promise.promised_stream_id`` as stream_id parameter + * in `nghttp2_submit_rst_stream()` if frame is PUSH_PROMISE. + * + * The implementation of this function must return 0 if it succeeds. + * It can return :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE` to + * reset the stream (promised stream if frame is PUSH_PROMISE). For + * critical errors, it must return + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. If the other value is + * returned, it is treated as if :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` + * is returned. If :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` is returned, + * `nghttp2_session_mem_recv()` function will immediately return + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_begin_headers_callback()`. + */ +typedef int (*nghttp2_on_begin_headers_callback)(nghttp2_session *session, + const nghttp2_frame *frame, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when a header name/value pair is received + * for the |frame|. The |name| of length |namelen| is header name. + * The |value| of length |valuelen| is header value. The |flags| is + * bitwise OR of one or more of :type:`nghttp2_nv_flag`. + * + * If :enum:`NGHTTP2_NV_FLAG_NO_INDEX` is set in |flags|, the receiver + * must not index this name/value pair when forwarding it to the next + * hop. More specifically, "Literal Header Field never Indexed" + * representation must be used in HPACK encoding. + * + * When this callback is invoked, ``frame->hd.type`` is either + * :enum:`NGHTTP2_HEADERS` or :enum:`NGHTTP2_PUSH_PROMISE`. After all + * header name/value pairs are processed with this callback, and no + * error has been detected, :type:`nghttp2_on_frame_recv_callback` + * will be invoked. If there is an error in decompression, + * :type:`nghttp2_on_frame_recv_callback` for the |frame| will not be + * invoked. + * + * Both |name| and |value| are guaranteed to be NULL-terminated. The + * |namelen| and |valuelen| do not include terminal NULL. If + * `nghttp2_option_set_no_http_messaging()` is used with nonzero + * value, NULL character may be included in |name| or |value| before + * terminating NULL. + * + * Please note that unless `nghttp2_option_set_no_http_messaging()` is + * used, nghttp2 library does perform validation against the |name| + * and the |value| using `nghttp2_check_header_name()` and + * `nghttp2_check_header_value()`. In addition to this, nghttp2 + * performs validation based on HTTP Messaging rule, which is briefly + * explained in :ref:`http-messaging` section. + * + * If the application uses `nghttp2_session_mem_recv()`, it can return + * :enum:`NGHTTP2_ERR_PAUSE` to make `nghttp2_session_mem_recv()` + * return without processing further input bytes. The memory pointed + * by |frame|, |name| and |value| parameters are retained until + * `nghttp2_session_mem_recv()` or `nghttp2_session_recv()` is called. + * The application must retain the input bytes which was used to + * produce these parameters, because it may refer to the memory region + * included in the input bytes. + * + * Returning :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE` will close + * the stream (promised stream if frame is PUSH_PROMISE) by issuing + * RST_STREAM with :enum:`NGHTTP2_INTERNAL_ERROR`. In this case, + * :type:`nghttp2_on_header_callback` and + * :type:`nghttp2_on_frame_recv_callback` will not be invoked. If a + * different error code is desirable, use + * `nghttp2_submit_rst_stream()` with a desired error code and then + * return :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`. Again, use + * ``frame->push_promise.promised_stream_id`` as stream_id parameter + * in `nghttp2_submit_rst_stream()` if frame is PUSH_PROMISE. + * + * The implementation of this function must return 0 if it succeeds. + * It may return :enum:`NGHTTP2_ERR_PAUSE` or + * :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`. For other critical + * failures, it must return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. If + * the other nonzero value is returned, it is treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. If + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` is returned, + * `nghttp2_session_recv()` and `nghttp2_session_mem_recv()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_header_callback()`. + * + * .. warning:: + * + * Application should properly limit the total buffer size to store + * incoming header fields. Without it, peer may send large number + * of header fields or large header fields to cause out of memory in + * local endpoint. Due to how HPACK works, peer can do this + * effectively without using much memory on their own. + */ +typedef int (*nghttp2_on_header_callback)(nghttp2_session *session, + const nghttp2_frame *frame, + const uint8_t *name, size_t namelen, + const uint8_t *value, size_t valuelen, + uint8_t flags, void *user_data); + +/** + * @functypedef + * + * Callback function invoked when a header name/value pair is received + * for the |frame|. The |name| is header name. The |value| is header + * value. The |flags| is bitwise OR of one or more of + * :type:`nghttp2_nv_flag`. + * + * This callback behaves like :type:`nghttp2_on_header_callback`, + * except that |name| and |value| are stored in reference counted + * buffer. If application wishes to keep these references without + * copying them, use `nghttp2_rcbuf_incref()` to increment their + * reference count. It is the application's responsibility to call + * `nghttp2_rcbuf_decref()` if they called `nghttp2_rcbuf_incref()` so + * as not to leak memory. If the |session| is created by + * `nghttp2_session_server_new3()` or `nghttp2_session_client_new3()`, + * the function to free memory is the one belongs to the mem + * parameter. As long as this free function alives, |name| and + * |value| can live after |session| was destroyed. + */ +typedef int (*nghttp2_on_header_callback2)(nghttp2_session *session, + const nghttp2_frame *frame, + nghttp2_rcbuf *name, + nghttp2_rcbuf *value, uint8_t flags, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when a invalid header name/value pair is + * received for the |frame|. + * + * The parameter and behaviour are similar to + * :type:`nghttp2_on_header_callback`. The difference is that this + * callback is only invoked when a invalid header name/value pair is + * received which is treated as stream error if this callback is not + * set. Only invalid regular header field are passed to this + * callback. In other words, invalid pseudo header field is not + * passed to this callback. Also header fields which includes upper + * cased latter are also treated as error without passing them to this + * callback. + * + * This callback is only considered if HTTP messaging validation is + * turned on (which is on by default, see + * `nghttp2_option_set_no_http_messaging()`). + * + * With this callback, application inspects the incoming invalid + * field, and it also can reset stream from this callback by returning + * :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`. By default, the + * error code is :enum:`NGHTTP2_PROTOCOL_ERROR`. To change the error + * code, call `nghttp2_submit_rst_stream()` with the error code of + * choice in addition to returning + * :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`. + * + * If 0 is returned, the header field is ignored, and the stream is + * not reset. + */ +typedef int (*nghttp2_on_invalid_header_callback)( + nghttp2_session *session, const nghttp2_frame *frame, const uint8_t *name, + size_t namelen, const uint8_t *value, size_t valuelen, uint8_t flags, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when a invalid header name/value pair is + * received for the |frame|. + * + * The parameter and behaviour are similar to + * :type:`nghttp2_on_header_callback2`. The difference is that this + * callback is only invoked when a invalid header name/value pair is + * received which is silently ignored if this callback is not set. + * Only invalid regular header field are passed to this callback. In + * other words, invalid pseudo header field is not passed to this + * callback. Also header fields which includes upper cased latter are + * also treated as error without passing them to this callback. + * + * This callback is only considered if HTTP messaging validation is + * turned on (which is on by default, see + * `nghttp2_option_set_no_http_messaging()`). + * + * With this callback, application inspects the incoming invalid + * field, and it also can reset stream from this callback by returning + * :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`. By default, the + * error code is :enum:`NGHTTP2_INTERNAL_ERROR`. To change the error + * code, call `nghttp2_submit_rst_stream()` with the error code of + * choice in addition to returning + * :enum:`NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE`. + */ +typedef int (*nghttp2_on_invalid_header_callback2)( + nghttp2_session *session, const nghttp2_frame *frame, nghttp2_rcbuf *name, + nghttp2_rcbuf *value, uint8_t flags, void *user_data); + +/** + * @functypedef + * + * Callback function invoked when the library asks application how + * many padding bytes are required for the transmission of the + * |frame|. The application must choose the total length of payload + * including padded bytes in range [frame->hd.length, max_payloadlen], + * inclusive. Choosing number not in this range will be treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. Returning + * ``frame->hd.length`` means no padding is added. Returning + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` will make + * `nghttp2_session_send()` and `nghttp2_session_mem_send()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_select_padding_callback()`. + */ +typedef ssize_t (*nghttp2_select_padding_callback)(nghttp2_session *session, + const nghttp2_frame *frame, + size_t max_payloadlen, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when library wants to get max length of + * data to send data to the remote peer. The implementation of this + * function should return a value in the following range. [1, + * min(|session_remote_window_size|, |stream_remote_window_size|, + * |remote_max_frame_size|)]. If a value greater than this range is + * returned than the max allow value will be used. Returning a value + * smaller than this range is treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. The |frame_type| is provided + * for future extensibility and identifies the type of frame (see + * :type:`nghttp2_frame_type`) for which to get the length for. + * Currently supported frame types are: :enum:`NGHTTP2_DATA`. + * + * This callback can be used to control the length in bytes for which + * :type:`nghttp2_data_source_read_callback` is allowed to send to the + * remote endpoint. This callback is optional. Returning + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` will signal the entire session + * failure. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_data_source_read_length_callback()`. + */ +typedef ssize_t (*nghttp2_data_source_read_length_callback)( + nghttp2_session *session, uint8_t frame_type, int32_t stream_id, + int32_t session_remote_window_size, int32_t stream_remote_window_size, + uint32_t remote_max_frame_size, void *user_data); + +/** + * @functypedef + * + * Callback function invoked when a frame header is received. The + * |hd| points to received frame header. + * + * Unlike :type:`nghttp2_on_frame_recv_callback`, this callback will + * also be called when frame header of CONTINUATION frame is received. + * + * If both :type:`nghttp2_on_begin_frame_callback` and + * :type:`nghttp2_on_begin_headers_callback` are set and HEADERS or + * PUSH_PROMISE is received, :type:`nghttp2_on_begin_frame_callback` + * will be called first. + * + * The implementation of this function must return 0 if it succeeds. + * If nonzero value is returned, it is treated as fatal error and + * `nghttp2_session_recv()` and `nghttp2_session_mem_recv()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + * + * To set this callback to :type:`nghttp2_session_callbacks`, use + * `nghttp2_session_callbacks_set_on_begin_frame_callback()`. + */ +typedef int (*nghttp2_on_begin_frame_callback)(nghttp2_session *session, + const nghttp2_frame_hd *hd, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when chunk of extension frame payload is + * received. The |hd| points to frame header. The received + * chunk is |data| of length |len|. + * + * The implementation of this function must return 0 if it succeeds. + * + * To abort processing this extension frame, return + * :enum:`NGHTTP2_ERR_CANCEL`. + * + * If fatal error occurred, application should return + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. In this case, + * `nghttp2_session_recv()` and `nghttp2_session_mem_recv()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. If the + * other values are returned, currently they are treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + */ +typedef int (*nghttp2_on_extension_chunk_recv_callback)( + nghttp2_session *session, const nghttp2_frame_hd *hd, const uint8_t *data, + size_t len, void *user_data); + +/** + * @functypedef + * + * Callback function invoked when library asks the application to + * unpack extension payload from its wire format. The extension + * payload has been passed to the application using + * :type:`nghttp2_on_extension_chunk_recv_callback`. The frame header + * is already unpacked by the library and provided as |hd|. + * + * To receive extension frames, the application must tell desired + * extension frame type to the library using + * `nghttp2_option_set_user_recv_extension_type()`. + * + * The implementation of this function may store the pointer to the + * created object as a result of unpacking in |*payload|, and returns + * 0. The pointer stored in |*payload| is opaque to the library, and + * the library does not own its pointer. |*payload| is initialized as + * ``NULL``. The |*payload| is available as ``frame->ext.payload`` in + * :type:`nghttp2_on_frame_recv_callback`. Therefore if application + * can free that memory inside :type:`nghttp2_on_frame_recv_callback` + * callback. Of course, application has a liberty not ot use + * |*payload|, and do its own mechanism to process extension frames. + * + * To abort processing this extension frame, return + * :enum:`NGHTTP2_ERR_CANCEL`. + * + * If fatal error occurred, application should return + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. In this case, + * `nghttp2_session_recv()` and `nghttp2_session_mem_recv()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. If the + * other values are returned, currently they are treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + */ +typedef int (*nghttp2_unpack_extension_callback)(nghttp2_session *session, + void **payload, + const nghttp2_frame_hd *hd, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when library asks the application to pack + * extension payload in its wire format. The frame header will be + * packed by library. Application must pack payload only. + * ``frame->ext.payload`` is the object passed to + * `nghttp2_submit_extension()` as payload parameter. Application + * must pack extension payload to the |buf| of its capacity |len| + * bytes. The |len| is at least 16KiB. + * + * The implementation of this function should return the number of + * bytes written into |buf| when it succeeds. + * + * To abort processing this extension frame, return + * :enum:`NGHTTP2_ERR_CANCEL`, and + * :type:`nghttp2_on_frame_not_send_callback` will be invoked. + * + * If fatal error occurred, application should return + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. In this case, + * `nghttp2_session_send()` and `nghttp2_session_mem_send()` functions + * immediately return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. If the + * other values are returned, currently they are treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. If the return value is + * strictly larger than |len|, it is treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. + */ +typedef ssize_t (*nghttp2_pack_extension_callback)(nghttp2_session *session, + uint8_t *buf, size_t len, + const nghttp2_frame *frame, + void *user_data); + +/** + * @functypedef + * + * Callback function invoked when library provides the error message + * intended for human consumption. This callback is solely for + * debugging purpose. The |msg| is typically NULL-terminated string + * of length |len|. |len| does not include the sentinel NULL + * character. + * + * The format of error message may change between nghttp2 library + * versions. The application should not depend on the particular + * format. + * + * Normally, application should return 0 from this callback. If fatal + * error occurred while doing something in this callback, application + * should return :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. In this case, + * library will return immediately with return value + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`. Currently, if nonzero value + * is returned from this callback, they are treated as + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE`, but application should not + * rely on this details. + */ +typedef int (*nghttp2_error_callback)(nghttp2_session *session, const char *msg, + size_t len, void *user_data); + +struct nghttp2_session_callbacks; + +/** + * @struct + * + * Callback functions for :type:`nghttp2_session`. The details of + * this structure are intentionally hidden from the public API. + */ +typedef struct nghttp2_session_callbacks nghttp2_session_callbacks; + +/** + * @function + * + * Initializes |*callbacks_ptr| with NULL values. + * + * The initialized object can be used when initializing multiple + * :type:`nghttp2_session` objects. + * + * When the application finished using this object, it can use + * `nghttp2_session_callbacks_del()` to free its memory. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int +nghttp2_session_callbacks_new(nghttp2_session_callbacks **callbacks_ptr); + +/** + * @function + * + * Frees any resources allocated for |callbacks|. If |callbacks| is + * ``NULL``, this function does nothing. + */ +NGHTTP2_EXTERN void +nghttp2_session_callbacks_del(nghttp2_session_callbacks *callbacks); + +/** + * @function + * + * Sets callback function invoked when a session wants to send data to + * the remote peer. This callback is not necessary if the application + * uses solely `nghttp2_session_mem_send()` to serialize data to + * transmit. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_send_callback( + nghttp2_session_callbacks *cbs, nghttp2_send_callback send_callback); + +/** + * @function + * + * Sets callback function invoked when the a session wants to receive + * data from the remote peer. This callback is not necessary if the + * application uses solely `nghttp2_session_mem_recv()` to process + * received data. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_recv_callback( + nghttp2_session_callbacks *cbs, nghttp2_recv_callback recv_callback); + +/** + * @function + * + * Sets callback function invoked by `nghttp2_session_recv()` and + * `nghttp2_session_mem_recv()` when a frame is received. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_frame_recv_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_frame_recv_callback on_frame_recv_callback); + +/** + * @function + * + * Sets callback function invoked by `nghttp2_session_recv()` and + * `nghttp2_session_mem_recv()` when an invalid non-DATA frame is + * received. + */ +NGHTTP2_EXTERN void +nghttp2_session_callbacks_set_on_invalid_frame_recv_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_invalid_frame_recv_callback on_invalid_frame_recv_callback); + +/** + * @function + * + * Sets callback function invoked when a chunk of data in DATA frame + * is received. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_data_chunk_recv_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_data_chunk_recv_callback on_data_chunk_recv_callback); + +/** + * @function + * + * Sets callback function invoked before a non-DATA frame is sent. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_before_frame_send_callback( + nghttp2_session_callbacks *cbs, + nghttp2_before_frame_send_callback before_frame_send_callback); + +/** + * @function + * + * Sets callback function invoked after a frame is sent. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_frame_send_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_frame_send_callback on_frame_send_callback); + +/** + * @function + * + * Sets callback function invoked when a non-DATA frame is not sent + * because of an error. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_frame_not_send_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_frame_not_send_callback on_frame_not_send_callback); + +/** + * @function + * + * Sets callback function invoked when the stream is closed. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_stream_close_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_stream_close_callback on_stream_close_callback); + +/** + * @function + * + * Sets callback function invoked when the reception of header block + * in HEADERS or PUSH_PROMISE is started. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_begin_headers_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_begin_headers_callback on_begin_headers_callback); + +/** + * @function + * + * Sets callback function invoked when a header name/value pair is + * received. If both + * `nghttp2_session_callbacks_set_on_header_callback()` and + * `nghttp2_session_callbacks_set_on_header_callback2()` are used to + * set callbacks, the latter has the precedence. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_header_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_header_callback on_header_callback); + +/** + * @function + * + * Sets callback function invoked when a header name/value pair is + * received. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_header_callback2( + nghttp2_session_callbacks *cbs, + nghttp2_on_header_callback2 on_header_callback2); + +/** + * @function + * + * Sets callback function invoked when a invalid header name/value + * pair is received. If both + * `nghttp2_session_callbacks_set_on_invalid_header_callback()` and + * `nghttp2_session_callbacks_set_on_invalid_header_callback2()` are + * used to set callbacks, the latter takes the precedence. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_invalid_header_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_invalid_header_callback on_invalid_header_callback); + +/** + * @function + * + * Sets callback function invoked when a invalid header name/value + * pair is received. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_invalid_header_callback2( + nghttp2_session_callbacks *cbs, + nghttp2_on_invalid_header_callback2 on_invalid_header_callback2); + +/** + * @function + * + * Sets callback function invoked when the library asks application + * how many padding bytes are required for the transmission of the + * given frame. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_select_padding_callback( + nghttp2_session_callbacks *cbs, + nghttp2_select_padding_callback select_padding_callback); + +/** + * @function + * + * Sets callback function determine the length allowed in + * :type:`nghttp2_data_source_read_callback`. + */ +NGHTTP2_EXTERN void +nghttp2_session_callbacks_set_data_source_read_length_callback( + nghttp2_session_callbacks *cbs, + nghttp2_data_source_read_length_callback data_source_read_length_callback); + +/** + * @function + * + * Sets callback function invoked when a frame header is received. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_on_begin_frame_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_begin_frame_callback on_begin_frame_callback); + +/** + * @function + * + * Sets callback function invoked when + * :enum:`NGHTTP2_DATA_FLAG_NO_COPY` is used in + * :type:`nghttp2_data_source_read_callback` to avoid data copy. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_send_data_callback( + nghttp2_session_callbacks *cbs, + nghttp2_send_data_callback send_data_callback); + +/** + * @function + * + * Sets callback function invoked when the library asks the + * application to pack extension frame payload in wire format. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_pack_extension_callback( + nghttp2_session_callbacks *cbs, + nghttp2_pack_extension_callback pack_extension_callback); + +/** + * @function + * + * Sets callback function invoked when the library asks the + * application to unpack extension frame payload from wire format. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_unpack_extension_callback( + nghttp2_session_callbacks *cbs, + nghttp2_unpack_extension_callback unpack_extension_callback); + +/** + * @function + * + * Sets callback function invoked when chunk of extension frame + * payload is received. + */ +NGHTTP2_EXTERN void +nghttp2_session_callbacks_set_on_extension_chunk_recv_callback( + nghttp2_session_callbacks *cbs, + nghttp2_on_extension_chunk_recv_callback on_extension_chunk_recv_callback); + +/** + * @function + * + * Sets callback function invoked when library tells error message to + * the application. + */ +NGHTTP2_EXTERN void nghttp2_session_callbacks_set_error_callback( + nghttp2_session_callbacks *cbs, nghttp2_error_callback error_callback); + +/** + * @functypedef + * + * Custom memory allocator to replace malloc(). The |mem_user_data| + * is the mem_user_data member of :type:`nghttp2_mem` structure. + */ +typedef void *(*nghttp2_malloc)(size_t size, void *mem_user_data); + +/** + * @functypedef + * + * Custom memory allocator to replace free(). The |mem_user_data| is + * the mem_user_data member of :type:`nghttp2_mem` structure. + */ +typedef void (*nghttp2_free)(void *ptr, void *mem_user_data); + +/** + * @functypedef + * + * Custom memory allocator to replace calloc(). The |mem_user_data| + * is the mem_user_data member of :type:`nghttp2_mem` structure. + */ +typedef void *(*nghttp2_calloc)(size_t nmemb, size_t size, void *mem_user_data); + +/** + * @functypedef + * + * Custom memory allocator to replace realloc(). The |mem_user_data| + * is the mem_user_data member of :type:`nghttp2_mem` structure. + */ +typedef void *(*nghttp2_realloc)(void *ptr, size_t size, void *mem_user_data); + +/** + * @struct + * + * Custom memory allocator functions and user defined pointer. The + * |mem_user_data| member is passed to each allocator function. This + * can be used, for example, to achieve per-session memory pool. + * + * In the following example code, ``my_malloc``, ``my_free``, + * ``my_calloc`` and ``my_realloc`` are the replacement of the + * standard allocators ``malloc``, ``free``, ``calloc`` and + * ``realloc`` respectively:: + * + * void *my_malloc_cb(size_t size, void *mem_user_data) { + * return my_malloc(size); + * } + * + * void my_free_cb(void *ptr, void *mem_user_data) { my_free(ptr); } + * + * void *my_calloc_cb(size_t nmemb, size_t size, void *mem_user_data) { + * return my_calloc(nmemb, size); + * } + * + * void *my_realloc_cb(void *ptr, size_t size, void *mem_user_data) { + * return my_realloc(ptr, size); + * } + * + * void session_new() { + * nghttp2_session *session; + * nghttp2_session_callbacks *callbacks; + * nghttp2_mem mem = {NULL, my_malloc_cb, my_free_cb, my_calloc_cb, + * my_realloc_cb}; + * + * ... + * + * nghttp2_session_client_new3(&session, callbacks, NULL, NULL, &mem); + * + * ... + * } + */ +typedef struct { + /** + * An arbitrary user supplied data. This is passed to each + * allocator function. + */ + void *mem_user_data; + /** + * Custom allocator function to replace malloc(). + */ + nghttp2_malloc malloc; + /** + * Custom allocator function to replace free(). + */ + nghttp2_free free; + /** + * Custom allocator function to replace calloc(). + */ + nghttp2_calloc calloc; + /** + * Custom allocator function to replace realloc(). + */ + nghttp2_realloc realloc; +} nghttp2_mem; + +struct nghttp2_option; + +/** + * @struct + * + * Configuration options for :type:`nghttp2_session`. The details of + * this structure are intentionally hidden from the public API. + */ +typedef struct nghttp2_option nghttp2_option; + +/** + * @function + * + * Initializes |*option_ptr| with default values. + * + * When the application finished using this object, it can use + * `nghttp2_option_del()` to free its memory. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_option_new(nghttp2_option **option_ptr); + +/** + * @function + * + * Frees any resources allocated for |option|. If |option| is + * ``NULL``, this function does nothing. + */ +NGHTTP2_EXTERN void nghttp2_option_del(nghttp2_option *option); + +/** + * @function + * + * This option prevents the library from sending WINDOW_UPDATE for a + * connection automatically. If this option is set to nonzero, the + * library won't send WINDOW_UPDATE for DATA until application calls + * `nghttp2_session_consume()` to indicate the consumed amount of + * data. Don't use `nghttp2_submit_window_update()` for this purpose. + * By default, this option is set to zero. + */ +NGHTTP2_EXTERN void +nghttp2_option_set_no_auto_window_update(nghttp2_option *option, int val); + +/** + * @function + * + * This option sets the SETTINGS_MAX_CONCURRENT_STREAMS value of + * remote endpoint as if it is received in SETTINGS frame. Without + * specifying this option, before the local endpoint receives + * SETTINGS_MAX_CONCURRENT_STREAMS in SETTINGS frame from remote + * endpoint, SETTINGS_MAX_CONCURRENT_STREAMS is unlimited. This may + * cause problem if local endpoint submits lots of requests initially + * and sending them at once to the remote peer may lead to the + * rejection of some requests. Specifying this option to the sensible + * value, say 100, may avoid this kind of issue. This value will be + * overwritten if the local endpoint receives + * SETTINGS_MAX_CONCURRENT_STREAMS from the remote endpoint. + */ +NGHTTP2_EXTERN void +nghttp2_option_set_peer_max_concurrent_streams(nghttp2_option *option, + uint32_t val); + +/** + * @function + * + * By default, nghttp2 library, if configured as server, requires + * first 24 bytes of client magic byte string (MAGIC). In most cases, + * this will simplify the implementation of server. But sometimes + * server may want to detect the application protocol based on first + * few bytes on clear text communication. + * + * If this option is used with nonzero |val|, nghttp2 library does not + * handle MAGIC. It still checks following SETTINGS frame. This + * means that applications should deal with MAGIC by themselves. + * + * If this option is not used or used with zero value, if MAGIC does + * not match :macro:`NGHTTP2_CLIENT_MAGIC`, `nghttp2_session_recv()` + * and `nghttp2_session_mem_recv()` will return error + * :enum:`NGHTTP2_ERR_BAD_CLIENT_MAGIC`, which is fatal error. + */ +NGHTTP2_EXTERN void +nghttp2_option_set_no_recv_client_magic(nghttp2_option *option, int val); + +/** + * @function + * + * By default, nghttp2 library enforces subset of HTTP Messaging rules + * described in `HTTP/2 specification, section 8 + * `_. See + * :ref:`http-messaging` section for details. For those applications + * who use nghttp2 library as non-HTTP use, give nonzero to |val| to + * disable this enforcement. Please note that disabling this feature + * does not change the fundamental client and server model of HTTP. + * That is, even if the validation is disabled, only client can send + * requests. + */ +NGHTTP2_EXTERN void nghttp2_option_set_no_http_messaging(nghttp2_option *option, + int val); + +/** + * @function + * + * RFC 7540 does not enforce any limit on the number of incoming + * reserved streams (in RFC 7540 terms, streams in reserved (remote) + * state). This only affects client side, since only server can push + * streams. Malicious server can push arbitrary number of streams, + * and make client's memory exhausted. This option can set the + * maximum number of such incoming streams to avoid possible memory + * exhaustion. If this option is set, and pushed streams are + * automatically closed on reception, without calling user provided + * callback, if they exceed the given limit. The default value is + * 200. If session is configured as server side, this option has no + * effect. Server can control the number of streams to push. + */ +NGHTTP2_EXTERN void +nghttp2_option_set_max_reserved_remote_streams(nghttp2_option *option, + uint32_t val); + +/** + * @function + * + * Sets extension frame type the application is willing to handle with + * user defined callbacks (see + * :type:`nghttp2_on_extension_chunk_recv_callback` and + * :type:`nghttp2_unpack_extension_callback`). The |type| is + * extension frame type, and must be strictly greater than 0x9. + * Otherwise, this function does nothing. The application can call + * this function multiple times to set more than one frame type to + * receive. The application does not have to call this function if it + * just sends extension frames. + */ +NGHTTP2_EXTERN void +nghttp2_option_set_user_recv_extension_type(nghttp2_option *option, + uint8_t type); + +/** + * @function + * + * Sets extension frame type the application is willing to receive + * using builtin handler. The |type| is the extension frame type to + * receive, and must be strictly greater than 0x9. Otherwise, this + * function does nothing. The application can call this function + * multiple times to set more than one frame type to receive. The + * application does not have to call this function if it just sends + * extension frames. + * + * If same frame type is passed to both + * `nghttp2_option_set_builtin_recv_extension_type()` and + * `nghttp2_option_set_user_recv_extension_type()`, the latter takes + * precedence. + */ +NGHTTP2_EXTERN void +nghttp2_option_set_builtin_recv_extension_type(nghttp2_option *option, + uint8_t type); + +/** + * @function + * + * This option prevents the library from sending PING frame with ACK + * flag set automatically when PING frame without ACK flag set is + * received. If this option is set to nonzero, the library won't send + * PING frame with ACK flag set in the response for incoming PING + * frame. The application can send PING frame with ACK flag set using + * `nghttp2_submit_ping()` with :enum:`NGHTTP2_FLAG_ACK` as flags + * parameter. + */ +NGHTTP2_EXTERN void nghttp2_option_set_no_auto_ping_ack(nghttp2_option *option, + int val); + +/** + * @function + * + * This option sets the maximum length of header block (a set of + * header fields per one HEADERS frame) to send. The length of a + * given set of header fields is calculated using + * `nghttp2_hd_deflate_bound()`. The default value is 64KiB. If + * application attempts to send header fields larger than this limit, + * the transmission of the frame fails with error code + * :enum:`NGHTTP2_ERR_FRAME_SIZE_ERROR`. + */ +NGHTTP2_EXTERN void +nghttp2_option_set_max_send_header_block_length(nghttp2_option *option, + size_t val); + +/** + * @function + * + * This option sets the maximum dynamic table size for deflating + * header fields. The default value is 4KiB. In HTTP/2, receiver of + * deflated header block can specify maximum dynamic table size. The + * actual maximum size is the minimum of the size receiver specified + * and this option value. + */ +NGHTTP2_EXTERN void +nghttp2_option_set_max_deflate_dynamic_table_size(nghttp2_option *option, + size_t val); + +/** + * @function + * + * This option prevents the library from retaining closed streams to + * maintain the priority tree. If this option is set to nonzero, + * applications can discard closed stream completely to save memory. + */ +NGHTTP2_EXTERN void nghttp2_option_set_no_closed_streams(nghttp2_option *option, + int val); + +/** + * @function + * + * Initializes |*session_ptr| for client use. The all members of + * |callbacks| are copied to |*session_ptr|. Therefore |*session_ptr| + * does not store |callbacks|. The |user_data| is an arbitrary user + * supplied data, which will be passed to the callback functions. + * + * The :type:`nghttp2_send_callback` must be specified. If the + * application code uses `nghttp2_session_recv()`, the + * :type:`nghttp2_recv_callback` must be specified. The other members + * of |callbacks| can be ``NULL``. + * + * If this function fails, |*session_ptr| is left untouched. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int +nghttp2_session_client_new(nghttp2_session **session_ptr, + const nghttp2_session_callbacks *callbacks, + void *user_data); + +/** + * @function + * + * Initializes |*session_ptr| for server use. The all members of + * |callbacks| are copied to |*session_ptr|. Therefore |*session_ptr| + * does not store |callbacks|. The |user_data| is an arbitrary user + * supplied data, which will be passed to the callback functions. + * + * The :type:`nghttp2_send_callback` must be specified. If the + * application code uses `nghttp2_session_recv()`, the + * :type:`nghttp2_recv_callback` must be specified. The other members + * of |callbacks| can be ``NULL``. + * + * If this function fails, |*session_ptr| is left untouched. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int +nghttp2_session_server_new(nghttp2_session **session_ptr, + const nghttp2_session_callbacks *callbacks, + void *user_data); + +/** + * @function + * + * Like `nghttp2_session_client_new()`, but with additional options + * specified in the |option|. + * + * The |option| can be ``NULL`` and the call is equivalent to + * `nghttp2_session_client_new()`. + * + * This function does not take ownership |option|. The application is + * responsible for freeing |option| if it finishes using the object. + * + * The library code does not refer to |option| after this function + * returns. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int +nghttp2_session_client_new2(nghttp2_session **session_ptr, + const nghttp2_session_callbacks *callbacks, + void *user_data, const nghttp2_option *option); + +/** + * @function + * + * Like `nghttp2_session_server_new()`, but with additional options + * specified in the |option|. + * + * The |option| can be ``NULL`` and the call is equivalent to + * `nghttp2_session_server_new()`. + * + * This function does not take ownership |option|. The application is + * responsible for freeing |option| if it finishes using the object. + * + * The library code does not refer to |option| after this function + * returns. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int +nghttp2_session_server_new2(nghttp2_session **session_ptr, + const nghttp2_session_callbacks *callbacks, + void *user_data, const nghttp2_option *option); + +/** + * @function + * + * Like `nghttp2_session_client_new2()`, but with additional custom + * memory allocator specified in the |mem|. + * + * The |mem| can be ``NULL`` and the call is equivalent to + * `nghttp2_session_client_new2()`. + * + * This function does not take ownership |mem|. The application is + * responsible for freeing |mem|. + * + * The library code does not refer to |mem| pointer after this + * function returns, so the application can safely free it. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_session_client_new3( + nghttp2_session **session_ptr, const nghttp2_session_callbacks *callbacks, + void *user_data, const nghttp2_option *option, nghttp2_mem *mem); + +/** + * @function + * + * Like `nghttp2_session_server_new2()`, but with additional custom + * memory allocator specified in the |mem|. + * + * The |mem| can be ``NULL`` and the call is equivalent to + * `nghttp2_session_server_new2()`. + * + * This function does not take ownership |mem|. The application is + * responsible for freeing |mem|. + * + * The library code does not refer to |mem| pointer after this + * function returns, so the application can safely free it. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_session_server_new3( + nghttp2_session **session_ptr, const nghttp2_session_callbacks *callbacks, + void *user_data, const nghttp2_option *option, nghttp2_mem *mem); + +/** + * @function + * + * Frees any resources allocated for |session|. If |session| is + * ``NULL``, this function does nothing. + */ +NGHTTP2_EXTERN void nghttp2_session_del(nghttp2_session *session); + +/** + * @function + * + * Sends pending frames to the remote peer. + * + * This function retrieves the highest prioritized frame from the + * outbound queue and sends it to the remote peer. It does this as + * many as possible until the user callback + * :type:`nghttp2_send_callback` returns + * :enum:`NGHTTP2_ERR_WOULDBLOCK` or the outbound queue becomes empty. + * This function calls several callback functions which are passed + * when initializing the |session|. Here is the simple time chart + * which tells when each callback is invoked: + * + * 1. Get the next frame to send from outbound queue. + * + * 2. Prepare transmission of the frame. + * + * 3. If the control frame cannot be sent because some preconditions + * are not met (e.g., request HEADERS cannot be sent after GOAWAY), + * :type:`nghttp2_on_frame_not_send_callback` is invoked. Abort + * the following steps. + * + * 4. If the frame is HEADERS, PUSH_PROMISE or DATA, + * :type:`nghttp2_select_padding_callback` is invoked. + * + * 5. If the frame is request HEADERS, the stream is opened here. + * + * 6. :type:`nghttp2_before_frame_send_callback` is invoked. + * + * 7. If :enum:`NGHTTP2_ERR_CANCEL` is returned from + * :type:`nghttp2_before_frame_send_callback`, the current frame + * transmission is canceled, and + * :type:`nghttp2_on_frame_not_send_callback` is invoked. Abort + * the following steps. + * + * 8. :type:`nghttp2_send_callback` is invoked one or more times to + * send the frame. + * + * 9. :type:`nghttp2_on_frame_send_callback` is invoked. + * + * 10. If the transmission of the frame triggers closure of the + * stream, the stream is closed and + * :type:`nghttp2_on_stream_close_callback` is invoked. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` + * The callback function failed. + */ +NGHTTP2_EXTERN int nghttp2_session_send(nghttp2_session *session); + +/** + * @function + * + * Returns the serialized data to send. + * + * This function behaves like `nghttp2_session_send()` except that it + * does not use :type:`nghttp2_send_callback` to transmit data. + * Instead, it assigns the pointer to the serialized data to the + * |*data_ptr| and returns its length. The other callbacks are called + * in the same way as they are in `nghttp2_session_send()`. + * + * If no data is available to send, this function returns 0. + * + * This function may not return all serialized data in one invocation. + * To get all data, call this function repeatedly until it returns 0 + * or one of negative error codes. + * + * The assigned |*data_ptr| is valid until the next call of + * `nghttp2_session_mem_send()` or `nghttp2_session_send()`. + * + * The caller must send all data before sending the next chunk of + * data. + * + * This function returns the length of the data pointed by the + * |*data_ptr| if it succeeds, or one of the following negative error + * codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * + * .. note:: + * + * This function may produce very small byte string. If that is the + * case, and application disables Nagle algorithm (``TCP_NODELAY``), + * then writing this small chunk leads to very small packet, and it + * is very inefficient. An application should be responsible to + * buffer up small chunks of data as necessary to avoid this + * situation. + */ +NGHTTP2_EXTERN ssize_t nghttp2_session_mem_send(nghttp2_session *session, + const uint8_t **data_ptr); + +/** + * @function + * + * Receives frames from the remote peer. + * + * This function receives as many frames as possible until the user + * callback :type:`nghttp2_recv_callback` returns + * :enum:`NGHTTP2_ERR_WOULDBLOCK`. This function calls several + * callback functions which are passed when initializing the + * |session|. Here is the simple time chart which tells when each + * callback is invoked: + * + * 1. :type:`nghttp2_recv_callback` is invoked one or more times to + * receive frame header. + * + * 2. When frame header is received, + * :type:`nghttp2_on_begin_frame_callback` is invoked. + * + * 3. If the frame is DATA frame: + * + * 1. :type:`nghttp2_recv_callback` is invoked to receive DATA + * payload. For each chunk of data, + * :type:`nghttp2_on_data_chunk_recv_callback` is invoked. + * + * 2. If one DATA frame is completely received, + * :type:`nghttp2_on_frame_recv_callback` is invoked. If the + * reception of the frame triggers the closure of the stream, + * :type:`nghttp2_on_stream_close_callback` is invoked. + * + * 4. If the frame is the control frame: + * + * 1. :type:`nghttp2_recv_callback` is invoked one or more times to + * receive whole frame. + * + * 2. If the received frame is valid, then following actions are + * taken. If the frame is either HEADERS or PUSH_PROMISE, + * :type:`nghttp2_on_begin_headers_callback` is invoked. Then + * :type:`nghttp2_on_header_callback` is invoked for each header + * name/value pair. For invalid header field, + * :type:`nghttp2_on_invalid_header_callback` is called. After + * all name/value pairs are emitted successfully, + * :type:`nghttp2_on_frame_recv_callback` is invoked. For other + * frames, :type:`nghttp2_on_frame_recv_callback` is invoked. + * If the reception of the frame triggers the closure of the + * stream, :type:`nghttp2_on_stream_close_callback` is invoked. + * + * 3. If the received frame is unpacked but is interpreted as + * invalid, :type:`nghttp2_on_invalid_frame_recv_callback` is + * invoked. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_EOF` + * The remote peer did shutdown on the connection. + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` + * The callback function failed. + * :enum:`NGHTTP2_ERR_BAD_CLIENT_MAGIC` + * Invalid client magic was detected. This error only returns + * when |session| was configured as server and + * `nghttp2_option_set_no_recv_client_magic()` is not used with + * nonzero value. + * :enum:`NGHTTP2_ERR_FLOODED` + * Flooding was detected in this HTTP/2 session, and it must be + * closed. This is most likely caused by misbehaviour of peer. + */ +NGHTTP2_EXTERN int nghttp2_session_recv(nghttp2_session *session); + +/** + * @function + * + * Processes data |in| as an input from the remote endpoint. The + * |inlen| indicates the number of bytes in the |in|. + * + * This function behaves like `nghttp2_session_recv()` except that it + * does not use :type:`nghttp2_recv_callback` to receive data; the + * |in| is the only data for the invocation of this function. If all + * bytes are processed, this function returns. The other callbacks + * are called in the same way as they are in `nghttp2_session_recv()`. + * + * In the current implementation, this function always tries to + * processes all input data unless either an error occurs or + * :enum:`NGHTTP2_ERR_PAUSE` is returned from + * :type:`nghttp2_on_header_callback` or + * :type:`nghttp2_on_data_chunk_recv_callback`. If + * :enum:`NGHTTP2_ERR_PAUSE` is used, the return value includes the + * number of bytes which was used to produce the data or frame for the + * callback. + * + * This function returns the number of processed bytes, or one of the + * following negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_CALLBACK_FAILURE` + * The callback function failed. + * :enum:`NGHTTP2_ERR_BAD_CLIENT_MAGIC` + * Invalid client magic was detected. This error only returns + * when |session| was configured as server and + * `nghttp2_option_set_no_recv_client_magic()` is not used with + * nonzero value. + * :enum:`NGHTTP2_ERR_FLOODED` + * Flooding was detected in this HTTP/2 session, and it must be + * closed. This is most likely caused by misbehaviour of peer. + */ +NGHTTP2_EXTERN ssize_t nghttp2_session_mem_recv(nghttp2_session *session, + const uint8_t *in, + size_t inlen); + +/** + * @function + * + * Puts back previously deferred DATA frame in the stream |stream_id| + * to the outbound queue. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The stream does not exist; or no deferred data exist. + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_session_resume_data(nghttp2_session *session, + int32_t stream_id); + +/** + * @function + * + * Returns nonzero value if |session| wants to receive data from the + * remote peer. + * + * If both `nghttp2_session_want_read()` and + * `nghttp2_session_want_write()` return 0, the application should + * drop the connection. + */ +NGHTTP2_EXTERN int nghttp2_session_want_read(nghttp2_session *session); + +/** + * @function + * + * Returns nonzero value if |session| wants to send data to the remote + * peer. + * + * If both `nghttp2_session_want_read()` and + * `nghttp2_session_want_write()` return 0, the application should + * drop the connection. + */ +NGHTTP2_EXTERN int nghttp2_session_want_write(nghttp2_session *session); + +/** + * @function + * + * Returns stream_user_data for the stream |stream_id|. The + * stream_user_data is provided by `nghttp2_submit_request()`, + * `nghttp2_submit_headers()` or + * `nghttp2_session_set_stream_user_data()`. Unless it is set using + * `nghttp2_session_set_stream_user_data()`, if the stream is + * initiated by the remote endpoint, stream_user_data is always + * ``NULL``. If the stream does not exist, this function returns + * ``NULL``. + */ +NGHTTP2_EXTERN void * +nghttp2_session_get_stream_user_data(nghttp2_session *session, + int32_t stream_id); + +/** + * @function + * + * Sets the |stream_user_data| to the stream denoted by the + * |stream_id|. If a stream user data is already set to the stream, + * it is replaced with the |stream_user_data|. It is valid to specify + * ``NULL`` in the |stream_user_data|, which nullifies the associated + * data pointer. + * + * It is valid to set the |stream_user_data| to the stream reserved by + * PUSH_PROMISE frame. + * + * This function returns 0 if it succeeds, or one of following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The stream does not exist + */ +NGHTTP2_EXTERN int +nghttp2_session_set_stream_user_data(nghttp2_session *session, + int32_t stream_id, void *stream_user_data); + +/** + * @function + * + * Returns the number of frames in the outbound queue. This does not + * include the deferred DATA frames. + */ +NGHTTP2_EXTERN size_t +nghttp2_session_get_outbound_queue_size(nghttp2_session *session); + +/** + * @function + * + * Returns the number of DATA payload in bytes received without + * WINDOW_UPDATE transmission for the stream |stream_id|. The local + * (receive) window size can be adjusted by + * `nghttp2_submit_window_update()`. This function takes into account + * that and returns effective data length. In particular, if the + * local window size is reduced by submitting negative + * window_size_increment with `nghttp2_submit_window_update()`, this + * function returns the number of bytes less than actually received. + * + * This function returns -1 if it fails. + */ +NGHTTP2_EXTERN int32_t nghttp2_session_get_stream_effective_recv_data_length( + nghttp2_session *session, int32_t stream_id); + +/** + * @function + * + * Returns the local (receive) window size for the stream |stream_id|. + * The local window size can be adjusted by + * `nghttp2_submit_window_update()`. This function takes into account + * that and returns effective window size. + * + * This function does not take into account the amount of received + * data from the remote endpoint. Use + * `nghttp2_session_get_stream_local_window_size()` to know the amount + * of data the remote endpoint can send without receiving stream level + * WINDOW_UPDATE frame. Note that each stream is still subject to the + * connection level flow control. + * + * This function returns -1 if it fails. + */ +NGHTTP2_EXTERN int32_t nghttp2_session_get_stream_effective_local_window_size( + nghttp2_session *session, int32_t stream_id); + +/** + * @function + * + * Returns the amount of flow-controlled payload (e.g., DATA) that the + * remote endpoint can send without receiving stream level + * WINDOW_UPDATE frame. It is also subject to the connection level + * flow control. So the actual amount of data to send is + * min(`nghttp2_session_get_stream_local_window_size()`, + * `nghttp2_session_get_local_window_size()`). + * + * This function returns -1 if it fails. + */ +NGHTTP2_EXTERN int32_t nghttp2_session_get_stream_local_window_size( + nghttp2_session *session, int32_t stream_id); + +/** + * @function + * + * Returns the number of DATA payload in bytes received without + * WINDOW_UPDATE transmission for a connection. The local (receive) + * window size can be adjusted by `nghttp2_submit_window_update()`. + * This function takes into account that and returns effective data + * length. In particular, if the local window size is reduced by + * submitting negative window_size_increment with + * `nghttp2_submit_window_update()`, this function returns the number + * of bytes less than actually received. + * + * This function returns -1 if it fails. + */ +NGHTTP2_EXTERN int32_t +nghttp2_session_get_effective_recv_data_length(nghttp2_session *session); + +/** + * @function + * + * Returns the local (receive) window size for a connection. The + * local window size can be adjusted by + * `nghttp2_submit_window_update()`. This function takes into account + * that and returns effective window size. + * + * This function does not take into account the amount of received + * data from the remote endpoint. Use + * `nghttp2_session_get_local_window_size()` to know the amount of + * data the remote endpoint can send without receiving + * connection-level WINDOW_UPDATE frame. Note that each stream is + * still subject to the stream level flow control. + * + * This function returns -1 if it fails. + */ +NGHTTP2_EXTERN int32_t +nghttp2_session_get_effective_local_window_size(nghttp2_session *session); + +/** + * @function + * + * Returns the amount of flow-controlled payload (e.g., DATA) that the + * remote endpoint can send without receiving connection level + * WINDOW_UPDATE frame. Note that each stream is still subject to the + * stream level flow control (see + * `nghttp2_session_get_stream_local_window_size()`). + * + * This function returns -1 if it fails. + */ +NGHTTP2_EXTERN int32_t +nghttp2_session_get_local_window_size(nghttp2_session *session); + +/** + * @function + * + * Returns the remote window size for a given stream |stream_id|. + * + * This is the amount of flow-controlled payload (e.g., DATA) that the + * local endpoint can send without stream level WINDOW_UPDATE. There + * is also connection level flow control, so the effective size of + * payload that the local endpoint can actually send is + * min(`nghttp2_session_get_stream_remote_window_size()`, + * `nghttp2_session_get_remote_window_size()`). + * + * This function returns -1 if it fails. + */ +NGHTTP2_EXTERN int32_t nghttp2_session_get_stream_remote_window_size( + nghttp2_session *session, int32_t stream_id); + +/** + * @function + * + * Returns the remote window size for a connection. + * + * This function always succeeds. + */ +NGHTTP2_EXTERN int32_t +nghttp2_session_get_remote_window_size(nghttp2_session *session); + +/** + * @function + * + * Returns 1 if local peer half closed the given stream |stream_id|. + * Returns 0 if it did not. Returns -1 if no such stream exists. + */ +NGHTTP2_EXTERN int +nghttp2_session_get_stream_local_close(nghttp2_session *session, + int32_t stream_id); + +/** + * @function + * + * Returns 1 if remote peer half closed the given stream |stream_id|. + * Returns 0 if it did not. Returns -1 if no such stream exists. + */ +NGHTTP2_EXTERN int +nghttp2_session_get_stream_remote_close(nghttp2_session *session, + int32_t stream_id); + +/** + * @function + * + * Returns the current dynamic table size of HPACK inflater, including + * the overhead 32 bytes per entry described in RFC 7541. + */ +NGHTTP2_EXTERN size_t +nghttp2_session_get_hd_inflate_dynamic_table_size(nghttp2_session *session); + +/** + * @function + * + * Returns the current dynamic table size of HPACK deflater including + * the overhead 32 bytes per entry described in RFC 7541. + */ +NGHTTP2_EXTERN size_t +nghttp2_session_get_hd_deflate_dynamic_table_size(nghttp2_session *session); + +/** + * @function + * + * Signals the session so that the connection should be terminated. + * + * The last stream ID is the minimum value between the stream ID of a + * stream for which :type:`nghttp2_on_frame_recv_callback` was called + * most recently and the last stream ID we have sent to the peer + * previously. + * + * The |error_code| is the error code of this GOAWAY frame. The + * pre-defined error code is one of :enum:`nghttp2_error_code`. + * + * After the transmission, both `nghttp2_session_want_read()` and + * `nghttp2_session_want_write()` return 0. + * + * This function should be called when the connection should be + * terminated after sending GOAWAY. If the remaining streams should + * be processed after GOAWAY, use `nghttp2_submit_goaway()` instead. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_session_terminate_session(nghttp2_session *session, + uint32_t error_code); + +/** + * @function + * + * Signals the session so that the connection should be terminated. + * + * This function behaves like `nghttp2_session_terminate_session()`, + * but the last stream ID can be specified by the application for fine + * grained control of stream. The HTTP/2 specification does not allow + * last_stream_id to be increased. So the actual value sent as + * last_stream_id is the minimum value between the given + * |last_stream_id| and the last_stream_id we have previously sent to + * the peer. + * + * The |last_stream_id| is peer's stream ID or 0. So if |session| is + * initialized as client, |last_stream_id| must be even or 0. If + * |session| is initialized as server, |last_stream_id| must be odd or + * 0. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |last_stream_id| is invalid. + */ +NGHTTP2_EXTERN int nghttp2_session_terminate_session2(nghttp2_session *session, + int32_t last_stream_id, + uint32_t error_code); + +/** + * @function + * + * Signals to the client that the server started graceful shutdown + * procedure. + * + * This function is only usable for server. If this function is + * called with client side session, this function returns + * :enum:`NGHTTP2_ERR_INVALID_STATE`. + * + * To gracefully shutdown HTTP/2 session, server should call this + * function to send GOAWAY with last_stream_id (1u << 31) - 1. And + * after some delay (e.g., 1 RTT), send another GOAWAY with the stream + * ID that the server has some processing using + * `nghttp2_submit_goaway()`. See also + * `nghttp2_session_get_last_proc_stream_id()`. + * + * Unlike `nghttp2_submit_goaway()`, this function just sends GOAWAY + * and does nothing more. This is a mere indication to the client + * that session shutdown is imminent. The application should call + * `nghttp2_submit_goaway()` with appropriate last_stream_id after + * this call. + * + * If one or more GOAWAY frame have been already sent by either + * `nghttp2_submit_goaway()` or `nghttp2_session_terminate_session()`, + * this function has no effect. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_STATE` + * The |session| is initialized as client. + */ +NGHTTP2_EXTERN int nghttp2_submit_shutdown_notice(nghttp2_session *session); + +/** + * @function + * + * Returns the value of SETTINGS |id| notified by a remote endpoint. + * The |id| must be one of values defined in + * :enum:`nghttp2_settings_id`. + */ +NGHTTP2_EXTERN uint32_t nghttp2_session_get_remote_settings( + nghttp2_session *session, nghttp2_settings_id id); + +/** + * @function + * + * Returns the value of SETTINGS |id| of local endpoint acknowledged + * by the remote endpoint. The |id| must be one of the values defined + * in :enum:`nghttp2_settings_id`. + */ +NGHTTP2_EXTERN uint32_t nghttp2_session_get_local_settings( + nghttp2_session *session, nghttp2_settings_id id); + +/** + * @function + * + * Tells the |session| that next stream ID is |next_stream_id|. The + * |next_stream_id| must be equal or greater than the value returned + * by `nghttp2_session_get_next_stream_id()`. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |next_stream_id| is strictly less than the value + * `nghttp2_session_get_next_stream_id()` returns; or + * |next_stream_id| is invalid (e.g., even integer for client, or + * odd integer for server). + */ +NGHTTP2_EXTERN int nghttp2_session_set_next_stream_id(nghttp2_session *session, + int32_t next_stream_id); + +/** + * @function + * + * Returns the next outgoing stream ID. Notice that return type is + * uint32_t. If we run out of stream ID for this session, this + * function returns 1 << 31. + */ +NGHTTP2_EXTERN uint32_t +nghttp2_session_get_next_stream_id(nghttp2_session *session); + +/** + * @function + * + * Tells the |session| that |size| bytes for a stream denoted by + * |stream_id| were consumed by application and are ready to + * WINDOW_UPDATE. The consumed bytes are counted towards both + * connection and stream level WINDOW_UPDATE (see + * `nghttp2_session_consume_connection()` and + * `nghttp2_session_consume_stream()` to update consumption + * independently). This function is intended to be used without + * automatic window update (see + * `nghttp2_option_set_no_auto_window_update()`). + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0. + * :enum:`NGHTTP2_ERR_INVALID_STATE` + * Automatic WINDOW_UPDATE is not disabled. + */ +NGHTTP2_EXTERN int nghttp2_session_consume(nghttp2_session *session, + int32_t stream_id, size_t size); + +/** + * @function + * + * Like `nghttp2_session_consume()`, but this only tells library that + * |size| bytes were consumed only for connection level. Note that + * HTTP/2 maintains connection and stream level flow control windows + * independently. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_STATE` + * Automatic WINDOW_UPDATE is not disabled. + */ +NGHTTP2_EXTERN int nghttp2_session_consume_connection(nghttp2_session *session, + size_t size); + +/** + * @function + * + * Like `nghttp2_session_consume()`, but this only tells library that + * |size| bytes were consumed only for stream denoted by |stream_id|. + * Note that HTTP/2 maintains connection and stream level flow control + * windows independently. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0. + * :enum:`NGHTTP2_ERR_INVALID_STATE` + * Automatic WINDOW_UPDATE is not disabled. + */ +NGHTTP2_EXTERN int nghttp2_session_consume_stream(nghttp2_session *session, + int32_t stream_id, + size_t size); + +/** + * @function + * + * Changes priority of existing stream denoted by |stream_id|. The + * new priority specification is |pri_spec|. + * + * The priority is changed silently and instantly, and no PRIORITY + * frame will be sent to notify the peer of this change. This + * function may be useful for server to change the priority of pushed + * stream. + * + * If |session| is initialized as server, and ``pri_spec->stream_id`` + * points to the idle stream, the idle stream is created if it does + * not exist. The created idle stream will depend on root stream + * (stream 0) with weight 16. + * + * Otherwise, if stream denoted by ``pri_spec->stream_id`` is not + * found, we use default priority instead of given |pri_spec|. That + * is make stream depend on root stream with weight 16. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * Attempted to depend on itself; or no stream exist for the given + * |stream_id|; or |stream_id| is 0 + */ +NGHTTP2_EXTERN int +nghttp2_session_change_stream_priority(nghttp2_session *session, + int32_t stream_id, + const nghttp2_priority_spec *pri_spec); + +/** + * @function + * + * Creates idle stream with the given |stream_id|, and priority + * |pri_spec|. + * + * The stream creation is done without sending PRIORITY frame, which + * means that peer does not know about the existence of this idle + * stream in the local endpoint. + * + * RFC 7540 does not disallow the use of creation of idle stream with + * odd or even stream ID regardless of client or server. So this + * function can create odd or even stream ID regardless of client or + * server. But probably it is a bit safer to use the stream ID the + * local endpoint can initiate (in other words, use odd stream ID for + * client, and even stream ID for server), to avoid potential + * collision from peer's instruction. Also we can use + * `nghttp2_session_set_next_stream_id()` to avoid to open created + * idle streams accidentally if we follow this recommendation. + * + * If |session| is initialized as server, and ``pri_spec->stream_id`` + * points to the idle stream, the idle stream is created if it does + * not exist. The created idle stream will depend on root stream + * (stream 0) with weight 16. + * + * Otherwise, if stream denoted by ``pri_spec->stream_id`` is not + * found, we use default priority instead of given |pri_spec|. That + * is make stream depend on root stream with weight 16. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * Attempted to depend on itself; or stream denoted by |stream_id| + * already exists; or |stream_id| cannot be used to create idle + * stream (in other words, local endpoint has already opened + * stream ID greater than or equal to the given stream ID; or + * |stream_id| is 0 + */ +NGHTTP2_EXTERN int +nghttp2_session_create_idle_stream(nghttp2_session *session, int32_t stream_id, + const nghttp2_priority_spec *pri_spec); + +/** + * @function + * + * Performs post-process of HTTP Upgrade request. This function can + * be called from both client and server, but the behavior is very + * different in each other. + * + * .. warning:: + * + * This function is deprecated in favor of + * `nghttp2_session_upgrade2()`, because this function lacks the + * parameter to tell the library the request method used in the + * original HTTP request. This information is required for client + * to validate actual response body length against content-length + * header field (see `nghttp2_option_set_no_http_messaging()`). If + * HEAD is used in request, the length of response body must be 0 + * regardless of value included in content-length header field. + * + * If called from client side, the |settings_payload| must be the + * value sent in ``HTTP2-Settings`` header field and must be decoded + * by base64url decoder. The |settings_payloadlen| is the length of + * |settings_payload|. The |settings_payload| is unpacked and its + * setting values will be submitted using `nghttp2_submit_settings()`. + * This means that the client application code does not need to submit + * SETTINGS by itself. The stream with stream ID=1 is opened and the + * |stream_user_data| is used for its stream_user_data. The opened + * stream becomes half-closed (local) state. + * + * If called from server side, the |settings_payload| must be the + * value received in ``HTTP2-Settings`` header field and must be + * decoded by base64url decoder. The |settings_payloadlen| is the + * length of |settings_payload|. It is treated as if the SETTINGS + * frame with that payload is received. Thus, callback functions for + * the reception of SETTINGS frame will be invoked. The stream with + * stream ID=1 is opened. The |stream_user_data| is ignored. The + * opened stream becomes half-closed (remote). + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |settings_payload| is badly formed. + * :enum:`NGHTTP2_ERR_PROTO` + * The stream ID 1 is already used or closed; or is not available. + */ +NGHTTP2_EXTERN int nghttp2_session_upgrade(nghttp2_session *session, + const uint8_t *settings_payload, + size_t settings_payloadlen, + void *stream_user_data); + +/** + * @function + * + * Performs post-process of HTTP Upgrade request. This function can + * be called from both client and server, but the behavior is very + * different in each other. + * + * If called from client side, the |settings_payload| must be the + * value sent in ``HTTP2-Settings`` header field and must be decoded + * by base64url decoder. The |settings_payloadlen| is the length of + * |settings_payload|. The |settings_payload| is unpacked and its + * setting values will be submitted using `nghttp2_submit_settings()`. + * This means that the client application code does not need to submit + * SETTINGS by itself. The stream with stream ID=1 is opened and the + * |stream_user_data| is used for its stream_user_data. The opened + * stream becomes half-closed (local) state. + * + * If called from server side, the |settings_payload| must be the + * value received in ``HTTP2-Settings`` header field and must be + * decoded by base64url decoder. The |settings_payloadlen| is the + * length of |settings_payload|. It is treated as if the SETTINGS + * frame with that payload is received. Thus, callback functions for + * the reception of SETTINGS frame will be invoked. The stream with + * stream ID=1 is opened. The |stream_user_data| is ignored. The + * opened stream becomes half-closed (remote). + * + * If the request method is HEAD, pass nonzero value to + * |head_request|. Otherwise, pass 0. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |settings_payload| is badly formed. + * :enum:`NGHTTP2_ERR_PROTO` + * The stream ID 1 is already used or closed; or is not available. + */ +NGHTTP2_EXTERN int nghttp2_session_upgrade2(nghttp2_session *session, + const uint8_t *settings_payload, + size_t settings_payloadlen, + int head_request, + void *stream_user_data); + +/** + * @function + * + * Serializes the SETTINGS values |iv| in the |buf|. The size of the + * |buf| is specified by |buflen|. The number of entries in the |iv| + * array is given by |niv|. The required space in |buf| for the |niv| + * entries is ``6*niv`` bytes and if the given buffer is too small, an + * error is returned. This function is used mainly for creating a + * SETTINGS payload to be sent with the ``HTTP2-Settings`` header + * field in an HTTP Upgrade request. The data written in |buf| is NOT + * base64url encoded and the application is responsible for encoding. + * + * This function returns the number of bytes written in |buf|, or one + * of the following negative error codes: + * + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |iv| contains duplicate settings ID or invalid value. + * + * :enum:`NGHTTP2_ERR_INSUFF_BUFSIZE` + * The provided |buflen| size is too small to hold the output. + */ +NGHTTP2_EXTERN ssize_t nghttp2_pack_settings_payload( + uint8_t *buf, size_t buflen, const nghttp2_settings_entry *iv, size_t niv); + +/** + * @function + * + * Returns string describing the |lib_error_code|. The + * |lib_error_code| must be one of the :enum:`nghttp2_error`. + */ +NGHTTP2_EXTERN const char *nghttp2_strerror(int lib_error_code); + +/** + * @function + * + * Returns string representation of HTTP/2 error code |error_code| + * (e.g., ``PROTOCOL_ERROR`` is returned if ``error_code == + * NGHTTP2_PROTOCOL_ERROR``). If string representation is unknown for + * given |error_code|, this function returns string ``unknown``. + */ +NGHTTP2_EXTERN const char *nghttp2_http2_strerror(uint32_t error_code); + +/** + * @function + * + * Initializes |pri_spec| with the |stream_id| of the stream to depend + * on with |weight| and its exclusive flag. If |exclusive| is + * nonzero, exclusive flag is set. + * + * The |weight| must be in [:enum:`NGHTTP2_MIN_WEIGHT`, + * :enum:`NGHTTP2_MAX_WEIGHT`], inclusive. + */ +NGHTTP2_EXTERN void nghttp2_priority_spec_init(nghttp2_priority_spec *pri_spec, + int32_t stream_id, + int32_t weight, int exclusive); + +/** + * @function + * + * Initializes |pri_spec| with the default values. The default values + * are: stream_id = 0, weight = :macro:`NGHTTP2_DEFAULT_WEIGHT` and + * exclusive = 0. + */ +NGHTTP2_EXTERN void +nghttp2_priority_spec_default_init(nghttp2_priority_spec *pri_spec); + +/** + * @function + * + * Returns nonzero if the |pri_spec| is filled with default values. + */ +NGHTTP2_EXTERN int +nghttp2_priority_spec_check_default(const nghttp2_priority_spec *pri_spec); + +/** + * @function + * + * Submits HEADERS frame and optionally one or more DATA frames. + * + * The |pri_spec| is priority specification of this request. ``NULL`` + * means the default priority (see + * `nghttp2_priority_spec_default_init()`). To specify the priority, + * use `nghttp2_priority_spec_init()`. If |pri_spec| is not ``NULL``, + * this function will copy its data members. + * + * The ``pri_spec->weight`` must be in [:enum:`NGHTTP2_MIN_WEIGHT`, + * :enum:`NGHTTP2_MAX_WEIGHT`], inclusive. If ``pri_spec->weight`` is + * strictly less than :enum:`NGHTTP2_MIN_WEIGHT`, it becomes + * :enum:`NGHTTP2_MIN_WEIGHT`. If it is strictly greater than + * :enum:`NGHTTP2_MAX_WEIGHT`, it becomes :enum:`NGHTTP2_MAX_WEIGHT`. + * + * The |nva| is an array of name/value pair :type:`nghttp2_nv` with + * |nvlen| elements. The application is responsible to include + * required pseudo-header fields (header field whose name starts with + * ":") in |nva| and must place pseudo-headers before regular header + * fields. + * + * This function creates copies of all name/value pairs in |nva|. It + * also lower-cases all names in |nva|. The order of elements in + * |nva| is preserved. For header fields with + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME` and + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_VALUE` are set, header field name + * and value are not copied respectively. With + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME`, application is responsible to + * pass header field name in lowercase. The application should + * maintain the references to them until + * :type:`nghttp2_on_frame_send_callback` or + * :type:`nghttp2_on_frame_not_send_callback` is called. + * + * HTTP/2 specification has requirement about header fields in the + * request HEADERS. See the specification for more details. + * + * If |data_prd| is not ``NULL``, it provides data which will be sent + * in subsequent DATA frames. In this case, a method that allows + * request message bodies + * (https://tools.ietf.org/html/rfc7231#section-4) must be specified + * with ``:method`` key in |nva| (e.g. ``POST``). This function does + * not take ownership of the |data_prd|. The function copies the + * members of the |data_prd|. If |data_prd| is ``NULL``, HEADERS have + * END_STREAM set. The |stream_user_data| is data associated to the + * stream opened by this request and can be an arbitrary pointer, + * which can be retrieved later by + * `nghttp2_session_get_stream_user_data()`. + * + * This function returns assigned stream ID if it succeeds, or one of + * the following negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE` + * No stream ID is available because maximum stream ID was + * reached. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * Trying to depend on itself (new stream ID equals + * ``pri_spec->stream_id``). + * :enum:`NGHTTP2_ERR_PROTO` + * The |session| is server session. + * + * .. warning:: + * + * This function returns assigned stream ID if it succeeds. But + * that stream is not opened yet. The application must not submit + * frame to that stream ID before + * :type:`nghttp2_before_frame_send_callback` is called for this + * frame. + * + */ +NGHTTP2_EXTERN int32_t nghttp2_submit_request( + nghttp2_session *session, const nghttp2_priority_spec *pri_spec, + const nghttp2_nv *nva, size_t nvlen, const nghttp2_data_provider *data_prd, + void *stream_user_data); + +/** + * @function + * + * Submits response HEADERS frame and optionally one or more DATA + * frames against the stream |stream_id|. + * + * The |nva| is an array of name/value pair :type:`nghttp2_nv` with + * |nvlen| elements. The application is responsible to include + * required pseudo-header fields (header field whose name starts with + * ":") in |nva| and must place pseudo-headers before regular header + * fields. + * + * This function creates copies of all name/value pairs in |nva|. It + * also lower-cases all names in |nva|. The order of elements in + * |nva| is preserved. For header fields with + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME` and + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_VALUE` are set, header field name + * and value are not copied respectively. With + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME`, application is responsible to + * pass header field name in lowercase. The application should + * maintain the references to them until + * :type:`nghttp2_on_frame_send_callback` or + * :type:`nghttp2_on_frame_not_send_callback` is called. + * + * HTTP/2 specification has requirement about header fields in the + * response HEADERS. See the specification for more details. + * + * If |data_prd| is not ``NULL``, it provides data which will be sent + * in subsequent DATA frames. This function does not take ownership + * of the |data_prd|. The function copies the members of the + * |data_prd|. If |data_prd| is ``NULL``, HEADERS will have + * END_STREAM flag set. + * + * This method can be used as normal HTTP response and push response. + * When pushing a resource using this function, the |session| must be + * configured using `nghttp2_session_server_new()` or its variants and + * the target stream denoted by the |stream_id| must be reserved using + * `nghttp2_submit_push_promise()`. + * + * To send non-final response headers (e.g., HTTP status 101), don't + * use this function because this function half-closes the outbound + * stream. Instead, use `nghttp2_submit_headers()` for this purpose. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0. + * :enum:`NGHTTP2_ERR_DATA_EXIST` + * DATA or HEADERS has been already submitted and not fully + * processed yet. Normally, this does not happen, but when + * application wrongly calls `nghttp2_submit_response()` twice, + * this may happen. + * :enum:`NGHTTP2_ERR_PROTO` + * The |session| is client session. + * + * .. warning:: + * + * Calling this function twice for the same stream ID may lead to + * program crash. It is generally considered to a programming error + * to commit response twice. + */ +NGHTTP2_EXTERN int +nghttp2_submit_response(nghttp2_session *session, int32_t stream_id, + const nghttp2_nv *nva, size_t nvlen, + const nghttp2_data_provider *data_prd); + +/** + * @function + * + * Submits trailer fields HEADERS against the stream |stream_id|. + * + * The |nva| is an array of name/value pair :type:`nghttp2_nv` with + * |nvlen| elements. The application must not include pseudo-header + * fields (headers whose names starts with ":") in |nva|. + * + * This function creates copies of all name/value pairs in |nva|. It + * also lower-cases all names in |nva|. The order of elements in + * |nva| is preserved. For header fields with + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME` and + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_VALUE` are set, header field name + * and value are not copied respectively. With + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME`, application is responsible to + * pass header field name in lowercase. The application should + * maintain the references to them until + * :type:`nghttp2_on_frame_send_callback` or + * :type:`nghttp2_on_frame_not_send_callback` is called. + * + * For server, trailer fields must follow response HEADERS or response + * DATA without END_STREAM flat set. The library does not enforce + * this requirement, and applications should do this for themselves. + * If `nghttp2_submit_trailer()` is called before any response HEADERS + * submission (usually by `nghttp2_submit_response()`), the content of + * |nva| will be sent as response headers, which will result in error. + * + * This function has the same effect with `nghttp2_submit_headers()`, + * with flags = :enum:`NGHTTP2_FLAG_END_STREAM` and both pri_spec and + * stream_user_data to NULL. + * + * To submit trailer fields after `nghttp2_submit_response()` is + * called, the application has to specify + * :type:`nghttp2_data_provider` to `nghttp2_submit_response()`. + * Inside of :type:`nghttp2_data_source_read_callback`, when setting + * :enum:`NGHTTP2_DATA_FLAG_EOF`, also set + * :enum:`NGHTTP2_DATA_FLAG_NO_END_STREAM`. After that, the + * application can send trailer fields using + * `nghttp2_submit_trailer()`. `nghttp2_submit_trailer()` can be used + * inside :type:`nghttp2_data_source_read_callback`. + * + * This function returns 0 if it succeeds and |stream_id| is -1. + * Otherwise, this function returns 0 if it succeeds, or one of the + * following negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0. + */ +NGHTTP2_EXTERN int nghttp2_submit_trailer(nghttp2_session *session, + int32_t stream_id, + const nghttp2_nv *nva, size_t nvlen); + +/** + * @function + * + * Submits HEADERS frame. The |flags| is bitwise OR of the + * following values: + * + * * :enum:`NGHTTP2_FLAG_END_STREAM` + * + * If |flags| includes :enum:`NGHTTP2_FLAG_END_STREAM`, this frame has + * END_STREAM flag set. + * + * The library handles the CONTINUATION frame internally and it + * correctly sets END_HEADERS to the last sequence of the PUSH_PROMISE + * or CONTINUATION frame. + * + * If the |stream_id| is -1, this frame is assumed as request (i.e., + * request HEADERS frame which opens new stream). In this case, the + * assigned stream ID will be returned. Otherwise, specify stream ID + * in |stream_id|. + * + * The |pri_spec| is priority specification of this request. ``NULL`` + * means the default priority (see + * `nghttp2_priority_spec_default_init()`). To specify the priority, + * use `nghttp2_priority_spec_init()`. If |pri_spec| is not ``NULL``, + * this function will copy its data members. + * + * The ``pri_spec->weight`` must be in [:enum:`NGHTTP2_MIN_WEIGHT`, + * :enum:`NGHTTP2_MAX_WEIGHT`], inclusive. If ``pri_spec->weight`` is + * strictly less than :enum:`NGHTTP2_MIN_WEIGHT`, it becomes + * :enum:`NGHTTP2_MIN_WEIGHT`. If it is strictly greater than + * :enum:`NGHTTP2_MAX_WEIGHT`, it becomes :enum:`NGHTTP2_MAX_WEIGHT`. + * + * The |nva| is an array of name/value pair :type:`nghttp2_nv` with + * |nvlen| elements. The application is responsible to include + * required pseudo-header fields (header field whose name starts with + * ":") in |nva| and must place pseudo-headers before regular header + * fields. + * + * This function creates copies of all name/value pairs in |nva|. It + * also lower-cases all names in |nva|. The order of elements in + * |nva| is preserved. For header fields with + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME` and + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_VALUE` are set, header field name + * and value are not copied respectively. With + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME`, application is responsible to + * pass header field name in lowercase. The application should + * maintain the references to them until + * :type:`nghttp2_on_frame_send_callback` or + * :type:`nghttp2_on_frame_not_send_callback` is called. + * + * The |stream_user_data| is a pointer to an arbitrary data which is + * associated to the stream this frame will open. Therefore it is + * only used if this frame opens streams, in other words, it changes + * stream state from idle or reserved to open. + * + * This function is low-level in a sense that the application code can + * specify flags directly. For usual HTTP request, + * `nghttp2_submit_request()` is useful. Likewise, for HTTP response, + * prefer `nghttp2_submit_response()`. + * + * This function returns newly assigned stream ID if it succeeds and + * |stream_id| is -1. Otherwise, this function returns 0 if it + * succeeds, or one of the following negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE` + * No stream ID is available because maximum stream ID was + * reached. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0; or trying to depend on itself (stream ID + * equals ``pri_spec->stream_id``). + * :enum:`NGHTTP2_ERR_DATA_EXIST` + * DATA or HEADERS has been already submitted and not fully + * processed yet. This happens if stream denoted by |stream_id| + * is in reserved state. + * :enum:`NGHTTP2_ERR_PROTO` + * The |stream_id| is -1, and |session| is server session. + * + * .. warning:: + * + * This function returns assigned stream ID if it succeeds and + * |stream_id| is -1. But that stream is not opened yet. The + * application must not submit frame to that stream ID before + * :type:`nghttp2_before_frame_send_callback` is called for this + * frame. + * + */ +NGHTTP2_EXTERN int32_t nghttp2_submit_headers( + nghttp2_session *session, uint8_t flags, int32_t stream_id, + const nghttp2_priority_spec *pri_spec, const nghttp2_nv *nva, size_t nvlen, + void *stream_user_data); + +/** + * @function + * + * Submits one or more DATA frames to the stream |stream_id|. The + * data to be sent are provided by |data_prd|. If |flags| contains + * :enum:`NGHTTP2_FLAG_END_STREAM`, the last DATA frame has END_STREAM + * flag set. + * + * This function does not take ownership of the |data_prd|. The + * function copies the members of the |data_prd|. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_DATA_EXIST` + * DATA or HEADERS has been already submitted and not fully + * processed yet. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0. + * :enum:`NGHTTP2_ERR_STREAM_CLOSED` + * The stream was already closed; or the |stream_id| is invalid. + * + * .. note:: + * + * Currently, only one DATA or HEADERS is allowed for a stream at a + * time. Submitting these frames more than once before first DATA + * or HEADERS is finished results in :enum:`NGHTTP2_ERR_DATA_EXIST` + * error code. The earliest callback which tells that previous + * frame is done is :type:`nghttp2_on_frame_send_callback`. In side + * that callback, new data can be submitted using + * `nghttp2_submit_data()`. Of course, all data except for last one + * must not have :enum:`NGHTTP2_FLAG_END_STREAM` flag set in + * |flags|. This sounds a bit complicated, and we recommend to use + * `nghttp2_submit_request()` and `nghttp2_submit_response()` to + * avoid this cascading issue. The experience shows that for HTTP + * use, these two functions are enough to implement both client and + * server. + */ +NGHTTP2_EXTERN int nghttp2_submit_data(nghttp2_session *session, uint8_t flags, + int32_t stream_id, + const nghttp2_data_provider *data_prd); + +/** + * @function + * + * Submits PRIORITY frame to change the priority of stream |stream_id| + * to the priority specification |pri_spec|. + * + * The |flags| is currently ignored and should be + * :enum:`NGHTTP2_FLAG_NONE`. + * + * The |pri_spec| is priority specification of this request. ``NULL`` + * is not allowed for this function. To specify the priority, use + * `nghttp2_priority_spec_init()`. This function will copy its data + * members. + * + * The ``pri_spec->weight`` must be in [:enum:`NGHTTP2_MIN_WEIGHT`, + * :enum:`NGHTTP2_MAX_WEIGHT`], inclusive. If ``pri_spec->weight`` is + * strictly less than :enum:`NGHTTP2_MIN_WEIGHT`, it becomes + * :enum:`NGHTTP2_MIN_WEIGHT`. If it is strictly greater than + * :enum:`NGHTTP2_MAX_WEIGHT`, it becomes :enum:`NGHTTP2_MAX_WEIGHT`. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0; or the |pri_spec| is NULL; or trying to + * depend on itself. + */ +NGHTTP2_EXTERN int +nghttp2_submit_priority(nghttp2_session *session, uint8_t flags, + int32_t stream_id, + const nghttp2_priority_spec *pri_spec); + +/** + * @function + * + * Submits RST_STREAM frame to cancel/reject the stream |stream_id| + * with the error code |error_code|. + * + * The pre-defined error code is one of :enum:`nghttp2_error_code`. + * + * The |flags| is currently ignored and should be + * :enum:`NGHTTP2_FLAG_NONE`. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0. + */ +NGHTTP2_EXTERN int nghttp2_submit_rst_stream(nghttp2_session *session, + uint8_t flags, int32_t stream_id, + uint32_t error_code); + +/** + * @function + * + * Stores local settings and submits SETTINGS frame. The |iv| is the + * pointer to the array of :type:`nghttp2_settings_entry`. The |niv| + * indicates the number of :type:`nghttp2_settings_entry`. + * + * The |flags| is currently ignored and should be + * :enum:`NGHTTP2_FLAG_NONE`. + * + * This function does not take ownership of the |iv|. This function + * copies all the elements in the |iv|. + * + * While updating individual stream's local window size, if the window + * size becomes strictly larger than NGHTTP2_MAX_WINDOW_SIZE, + * RST_STREAM is issued against such a stream. + * + * SETTINGS with :enum:`NGHTTP2_FLAG_ACK` is automatically submitted + * by the library and application could not send it at its will. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |iv| contains invalid value (e.g., initial window size + * strictly greater than (1 << 31) - 1. + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_submit_settings(nghttp2_session *session, + uint8_t flags, + const nghttp2_settings_entry *iv, + size_t niv); + +/** + * @function + * + * Submits PUSH_PROMISE frame. + * + * The |flags| is currently ignored. The library handles the + * CONTINUATION frame internally and it correctly sets END_HEADERS to + * the last sequence of the PUSH_PROMISE or CONTINUATION frame. + * + * The |stream_id| must be client initiated stream ID. + * + * The |nva| is an array of name/value pair :type:`nghttp2_nv` with + * |nvlen| elements. The application is responsible to include + * required pseudo-header fields (header field whose name starts with + * ":") in |nva| and must place pseudo-headers before regular header + * fields. + * + * This function creates copies of all name/value pairs in |nva|. It + * also lower-cases all names in |nva|. The order of elements in + * |nva| is preserved. For header fields with + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME` and + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_VALUE` are set, header field name + * and value are not copied respectively. With + * :enum:`NGHTTP2_NV_FLAG_NO_COPY_NAME`, application is responsible to + * pass header field name in lowercase. The application should + * maintain the references to them until + * :type:`nghttp2_on_frame_send_callback` or + * :type:`nghttp2_on_frame_not_send_callback` is called. + * + * The |promised_stream_user_data| is a pointer to an arbitrary data + * which is associated to the promised stream this frame will open and + * make it in reserved state. It is available using + * `nghttp2_session_get_stream_user_data()`. The application can + * access it in :type:`nghttp2_before_frame_send_callback` and + * :type:`nghttp2_on_frame_send_callback` of this frame. + * + * The client side is not allowed to use this function. + * + * To submit response headers and data, use + * `nghttp2_submit_response()`. + * + * This function returns assigned promised stream ID if it succeeds, + * or one of the following negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_PROTO` + * This function was invoked when |session| is initialized as + * client. + * :enum:`NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE` + * No stream ID is available because maximum stream ID was + * reached. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is 0; The |stream_id| does not designate stream + * that peer initiated. + * :enum:`NGHTTP2_ERR_STREAM_CLOSED` + * The stream was already closed; or the |stream_id| is invalid. + * + * .. warning:: + * + * This function returns assigned promised stream ID if it succeeds. + * As of 1.16.0, stream object for pushed resource is created when + * this function succeeds. In that case, the application can submit + * push response for the promised frame. + * + * In 1.15.0 or prior versions, pushed stream is not opened yet when + * this function succeeds. The application must not submit frame to + * that stream ID before :type:`nghttp2_before_frame_send_callback` + * is called for this frame. + * + */ +NGHTTP2_EXTERN int32_t nghttp2_submit_push_promise( + nghttp2_session *session, uint8_t flags, int32_t stream_id, + const nghttp2_nv *nva, size_t nvlen, void *promised_stream_user_data); + +/** + * @function + * + * Submits PING frame. You don't have to send PING back when you + * received PING frame. The library automatically submits PING frame + * in this case. + * + * The |flags| is bitwise OR of 0 or more of the following value. + * + * * :enum:`NGHTTP2_FLAG_ACK` + * + * Unless `nghttp2_option_set_no_auto_ping_ack()` is used, the |flags| + * should be :enum:`NGHTTP2_FLAG_NONE`. + * + * If the |opaque_data| is non ``NULL``, then it should point to the 8 + * bytes array of memory to specify opaque data to send with PING + * frame. If the |opaque_data| is ``NULL``, zero-cleared 8 bytes will + * be sent as opaque data. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_submit_ping(nghttp2_session *session, uint8_t flags, + const uint8_t *opaque_data); + +/** + * @function + * + * Submits GOAWAY frame with the last stream ID |last_stream_id| and + * the error code |error_code|. + * + * The pre-defined error code is one of :enum:`nghttp2_error_code`. + * + * The |flags| is currently ignored and should be + * :enum:`NGHTTP2_FLAG_NONE`. + * + * The |last_stream_id| is peer's stream ID or 0. So if |session| is + * initialized as client, |last_stream_id| must be even or 0. If + * |session| is initialized as server, |last_stream_id| must be odd or + * 0. + * + * The HTTP/2 specification says last_stream_id must not be increased + * from the value previously sent. So the actual value sent as + * last_stream_id is the minimum value between the given + * |last_stream_id| and the last_stream_id previously sent to the + * peer. + * + * If the |opaque_data| is not ``NULL`` and |opaque_data_len| is not + * zero, those data will be sent as additional debug data. The + * library makes a copy of the memory region pointed by |opaque_data| + * with the length |opaque_data_len|, so the caller does not need to + * keep this memory after the return of this function. If the + * |opaque_data_len| is 0, the |opaque_data| could be ``NULL``. + * + * After successful transmission of GOAWAY, following things happen. + * All incoming streams having strictly more than |last_stream_id| are + * closed. All incoming HEADERS which starts new stream are simply + * ignored. After all active streams are handled, both + * `nghttp2_session_want_read()` and `nghttp2_session_want_write()` + * return 0 and the application can close session. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |opaque_data_len| is too large; the |last_stream_id| is + * invalid. + */ +NGHTTP2_EXTERN int nghttp2_submit_goaway(nghttp2_session *session, + uint8_t flags, int32_t last_stream_id, + uint32_t error_code, + const uint8_t *opaque_data, + size_t opaque_data_len); + +/** + * @function + * + * Returns the last stream ID of a stream for which + * :type:`nghttp2_on_frame_recv_callback` was invoked most recently. + * The returned value can be used as last_stream_id parameter for + * `nghttp2_submit_goaway()` and + * `nghttp2_session_terminate_session2()`. + * + * This function always succeeds. + */ +NGHTTP2_EXTERN int32_t +nghttp2_session_get_last_proc_stream_id(nghttp2_session *session); + +/** + * @function + * + * Returns nonzero if new request can be sent from local endpoint. + * + * This function return 0 if request is not allowed for this session. + * There are several reasons why request is not allowed. Some of the + * reasons are: session is server; stream ID has been spent; GOAWAY + * has been sent or received. + * + * The application can call `nghttp2_submit_request()` without + * consulting this function. In that case, `nghttp2_submit_request()` + * may return error. Or, request is failed to sent, and + * :type:`nghttp2_on_stream_close_callback` is called. + */ +NGHTTP2_EXTERN int +nghttp2_session_check_request_allowed(nghttp2_session *session); + +/** + * @function + * + * Returns nonzero if |session| is initialized as server side session. + */ +NGHTTP2_EXTERN int +nghttp2_session_check_server_session(nghttp2_session *session); + +/** + * @function + * + * Submits WINDOW_UPDATE frame. + * + * The |flags| is currently ignored and should be + * :enum:`NGHTTP2_FLAG_NONE`. + * + * The |stream_id| is the stream ID to send this WINDOW_UPDATE. To + * send connection level WINDOW_UPDATE, specify 0 to |stream_id|. + * + * If the |window_size_increment| is positive, the WINDOW_UPDATE with + * that value as window_size_increment is queued. If the + * |window_size_increment| is larger than the received bytes from the + * remote endpoint, the local window size is increased by that + * difference. If the sole purpose is to increase the local window + * size, consider to use `nghttp2_session_set_local_window_size()`. + * + * If the |window_size_increment| is negative, the local window size + * is decreased by -|window_size_increment|. If automatic + * WINDOW_UPDATE is enabled + * (`nghttp2_option_set_no_auto_window_update()`), and the library + * decided that the WINDOW_UPDATE should be submitted, then + * WINDOW_UPDATE is queued with the current received bytes count. If + * the sole purpose is to decrease the local window size, consider to + * use `nghttp2_session_set_local_window_size()`. + * + * If the |window_size_increment| is 0, the function does nothing and + * returns 0. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_FLOW_CONTROL` + * The local window size overflow or gets negative. + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_submit_window_update(nghttp2_session *session, + uint8_t flags, + int32_t stream_id, + int32_t window_size_increment); + +/** + * @function + * + * Set local window size (local endpoints's window size) to the given + * |window_size| for the given stream denoted by |stream_id|. To + * change connection level window size, specify 0 to |stream_id|. To + * increase window size, this function may submit WINDOW_UPDATE frame + * to transmission queue. + * + * The |flags| is currently ignored and should be + * :enum:`NGHTTP2_FLAG_NONE`. + * + * This sounds similar to `nghttp2_submit_window_update()`, but there + * are 2 differences. The first difference is that this function + * takes the absolute value of window size to set, rather than the + * delta. To change the window size, this may be easier to use since + * the application just declares the intended window size, rather than + * calculating delta. The second difference is that + * `nghttp2_submit_window_update()` affects the received bytes count + * which has not acked yet. By the specification of + * `nghttp2_submit_window_update()`, to strictly increase the local + * window size, we have to submit delta including all received bytes + * count, which might not be desirable in some cases. On the other + * hand, this function does not affect the received bytes count. It + * just sets the local window size to the given value. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The |stream_id| is negative. + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int +nghttp2_session_set_local_window_size(nghttp2_session *session, uint8_t flags, + int32_t stream_id, int32_t window_size); + +/** + * @function + * + * Submits extension frame. + * + * Application can pass arbitrary frame flags and stream ID in |flags| + * and |stream_id| respectively. The |payload| is opaque pointer, and + * it can be accessible though ``frame->ext.payload`` in + * :type:`nghttp2_pack_extension_callback`. The library will not own + * passed |payload| pointer. + * + * The application must set :type:`nghttp2_pack_extension_callback` + * using `nghttp2_session_callbacks_set_pack_extension_callback()`. + * + * The application should retain the memory pointed by |payload| until + * the transmission of extension frame is done (which is indicated by + * :type:`nghttp2_on_frame_send_callback`), or transmission fails + * (which is indicated by :type:`nghttp2_on_frame_not_send_callback`). + * If application does not touch this memory region after packing it + * into a wire format, application can free it inside + * :type:`nghttp2_pack_extension_callback`. + * + * The standard HTTP/2 frame cannot be sent with this function, so + * |type| must be strictly grater than 0x9. Otherwise, this function + * will fail with error code :enum:`NGHTTP2_ERR_INVALID_ARGUMENT`. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_INVALID_STATE` + * If :type:`nghttp2_pack_extension_callback` is not set. + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * If |type| specifies standard HTTP/2 frame type. The frame + * types in the rage [0x0, 0x9], both inclusive, are standard + * HTTP/2 frame type, and cannot be sent using this function. + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory + */ +NGHTTP2_EXTERN int nghttp2_submit_extension(nghttp2_session *session, + uint8_t type, uint8_t flags, + int32_t stream_id, void *payload); + +/** + * @struct + * + * The payload of ALTSVC frame. ALTSVC frame is a non-critical + * extension to HTTP/2. If this frame is received, and + * `nghttp2_option_set_user_recv_extension_type()` is not set, and + * `nghttp2_option_set_builtin_recv_extension_type()` is set for + * :enum:`NGHTTP2_ALTSVC`, ``nghttp2_extension.payload`` will point to + * this struct. + * + * It has the following members: + */ +typedef struct { + /** + * The pointer to origin which this alternative service is + * associated with. This is not necessarily NULL-terminated. + */ + uint8_t *origin; + /** + * The length of the |origin|. + */ + size_t origin_len; + /** + * The pointer to Alt-Svc field value contained in ALTSVC frame. + * This is not necessarily NULL-terminated. + */ + uint8_t *field_value; + /** + * The length of the |field_value|. + */ + size_t field_value_len; +} nghttp2_ext_altsvc; + +/** + * @function + * + * Submits ALTSVC frame. + * + * ALTSVC frame is a non-critical extension to HTTP/2, and defined in + * is defined in `RFC 7383 + * `_. + * + * The |flags| is currently ignored and should be + * :enum:`NGHTTP2_FLAG_NONE`. + * + * The |origin| points to the origin this alternative service is + * associated with. The |origin_len| is the length of the origin. If + * |stream_id| is 0, the origin must be specified. If |stream_id| is + * not zero, the origin must be empty (in other words, |origin_len| + * must be 0). + * + * The ALTSVC frame is only usable from server side. If this function + * is invoked with client side session, this function returns + * :enum:`NGHTTP2_ERR_INVALID_STATE`. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory + * :enum:`NGHTTP2_ERR_INVALID_STATE` + * The function is called from client side session + * :enum:`NGHTTP2_ERR_INVALID_ARGUMENT` + * The sum of |origin_len| and |field_value_len| is larger than + * 16382; or |origin_len| is 0 while |stream_id| is 0; or + * |origin_len| is not 0 while |stream_id| is not 0. + */ +NGHTTP2_EXTERN int nghttp2_submit_altsvc(nghttp2_session *session, + uint8_t flags, int32_t stream_id, + const uint8_t *origin, + size_t origin_len, + const uint8_t *field_value, + size_t field_value_len); + +/** + * @function + * + * Compares ``lhs->name`` of length ``lhs->namelen`` bytes and + * ``rhs->name`` of length ``rhs->namelen`` bytes. Returns negative + * integer if ``lhs->name`` is found to be less than ``rhs->name``; or + * returns positive integer if ``lhs->name`` is found to be greater + * than ``rhs->name``; or returns 0 otherwise. + */ +NGHTTP2_EXTERN int nghttp2_nv_compare_name(const nghttp2_nv *lhs, + const nghttp2_nv *rhs); + +/** + * @function + * + * A helper function for dealing with NPN in client side or ALPN in + * server side. The |in| contains peer's protocol list in preferable + * order. The format of |in| is length-prefixed and not + * null-terminated. For example, ``h2`` and + * ``http/1.1`` stored in |in| like this:: + * + * in[0] = 2 + * in[1..2] = "h2" + * in[3] = 8 + * in[4..11] = "http/1.1" + * inlen = 12 + * + * The selection algorithm is as follows: + * + * 1. If peer's list contains HTTP/2 protocol the library supports, + * it is selected and returns 1. The following step is not taken. + * + * 2. If peer's list contains ``http/1.1``, this function selects + * ``http/1.1`` and returns 0. The following step is not taken. + * + * 3. This function selects nothing and returns -1 (So called + * non-overlap case). In this case, |out| and |outlen| are left + * untouched. + * + * Selecting ``h2`` means that ``h2`` is written into |*out| and its + * length (which is 2) is assigned to |*outlen|. + * + * For ALPN, refer to https://tools.ietf.org/html/rfc7301 + * + * See http://technotes.googlecode.com/git/nextprotoneg.html for more + * details about NPN. + * + * For NPN, to use this method you should do something like:: + * + * static int select_next_proto_cb(SSL* ssl, + * unsigned char **out, + * unsigned char *outlen, + * const unsigned char *in, + * unsigned int inlen, + * void *arg) + * { + * int rv; + * rv = nghttp2_select_next_protocol(out, outlen, in, inlen); + * if (rv == -1) { + * return SSL_TLSEXT_ERR_NOACK; + * } + * if (rv == 1) { + * ((MyType*)arg)->http2_selected = 1; + * } + * return SSL_TLSEXT_ERR_OK; + * } + * ... + * SSL_CTX_set_next_proto_select_cb(ssl_ctx, select_next_proto_cb, my_obj); + * + */ +NGHTTP2_EXTERN int nghttp2_select_next_protocol(unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen); + +/** + * @function + * + * Returns a pointer to a nghttp2_info struct with version information + * about the run-time library in use. The |least_version| argument + * can be set to a 24 bit numerical value for the least accepted + * version number and if the condition is not met, this function will + * return a ``NULL``. Pass in 0 to skip the version checking. + */ +NGHTTP2_EXTERN nghttp2_info *nghttp2_version(int least_version); + +/** + * @function + * + * Returns nonzero if the :type:`nghttp2_error` library error code + * |lib_error| is fatal. + */ +NGHTTP2_EXTERN int nghttp2_is_fatal(int lib_error_code); + +/** + * @function + * + * Returns nonzero if HTTP header field name |name| of length |len| is + * valid according to http://tools.ietf.org/html/rfc7230#section-3.2 + * + * Because this is a header field name in HTTP2, the upper cased alphabet + * is treated as error. + */ +NGHTTP2_EXTERN int nghttp2_check_header_name(const uint8_t *name, size_t len); + +/** + * @function + * + * Returns nonzero if HTTP header field value |value| of length |len| + * is valid according to + * http://tools.ietf.org/html/rfc7230#section-3.2 + */ +NGHTTP2_EXTERN int nghttp2_check_header_value(const uint8_t *value, size_t len); + +/* HPACK API */ + +struct nghttp2_hd_deflater; + +/** + * @struct + * + * HPACK deflater object. + */ +typedef struct nghttp2_hd_deflater nghttp2_hd_deflater; + +/** + * @function + * + * Initializes |*deflater_ptr| for deflating name/values pairs. + * + * The |max_deflate_dynamic_table_size| is the upper bound of header + * table size the deflater will use. + * + * If this function fails, |*deflater_ptr| is left untouched. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int +nghttp2_hd_deflate_new(nghttp2_hd_deflater **deflater_ptr, + size_t max_deflate_dynamic_table_size); + +/** + * @function + * + * Like `nghttp2_hd_deflate_new()`, but with additional custom memory + * allocator specified in the |mem|. + * + * The |mem| can be ``NULL`` and the call is equivalent to + * `nghttp2_hd_deflate_new()`. + * + * This function does not take ownership |mem|. The application is + * responsible for freeing |mem|. + * + * The library code does not refer to |mem| pointer after this + * function returns, so the application can safely free it. + */ +NGHTTP2_EXTERN int +nghttp2_hd_deflate_new2(nghttp2_hd_deflater **deflater_ptr, + size_t max_deflate_dynamic_table_size, + nghttp2_mem *mem); + +/** + * @function + * + * Deallocates any resources allocated for |deflater|. + */ +NGHTTP2_EXTERN void nghttp2_hd_deflate_del(nghttp2_hd_deflater *deflater); + +/** + * @function + * + * Changes header table size of the |deflater| to + * |settings_max_dynamic_table_size| bytes. This may trigger eviction + * in the dynamic table. + * + * The |settings_max_dynamic_table_size| should be the value received + * in SETTINGS_HEADER_TABLE_SIZE. + * + * The deflater never uses more memory than + * ``max_deflate_dynamic_table_size`` bytes specified in + * `nghttp2_hd_deflate_new()`. Therefore, if + * |settings_max_dynamic_table_size| > + * ``max_deflate_dynamic_table_size``, resulting maximum table size + * becomes ``max_deflate_dynamic_table_size``. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int +nghttp2_hd_deflate_change_table_size(nghttp2_hd_deflater *deflater, + size_t settings_max_dynamic_table_size); + +/** + * @function + * + * Deflates the |nva|, which has the |nvlen| name/value pairs, into + * the |buf| of length |buflen|. + * + * If |buf| is not large enough to store the deflated header block, + * this function fails with :enum:`NGHTTP2_ERR_INSUFF_BUFSIZE`. The + * caller should use `nghttp2_hd_deflate_bound()` to know the upper + * bound of buffer size required to deflate given header name/value + * pairs. + * + * Once this function fails, subsequent call of this function always + * returns :enum:`NGHTTP2_ERR_HEADER_COMP`. + * + * After this function returns, it is safe to delete the |nva|. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_HEADER_COMP` + * Deflation process has failed. + * :enum:`NGHTTP2_ERR_INSUFF_BUFSIZE` + * The provided |buflen| size is too small to hold the output. + */ +NGHTTP2_EXTERN ssize_t nghttp2_hd_deflate_hd(nghttp2_hd_deflater *deflater, + uint8_t *buf, size_t buflen, + const nghttp2_nv *nva, + size_t nvlen); + +/** + * @function + * + * Deflates the |nva|, which has the |nvlen| name/value pairs, into + * the |veclen| size of buf vector |vec|. The each size of buffer + * must be set in len field of :type:`nghttp2_vec`. If and only if + * one chunk is filled up completely, next chunk will be used. If + * |vec| is not large enough to store the deflated header block, this + * function fails with :enum:`NGHTTP2_ERR_INSUFF_BUFSIZE`. The caller + * should use `nghttp2_hd_deflate_bound()` to know the upper bound of + * buffer size required to deflate given header name/value pairs. + * + * Once this function fails, subsequent call of this function always + * returns :enum:`NGHTTP2_ERR_HEADER_COMP`. + * + * After this function returns, it is safe to delete the |nva|. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_HEADER_COMP` + * Deflation process has failed. + * :enum:`NGHTTP2_ERR_INSUFF_BUFSIZE` + * The provided |buflen| size is too small to hold the output. + */ +NGHTTP2_EXTERN ssize_t nghttp2_hd_deflate_hd_vec(nghttp2_hd_deflater *deflater, + const nghttp2_vec *vec, + size_t veclen, + const nghttp2_nv *nva, + size_t nvlen); + +/** + * @function + * + * Returns an upper bound on the compressed size after deflation of + * |nva| of length |nvlen|. + */ +NGHTTP2_EXTERN size_t nghttp2_hd_deflate_bound(nghttp2_hd_deflater *deflater, + const nghttp2_nv *nva, + size_t nvlen); + +/** + * @function + * + * Returns the number of entries that header table of |deflater| + * contains. This is the sum of the number of static table and + * dynamic table, so the return value is at least 61. + */ +NGHTTP2_EXTERN +size_t nghttp2_hd_deflate_get_num_table_entries(nghttp2_hd_deflater *deflater); + +/** + * @function + * + * Returns the table entry denoted by |idx| from header table of + * |deflater|. The |idx| is 1-based, and idx=1 returns first entry of + * static table. idx=62 returns first entry of dynamic table if it + * exists. Specifying idx=0 is error, and this function returns NULL. + * If |idx| is strictly greater than the number of entries the tables + * contain, this function returns NULL. + */ +NGHTTP2_EXTERN +const nghttp2_nv * +nghttp2_hd_deflate_get_table_entry(nghttp2_hd_deflater *deflater, size_t idx); + +/** + * @function + * + * Returns the used dynamic table size, including the overhead 32 + * bytes per entry described in RFC 7541. + */ +NGHTTP2_EXTERN +size_t nghttp2_hd_deflate_get_dynamic_table_size(nghttp2_hd_deflater *deflater); + +/** + * @function + * + * Returns the maximum dynamic table size. + */ +NGHTTP2_EXTERN +size_t +nghttp2_hd_deflate_get_max_dynamic_table_size(nghttp2_hd_deflater *deflater); + +struct nghttp2_hd_inflater; + +/** + * @struct + * + * HPACK inflater object. + */ +typedef struct nghttp2_hd_inflater nghttp2_hd_inflater; + +/** + * @function + * + * Initializes |*inflater_ptr| for inflating name/values pairs. + * + * If this function fails, |*inflater_ptr| is left untouched. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + */ +NGHTTP2_EXTERN int nghttp2_hd_inflate_new(nghttp2_hd_inflater **inflater_ptr); + +/** + * @function + * + * Like `nghttp2_hd_inflate_new()`, but with additional custom memory + * allocator specified in the |mem|. + * + * The |mem| can be ``NULL`` and the call is equivalent to + * `nghttp2_hd_inflate_new()`. + * + * This function does not take ownership |mem|. The application is + * responsible for freeing |mem|. + * + * The library code does not refer to |mem| pointer after this + * function returns, so the application can safely free it. + */ +NGHTTP2_EXTERN int nghttp2_hd_inflate_new2(nghttp2_hd_inflater **inflater_ptr, + nghttp2_mem *mem); + +/** + * @function + * + * Deallocates any resources allocated for |inflater|. + */ +NGHTTP2_EXTERN void nghttp2_hd_inflate_del(nghttp2_hd_inflater *inflater); + +/** + * @function + * + * Changes header table size in the |inflater|. This may trigger + * eviction in the dynamic table. + * + * The |settings_max_dynamic_table_size| should be the value + * transmitted in SETTINGS_HEADER_TABLE_SIZE. + * + * This function must not be called while header block is being + * inflated. In other words, this function must be called after + * initialization of |inflater|, but before calling + * `nghttp2_hd_inflate_hd2()`, or after + * `nghttp2_hd_inflate_end_headers()`. Otherwise, + * `NGHTTP2_ERR_INVALID_STATE` was returned. + * + * This function returns 0 if it succeeds, or one of the following + * negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_INVALID_STATE` + * The function is called while header block is being inflated. + * Probably, application missed to call + * `nghttp2_hd_inflate_end_headers()`. + */ +NGHTTP2_EXTERN int +nghttp2_hd_inflate_change_table_size(nghttp2_hd_inflater *inflater, + size_t settings_max_dynamic_table_size); + +/** + * @enum + * + * The flags for header inflation. + */ +typedef enum { + /** + * No flag set. + */ + NGHTTP2_HD_INFLATE_NONE = 0, + /** + * Indicates all headers were inflated. + */ + NGHTTP2_HD_INFLATE_FINAL = 0x01, + /** + * Indicates a header was emitted. + */ + NGHTTP2_HD_INFLATE_EMIT = 0x02 +} nghttp2_hd_inflate_flag; + +/** + * @function + * + * .. warning:: + * + * Deprecated. Use `nghttp2_hd_inflate_hd2()` instead. + * + * Inflates name/value block stored in |in| with length |inlen|. This + * function performs decompression. For each successful emission of + * header name/value pair, :enum:`NGHTTP2_HD_INFLATE_EMIT` is set in + * |*inflate_flags| and name/value pair is assigned to the |nv_out| + * and the function returns. The caller must not free the members of + * |nv_out|. + * + * The |nv_out| may include pointers to the memory region in the |in|. + * The caller must retain the |in| while the |nv_out| is used. + * + * The application should call this function repeatedly until the + * ``(*inflate_flags) & NGHTTP2_HD_INFLATE_FINAL`` is nonzero and + * return value is non-negative. This means the all input values are + * processed successfully. Then the application must call + * `nghttp2_hd_inflate_end_headers()` to prepare for the next header + * block input. + * + * The caller can feed complete compressed header block. It also can + * feed it in several chunks. The caller must set |in_final| to + * nonzero if the given input is the last block of the compressed + * header. + * + * This function returns the number of bytes processed if it succeeds, + * or one of the following negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_HEADER_COMP` + * Inflation process has failed. + * :enum:`NGHTTP2_ERR_BUFFER_ERROR` + * The header field name or value is too large. + * + * Example follows:: + * + * int inflate_header_block(nghttp2_hd_inflater *hd_inflater, + * uint8_t *in, size_t inlen, int final) + * { + * ssize_t rv; + * + * for(;;) { + * nghttp2_nv nv; + * int inflate_flags = 0; + * + * rv = nghttp2_hd_inflate_hd(hd_inflater, &nv, &inflate_flags, + * in, inlen, final); + * + * if(rv < 0) { + * fprintf(stderr, "inflate failed with error code %zd", rv); + * return -1; + * } + * + * in += rv; + * inlen -= rv; + * + * if(inflate_flags & NGHTTP2_HD_INFLATE_EMIT) { + * fwrite(nv.name, nv.namelen, 1, stderr); + * fprintf(stderr, ": "); + * fwrite(nv.value, nv.valuelen, 1, stderr); + * fprintf(stderr, "\n"); + * } + * if(inflate_flags & NGHTTP2_HD_INFLATE_FINAL) { + * nghttp2_hd_inflate_end_headers(hd_inflater); + * break; + * } + * if((inflate_flags & NGHTTP2_HD_INFLATE_EMIT) == 0 && + * inlen == 0) { + * break; + * } + * } + * + * return 0; + * } + * + */ +NGHTTP2_EXTERN ssize_t nghttp2_hd_inflate_hd(nghttp2_hd_inflater *inflater, + nghttp2_nv *nv_out, + int *inflate_flags, uint8_t *in, + size_t inlen, int in_final); + +/** + * @function + * + * Inflates name/value block stored in |in| with length |inlen|. This + * function performs decompression. For each successful emission of + * header name/value pair, :enum:`NGHTTP2_HD_INFLATE_EMIT` is set in + * |*inflate_flags| and name/value pair is assigned to the |nv_out| + * and the function returns. The caller must not free the members of + * |nv_out|. + * + * The |nv_out| may include pointers to the memory region in the |in|. + * The caller must retain the |in| while the |nv_out| is used. + * + * The application should call this function repeatedly until the + * ``(*inflate_flags) & NGHTTP2_HD_INFLATE_FINAL`` is nonzero and + * return value is non-negative. If that happens, all given input + * data (|inlen| bytes) are processed successfully. Then the + * application must call `nghttp2_hd_inflate_end_headers()` to prepare + * for the next header block input. + * + * In other words, if |in_final| is nonzero, and this function returns + * |inlen|, you can assert that :enum:`NGHTTP2_HD_INFLATE_FINAL` is + * set in |*inflate_flags|. + * + * The caller can feed complete compressed header block. It also can + * feed it in several chunks. The caller must set |in_final| to + * nonzero if the given input is the last block of the compressed + * header. + * + * This function returns the number of bytes processed if it succeeds, + * or one of the following negative error codes: + * + * :enum:`NGHTTP2_ERR_NOMEM` + * Out of memory. + * :enum:`NGHTTP2_ERR_HEADER_COMP` + * Inflation process has failed. + * :enum:`NGHTTP2_ERR_BUFFER_ERROR` + * The header field name or value is too large. + * + * Example follows:: + * + * int inflate_header_block(nghttp2_hd_inflater *hd_inflater, + * uint8_t *in, size_t inlen, int final) + * { + * ssize_t rv; + * + * for(;;) { + * nghttp2_nv nv; + * int inflate_flags = 0; + * + * rv = nghttp2_hd_inflate_hd2(hd_inflater, &nv, &inflate_flags, + * in, inlen, final); + * + * if(rv < 0) { + * fprintf(stderr, "inflate failed with error code %zd", rv); + * return -1; + * } + * + * in += rv; + * inlen -= rv; + * + * if(inflate_flags & NGHTTP2_HD_INFLATE_EMIT) { + * fwrite(nv.name, nv.namelen, 1, stderr); + * fprintf(stderr, ": "); + * fwrite(nv.value, nv.valuelen, 1, stderr); + * fprintf(stderr, "\n"); + * } + * if(inflate_flags & NGHTTP2_HD_INFLATE_FINAL) { + * nghttp2_hd_inflate_end_headers(hd_inflater); + * break; + * } + * if((inflate_flags & NGHTTP2_HD_INFLATE_EMIT) == 0 && + * inlen == 0) { + * break; + * } + * } + * + * return 0; + * } + * + */ +NGHTTP2_EXTERN ssize_t nghttp2_hd_inflate_hd2(nghttp2_hd_inflater *inflater, + nghttp2_nv *nv_out, + int *inflate_flags, + const uint8_t *in, size_t inlen, + int in_final); + +/** + * @function + * + * Signals the end of decompression for one header block. + * + * This function returns 0 if it succeeds. Currently this function + * always succeeds. + */ +NGHTTP2_EXTERN int +nghttp2_hd_inflate_end_headers(nghttp2_hd_inflater *inflater); + +/** + * @function + * + * Returns the number of entries that header table of |inflater| + * contains. This is the sum of the number of static table and + * dynamic table, so the return value is at least 61. + */ +NGHTTP2_EXTERN +size_t nghttp2_hd_inflate_get_num_table_entries(nghttp2_hd_inflater *inflater); + +/** + * @function + * + * Returns the table entry denoted by |idx| from header table of + * |inflater|. The |idx| is 1-based, and idx=1 returns first entry of + * static table. idx=62 returns first entry of dynamic table if it + * exists. Specifying idx=0 is error, and this function returns NULL. + * If |idx| is strictly greater than the number of entries the tables + * contain, this function returns NULL. + */ +NGHTTP2_EXTERN +const nghttp2_nv * +nghttp2_hd_inflate_get_table_entry(nghttp2_hd_inflater *inflater, size_t idx); + +/** + * @function + * + * Returns the used dynamic table size, including the overhead 32 + * bytes per entry described in RFC 7541. + */ +NGHTTP2_EXTERN +size_t nghttp2_hd_inflate_get_dynamic_table_size(nghttp2_hd_inflater *inflater); + +/** + * @function + * + * Returns the maximum dynamic table size. + */ +NGHTTP2_EXTERN +size_t +nghttp2_hd_inflate_get_max_dynamic_table_size(nghttp2_hd_inflater *inflater); + +struct nghttp2_stream; + +/** + * @struct + * + * The structure to represent HTTP/2 stream. The details of this + * structure are intentionally hidden from the public API. + */ +typedef struct nghttp2_stream nghttp2_stream; + +/** + * @function + * + * Returns pointer to :type:`nghttp2_stream` object denoted by + * |stream_id|. If stream was not found, returns NULL. + * + * Returns imaginary root stream (see + * `nghttp2_session_get_root_stream()`) if 0 is given in |stream_id|. + * + * Unless |stream_id| == 0, the returned pointer is valid until next + * call of `nghttp2_session_send()`, `nghttp2_session_mem_send()`, + * `nghttp2_session_recv()`, and `nghttp2_session_mem_recv()`. + */ +NGHTTP2_EXTERN nghttp2_stream * +nghttp2_session_find_stream(nghttp2_session *session, int32_t stream_id); + +/** + * @enum + * + * State of stream as described in RFC 7540. + */ +typedef enum { + /** + * idle state. + */ + NGHTTP2_STREAM_STATE_IDLE = 1, + /** + * open state. + */ + NGHTTP2_STREAM_STATE_OPEN, + /** + * reserved (local) state. + */ + NGHTTP2_STREAM_STATE_RESERVED_LOCAL, + /** + * reserved (remote) state. + */ + NGHTTP2_STREAM_STATE_RESERVED_REMOTE, + /** + * half closed (local) state. + */ + NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL, + /** + * half closed (remote) state. + */ + NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE, + /** + * closed state. + */ + NGHTTP2_STREAM_STATE_CLOSED +} nghttp2_stream_proto_state; + +/** + * @function + * + * Returns state of |stream|. The root stream retrieved by + * `nghttp2_session_get_root_stream()` will have stream state + * :enum:`NGHTTP2_STREAM_STATE_IDLE`. + */ +NGHTTP2_EXTERN nghttp2_stream_proto_state +nghttp2_stream_get_state(nghttp2_stream *stream); + +/** + * @function + * + * Returns root of dependency tree, which is imaginary stream with + * stream ID 0. The returned pointer is valid until |session| is + * freed by `nghttp2_session_del()`. + */ +NGHTTP2_EXTERN nghttp2_stream * +nghttp2_session_get_root_stream(nghttp2_session *session); + +/** + * @function + * + * Returns the parent stream of |stream| in dependency tree. Returns + * NULL if there is no such stream. + */ +NGHTTP2_EXTERN nghttp2_stream * +nghttp2_stream_get_parent(nghttp2_stream *stream); + +NGHTTP2_EXTERN int32_t nghttp2_stream_get_stream_id(nghttp2_stream *stream); + +/** + * @function + * + * Returns the next sibling stream of |stream| in dependency tree. + * Returns NULL if there is no such stream. + */ +NGHTTP2_EXTERN nghttp2_stream * +nghttp2_stream_get_next_sibling(nghttp2_stream *stream); + +/** + * @function + * + * Returns the previous sibling stream of |stream| in dependency tree. + * Returns NULL if there is no such stream. + */ +NGHTTP2_EXTERN nghttp2_stream * +nghttp2_stream_get_previous_sibling(nghttp2_stream *stream); + +/** + * @function + * + * Returns the first child stream of |stream| in dependency tree. + * Returns NULL if there is no such stream. + */ +NGHTTP2_EXTERN nghttp2_stream * +nghttp2_stream_get_first_child(nghttp2_stream *stream); + +/** + * @function + * + * Returns dependency weight to the parent stream of |stream|. + */ +NGHTTP2_EXTERN int32_t nghttp2_stream_get_weight(nghttp2_stream *stream); + +/** + * @function + * + * Returns the sum of the weight for |stream|'s children. + */ +NGHTTP2_EXTERN int32_t +nghttp2_stream_get_sum_dependency_weight(nghttp2_stream *stream); + +/** + * @functypedef + * + * Callback function invoked when the library outputs debug logging. + * The function is called with arguments suitable for ``vfprintf(3)`` + * + * The debug output is only enabled if the library is built with + * ``DEBUGBUILD`` macro defined. + */ +typedef void (*nghttp2_debug_vprintf_callback)(const char *format, + va_list args); + +/** + * @function + * + * Sets a debug output callback called by the library when built with + * ``DEBUGBUILD`` macro defined. If this option is not used, debug + * log is written into standard error output. + * + * For builds without ``DEBUGBUILD`` macro defined, this function is + * noop. + * + * Note that building with ``DEBUGBUILD`` may cause significant + * performance penalty to libnghttp2 because of extra processing. It + * should be used for debugging purpose only. + * + * .. Warning:: + * + * Building with ``DEBUGBUILD`` may cause significant performance + * penalty to libnghttp2 because of extra processing. It should be + * used for debugging purpose only. We write this two times because + * this is important. + */ +NGHTTP2_EXTERN void nghttp2_set_debug_vprintf_callback( + nghttp2_debug_vprintf_callback debug_vprintf_callback); + +#ifdef __cplusplus +} +#endif + +#endif /* NGHTTP2_H */ diff --git a/tools/sdk/include/nvs_flash/nvs.h b/tools/sdk/include/nvs_flash/nvs.h index dfdd18c92c8..0cc3ba09a6e 100644 --- a/tools/sdk/include/nvs_flash/nvs.h +++ b/tools/sdk/include/nvs_flash/nvs.h @@ -28,22 +28,32 @@ extern "C" { */ typedef uint32_t nvs_handle; -#define ESP_ERR_NVS_BASE 0x1100 /*!< Starting number of error codes */ -#define ESP_ERR_NVS_NOT_INITIALIZED (ESP_ERR_NVS_BASE + 0x01) /*!< The storage driver is not initialized */ -#define ESP_ERR_NVS_NOT_FOUND (ESP_ERR_NVS_BASE + 0x02) /*!< Id namespace doesn’t exist yet and mode is NVS_READONLY */ -#define ESP_ERR_NVS_TYPE_MISMATCH (ESP_ERR_NVS_BASE + 0x03) /*!< The type of set or get operation doesn't match the type of value stored in NVS */ -#define ESP_ERR_NVS_READ_ONLY (ESP_ERR_NVS_BASE + 0x04) /*!< Storage handle was opened as read only */ -#define ESP_ERR_NVS_NOT_ENOUGH_SPACE (ESP_ERR_NVS_BASE + 0x05) /*!< There is not enough space in the underlying storage to save the value */ -#define ESP_ERR_NVS_INVALID_NAME (ESP_ERR_NVS_BASE + 0x06) /*!< Namespace name doesn’t satisfy constraints */ -#define ESP_ERR_NVS_INVALID_HANDLE (ESP_ERR_NVS_BASE + 0x07) /*!< Handle has been closed or is NULL */ -#define ESP_ERR_NVS_REMOVE_FAILED (ESP_ERR_NVS_BASE + 0x08) /*!< The value wasn’t updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn’t fail again. */ -#define ESP_ERR_NVS_KEY_TOO_LONG (ESP_ERR_NVS_BASE + 0x09) /*!< Key name is too long */ -#define ESP_ERR_NVS_PAGE_FULL (ESP_ERR_NVS_BASE + 0x0a) /*!< Internal error; never returned by nvs_ API functions */ -#define ESP_ERR_NVS_INVALID_STATE (ESP_ERR_NVS_BASE + 0x0b) /*!< NVS is in an inconsistent state due to a previous error. Call nvs_flash_init and nvs_open again, then retry. */ -#define ESP_ERR_NVS_INVALID_LENGTH (ESP_ERR_NVS_BASE + 0x0c) /*!< String or blob length is not sufficient to store data */ -#define ESP_ERR_NVS_NO_FREE_PAGES (ESP_ERR_NVS_BASE + 0x0d) /*!< NVS partition doesn't contain any empty pages. This may happen if NVS partition was truncated. Erase the whole partition and call nvs_flash_init again. */ -#define ESP_ERR_NVS_VALUE_TOO_LONG (ESP_ERR_NVS_BASE + 0x0e) /*!< String or blob length is longer than supported by the implementation */ -#define ESP_ERR_NVS_PART_NOT_FOUND (ESP_ERR_NVS_BASE + 0x0f) /*!< Partition with specified name is not found in the partition table */ +#define ESP_ERR_NVS_BASE 0x1100 /*!< Starting number of error codes */ +#define ESP_ERR_NVS_NOT_INITIALIZED (ESP_ERR_NVS_BASE + 0x01) /*!< The storage driver is not initialized */ +#define ESP_ERR_NVS_NOT_FOUND (ESP_ERR_NVS_BASE + 0x02) /*!< Id namespace doesn’t exist yet and mode is NVS_READONLY */ +#define ESP_ERR_NVS_TYPE_MISMATCH (ESP_ERR_NVS_BASE + 0x03) /*!< The type of set or get operation doesn't match the type of value stored in NVS */ +#define ESP_ERR_NVS_READ_ONLY (ESP_ERR_NVS_BASE + 0x04) /*!< Storage handle was opened as read only */ +#define ESP_ERR_NVS_NOT_ENOUGH_SPACE (ESP_ERR_NVS_BASE + 0x05) /*!< There is not enough space in the underlying storage to save the value */ +#define ESP_ERR_NVS_INVALID_NAME (ESP_ERR_NVS_BASE + 0x06) /*!< Namespace name doesn’t satisfy constraints */ +#define ESP_ERR_NVS_INVALID_HANDLE (ESP_ERR_NVS_BASE + 0x07) /*!< Handle has been closed or is NULL */ +#define ESP_ERR_NVS_REMOVE_FAILED (ESP_ERR_NVS_BASE + 0x08) /*!< The value wasn’t updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn’t fail again. */ +#define ESP_ERR_NVS_KEY_TOO_LONG (ESP_ERR_NVS_BASE + 0x09) /*!< Key name is too long */ +#define ESP_ERR_NVS_PAGE_FULL (ESP_ERR_NVS_BASE + 0x0a) /*!< Internal error; never returned by nvs API functions */ +#define ESP_ERR_NVS_INVALID_STATE (ESP_ERR_NVS_BASE + 0x0b) /*!< NVS is in an inconsistent state due to a previous error. Call nvs_flash_init and nvs_open again, then retry. */ +#define ESP_ERR_NVS_INVALID_LENGTH (ESP_ERR_NVS_BASE + 0x0c) /*!< String or blob length is not sufficient to store data */ +#define ESP_ERR_NVS_NO_FREE_PAGES (ESP_ERR_NVS_BASE + 0x0d) /*!< NVS partition doesn't contain any empty pages. This may happen if NVS partition was truncated. Erase the whole partition and call nvs_flash_init again. */ +#define ESP_ERR_NVS_VALUE_TOO_LONG (ESP_ERR_NVS_BASE + 0x0e) /*!< String or blob length is longer than supported by the implementation */ +#define ESP_ERR_NVS_PART_NOT_FOUND (ESP_ERR_NVS_BASE + 0x0f) /*!< Partition with specified name is not found in the partition table */ + +#define ESP_ERR_NVS_NEW_VERSION_FOUND (ESP_ERR_NVS_BASE + 0x10) /*!< NVS partition contains data in new format and cannot be recognized by this version of code */ +#define ESP_ERR_NVS_XTS_ENCR_FAILED (ESP_ERR_NVS_BASE + 0x11) /*!< XTS encryption failed while writing NVS entry */ +#define ESP_ERR_NVS_XTS_DECR_FAILED (ESP_ERR_NVS_BASE + 0x12) /*!< XTS decryption failed while reading NVS entry */ +#define ESP_ERR_NVS_XTS_CFG_FAILED (ESP_ERR_NVS_BASE + 0x13) /*!< XTS configuration setting failed */ +#define ESP_ERR_NVS_XTS_CFG_NOT_FOUND (ESP_ERR_NVS_BASE + 0x14) /*!< XTS configuration not found */ +#define ESP_ERR_NVS_ENCR_NOT_SUPPORTED (ESP_ERR_NVS_BASE + 0x15) /*!< NVS encryption is not supported in this version */ +#define ESP_ERR_NVS_KEYS_NOT_INITIALIZED (ESP_ERR_NVS_BASE + 0x16) /*!< NVS key partition is uninitialized */ +#define ESP_ERR_NVS_CORRUPT_KEY_PART (ESP_ERR_NVS_BASE + 0x17) /*!< NVS key partition is corrupt */ + #define NVS_DEFAULT_PART_NAME "nvs" /*!< Default partition name of the NVS partition in the partition table */ /** @@ -126,7 +136,7 @@ esp_err_t nvs_open_from_partition(const char *part_name, const char* name, nvs_o * 15 characters. Shouldn't be empty. * @param[in] value The value to set. * For strings, the maximum length (including null character) is - * 1984 bytes. + * 4000 bytes. * * @return * - ESP_OK if value was set successfully @@ -163,7 +173,8 @@ esp_err_t nvs_set_str (nvs_handle handle, const char* key, const char* value); * @param[in] key Key name. Maximal length is 15 characters. Shouldn't be empty. * @param[in] value The value to set. * @param[in] length length of binary value to set, in bytes; Maximum length is - * 1984 bytes. + * 508000 bytes or (97.6% of the partition size - 4000) bytes + * whichever is lower. * * @return * - ESP_OK if value was set successfully @@ -356,6 +367,88 @@ esp_err_t nvs_commit(nvs_handle handle); */ void nvs_close(nvs_handle handle); +/** + * @note Info about storage space NVS. + */ +typedef struct { + size_t used_entries; /**< Amount of used entries. */ + size_t free_entries; /**< Amount of free entries. */ + size_t total_entries; /**< Amount all available entries. */ + size_t namespace_count; /**< Amount name space. */ +} nvs_stats_t; + +/** + * @brief Fill structure nvs_stats_t. It provides info about used memory the partition. + * + * This function calculates to runtime the number of used entries, free entries, total entries, + * and amount namespace in partition. + * + * \code{c} + * // Example of nvs_get_stats() to get the number of used entries and free entries: + * nvs_stats_t nvs_stats; + * nvs_get_stats(NULL, &nvs_stats); + * printf("Count: UsedEntries = (%d), FreeEntries = (%d), AllEntries = (%d)\n", + nvs_stats.used_entries, nvs_stats.free_entries, nvs_stats.total_entries); + * \endcode + * + * @param[in] part_name Partition name NVS in the partition table. + * If pass a NULL than will use NVS_DEFAULT_PART_NAME ("nvs"). + * + * @param[out] nvs_stats Returns filled structure nvs_states_t. + * It provides info about used memory the partition. + * + * + * @return + * - ESP_OK if the changes have been written successfully. + * Return param nvs_stats will be filled. + * - ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "name" is not found. + * Return param nvs_stats will be filled 0. + * - ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. + * Return param nvs_stats will be filled 0. + * - ESP_ERR_INVALID_ARG if nvs_stats equal to NULL. + * - ESP_ERR_INVALID_STATE if there is page with the status of INVALID. + * Return param nvs_stats will be filled not with correct values because + * not all pages will be counted. Counting will be interrupted at the first INVALID page. + */ +esp_err_t nvs_get_stats(const char* part_name, nvs_stats_t* nvs_stats); + +/** + * @brief Calculate all entries in a namespace. + * + * Note that to find out the total number of records occupied by the namespace, + * add one to the returned value used_entries (if err is equal to ESP_OK). + * Because the name space entry takes one entry. + * + * \code{c} + * // Example of nvs_get_used_entry_count() to get amount of all key-value pairs in one namespace: + * nvs_handle handle; + * nvs_open("namespace1", NVS_READWRITE, &handle); + * ... + * size_t used_entries; + * size_t total_entries_namespace; + * if(nvs_get_used_entry_count(handle, &used_entries) == ESP_OK){ + * // the total number of records occupied by the namespace + * total_entries_namespace = used_entries + 1; + * } + * \endcode + * + * @param[in] handle Handle obtained from nvs_open function. + * + * @param[out] used_entries Returns amount of used entries from a namespace. + * + * + * @return + * - ESP_OK if the changes have been written successfully. + * Return param used_entries will be filled valid value. + * - ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. + * Return param used_entries will be filled 0. + * - ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL. + * Return param used_entries will be filled 0. + * - ESP_ERR_INVALID_ARG if nvs_stats equal to NULL. + * - Other error codes from the underlying storage driver. + * Return param used_entries will be filled 0. + */ +esp_err_t nvs_get_used_entry_count(nvs_handle handle, size_t* used_entries); #ifdef __cplusplus } // extern "C" diff --git a/tools/sdk/include/nvs_flash/nvs_flash.h b/tools/sdk/include/nvs_flash/nvs_flash.h index a7ef7f4511e..55b218ec56e 100644 --- a/tools/sdk/include/nvs_flash/nvs_flash.h +++ b/tools/sdk/include/nvs_flash/nvs_flash.h @@ -19,6 +19,18 @@ extern "C" { #endif #include "nvs.h" +#include "esp_partition.h" + + +#define NVS_KEY_SIZE 32 // AES-256 + +/** + * @brief Key for encryption and decryption + */ +typedef struct { + uint8_t eky[NVS_KEY_SIZE]; /*!< XTS encryption and decryption key*/ + uint8_t tky[NVS_KEY_SIZE]; /*!< XTS tweak key */ +} nvs_sec_cfg_t; /** * @brief Initialize the default NVS partition. @@ -99,6 +111,81 @@ esp_err_t nvs_flash_erase(void); */ esp_err_t nvs_flash_erase_partition(const char *part_name); + +/** + * @brief Initialize the default NVS partition. + * + * This API initialises the default NVS partition. The default NVS partition + * is the one that is labeled "nvs" in the partition table. + * + * @param[in] cfg Security configuration (keys) to be used for NVS encryption/decryption. + * If cfg is NULL, no encryption is used. + * + * @return + * - ESP_OK if storage was successfully initialized. + * - ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages + * (which may happen if NVS partition was truncated) + * - ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table + * - one of the error codes from the underlying flash storage driver + */ +esp_err_t nvs_flash_secure_init(nvs_sec_cfg_t* cfg); + +/** + * @brief Initialize NVS flash storage for the specified partition. + * + * @param[in] partition_label Label of the partition. Note that internally a reference to + * passed value is kept and it should be accessible for future operations + * + * @param[in] cfg Security configuration (keys) to be used for NVS encryption/decryption. + * If cfg is null, no encryption/decryption is used. + * @return + * - ESP_OK if storage was successfully initialized. + * - ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages + * (which may happen if NVS partition was truncated) + * - ESP_ERR_NOT_FOUND if specified partition is not found in the partition table + * - one of the error codes from the underlying flash storage driver + */ +esp_err_t nvs_flash_secure_init_partition(const char *partition_label, nvs_sec_cfg_t* cfg); + +/** + * @brief Generate and store NVS keys in the provided esp partition + * + * @param[in] partition Pointer to partition structure obtained using + * esp_partition_find_first or esp_partition_get. + * Must be non-NULL. + * @param[out] cfg Pointer to nvs security configuration structure. + * Pointer must be non-NULL. + * Generated keys will be populated in this structure. + * + * + * @return + * -ESP_OK, if cfg was read successfully; + * -or error codes from esp_partition_write/erase APIs. + */ + +esp_err_t nvs_flash_generate_keys(const esp_partition_t* partition, nvs_sec_cfg_t* cfg); + + +/** + * @brief Read NVS security configuration from a partition. + * + * @param[in] partition Pointer to partition structure obtained using + * esp_partition_find_first or esp_partition_get. + * Must be non-NULL. + * @param[out] cfg Pointer to nvs security configuration structure. + * Pointer must be non-NULL. + * + * @note Provided parition is assumed to be marked 'encrypted'. + * + * @return + * -ESP_OK, if cfg was read successfully; + * -ESP_ERR_NVS_KEYS_NOT_INITIALIZED, if the partition is not yet written with keys. + * -ESP_ERR_NVS_CORRUPT_KEY_PART, if the partition containing keys is found to be corrupt + * -or error codes from esp_partition_read API. + */ + +esp_err_t nvs_flash_read_security_cfg(const esp_partition_t* partition, nvs_sec_cfg_t* cfg); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/openssl/internal/x509_vfy.h b/tools/sdk/include/openssl/internal/x509_vfy.h index d5b0d1a2132..fec367d5fd8 100644 --- a/tools/sdk/include/openssl/internal/x509_vfy.h +++ b/tools/sdk/include/openssl/internal/x509_vfy.h @@ -1,111 +1,111 @@ -// 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 _X509_VFY_H_ -#define _X509_VFY_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#define X509_V_OK 0 -#define X509_V_ERR_UNSPECIFIED 1 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 -#define X509_V_ERR_UNABLE_TO_GET_CRL 3 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 -#define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 -#define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 -#define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 -#define X509_V_ERR_CERT_NOT_YET_VALID 9 -#define X509_V_ERR_CERT_HAS_EXPIRED 10 -#define X509_V_ERR_CRL_NOT_YET_VALID 11 -#define X509_V_ERR_CRL_HAS_EXPIRED 12 -#define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 -#define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 -#define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 -#define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 -#define X509_V_ERR_OUT_OF_MEM 17 -#define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 -#define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 -#define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 -#define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 -#define X509_V_ERR_CERT_REVOKED 23 -#define X509_V_ERR_INVALID_CA 24 -#define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 -#define X509_V_ERR_INVALID_PURPOSE 26 -#define X509_V_ERR_CERT_UNTRUSTED 27 -#define X509_V_ERR_CERT_REJECTED 28 -/* These are 'informational' when looking for issuer cert */ -#define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 -#define X509_V_ERR_AKID_SKID_MISMATCH 30 -#define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 -#define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 -#define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 -#define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 -#define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 -#define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 -#define X509_V_ERR_INVALID_NON_CA 37 -#define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 -#define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 -#define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 -#define X509_V_ERR_INVALID_EXTENSION 41 -#define X509_V_ERR_INVALID_POLICY_EXTENSION 42 -#define X509_V_ERR_NO_EXPLICIT_POLICY 43 -#define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 -#define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 -#define X509_V_ERR_UNNESTED_RESOURCE 46 -#define X509_V_ERR_PERMITTED_VIOLATION 47 -#define X509_V_ERR_EXCLUDED_VIOLATION 48 -#define X509_V_ERR_SUBTREE_MINMAX 49 -/* The application is not happy */ -#define X509_V_ERR_APPLICATION_VERIFICATION 50 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 -#define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 -#define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 -/* Another issuer check debug option */ -#define X509_V_ERR_PATH_LOOP 55 -/* Suite B mode algorithm violation */ -#define X509_V_ERR_SUITE_B_INVALID_VERSION 56 -#define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 -#define X509_V_ERR_SUITE_B_INVALID_CURVE 58 -#define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 -#define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 -#define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61 -/* Host, email and IP check errors */ -#define X509_V_ERR_HOSTNAME_MISMATCH 62 -#define X509_V_ERR_EMAIL_MISMATCH 63 -#define X509_V_ERR_IP_ADDRESS_MISMATCH 64 -/* DANE TLSA errors */ -#define X509_V_ERR_DANE_NO_MATCH 65 -/* security level errors */ -#define X509_V_ERR_EE_KEY_TOO_SMALL 66 -#define X509_V_ERR_CA_KEY_TOO_SMALL 67 -#define X509_V_ERR_CA_MD_TOO_WEAK 68 -/* Caller error */ -#define X509_V_ERR_INVALID_CALL 69 -/* Issuer lookup error */ -#define X509_V_ERR_STORE_LOOKUP 70 -/* Certificate transparency */ -#define X509_V_ERR_NO_VALID_SCTS 71 - -#define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72 - -#ifdef __cplusplus -} -#endif - -#endif +// 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 _X509_VFY_H_ +#define _X509_VFY_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define X509_V_OK 0 +#define X509_V_ERR_UNSPECIFIED 1 +#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 +#define X509_V_ERR_UNABLE_TO_GET_CRL 3 +#define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 +#define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 +#define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 +#define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 +#define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 +#define X509_V_ERR_CERT_NOT_YET_VALID 9 +#define X509_V_ERR_CERT_HAS_EXPIRED 10 +#define X509_V_ERR_CRL_NOT_YET_VALID 11 +#define X509_V_ERR_CRL_HAS_EXPIRED 12 +#define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 +#define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 +#define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 +#define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 +#define X509_V_ERR_OUT_OF_MEM 17 +#define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 +#define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 +#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 +#define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 +#define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 +#define X509_V_ERR_CERT_REVOKED 23 +#define X509_V_ERR_INVALID_CA 24 +#define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 +#define X509_V_ERR_INVALID_PURPOSE 26 +#define X509_V_ERR_CERT_UNTRUSTED 27 +#define X509_V_ERR_CERT_REJECTED 28 +/* These are 'informational' when looking for issuer cert */ +#define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 +#define X509_V_ERR_AKID_SKID_MISMATCH 30 +#define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 +#define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 +#define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 +#define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 +#define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 +#define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 +#define X509_V_ERR_INVALID_NON_CA 37 +#define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 +#define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 +#define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 +#define X509_V_ERR_INVALID_EXTENSION 41 +#define X509_V_ERR_INVALID_POLICY_EXTENSION 42 +#define X509_V_ERR_NO_EXPLICIT_POLICY 43 +#define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 +#define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 +#define X509_V_ERR_UNNESTED_RESOURCE 46 +#define X509_V_ERR_PERMITTED_VIOLATION 47 +#define X509_V_ERR_EXCLUDED_VIOLATION 48 +#define X509_V_ERR_SUBTREE_MINMAX 49 +/* The application is not happy */ +#define X509_V_ERR_APPLICATION_VERIFICATION 50 +#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 +#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 +#define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 +#define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 +/* Another issuer check debug option */ +#define X509_V_ERR_PATH_LOOP 55 +/* Suite B mode algorithm violation */ +#define X509_V_ERR_SUITE_B_INVALID_VERSION 56 +#define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 +#define X509_V_ERR_SUITE_B_INVALID_CURVE 58 +#define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 +#define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 +#define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61 +/* Host, email and IP check errors */ +#define X509_V_ERR_HOSTNAME_MISMATCH 62 +#define X509_V_ERR_EMAIL_MISMATCH 63 +#define X509_V_ERR_IP_ADDRESS_MISMATCH 64 +/* DANE TLSA errors */ +#define X509_V_ERR_DANE_NO_MATCH 65 +/* security level errors */ +#define X509_V_ERR_EE_KEY_TOO_SMALL 66 +#define X509_V_ERR_CA_KEY_TOO_SMALL 67 +#define X509_V_ERR_CA_MD_TOO_WEAK 68 +/* Caller error */ +#define X509_V_ERR_INVALID_CALL 69 +/* Issuer lookup error */ +#define X509_V_ERR_STORE_LOOKUP 70 +/* Certificate transparency */ +#define X509_V_ERR_NO_VALID_SCTS 71 + +#define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/openssl/openssl/ssl.h b/tools/sdk/include/openssl/openssl/ssl.h old mode 100755 new mode 100644 index 95fd6e9eb94..88d7bca69dc --- a/tools/sdk/include/openssl/openssl/ssl.h +++ b/tools/sdk/include/openssl/openssl/ssl.h @@ -1,1822 +1,1822 @@ -// 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 _SSL_H_ -#define _SSL_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#include "internal/ssl_x509.h" -#include "internal/ssl_pkey.h" - -/* -{ -*/ - -#define SSL_CB_ALERT 0x4000 - -#define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT (1 << 0) -#define X509_CHECK_FLAG_NO_WILDCARDS (1 << 1) -#define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS (1 << 2) -#define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS (1 << 3) -#define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS (1 << 4) - -/** - * @brief create a SSL context - * - * @param method - the SSL context method point - * - * @return the context point - */ -SSL_CTX* SSL_CTX_new(const SSL_METHOD *method); - -/** - * @brief free a SSL context - * - * @param method - the SSL context point - * - * @return none - */ -void SSL_CTX_free(SSL_CTX *ctx); - -/** - * @brief create a SSL - * - * @param ctx - the SSL context point - * - * @return the SSL point - */ -SSL* SSL_new(SSL_CTX *ctx); - -/** - * @brief free the SSL - * - * @param ssl - the SSL point - * - * @return none - */ -void SSL_free(SSL *ssl); - -/** - * @brief connect to the remote SSL server - * - * @param ssl - the SSL point - * - * @return result - * 1 : OK - * -1 : failed - */ -int SSL_connect(SSL *ssl); - -/** - * @brief accept the remote connection - * - * @param ssl - the SSL point - * - * @return result - * 1 : OK - * -1 : failed - */ -int SSL_accept(SSL *ssl); - -/** - * @brief read data from to remote - * - * @param ssl - the SSL point which has been connected - * @param buffer - the received data buffer point - * @param len - the received data length - * - * @return result - * > 0 : OK, and return received data bytes - * = 0 : connection is closed - * < 0 : an error catch - */ -int SSL_read(SSL *ssl, void *buffer, int len); - -/** - * @brief send the data to remote - * - * @param ssl - the SSL point which has been connected - * @param buffer - the send data buffer point - * @param len - the send data length - * - * @return result - * > 0 : OK, and return sent data bytes - * = 0 : connection is closed - * < 0 : an error catch - */ -int SSL_write(SSL *ssl, const void *buffer, int len); - -/** - * @brief get the verifying result of the SSL certification - * - * @param ssl - the SSL point - * - * @return the result of verifying - */ -long SSL_get_verify_result(const SSL *ssl); - -/** - * @brief shutdown the connection - * - * @param ssl - the SSL point - * - * @return result - * 1 : OK - * 0 : shutdown is not finished - * -1 : an error catch - */ -int SSL_shutdown(SSL *ssl); - -/** - * @brief bind the socket file description into the SSL - * - * @param ssl - the SSL point - * @param fd - socket handle - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_set_fd(SSL *ssl, int fd); - -/** - * @brief Set the hostname for SNI - * - * @param ssl - the SSL context point - * @param hostname - pointer to the hostname - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_set_tlsext_host_name(SSL* ssl, const char *hostname); - -/** - * @brief These functions load the private key into the SSL_CTX or SSL object - * - * @param ctx - the SSL context point - * @param pkey - private key object point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey); - -/** - * @brief These functions load the certification into the SSL_CTX or SSL object - * - * @param ctx - the SSL context point - * @param pkey - certification object point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the SSLV2.3 version SSL context client method - */ -const SSL_METHOD* SSLv23_client_method(void); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the TLSV1.0 version SSL context client method - */ -const SSL_METHOD* TLSv1_client_method(void); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the SSLV1.0 version SSL context client method - */ -const SSL_METHOD* SSLv3_client_method(void); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the TLSV1.1 version SSL context client method - */ -const SSL_METHOD* TLSv1_1_client_method(void); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the TLSV1.2 version SSL context client method - */ -const SSL_METHOD* TLSv1_2_client_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLS any version SSL context client method - */ -const SSL_METHOD* TLS_client_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the SSLV2.3 version SSL context server method - */ -const SSL_METHOD* SSLv23_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLSV1.1 version SSL context server method - */ -const SSL_METHOD* TLSv1_1_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLSV1.2 version SSL context server method - */ -const SSL_METHOD* TLSv1_2_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLSV1.0 version SSL context server method - */ -const SSL_METHOD* TLSv1_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the SSLV3.0 version SSL context server method - */ -const SSL_METHOD* SSLv3_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLS any version SSL context server method - */ -const SSL_METHOD* TLS_server_method(void); - - -/** - * @brief set the SSL context ALPN select callback function - * - * @param ctx - SSL context point - * @param cb - ALPN select callback function - * @param arg - ALPN select callback function entry private data point - * - * @return none - */ -void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, - int (*cb) (SSL *ssl, - const unsigned char **out, - unsigned char *outlen, - const unsigned char *in, - unsigned int inlen, - void *arg), - void *arg); - - -/** - * @brief set the SSL context ALPN select protocol - * - * @param ctx - SSL context point - * @param protos - ALPN protocol name - * @param protos_len - ALPN protocol name bytes - * - * @return result - * 0 : OK - * 1 : failed - */ -int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos, unsigned int protos_len); - -/** - * @brief set the SSL context next ALPN select callback function - * - * @param ctx - SSL context point - * @param cb - ALPN select callback function - * @param arg - ALPN select callback function entry private data point - * - * @return none - */ -void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, - int (*cb) (SSL *ssl, - unsigned char **out, - unsigned char *outlen, - const unsigned char *in, - unsigned int inlen, - void *arg), - void *arg); - -/** - * @brief get SSL error code - * - * @param ssl - SSL point - * @param ret_code - SSL return code - * - * @return SSL error number - */ -int SSL_get_error(const SSL *ssl, int ret_code); - -/** - * @brief clear the SSL error code - * - * @param none - * - * @return none - */ -void ERR_clear_error(void); - -/** - * @brief get the current SSL error code - * - * @param none - * - * @return current SSL error number - */ -int ERR_get_error(void); - -/** - * @brief register the SSL error strings - * - * @param none - * - * @return none - */ -void ERR_load_SSL_strings(void); - -/** - * @brief initialize the SSL library - * - * @param none - * - * @return none - */ -void SSL_library_init(void); - -/** - * @brief generates a human-readable string representing the error code e - * and store it into the "ret" point memory - * - * @param e - error code - * @param ret - memory point to store the string - * - * @return the result string point - */ -char *ERR_error_string(unsigned long e, char *ret); - -/** - * @brief add the SSL context option - * - * @param ctx - SSL context point - * @param opt - new SSL context option - * - * @return the SSL context option - */ -unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long opt); - -/** - * @brief add the SSL context mode - * - * @param ctx - SSL context point - * @param mod - new SSL context mod - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_mode(SSL_CTX *ctx, int mod); - -/* -} -*/ - -/** - * @brief perform the SSL handshake - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - * -1 : a error catch - */ -int SSL_do_handshake(SSL *ssl); - -/** - * @brief get the SSL current version - * - * @param ssl - SSL point - * - * @return the version string - */ -const char *SSL_get_version(const SSL *ssl); - -/** - * @brief set the SSL context version - * - * @param ctx - SSL context point - * @param meth - SSL method point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth); - -/** - * @brief get the bytes numbers which are to be read - * - * @param ssl - SSL point - * - * @return bytes number - */ -int SSL_pending(const SSL *ssl); - -/** - * @brief check if SSL want nothing - * - * @param ssl - SSL point - * - * @return result - * 0 : false - * 1 : true - */ -int SSL_want_nothing(const SSL *ssl); - -/** - * @brief check if SSL want to read - * - * @param ssl - SSL point - * - * @return result - * 0 : false - * 1 : true - */ -int SSL_want_read(const SSL *ssl); - -/** - * @brief check if SSL want to write - * - * @param ssl - SSL point - * - * @return result - * 0 : false - * 1 : true - */ -int SSL_want_write(const SSL *ssl); - -/** - * @brief get the SSL context current method - * - * @param ctx - SSL context point - * - * @return the SSL context current method - */ -const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx); - -/** - * @brief get the SSL current method - * - * @param ssl - SSL point - * - * @return the SSL current method - */ -const SSL_METHOD *SSL_get_ssl_method(SSL *ssl); - -/** - * @brief set the SSL method - * - * @param ssl - SSL point - * @param meth - SSL method point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_set_ssl_method(SSL *ssl, const SSL_METHOD *method); - -/** - * @brief add CA client certification into the SSL - * - * @param ssl - SSL point - * @param x - CA certification point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_add_client_CA(SSL *ssl, X509 *x); - -/** - * @brief add CA client certification into the SSL context - * - * @param ctx - SSL context point - * @param x - CA certification point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x); - -/** - * @brief set the SSL CA certification list - * - * @param ssl - SSL point - * @param name_list - CA certification list - * - * @return none - */ -void SSL_set_client_CA_list(SSL *ssl, STACK_OF(X509_NAME) *name_list); - -/** - * @brief set the SSL context CA certification list - * - * @param ctx - SSL context point - * @param name_list - CA certification list - * - * @return none - */ -void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list); - -/** - * @briefget the SSL CA certification list - * - * @param ssl - SSL point - * - * @return CA certification list - */ -STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *ssl); - -/** - * @brief get the SSL context CA certification list - * - * @param ctx - SSL context point - * - * @return CA certification list - */ -STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx); - -/** - * @brief get the SSL certification point - * - * @param ssl - SSL point - * - * @return SSL certification point - */ -X509 *SSL_get_certificate(const SSL *ssl); - -/** - * @brief get the SSL private key point - * - * @param ssl - SSL point - * - * @return SSL private key point - */ -EVP_PKEY *SSL_get_privatekey(const SSL *ssl); - -/** - * @brief set the SSL information callback function - * - * @param ssl - SSL point - * @param cb - information callback function - * - * @return none - */ -void SSL_set_info_callback(SSL *ssl, void (*cb) (const SSL *ssl, int type, int val)); - -/** - * @brief get the SSL state - * - * @param ssl - SSL point - * - * @return SSL state - */ -OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl); - -/** - * @brief set the SSL context read buffer length - * - * @param ctx - SSL context point - * @param len - read buffer length - * - * @return none - */ -void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len); - -/** - * @brief set the SSL read buffer length - * - * @param ssl - SSL point - * @param len - read buffer length - * - * @return none - */ -void SSL_set_default_read_buffer_len(SSL *ssl, size_t len); - -/** - * @brief set the SSL security level - * - * @param ssl - SSL point - * @param level - security level - * - * @return none - */ -void SSL_set_security_level(SSL *ssl, int level); - -/** - * @brief get the SSL security level - * - * @param ssl - SSL point - * - * @return security level - */ -int SSL_get_security_level(const SSL *ssl); - -/** - * @brief get the SSL verifying mode of the SSL context - * - * @param ctx - SSL context point - * - * @return verifying mode - */ -int SSL_CTX_get_verify_mode(const SSL_CTX *ctx); - -/** - * @brief get the SSL verifying depth of the SSL context - * - * @param ctx - SSL context point - * - * @return verifying depth - */ -int SSL_CTX_get_verify_depth(const SSL_CTX *ctx); - -/** - * @brief set the SSL context verifying of the SSL context - * - * @param ctx - SSL context point - * @param mode - verifying mode - * @param verify_callback - verifying callback function - * - * @return none - */ -void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); - -/** - * @brief set the SSL verifying of the SSL context - * - * @param ctx - SSL point - * @param mode - verifying mode - * @param verify_callback - verifying callback function - * - * @return none - */ -void SSL_set_verify(SSL *s, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); - -/** - * @brief set the SSL verify depth of the SSL context - * - * @param ctx - SSL context point - * @param depth - verifying depth - * - * @return none - */ -void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); - -/** - * @brief certification verifying callback function - * - * @param preverify_ok - verifying result - * @param x509_ctx - X509 certification point - * - * @return verifying result - */ -int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx); - -/** - * @brief set the session timeout time - * - * @param ctx - SSL context point - * @param t - new session timeout time - * - * @return old session timeout time - */ -long SSL_CTX_set_timeout(SSL_CTX *ctx, long t); - -/** - * @brief get the session timeout time - * - * @param ctx - SSL context point - * - * @return current session timeout time - */ -long SSL_CTX_get_timeout(const SSL_CTX *ctx); - -/** - * @brief set the SSL context cipher through the list string - * - * @param ctx - SSL context point - * @param str - cipher controller list string - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str); - -/** - * @brief set the SSL cipher through the list string - * - * @param ssl - SSL point - * @param str - cipher controller list string - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_set_cipher_list(SSL *ssl, const char *str); - -/** - * @brief get the SSL cipher list string - * - * @param ssl - SSL point - * - * @return cipher controller list string - */ -const char *SSL_get_cipher_list(const SSL *ssl, int n); - -/** - * @brief get the SSL cipher - * - * @param ssl - SSL point - * - * @return current cipher - */ -const SSL_CIPHER *SSL_get_current_cipher(const SSL *ssl); - -/** - * @brief get the SSL cipher string - * - * @param ssl - SSL point - * - * @return cipher string - */ -const char *SSL_get_cipher(const SSL *ssl); - -/** - * @brief get the SSL context object X509 certification storage - * - * @param ctx - SSL context point - * - * @return x509 certification storage - */ -X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx); - -/** - * @brief set the SSL context object X509 certification store - * - * @param ctx - SSL context point - * @param store - X509 certification store - * - * @return none - */ -void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store); - -/** - * @brief get the SSL specifical statement - * - * @param ssl - SSL point - * - * @return specifical statement - */ -int SSL_want(const SSL *ssl); - -/** - * @brief check if the SSL is SSL_X509_LOOKUP state - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_want_x509_lookup(const SSL *ssl); - -/** - * @brief reset the SSL - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_clear(SSL *ssl); - -/** - * @brief get the socket handle of the SSL - * - * @param ssl - SSL point - * - * @return result - * >= 0 : yes, and return socket handle - * < 0 : a error catch - */ -int SSL_get_fd(const SSL *ssl); - -/** - * @brief get the read only socket handle of the SSL - * - * @param ssl - SSL point - * - * @return result - * >= 0 : yes, and return socket handle - * < 0 : a error catch - */ -int SSL_get_rfd(const SSL *ssl); - -/** - * @brief get the write only socket handle of the SSL - * - * @param ssl - SSL point - * - * @return result - * >= 0 : yes, and return socket handle - * < 0 : a error catch - */ -int SSL_get_wfd(const SSL *ssl); - -/** - * @brief set the SSL if we can read as many as data - * - * @param ssl - SSL point - * @param yes - enable the function - * - * @return none - */ -void SSL_set_read_ahead(SSL *s, int yes); - -/** - * @brief set the SSL context if we can read as many as data - * - * @param ctx - SSL context point - * @param yes - enbale the function - * - * @return none - */ -void SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes); - -/** - * @brief get the SSL ahead signal if we can read as many as data - * - * @param ssl - SSL point - * - * @return SSL context ahead signal - */ -int SSL_get_read_ahead(const SSL *ssl); - -/** - * @brief get the SSL context ahead signal if we can read as many as data - * - * @param ctx - SSL context point - * - * @return SSL context ahead signal - */ -long SSL_CTX_get_read_ahead(SSL_CTX *ctx); - -/** - * @brief check if some data can be read - * - * @param ssl - SSL point - * - * @return - * 1 : there are bytes to be read - * 0 : no data - */ -int SSL_has_pending(const SSL *ssl); - -/** - * @brief load the X509 certification into SSL context - * - * @param ctx - SSL context point - * @param x - X509 certification point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);//loads the certificate x into ctx - -/** - * @brief load the ASN1 certification into SSL context - * - * @param ctx - SSL context point - * @param len - certification length - * @param d - data point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d); - -/** - * @brief load the certification file into SSL context - * - * @param ctx - SSL context point - * @param file - certification file name - * @param type - certification encoding type - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type); - -/** - * @brief load the certification chain file into SSL context - * - * @param ctx - SSL context point - * @param file - certification chain file name - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file); - - -/** - * @brief load the ASN1 private key into SSL context - * - * @param ctx - SSL context point - * @param d - data point - * @param len - private key length - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, const unsigned char *d, long len);//adds the private key of type pk stored at memory location d (length len) to ctx - -/** - * @brief load the private key file into SSL context - * - * @param ctx - SSL context point - * @param file - private key file name - * @param type - private key encoding type - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type); - -/** - * @brief load the RSA private key into SSL context - * - * @param ctx - SSL context point - * @param x - RSA private key point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa); - -/** - * @brief load the RSA ASN1 private key into SSL context - * - * @param ctx - SSL context point - * @param d - data point - * @param len - RSA private key length - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len); - -/** - * @brief load the RSA private key file into SSL context - * - * @param ctx - SSL context point - * @param file - RSA private key file name - * @param type - private key encoding type - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type); - - -/** - * @brief check if the private key and certification is matched - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_check_private_key(const SSL_CTX *ctx); - -/** - * @brief set the SSL context server information - * - * @param ctx - SSL context point - * @param serverinfo - server information string - * @param serverinfo_length - server information length - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, size_t serverinfo_length); - -/** - * @brief load the SSL context server infomation file into SSL context - * - * @param ctx - SSL context point - * @param file - server information file - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file); - -/** - * @brief SSL select next function - * - * @param out - point of output data point - * @param outlen - output data length - * @param in - input data - * @param inlen - input data length - * @param client - client data point - * @param client_len -client data length - * - * @return NPN state - * OPENSSL_NPN_UNSUPPORTED : not support - * OPENSSL_NPN_NEGOTIATED : negotiated - * OPENSSL_NPN_NO_OVERLAP : no overlap - */ -int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, - const unsigned char *in, unsigned int inlen, - const unsigned char *client, unsigned int client_len); - -/** - * @brief load the extra certification chain into the SSL context - * - * @param ctx - SSL context point - * @param x509 - X509 certification - * - * @return result - * 1 : OK - * 0 : failed - */ -long SSL_CTX_add_extra_chain_cert(SSL_CTX *ctx, X509 *); - -/** - * @brief control the SSL context - * - * @param ctx - SSL context point - * @param cmd - command - * @param larg - parameter length - * @param parg - parameter point - * - * @return result - * 1 : OK - * 0 : failed - */ -long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, char *parg); - -/** - * @brief get the SSL context cipher - * - * @param ctx - SSL context point - * - * @return SSL context cipher - */ -STACK *SSL_CTX_get_ciphers(const SSL_CTX *ctx); - -/** - * @brief check if the SSL context can read as many as data - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -long SSL_CTX_get_default_read_ahead(SSL_CTX *ctx); - -/** - * @brief get the SSL context extra data - * - * @param ctx - SSL context point - * @param idx - index - * - * @return data point - */ -char *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx); - -/** - * @brief get the SSL context quiet shutdown option - * - * @param ctx - SSL context point - * - * @return quiet shutdown option - */ -int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx); - -/** - * @brief load the SSL context CA file - * - * @param ctx - SSL context point - * @param CAfile - CA certification file - * @param CApath - CA certification file path - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, const char *CApath); - -/** - * @brief add SSL context reference count by '1' - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_up_ref(SSL_CTX *ctx); - -/** - * @brief set SSL context application private data - * - * @param ctx - SSL context point - * @param arg - private data - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_app_data(SSL_CTX *ctx, void *arg); - -/** - * @brief set SSL context client certification callback function - * - * @param ctx - SSL context point - * @param cb - callback function - * - * @return none - */ -void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)); - -/** - * @brief set the SSL context if we can read as many as data - * - * @param ctx - SSL context point - * @param m - enable the fuction - * - * @return none - */ -void SSL_CTX_set_default_read_ahead(SSL_CTX *ctx, int m); - -/** - * @brief set SSL context default verifying path - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx); - -/** - * @brief set SSL context default verifying directory - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx); - -/** - * @brief set SSL context default verifying file - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_default_verify_file(SSL_CTX *ctx); - -/** - * @brief set SSL context extra data - * - * @param ctx - SSL context point - * @param idx - data index - * @param arg - data point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, char *arg); - -/** - * @brief clear the SSL context option bit of "op" - * - * @param ctx - SSL context point - * @param op - option - * - * @return SSL context option - */ -unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op); - -/** - * @brief get the SSL context option - * - * @param ctx - SSL context point - * @param op - option - * - * @return SSL context option - */ -unsigned long SSL_CTX_get_options(SSL_CTX *ctx); - -/** - * @brief set the SSL context quiet shutdown mode - * - * @param ctx - SSL context point - * @param mode - mode - * - * @return none - */ -void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode); - -/** - * @brief get the SSL context X509 certification - * - * @param ctx - SSL context point - * - * @return X509 certification - */ -X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx); - -/** - * @brief get the SSL context private key - * - * @param ctx - SSL context point - * - * @return private key - */ -EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx); - -/** - * @brief set SSL context PSK identity hint - * - * @param ctx - SSL context point - * @param hint - PSK identity hint - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *hint); - -/** - * @brief set SSL context PSK server callback function - * - * @param ctx - SSL context point - * @param callback - callback function - * - * @return none - */ -void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, - unsigned int (*callback)(SSL *ssl, - const char *identity, - unsigned char *psk, - int max_psk_len)); -/** - * @brief get alert description string - * - * @param value - alert value - * - * @return alert description string - */ -const char *SSL_alert_desc_string(int value); - -/** - * @brief get alert description long string - * - * @param value - alert value - * - * @return alert description long string - */ -const char *SSL_alert_desc_string_long(int value); - -/** - * @brief get alert type string - * - * @param value - alert value - * - * @return alert type string - */ -const char *SSL_alert_type_string(int value); - -/** - * @brief get alert type long string - * - * @param value - alert value - * - * @return alert type long string - */ -const char *SSL_alert_type_string_long(int value); - -/** - * @brief get SSL context of the SSL - * - * @param ssl - SSL point - * - * @return SSL context - */ -SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl); - -/** - * @brief get SSL application data - * - * @param ssl - SSL point - * - * @return application data - */ -char *SSL_get_app_data(SSL *ssl); - -/** - * @brief get SSL cipher bits - * - * @param ssl - SSL point - * @param alg_bits - algorithm bits - * - * @return strength bits - */ -int SSL_get_cipher_bits(const SSL *ssl, int *alg_bits); - -/** - * @brief get SSL cipher name - * - * @param ssl - SSL point - * - * @return SSL cipher name - */ -char *SSL_get_cipher_name(const SSL *ssl); - -/** - * @brief get SSL cipher version - * - * @param ssl - SSL point - * - * @return SSL cipher version - */ -char *SSL_get_cipher_version(const SSL *ssl); - -/** - * @brief get SSL extra data - * - * @param ssl - SSL point - * @param idx - data index - * - * @return extra data - */ -char *SSL_get_ex_data(const SSL *ssl, int idx); - -/** - * @brief get index of the SSL extra data X509 storage context - * - * @param none - * - * @return data index - */ -int SSL_get_ex_data_X509_STORE_CTX_idx(void); - -/** - * @brief get peer certification chain - * - * @param ssl - SSL point - * - * @return certification chain - */ -STACK *SSL_get_peer_cert_chain(const SSL *ssl); - -/** - * @brief get peer certification - * - * @param ssl - SSL point - * - * @return certification - */ -X509 *SSL_get_peer_certificate(const SSL *ssl); - -/** - * @brief get SSL quiet shutdown mode - * - * @param ssl - SSL point - * - * @return quiet shutdown mode - */ -int SSL_get_quiet_shutdown(const SSL *ssl); - -/** - * @brief get SSL read only IO handle - * - * @param ssl - SSL point - * - * @return IO handle - */ -BIO *SSL_get_rbio(const SSL *ssl); - -/** - * @brief get SSL shared ciphers - * - * @param ssl - SSL point - * @param buf - buffer to store the ciphers - * @param len - buffer len - * - * @return shared ciphers - */ -char *SSL_get_shared_ciphers(const SSL *ssl, char *buf, int len); - -/** - * @brief get SSL shutdown mode - * - * @param ssl - SSL point - * - * @return shutdown mode - */ -int SSL_get_shutdown(const SSL *ssl); - -/** - * @brief get SSL session time - * - * @param ssl - SSL point - * - * @return session time - */ -long SSL_get_time(const SSL *ssl); - -/** - * @brief get SSL session timeout time - * - * @param ssl - SSL point - * - * @return session timeout time - */ -long SSL_get_timeout(const SSL *ssl); - -/** - * @brief get SSL verifying mode - * - * @param ssl - SSL point - * - * @return verifying mode - */ -int SSL_get_verify_mode(const SSL *ssl); - -/** - * @brief get SSL verify parameters - * - * @param ssl - SSL point - * - * @return verify parameters - */ -X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl); - -/** - * @brief set expected hostname the peer cert CN should have - * - * @param param - verify parameters from SSL_get0_param() - * - * @param name - the expected hostname - * - * @param namelen - the length of the hostname, or 0 if NUL terminated - * - * @return verify parameters - */ -int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, - const char *name, size_t namelen); - -/** - * @brief set parameters for X509 host verify action - * - * @param param -verify parameters from SSL_get0_param() - * - * @param flags - bitfield of X509_CHECK_FLAG_... parameters to set - * - * @return 1 for success, 0 for failure - */ -int X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, - unsigned long flags); - -/** - * @brief clear parameters for X509 host verify action - * - * @param param -verify parameters from SSL_get0_param() - * - * @param flags - bitfield of X509_CHECK_FLAG_... parameters to clear - * - * @return 1 for success, 0 for failure - */ -int X509_VERIFY_PARAM_clear_hostflags(X509_VERIFY_PARAM *param, - unsigned long flags); - -/** - * @brief get SSL write only IO handle - * - * @param ssl - SSL point - * - * @return IO handle - */ -BIO *SSL_get_wbio(const SSL *ssl); - -/** - * @brief load SSL client CA certification file - * - * @param file - file name - * - * @return certification loading object - */ -STACK *SSL_load_client_CA_file(const char *file); - -/** - * @brief add SSL reference by '1' - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_up_ref(SSL *ssl); - -/** - * @brief read and put data into buf, but not clear the SSL low-level storage - * - * @param ssl - SSL point - * @param buf - storage buffer point - * @param num - data bytes - * - * @return result - * > 0 : OK, and return read bytes - * = 0 : connect is closed - * < 0 : a error catch - */ -int SSL_peek(SSL *ssl, void *buf, int num); - -/** - * @brief make SSL renegotiate - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_renegotiate(SSL *ssl); - -/** - * @brief get the state string where SSL is reading - * - * @param ssl - SSL point - * - * @return state string - */ -const char *SSL_rstate_string(SSL *ssl); - -/** - * @brief get the statement long string where SSL is reading - * - * @param ssl - SSL point - * - * @return statement long string - */ -const char *SSL_rstate_string_long(SSL *ssl); - -/** - * @brief set SSL accept statement - * - * @param ssl - SSL point - * - * @return none - */ -void SSL_set_accept_state(SSL *ssl); - -/** - * @brief set SSL application data - * - * @param ssl - SSL point - * @param arg - SSL application data point - * - * @return none - */ -void SSL_set_app_data(SSL *ssl, char *arg); - -/** - * @brief set SSL BIO - * - * @param ssl - SSL point - * @param rbio - read only IO - * @param wbio - write only IO - * - * @return none - */ -void SSL_set_bio(SSL *ssl, BIO *rbio, BIO *wbio); - -/** - * @brief clear SSL option - * - * @param ssl - SSL point - * @param op - clear option - * - * @return SSL option - */ -unsigned long SSL_clear_options(SSL *ssl, unsigned long op); - -/** - * @brief get SSL option - * - * @param ssl - SSL point - * - * @return SSL option - */ -unsigned long SSL_get_options(SSL *ssl); - -/** - * @brief clear SSL option - * - * @param ssl - SSL point - * @param op - setting option - * - * @return SSL option - */ -unsigned long SSL_set_options(SSL *ssl, unsigned long op); - -/** - * @brief set SSL quiet shutdown mode - * - * @param ssl - SSL point - * @param mode - quiet shutdown mode - * - * @return none - */ -void SSL_set_quiet_shutdown(SSL *ssl, int mode); - -/** - * @brief set SSL shutdown mode - * - * @param ssl - SSL point - * @param mode - shutdown mode - * - * @return none - */ -void SSL_set_shutdown(SSL *ssl, int mode); - -/** - * @brief set SSL session time - * - * @param ssl - SSL point - * @param t - session time - * - * @return session time - */ -void SSL_set_time(SSL *ssl, long t); - -/** - * @brief set SSL session timeout time - * - * @param ssl - SSL point - * @param t - session timeout time - * - * @return session timeout time - */ -void SSL_set_timeout(SSL *ssl, long t); - -/** - * @brief get SSL statement string - * - * @param ssl - SSL point - * - * @return SSL statement string - */ -char *SSL_state_string(const SSL *ssl); - -/** - * @brief get SSL statement long string - * - * @param ssl - SSL point - * - * @return SSL statement long string - */ -char *SSL_state_string_long(const SSL *ssl); - -/** - * @brief get SSL renegotiation count - * - * @param ssl - SSL point - * - * @return renegotiation count - */ -long SSL_total_renegotiations(SSL *ssl); - -/** - * @brief get SSL version - * - * @param ssl - SSL point - * - * @return SSL version - */ -int SSL_version(const SSL *ssl); - -/** - * @brief set SSL PSK identity hint - * - * @param ssl - SSL point - * @param hint - identity hint - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_use_psk_identity_hint(SSL *ssl, const char *hint); - -/** - * @brief get SSL PSK identity hint - * - * @param ssl - SSL point - * - * @return identity hint - */ -const char *SSL_get_psk_identity_hint(SSL *ssl); - -/** - * @brief get SSL PSK identity - * - * @param ssl - SSL point - * - * @return identity - */ -const char *SSL_get_psk_identity(SSL *ssl); - -#ifdef __cplusplus -} -#endif - -#endif +// 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 _SSL_H_ +#define _SSL_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "internal/ssl_x509.h" +#include "internal/ssl_pkey.h" + +/* +{ +*/ + +#define SSL_CB_ALERT 0x4000 + +#define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT (1 << 0) +#define X509_CHECK_FLAG_NO_WILDCARDS (1 << 1) +#define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS (1 << 2) +#define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS (1 << 3) +#define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS (1 << 4) + +/** + * @brief create a SSL context + * + * @param method - the SSL context method point + * + * @return the context point + */ +SSL_CTX* SSL_CTX_new(const SSL_METHOD *method); + +/** + * @brief free a SSL context + * + * @param method - the SSL context point + * + * @return none + */ +void SSL_CTX_free(SSL_CTX *ctx); + +/** + * @brief create a SSL + * + * @param ctx - the SSL context point + * + * @return the SSL point + */ +SSL* SSL_new(SSL_CTX *ctx); + +/** + * @brief free the SSL + * + * @param ssl - the SSL point + * + * @return none + */ +void SSL_free(SSL *ssl); + +/** + * @brief connect to the remote SSL server + * + * @param ssl - the SSL point + * + * @return result + * 1 : OK + * -1 : failed + */ +int SSL_connect(SSL *ssl); + +/** + * @brief accept the remote connection + * + * @param ssl - the SSL point + * + * @return result + * 1 : OK + * -1 : failed + */ +int SSL_accept(SSL *ssl); + +/** + * @brief read data from to remote + * + * @param ssl - the SSL point which has been connected + * @param buffer - the received data buffer point + * @param len - the received data length + * + * @return result + * > 0 : OK, and return received data bytes + * = 0 : connection is closed + * < 0 : an error catch + */ +int SSL_read(SSL *ssl, void *buffer, int len); + +/** + * @brief send the data to remote + * + * @param ssl - the SSL point which has been connected + * @param buffer - the send data buffer point + * @param len - the send data length + * + * @return result + * > 0 : OK, and return sent data bytes + * = 0 : connection is closed + * < 0 : an error catch + */ +int SSL_write(SSL *ssl, const void *buffer, int len); + +/** + * @brief get the verifying result of the SSL certification + * + * @param ssl - the SSL point + * + * @return the result of verifying + */ +long SSL_get_verify_result(const SSL *ssl); + +/** + * @brief shutdown the connection + * + * @param ssl - the SSL point + * + * @return result + * 1 : OK + * 0 : shutdown is not finished + * -1 : an error catch + */ +int SSL_shutdown(SSL *ssl); + +/** + * @brief bind the socket file description into the SSL + * + * @param ssl - the SSL point + * @param fd - socket handle + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_set_fd(SSL *ssl, int fd); + +/** + * @brief Set the hostname for SNI + * + * @param ssl - the SSL context point + * @param hostname - pointer to the hostname + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_set_tlsext_host_name(SSL* ssl, const char *hostname); + +/** + * @brief These functions load the private key into the SSL_CTX or SSL object + * + * @param ctx - the SSL context point + * @param pkey - private key object point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey); + +/** + * @brief These functions load the certification into the SSL_CTX or SSL object + * + * @param ctx - the SSL context point + * @param pkey - certification object point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the SSLV2.3 version SSL context client method + */ +const SSL_METHOD* SSLv23_client_method(void); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the TLSV1.0 version SSL context client method + */ +const SSL_METHOD* TLSv1_client_method(void); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the SSLV1.0 version SSL context client method + */ +const SSL_METHOD* SSLv3_client_method(void); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the TLSV1.1 version SSL context client method + */ +const SSL_METHOD* TLSv1_1_client_method(void); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the TLSV1.2 version SSL context client method + */ +const SSL_METHOD* TLSv1_2_client_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLS any version SSL context client method + */ +const SSL_METHOD* TLS_client_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the SSLV2.3 version SSL context server method + */ +const SSL_METHOD* SSLv23_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLSV1.1 version SSL context server method + */ +const SSL_METHOD* TLSv1_1_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLSV1.2 version SSL context server method + */ +const SSL_METHOD* TLSv1_2_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLSV1.0 version SSL context server method + */ +const SSL_METHOD* TLSv1_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the SSLV3.0 version SSL context server method + */ +const SSL_METHOD* SSLv3_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLS any version SSL context server method + */ +const SSL_METHOD* TLS_server_method(void); + + +/** + * @brief set the SSL context ALPN select callback function + * + * @param ctx - SSL context point + * @param cb - ALPN select callback function + * @param arg - ALPN select callback function entry private data point + * + * @return none + */ +void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, + int (*cb) (SSL *ssl, + const unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg), + void *arg); + + +/** + * @brief set the SSL context ALPN select protocol + * + * @param ctx - SSL context point + * @param protos - ALPN protocol name + * @param protos_len - ALPN protocol name bytes + * + * @return result + * 0 : OK + * 1 : failed + */ +int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos, unsigned int protos_len); + +/** + * @brief set the SSL context next ALPN select callback function + * + * @param ctx - SSL context point + * @param cb - ALPN select callback function + * @param arg - ALPN select callback function entry private data point + * + * @return none + */ +void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, + int (*cb) (SSL *ssl, + unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg), + void *arg); + +/** + * @brief get SSL error code + * + * @param ssl - SSL point + * @param ret_code - SSL return code + * + * @return SSL error number + */ +int SSL_get_error(const SSL *ssl, int ret_code); + +/** + * @brief clear the SSL error code + * + * @param none + * + * @return none + */ +void ERR_clear_error(void); + +/** + * @brief get the current SSL error code + * + * @param none + * + * @return current SSL error number + */ +int ERR_get_error(void); + +/** + * @brief register the SSL error strings + * + * @param none + * + * @return none + */ +void ERR_load_SSL_strings(void); + +/** + * @brief initialize the SSL library + * + * @param none + * + * @return none + */ +void SSL_library_init(void); + +/** + * @brief generates a human-readable string representing the error code e + * and store it into the "ret" point memory + * + * @param e - error code + * @param ret - memory point to store the string + * + * @return the result string point + */ +char *ERR_error_string(unsigned long e, char *ret); + +/** + * @brief add the SSL context option + * + * @param ctx - SSL context point + * @param opt - new SSL context option + * + * @return the SSL context option + */ +unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long opt); + +/** + * @brief add the SSL context mode + * + * @param ctx - SSL context point + * @param mod - new SSL context mod + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_mode(SSL_CTX *ctx, int mod); + +/* +} +*/ + +/** + * @brief perform the SSL handshake + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + * -1 : a error catch + */ +int SSL_do_handshake(SSL *ssl); + +/** + * @brief get the SSL current version + * + * @param ssl - SSL point + * + * @return the version string + */ +const char *SSL_get_version(const SSL *ssl); + +/** + * @brief set the SSL context version + * + * @param ctx - SSL context point + * @param meth - SSL method point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth); + +/** + * @brief get the bytes numbers which are to be read + * + * @param ssl - SSL point + * + * @return bytes number + */ +int SSL_pending(const SSL *ssl); + +/** + * @brief check if SSL want nothing + * + * @param ssl - SSL point + * + * @return result + * 0 : false + * 1 : true + */ +int SSL_want_nothing(const SSL *ssl); + +/** + * @brief check if SSL want to read + * + * @param ssl - SSL point + * + * @return result + * 0 : false + * 1 : true + */ +int SSL_want_read(const SSL *ssl); + +/** + * @brief check if SSL want to write + * + * @param ssl - SSL point + * + * @return result + * 0 : false + * 1 : true + */ +int SSL_want_write(const SSL *ssl); + +/** + * @brief get the SSL context current method + * + * @param ctx - SSL context point + * + * @return the SSL context current method + */ +const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx); + +/** + * @brief get the SSL current method + * + * @param ssl - SSL point + * + * @return the SSL current method + */ +const SSL_METHOD *SSL_get_ssl_method(SSL *ssl); + +/** + * @brief set the SSL method + * + * @param ssl - SSL point + * @param meth - SSL method point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_set_ssl_method(SSL *ssl, const SSL_METHOD *method); + +/** + * @brief add CA client certification into the SSL + * + * @param ssl - SSL point + * @param x - CA certification point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_add_client_CA(SSL *ssl, X509 *x); + +/** + * @brief add CA client certification into the SSL context + * + * @param ctx - SSL context point + * @param x - CA certification point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x); + +/** + * @brief set the SSL CA certification list + * + * @param ssl - SSL point + * @param name_list - CA certification list + * + * @return none + */ +void SSL_set_client_CA_list(SSL *ssl, STACK_OF(X509_NAME) *name_list); + +/** + * @brief set the SSL context CA certification list + * + * @param ctx - SSL context point + * @param name_list - CA certification list + * + * @return none + */ +void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list); + +/** + * @briefget the SSL CA certification list + * + * @param ssl - SSL point + * + * @return CA certification list + */ +STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *ssl); + +/** + * @brief get the SSL context CA certification list + * + * @param ctx - SSL context point + * + * @return CA certification list + */ +STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx); + +/** + * @brief get the SSL certification point + * + * @param ssl - SSL point + * + * @return SSL certification point + */ +X509 *SSL_get_certificate(const SSL *ssl); + +/** + * @brief get the SSL private key point + * + * @param ssl - SSL point + * + * @return SSL private key point + */ +EVP_PKEY *SSL_get_privatekey(const SSL *ssl); + +/** + * @brief set the SSL information callback function + * + * @param ssl - SSL point + * @param cb - information callback function + * + * @return none + */ +void SSL_set_info_callback(SSL *ssl, void (*cb) (const SSL *ssl, int type, int val)); + +/** + * @brief get the SSL state + * + * @param ssl - SSL point + * + * @return SSL state + */ +OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl); + +/** + * @brief set the SSL context read buffer length + * + * @param ctx - SSL context point + * @param len - read buffer length + * + * @return none + */ +void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len); + +/** + * @brief set the SSL read buffer length + * + * @param ssl - SSL point + * @param len - read buffer length + * + * @return none + */ +void SSL_set_default_read_buffer_len(SSL *ssl, size_t len); + +/** + * @brief set the SSL security level + * + * @param ssl - SSL point + * @param level - security level + * + * @return none + */ +void SSL_set_security_level(SSL *ssl, int level); + +/** + * @brief get the SSL security level + * + * @param ssl - SSL point + * + * @return security level + */ +int SSL_get_security_level(const SSL *ssl); + +/** + * @brief get the SSL verifying mode of the SSL context + * + * @param ctx - SSL context point + * + * @return verifying mode + */ +int SSL_CTX_get_verify_mode(const SSL_CTX *ctx); + +/** + * @brief get the SSL verifying depth of the SSL context + * + * @param ctx - SSL context point + * + * @return verifying depth + */ +int SSL_CTX_get_verify_depth(const SSL_CTX *ctx); + +/** + * @brief set the SSL context verifying of the SSL context + * + * @param ctx - SSL context point + * @param mode - verifying mode + * @param verify_callback - verifying callback function + * + * @return none + */ +void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); + +/** + * @brief set the SSL verifying of the SSL context + * + * @param ctx - SSL point + * @param mode - verifying mode + * @param verify_callback - verifying callback function + * + * @return none + */ +void SSL_set_verify(SSL *s, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); + +/** + * @brief set the SSL verify depth of the SSL context + * + * @param ctx - SSL context point + * @param depth - verifying depth + * + * @return none + */ +void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); + +/** + * @brief certification verifying callback function + * + * @param preverify_ok - verifying result + * @param x509_ctx - X509 certification point + * + * @return verifying result + */ +int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx); + +/** + * @brief set the session timeout time + * + * @param ctx - SSL context point + * @param t - new session timeout time + * + * @return old session timeout time + */ +long SSL_CTX_set_timeout(SSL_CTX *ctx, long t); + +/** + * @brief get the session timeout time + * + * @param ctx - SSL context point + * + * @return current session timeout time + */ +long SSL_CTX_get_timeout(const SSL_CTX *ctx); + +/** + * @brief set the SSL context cipher through the list string + * + * @param ctx - SSL context point + * @param str - cipher controller list string + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str); + +/** + * @brief set the SSL cipher through the list string + * + * @param ssl - SSL point + * @param str - cipher controller list string + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_set_cipher_list(SSL *ssl, const char *str); + +/** + * @brief get the SSL cipher list string + * + * @param ssl - SSL point + * + * @return cipher controller list string + */ +const char *SSL_get_cipher_list(const SSL *ssl, int n); + +/** + * @brief get the SSL cipher + * + * @param ssl - SSL point + * + * @return current cipher + */ +const SSL_CIPHER *SSL_get_current_cipher(const SSL *ssl); + +/** + * @brief get the SSL cipher string + * + * @param ssl - SSL point + * + * @return cipher string + */ +const char *SSL_get_cipher(const SSL *ssl); + +/** + * @brief get the SSL context object X509 certification storage + * + * @param ctx - SSL context point + * + * @return x509 certification storage + */ +X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx); + +/** + * @brief set the SSL context object X509 certification store + * + * @param ctx - SSL context point + * @param store - X509 certification store + * + * @return none + */ +void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store); + +/** + * @brief get the SSL specifical statement + * + * @param ssl - SSL point + * + * @return specifical statement + */ +int SSL_want(const SSL *ssl); + +/** + * @brief check if the SSL is SSL_X509_LOOKUP state + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_want_x509_lookup(const SSL *ssl); + +/** + * @brief reset the SSL + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_clear(SSL *ssl); + +/** + * @brief get the socket handle of the SSL + * + * @param ssl - SSL point + * + * @return result + * >= 0 : yes, and return socket handle + * < 0 : a error catch + */ +int SSL_get_fd(const SSL *ssl); + +/** + * @brief get the read only socket handle of the SSL + * + * @param ssl - SSL point + * + * @return result + * >= 0 : yes, and return socket handle + * < 0 : a error catch + */ +int SSL_get_rfd(const SSL *ssl); + +/** + * @brief get the write only socket handle of the SSL + * + * @param ssl - SSL point + * + * @return result + * >= 0 : yes, and return socket handle + * < 0 : a error catch + */ +int SSL_get_wfd(const SSL *ssl); + +/** + * @brief set the SSL if we can read as many as data + * + * @param ssl - SSL point + * @param yes - enable the function + * + * @return none + */ +void SSL_set_read_ahead(SSL *s, int yes); + +/** + * @brief set the SSL context if we can read as many as data + * + * @param ctx - SSL context point + * @param yes - enbale the function + * + * @return none + */ +void SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes); + +/** + * @brief get the SSL ahead signal if we can read as many as data + * + * @param ssl - SSL point + * + * @return SSL context ahead signal + */ +int SSL_get_read_ahead(const SSL *ssl); + +/** + * @brief get the SSL context ahead signal if we can read as many as data + * + * @param ctx - SSL context point + * + * @return SSL context ahead signal + */ +long SSL_CTX_get_read_ahead(SSL_CTX *ctx); + +/** + * @brief check if some data can be read + * + * @param ssl - SSL point + * + * @return + * 1 : there are bytes to be read + * 0 : no data + */ +int SSL_has_pending(const SSL *ssl); + +/** + * @brief load the X509 certification into SSL context + * + * @param ctx - SSL context point + * @param x - X509 certification point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);//loads the certificate x into ctx + +/** + * @brief load the ASN1 certification into SSL context + * + * @param ctx - SSL context point + * @param len - certification length + * @param d - data point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d); + +/** + * @brief load the certification file into SSL context + * + * @param ctx - SSL context point + * @param file - certification file name + * @param type - certification encoding type + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type); + +/** + * @brief load the certification chain file into SSL context + * + * @param ctx - SSL context point + * @param file - certification chain file name + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file); + + +/** + * @brief load the ASN1 private key into SSL context + * + * @param ctx - SSL context point + * @param d - data point + * @param len - private key length + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, const unsigned char *d, long len);//adds the private key of type pk stored at memory location d (length len) to ctx + +/** + * @brief load the private key file into SSL context + * + * @param ctx - SSL context point + * @param file - private key file name + * @param type - private key encoding type + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type); + +/** + * @brief load the RSA private key into SSL context + * + * @param ctx - SSL context point + * @param x - RSA private key point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa); + +/** + * @brief load the RSA ASN1 private key into SSL context + * + * @param ctx - SSL context point + * @param d - data point + * @param len - RSA private key length + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len); + +/** + * @brief load the RSA private key file into SSL context + * + * @param ctx - SSL context point + * @param file - RSA private key file name + * @param type - private key encoding type + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type); + + +/** + * @brief check if the private key and certification is matched + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_check_private_key(const SSL_CTX *ctx); + +/** + * @brief set the SSL context server information + * + * @param ctx - SSL context point + * @param serverinfo - server information string + * @param serverinfo_length - server information length + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, size_t serverinfo_length); + +/** + * @brief load the SSL context server infomation file into SSL context + * + * @param ctx - SSL context point + * @param file - server information file + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file); + +/** + * @brief SSL select next function + * + * @param out - point of output data point + * @param outlen - output data length + * @param in - input data + * @param inlen - input data length + * @param client - client data point + * @param client_len -client data length + * + * @return NPN state + * OPENSSL_NPN_UNSUPPORTED : not support + * OPENSSL_NPN_NEGOTIATED : negotiated + * OPENSSL_NPN_NO_OVERLAP : no overlap + */ +int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, + const unsigned char *client, unsigned int client_len); + +/** + * @brief load the extra certification chain into the SSL context + * + * @param ctx - SSL context point + * @param x509 - X509 certification + * + * @return result + * 1 : OK + * 0 : failed + */ +long SSL_CTX_add_extra_chain_cert(SSL_CTX *ctx, X509 *); + +/** + * @brief control the SSL context + * + * @param ctx - SSL context point + * @param cmd - command + * @param larg - parameter length + * @param parg - parameter point + * + * @return result + * 1 : OK + * 0 : failed + */ +long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, char *parg); + +/** + * @brief get the SSL context cipher + * + * @param ctx - SSL context point + * + * @return SSL context cipher + */ +STACK *SSL_CTX_get_ciphers(const SSL_CTX *ctx); + +/** + * @brief check if the SSL context can read as many as data + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +long SSL_CTX_get_default_read_ahead(SSL_CTX *ctx); + +/** + * @brief get the SSL context extra data + * + * @param ctx - SSL context point + * @param idx - index + * + * @return data point + */ +char *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx); + +/** + * @brief get the SSL context quiet shutdown option + * + * @param ctx - SSL context point + * + * @return quiet shutdown option + */ +int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx); + +/** + * @brief load the SSL context CA file + * + * @param ctx - SSL context point + * @param CAfile - CA certification file + * @param CApath - CA certification file path + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, const char *CApath); + +/** + * @brief add SSL context reference count by '1' + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_up_ref(SSL_CTX *ctx); + +/** + * @brief set SSL context application private data + * + * @param ctx - SSL context point + * @param arg - private data + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_app_data(SSL_CTX *ctx, void *arg); + +/** + * @brief set SSL context client certification callback function + * + * @param ctx - SSL context point + * @param cb - callback function + * + * @return none + */ +void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)); + +/** + * @brief set the SSL context if we can read as many as data + * + * @param ctx - SSL context point + * @param m - enable the fuction + * + * @return none + */ +void SSL_CTX_set_default_read_ahead(SSL_CTX *ctx, int m); + +/** + * @brief set SSL context default verifying path + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx); + +/** + * @brief set SSL context default verifying directory + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx); + +/** + * @brief set SSL context default verifying file + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_default_verify_file(SSL_CTX *ctx); + +/** + * @brief set SSL context extra data + * + * @param ctx - SSL context point + * @param idx - data index + * @param arg - data point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, char *arg); + +/** + * @brief clear the SSL context option bit of "op" + * + * @param ctx - SSL context point + * @param op - option + * + * @return SSL context option + */ +unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op); + +/** + * @brief get the SSL context option + * + * @param ctx - SSL context point + * @param op - option + * + * @return SSL context option + */ +unsigned long SSL_CTX_get_options(SSL_CTX *ctx); + +/** + * @brief set the SSL context quiet shutdown mode + * + * @param ctx - SSL context point + * @param mode - mode + * + * @return none + */ +void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode); + +/** + * @brief get the SSL context X509 certification + * + * @param ctx - SSL context point + * + * @return X509 certification + */ +X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx); + +/** + * @brief get the SSL context private key + * + * @param ctx - SSL context point + * + * @return private key + */ +EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx); + +/** + * @brief set SSL context PSK identity hint + * + * @param ctx - SSL context point + * @param hint - PSK identity hint + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *hint); + +/** + * @brief set SSL context PSK server callback function + * + * @param ctx - SSL context point + * @param callback - callback function + * + * @return none + */ +void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, + unsigned int (*callback)(SSL *ssl, + const char *identity, + unsigned char *psk, + int max_psk_len)); +/** + * @brief get alert description string + * + * @param value - alert value + * + * @return alert description string + */ +const char *SSL_alert_desc_string(int value); + +/** + * @brief get alert description long string + * + * @param value - alert value + * + * @return alert description long string + */ +const char *SSL_alert_desc_string_long(int value); + +/** + * @brief get alert type string + * + * @param value - alert value + * + * @return alert type string + */ +const char *SSL_alert_type_string(int value); + +/** + * @brief get alert type long string + * + * @param value - alert value + * + * @return alert type long string + */ +const char *SSL_alert_type_string_long(int value); + +/** + * @brief get SSL context of the SSL + * + * @param ssl - SSL point + * + * @return SSL context + */ +SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl); + +/** + * @brief get SSL application data + * + * @param ssl - SSL point + * + * @return application data + */ +char *SSL_get_app_data(SSL *ssl); + +/** + * @brief get SSL cipher bits + * + * @param ssl - SSL point + * @param alg_bits - algorithm bits + * + * @return strength bits + */ +int SSL_get_cipher_bits(const SSL *ssl, int *alg_bits); + +/** + * @brief get SSL cipher name + * + * @param ssl - SSL point + * + * @return SSL cipher name + */ +char *SSL_get_cipher_name(const SSL *ssl); + +/** + * @brief get SSL cipher version + * + * @param ssl - SSL point + * + * @return SSL cipher version + */ +char *SSL_get_cipher_version(const SSL *ssl); + +/** + * @brief get SSL extra data + * + * @param ssl - SSL point + * @param idx - data index + * + * @return extra data + */ +char *SSL_get_ex_data(const SSL *ssl, int idx); + +/** + * @brief get index of the SSL extra data X509 storage context + * + * @param none + * + * @return data index + */ +int SSL_get_ex_data_X509_STORE_CTX_idx(void); + +/** + * @brief get peer certification chain + * + * @param ssl - SSL point + * + * @return certification chain + */ +STACK *SSL_get_peer_cert_chain(const SSL *ssl); + +/** + * @brief get peer certification + * + * @param ssl - SSL point + * + * @return certification + */ +X509 *SSL_get_peer_certificate(const SSL *ssl); + +/** + * @brief get SSL quiet shutdown mode + * + * @param ssl - SSL point + * + * @return quiet shutdown mode + */ +int SSL_get_quiet_shutdown(const SSL *ssl); + +/** + * @brief get SSL read only IO handle + * + * @param ssl - SSL point + * + * @return IO handle + */ +BIO *SSL_get_rbio(const SSL *ssl); + +/** + * @brief get SSL shared ciphers + * + * @param ssl - SSL point + * @param buf - buffer to store the ciphers + * @param len - buffer len + * + * @return shared ciphers + */ +char *SSL_get_shared_ciphers(const SSL *ssl, char *buf, int len); + +/** + * @brief get SSL shutdown mode + * + * @param ssl - SSL point + * + * @return shutdown mode + */ +int SSL_get_shutdown(const SSL *ssl); + +/** + * @brief get SSL session time + * + * @param ssl - SSL point + * + * @return session time + */ +long SSL_get_time(const SSL *ssl); + +/** + * @brief get SSL session timeout time + * + * @param ssl - SSL point + * + * @return session timeout time + */ +long SSL_get_timeout(const SSL *ssl); + +/** + * @brief get SSL verifying mode + * + * @param ssl - SSL point + * + * @return verifying mode + */ +int SSL_get_verify_mode(const SSL *ssl); + +/** + * @brief get SSL verify parameters + * + * @param ssl - SSL point + * + * @return verify parameters + */ +X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl); + +/** + * @brief set expected hostname the peer cert CN should have + * + * @param param - verify parameters from SSL_get0_param() + * + * @param name - the expected hostname + * + * @param namelen - the length of the hostname, or 0 if NUL terminated + * + * @return verify parameters + */ +int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, + const char *name, size_t namelen); + +/** + * @brief set parameters for X509 host verify action + * + * @param param -verify parameters from SSL_get0_param() + * + * @param flags - bitfield of X509_CHECK_FLAG_... parameters to set + * + * @return 1 for success, 0 for failure + */ +int X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, + unsigned long flags); + +/** + * @brief clear parameters for X509 host verify action + * + * @param param -verify parameters from SSL_get0_param() + * + * @param flags - bitfield of X509_CHECK_FLAG_... parameters to clear + * + * @return 1 for success, 0 for failure + */ +int X509_VERIFY_PARAM_clear_hostflags(X509_VERIFY_PARAM *param, + unsigned long flags); + +/** + * @brief get SSL write only IO handle + * + * @param ssl - SSL point + * + * @return IO handle + */ +BIO *SSL_get_wbio(const SSL *ssl); + +/** + * @brief load SSL client CA certification file + * + * @param file - file name + * + * @return certification loading object + */ +STACK *SSL_load_client_CA_file(const char *file); + +/** + * @brief add SSL reference by '1' + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_up_ref(SSL *ssl); + +/** + * @brief read and put data into buf, but not clear the SSL low-level storage + * + * @param ssl - SSL point + * @param buf - storage buffer point + * @param num - data bytes + * + * @return result + * > 0 : OK, and return read bytes + * = 0 : connect is closed + * < 0 : a error catch + */ +int SSL_peek(SSL *ssl, void *buf, int num); + +/** + * @brief make SSL renegotiate + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_renegotiate(SSL *ssl); + +/** + * @brief get the state string where SSL is reading + * + * @param ssl - SSL point + * + * @return state string + */ +const char *SSL_rstate_string(SSL *ssl); + +/** + * @brief get the statement long string where SSL is reading + * + * @param ssl - SSL point + * + * @return statement long string + */ +const char *SSL_rstate_string_long(SSL *ssl); + +/** + * @brief set SSL accept statement + * + * @param ssl - SSL point + * + * @return none + */ +void SSL_set_accept_state(SSL *ssl); + +/** + * @brief set SSL application data + * + * @param ssl - SSL point + * @param arg - SSL application data point + * + * @return none + */ +void SSL_set_app_data(SSL *ssl, char *arg); + +/** + * @brief set SSL BIO + * + * @param ssl - SSL point + * @param rbio - read only IO + * @param wbio - write only IO + * + * @return none + */ +void SSL_set_bio(SSL *ssl, BIO *rbio, BIO *wbio); + +/** + * @brief clear SSL option + * + * @param ssl - SSL point + * @param op - clear option + * + * @return SSL option + */ +unsigned long SSL_clear_options(SSL *ssl, unsigned long op); + +/** + * @brief get SSL option + * + * @param ssl - SSL point + * + * @return SSL option + */ +unsigned long SSL_get_options(SSL *ssl); + +/** + * @brief clear SSL option + * + * @param ssl - SSL point + * @param op - setting option + * + * @return SSL option + */ +unsigned long SSL_set_options(SSL *ssl, unsigned long op); + +/** + * @brief set SSL quiet shutdown mode + * + * @param ssl - SSL point + * @param mode - quiet shutdown mode + * + * @return none + */ +void SSL_set_quiet_shutdown(SSL *ssl, int mode); + +/** + * @brief set SSL shutdown mode + * + * @param ssl - SSL point + * @param mode - shutdown mode + * + * @return none + */ +void SSL_set_shutdown(SSL *ssl, int mode); + +/** + * @brief set SSL session time + * + * @param ssl - SSL point + * @param t - session time + * + * @return session time + */ +void SSL_set_time(SSL *ssl, long t); + +/** + * @brief set SSL session timeout time + * + * @param ssl - SSL point + * @param t - session timeout time + * + * @return session timeout time + */ +void SSL_set_timeout(SSL *ssl, long t); + +/** + * @brief get SSL statement string + * + * @param ssl - SSL point + * + * @return SSL statement string + */ +char *SSL_state_string(const SSL *ssl); + +/** + * @brief get SSL statement long string + * + * @param ssl - SSL point + * + * @return SSL statement long string + */ +char *SSL_state_string_long(const SSL *ssl); + +/** + * @brief get SSL renegotiation count + * + * @param ssl - SSL point + * + * @return renegotiation count + */ +long SSL_total_renegotiations(SSL *ssl); + +/** + * @brief get SSL version + * + * @param ssl - SSL point + * + * @return SSL version + */ +int SSL_version(const SSL *ssl); + +/** + * @brief set SSL PSK identity hint + * + * @param ssl - SSL point + * @param hint - identity hint + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_use_psk_identity_hint(SSL *ssl, const char *hint); + +/** + * @brief get SSL PSK identity hint + * + * @param ssl - SSL point + * + * @return identity hint + */ +const char *SSL_get_psk_identity_hint(SSL *ssl); + +/** + * @brief get SSL PSK identity + * + * @param ssl - SSL point + * + * @return identity + */ +const char *SSL_get_psk_identity(SSL *ssl); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/protobuf-c/protobuf-c/protobuf-c.h b/tools/sdk/include/protobuf-c/protobuf-c/protobuf-c.h new file mode 100755 index 00000000000..c8fa4fc2a7c --- /dev/null +++ b/tools/sdk/include/protobuf-c/protobuf-c/protobuf-c.h @@ -0,0 +1,1106 @@ +/* + * Copyright (c) 2008-2017, Dave Benson and the protobuf-c authors. + * 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 + * 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 + * \mainpage Introduction + * + * This is [protobuf-c], a C implementation of [Protocol Buffers]. + * + * This file defines the public API for the `libprotobuf-c` support library. + * This API includes interfaces that can be used directly by client code as well + * as the interfaces used by the code generated by the `protoc-c` compiler. + * + * The `libprotobuf-c` support library performs the actual serialization and + * deserialization of Protocol Buffers messages. It interacts with structures, + * definitions, and metadata generated by the `protoc-c` compiler from .proto + * files. + * + * \authors Dave Benson and the `protobuf-c` authors. + * + * \copyright 2008-2014. Licensed under the terms of the [BSD-2-Clause] license. + * + * [protobuf-c]: https://github.com/protobuf-c/protobuf-c + * [Protocol Buffers]: https://developers.google.com/protocol-buffers/ + * [BSD-2-Clause]: http://opensource.org/licenses/BSD-2-Clause + * + * \page gencode Generated Code + * + * For each enum, we generate a C enum. For each message, we generate a C + * structure which can be cast to a `ProtobufCMessage`. + * + * For each enum and message, we generate a descriptor object that allows us to + * implement a kind of reflection on the structures. + * + * First, some naming conventions: + * + * - The name of the type for enums and messages and services is camel case + * (meaning WordsAreCrammedTogether) except that double underscores are used + * to delimit scopes. For example, the following `.proto` file: + * +~~~{.proto} + package foo.bar; + message BazBah { + optional int32 val = 1; + } +~~~ + * + * would generate a C type `Foo__Bar__BazBah`. + * + * - Identifiers for functions and globals are all lowercase, with camel case + * words separated by single underscores. For example, one of the function + * prototypes generated by `protoc-c` for the above example: + * +~~~{.c} +Foo__Bar__BazBah * + foo__bar__baz_bah__unpack + (ProtobufCAllocator *allocator, + size_t len, + const uint8_t *data); +~~~ + * + * - Identifiers for enum values contain an uppercase prefix which embeds the + * package name and the enum type name. + * + * - A double underscore is used to separate further components of identifier + * names. + * + * For example, in the name of the unpack function above, the package name + * `foo.bar` has become `foo__bar`, the message name BazBah has become + * `baz_bah`, and the method name is `unpack`. These are all joined with double + * underscores to form the C identifier `foo__bar__baz_bah__unpack`. + * + * We also generate descriptor objects for messages and enums. These are + * declared in the `.pb-c.h` files: + * +~~~{.c} +extern const ProtobufCMessageDescriptor foo__bar__baz_bah__descriptor; +~~~ + * + * The message structures all begin with `ProtobufCMessageDescriptor *` which is + * sufficient to allow them to be cast to `ProtobufCMessage`. + * + * For each message defined in a `.proto` file, we generate a number of + * functions and macros. Each function name contains a prefix based on the + * package name and message name in order to make it a unique C identifier. + * + * - `INIT`. Statically initializes a message object, initializing its + * descriptor and setting its fields to default values. Uninitialized + * messages cannot be processed by the protobuf-c library. + * +~~~{.c} +#define FOO__BAR__BAZ_BAH__INIT \ + { PROTOBUF_C_MESSAGE_INIT (&foo__bar__baz_bah__descriptor), 0 } +~~~ + * - `init()`. Initializes a message object, initializing its descriptor and + * setting its fields to default values. Uninitialized messages cannot be + * processed by the protobuf-c library. + * +~~~{.c} +void foo__bar__baz_bah__init + (Foo__Bar__BazBah *message); +~~~ + * - `unpack()`. Unpacks data for a particular message format. Note that the + * `allocator` parameter is usually `NULL` to indicate that the system's + * `malloc()` and `free()` functions should be used for dynamically allocating + * memory. + * +~~~{.c} +Foo__Bar__BazBah * + foo__bar__baz_bah__unpack + (ProtobufCAllocator *allocator, + size_t len, + const uint8_t *data); +~~~ + * + * - `free_unpacked()`. Frees a message object obtained with the `unpack()` + * method. Freeing `NULL` is allowed (the same as with `free()`). + * +~~~{.c} +void foo__bar__baz_bah__free_unpacked + (Foo__Bar__BazBah *message, + ProtobufCAllocator *allocator); +~~~ + * + * - `get_packed_size()`. Calculates the length in bytes of the serialized + * representation of the message object. + * +~~~{.c} +size_t foo__bar__baz_bah__get_packed_size + (const Foo__Bar__BazBah *message); +~~~ + * + * - `pack()`. Pack a message object into a preallocated buffer. Assumes that + * the buffer is large enough. (Use `get_packed_size()` first.) + * +~~~{.c} +size_t foo__bar__baz_bah__pack + (const Foo__Bar__BazBah *message, + uint8_t *out); +~~~ + * + * - `pack_to_buffer()`. Packs a message into a "virtual buffer". This is an + * object which defines an "append bytes" callback to consume data as it is + * serialized. + * +~~~{.c} +size_t foo__bar__baz_bah__pack_to_buffer + (const Foo__Bar__BazBah *message, + ProtobufCBuffer *buffer); +~~~ + * + * \page pack Packing and unpacking messages + * + * To pack a message, first compute the packed size of the message with + * protobuf_c_message_get_packed_size(), then allocate a buffer of at least + * that size, then call protobuf_c_message_pack(). + * + * Alternatively, a message can be serialized without calculating the final size + * first. Use the protobuf_c_message_pack_to_buffer() function and provide a + * ProtobufCBuffer object which implements an "append" method that consumes + * data. + * + * To unpack a message, call the protobuf_c_message_unpack() function. The + * result can be cast to an object of the type that matches the descriptor for + * the message. + * + * The result of unpacking a message should be freed with + * protobuf_c_message_free_unpacked(). + */ + +#ifndef PROTOBUF_C_H +#define PROTOBUF_C_H + +#include +#include +#include +#include + +#ifdef __cplusplus +# define PROTOBUF_C__BEGIN_DECLS extern "C" { +# define PROTOBUF_C__END_DECLS } +#else +# define PROTOBUF_C__BEGIN_DECLS +# define PROTOBUF_C__END_DECLS +#endif + +PROTOBUF_C__BEGIN_DECLS + +#if defined(_WIN32) && defined(PROTOBUF_C_USE_SHARED_LIB) +# ifdef PROTOBUF_C_EXPORT +# define PROTOBUF_C__API __declspec(dllexport) +# else +# define PROTOBUF_C__API __declspec(dllimport) +# endif +#else +# define PROTOBUF_C__API +#endif + +#if !defined(PROTOBUF_C__NO_DEPRECATED) && \ + ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +# define PROTOBUF_C__DEPRECATED __attribute__((__deprecated__)) +#else +# define PROTOBUF_C__DEPRECATED +#endif + +#ifndef PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE + #define PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE(enum_name) \ + , _##enum_name##_IS_INT_SIZE = INT_MAX +#endif + +#define PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC 0x14159bc3 +#define PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC 0x28aaeef9 +#define PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC 0x114315af + +/* Empty string used for initializers */ +extern const char protobuf_c_empty_string[]; + +/** + * \defgroup api Public API + * + * This is the public API for `libprotobuf-c`. These interfaces are stable and + * subject to Semantic Versioning guarantees. + * + * @{ + */ + +/** + * Values for the `flags` word in `ProtobufCFieldDescriptor`. + */ +typedef enum { + /** Set if the field is repeated and marked with the `packed` option. */ + PROTOBUF_C_FIELD_FLAG_PACKED = (1 << 0), + + /** Set if the field is marked with the `deprecated` option. */ + PROTOBUF_C_FIELD_FLAG_DEPRECATED = (1 << 1), + + /** Set if the field is a member of a oneof (union). */ + PROTOBUF_C_FIELD_FLAG_ONEOF = (1 << 2), +} ProtobufCFieldFlag; + +/** + * Message field rules. + * + * \see [Defining A Message Type] in the Protocol Buffers documentation. + * + * [Defining A Message Type]: + * https://developers.google.com/protocol-buffers/docs/proto#simple + */ +typedef enum { + /** A well-formed message must have exactly one of this field. */ + PROTOBUF_C_LABEL_REQUIRED, + + /** + * A well-formed message can have zero or one of this field (but not + * more than one). + */ + PROTOBUF_C_LABEL_OPTIONAL, + + /** + * This field can be repeated any number of times (including zero) in a + * well-formed message. The order of the repeated values will be + * preserved. + */ + PROTOBUF_C_LABEL_REPEATED, + + /** + * This field has no label. This is valid only in proto3 and is + * equivalent to OPTIONAL but no "has" quantifier will be consulted. + */ + PROTOBUF_C_LABEL_NONE, +} ProtobufCLabel; + +/** + * Field value types. + * + * \see [Scalar Value Types] in the Protocol Buffers documentation. + * + * [Scalar Value Types]: + * https://developers.google.com/protocol-buffers/docs/proto#scalar + */ +typedef enum { + PROTOBUF_C_TYPE_INT32, /**< int32 */ + PROTOBUF_C_TYPE_SINT32, /**< signed int32 */ + PROTOBUF_C_TYPE_SFIXED32, /**< signed int32 (4 bytes) */ + PROTOBUF_C_TYPE_INT64, /**< int64 */ + PROTOBUF_C_TYPE_SINT64, /**< signed int64 */ + PROTOBUF_C_TYPE_SFIXED64, /**< signed int64 (8 bytes) */ + PROTOBUF_C_TYPE_UINT32, /**< unsigned int32 */ + PROTOBUF_C_TYPE_FIXED32, /**< unsigned int32 (4 bytes) */ + PROTOBUF_C_TYPE_UINT64, /**< unsigned int64 */ + PROTOBUF_C_TYPE_FIXED64, /**< unsigned int64 (8 bytes) */ + PROTOBUF_C_TYPE_FLOAT, /**< float */ + PROTOBUF_C_TYPE_DOUBLE, /**< double */ + PROTOBUF_C_TYPE_BOOL, /**< boolean */ + PROTOBUF_C_TYPE_ENUM, /**< enumerated type */ + PROTOBUF_C_TYPE_STRING, /**< UTF-8 or ASCII string */ + PROTOBUF_C_TYPE_BYTES, /**< arbitrary byte sequence */ + PROTOBUF_C_TYPE_MESSAGE, /**< nested message */ +} ProtobufCType; + +/** + * Field wire types. + * + * \see [Message Structure] in the Protocol Buffers documentation. + * + * [Message Structure]: + * https://developers.google.com/protocol-buffers/docs/encoding#structure + */ +typedef enum { + PROTOBUF_C_WIRE_TYPE_VARINT = 0, + PROTOBUF_C_WIRE_TYPE_64BIT = 1, + PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED = 2, + /* "Start group" and "end group" wire types are unsupported. */ + PROTOBUF_C_WIRE_TYPE_32BIT = 5, +} ProtobufCWireType; + +struct ProtobufCAllocator; +struct ProtobufCBinaryData; +struct ProtobufCBuffer; +struct ProtobufCBufferSimple; +struct ProtobufCEnumDescriptor; +struct ProtobufCEnumValue; +struct ProtobufCEnumValueIndex; +struct ProtobufCFieldDescriptor; +struct ProtobufCIntRange; +struct ProtobufCMessage; +struct ProtobufCMessageDescriptor; +struct ProtobufCMessageUnknownField; +struct ProtobufCMethodDescriptor; +struct ProtobufCService; +struct ProtobufCServiceDescriptor; + +typedef struct ProtobufCAllocator ProtobufCAllocator; +typedef struct ProtobufCBinaryData ProtobufCBinaryData; +typedef struct ProtobufCBuffer ProtobufCBuffer; +typedef struct ProtobufCBufferSimple ProtobufCBufferSimple; +typedef struct ProtobufCEnumDescriptor ProtobufCEnumDescriptor; +typedef struct ProtobufCEnumValue ProtobufCEnumValue; +typedef struct ProtobufCEnumValueIndex ProtobufCEnumValueIndex; +typedef struct ProtobufCFieldDescriptor ProtobufCFieldDescriptor; +typedef struct ProtobufCIntRange ProtobufCIntRange; +typedef struct ProtobufCMessage ProtobufCMessage; +typedef struct ProtobufCMessageDescriptor ProtobufCMessageDescriptor; +typedef struct ProtobufCMessageUnknownField ProtobufCMessageUnknownField; +typedef struct ProtobufCMethodDescriptor ProtobufCMethodDescriptor; +typedef struct ProtobufCService ProtobufCService; +typedef struct ProtobufCServiceDescriptor ProtobufCServiceDescriptor; + +/** Boolean type. */ +typedef int protobuf_c_boolean; + +typedef void (*ProtobufCClosure)(const ProtobufCMessage *, void *closure_data); +typedef void (*ProtobufCMessageInit)(ProtobufCMessage *); +typedef void (*ProtobufCServiceDestroy)(ProtobufCService *); + +/** + * Structure for defining a custom memory allocator. + */ +struct ProtobufCAllocator { + /** Function to allocate memory. */ + void *(*alloc)(void *allocator_data, size_t size); + + /** Function to free memory. */ + void (*free)(void *allocator_data, void *pointer); + + /** Opaque pointer passed to `alloc` and `free` functions. */ + void *allocator_data; +}; + +/** + * Structure for the protobuf `bytes` scalar type. + * + * The data contained in a `ProtobufCBinaryData` is an arbitrary sequence of + * bytes. It may contain embedded `NUL` characters and is not required to be + * `NUL`-terminated. + */ +struct ProtobufCBinaryData { + size_t len; /**< Number of bytes in the `data` field. */ + uint8_t *data; /**< Data bytes. */ +}; + +/** + * Structure for defining a virtual append-only buffer. Used by + * protobuf_c_message_pack_to_buffer() to abstract the consumption of serialized + * bytes. + * + * `ProtobufCBuffer` "subclasses" may be defined on the stack. For example, to + * write to a `FILE` object: + * +~~~{.c} +typedef struct { + ProtobufCBuffer base; + FILE *fp; +} BufferAppendToFile; + +static void +my_buffer_file_append(ProtobufCBuffer *buffer, + size_t len, + const uint8_t *data) +{ + BufferAppendToFile *file_buf = (BufferAppendToFile *) buffer; + fwrite(data, len, 1, file_buf->fp); // XXX: No error handling! +} +~~~ + * + * To use this new type of ProtobufCBuffer, it could be called as follows: + * +~~~{.c} +... +BufferAppendToFile tmp = {0}; +tmp.base.append = my_buffer_file_append; +tmp.fp = fp; +protobuf_c_message_pack_to_buffer(&message, &tmp); +... +~~~ + */ +struct ProtobufCBuffer { + /** Append function. Consumes the `len` bytes stored at `data`. */ + void (*append)(ProtobufCBuffer *buffer, + size_t len, + const uint8_t *data); +}; + +/** + * Simple buffer "subclass" of `ProtobufCBuffer`. + * + * A `ProtobufCBufferSimple` object is declared on the stack and uses a + * scratch buffer provided by the user for the initial allocation. It performs + * exponential resizing, using dynamically allocated memory. A + * `ProtobufCBufferSimple` object can be created and used as follows: + * +~~~{.c} +uint8_t pad[128]; +ProtobufCBufferSimple simple = PROTOBUF_C_BUFFER_SIMPLE_INIT(pad); +ProtobufCBuffer *buffer = (ProtobufCBuffer *) &simple; +~~~ + * + * `buffer` can now be used with `protobuf_c_message_pack_to_buffer()`. Once a + * message has been serialized to a `ProtobufCBufferSimple` object, the + * serialized data bytes can be accessed from the `.data` field. + * + * To free the memory allocated by a `ProtobufCBufferSimple` object, if any, + * call PROTOBUF_C_BUFFER_SIMPLE_CLEAR() on the object, for example: + * +~~~{.c} +PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&simple); +~~~ + * + * \see PROTOBUF_C_BUFFER_SIMPLE_INIT + * \see PROTOBUF_C_BUFFER_SIMPLE_CLEAR + */ +struct ProtobufCBufferSimple { + /** "Base class". */ + ProtobufCBuffer base; + /** Number of bytes allocated in `data`. */ + size_t alloced; + /** Number of bytes currently stored in `data`. */ + size_t len; + /** Data bytes. */ + uint8_t *data; + /** Whether `data` must be freed. */ + protobuf_c_boolean must_free_data; + /** Allocator to use. May be NULL to indicate the system allocator. */ + ProtobufCAllocator *allocator; +}; + +/** + * Describes an enumeration as a whole, with all of its values. + */ +struct ProtobufCEnumDescriptor { + /** Magic value checked to ensure that the API is used correctly. */ + uint32_t magic; + + /** The qualified name (e.g., "namespace.Type"). */ + const char *name; + /** The unqualified name as given in the .proto file (e.g., "Type"). */ + const char *short_name; + /** Identifier used in generated C code. */ + const char *c_name; + /** The dot-separated namespace. */ + const char *package_name; + + /** Number elements in `values`. */ + unsigned n_values; + /** Array of distinct values, sorted by numeric value. */ + const ProtobufCEnumValue *values; + + /** Number of elements in `values_by_name`. */ + unsigned n_value_names; + /** Array of named values, including aliases, sorted by name. */ + const ProtobufCEnumValueIndex *values_by_name; + + /** Number of elements in `value_ranges`. */ + unsigned n_value_ranges; + /** Value ranges, for faster lookups by numeric value. */ + const ProtobufCIntRange *value_ranges; + + /** Reserved for future use. */ + void *reserved1; + /** Reserved for future use. */ + void *reserved2; + /** Reserved for future use. */ + void *reserved3; + /** Reserved for future use. */ + void *reserved4; +}; + +/** + * Represents a single value of an enumeration. + */ +struct ProtobufCEnumValue { + /** The string identifying this value in the .proto file. */ + const char *name; + + /** The string identifying this value in generated C code. */ + const char *c_name; + + /** The numeric value assigned in the .proto file. */ + int value; +}; + +/** + * Used by `ProtobufCEnumDescriptor` to look up enum values. + */ +struct ProtobufCEnumValueIndex { + /** Name of the enum value. */ + const char *name; + /** Index into values[] array. */ + unsigned index; +}; + +/** + * Describes a single field in a message. + */ +struct ProtobufCFieldDescriptor { + /** Name of the field as given in the .proto file. */ + const char *name; + + /** Tag value of the field as given in the .proto file. */ + uint32_t id; + + /** Whether the field is `REQUIRED`, `OPTIONAL`, or `REPEATED`. */ + ProtobufCLabel label; + + /** The type of the field. */ + ProtobufCType type; + + /** + * The offset in bytes of the message's C structure's quantifier field + * (the `has_MEMBER` field for optional members or the `n_MEMBER` field + * for repeated members or the case enum for oneofs). + */ + unsigned quantifier_offset; + + /** + * The offset in bytes into the message's C structure for the member + * itself. + */ + unsigned offset; + + /** + * A type-specific descriptor. + * + * If `type` is `PROTOBUF_C_TYPE_ENUM`, then `descriptor` points to the + * corresponding `ProtobufCEnumDescriptor`. + * + * If `type` is `PROTOBUF_C_TYPE_MESSAGE`, then `descriptor` points to + * the corresponding `ProtobufCMessageDescriptor`. + * + * Otherwise this field is NULL. + */ + const void *descriptor; /* for MESSAGE and ENUM types */ + + /** The default value for this field, if defined. May be NULL. */ + const void *default_value; + + /** + * A flag word. Zero or more of the bits defined in the + * `ProtobufCFieldFlag` enum may be set. + */ + uint32_t flags; + + /** Reserved for future use. */ + unsigned reserved_flags; + /** Reserved for future use. */ + void *reserved2; + /** Reserved for future use. */ + void *reserved3; +}; + +/** + * Helper structure for optimizing int => index lookups in the case + * where the keys are mostly consecutive values, as they presumably are for + * enums and fields. + * + * The data structures requires that the values in the original array are + * sorted. + */ +struct ProtobufCIntRange { + int start_value; + unsigned orig_index; + /* + * NOTE: the number of values in the range can be inferred by looking + * at the next element's orig_index. A dummy element is added to make + * this simple. + */ +}; + +/** + * An instance of a message. + * + * `ProtobufCMessage` is a light-weight "base class" for all messages. + * + * In particular, `ProtobufCMessage` doesn't have any allocation policy + * associated with it. That's because it's common to create `ProtobufCMessage` + * objects on the stack. In fact, that's what we recommend for sending messages. + * If the object is allocated from the stack, you can't really have a memory + * leak. + * + * This means that calls to functions like protobuf_c_message_unpack() which + * return a `ProtobufCMessage` must be paired with a call to a free function, + * like protobuf_c_message_free_unpacked(). + */ +struct ProtobufCMessage { + /** The descriptor for this message type. */ + const ProtobufCMessageDescriptor *descriptor; + /** The number of elements in `unknown_fields`. */ + unsigned n_unknown_fields; + /** The fields that weren't recognized by the parser. */ + ProtobufCMessageUnknownField *unknown_fields; +}; + +/** + * Describes a message. + */ +struct ProtobufCMessageDescriptor { + /** Magic value checked to ensure that the API is used correctly. */ + uint32_t magic; + + /** The qualified name (e.g., "namespace.Type"). */ + const char *name; + /** The unqualified name as given in the .proto file (e.g., "Type"). */ + const char *short_name; + /** Identifier used in generated C code. */ + const char *c_name; + /** The dot-separated namespace. */ + const char *package_name; + + /** + * Size in bytes of the C structure representing an instance of this + * type of message. + */ + size_t sizeof_message; + + /** Number of elements in `fields`. */ + unsigned n_fields; + /** Field descriptors, sorted by tag number. */ + const ProtobufCFieldDescriptor *fields; + /** Used for looking up fields by name. */ + const unsigned *fields_sorted_by_name; + + /** Number of elements in `field_ranges`. */ + unsigned n_field_ranges; + /** Used for looking up fields by id. */ + const ProtobufCIntRange *field_ranges; + + /** Message initialisation function. */ + ProtobufCMessageInit message_init; + + /** Reserved for future use. */ + void *reserved1; + /** Reserved for future use. */ + void *reserved2; + /** Reserved for future use. */ + void *reserved3; +}; + +/** + * An unknown message field. + */ +struct ProtobufCMessageUnknownField { + /** The tag number. */ + uint32_t tag; + /** The wire type of the field. */ + ProtobufCWireType wire_type; + /** Number of bytes in `data`. */ + size_t len; + /** Field data. */ + uint8_t *data; +}; + +/** + * Method descriptor. + */ +struct ProtobufCMethodDescriptor { + /** Method name. */ + const char *name; + /** Input message descriptor. */ + const ProtobufCMessageDescriptor *input; + /** Output message descriptor. */ + const ProtobufCMessageDescriptor *output; +}; + +/** + * Service. + */ +struct ProtobufCService { + /** Service descriptor. */ + const ProtobufCServiceDescriptor *descriptor; + /** Function to invoke the service. */ + void (*invoke)(ProtobufCService *service, + unsigned method_index, + const ProtobufCMessage *input, + ProtobufCClosure closure, + void *closure_data); + /** Function to destroy the service. */ + void (*destroy)(ProtobufCService *service); +}; + +/** + * Service descriptor. + */ +struct ProtobufCServiceDescriptor { + /** Magic value checked to ensure that the API is used correctly. */ + uint32_t magic; + + /** Service name. */ + const char *name; + /** Short version of service name. */ + const char *short_name; + /** C identifier for the service name. */ + const char *c_name; + /** Package name. */ + const char *package; + /** Number of elements in `methods`. */ + unsigned n_methods; + /** Method descriptors, in the order defined in the .proto file. */ + const ProtobufCMethodDescriptor *methods; + /** Sort index of methods. */ + const unsigned *method_indices_by_name; +}; + +/** + * Get the version of the protobuf-c library. Note that this is the version of + * the library linked against, not the version of the headers compiled against. + * + * \return A string containing the version number of protobuf-c. + */ +PROTOBUF_C__API +const char * +protobuf_c_version(void); + +/** + * Get the version of the protobuf-c library. Note that this is the version of + * the library linked against, not the version of the headers compiled against. + * + * \return A 32 bit unsigned integer containing the version number of + * protobuf-c, represented in base-10 as (MAJOR*1E6) + (MINOR*1E3) + PATCH. + */ +PROTOBUF_C__API +uint32_t +protobuf_c_version_number(void); + +/** + * The version of the protobuf-c headers, represented as a string using the same + * format as protobuf_c_version(). + */ +#define PROTOBUF_C_VERSION "1.3.0" + +/** + * The version of the protobuf-c headers, represented as an integer using the + * same format as protobuf_c_version_number(). + */ +#define PROTOBUF_C_VERSION_NUMBER 1003000 + +/** + * The minimum protoc-c version which works with the current version of the + * protobuf-c headers. + */ +#define PROTOBUF_C_MIN_COMPILER_VERSION 1000000 + +/** + * Look up a `ProtobufCEnumValue` from a `ProtobufCEnumDescriptor` by name. + * + * \param desc + * The `ProtobufCEnumDescriptor` object. + * \param name + * The `name` field from the corresponding `ProtobufCEnumValue` object to + * match. + * \return + * A `ProtobufCEnumValue` object. + * \retval NULL + * If not found or if the optimize_for = CODE_SIZE option was set. + */ +PROTOBUF_C__API +const ProtobufCEnumValue * +protobuf_c_enum_descriptor_get_value_by_name( + const ProtobufCEnumDescriptor *desc, + const char *name); + +/** + * Look up a `ProtobufCEnumValue` from a `ProtobufCEnumDescriptor` by numeric + * value. + * + * \param desc + * The `ProtobufCEnumDescriptor` object. + * \param value + * The `value` field from the corresponding `ProtobufCEnumValue` object to + * match. + * + * \return + * A `ProtobufCEnumValue` object. + * \retval NULL + * If not found. + */ +PROTOBUF_C__API +const ProtobufCEnumValue * +protobuf_c_enum_descriptor_get_value( + const ProtobufCEnumDescriptor *desc, + int value); + +/** + * Look up a `ProtobufCFieldDescriptor` from a `ProtobufCMessageDescriptor` by + * the name of the field. + * + * \param desc + * The `ProtobufCMessageDescriptor` object. + * \param name + * The name of the field. + * \return + * A `ProtobufCFieldDescriptor` object. + * \retval NULL + * If not found or if the optimize_for = CODE_SIZE option was set. + */ +PROTOBUF_C__API +const ProtobufCFieldDescriptor * +protobuf_c_message_descriptor_get_field_by_name( + const ProtobufCMessageDescriptor *desc, + const char *name); + +/** + * Look up a `ProtobufCFieldDescriptor` from a `ProtobufCMessageDescriptor` by + * the tag value of the field. + * + * \param desc + * The `ProtobufCMessageDescriptor` object. + * \param value + * The tag value of the field. + * \return + * A `ProtobufCFieldDescriptor` object. + * \retval NULL + * If not found. + */ +PROTOBUF_C__API +const ProtobufCFieldDescriptor * +protobuf_c_message_descriptor_get_field( + const ProtobufCMessageDescriptor *desc, + unsigned value); + +/** + * Determine the number of bytes required to store the serialised message. + * + * \param message + * The message object to serialise. + * \return + * Number of bytes. + */ +PROTOBUF_C__API +size_t +protobuf_c_message_get_packed_size(const ProtobufCMessage *message); + +/** + * Serialise a message from its in-memory representation. + * + * This function stores the serialised bytes of the message in a pre-allocated + * buffer. + * + * \param message + * The message object to serialise. + * \param[out] out + * Buffer to store the bytes of the serialised message. This buffer must + * have enough space to store the packed message. Use + * protobuf_c_message_get_packed_size() to determine the number of bytes + * required. + * \return + * Number of bytes stored in `out`. + */ +PROTOBUF_C__API +size_t +protobuf_c_message_pack(const ProtobufCMessage *message, uint8_t *out); + +/** + * Serialise a message from its in-memory representation to a virtual buffer. + * + * This function calls the `append` method of a `ProtobufCBuffer` object to + * consume the bytes generated by the serialiser. + * + * \param message + * The message object to serialise. + * \param buffer + * The virtual buffer object. + * \return + * Number of bytes passed to the virtual buffer. + */ +PROTOBUF_C__API +size_t +protobuf_c_message_pack_to_buffer( + const ProtobufCMessage *message, + ProtobufCBuffer *buffer); + +/** + * Unpack a serialised message into an in-memory representation. + * + * \param descriptor + * The message descriptor. + * \param allocator + * `ProtobufCAllocator` to use for memory allocation. May be NULL to + * specify the default allocator. + * \param len + * Length in bytes of the serialised message. + * \param data + * Pointer to the serialised message. + * \return + * An unpacked message object. + * \retval NULL + * If an error occurred during unpacking. + */ +PROTOBUF_C__API +ProtobufCMessage * +protobuf_c_message_unpack( + const ProtobufCMessageDescriptor *descriptor, + ProtobufCAllocator *allocator, + size_t len, + const uint8_t *data); + +/** + * Free an unpacked message object. + * + * This function should be used to deallocate the memory used by a call to + * protobuf_c_message_unpack(). + * + * \param message + * The message object to free. May be NULL. + * \param allocator + * `ProtobufCAllocator` to use for memory deallocation. May be NULL to + * specify the default allocator. + */ +PROTOBUF_C__API +void +protobuf_c_message_free_unpacked( + ProtobufCMessage *message, + ProtobufCAllocator *allocator); + +/** + * Check the validity of a message object. + * + * Makes sure all required fields (`PROTOBUF_C_LABEL_REQUIRED`) are present. + * Recursively checks nested messages. + * + * \retval TRUE + * Message is valid. + * \retval FALSE + * Message is invalid. + */ +PROTOBUF_C__API +protobuf_c_boolean +protobuf_c_message_check(const ProtobufCMessage *); + +/** Message initialiser. */ +#define PROTOBUF_C_MESSAGE_INIT(descriptor) { descriptor, 0, NULL } + +/** + * Initialise a message object from a message descriptor. + * + * \param descriptor + * Message descriptor. + * \param message + * Allocated block of memory of size `descriptor->sizeof_message`. + */ +PROTOBUF_C__API +void +protobuf_c_message_init( + const ProtobufCMessageDescriptor *descriptor, + void *message); + +/** + * Free a service. + * + * \param service + * The service object to free. + */ +PROTOBUF_C__API +void +protobuf_c_service_destroy(ProtobufCService *service); + +/** + * Look up a `ProtobufCMethodDescriptor` by name. + * + * \param desc + * Service descriptor. + * \param name + * Name of the method. + * + * \return + * A `ProtobufCMethodDescriptor` object. + * \retval NULL + * If not found or if the optimize_for = CODE_SIZE option was set. + */ +PROTOBUF_C__API +const ProtobufCMethodDescriptor * +protobuf_c_service_descriptor_get_method_by_name( + const ProtobufCServiceDescriptor *desc, + const char *name); + +/** + * Initialise a `ProtobufCBufferSimple` object. + */ +#define PROTOBUF_C_BUFFER_SIMPLE_INIT(array_of_bytes) \ +{ \ + { protobuf_c_buffer_simple_append }, \ + sizeof(array_of_bytes), \ + 0, \ + (array_of_bytes), \ + 0, \ + NULL \ +} + +/** + * Clear a `ProtobufCBufferSimple` object, freeing any allocated memory. + */ +#define PROTOBUF_C_BUFFER_SIMPLE_CLEAR(simp_buf) \ +do { \ + if ((simp_buf)->must_free_data) { \ + if ((simp_buf)->allocator != NULL) \ + (simp_buf)->allocator->free( \ + (simp_buf)->allocator, \ + (simp_buf)->data); \ + else \ + free((simp_buf)->data); \ + } \ +} while (0) + +/** + * The `append` method for `ProtobufCBufferSimple`. + * + * \param buffer + * The buffer object to append to. Must actually be a + * `ProtobufCBufferSimple` object. + * \param len + * Number of bytes in `data`. + * \param data + * Data to append. + */ +PROTOBUF_C__API +void +protobuf_c_buffer_simple_append( + ProtobufCBuffer *buffer, + size_t len, + const unsigned char *data); + +PROTOBUF_C__API +void +protobuf_c_service_generated_init( + ProtobufCService *service, + const ProtobufCServiceDescriptor *descriptor, + ProtobufCServiceDestroy destroy); + +PROTOBUF_C__API +void +protobuf_c_service_invoke_internal( + ProtobufCService *service, + unsigned method_index, + const ProtobufCMessage *input, + ProtobufCClosure closure, + void *closure_data); + +/**@}*/ + +PROTOBUF_C__END_DECLS + +#endif /* PROTOBUF_C_H */ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_bytes_field.h b/tools/sdk/include/protobuf-c/protoc-c/c_bytes_field.h new file mode 100644 index 00000000000..c4a71e85b47 --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_bytes_field.h @@ -0,0 +1,100 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_BYTES_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_BYTES_FIELD_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace c { + +class BytesFieldGenerator : public FieldGenerator { + public: + explicit BytesFieldGenerator(const FieldDescriptor* descriptor); + ~BytesFieldGenerator(); + + // implements FieldGenerator --------------------------------------- + void GenerateStructMembers(io::Printer* printer) const; + void GenerateDescriptorInitializer(io::Printer* printer) const; + void GenerateDefaultValueDeclarations(io::Printer* printer) const; + void GenerateDefaultValueImplementations(io::Printer* printer) const; + string GetDefaultValue(void) const; + void GenerateStaticInit(io::Printer* printer) const; + + private: + std::map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(BytesFieldGenerator); +}; + + +} // namespace c +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_C_STRING_FIELD_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_enum.h b/tools/sdk/include/protobuf-c/protoc-c/c_enum.h new file mode 100644 index 00000000000..9eb9a6679ce --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_enum.h @@ -0,0 +1,118 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_ENUM_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_ENUM_H__ + +#include +#include + +namespace google { +namespace protobuf { + namespace io { + class Printer; // printer.h + } +} + +namespace protobuf { +namespace compiler { +namespace c { + +class EnumGenerator { + public: + // See generator.cc for the meaning of dllexport_decl. + explicit EnumGenerator(const EnumDescriptor* descriptor, + const string& dllexport_decl); + ~EnumGenerator(); + + // Header stuff. + + // Generate header code defining the enum. This code should be placed + // within the enum's package namespace, but NOT within any class, even for + // nested enums. + void GenerateDefinition(io::Printer* printer); + + void GenerateDescriptorDeclarations(io::Printer* printer); + + + // Source file stuff. + + // Generate the ProtobufCEnumDescriptor for this enum + void GenerateEnumDescriptor(io::Printer* printer); + + // Generate static initializer for a ProtobufCEnumValue + // given the index of the value in the enum. + void GenerateValueInitializer(io::Printer *printer, int index); + + private: + const EnumDescriptor* descriptor_; + string dllexport_decl_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); +}; + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_ENUM_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_enum_field.h b/tools/sdk/include/protobuf-c/protoc-c/c_enum_field.h new file mode 100644 index 00000000000..11df6824693 --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_enum_field.h @@ -0,0 +1,98 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_ENUM_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_ENUM_FIELD_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace c { + +class EnumFieldGenerator : public FieldGenerator { + public: + explicit EnumFieldGenerator(const FieldDescriptor* descriptor); + ~EnumFieldGenerator(); + + // implements FieldGenerator --------------------------------------- + void GenerateStructMembers(io::Printer* printer) const; + void GenerateDescriptorInitializer(io::Printer* printer) const; + string GetDefaultValue(void) const; + void GenerateStaticInit(io::Printer* printer) const; + + private: + std::map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); +}; + + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_ENUM_FIELD_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_extension.h b/tools/sdk/include/protobuf-c/protoc-c/c_extension.h new file mode 100644 index 00000000000..ddbf270e5a1 --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_extension.h @@ -0,0 +1,110 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_EXTENSION_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_EXTENSION_H__ + +#include +#include + +namespace google { +namespace protobuf { + class FieldDescriptor; // descriptor.h + namespace io { + class Printer; // printer.h + } +} + +namespace protobuf { +namespace compiler { +namespace c { + +// Generates code for an extension, which may be within the scope of some +// message or may be at file scope. This is much simpler than FieldGenerator +// since extensions are just simple identifiers with interesting types. +class ExtensionGenerator { + public: + // See generator.cc for the meaning of dllexport_decl. + explicit ExtensionGenerator(const FieldDescriptor* descriptor, + const string& dllexport_decl); + ~ExtensionGenerator(); + + // Header stuff. + void GenerateDeclaration(io::Printer* printer); + + // Source file stuff. + void GenerateDefinition(io::Printer* printer); + + private: + const FieldDescriptor* descriptor_; + string type_traits_; + string dllexport_decl_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); +}; + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_field.h b/tools/sdk/include/protobuf-c/protoc-c/c_field.h new file mode 100644 index 00000000000..91f1a03dafb --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_field.h @@ -0,0 +1,132 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__ + +#include +#include + +namespace google { +namespace protobuf { + namespace io { + class Printer; // printer.h + } +} + +namespace protobuf { +namespace compiler { +namespace c { + +class FieldGenerator { + public: + explicit FieldGenerator(const FieldDescriptor *descriptor) : descriptor_(descriptor) {} + virtual ~FieldGenerator(); + + // Generate definitions to be included in the structure. + virtual void GenerateStructMembers(io::Printer* printer) const = 0; + + // Generate a static initializer for this field. + virtual void GenerateDescriptorInitializer(io::Printer* printer) const = 0; + + virtual void GenerateDefaultValueDeclarations(io::Printer* printer) const { } + virtual void GenerateDefaultValueImplementations(io::Printer* printer) const { } + virtual string GetDefaultValue() const = 0; + + // Generate members to initialize this field from a static initializer + virtual void GenerateStaticInit(io::Printer* printer) const = 0; + + + protected: + void GenerateDescriptorInitializerGeneric(io::Printer* printer, + bool optional_uses_has, + const string &type_macro, + const string &descriptor_addr) const; + const FieldDescriptor *descriptor_; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); +}; + +// Convenience class which constructs FieldGenerators for a Descriptor. +class FieldGeneratorMap { + public: + explicit FieldGeneratorMap(const Descriptor* descriptor); + ~FieldGeneratorMap(); + + const FieldGenerator& get(const FieldDescriptor* field) const; + + private: + const Descriptor* descriptor_; + scoped_array > field_generators_; + + static FieldGenerator* MakeGenerator(const FieldDescriptor* field); + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); +}; + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_file.h b/tools/sdk/include/protobuf-c/protoc-c/c_file.h new file mode 100644 index 00000000000..ed38ce425c3 --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_file.h @@ -0,0 +1,117 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_FILE_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_FILE_H__ + +#include +#include +#include +#include + +namespace google { +namespace protobuf { + class FileDescriptor; // descriptor.h + namespace io { + class Printer; // printer.h + } +} + +namespace protobuf { +namespace compiler { +namespace c { + +class EnumGenerator; // enum.h +class MessageGenerator; // message.h +class ServiceGenerator; // service.h +class ExtensionGenerator; // extension.h + +class FileGenerator { + public: + // See generator.cc for the meaning of dllexport_decl. + explicit FileGenerator(const FileDescriptor* file, + const string& dllexport_decl); + ~FileGenerator(); + + void GenerateHeader(io::Printer* printer); + void GenerateSource(io::Printer* printer); + + private: + const FileDescriptor* file_; + + scoped_array > message_generators_; + scoped_array > enum_generators_; + scoped_array > service_generators_; + scoped_array > extension_generators_; + + // E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}. + vector package_parts_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); +}; + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_FILE_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_generator.h b/tools/sdk/include/protobuf-c/protoc-c/c_generator.h new file mode 100644 index 00000000000..f454710b36f --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_generator.h @@ -0,0 +1,100 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +// Generates C code for a given .proto file. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_GENERATOR_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_GENERATOR_H__ + +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace c { + +// CodeGenerator implementation which generates a C++ source file and +// header. If you create your own protocol compiler binary and you want +// it to support C++ output, you can do so by registering an instance of this +// CodeGenerator with the CommandLineInterface in your main() function. +class LIBPROTOC_EXPORT CGenerator : public CodeGenerator { + public: + CGenerator(); + ~CGenerator(); + + // implements CodeGenerator ---------------------------------------- + bool Generate(const FileDescriptor* file, + const string& parameter, + OutputDirectory* output_directory, + string* error) const; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CGenerator); +}; + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_GENERATOR_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_helpers.h b/tools/sdk/include/protobuf-c/protoc-c/c_helpers.h new file mode 100644 index 00000000000..9dc8c5e859c --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_helpers.h @@ -0,0 +1,197 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_HELPERS_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_HELPERS_H__ + +#include +#include +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace c { + +// Returns the non-nested type name for the given type. If "qualified" is +// true, prefix the type with the full namespace. For example, if you had: +// package foo.bar; +// message Baz { message Qux {} } +// Then the qualified ClassName for Qux would be: +// Foo__Bar__Baz_Qux +// While the non-qualified version would be: +// Baz_Qux +string ClassName(const Descriptor* descriptor, bool qualified); +string ClassName(const EnumDescriptor* enum_descriptor, bool qualified); + +// --- Borrowed from stubs. --- +template string SimpleItoa(T n) { + std::stringstream stream; + stream << n; + return stream.str(); +} + +string SimpleFtoa(float f); +string SimpleDtoa(double f); +void SplitStringUsing(const string &str, const char *delim, std::vector *out); +string CEscape(const string& src); +string StringReplace(const string& s, const string& oldsub, const string& newsub, bool replace_all); +inline bool HasSuffixString(const string& str, const string& suffix) { return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; } +inline string StripSuffixString(const string& str, const string& suffix) { if (HasSuffixString(str, suffix)) { return str.substr(0, str.size() - suffix.size()); } else { return str; } } +char* FastHexToBuffer(int i, char* buffer); + + +// Get the (unqualified) name that should be used for this field in C code. +// The name is coerced to lower-case to emulate proto1 behavior. People +// should be using lowercase-with-underscores style for proto field names +// anyway, so normally this just returns field->name(). +string FieldName(const FieldDescriptor* field); + +// Get macro string for deprecated field +string FieldDeprecated(const FieldDescriptor* field); + +// Returns the scope where the field was defined (for extensions, this is +// different from the message type to which the field applies). +inline const Descriptor* FieldScope(const FieldDescriptor* field) { + return field->is_extension() ? + field->extension_scope() : field->containing_type(); +} + +// convert a CamelCase class name into an all uppercase affair +// with underscores separating words, e.g. MyClass becomes MY_CLASS. +string CamelToUpper(const string &class_name); +string CamelToLower(const string &class_name); + +// lowercased, underscored name to camel case +string ToCamel(const string &name); + +// lowercase the string +string ToLower(const string &class_name); +string ToUpper(const string &class_name); + +// full_name() to lowercase with underscores +string FullNameToLower(const string &full_name); +string FullNameToUpper(const string &full_name); + +// full_name() to c-typename (with underscores for packages, otherwise camel case) +string FullNameToC(const string &class_name); + +// Splits, indents, formats, and prints comment lines +void PrintComment (io::Printer* printer, string comment); + +// make a string of spaces as long as input +string ConvertToSpaces(const string &input); + +// Strips ".proto" or ".protodevel" from the end of a filename. +string StripProto(const string& filename); + +// Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.). +// Note: non-built-in type names will be qualified, meaning they will start +// with a ::. If you are using the type as a template parameter, you will +// need to insure there is a space between the < and the ::, because the +// ridiculous C++ standard defines "<:" to be a synonym for "[". +const char* PrimitiveTypeName(FieldDescriptor::CppType type); + +// Get the declared type name in CamelCase format, as is used e.g. for the +// methods of WireFormat. For example, TYPE_INT32 becomes "Int32". +const char* DeclaredTypeMethodName(FieldDescriptor::Type type); + +// Convert a file name into a valid identifier. +string FilenameIdentifier(const string& filename); + +// Return the name of the BuildDescriptors() function for a given file. +string GlobalBuildDescriptorsName(const string& filename); + +// return 'required', 'optional', or 'repeated' +string GetLabelName(FieldDescriptor::Label label); + + +// write IntRanges entries for a bunch of sorted values. +// returns the number of ranges there are to bsearch. +unsigned WriteIntRanges(io::Printer* printer, int n_values, const int *values, const string &name); + +struct NameIndex +{ + unsigned index; + const char *name; +}; +int compare_name_indices_by_name(const void*, const void*); + +// Return the syntax version of the file containing the field. +// This wrapper is needed to be able to compile against protobuf2. +inline int FieldSyntax(const FieldDescriptor* field) { +#ifdef HAVE_PROTO3 + return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? 3 : 2; +#else + return 2; +#endif +} + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_HELPERS_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_message.h b/tools/sdk/include/protobuf-c/protoc-c/c_message.h new file mode 100644 index 00000000000..8b115d1c8cb --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_message.h @@ -0,0 +1,141 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { + namespace io { + class Printer; // printer.h + } +} + +namespace protobuf { +namespace compiler { +namespace c { + +class EnumGenerator; // enum.h +class ExtensionGenerator; // extension.h + +class MessageGenerator { + public: + // See generator.cc for the meaning of dllexport_decl. + explicit MessageGenerator(const Descriptor* descriptor, + const string& dllexport_decl); + ~MessageGenerator(); + + // Header stuff. + + // Generate typedef. + void GenerateStructTypedef(io::Printer* printer); + + // Generate descriptor prototype + void GenerateDescriptorDeclarations(io::Printer* printer); + + // Generate descriptor prototype + void GenerateClosureTypedef(io::Printer* printer); + + // Generate definitions of all nested enums (must come before class + // definitions because those classes use the enums definitions). + void GenerateEnumDefinitions(io::Printer* printer); + + // Generate definitions for this class and all its nested types. + void GenerateStructDefinition(io::Printer* printer); + + // Generate __INIT macro for populating this structure + void GenerateStructStaticInitMacro(io::Printer* printer); + + // Generate standard helper functions declarations for this message. + void GenerateHelperFunctionDeclarations(io::Printer* printer, bool is_submessage); + + // Source file stuff. + + // Generate code that initializes the global variable storing the message's + // descriptor. + void GenerateMessageDescriptor(io::Printer* printer); + void GenerateHelperFunctionDefinitions(io::Printer* printer, bool is_submessage); + + private: + + string GetDefaultValueC(const FieldDescriptor *fd); + + const Descriptor* descriptor_; + string dllexport_decl_; + FieldGeneratorMap field_generators_; + scoped_array > nested_generators_; + scoped_array > enum_generators_; + scoped_array > extension_generators_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); +}; + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_message_field.h b/tools/sdk/include/protobuf-c/protoc-c/c_message_field.h new file mode 100644 index 00000000000..b059fb031b0 --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_message_field.h @@ -0,0 +1,97 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_FIELD_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace c { + +class MessageFieldGenerator : public FieldGenerator { + public: + explicit MessageFieldGenerator(const FieldDescriptor* descriptor); + ~MessageFieldGenerator(); + + // implements FieldGenerator --------------------------------------- + void GenerateStructMembers(io::Printer* printer) const; + void GenerateDescriptorInitializer(io::Printer* printer) const; + string GetDefaultValue(void) const; + void GenerateStaticInit(io::Printer* printer) const; + + private: + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); +}; + + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_MESSAGE_FIELD_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_primitive_field.h b/tools/sdk/include/protobuf-c/protoc-c/c_primitive_field.h new file mode 100644 index 00000000000..5ff254c5dd8 --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_primitive_field.h @@ -0,0 +1,96 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_PRIMITIVE_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_PRIMITIVE_FIELD_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace c { + +class PrimitiveFieldGenerator : public FieldGenerator { + public: + explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor); + ~PrimitiveFieldGenerator(); + + // implements FieldGenerator --------------------------------------- + void GenerateStructMembers(io::Printer* printer) const; + void GenerateDescriptorInitializer(io::Printer* printer) const; + string GetDefaultValue(void) const; + void GenerateStaticInit(io::Printer* printer) const; + + private: + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); +}; + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_PRIMITIVE_FIELD_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_service.h b/tools/sdk/include/protobuf-c/protoc-c/c_service.h new file mode 100644 index 00000000000..6f1798ca724 --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_service.h @@ -0,0 +1,112 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_SERVICE_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_SERVICE_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { + namespace io { + class Printer; // printer.h + } +} + +namespace protobuf { +namespace compiler { +namespace c { + +class ServiceGenerator { + public: + // See generator.cc for the meaning of dllexport_decl. + explicit ServiceGenerator(const ServiceDescriptor* descriptor, + const string& dllexport_decl); + ~ServiceGenerator(); + + // Header stuff. + void GenerateMainHFile(io::Printer* printer); + void GenerateVfuncs(io::Printer* printer); + void GenerateInitMacros(io::Printer* printer); + void GenerateDescriptorDeclarations(io::Printer* printer); + void GenerateCallersDeclarations(io::Printer* printer); + + // Source file stuff. + void GenerateCFile(io::Printer* printer); + void GenerateServiceDescriptor(io::Printer* printer); + void GenerateInit(io::Printer* printer); + void GenerateCallersImplementations(io::Printer* printer); + + const ServiceDescriptor* descriptor_; + std::map vars_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceGenerator); +}; + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_SERVICE_H__ diff --git a/tools/sdk/include/protobuf-c/protoc-c/c_string_field.h b/tools/sdk/include/protobuf-c/protoc-c/c_string_field.h new file mode 100644 index 00000000000..68f0d25b7dd --- /dev/null +++ b/tools/sdk/include/protobuf-c/protoc-c/c_string_field.h @@ -0,0 +1,100 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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 Google Inc. 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. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Copyright (c) 2008-2013, Dave Benson. 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 +// 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. + +// Modified to implement C code by Dave Benson. + +#ifndef GOOGLE_PROTOBUF_COMPILER_C_STRING_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_C_STRING_FIELD_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace c { + +class StringFieldGenerator : public FieldGenerator { + public: + explicit StringFieldGenerator(const FieldDescriptor* descriptor); + ~StringFieldGenerator(); + + // implements FieldGenerator --------------------------------------- + void GenerateStructMembers(io::Printer* printer) const; + void GenerateDescriptorInitializer(io::Printer* printer) const; + void GenerateDefaultValueDeclarations(io::Printer* printer) const; + void GenerateDefaultValueImplementations(io::Printer* printer) const; + string GetDefaultValue(void) const; + void GenerateStaticInit(io::Printer* printer) const; + + private: + std::map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator); +}; + + +} // namespace c +} // namespace compiler +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_COMPILER_C_STRING_FIELD_H__ diff --git a/tools/sdk/include/protobuf-c/t/generated-code2/common-test-arrays.h b/tools/sdk/include/protobuf-c/t/generated-code2/common-test-arrays.h new file mode 100644 index 00000000000..1535d38e821 --- /dev/null +++ b/tools/sdk/include/protobuf-c/t/generated-code2/common-test-arrays.h @@ -0,0 +1,62 @@ + +/* data included from the c++ packed-data generator, + and from the c test code. */ + +#define THOUSAND 1000 +#define MILLION 1000000 +#define BILLION 1000000000LL +#define TRILLION 1000000000000LL +#define QUADRILLION 1000000000000000LL +#define QUINTILLION 1000000000000000000LL + +int32_t int32_arr0[2] = { -1, 1 }; +int32_t int32_arr1[5] = { 42, 666, -1123123, 0, 47 }; +int32_t int32_arr_min_max[2] = { INT32_MIN, INT32_MAX }; + +uint32_t uint32_roundnumbers[4] = { BILLION, MILLION, 1, 0 }; +uint32_t uint32_0_max[2] = { 0, UINT32_MAX }; + +int64_t int64_roundnumbers[15] = { -QUINTILLION, -QUADRILLION, -TRILLION, + -BILLION, -MILLION, -THOUSAND, + 1, + THOUSAND, MILLION, BILLION, + TRILLION, QUADRILLION, QUINTILLION }; +int64_t int64_min_max[2] = { INT64_MIN, INT64_MAX }; + +uint64_t uint64_roundnumbers[9] = { 1, + THOUSAND, MILLION, BILLION, + TRILLION, QUADRILLION, QUINTILLION }; +uint64_t uint64_0_1_max[3] = { 0, 1, UINT64_MAX }; +uint64_t uint64_random[] = {0, + 666, + 4200000000ULL, + 16ULL * (uint64_t) QUINTILLION + 33 }; + +#define FLOATING_POINT_RANDOM \ +-1000.0, -100.0, -42.0, 0, 666, 131313 +float float_random[] = { FLOATING_POINT_RANDOM }; +double double_random[] = { FLOATING_POINT_RANDOM }; + +protobuf_c_boolean boolean_0[] = {0 }; +protobuf_c_boolean boolean_1[] = {1 }; +protobuf_c_boolean boolean_random[] = {0,1,1,0,0,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,0,1,1,0 }; + +TEST_ENUM_SMALL_TYPE_NAME enum_small_0[] = { TEST_ENUM_SMALL(VALUE) }; +TEST_ENUM_SMALL_TYPE_NAME enum_small_1[] = { TEST_ENUM_SMALL(OTHER_VALUE) }; +#define T(v) (TEST_ENUM_SMALL_TYPE_NAME)(v) +TEST_ENUM_SMALL_TYPE_NAME enum_small_random[] = {T(0),T(1),T(1),T(0),T(0),T(1),T(1),T(1),T(0),T(0),T(0),T(0),T(0),T(1),T(1),T(1),T(1),T(1),T(1),T(0),T(1),T(1),T(0),T(1),T(1),T(0) }; +#undef T + +#define T(v) (TEST_ENUM_TYPE_NAME)(v) +TEST_ENUM_TYPE_NAME enum_0[] = { T(0) }; +TEST_ENUM_TYPE_NAME enum_1[] = { T(1) }; +TEST_ENUM_TYPE_NAME enum_random[] = { + T(0), T(268435455), T(127), T(16384), T(16383), + T(2097152), T(2097151), T(128), T(268435456), + T(0), T(2097152), T(268435455), T(127), T(16383), T(16384) }; +#undef T + +char *repeated_strings_0[] = { (char*)"onestring" }; +char *repeated_strings_1[] = { (char*)"two", (char*)"string" }; +char *repeated_strings_2[] = { (char*)"many", (char*)"tiny", (char*)"little", (char*)"strings", (char*)"should", (char*)"be", (char*)"handled" }; +char *repeated_strings_3[] = { (char*)"one very long strings XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" }; diff --git a/tools/sdk/include/protocomm/protocomm.h b/tools/sdk/include/protocomm/protocomm.h new file mode 100644 index 00000000000..239d71390b2 --- /dev/null +++ b/tools/sdk/include/protocomm/protocomm.h @@ -0,0 +1,235 @@ +// 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 +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Function prototype for protocomm endpoint handler + */ +typedef esp_err_t (*protocomm_req_handler_t)( + uint32_t session_id, /*!< Session ID for identifying protocomm client */ + const uint8_t *inbuf, /*!< Pointer to user provided input data buffer */ + ssize_t inlen, /*!< Length o the input buffer */ + uint8_t **outbuf, /*!< Pointer to output buffer allocated by handler */ + ssize_t *outlen, /*!< Length of the allocated output buffer */ + void *priv_data /*!< Private data passed to the handler (NULL if not used) */ +); + +/** + * @brief This structure corresponds to a unique instance of protocomm + * returned when the API `protocomm_new()` is called. The remaining + * Protocomm APIs require this object as the first parameter. + * + * @note Structure of the protocomm object is kept private + */ +typedef struct protocomm protocomm_t; + +/** + * @brief Create a new protocomm instance + * + * This API will return a new dynamically allocated protocomm instance + * with all elements of the protocomm_t structure initialized to NULL. + * + * @return + * - protocomm_t* : On success + * - NULL : No memory for allocating new instance + */ +protocomm_t *protocomm_new(); + +/** + * @brief Delete a protocomm instance + * + * This API will deallocate a protocomm instance that was created + * using `protocomm_new()`. + * + * @param[in] pc Pointer to the protocomm instance to be deleted + */ +void protocomm_delete(protocomm_t *pc); + +/** + * @brief Add endpoint request handler for a protocomm instance + * + * This API will bind an endpoint handler function to the specified + * endpoint name, along with any private data that needs to be pass to + * the handler at the time of call. + * + * @note + * - An endpoint must be bound to a valid protocomm instance, + * created using `protocomm_new()`. + * - This function internally calls the registered `add_endpoint()` + * function of the selected transport which is a member of the + * protocomm_t instance structure. + * + * @param[in] pc Pointer to the protocomm instance + * @param[in] ep_name Endpoint identifier(name) string + * @param[in] h Endpoint handler function + * @param[in] priv_data Pointer to private data to be passed as a + * parameter to the handler function on call. + * Pass NULL if not needed. + * + * @return + * - ESP_OK : Success + * - ESP_FAIL : Error adding endpoint / Endpoint with this name already exists + * - ESP_ERR_NO_MEM : Error allocating endpoint resource + * - ESP_ERR_INVALID_ARG : Null instance/name/handler arguments + */ +esp_err_t protocomm_add_endpoint(protocomm_t *pc, const char *ep_name, + protocomm_req_handler_t h, void *priv_data); + +/** + * @brief Remove endpoint request handler for a protocomm instance + * + * This API will remove a registered endpoint handler identified by + * an endpoint name. + * + * @note + * - This function internally calls the registered `remove_endpoint()` + * function which is a member of the protocomm_t instance structure. + * + * @param[in] pc Pointer to the protocomm instance + * @param[in] ep_name Endpoint identifier(name) string + * + * @return + * - ESP_OK : Success + * - ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist + * - ESP_ERR_INVALID_ARG : Null instance/name arguments + */ +esp_err_t protocomm_remove_endpoint(protocomm_t *pc, const char *ep_name); + +/** + * @brief Calls the registered handler of an endpoint session + * for processing incoming data and generating the response + * + * @note + * - An endpoint must be bound to a valid protocomm instance, + * created using `protocomm_new()`. + * - Resulting output buffer must be deallocated by the caller. + * + * @param[in] pc Pointer to the protocomm instance + * @param[in] ep_name Endpoint identifier(name) string + * @param[in] session_id Unique ID for a communication session + * @param[in] inbuf Input buffer contains input request data which is to be + * processed by the registered handler + * @param[in] inlen Length of the input buffer + * @param[out] outbuf Pointer to internally allocated output buffer, + * where the resulting response data output from + * the registered handler is to be stored + * @param[out] outlen Buffer length of the allocated output buffer + * + * @return + * - ESP_OK : Request handled successfully + * - ESP_FAIL : Internal error in execution of registered handler + * - ESP_ERR_NO_MEM : Error allocating internal resource + * - ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist + * - ESP_ERR_INVALID_ARG : Null instance/name arguments + */ +esp_err_t protocomm_req_handle(protocomm_t *pc, const char *ep_name, uint32_t session_id, + const uint8_t *inbuf, ssize_t inlen, + uint8_t **outbuf, ssize_t *outlen); + +/** + * @brief Add endpoint security for a protocomm instance + * + * This API will bind a security session establisher to the specified + * endpoint name, along with any proof of possession that may be required + * for authenticating a session client. + * + * @note + * - An endpoint must be bound to a valid protocomm instance, + * created using `protocomm_new()`. + * - The choice of security can be any `protocomm_security_t` instance. + * Choices `protocomm_security0` and `protocomm_security1` are readily available. + * + * @param[in] pc Pointer to the protocomm instance + * @param[in] ep_name Endpoint identifier(name) string + * @param[in] sec Pointer to endpoint security instance + * @param[in] pop Pointer to proof of possession for authenticating a client + * + * @return + * - ESP_OK : Success + * - ESP_FAIL : Error adding endpoint / Endpoint with this name already exists + * - ESP_ERR_INVALID_STATE : Security endpoint already set + * - ESP_ERR_NO_MEM : Error allocating endpoint resource + * - ESP_ERR_INVALID_ARG : Null instance/name/handler arguments + */ +esp_err_t protocomm_set_security(protocomm_t *pc, const char *ep_name, + const protocomm_security_t *sec, + const protocomm_security_pop_t *pop); + +/** + * @brief Remove endpoint security for a protocomm instance + * + * This API will remove a registered security endpoint identified by + * an endpoint name. + * + * @param[in] pc Pointer to the protocomm instance + * @param[in] ep_name Endpoint identifier(name) string + * + * @return + * - ESP_OK : Success + * - ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist + * - ESP_ERR_INVALID_ARG : Null instance/name arguments + */ +esp_err_t protocomm_unset_security(protocomm_t *pc, const char *ep_name); + +/** + * @brief Set endpoint for version verification + * + * This API can be used for setting an application specific protocol + * version which can be verified by clients through the endpoint. + * + * @note + * - An endpoint must be bound to a valid protocomm instance, + * created using `protocomm_new()`. + + * @param[in] pc Pointer to the protocomm instance + * @param[in] ep_name Endpoint identifier(name) string + * @param[in] version Version identifier(name) string + * + * @return + * - ESP_OK : Success + * - ESP_FAIL : Error adding endpoint / Endpoint with this name already exists + * - ESP_ERR_INVALID_STATE : Version endpoint already set + * - ESP_ERR_NO_MEM : Error allocating endpoint resource + * - ESP_ERR_INVALID_ARG : Null instance/name/handler arguments + */ +esp_err_t protocomm_set_version(protocomm_t *pc, const char *ep_name, + const char *version); + +/** + * @brief Remove version verification endpoint from a protocomm instance + * + * This API will remove a registered version endpoint identified by + * an endpoint name. + * + * @param[in] pc Pointer to the protocomm instance + * @param[in] ep_name Endpoint identifier(name) string + * + * @return + * - ESP_OK : Success + * - ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist + * - ESP_ERR_INVALID_ARG : Null instance/name arguments + */ +esp_err_t protocomm_unset_version(protocomm_t *pc, const char *ep_name); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/protocomm/protocomm_ble.h b/tools/sdk/include/protocomm/protocomm_ble.h new file mode 100644 index 00000000000..92714444f0e --- /dev/null +++ b/tools/sdk/include/protocomm/protocomm_ble.h @@ -0,0 +1,111 @@ +// 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 + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * BLE device name cannot be larger than this value + * 31 bytes (max scan response size) - 1 byte (length) - 1 byte (type) = 29 bytes + */ +#define MAX_BLE_DEVNAME_LEN (ESP_BLE_SCAN_RSP_DATA_LEN_MAX - 2) + +/** + * @brief This structure maps handler required by protocomm layer to + * UUIDs which are used to uniquely identify BLE characteristics + * from a smartphone or a similar client device. + */ +typedef struct name_uuid { + /** + * Name of the handler, which is passed to protocomm layer + */ + const char *name; + + /** + * UUID to be assigned to the BLE characteristic which is + * mapped to the handler + */ + uint16_t uuid; +} protocomm_ble_name_uuid_t; + +/** + * @brief Config parameters for protocomm BLE service + */ +typedef struct { + /** + * BLE device name being broadcast at the time of provisioning + */ + char device_name[MAX_BLE_DEVNAME_LEN]; + + /** + * 128 bit UUID of the provisioning service + */ + uint8_t service_uuid[ESP_UUID_LEN_128]; + + /** + * Number of entries in the Name-UUID lookup table + */ + ssize_t nu_lookup_count; + + /** + * Pointer to the Name-UUID lookup table + */ + protocomm_ble_name_uuid_t *nu_lookup; +} protocomm_ble_config_t; + +/** + * @brief Start Bluetooth Low Energy based transport layer for provisioning + * + * Initialize and start required BLE service for provisioning. This includes + * the initialization for characteristics/service for BLE. + * + * @param[in] pc Protocomm instance pointer obtained from protocomm_new() + * @param[in] config Pointer to config structure for initializing BLE + * + * @return + * - ESP_OK : Success + * - ESP_FAIL : Simple BLE start error + * - ESP_ERR_NO_MEM : Error allocating memory for internal resources + * - ESP_ERR_INVALID_STATE : Error in ble config + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t protocomm_ble_start(protocomm_t *pc, const protocomm_ble_config_t *config); + +/** + * @brief Stop Bluetooth Low Energy based transport layer for provisioning + * + * Stops service/task responsible for BLE based interactions for provisioning + * + * @note You might want to optionally reclaim memory from Bluetooth. + * Refer to the documentation of `esp_bt_mem_release` in that case. + * + * @param[in] pc Same protocomm instance that was passed to protocomm_ble_start() + * + * @return + * - ESP_OK : Success + * - ESP_FAIL : Simple BLE stop error + * - ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance + */ +esp_err_t protocomm_ble_stop(protocomm_t *pc); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/protocomm/protocomm_console.h b/tools/sdk/include/protocomm/protocomm_console.h new file mode 100644 index 00000000000..767bcd7ca01 --- /dev/null +++ b/tools/sdk/include/protocomm/protocomm_console.h @@ -0,0 +1,67 @@ +// 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 + +#define PROTOCOMM_CONSOLE_DEFAULT_CONFIG() { \ + .stack_size = 4096, \ + .task_priority = tskIDLE_PRIORITY + 3, \ +} + +/** + * @brief Config parameters for protocomm console + */ +typedef struct { + size_t stack_size; /*!< Stack size of console task */ + unsigned task_priority; /*!< Priority of console task */ +} protocomm_console_config_t; + +/** + * @brief Start console based protocomm transport + * + * @note This is a singleton. ie. Protocomm can have multiple instances, but only + * one instance can be bound to a console based transport layer. + * + * @param[in] pc Protocomm instance pointer obtained from protocomm_new() + * @param[in] config Config param structure for protocomm console + * + * @return + * - ESP_OK : Success + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_NOT_SUPPORTED : Transport layer bound to another protocomm instance + * - ESP_ERR_INVALID_STATE : Transport layer already bound to this protocomm instance + * - ESP_FAIL : Failed to start console thread + */ +esp_err_t protocomm_console_start(protocomm_t *pc, const protocomm_console_config_t *config); + +/** + * @brief Stop console protocomm transport + * + * @param[in] pc Same protocomm instance that was passed to protocomm_console_start() + * + * @return + * - ESP_OK : Success + * - ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance pointer + */ +esp_err_t protocomm_console_stop(protocomm_t *pc); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/protocomm/protocomm_httpd.h b/tools/sdk/include/protocomm/protocomm_httpd.h new file mode 100644 index 00000000000..2baf7545512 --- /dev/null +++ b/tools/sdk/include/protocomm/protocomm_httpd.h @@ -0,0 +1,107 @@ +// 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 + +#define PROTOCOMM_HTTPD_DEFAULT_CONFIG() { \ + .port = 80, \ + .stack_size = 4096, \ + .task_priority = tskIDLE_PRIORITY + 5, \ +} + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Config parameters for protocomm HTTP server + */ +typedef struct { + + uint16_t port; /*!< Port on which the HTTP server will listen */ + + /** + * Stack size of server task, adjusted depending + * upon stack usage of endpoint handler + */ + size_t stack_size; + unsigned task_priority; /*!< Priority of server task */ +} protocomm_http_server_config_t; /*!< HTTP Server Configuration, if HTTP Server has not been started already */ + +/** Protocomm HTTPD Configuration Data + */ +typedef union { + /** HTTP Server Handle, if ext_handle_provided is set to true + */ + void *handle; + + /** HTTP Server Configuration, if a server is not already active + */ + protocomm_http_server_config_t config; +} protocomm_httpd_config_data_t; + +/** + * @brief Config parameters for protocomm HTTP server + */ +typedef struct { + /** Flag to indicate of an external HTTP Server Handle has been provided. + * In such as case, protocomm will use the same HTTP Server and not start + * a new one internally. + */ + bool ext_handle_provided; + /** Protocomm HTTPD Configuration Data */ + protocomm_httpd_config_data_t data; +} protocomm_httpd_config_t; + +/** + * @brief Start HTTPD protocomm transport + * + * This API internally creates a framework to allow endpoint registration and security + * configuration for the protocomm. + * + * @note This is a singleton. ie. Protocomm can have multiple instances, but only + * one instance can be bound to an HTTP transport layer. + * + * @param[in] pc Protocomm instance pointer obtained from protocomm_new() + * @param[in] config Pointer to config structure for initializing HTTP server + * + * @return + * - ESP_OK : Success + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_NOT_SUPPORTED : Transport layer bound to another protocomm instance + * - ESP_ERR_INVALID_STATE : Transport layer already bound to this protocomm instance + * - ESP_ERR_NO_MEM : Memory allocation for server resource failed + * - ESP_ERR_HTTPD_* : HTTP server error on start + */ +esp_err_t protocomm_httpd_start(protocomm_t *pc, const protocomm_httpd_config_t *config); + +/** + * @brief Stop HTTPD protocomm transport + * + * This API cleans up the HTTPD transport protocomm and frees all the handlers registered + * with the protocomm. + * + * @param[in] pc Same protocomm instance that was passed to protocomm_httpd_start() + * + * @return + * - ESP_OK : Success + * - ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance pointer + */ +esp_err_t protocomm_httpd_stop(protocomm_t *pc); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/protocomm/protocomm_security.h b/tools/sdk/include/protocomm/protocomm_security.h new file mode 100644 index 00000000000..28f43a65742 --- /dev/null +++ b/tools/sdk/include/protocomm/protocomm_security.h @@ -0,0 +1,101 @@ +// 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 Proof Of Possession for authenticating a secure session + */ +typedef struct protocomm_security_pop { + /** + * Pointer to buffer containing the proof of possession data + */ + const uint8_t *data; + + /** + * Length (in bytes) of the proof of possession data + */ + uint16_t len; +} protocomm_security_pop_t; + +/** + * @brief Protocomm security object structure. + * + * The member functions are used for implementing secure + * protocomm sessions. + * + * @note This structure should not have any dynamic + * members to allow re-entrancy + */ +typedef struct protocomm_security { + /** + * Unique version number of security implementation + */ + int ver; + + /** + * Function for initializing/allocating security + * infrastructure + */ + esp_err_t (*init)(); + + /** + * Function for deallocating security infrastructure + */ + esp_err_t (*cleanup)(); + + /** + * Starts new secure transport session with specified ID + */ + esp_err_t (*new_transport_session)(uint32_t session_id); + + /** + * Closes a secure transport session with specified ID + */ + esp_err_t (*close_transport_session)(uint32_t session_id); + + /** + * Handler function for authenticating connection + * request and establishing secure session + */ + esp_err_t (*security_req_handler)(const protocomm_security_pop_t *pop, + uint32_t session_id, + const uint8_t *inbuf, ssize_t inlen, + uint8_t **outbuf, ssize_t *outlen, + void *priv_data); + + /** + * Function which implements the encryption algorithm + */ + esp_err_t (*encrypt)(uint32_t session_id, + const uint8_t *inbuf, ssize_t inlen, + uint8_t *outbuf, ssize_t *outlen); + + /** + * Function which implements the decryption algorithm + */ + esp_err_t (*decrypt)(uint32_t session_id, + const uint8_t *inbuf, ssize_t inlen, + uint8_t *outbuf, ssize_t *outlen); +} protocomm_security_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/protocomm/protocomm_security0.h b/tools/sdk/include/protocomm/protocomm_security0.h new file mode 100644 index 00000000000..9ae8744d470 --- /dev/null +++ b/tools/sdk/include/protocomm/protocomm_security0.h @@ -0,0 +1,33 @@ +// 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 Protocomm security version 0 implementation + * + * This is a simple implementation to be used when no + * security is required for the protocomm instance + */ +extern const protocomm_security_t protocomm_security0; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/protocomm/protocomm_security1.h b/tools/sdk/include/protocomm/protocomm_security1.h new file mode 100644 index 00000000000..12a05c322aa --- /dev/null +++ b/tools/sdk/include/protocomm/protocomm_security1.h @@ -0,0 +1,33 @@ +// 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 Protocomm security version 1 implementation + * + * This is a full fledged security implementation using + * Curve25519 key exchange and AES-256-CTR encryption + */ +extern const protocomm_security_t protocomm_security1; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/pthread/esp_pthread.h b/tools/sdk/include/pthread/esp_pthread.h new file mode 100644 index 00000000000..3ce3703dccb --- /dev/null +++ b/tools/sdk/include/pthread/esp_pthread.h @@ -0,0 +1,73 @@ +// 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 + +#ifndef PTHREAD_STACK_MIN +#define PTHREAD_STACK_MIN CONFIG_PTHREAD_STACK_MIN +#endif + +/** pthread configuration structure that influences pthread creation */ +typedef struct { + size_t stack_size; ///< the stack size of the pthread + size_t prio; ///< the thread's priority + bool inherit_cfg; ///< inherit this configuration further +} esp_pthread_cfg_t; + +/** + * @brief Configure parameters for creating pthread + * + * This API allows you to configure how the subsequent + * pthread_create() call will behave. This call can be used to setup + * configuration parameters like stack size, priority, configuration + * inheritance etc. + * + * If the 'inherit' flag in the configuration structure is enabled, + * then the same configuration is also inherited in the thread + * subtree. + * + * @note Passing non-NULL attributes to pthread_create() will override + * the stack_size parameter set using this API + * + * @param cfg The pthread config parameters + * + * @return + * - ESP_OK if configuration was successfully set + * - ESP_ERR_NO_MEM if out of memory + * - ESP_ERR_INVALID_ARG if stack_size is less than PTHREAD_STACK_MIN + */ +esp_err_t esp_pthread_set_cfg(const esp_pthread_cfg_t *cfg); + +/** + * @brief Get current pthread creation configuration + * + * This will retrieve the current configuration that will be used for + * creating threads. + * + * @param p Pointer to the pthread config structure that will be + * updated with the currently configured parameters + * + * @return + * - ESP_OK if the configuration was available + * - ESP_ERR_NOT_FOUND if a configuration wasn't previously set + */ +esp_err_t esp_pthread_get_cfg(esp_pthread_cfg_t *p); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/sdmmc/sdmmc_cmd.h b/tools/sdk/include/sdmmc/sdmmc_cmd.h index 58b6f082cc0..aa12a4477a4 100644 --- a/tools/sdk/include/sdmmc/sdmmc_cmd.h +++ b/tools/sdk/include/sdmmc/sdmmc_cmd.h @@ -1,4 +1,4 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// 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. @@ -29,7 +29,8 @@ extern "C" { * Support for MMC/eMMC cards will be added later. * * @param host pointer to structure defining host controller - * @param out_card pointer to structure which will receive information about the card when the function completes + * @param out_card pointer to structure which will receive information + * about the card when the function completes * @return * - ESP_OK on success * - One of the error codes from SDMMC host controller @@ -47,8 +48,10 @@ void sdmmc_card_print_info(FILE* stream, const sdmmc_card_t* card); /** * Write given number of sectors to SD/MMC card * - * @param card pointer to card information structure previously initialized using sdmmc_card_init - * @param src pointer to data buffer to read data from; data size must be equal to sector_count * card->csd.sector_size + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param src pointer to data buffer to read data from; data size must be + * equal to sector_count * card->csd.sector_size * @param start_sector sector where to start writing * @param sector_count number of sectors to write * @return @@ -61,8 +64,10 @@ esp_err_t sdmmc_write_sectors(sdmmc_card_t* card, const void* src, /** * Write given number of sectors to SD/MMC card * - * @param card pointer to card information structure previously initialized using sdmmc_card_init - * @param dst pointer to data buffer to write into; buffer size must be at least sector_count * card->csd.sector_size + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param dst pointer to data buffer to write into; buffer size must be + * at least sector_count * card->csd.sector_size * @param start_sector sector where to start reading * @param sector_count number of sectors to read * @return @@ -72,6 +77,149 @@ esp_err_t sdmmc_write_sectors(sdmmc_card_t* card, const void* src, esp_err_t sdmmc_read_sectors(sdmmc_card_t* card, void* dst, size_t start_sector, size_t sector_count); +/** + * Read one byte from an SDIO card using IO_RW_DIRECT (CMD52) + * + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param function IO function number + * @param reg byte address within IO function + * @param[out] out_byte output, receives the value read from the card + * @return + * - ESP_OK on success + * - One of the error codes from SDMMC host controller + */ +esp_err_t sdmmc_io_read_byte(sdmmc_card_t* card, uint32_t function, + uint32_t reg, uint8_t *out_byte); + +/** + * Write one byte to an SDIO card using IO_RW_DIRECT (CMD52) + * + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param function IO function number + * @param reg byte address within IO function + * @param in_byte value to be written + * @param[out] out_byte if not NULL, receives new byte value read + * from the card (read-after-write). + * @return + * - ESP_OK on success + * - One of the error codes from SDMMC host controller + */ +esp_err_t sdmmc_io_write_byte(sdmmc_card_t* card, uint32_t function, + uint32_t reg, uint8_t in_byte, uint8_t* out_byte); + +/** + * Read multiple bytes from an SDIO card using IO_RW_EXTENDED (CMD53) + * + * This function performs read operation using CMD53 in byte mode. + * For block mode, see sdmmc_io_read_blocks. + * + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param function IO function number + * @param addr byte address within IO function where reading starts + * @param dst buffer which receives the data read from card + * @param size number of bytes to read + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_SIZE if size exceeds 512 bytes + * - One of the error codes from SDMMC host controller + */ +esp_err_t sdmmc_io_read_bytes(sdmmc_card_t* card, uint32_t function, + uint32_t addr, void* dst, size_t size); + +/** + * Write multiple bytes to an SDIO card using IO_RW_EXTENDED (CMD53) + * + * This function performs write operation using CMD53 in byte mode. + * For block mode, see sdmmc_io_write_blocks. + * + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param function IO function number + * @param addr byte address within IO function where writing starts + * @param src data to be written + * @param size number of bytes to write + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_SIZE if size exceeds 512 bytes + * - One of the error codes from SDMMC host controller + */ +esp_err_t sdmmc_io_write_bytes(sdmmc_card_t* card, uint32_t function, + uint32_t addr, const void* src, size_t size); + +/** + * Read blocks of data from an SDIO card using IO_RW_EXTENDED (CMD53) + * + * This function performs read operation using CMD53 in block mode. + * For byte mode, see sdmmc_io_read_bytes. + * + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param function IO function number + * @param addr byte address within IO function where writing starts + * @param dst buffer which receives the data read from card + * @param size number of bytes to read, must be divisible by the card block + * size. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes + * - One of the error codes from SDMMC host controller + */ +esp_err_t sdmmc_io_read_blocks(sdmmc_card_t* card, uint32_t function, + uint32_t addr, void* dst, size_t size); + +/** + * Write blocks of data to an SDIO card using IO_RW_EXTENDED (CMD53) + * + * This function performs write operation using CMD53 in block mode. + * For byte mode, see sdmmc_io_write_bytes. + * + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param function IO function number + * @param addr byte address within IO function where writing starts + * @param src data to be written + * @param size number of bytes to read, must be divisible by the card block + * size. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes + * - One of the error codes from SDMMC host controller + */ +esp_err_t sdmmc_io_write_blocks(sdmmc_card_t* card, uint32_t function, + uint32_t addr, const void* src, size_t size); + +/** + * Enable SDIO interrupt in the SDMMC host + * + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @return + * - ESP_OK on success + * - ESP_ERR_NOT_SUPPORTED if the host controller does not support + * IO interrupts + */ +esp_err_t sdmmc_io_enable_int(sdmmc_card_t* card); + +/** + * Block until an SDIO interrupt is received + * + * Slave uses D1 line to signal interrupt condition to the host. + * This function can be used to wait for the interrupt. + * + * @param card pointer to card information structure previously initialized + * using sdmmc_card_init + * @param timeout_ticks time to wait for the interrupt, in RTOS ticks + * @return + * - ESP_OK if the interrupt is received + * - ESP_ERR_NOT_SUPPORTED if the host controller does not support + * IO interrupts + * - ESP_ERR_TIMEOUT if the interrupt does not happen in timeout_ticks + */ +esp_err_t sdmmc_io_wait_int(sdmmc_card_t* card, TickType_t timeout_ticks); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/smartconfig_ack/smartconfig_ack.h b/tools/sdk/include/smartconfig_ack/smartconfig_ack.h new file mode 100644 index 00000000000..be49fd3bd13 --- /dev/null +++ b/tools/sdk/include/smartconfig_ack/smartconfig_ack.h @@ -0,0 +1,74 @@ +// 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 + +#define SC_ACK_TASK_PRIORITY 2 /*!< Priority of sending smartconfig ACK task */ +#define SC_ACK_TASK_STACK_SIZE 2048 /*!< Stack size of sending smartconfig ACK task */ + +#define SC_ACK_TOUCH_SERVER_PORT 18266 /*!< ESP touch UDP port of server on cellphone */ +#define SC_ACK_AIRKISS_SERVER_PORT 10000 /*!< Airkiss UDP port of server on cellphone */ + +#define SC_ACK_TOUCH_LEN 11 /*!< Length of ESP touch ACK context */ +#define SC_ACK_AIRKISS_LEN 7 /*!< Length of Airkiss ACK context */ + +#define SC_ACK_MAX_COUNT 30 /*!< Maximum count of sending smartconfig ACK */ + +/** + * @brief Smartconfig ACK type. + */ +typedef enum { + SC_ACK_TYPE_ESPTOUCH = 0, /*!< ESP touch ACK type */ + SC_ACK_TYPE_AIRKISS, /*!< Airkiss ACK type */ +} sc_ack_type_t; + +/** + * @brief Smartconfig parameters passed to sc_ack_send call. + */ +typedef struct sc_ack { + sc_ack_type_t type; /*!< Smartconfig ACK type */ + uint8_t *link_flag; /*!< Smartconfig link flag */ + sc_callback_t cb; /*!< Smartconfig callback function */ + struct { + uint8_t token; /*!< Smartconfig token to be sent */ + uint8_t mac[6]; /*!< MAC address of station */ + uint8_t ip[4]; /*!< IP address of cellphone */ + } ctx; +} sc_ack_t; + +/** + * @brief Send smartconfig ACK to cellphone. + * + * @attention The API is only used in libsmartconfig.a. + * + * @param param: smartconfig parameters; + */ +void sc_ack_send(sc_ack_t *param); + +/** + * @brief Stop sending smartconfig ACK to cellphone. + * + * @attention The API is only used in libsmartconfig.a. + */ +void sc_ack_send_stop(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tools/sdk/include/soc/soc/can_struct.h b/tools/sdk/include/soc/soc/can_struct.h new file mode 100644 index 00000000000..3f566b135d5 --- /dev/null +++ b/tools/sdk/include/soc/soc/can_struct.h @@ -0,0 +1,211 @@ +// 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 _SOC_CAN_STRUCT_H_ +#define _SOC_CAN_STRUCT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* -------------------------- Register Definitions -------------------------- */ + +/* The CAN peripheral's registers are 8bits, however the ESP32 can only access + * peripheral registers every 32bits. Therefore each CAN register is mapped to + * the least significant byte of every 32bits. + */ +typedef union { + struct { + uint32_t byte: 8; /* LSB */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_reg_t; + +typedef union { + struct { + uint32_t reset: 1; /* MOD.0 Reset Mode */ + uint32_t listen_only: 1; /* MOD.1 Listen Only Mode */ + uint32_t self_test: 1; /* MOD.2 Self Test Mode */ + uint32_t acceptance_filter: 1; /* MOD.3 Acceptance Filter Mode */ + uint32_t reserved28: 28; /* Internal Reserved. MOD.4 Sleep Mode not supported */ + }; + uint32_t val; +} can_mode_reg_t; + +typedef union { + struct { + uint32_t tx_req: 1; /* CMR.0 Transmission Request */ + uint32_t abort_tx: 1; /* CMR.1 Abort Transmission */ + uint32_t release_rx_buff: 1; /* CMR.2 Release Receive Buffer */ + uint32_t clear_data_overrun: 1; /* CMR.3 Clear Data Overrun */ + uint32_t self_rx_req: 1; /* CMR.4 Self Reception Request */ + uint32_t reserved27: 27; /* Internal Reserved */ + }; + uint32_t val; +} can_cmd_reg_t; + +typedef union { + struct { + uint32_t rx_buff: 1; /* SR.0 Receive Buffer Status */ + uint32_t data_overrun: 1; /* SR.1 Data Overrun Status */ + uint32_t tx_buff: 1; /* SR.2 Transmit Buffer Status */ + uint32_t tx_complete: 1; /* SR.3 Transmission Complete Status */ + uint32_t rx: 1; /* SR.4 Receive Status */ + uint32_t tx: 1; /* SR.5 Transmit Status */ + uint32_t error: 1; /* SR.6 Error Status */ + uint32_t bus: 1; /* SR.7 Bus Status */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_status_reg_t; + +typedef union { + struct { + uint32_t rx: 1; /* IR.0 Receive Interrupt */ + uint32_t tx: 1; /* IR.1 Transmit Interrupt */ + uint32_t err_warn: 1; /* IR.2 Error Interrupt */ + uint32_t data_overrun: 1; /* IR.3 Data Overrun Interrupt */ + uint32_t reserved1: 1; /* Internal Reserved (Wake-up not supported) */ + uint32_t err_passive: 1; /* IR.5 Error Passive Interrupt */ + uint32_t arb_lost: 1; /* IR.6 Arbitration Lost Interrupt */ + uint32_t bus_err: 1; /* IR.7 Bus Error Interrupt */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_intr_reg_t; + +typedef union { + struct { + uint32_t rx: 1; /* IER.0 Receive Interrupt Enable */ + uint32_t tx: 1; /* IER.1 Transmit Interrupt Enable */ + uint32_t err_warn: 1; /* IER.2 Error Interrupt Enable */ + uint32_t data_overrun: 1; /* IER.3 Data Overrun Interrupt Enable */ + uint32_t reserved1: 1; /* Internal Reserved (Wake-up not supported) */ + uint32_t err_passive: 1; /* IER.5 Error Passive Interrupt Enable */ + uint32_t arb_lost: 1; /* IER.6 Arbitration Lost Interrupt Enable */ + uint32_t bus_err: 1; /* IER.7 Bus Error Interrupt Enable */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_intr_en_reg_t; + +typedef union { + struct { + uint32_t baud_rate_prescaler: 6; /* BTR0[5:0] Baud Rate Prescaler */ + uint32_t sync_jump_width: 2; /* BTR0[7:6] Synchronization Jump Width*/ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_bus_tim_0_reg_t; + +typedef union { + struct { + uint32_t time_seg_1: 4; /* BTR1[3:0] Timing Segment 1 */ + uint32_t time_seg_2: 3; /* BTR1[6:4] Timing Segment 2 */ + uint32_t sampling: 1; /* BTR1.7 Sampling*/ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_bus_tim_1_reg_t; + +typedef union { + struct { + uint32_t arbitration_lost_capture: 5; /* ALC[4:0] Arbitration lost capture */ + uint32_t reserved27: 27; /* Internal Reserved */ + }; + uint32_t val; +} can_arb_lost_cap_reg_t; + +typedef union { + struct { + uint32_t segment: 5; /* ECC[4:0] Error Code Segment 0 to 5 */ + uint32_t direction: 1; /* ECC.5 Error Direction (TX/RX) */ + uint32_t error_code: 2; /* ECC[7:6] Error Code */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_err_code_cap_reg_t; + +typedef struct { + can_reg_t code_reg[4]; + can_reg_t mask_reg[4]; + uint32_t reserved32[5]; +} can_acc_filter_t; + +typedef union { + struct { + uint32_t rx_message_counter: 5; /* RMC[4:0] RX Message Counter */ + uint32_t reserved27: 27; /* Internal Reserved */ + }; + uint32_t val; +} can_rx_msg_cnt_reg_t; + +typedef union { + struct { + uint32_t clock_divider: 3; /* CDR[2:0] CLKOUT frequency selector based of fOSC */ + uint32_t clock_off: 1; /* CDR.3 CLKOUT enable/disable */ + uint32_t reserved3: 3; /* Internal Reserved. RXINTEN and CBP not supported */ + uint32_t can_mode: 1; /* CDR.7 BasicCAN:0 PeliCAN:1 */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_clk_div_reg_t; + +/* ---------------------------- Register Layout ------------------------------ */ + +typedef volatile struct { + //Configuration and Control Registers + can_mode_reg_t mode_reg; /* Address 0 */ + can_cmd_reg_t command_reg; /* Address 1 */ + can_status_reg_t status_reg; /* Address 2 */ + can_intr_reg_t interrupt_reg; /* Address 3 */ + can_intr_en_reg_t interrupt_enable_reg; /* Address 4 */ + uint32_t reserved_05; /* Address 5 */ + can_bus_tim_0_reg_t bus_timing_0_reg; /* Address 6 */ + can_bus_tim_1_reg_t bus_timing_1_reg; /* Address 7 */ + uint32_t reserved_08; /* Address 8 (Output control not supported) */ + uint32_t reserved_09; /* Address 9 (Test Register not supported) */ + uint32_t reserved_10; /* Address 10 */ + + //Capture and Counter Registers + can_arb_lost_cap_reg_t arbitration_lost_captue_reg; /* Address 11 */ + can_err_code_cap_reg_t error_code_capture_reg; /* Address 12 */ + can_reg_t error_warning_limit_reg; /* EWLR[7:0] Error Warning Limit: Address 13 */ + can_reg_t rx_error_counter_reg; /* RXERR[7:0] Receive Error Counter: Address 14 */ + can_reg_t tx_error_counter_reg; /* TXERR[7:0] Transmit Error Counter: Address 15 */ + + //Shared Registers (TX Buff/RX Buff/Acc Filter) + union { + can_acc_filter_t acceptance_filter; + can_reg_t tx_rx_buffer[13]; + }; /* Address 16-28 TX/RX Buffer and Acc Filter*/; + + //Misc Registers + can_rx_msg_cnt_reg_t rx_message_counter_reg; /* Address 29 */ + can_reg_t reserved_30; /* Address 30 (RX Buffer Start Address not supported) */ + can_clk_div_reg_t clock_divider_reg; /* Address 31 */ + + //Start of RX FIFO +} can_dev_t; + +_Static_assert(sizeof(can_dev_t) == 128, "CAN registers should be 32 * 4 bytes"); + +extern can_dev_t CAN; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_CAN_STRUCT_H_ */ + diff --git a/tools/sdk/include/soc/soc/cpu.h b/tools/sdk/include/soc/soc/cpu.h index 05ec91776b1..f28feb59fa2 100644 --- a/tools/sdk/include/soc/soc/cpu.h +++ b/tools/sdk/include/soc/soc/cpu.h @@ -19,6 +19,7 @@ #include #include #include "xtensa/corebits.h" +#include "xtensa/config/core.h" /* C macros for xtensa special register read/write/exchange */ @@ -51,6 +52,14 @@ static inline void cpu_write_itlb(unsigned vpn, unsigned attr) asm volatile ("witlb %1, %0; isync\n" :: "r" (vpn), "r" (attr)); } +static inline void cpu_init_memctl() +{ +#if XCHAL_ERRATUM_572 + uint32_t memctl = XCHAL_CACHE_MEMCTL_DEFAULT; + WSR(MEMCTL, memctl); +#endif // XCHAL_ERRATUM_572 +} + /** * @brief Configure memory region protection * diff --git a/tools/sdk/include/soc/soc/dport_access.h b/tools/sdk/include/soc/soc/dport_access.h index 817ac98e7b7..2639e46ef14 100644 --- a/tools/sdk/include/soc/soc/dport_access.h +++ b/tools/sdk/include/soc/soc/dport_access.h @@ -18,6 +18,9 @@ #include #include "esp_attr.h" #include "esp_dport_access.h" +#include "soc.h" +#include "uart_reg.h" +#include "xtensa/xtruntime.h" #ifdef __cplusplus extern "C" { @@ -28,10 +31,29 @@ extern "C" { // The _DPORT_xxx register read macros access DPORT memory directly (as opposed to // DPORT_REG_READ which applies SMP-safe protections). // -// Use DPORT_REG_READ versions to be SMP-safe in IDF apps. If you want to -// make a sequence of DPORT reads, use DPORT_STALL_OTHER_CPU_START() macro -// explicitly and then use _DPORT_REG_READ macro while other CPU is stalled. -// +// There are several ways to read the DPORT registers: +// 1) Use DPORT_REG_READ versions to be SMP-safe in IDF apps. +// This method uses the pre-read APB implementation(*) without stall other CPU. +// This is beneficial for single readings. +// 2) If you want to make a sequence of DPORT reads to buffer, +// use dport_read_buffer(buff_out, address, num_words), +// it is the faster method and it doesn't stop other CPU. +// 3) If you want to make a sequence of DPORT reads, but you don't want to stop other CPU +// and you want to do it faster then you need use DPORT_SEQUENCE_REG_READ(). +// The difference from the first is that the user himself must disable interrupts while DPORT reading. +// Note that disable interrupt need only if the chip has two cores. +// 4) If you want to make a sequence of DPORT reads, +// use DPORT_STALL_OTHER_CPU_START() macro explicitly +// and then use _DPORT_REG_READ macro while other CPU is stalled. +// After completing read operations, use DPORT_STALL_OTHER_CPU_END(). +// This method uses stall other CPU while reading DPORT registers. +// Useful for compatibility, as well as for large consecutive readings. +// This method is slower, but must be used if ROM functions or +// other code is called which accesses DPORT without any other workaround. +// *) The pre-readable APB register before reading the DPORT register +// helps synchronize the operation of the two CPUs, +// so that reading on different CPUs no longer causes random errors APB register. + // _DPORT_REG_WRITE & DPORT_REG_WRITE are equivalent. #define _DPORT_REG_READ(_r) (*(volatile uint32_t *)(_r)) #define _DPORT_REG_WRITE(_r, _v) (*(volatile uint32_t *)(_r)) = (_v) @@ -39,16 +61,56 @@ extern "C" { // Write value to DPORT register (does not require protecting) #define DPORT_REG_WRITE(_r, _v) _DPORT_REG_WRITE((_r), (_v)) -// Read value from register, SMP-safe version. +/** + * @brief Read value from register, SMP-safe version. + * + * This method uses the pre-reading of the APB register before reading the register of the DPORT. + * This implementation is useful for reading DORT registers for single reading without stall other CPU. + * There is disable/enable interrupt. + * + * @param reg Register address + * @return Value + */ static inline uint32_t IRAM_ATTR DPORT_REG_READ(uint32_t reg) { - uint32_t val; - - DPORT_STALL_OTHER_CPU_START(); - val = _DPORT_REG_READ(reg); - DPORT_STALL_OTHER_CPU_END(); +#if defined(BOOTLOADER_BUILD) || !defined(CONFIG_ESP32_DPORT_WORKAROUND) || !defined(ESP_PLATFORM) + return _DPORT_REG_READ(reg); +#else + return esp_dport_access_reg_read(reg); +#endif +} - return val; +/** + * @brief Read value from register, NOT SMP-safe version. + * + * This method uses the pre-reading of the APB register before reading the register of the DPORT. + * There is not disable/enable interrupt. + * The difference from DPORT_REG_READ() is that the user himself must disable interrupts while DPORT reading. + * This implementation is useful for reading DORT registers in loop without stall other CPU. Note the usage example. + * The recommended way to read registers sequentially without stall other CPU + * is to use the method esp_dport_read_buffer(buff_out, address, num_words). It allows you to read registers in the buffer. + * + * \code{c} + * // This example shows how to use it. + * { // Use curly brackets to limit the visibility of variables in macros DPORT_INTERRUPT_DISABLE/RESTORE. + * DPORT_INTERRUPT_DISABLE(); // Disable interrupt only on current CPU. + * for (i = 0; i < max; ++i) { + * array[i] = DPORT_SEQUENCE_REG_READ(Address + i * 4); // reading DPORT registers + * } + * DPORT_INTERRUPT_RESTORE(); // restore the previous interrupt level + * } + * \endcode + * + * @param reg Register address + * @return Value + */ +static inline uint32_t IRAM_ATTR DPORT_SEQUENCE_REG_READ(uint32_t reg) +{ +#if defined(BOOTLOADER_BUILD) || !defined(CONFIG_ESP32_DPORT_WORKAROUND) || !defined(ESP_PLATFORM) + return _DPORT_REG_READ(reg); +#else + return esp_dport_access_sequence_reg_read(reg); +#endif } //get bit or get bits from register @@ -93,16 +155,22 @@ static inline uint32_t IRAM_ATTR DPORT_REG_READ(uint32_t reg) #define _DPORT_REG_SET_BIT(_r, _b) _DPORT_REG_WRITE((_r), (_DPORT_REG_READ(_r)|(_b))) #define _DPORT_REG_CLR_BIT(_r, _b) _DPORT_REG_WRITE((_r), (_DPORT_REG_READ(_r) & (~(_b)))) -//read value from register -static inline uint32_t IRAM_ATTR DPORT_READ_PERI_REG(uint32_t addr) +/** + * @brief Read value from register, SMP-safe version. + * + * This method uses the pre-reading of the APB register before reading the register of the DPORT. + * This implementation is useful for reading DORT registers for single reading without stall other CPU. + * + * @param reg Register address + * @return Value + */ +static inline uint32_t IRAM_ATTR DPORT_READ_PERI_REG(uint32_t reg) { - uint32_t val; - - DPORT_STALL_OTHER_CPU_START(); - val = _DPORT_READ_PERI_REG(addr); - DPORT_STALL_OTHER_CPU_END(); - - return val; +#if defined(BOOTLOADER_BUILD) || !defined(CONFIG_ESP32_DPORT_WORKAROUND) || !defined(ESP_PLATFORM) + return _DPORT_REG_READ(reg); +#else + return esp_dport_access_reg_read(reg); +#endif } //write value to register diff --git a/tools/sdk/include/soc/soc/dport_reg.h b/tools/sdk/include/soc/soc/dport_reg.h index b7c9bdb905b..9cc3320b39b 100644 --- a/tools/sdk/include/soc/soc/dport_reg.h +++ b/tools/sdk/include/soc/soc/dport_reg.h @@ -179,6 +179,9 @@ #define DPORT_CPUPERIOD_SEL_M ((DPORT_CPUPERIOD_SEL_V)<<(DPORT_CPUPERIOD_SEL_S)) #define DPORT_CPUPERIOD_SEL_V 0x3 #define DPORT_CPUPERIOD_SEL_S 0 +#define DPORT_CPUPERIOD_SEL_80 0 +#define DPORT_CPUPERIOD_SEL_160 1 +#define DPORT_CPUPERIOD_SEL_240 2 #define DPORT_PRO_CACHE_CTRL_REG (DR_REG_DPORT_BASE + 0x040) /* DPORT_PRO_DRAM_HL : R/W ;bitpos:[16] ;default: 1'b0 ; */ @@ -958,7 +961,8 @@ #define DPORT_CAN_CLK_EN (BIT(19)) #define DPORT_I2C_EXT1_CLK_EN (BIT(18)) #define DPORT_PWM0_CLK_EN (BIT(17)) -#define DPORT_SPI_CLK_EN_2 (BIT(16)) +#define DPORT_SPI_CLK_EN_2 (BIT(16)) /** Deprecated, please use DPORT_SPI3_CLK_EN **/ +#define DPORT_SPI3_CLK_EN (BIT(16)) #define DPORT_TIMERGROUP1_CLK_EN (BIT(15)) #define DPORT_EFUSE_CLK_EN (BIT(14)) #define DPORT_TIMERGROUP_CLK_EN (BIT(13)) @@ -968,12 +972,14 @@ #define DPORT_RMT_CLK_EN (BIT(9)) #define DPORT_UHCI0_CLK_EN (BIT(8)) #define DPORT_I2C_EXT0_CLK_EN (BIT(7)) -#define DPORT_SPI_CLK_EN (BIT(6)) +#define DPORT_SPI_CLK_EN (BIT(6)) /** Deprecated, please use DPORT_SPI2_CLK_EN **/ +#define DPORT_SPI2_CLK_EN (BIT(6)) #define DPORT_UART1_CLK_EN (BIT(5)) #define DPORT_I2S0_CLK_EN (BIT(4)) #define DPORT_WDG_CLK_EN (BIT(3)) #define DPORT_UART_CLK_EN (BIT(2)) -#define DPORT_SPI_CLK_EN_1 (BIT(1)) +#define DPORT_SPI_CLK_EN_1 (BIT(1)) /** Deprecated, please use DPORT_SPI01_CLK_EN **/ +#define DPORT_SPI01_CLK_EN (BIT(1)) #define DPORT_TIMERS_CLK_EN (BIT(0)) #define DPORT_PERIP_RST_EN_REG (DR_REG_DPORT_BASE + 0x0C4) /* DPORT_PERIP_RST : R/W ;bitpos:[31:0] ;default: 32'h0 ; */ @@ -992,7 +998,8 @@ #define DPORT_CAN_RST (BIT(19)) #define DPORT_I2C_EXT1_RST (BIT(18)) #define DPORT_PWM0_RST (BIT(17)) -#define DPORT_SPI_RST_2 (BIT(16)) +#define DPORT_SPI_RST_2 (BIT(16)) /** Deprecated, please use DPORT_SPI3_RST **/ +#define DPORT_SPI3_RST (BIT(16)) #define DPORT_TIMERGROUP1_RST (BIT(15)) #define DPORT_EFUSE_RST (BIT(14)) #define DPORT_TIMERGROUP_RST (BIT(13)) @@ -1002,12 +1009,14 @@ #define DPORT_RMT_RST (BIT(9)) #define DPORT_UHCI0_RST (BIT(8)) #define DPORT_I2C_EXT0_RST (BIT(7)) -#define DPORT_SPI_RST (BIT(6)) +#define DPORT_SPI_RST (BIT(6)) /** Deprecated, please use DPORT_SPI2_RST **/ +#define DPORT_SPI2_RST (BIT(6)) #define DPORT_UART1_RST (BIT(5)) #define DPORT_I2S0_RST (BIT(4)) #define DPORT_WDG_RST (BIT(3)) #define DPORT_UART_RST (BIT(2)) -#define DPORT_SPI_RST_1 (BIT(1)) +#define DPORT_SPI_RST_1 (BIT(1)) /** Deprecated, please use DPORT_SPI01_RST **/ +#define DPORT_SPI01_RST (BIT(1)) #define DPORT_TIMERS_RST (BIT(0)) #define DPORT_SLAVE_SPI_CONFIG_REG (DR_REG_DPORT_BASE + 0x0C8) /* DPORT_SPI_DECRYPT_ENABLE : R/W ;bitpos:[12] ;default: 1'b0 ; */ @@ -1055,6 +1064,10 @@ #define DPORT_WIFI_CLK_BT_EN_S 11 /* Mask for clock bits used by both WIFI and Bluetooth, bit 0, 3, 6, 7, 8, 9 */ #define DPORT_WIFI_CLK_WIFI_BT_COMMON_M 0x000003c9 +//bluetooth baseband bit11 +#define DPORT_BT_BASEBAND_EN BIT(11) +//bluetooth LC bit16 and bit17 +#define DPORT_BT_LC_EN (BIT(16)|BIT(17)) /* Remaining single bit clock masks */ #define DPORT_WIFI_CLK_SDIOSLAVE_EN BIT(4) diff --git a/tools/sdk/include/soc/soc/efuse_reg.h b/tools/sdk/include/soc/soc/efuse_reg.h index 0be58c46514..a2ee03d3142 100644 --- a/tools/sdk/include/soc/soc/efuse_reg.h +++ b/tools/sdk/include/soc/soc/efuse_reg.h @@ -17,11 +17,11 @@ #include "soc.h" #define EFUSE_BLK0_RDATA0_REG (DR_REG_EFUSE_BASE + 0x000) -/* EFUSE_RD_FLASH_CRYPT_CNT : RO ;bitpos:[27:20] ;default: 8'b0 ; */ +/* EFUSE_RD_FLASH_CRYPT_CNT : RO ;bitpos:[26:20] ;default: 7'b0 ; */ /*description: read for flash_crypt_cnt*/ -#define EFUSE_RD_FLASH_CRYPT_CNT 0x000000FF +#define EFUSE_RD_FLASH_CRYPT_CNT 0x0000007F #define EFUSE_RD_FLASH_CRYPT_CNT_M ((EFUSE_RD_FLASH_CRYPT_CNT_V)<<(EFUSE_RD_FLASH_CRYPT_CNT_S)) -#define EFUSE_RD_FLASH_CRYPT_CNT_V 0xFF +#define EFUSE_RD_FLASH_CRYPT_CNT_V 0x7F #define EFUSE_RD_FLASH_CRYPT_CNT_S 20 /* EFUSE_RD_EFUSE_RD_DIS : RO ;bitpos:[19:16] ;default: 4'b0 ; */ /*description: read for efuse_rd_disable*/ @@ -298,12 +298,15 @@ #define EFUSE_RD_CODING_SCHEME_V 0x3 #define EFUSE_RD_CODING_SCHEME_S 0 +#define EFUSE_CODING_SCHEME_VAL_NONE 0x0 +#define EFUSE_CODING_SCHEME_VAL_34 0x1 + #define EFUSE_BLK0_WDATA0_REG (DR_REG_EFUSE_BASE + 0x01c) -/* EFUSE_FLASH_CRYPT_CNT : R/W ;bitpos:[27:20] ;default: 8'b0 ; */ +/* EFUSE_FLASH_CRYPT_CNT : R/W ;bitpos:[26:20] ;default: 7'b0 ; */ /*description: program for flash_crypt_cnt*/ -#define EFUSE_FLASH_CRYPT_CNT 0x000000FF +#define EFUSE_FLASH_CRYPT_CNT 0x0000007F #define EFUSE_FLASH_CRYPT_CNT_M ((EFUSE_FLASH_CRYPT_CNT_V)<<(EFUSE_FLASH_CRYPT_CNT_S)) -#define EFUSE_FLASH_CRYPT_CNT_V 0xFF +#define EFUSE_FLASH_CRYPT_CNT_V 0x7F #define EFUSE_FLASH_CRYPT_CNT_S 20 /* EFUSE_RD_DIS : R/W ;bitpos:[19:16] ;default: 4'b0 ; */ /*description: program for efuse_rd_disable*/ diff --git a/tools/sdk/include/soc/soc/emac_reg_v2.h b/tools/sdk/include/soc/soc/emac_reg_v2.h index a33ce44adee..72af5bfe365 100644 --- a/tools/sdk/include/soc/soc/emac_reg_v2.h +++ b/tools/sdk/include/soc/soc/emac_reg_v2.h @@ -11,1274 +11,1450 @@ // WITHOUT 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_EMAC_REG_H_ +#define _SOC_EMAC_REG_H_ -#ifndef _EMAC_H_ -#define _EMAC_H_ #ifdef __cplusplus extern "C" { #endif - #include "soc.h" -#define REG_EMAC_BASE DR_REG_EMAC_BASE - -#define EMAC_DMABUSMODE_REG (REG_EMAC_BASE + 0x0000) -#define EMAC_DMAREBINCRBURST (BIT(31)) -#define EMAC_DMAREBINCRBURST_M (BIT(31)) -#define EMAC_DMAREBINCRBURST_V 1 -#define EMAC_DMAREBINCRBURST_S 31 -#define EMAC_DMACHANNELPRIOWT 0x00000003 -#define EMAC_DMACHANNELPRIOWT_M (EMAC_DMACHANNELPRIOWT_V << EMAC_DMACHANNELPRIOWT_S) -#define EMAC_DMACHANNELPRIOWT_V 0x00000003 -#define EMAC_DMACHANNELPRIOWT_S 28 -#define EMAC_DMATXRXPRIO (BIT(27)) -#define EMAC_DMATXRXPRIO_M (BIT(27)) -#define EMAC_DMATXRXPRIO_V 1 -#define EMAC_DMATXRXPRIO_S 27 -#define EMAC_DMAMIXEDBURST (BIT(26)) -#define EMAC_DMAMIXEDBURST_M (BIT(26)) -#define EMAC_DMAMIXEDBURST_V 1 -#define EMAC_DMAMIXEDBURST_S 26 -#define EMAC_DMAADDRALIBEA (BIT(25)) -#define EMAC_DMAADDRALIBEA_M (BIT(25)) -#define EMAC_DMAADDRALIBEA_V 1 -#define EMAC_DMAADDRALIBEA_S 25 -#define EMAC_PBLX8_MODE (BIT(24)) -#define EMAC_PBLX8_MODE_M (BIT(24)) -#define EMAC_PBLX8_MODE_V 1 -#define EMAC_PBLX8_MODE_S 24 -#define EMAC_USE_SEP_PBL (BIT(23)) -#define EMAC_USE_SEP_PBL_M (BIT(23)) -#define EMAC_USE_SEP_PBL_V 1 -#define EMAC_USE_SEP_PBL_S 23 -#define EMAC_RX_DMA_PBL 0x0000003F -#define EMAC_RX_DMA_PBL_M (EMAC_RX_DMA_PBL_V << EMAC_RX_DMA_PBL_S) -#define EMAC_RX_DMA_PBL_V 0x0000003F -#define EMAC_RX_DMA_PBL_S 17 -#define EMAC_FIXED_BURST (BIT(16)) -#define EMAC_FIXED_BURST_M (BIT(16)) -#define EMAC_FIXED_BURST_V 1 -#define EMAC_FIXED_BURST_S 16 -#define EMAC_PRI_RATIO 0x00000003 -#define EMAC_PRI_RATIO_M (EMAC_PRI_RATIO_V << EMAC_PRI_RATIO_S) -#define EMAC_PRI_RATIO_V 0x00000003 -#define EMAC_PRI_RATIO_S 14 -#define EMAC_PROG_BURST_LEN 0x0000003F -#define EMAC_PROG_BURST_LEN_M (EMAC_PROG_BURST_LEN_V << EMAC_PROG_BURST_LEN_S) -#define EMAC_PROG_BURST_LEN_V 0x0000003F -#define EMAC_PROG_BURST_LEN_S 8 -#define EMAC_ALT_DESC_SIZE (BIT(7)) -#define EMAC_ALT_DESC_SIZE_M (BIT(7)) -#define EMAC_ALT_DESC_SIZE_V 1 -#define EMAC_ALT_DESC_SIZE_S 7 -#define EMAC_DESC_SKIP_LEN 0x0000001F -#define EMAC_DESC_SKIP_LEN_M (EMAC_DESC_SKIP_LEN_V << EMAC_DESC_SKIP_LEN_S) -#define EMAC_DESC_SKIP_LEN_V 0x0000001F -#define EMAC_DESC_SKIP_LEN_S 2 -#define EMAC_DMA_ARB_SCH (BIT(1)) -#define EMAC_DMA_ARB_SCH_M (BIT(1)) -#define EMAC_DMA_ARB_SCH_V 1 -#define EMAC_DMA_ARB_SCH_S 1 -#define EMAC_SW_RST (BIT(0)) -#define EMAC_SW_RST_M (BIT(0)) -#define EMAC_SW_RST_V 1 -#define EMAC_SW_RST_S 0 - -#define EMAC_DMATXPOLLDEMAND_REG (REG_EMAC_BASE + 0x0004) -#define EMAC_TRANS_POLL_DEMAND 0xFFFFFFFF -#define EMAC_TRANS_POLL_DEMAND_M (EMAC_TRANS_POLL_DEMAND_V << EMAC_TRANS_POLL_DEMAND_S) -#define EMAC_TRANS_POLL_DEMAND_V 0xFFFFFFFF -#define EMAC_TRANS_POLL_DEMAND_S 0 - -#define EMAC_DMARXPOLLDEMAND_REG (REG_EMAC_BASE + 0x0008) -#define EMAC_RECV_POLL_DEMAND 0xFFFFFFFF -#define EMAC_RECV_POLL_DEMAND_M (EMAC_RECV_POLL_DEMAND_V << EMAC_RECV_POLL_DEMAND_S) -#define EMAC_RECV_POLL_DEMAND_V 0xFFFFFFFF -#define EMAC_RECV_POLL_DEMAND_S 0 - -#define EMAC_DMARXBASEADDR_REG (REG_EMAC_BASE + 0x000C) -#define EMAC_START_RECV_LIST 0xFFFFFFFF -#define EMAC_START_RECV_LIST_M (EMAC_START_RECV_LIST_V << EMAC_START_RECV_LIST_S) -#define EMAC_START_RECV_LIST_V 0xFFFFFFFF -#define EMAC_START_RECV_LIST_S 0 - -#define EMAC_DMATXBASEADDR_REG (REG_EMAC_BASE + 0x0010) -#define EMAC_START_TRANS_LIST 0xFFFFFFFF -#define EMAC_START_TRANS_LIST_M (EMAC_START_TRANS_LIST_V << EMAC_START_TRANS_LIST_S) -#define EMAC_START_TRANS_LIST_V 0xFFFFFFFF -#define EMAC_START_TRANS_LIST_S 0 - -#define EMAC_DMASTATUS_REG (REG_EMAC_BASE + 0x0014) -#define EMAC_GMAC_LPI_INT (BIT(30)) -#define EMAC_GMAC_LPI_INT_M (BIT(30)) -#define EMAC_GMAC_LPI_INT_V 1 -#define EMAC_GMAC_LPI_INT_S 30 -#define EMAC_TS_TRI_INT (BIT(29)) -#define EMAC_TS_TRI_INT_M (BIT(29)) -#define EMAC_TS_TRI_INT_V 1 -#define EMAC_TS_TRI_INT_S 29 -#define EMAC_GMAC_PMT_INT (BIT(28)) -#define EMAC_GMAC_PMT_INT_M (BIT(28)) -#define EMAC_GMAC_PMT_INT_V 1 -#define EMAC_GMAC_PMT_INT_S 28 -#define EMAC_GMAC_MMC_INT (BIT(27)) -#define EMAC_GMAC_MMC_INT_M (BIT(27)) -#define EMAC_GMAC_MMC_INT_V 1 -#define EMAC_GMAC_MMC_INT_S 27 -#define EMAC_GMAC_LINE_INF_INT (BIT(26)) -#define EMAC_GMAC_LINE_INF_INT_M (BIT(26)) -#define EMAC_GMAC_LINE_INF_INT_V 1 -#define EMAC_GMAC_LINE_INF_INT_S 26 -#define EMAC_ERROR_BITS 0x00000007 -#define EMAC_ERROR_BITS_M (EMAC_ERROR_BITS_V << EMAC_ERROR_BITS_S) -#define EMAC_ERROR_BITS_V 0x00000007 -#define EMAC_ERROR_BITS_S 23 -#define EMAC_TRANS_PROC_STATE 0x00000007 -#define EMAC_TRANS_PROC_STATE_M (EMAC_TRANS_PROC_STATE_V << EMAC_TRANS_PROC_STATE_S) -#define EMAC_TRANS_PROC_STATE_V 0x00000007 -#define EMAC_TRANS_PROC_STATE_S 20 -#define EMAC_RECV_PROC_STATE 0x00000007 -#define EMAC_RECV_PROC_STATE_M (EMAC_RECV_PROC_STATE_V << EMAC_RECV_PROC_STATE_S) -#define EMAC_RECV_PROC_STATE_V 0x00000007 -#define EMAC_RECV_PROC_STATE_S 17 -#define EMAC_NORM_INT_SUMM (BIT(16)) -#define EMAC_NORM_INT_SUMM_M (BIT(16)) -#define EMAC_NORM_INT_SUMM_V 1 -#define EMAC_NORM_INT_SUMM_S 16 -#define EMAC_ABN_INT_SUMM (BIT(15)) -#define EMAC_ABN_INT_SUMM_M (BIT(15)) -#define EMAC_ABN_INT_SUMM_V 1 -#define EMAC_ABN_INT_SUMM_S 15 -#define EMAC_EARLY_RECV_INT (BIT(14)) -#define EMAC_EARLY_RECV_INT_M (BIT(14)) -#define EMAC_EARLY_RECV_INT_V 1 -#define EMAC_EARLY_RECV_INT_S 14 -#define EMAC_FATAL_BUS_ERR_INT (BIT(13)) -#define EMAC_FATAL_BUS_ERR_INT_M (BIT(13)) -#define EMAC_FATAL_BUS_ERR_INT_V 1 -#define EMAC_FATAL_BUS_ERR_INT_S 13 -#define EMAC_EARLY_TRANS_INT (BIT(10)) -#define EMAC_EARLY_TRANS_INT_M (BIT(10)) -#define EMAC_EARLY_TRANS_INT_V 1 -#define EMAC_EARLY_TRANS_INT_S 10 -#define EMAC_RECV_WDT_TO (BIT(9)) -#define EMAC_RECV_WDT_TO_M (BIT(9)) -#define EMAC_RECV_WDT_TO_V 1 -#define EMAC_RECV_WDT_TO_S 9 -#define EMAC_RECV_PROC_STOP (BIT(8)) -#define EMAC_RECV_PROC_STOP_M (BIT(8)) -#define EMAC_RECV_PROC_STOP_V 1 -#define EMAC_RECV_PROC_STOP_S 8 -#define EMAC_RECV_BUF_UNAVAIL (BIT(7)) -#define EMAC_RECV_BUF_UNAVAIL_M (BIT(7)) -#define EMAC_RECV_BUF_UNAVAIL_V 1 -#define EMAC_RECV_BUF_UNAVAIL_S 7 -#define EMAC_RECV_INT (BIT(6)) -#define EMAC_RECV_INT_M (BIT(6)) -#define EMAC_RECV_INT_V 1 -#define EMAC_RECV_INT_S 6 -#define EMAC_TRANS_UNDFLOW (BIT(5)) -#define EMAC_TRANS_UNDFLOW_M (BIT(5)) -#define EMAC_TRANS_UNDFLOW_V 1 -#define EMAC_TRANS_UNDFLOW_S 5 -#define EMAC_RECV_OVFLOW (BIT(4)) -#define EMAC_RECV_OVFLOW_M (BIT(4)) -#define EMAC_RECV_OVFLOW_V 1 -#define EMAC_RECV_OVFLOW_S 4 -#define EMAC_TRANS_JABBER_TO (BIT(3)) -#define EMAC_TRANS_JABBER_TO_M (BIT(3)) -#define EMAC_TRANS_JABBER_TO_V 1 -#define EMAC_TRANS_JABBER_TO_S 3 -#define EMAC_TRANS_BUF_UNAVAIL (BIT(2)) -#define EMAC_TRANS_BUF_UNAVAIL_M (BIT(2)) -#define EMAC_TRANS_BUF_UNAVAIL_V 1 -#define EMAC_TRANS_BUF_UNAVAIL_S 2 -#define EMAC_TRANS_PROC_STOP (BIT(1)) -#define EMAC_TRANS_PROC_STOP_M (BIT(1)) -#define EMAC_TRANS_PROC_STOP_V 1 -#define EMAC_TRANS_PROC_STOP_S 1 -#define EMAC_TRANS_INT (BIT(0)) -#define EMAC_TRANS_INT_M (BIT(0)) -#define EMAC_TRANS_INT_V 1 -#define EMAC_TRANS_INT_S 0 - -#define EMAC_DMAOPERATION_MODE_REG (REG_EMAC_BASE + 0x0018) -#define EMAC_DIS_DROP_TCPIP_CHKSUM_ERR_FRAM (BIT(26)) -#define EMAC_DIS_DROP_TCPIP_CHKSUM_ERR_FRAM_M (BIT(26)) -#define EMAC_DIS_DROP_TCPIP_CHKSUM_ERR_FRAM_V 1 -#define EMAC_DIS_DROP_TCPIP_CHKSUM_ERR_FRAM_S 26 -#define EMAC_RECV_STORE_FORWARD (BIT(25)) -#define EMAC_RECV_STORE_FORWARD_M (BIT(25)) -#define EMAC_RECV_STORE_FORWARD_V 1 -#define EMAC_RECV_STORE_FORWARD_S 25 -#define EMAC_DIS_FLUSH_RECV_FRAMES (BIT(24)) -#define EMAC_DIS_FLUSH_RECV_FRAMES_M (BIT(24)) -#define EMAC_DIS_FLUSH_RECV_FRAMES_V 1 -#define EMAC_DIS_FLUSH_RECV_FRAMES_S 24 -#define EMAC_MSB_THRESHOLD_ACTIVATING_FLOW_CONTROL (BIT(23)) -#define EMAC_MSB_THRESHOLD_ACTIVATING_FLOW_CONTROL_M (BIT(23)) -#define EMAC_MSB_THRESHOLD_ACTIVATING_FLOW_CONTROL_V 1 -#define EMAC_MSB_THRESHOLD_ACTIVATING_FLOW_CONTROL_S 23 -#define EMAC_MSB_THRESHOLD_DEACTIVATING_FLOW_CONTROL (BIT(22)) -#define EMAC_MSB_THRESHOLD_DEACTIVATING_FLOW_CONTROL_M (BIT(22)) -#define EMAC_MSB_THRESHOLD_DEACTIVATING_FLOW_CONTROL_V 1 -#define EMAC_MSB_THRESHOLD_DEACTIVATING_FLOW_CONTROL_S 22 -#define EMAC_TRANSMIT_STORE_FORWARD (BIT(21)) -#define EMAC_TRANSMIT_STORE_FORWARD_M (BIT(21)) -#define EMAC_TRANSMIT_STORE_FORWARD_V 1 -#define EMAC_TRANSMIT_STORE_FORWARD_S 21 -#define EMAC_FLUSH_TRANSMIT_FIFO (BIT(20)) -#define EMAC_FLUSH_TRANSMIT_FIFO_M (BIT(20)) -#define EMAC_FLUSH_TRANSMIT_FIFO_V 1 -#define EMAC_FLUSH_TRANSMIT_FIFO_S 20 -#define EMAC_TRANSMIT_THRESHOLD_CONTROL 0x00000007 -#define EMAC_TRANSMIT_THRESHOLD_CONTROL_M (EMAC_TRANSMIT_THRESHOLD_CONTROL_V << EMAC_TRANSMIT_THRESHOLD_CONTROL_S) -#define EMAC_TRANSMIT_THRESHOLD_CONTROL_V 0x00000007 -#define EMAC_TRANSMIT_THRESHOLD_CONTROL_S 14 -#define EMAC_START_STOP_TRANSMISSION_COMMAND (BIT(13)) -#define EMAC_START_STOP_TRANSMISSION_COMMAND_M (BIT(13)) -#define EMAC_START_STOP_TRANSMISSION_COMMAND_V 1 -#define EMAC_START_STOP_TRANSMISSION_COMMAND_S 13 -#define EMAC_THRESHOLD_DEACTIVATING_FLOW_CONTROL 0x00000003 -#define EMAC_THRESHOLD_DEACTIVATING_FLOW_CONTROL_M (EMAC_THRESHOLD_DEACTIVATING_FLOW_CONTROL_V << EMAC_THRESHOLD_DEACTIVATING_FLOW_CONTROL_S) -#define EMAC_THRESHOLD_DEACTIVATING_FLOW_CONTROL_V 0x00000003 -#define EMAC_THRESHOLD_DEACTIVATING_FLOW_CONTROL_S 11 -#define EMAC_THRESHOLD_ACTIVATING_FLOW_CONTROL 0x00000003 -#define EMAC_THRESHOLD_ACTIVATING_FLOW_CONTROL_M (EMAC_THRESHOLD_ACTIVATING_FLOW_CONTROL_V << EMAC_THRESHOLD_ACTIVATING_FLOW_CONTROL_S) -#define EMAC_THRESHOLD_ACTIVATING_FLOW_CONTROL_V 0x00000003 -#define EMAC_THRESHOLD_ACTIVATING_FLOW_CONTROL_S 9 -#define EMAC_ENABLE_HW_FLOW_CONTROL (BIT(8)) -#define EMAC_ENABLE_HW_FLOW_CONTROL_M (BIT(8)) -#define EMAC_ENABLE_HW_FLOW_CONTROL_V 1 -#define EMAC_ENABLE_HW_FLOW_CONTROL_S 8 -#define EMAC_FORWARD_ERROR_FRAMES (BIT(7)) -#define EMAC_FORWARD_ERROR_FRAMES_M (BIT(7)) -#define EMAC_FORWARD_ERROR_FRAMES_V 1 -#define EMAC_FORWARD_ERROR_FRAMES_S 7 -#define EMAC_FORWARD_UNDERSIZED_GOOD_FRAMES (BIT(6)) -#define EMAC_FORWARD_UNDERSIZED_GOOD_FRAMES_M (BIT(6)) -#define EMAC_FORWARD_UNDERSIZED_GOOD_FRAMES_V 1 -#define EMAC_FORWARD_UNDERSIZED_GOOD_FRAMES_S 6 -#define EMAC_DROP_GIANT_FRAMES (BIT(5)) -#define EMAC_DROP_GIANT_FRAMES_M (BIT(5)) -#define EMAC_DROP_GIANT_FRAMES_V 1 -#define EMAC_DROP_GIANT_FRAMES_S 5 -#define EMAC_RECEIVE_THRESHOLD_CONTROL 0x00000003 -#define EMAC_RECEIVE_THRESHOLD_CONTROL_M (EMAC_RECEIVE_THRESHOLD_CONTROL_V << EMAC_RECEIVE_THRESHOLD_CONTROL_S) -#define EMAC_RECEIVE_THRESHOLD_CONTROL_V 0x00000003 -#define EMAC_RECEIVE_THRESHOLD_CONTROL_S 3 -#define EMAC_OPERATE_SECOND_FRAME (BIT(2)) -#define EMAC_OPERATE_SECOND_FRAME_M (BIT(2)) -#define EMAC_OPERATE_SECOND_FRAME_V 1 -#define EMAC_OPERATE_SECOND_FRAME_S 2 -#define EMAC_START_STOP_RECEIVE (BIT(1)) -#define EMAC_START_STOP_RECEIVE_M (BIT(1)) -#define EMAC_START_STOP_RECEIVE_V 1 -#define EMAC_START_STOP_RECEIVE_S 1 - -#define EMAC_DMAINTERRUPT_EN_REG (REG_EMAC_BASE + 0x001C) -#define EMAC_NORMAL_INTERRUPT_SUMMARY_ENABLE (BIT(16)) -#define EMAC_NORMAL_INTERRUPT_SUMMARY_ENABLE_M (BIT(16)) -#define EMAC_NORMAL_INTERRUPT_SUMMARY_ENABLE_V 1 -#define EMAC_NORMAL_INTERRUPT_SUMMARY_ENABLE_S 16 -#define EMAC_ABNORMAL_INTERRUPT_SUMMARY_ENABLE (BIT(15)) -#define EMAC_ABNORMAL_INTERRUPT_SUMMARY_ENABLE_M (BIT(15)) -#define EMAC_ABNORMAL_INTERRUPT_SUMMARY_ENABLE_V 1 -#define EMAC_ABNORMAL_INTERRUPT_SUMMARY_ENABLE_S 15 -#define EMAC_EARLY_RECEIVE_INTERRUPT_ENABLE (BIT(14)) -#define EMAC_EARLY_RECEIVE_INTERRUPT_ENABLE_M (BIT(14)) -#define EMAC_EARLY_RECEIVE_INTERRUPT_ENABLE_V 1 -#define EMAC_EARLY_RECEIVE_INTERRUPT_ENABLE_S 14 -#define EMAC_FATAL_BUS_ERROR_ENABLE (BIT(13)) -#define EMAC_FATAL_BUS_ERROR_ENABLE_M (BIT(13)) -#define EMAC_FATAL_BUS_ERROR_ENABLE_V 1 -#define EMAC_FATAL_BUS_ERROR_ENABLE_S 13 -#define EMAC_EARLY_TRANSMIT_INTERRUPT_ENABLE (BIT(10)) -#define EMAC_EARLY_TRANSMIT_INTERRUPT_ENABLE_M (BIT(10)) -#define EMAC_EARLY_TRANSMIT_INTERRUPT_ENABLE_V 1 -#define EMAC_EARLY_TRANSMIT_INTERRUPT_ENABLE_S 10 -#define EMAC_RECEIVE_WATCHDOG_TIMEOUT_ENABLE (BIT(9)) -#define EMAC_RECEIVE_WATCHDOG_TIMEOUT_ENABLE_M (BIT(9)) -#define EMAC_RECEIVE_WATCHDOG_TIMEOUT_ENABLE_V 1 -#define EMAC_RECEIVE_WATCHDOG_TIMEOUT_ENABLE_S 9 -#define EMAC_RECEIVE_STOPPED_ENABLE (BIT(8)) -#define EMAC_RECEIVE_STOPPED_ENABLE_M (BIT(8)) -#define EMAC_RECEIVE_STOPPED_ENABLE_V 1 -#define EMAC_RECEIVE_STOPPED_ENABLE_S 8 -#define EMAC_RECEIVE_BUFFER_UNAVAILABLE_ENABLE (BIT(7)) -#define EMAC_RECEIVE_BUFFER_UNAVAILABLE_ENABLE_M (BIT(7)) -#define EMAC_RECEIVE_BUFFER_UNAVAILABLE_ENABLE_V 1 -#define EMAC_RECEIVE_BUFFER_UNAVAILABLE_ENABLE_S 7 -#define EMAC_RECEIVE_INTERRUPT_ENABLE (BIT(6)) -#define EMAC_RECEIVE_INTERRUPT_ENABLE_M (BIT(6)) -#define EMAC_RECEIVE_INTERRUPT_ENABLE_V 1 -#define EMAC_RECEIVE_INTERRUPT_ENABLE_S 6 -#define EMAC_UNDERFLOW_INTERRUPT_ENABLE (BIT(5)) -#define EMAC_UNDERFLOW_INTERRUPT_ENABLE_M (BIT(5)) -#define EMAC_UNDERFLOW_INTERRUPT_ENABLE_V 1 -#define EMAC_UNDERFLOW_INTERRUPT_ENABLE_S 5 -#define EMAC_OVERFLOW_INTERRUPT_ENABLE (BIT(4)) -#define EMAC_OVERFLOW_INTERRUPT_ENABLE_M (BIT(4)) -#define EMAC_OVERFLOW_INTERRUPT_ENABLE_V 1 -#define EMAC_OVERFLOW_INTERRUPT_ENABLE_S 4 -#define EMAC_TRANSMIT_JABBER_TIMEOUT_ENABLE (BIT(3)) -#define EMAC_TRANSMIT_JABBER_TIMEOUT_ENABLE_M (BIT(3)) -#define EMAC_TRANSMIT_JABBER_TIMEOUT_ENABLE_V 1 -#define EMAC_TRANSMIT_JABBER_TIMEOUT_ENABLE_S 3 -#define EMAC_TRANSMIT_BUFFER_UNAVAILABLE_ENABLE (BIT(2)) -#define EMAC_TRANSMIT_BUFFER_UNAVAILABLE_ENABLE_M (BIT(2)) -#define EMAC_TRANSMIT_BUFFER_UNAVAILABLE_ENABLE_V 1 -#define EMAC_TRANSMIT_BUFFER_UNAVAILABLE_ENABLE_S 2 -#define EMAC_TRANSMIT_STOPPED_ENABLE (BIT(1)) -#define EMAC_TRANSMIT_STOPPED_ENABLE_M (BIT(1)) -#define EMAC_TRANSMIT_STOPPED_ENABLE_V 1 -#define EMAC_TRANSMIT_STOPPED_ENABLE_S 1 -#define EMAC_TRANSMIT_INTERRUPT_ENABLE (BIT(0)) -#define EMAC_TRANSMIT_INTERRUPT_ENABLE_M (BIT(0)) -#define EMAC_TRANSMIT_INTERRUPT_ENABLE_V 1 -#define EMAC_TRANSMIT_INTERRUPT_ENABLE_S 0 - -#define EMAC_DMAMISSEDFR_REG (REG_EMAC_BASE + 0x0020) -#define EMAC_OVERFLOW_BIT_FIFO_OVERFLOW_COUNTER (BIT(28)) -#define EMAC_OVERFLOW_BIT_FIFO_OVERFLOW_COUNTER_M (BIT(28)) -#define EMAC_OVERFLOW_BIT_FIFO_OVERFLOW_COUNTER_V 1 -#define EMAC_OVERFLOW_BIT_FIFO_OVERFLOW_COUNTER_S 28 -#define EMAC_OVERFLOW_FRAME_COUNTER 0x000007FF -#define EMAC_OVERFLOW_FRAME_COUNTER_M (EMAC_OVERFLOW_FRAME_COUNTER_V << EMAC_OVERFLOW_FRAME_COUNTER_S) -#define EMAC_OVERFLOW_FRAME_COUNTER_V 0x000007FF -#define EMAC_OVERFLOW_FRAME_COUNTER_S 17 -#define EMAC_OVERFLOW_BIT_MISSED_FRAME_COUNTER (BIT(16)) -#define EMAC_OVERFLOW_BIT_MISSED_FRAME_COUNTER_M (BIT(16)) -#define EMAC_OVERFLOW_BIT_MISSED_FRAME_COUNTER_V 1 -#define EMAC_OVERFLOW_BIT_MISSED_FRAME_COUNTER_S 16 -#define EMAC_MISSED_FRAME_COUNTER 0x0000FFFF -#define EMAC_MISSED_FRAME_COUNTER_M (EMAC_MISSED_FRAME_COUNTER_V << EMAC_MISSED_FRAME_COUNTER_S) -#define EMAC_MISSED_FRAME_COUNTER_V 0x0000FFFF -#define EMAC_MISSED_FRAME_COUNTER_S 0 - -#define EMAC_DMARECEIVE_INTERRUPT_WATCHDOG_TIMER_REG (REG_EMAC_BASE + 0x0024) -#define EMAC_RI_WATCHDOG_TIMER_COUNT 0x000000FF -#define EMAC_RI_WATCHDOG_TIMER_COUNT_M (EMAC_RI_WATCHDOG_TIMER_COUNT_V << EMAC_RI_WATCHDOG_TIMER_COUNT_S) -#define EMAC_RI_WATCHDOG_TIMER_COUNT_V 0x000000FF -#define EMAC_RI_WATCHDOG_TIMER_COUNT_S 0 - -#define EMAC_DMATXCURRDESC_REG (REG_EMAC_BASE + 0x0048) -#define EMAC_HOST_TRANSMIT_DESCRIPTOR_ADDRESS_POINTER 0xFFFFFFFF -#define EMAC_HOST_TRANSMIT_DESCRIPTOR_ADDRESS_POINTER_M (EMAC_HOST_TRANSMIT_DESCRIPTOR_ADDRESS_POINTER_V << EMAC_HOST_TRANSMIT_DESCRIPTOR_ADDRESS_POINTER_S) -#define EMAC_HOST_TRANSMIT_DESCRIPTOR_ADDRESS_POINTER_V 0xFFFFFFFF -#define EMAC_HOST_TRANSMIT_DESCRIPTOR_ADDRESS_POINTER_S 0 - -#define EMAC_DMARXCURRDESC_REG (REG_EMAC_BASE + 0x004C) -#define EMAC_HOST_RECEIVE_DESCRIPTOR_ADDRESS_POINTER 0xFFFFFFFF -#define EMAC_HOST_RECEIVE_DESCRIPTOR_ADDRESS_POINTER_M (EMAC_HOST_RECEIVE_DESCRIPTOR_ADDRESS_POINTER_V << EMAC_HOST_RECEIVE_DESCRIPTOR_ADDRESS_POINTER_S) -#define EMAC_HOST_RECEIVE_DESCRIPTOR_ADDRESS_POINTER_V 0xFFFFFFFF -#define EMAC_HOST_RECEIVE_DESCRIPTOR_ADDRESS_POINTER_S 0 - -#define EMAC_DMATXCURRADDR_BUF_REG (REG_EMAC_BASE + 0x0050) -#define EMAC_HOST_TRANSMIT_BUFFER_ADDRESS_POINTER 0xFFFFFFFF -#define EMAC_HOST_TRANSMIT_BUFFER_ADDRESS_POINTER_M (EMAC_HOST_TRANSMIT_BUFFER_ADDRESS_POINTER_V << EMAC_HOST_TRANSMIT_BUFFER_ADDRESS_POINTER_S) -#define EMAC_HOST_TRANSMIT_BUFFER_ADDRESS_POINTER_V 0xFFFFFFFF -#define EMAC_HOST_TRANSMIT_BUFFER_ADDRESS_POINTER_S 0 - -#define EMAC_DMARXCURRADDR_BUF_REG (REG_EMAC_BASE + 0x0054) -#define EMAC_HOST_RECEIVE_BUFFER_ADDRESS_POINTER 0xFFFFFFFF -#define EMAC_HOST_RECEIVE_BUFFER_ADDRESS_POINTER_M (EMAC_HOST_RECEIVE_BUFFER_ADDRESS_POINTER_V << EMAC_HOST_RECEIVE_BUFFER_ADDRESS_POINTER_S) -#define EMAC_HOST_RECEIVE_BUFFER_ADDRESS_POINTER_V 0xFFFFFFFF -#define EMAC_HOST_RECEIVE_BUFFER_ADDRESS_POINTER_S 0 - -#define EMAC_DMAHWFEATURE_REG (REG_EMAC_BASE + 0x0058) -#define EMAC_SELECTED_PHY_INTERFACE 0x00000007 -#define EMAC_SELECTED_PHY_INTERFACE_M (EMAC_SELECTED_PHY_INTERFACE_V << EMAC_SELECTED_PHY_INTERFACE_S) -#define EMAC_SELECTED_PHY_INTERFACE_V 0x00000007 -#define EMAC_SELECTED_PHY_INTERFACE_S 28 -#define EMAC_SOURCE_ADDRESS_VLAN_INSERTION (BIT(27)) -#define EMAC_SOURCE_ADDRESS_VLAN_INSERTION_M (BIT(27)) -#define EMAC_SOURCE_ADDRESS_VLAN_INSERTION_V 1 -#define EMAC_SOURCE_ADDRESS_VLAN_INSERTION_S 27 -#define EMAC_FLEXIBLE_PULSE_PER_SECOND_OUTPUT (BIT(26)) -#define EMAC_FLEXIBLE_PULSE_PER_SECOND_OUTPUT_M (BIT(26)) -#define EMAC_FLEXIBLE_PULSE_PER_SECOND_OUTPUT_V 1 -#define EMAC_FLEXIBLE_PULSE_PER_SECOND_OUTPUT_S 26 -#define EMAC_TIMESTAMPING_INTERNAL_SYSTEM_TIME (BIT(25)) -#define EMAC_TIMESTAMPING_INTERNAL_SYSTEM_TIME_M (BIT(25)) -#define EMAC_TIMESTAMPING_INTERNAL_SYSTEM_TIME_V 1 -#define EMAC_TIMESTAMPING_INTERNAL_SYSTEM_TIME_S 25 -#define EMAC_ENHANCED_DESCRIPTOR (BIT(24)) -#define EMAC_ENHANCED_DESCRIPTOR_M (BIT(24)) -#define EMAC_ENHANCED_DESCRIPTOR_V 1 -#define EMAC_ENHANCED_DESCRIPTOR_S 24 -#define EMAC_NUMBER_ADDITIONAL_TX_CHANNELS 0x00000003 -#define EMAC_NUMBER_ADDITIONAL_TX_CHANNELS_M (EMAC_NUMBER_ADDITIONAL_TX_CHANNELS_V << EMAC_NUMBER_ADDITIONAL_TX_CHANNELS_S) -#define EMAC_NUMBER_ADDITIONAL_TX_CHANNELS_V 0x00000003 -#define EMAC_NUMBER_ADDITIONAL_TX_CHANNELS_S 22 -#define EMAC_NUMBER_ADDITIONAL_RX_CHANNELS 0x00000003 -#define EMAC_NUMBER_ADDITIONAL_RX_CHANNELS_M (EMAC_NUMBER_ADDITIONAL_RX_CHANNELS_V << EMAC_NUMBER_ADDITIONAL_RX_CHANNELS_S) -#define EMAC_NUMBER_ADDITIONAL_RX_CHANNELS_V 0x00000003 -#define EMAC_NUMBER_ADDITIONAL_RX_CHANNELS_S 20 -#define EMAC_RXFIFOSIZE (BIT(19)) -#define EMAC_RXFIFOSIZE_M (BIT(19)) -#define EMAC_RXFIFOSIZE_V 1 -#define EMAC_RXFIFOSIZE_S 19 -#define EMAC_IP_CHECKSUM_OFFLOAD_TYPE2 (BIT(18)) -#define EMAC_IP_CHECKSUM_OFFLOAD_TYPE2_M (BIT(18)) -#define EMAC_IP_CHECKSUM_OFFLOAD_TYPE2_V 1 -#define EMAC_IP_CHECKSUM_OFFLOAD_TYPE2_S 18 -#define EMAC_IP_CHECKSUM_OFFLOAD_TYPE1 (BIT(17)) -#define EMAC_IP_CHECKSUM_OFFLOAD_TYPE1_M (BIT(17)) -#define EMAC_IP_CHECKSUM_OFFLOAD_TYPE1_V 1 -#define EMAC_IP_CHECKSUM_OFFLOAD_TYPE1_S 17 -#define EMAC_CHECKSUM_OFFLOAD_TX (BIT(16)) -#define EMAC_CHECKSUM_OFFLOAD_TX_M (BIT(16)) -#define EMAC_CHECKSUM_OFFLOAD_TX_V 1 -#define EMAC_CHECKSUM_OFFLOAD_TX_S 16 -#define EMAC_AV_FEATURE_SEL (BIT(15)) -#define EMAC_AV_FEATURE_SEL_M (BIT(15)) -#define EMAC_AV_FEATURE_SEL_V 1 -#define EMAC_AV_FEATURE_SEL_S 15 -#define EMAC_EEE_SEL (BIT(14)) -#define EMAC_EEE_SEL_M (BIT(14)) -#define EMAC_EEE_SEL_V 1 -#define EMAC_EEE_SEL_S 14 -#define EMAC_TSVER2_SEL (BIT(13)) -#define EMAC_TSVER2_SEL_M (BIT(13)) -#define EMAC_TSVER2_SEL_V 1 -#define EMAC_TSVER2_SEL_S 13 -#define EMAC_TSVER1_SEL (BIT(12)) -#define EMAC_TSVER1_SEL_M (BIT(12)) -#define EMAC_TSVER1_SEL_V 1 -#define EMAC_TSVER1_SEL_S 12 -#define EMAC_MMC_SEL (BIT(11)) -#define EMAC_MMC_SEL_M (BIT(11)) -#define EMAC_MMC_SEL_V 1 -#define EMAC_MMC_SEL_S 11 -#define EMAC_MGK_SEL (BIT(10)) -#define EMAC_MGK_SEL_M (BIT(10)) -#define EMAC_MGK_SEL_V 1 -#define EMAC_MGK_SEL_S 10 -#define EMAC_RWK_SEL (BIT(9)) -#define EMAC_RWK_SEL_M (BIT(9)) -#define EMAC_RWK_SEL_V 1 -#define EMAC_RWK_SEL_S 9 -#define EMAC_SMA_SEL (BIT(8)) -#define EMAC_SMA_SEL_M (BIT(8)) -#define EMAC_SMA_SEL_V 1 -#define EMAC_SMA_SEL_S 8 -#define EMAC_L3L4FLTR_EN (BIT(7)) -#define EMAC_L3L4FLTR_EN_M (BIT(7)) -#define EMAC_L3L4FLTR_EN_V 1 -#define EMAC_L3L4FLTR_EN_S 7 -#define EMAC_PCS_SEL (BIT(6)) -#define EMAC_PCS_SEL_M (BIT(6)) -#define EMAC_PCS_SEL_V 1 -#define EMAC_PCS_SEL_S 6 -#define EMAC_ADDMACADR_SEL (BIT(5)) -#define EMAC_ADDMACADR_SEL_M (BIT(5)) -#define EMAC_ADDMACADR_SEL_V 1 -#define EMAC_ADDMACADR_SEL_S 5 -#define EMAC_HASH_SEL (BIT(4)) -#define EMAC_HASH_SEL_M (BIT(4)) -#define EMAC_HASH_SEL_V 1 -#define EMAC_HASH_SEL_S 4 -#define EMAC_EXTHASH_EN (BIT(3)) -#define EMAC_EXTHASH_EN_M (BIT(3)) -#define EMAC_EXTHASH_EN_V 1 -#define EMAC_EXTHASH_EN_S 3 -#define EMAC_HD_SEL (BIT(2)) -#define EMAC_HD_SEL_M (BIT(2)) -#define EMAC_HD_SEL_V 1 -#define EMAC_HD_SEL_S 2 -#define EMAC_GMII_SEL (BIT(1)) -#define EMAC_GMII_SEL_M (BIT(1)) -#define EMAC_GMII_SEL_V 1 -#define EMAC_GMII_SEL_S 1 -#define EMAC_MII_SEL (BIT(0)) -#define EMAC_MII_SEL_M (BIT(0)) -#define EMAC_MII_SEL_V 1 -#define EMAC_MII_SEL_S 0 - -#define EMAC_DMASLOTFNCTRLSTS_REG (REG_EMAC_BASE + 0x0130) -#define EMAC_REFERENCE_SLOT_NUMBER 0x0000000F -#define EMAC_REFERENCE_SLOT_NUMBER_M (EMAC_REFERENCE_SLOT_NUMBER_V << EMAC_REFERENCE_SLOT_NUMBER_S) -#define EMAC_REFERENCE_SLOT_NUMBER_V 0x0000000F -#define EMAC_REFERENCE_SLOT_NUMBER_S 16 -#define EMAC_ADVANCE_SLOT_CHECK (BIT(1)) -#define EMAC_ADVANCE_SLOT_CHECK_M (BIT(1)) -#define EMAC_ADVANCE_SLOT_CHECK_V 1 -#define EMAC_ADVANCE_SLOT_CHECK_S 1 -#define EMAC_ENABLE_SLOT_COMPARISON (BIT(0)) -#define EMAC_ENABLE_SLOT_COMPARISON_M (BIT(0)) -#define EMAC_ENABLE_SLOT_COMPARISON_V 1 -#define EMAC_ENABLE_SLOT_COMPARISON_S 0 - -#define EMAC_DMACHANNELCTRL_REG (REG_EMAC_BASE + 0x0160) -#define EMAC_AVERAGE_BITS_PER_SLOT_INTERRUPT_ENABLE (BIT(17)) -#define EMAC_AVERAGE_BITS_PER_SLOT_INTERRUPT_ENABLE_M (BIT(17)) -#define EMAC_AVERAGE_BITS_PER_SLOT_INTERRUPT_ENABLE_V 1 -#define EMAC_AVERAGE_BITS_PER_SLOT_INTERRUPT_ENABLE_S 17 -#define EMAC_SLOT_COUNT 0x00000007 -#define EMAC_SLOT_COUNT_M (EMAC_SLOT_COUNT_V << EMAC_SLOT_COUNT_S) -#define EMAC_SLOT_COUNT_V 0x00000007 -#define EMAC_SLOT_COUNT_S 4 -#define EMAC_CREDIT_CONTROL (BIT(1)) -#define EMAC_CREDIT_CONTROL_M (BIT(1)) -#define EMAC_CREDIT_CONTROL_V 1 -#define EMAC_CREDIT_CONTROL_S 1 -#define EMAC_CREDIT_BASED_SHAPER_DISABLE (BIT(0)) -#define EMAC_CREDIT_BASED_SHAPER_DISABLE_M (BIT(0)) -#define EMAC_CREDIT_BASED_SHAPER_DISABLE_V 1 -#define EMAC_CREDIT_BASED_SHAPER_DISABLE_S 0 - -#define EMAC_DMACHANNELAVSTS_REG (REG_EMAC_BASE + 0x0064) -#define EMAC_ABS_UPDATED (BIT(17)) -#define EMAC_ABS_UPDATED_M (BIT(17)) -#define EMAC_ABS_UPDATED_V 1 -#define EMAC_ABS_UPDATED_S 17 -#define EMAC_AVERAGE_BITS_PER_SLOT 0x0001FFFF -#define EMAC_AVERAGE_BITS_PER_SLOT_M (EMAC_AVERAGE_BITS_PER_SLOT_V << EMAC_AVERAGE_BITS_PER_SLOT_S) -#define EMAC_AVERAGE_BITS_PER_SLOT_V 0x0001FFFF -#define EMAC_AVERAGE_BITS_PER_SLOT_S 0 - -#define EMAC_DMAIDLESLOPECREDIT_REG (REG_EMAC_BASE + 0x0068) -#define EMAC_IDLESLOPECREDIT 0x00003FFF -#define EMAC_IDLESLOPECREDIT_M (EMAC_IDLESLOPECREDIT_V << EMAC_IDLESLOPECREDIT_S) -#define EMAC_IDLESLOPECREDIT_V 0x00003FFF -#define EMAC_IDLESLOPECREDIT_S 0 - -#define EMAC_DMASENDSLOPECREDIT_REG (REG_EMAC_BASE + 0x006C) -#define EMAC_SENDSLOPECREDIT 0x00003FFF -#define EMAC_SENDSLOPECREDIT_M (EMAC_SENDSLOPECREDIT_V << EMAC_SENDSLOPECREDIT_S) -#define EMAC_SENDSLOPECREDIT_V 0x00003FFF -#define EMAC_SENDSLOPECREDIT_S 0 - -#define EMAC_DMAHIGHCREDIT_REG (REG_EMAC_BASE + 0x0070) -#define EMAC_HICREDIT 0x1FFFFFFF -#define EMAC_HICREDIT_M (EMAC_HICREDIT_V << EMAC_HICREDIT_S) -#define EMAC_HICREDIT_V 0x1FFFFFFF -#define EMAC_HICREDIT_S 0 - -#define EMAC_DMALOCREDIT_REG (REG_EMAC_BASE + 0x0074) -#define EMAC_LOCREDIT 0x1FFFFFFF -#define EMAC_LOCREDIT_M (EMAC_LOCREDIT_V << EMAC_LOCREDIT_S) -#define EMAC_LOCREDIT_V 0x1FFFFFFF -#define EMAC_LOCREDIT_S 0 - -#define EMAC_GMACCONFIG_REG (REG_EMAC_BASE + 0x1000) -#define EMAC_SOURCE_ADDRESS_INSERTION_REPLACEMENT_CONTROL 0x00000007 -#define EMAC_SOURCE_ADDRESS_INSERTION_REPLACEMENT_CONTROL_M (EMAC_SOURCE_ADDRESS_INSERTION_REPLACEMENT_CONTROL_V << EMAC_SOURCE_ADDRESS_INSERTION_REPLACEMENT_CONTROL_S) -#define EMAC_SOURCE_ADDRESS_INSERTION_REPLACEMENT_CONTROL_V 0x00000007 -#define EMAC_SOURCE_ADDRESS_INSERTION_REPLACEMENT_CONTROL_S 28 -#define EMAC_AS_SUPPORT_2K_PACKETS (BIT(27)) -#define EMAC_AS_SUPPORT_2K_PACKETS_M (BIT(27)) -#define EMAC_AS_SUPPORT_2K_PACKETS_V 1 -#define EMAC_AS_SUPPORT_2K_PACKETS_S 27 -#define EMAC_SMII_FORCE_TRANSMIT_ERROR (BIT(26)) -#define EMAC_SMII_FORCE_TRANSMIT_ERROR_M (BIT(26)) -#define EMAC_SMII_FORCE_TRANSMIT_ERROR_V 1 -#define EMAC_SMII_FORCE_TRANSMIT_ERROR_S 26 -#define EMAC_CRC_STRIPPING_TYPE_FRAMES (BIT(25)) -#define EMAC_CRC_STRIPPING_TYPE_FRAMES_M (BIT(25)) -#define EMAC_CRC_STRIPPING_TYPE_FRAMES_V 1 -#define EMAC_CRC_STRIPPING_TYPE_FRAMES_S 25 -#define EMAC_TRANSMIT_CONFIGURATION (BIT(24)) -#define EMAC_TRANSMIT_CONFIGURATION_M (BIT(24)) -#define EMAC_TRANSMIT_CONFIGURATION_V 1 -#define EMAC_TRANSMIT_CONFIGURATION_S 24 -#define EMAC_GMACWATCHDOG (BIT(23)) -#define EMAC_GMACWATCHDOG_M (BIT(23)) -#define EMAC_GMACWATCHDOG_V 1 -#define EMAC_GMACWATCHDOG_S 23 -#define EMAC_GMACJABBER (BIT(22)) -#define EMAC_GMACJABBER_M (BIT(22)) -#define EMAC_GMACJABBER_V 1 -#define EMAC_GMACJABBER_S 22 -#define EMAC_GMACFRAMEBURST (BIT(21)) -#define EMAC_GMACFRAMEBURST_M (BIT(21)) -#define EMAC_GMACFRAMEBURST_V 1 -#define EMAC_GMACFRAMEBURST_S 21 -#define EMAC_GMACJUMBOFRAME (BIT(20)) -#define EMAC_GMACJUMBOFRAME_M (BIT(20)) -#define EMAC_GMACJUMBOFRAME_V 1 -#define EMAC_GMACJUMBOFRAME_S 20 -#define EMAC_GMACINTERFRAMEGAP 0x00000007 -#define EMAC_GMACINTERFRAMEGAP_M (EMAC_GMACINTERFRAMEGAP_V << EMAC_GMACINTERFRAMEGAP_S) -#define EMAC_GMACINTERFRAMEGAP_V 0x00000007 -#define EMAC_GMACINTERFRAMEGAP_S 17 -#define EMAC_GMACDISABLECRS (BIT(16)) -#define EMAC_GMACDISABLECRS_M (BIT(16)) -#define EMAC_GMACDISABLECRS_V 1 -#define EMAC_GMACDISABLECRS_S 16 -#define EMAC_GMACMIIGMII (BIT(15)) -#define EMAC_GMACMIIGMII_M (BIT(15)) -#define EMAC_GMACMIIGMII_V 1 -#define EMAC_GMACMIIGMII_S 15 -#define EMAC_GMACFESPEED (BIT(14)) -#define EMAC_GMACFESPEED_M (BIT(14)) -#define EMAC_GMACFESPEED_V 1 -#define EMAC_GMACFESPEED_S 14 -#define EMAC_GMACRXOWN (BIT(13)) -#define EMAC_GMACRXOWN_M (BIT(13)) -#define EMAC_GMACRXOWN_V 1 -#define EMAC_GMACRXOWN_S 13 -#define EMAC_GMACLOOPBACK (BIT(12)) -#define EMAC_GMACLOOPBACK_M (BIT(12)) -#define EMAC_GMACLOOPBACK_V 1 -#define EMAC_GMACLOOPBACK_S 12 -#define EMAC_GMACDUPLEX (BIT(11)) -#define EMAC_GMACDUPLEX_M (BIT(11)) -#define EMAC_GMACDUPLEX_V 1 -#define EMAC_GMACDUPLEX_S 11 -#define EMAC_GMACRXIPCOFFLOAD (BIT(10)) -#define EMAC_GMACRXIPCOFFLOAD_M (BIT(10)) -#define EMAC_GMACRXIPCOFFLOAD_V 1 -#define EMAC_GMACRXIPCOFFLOAD_S 10 -#define EMAC_GMACRETRY (BIT(9)) -#define EMAC_GMACRETRY_M (BIT(9)) -#define EMAC_GMACRETRY_V 1 -#define EMAC_GMACRETRY_S 9 -#define EMAC_GMACLINK (BIT(8)) -#define EMAC_GMACLINK_M (BIT(8)) -#define EMAC_GMACLINK_V 1 -#define EMAC_GMACLINK_S 8 -#define EMAC_GMACPADCRCSTRIP (BIT(7)) -#define EMAC_GMACPADCRCSTRIP_M (BIT(7)) -#define EMAC_GMACPADCRCSTRIP_V 1 -#define EMAC_GMACPADCRCSTRIP_S 7 -#define EMAC_GMACBACKOFFLIMIT 0x00000003 -#define EMAC_GMACBACKOFFLIMIT_M (EMAC_GMACBACKOFFLIMIT_V << EMAC_GMACBACKOFFLIMIT_S) -#define EMAC_GMACBACKOFFLIMIT_V 0x00000003 -#define EMAC_GMACBACKOFFLIMIT_S 5 -#define EMAC_GMACDEFERRALCHECK (BIT(4)) -#define EMAC_GMACDEFERRALCHECK_M (BIT(4)) -#define EMAC_GMACDEFERRALCHECK_V 1 -#define EMAC_GMACDEFERRALCHECK_S 4 -#define EMAC_GMACTX (BIT(3)) -#define EMAC_GMACTX_M (BIT(3)) -#define EMAC_GMACTX_V 1 -#define EMAC_GMACTX_S 3 -#define EMAC_GMACRX (BIT(2)) -#define EMAC_GMACRX_M (BIT(2)) -#define EMAC_GMACRX_V 1 -#define EMAC_GMACRX_S 2 -#define EMAC_PREAMBLE_LENGTH_TRANSMIT_FRAMES 0x00000003 -#define EMAC_PREAMBLE_LENGTH_TRANSMIT_FRAMES_M (EMAC_PREAMBLE_LENGTH_TRANSMIT_FRAMES_V << EMAC_PREAMBLE_LENGTH_TRANSMIT_FRAMES_S) -#define EMAC_PREAMBLE_LENGTH_TRANSMIT_FRAMES_V 0x00000003 -#define EMAC_PREAMBLE_LENGTH_TRANSMIT_FRAMES_S 0 - -#define EMAC_GMACFRAMEFILTER_REG (REG_EMAC_BASE + 0x1004) -#define EMAC_RECEIVEALL (BIT(31)) -#define EMAC_RECEIVEALL_M (BIT(31)) -#define EMAC_RECEIVEALL_V 1 -#define EMAC_RECEIVEALL_S 31 -#define EMAC_DROP_NON_TCP_UDP_IP_FRAMES (BIT(21)) -#define EMAC_DROP_NON_TCP_UDP_IP_FRAMES_M (BIT(21)) -#define EMAC_DROP_NON_TCP_UDP_IP_FRAMES_V 1 -#define EMAC_DROP_NON_TCP_UDP_IP_FRAMES_S 21 -#define EMAC_LAYER_3_AND_LAYER_4_FILTER_ENABLE (BIT(20)) -#define EMAC_LAYER_3_AND_LAYER_4_FILTER_ENABLE_M (BIT(20)) -#define EMAC_LAYER_3_AND_LAYER_4_FILTER_ENABLE_V 1 -#define EMAC_LAYER_3_AND_LAYER_4_FILTER_ENABLE_S 20 -#define EMAC_VLAN_TAG_FILTER_ENABLE (BIT(16)) -#define EMAC_VLAN_TAG_FILTER_ENABLE_M (BIT(16)) -#define EMAC_VLAN_TAG_FILTER_ENABLE_V 1 -#define EMAC_VLAN_TAG_FILTER_ENABLE_S 16 -#define EMAC_HASH_OR_PERFECT_FILTE (BIT(10)) -#define EMAC_HASH_OR_PERFECT_FILTE_M (BIT(10)) -#define EMAC_HASH_OR_PERFECT_FILTE_V 1 -#define EMAC_HASH_OR_PERFECT_FILTE_S 10 -#define EMAC_SOURCE_ADDRESS_FILTER_ENABLE (BIT(9)) -#define EMAC_SOURCE_ADDRESS_FILTER_ENABLE_M (BIT(9)) -#define EMAC_SOURCE_ADDRESS_FILTER_ENABLE_V 1 -#define EMAC_SOURCE_ADDRESS_FILTER_ENABLE_S 9 -#define EMAC_SA_INVERSE_FILTERING (BIT(8)) -#define EMAC_SA_INVERSE_FILTERING_M (BIT(8)) -#define EMAC_SA_INVERSE_FILTERING_V 1 -#define EMAC_SA_INVERSE_FILTERING_S 8 -#define EMAC_PASS_CONTROL_FRAMES 0x00000003 -#define EMAC_PASS_CONTROL_FRAMES_M (EMAC_PASS_CONTROL_FRAMES_V << EMAC_PASS_CONTROL_FRAMES_S) -#define EMAC_PASS_CONTROL_FRAMES_V 0x00000003 -#define EMAC_PASS_CONTROL_FRAMES_S 6 -#define EMAC_DISABLE_BROADCAST_FRAMES (BIT(5)) -#define EMAC_DISABLE_BROADCAST_FRAMES_M (BIT(5)) -#define EMAC_DISABLE_BROADCAST_FRAMES_V 1 -#define EMAC_DISABLE_BROADCAST_FRAMES_S 5 -#define EMAC_PASS_ALL_MULTICAST (BIT(4)) -#define EMAC_PASS_ALL_MULTICAST_M (BIT(4)) -#define EMAC_PASS_ALL_MULTICAST_V 1 -#define EMAC_PASS_ALL_MULTICAST_S 4 -#define EMAC_DA_INVERSE_FILTERING (BIT(3)) -#define EMAC_DA_INVERSE_FILTERING_M (BIT(3)) -#define EMAC_DA_INVERSE_FILTERING_V 1 -#define EMAC_DA_INVERSE_FILTERING_S 3 -#define EMAC_HASH_MULTICAST (BIT(2)) -#define EMAC_HASH_MULTICAST_M (BIT(2)) -#define EMAC_HASH_MULTICAST_V 1 -#define EMAC_HASH_MULTICAST_S 2 -#define EMAC_HASH_UNICAST (BIT(1)) -#define EMAC_HASH_UNICAST_M (BIT(1)) -#define EMAC_HASH_UNICAST_V 1 -#define EMAC_HASH_UNICAST_S 1 -#define EMAC_PROMISCUOUS_MODE (BIT(0)) -#define EMAC_PROMISCUOUS_MODE_M (BIT(0)) -#define EMAC_PROMISCUOUS_MODE_V 1 -#define EMAC_PROMISCUOUS_MODE_S 0 - -#define EMAC_GMACHASHHIGH_REG (REG_EMAC_BASE + 0x1008) -#define EMAC_HASH_TABLE_HIGH 0xFFFFFFFF -#define EMAC_HASH_TABLE_HIGH_M (EMAC_HASH_TABLE_HIGH_V << EMAC_HASH_TABLE_HIGH_S) -#define EMAC_HASH_TABLE_HIGH_V 0xFFFFFFFF -#define EMAC_HASH_TABLE_HIGH_S 0 - -#define EMAC_GMACHASHLOW_REG (REG_EMAC_BASE + 0x100C) -#define EMAC_HASH_TABLE_LOW 0xFFFFFFFF -#define EMAC_HASH_TABLE_LOW_M (EMAC_HASH_TABLE_LOW_V << EMAC_HASH_TABLE_LOW_S) -#define EMAC_HASH_TABLE_LOW_V 0xFFFFFFFF -#define EMAC_HASH_TABLE_LOW_S 0 - -#define EMAC_GMACGMIIADDR_REG (REG_EMAC_BASE + 0x1010) -#define EMAC_GMIIDEV 0x0000001F -#define EMAC_GMIIDEV_M (EMAC_GMIIDEV_V << EMAC_GMIIDEV_S) -#define EMAC_GMIIDEV_V 0x0000001F -#define EMAC_GMIIDEV_S 11 -#define EMAC_GMIIREG 0x0000001F -#define EMAC_GMIIREG_M (EMAC_GMIIREG_V << EMAC_GMIIREG_S) -#define EMAC_GMIIREG_V 0x0000001F -#define EMAC_GMIIREG_S 6 -#define EMAC_GMIICSRCLK 0x0000000F -#define EMAC_GMIICSRCLK_M (EMAC_GMIICSRCLK_V << EMAC_GMIICSRCLK_S) -#define EMAC_GMIICSRCLK_V 0x0000000F -#define EMAC_GMIICSRCLK_S 2 -#define EMAC_GMIIWRITE (BIT(1)) -#define EMAC_GMIIWRITE_M (BIT(1)) -#define EMAC_GMIIWRITE_V 1 -#define EMAC_GMIIWRITE_S 1 -#define EMAC_GMIIBUSY (BIT(0)) -#define EMAC_GMIIBUSY_M (BIT(0)) -#define EMAC_GMIIBUSY_V 1 -#define EMAC_GMIIBUSY_S 0 - -#define EMAC_GMACGMIIDATA_REG (REG_EMAC_BASE + 0x1014) -#define EMAC_GMII_DATA 0x0000FFFF -#define EMAC_GMII_DATA_M (EMAC_GMII_DATA_V << EMAC_GMII_DATA_S) -#define EMAC_GMII_DATA_V 0x0000FFFF -#define EMAC_GMII_DATA_S 0 - -#define EMAC_GMACFLOWCONTROL_REG (REG_EMAC_BASE + 0x1018) -#define EMAC_PAUSE_TIME 0x0000FFFF -#define EMAC_PAUSE_TIME_M (EMAC_PAUSE_TIME_V << EMAC_PAUSE_TIME_S) -#define EMAC_PAUSE_TIME_V 0x0000FFFF -#define EMAC_PAUSE_TIME_S 16 -#define EMAC_DISABLE_ZERO_QUANTA_PAUSE (BIT(7)) -#define EMAC_DISABLE_ZERO_QUANTA_PAUSE_M (BIT(7)) -#define EMAC_DISABLE_ZERO_QUANTA_PAUSE_V 1 -#define EMAC_DISABLE_ZERO_QUANTA_PAUSE_S 7 -#define EMAC_PAUSE_LOW_THRESHOLD 0x00000003 -#define EMAC_PAUSE_LOW_THRESHOLD_M (EMAC_PAUSE_LOW_THRESHOLD_V << EMAC_PAUSE_LOW_THRESHOLD_S) -#define EMAC_PAUSE_LOW_THRESHOLD_V 0x00000003 -#define EMAC_PAUSE_LOW_THRESHOLD_S 4 -#define EMAC_UNICAST_PAUSE_FRAME_DETECT (BIT(3)) -#define EMAC_UNICAST_PAUSE_FRAME_DETECT_M (BIT(3)) -#define EMAC_UNICAST_PAUSE_FRAME_DETECT_V 1 -#define EMAC_UNICAST_PAUSE_FRAME_DETECT_S 3 -#define EMAC_RECEIVE_FLOW_CONTROL_ENABLE (BIT(2)) -#define EMAC_RECEIVE_FLOW_CONTROL_ENABLE_M (BIT(2)) -#define EMAC_RECEIVE_FLOW_CONTROL_ENABLE_V 1 -#define EMAC_RECEIVE_FLOW_CONTROL_ENABLE_S 2 -#define EMAC_TRANSMIT_FLOW_CONTROL_ENABLE (BIT(1)) -#define EMAC_TRANSMIT_FLOW_CONTROL_ENABLE_M (BIT(1)) -#define EMAC_TRANSMIT_FLOW_CONTROL_ENABLE_V 1 -#define EMAC_TRANSMIT_FLOW_CONTROL_ENABLE_S 1 -#define EMAC_FLOW_CONTROL_BUSY_BACKPRESSURE_ACTIVATE (BIT(0)) -#define EMAC_FLOW_CONTROL_BUSY_BACKPRESSURE_ACTIVATE_M (BIT(0)) -#define EMAC_FLOW_CONTROL_BUSY_BACKPRESSURE_ACTIVATE_V 1 -#define EMAC_FLOW_CONTROL_BUSY_BACKPRESSURE_ACTIVATE_S 0 - -#define EMAC_GMACVLAN_REG (REG_EMAC_BASE + 0x101C) -#define EMAC_VLAN_TAG_HASH_TABLE_MATCH_ENABLE (BIT(19)) -#define EMAC_VLAN_TAG_HASH_TABLE_MATCH_ENABLE_M (BIT(19)) -#define EMAC_VLAN_TAG_HASH_TABLE_MATCH_ENABLE_V 1 -#define EMAC_VLAN_TAG_HASH_TABLE_MATCH_ENABLE_S 19 -#define EMAC_ENABLE_S_VLAN (BIT(18)) -#define EMAC_ENABLE_S_VLAN_M (BIT(18)) -#define EMAC_ENABLE_S_VLAN_V 1 -#define EMAC_ENABLE_S_VLAN_S 18 -#define EMAC_VLAN_TAG_INVERSE_MATCH_ENABLE (BIT(17)) -#define EMAC_VLAN_TAG_INVERSE_MATCH_ENABLE_M (BIT(17)) -#define EMAC_VLAN_TAG_INVERSE_MATCH_ENABLE_V 1 -#define EMAC_VLAN_TAG_INVERSE_MATCH_ENABLE_S 17 -#define EMAC_ENABLE_VLAN_TAG_COMPARISON (BIT(16)) -#define EMAC_ENABLE_VLAN_TAG_COMPARISON_M (BIT(16)) -#define EMAC_ENABLE_VLAN_TAG_COMPARISON_V 1 -#define EMAC_ENABLE_VLAN_TAG_COMPARISON_S 16 -#define EMAC_VLAN_TAG_IDENTIFIER_RECEIVE_FRAMES 0x0000FFFF -#define EMAC_VLAN_TAG_IDENTIFIER_RECEIVE_FRAMES_M (EMAC_VLAN_TAG_IDENTIFIER_RECEIVE_FRAMES_V << EMAC_VLAN_TAG_IDENTIFIER_RECEIVE_FRAMES_S) -#define EMAC_VLAN_TAG_IDENTIFIER_RECEIVE_FRAMES_V 0x0000FFFF -#define EMAC_VLAN_TAG_IDENTIFIER_RECEIVE_FRAMES_S 0 - -#define EMAC_GMACVERSION_REG (REG_EMAC_BASE + 0x1020) -#define EMAC_USERVER 0x000000FF -#define EMAC_USERVER_M (EMAC_USERVER_V << EMAC_USERVER_S) -#define EMAC_USERVER_V 0x000000FF -#define EMAC_USERVER_S 8 -#define EMAC_SNPSVER 0x000000FF -#define EMAC_SNPSVER_M (EMAC_SNPSVER_V << EMAC_SNPSVER_S) -#define EMAC_SNPSVER_V 0x000000FF -#define EMAC_SNPSVER_S 0 - -#define EMAC_GMACDEBUG_REG (REG_EMAC_BASE + 0x1024) -#define EMAC_MTL_TXSTATUS_FIFO_FULL_STATUS (BIT(25)) -#define EMAC_MTL_TXSTATUS_FIFO_FULL_STATUS_M (BIT(25)) -#define EMAC_MTL_TXSTATUS_FIFO_FULL_STATUS_V 1 -#define EMAC_MTL_TXSTATUS_FIFO_FULL_STATUS_S 25 -#define EMAC_MTL_TX_FIFO_NOT_EMPTY_STATUS (BIT(24)) -#define EMAC_MTL_TX_FIFO_NOT_EMPTY_STATUS_M (BIT(24)) -#define EMAC_MTL_TX_FIFO_NOT_EMPTY_STATUS_V 1 -#define EMAC_MTL_TX_FIFO_NOT_EMPTY_STATUS_S 24 -#define EMAC_MTL_TX_FIFO_WRITE_CONTROLLER_STATUS (BIT(22)) -#define EMAC_MTL_TX_FIFO_WRITE_CONTROLLER_STATUS_M (BIT(22)) -#define EMAC_MTL_TX_FIFO_WRITE_CONTROLLER_STATUS_V 1 -#define EMAC_MTL_TX_FIFO_WRITE_CONTROLLER_STATUS_S 22 -#define EMAC_MTL_TX_FIFO_READ_CONTROLLER_STATUS 0x00000003 -#define EMAC_MTL_TX_FIFO_READ_CONTROLLER_STATUS_M (EMAC_MTL_TX_FIFO_READ_CONTROLLER_STATUS_V << EMAC_MTL_TX_FIFO_READ_CONTROLLER_STATUS_S) -#define EMAC_MTL_TX_FIFO_READ_CONTROLLER_STATUS_V 0x00000003 -#define EMAC_MTL_TX_FIFO_READ_CONTROLLER_STATUS_S 20 -#define EMAC_MAC_TRANSMITTER_PAUSE (BIT(19)) -#define EMAC_MAC_TRANSMITTER_PAUSE_M (BIT(19)) -#define EMAC_MAC_TRANSMITTER_PAUSE_V 1 -#define EMAC_MAC_TRANSMITTER_PAUSE_S 19 -#define EMAC_MAC_TRANSMIT_FRAME_CONTROLLER_STATUS 0x00000003 -#define EMAC_MAC_TRANSMIT_FRAME_CONTROLLER_STATUS_M (EMAC_MAC_TRANSMIT_FRAME_CONTROLLER_STATUS_V << EMAC_MAC_TRANSMIT_FRAME_CONTROLLER_STATUS_S) -#define EMAC_MAC_TRANSMIT_FRAME_CONTROLLER_STATUS_V 0x00000003 -#define EMAC_MAC_TRANSMIT_FRAME_CONTROLLER_STATUS_S 17 -#define EMAC_MAC_TRANSMIT_PROTOCOL_ENGINE_STATUS (BIT(16)) -#define EMAC_MAC_TRANSMIT_PROTOCOL_ENGINE_STATUS_M (BIT(16)) -#define EMAC_MAC_TRANSMIT_PROTOCOL_ENGINE_STATUS_V 1 -#define EMAC_MAC_TRANSMIT_PROTOCOL_ENGINE_STATUS_S 16 -#define EMAC_MTL_RXFIFO_FILL_LEVEL_STATUS 0x00000003 -#define EMAC_MTL_RXFIFO_FILL_LEVEL_STATUS_M (EMAC_MTL_RXFIFO_FILL_LEVEL_STATUS_V << EMAC_MTL_RXFIFO_FILL_LEVEL_STATUS_S) -#define EMAC_MTL_RXFIFO_FILL_LEVEL_STATUS_V 0x00000003 -#define EMAC_MTL_RXFIFO_FILL_LEVEL_STATUS_S 8 -#define EMAC_MTL_RXFIFO_READ_CONTROLLER_STATE 0x00000003 -#define EMAC_MTL_RXFIFO_READ_CONTROLLER_STATE_M (EMAC_MTL_RXFIFO_READ_CONTROLLER_STATE_V << EMAC_MTL_RXFIFO_READ_CONTROLLER_STATE_S) -#define EMAC_MTL_RXFIFO_READ_CONTROLLER_STATE_V 0x00000003 -#define EMAC_MTL_RXFIFO_READ_CONTROLLER_STATE_S 5 -#define EMAC_MTL_RX_FIFO_WRITE_CONTROLLER_ACTIVE_STATUS (BIT(4)) -#define EMAC_MTL_RX_FIFO_WRITE_CONTROLLER_ACTIVE_STATUS_M (BIT(4)) -#define EMAC_MTL_RX_FIFO_WRITE_CONTROLLER_ACTIVE_STATUS_V 1 -#define EMAC_MTL_RX_FIFO_WRITE_CONTROLLER_ACTIVE_STATUS_S 4 -#define EMAC_MAC_RECEIVE_FRAME_FIFO_CONTROLLER_STATUS 0x00000003 -#define EMAC_MAC_RECEIVE_FRAME_FIFO_CONTROLLER_STATUS_M (EMAC_MAC_RECEIVE_FRAME_FIFO_CONTROLLER_STATUS_V << EMAC_MAC_RECEIVE_FRAME_FIFO_CONTROLLER_STATUS_S) -#define EMAC_MAC_RECEIVE_FRAME_FIFO_CONTROLLER_STATUS_V 0x00000003 -#define EMAC_MAC_RECEIVE_FRAME_FIFO_CONTROLLER_STATUS_S 1 -#define EMAC_MAC_RECEIVE_PROTOCOL_ENGINE_STATUS (BIT(0)) -#define EMAC_MAC_RECEIVE_PROTOCOL_ENGINE_STATUS_M (BIT(0)) -#define EMAC_MAC_RECEIVE_PROTOCOL_ENGINE_STATUS_V 1 -#define EMAC_MAC_RECEIVE_PROTOCOL_ENGINE_STATUS_S 0 - -#define EMAC_GMACLPITIMERSCONTROL_REG (REG_EMAC_BASE + 0x1034) -#define EMAC_LPI_LS_TIMER 0x000003FF -#define EMAC_LPI_LS_TIMER_M (EMAC_LPI_LS_TIMER_V << EMAC_LPI_LS_TIMER_S) -#define EMAC_LPI_LS_TIMER_V 0x000003FF -#define EMAC_LPI_LS_TIMER_S 16 -#define EMAC_LPI_TW_TIMER 0x0000FFFF -#define EMAC_LPI_TW_TIMER_M (EMAC_LPI_TW_TIMER_V << EMAC_LPI_TW_TIMER_S) -#define EMAC_LPI_TW_TIMER_V 0x0000FFFF -#define EMAC_LPI_TW_TIMER_S 0 - -#define EMAC_GMACINTERRUPTSTATUS_REG (REG_EMAC_BASE + 0x1038) -#define EMAC_GPI_INTERRUPT_STATUS (BIT(11)) -#define EMAC_GPI_INTERRUPT_STATUS_M (BIT(11)) -#define EMAC_GPI_INTERRUPT_STATUS_V 1 -#define EMAC_GPI_INTERRUPT_STATUS_S 11 -#define EMAC_LPI_INTERRUPT_STATUS (BIT(10)) -#define EMAC_LPI_INTERRUPT_STATUS_M (BIT(10)) -#define EMAC_LPI_INTERRUPT_STATUS_V 1 -#define EMAC_LPI_INTERRUPT_STATUS_S 10 -#define EMAC_TIMESTAMP_INTERRUP_STATUS (BIT(9)) -#define EMAC_TIMESTAMP_INTERRUP_STATUS_M (BIT(9)) -#define EMAC_TIMESTAMP_INTERRUP_STATUS_V 1 -#define EMAC_TIMESTAMP_INTERRUP_STATUS_S 9 -#define EMAC_MMC_RECEIVE_CHECKSUM_OFFLOAD_INTERRUPT_STATUS (BIT(7)) -#define EMAC_MMC_RECEIVE_CHECKSUM_OFFLOAD_INTERRUPT_STATUS_M (BIT(7)) -#define EMAC_MMC_RECEIVE_CHECKSUM_OFFLOAD_INTERRUPT_STATUS_V 1 -#define EMAC_MMC_RECEIVE_CHECKSUM_OFFLOAD_INTERRUPT_STATUS_S 7 -#define EMAC_MMC_TRANSMIT_INTERRUPT_STATUS (BIT(6)) -#define EMAC_MMC_TRANSMIT_INTERRUPT_STATUS_M (BIT(6)) -#define EMAC_MMC_TRANSMIT_INTERRUPT_STATUS_V 1 -#define EMAC_MMC_TRANSMIT_INTERRUPT_STATUS_S 6 -#define EMAC_MMC_RECEIVE_INTERRUPT_STATUS (BIT(5)) -#define EMAC_MMC_RECEIVE_INTERRUPT_STATUS_M (BIT(5)) -#define EMAC_MMC_RECEIVE_INTERRUPT_STATUS_V 1 -#define EMAC_MMC_RECEIVE_INTERRUPT_STATUS_S 5 -#define EMAC_MMC_INTERRUPT_STATUS (BIT(4)) -#define EMAC_MMC_INTERRUPT_STATUS_M (BIT(4)) -#define EMAC_MMC_INTERRUPT_STATUS_V 1 -#define EMAC_MMC_INTERRUPT_STATUS_S 4 -#define EMAC_PMT_INTERRUPT_STATUS (BIT(3)) -#define EMAC_PMT_INTERRUPT_STATUS_M (BIT(3)) -#define EMAC_PMT_INTERRUPT_STATUS_V 1 -#define EMAC_PMT_INTERRUPT_STATUS_S 3 -#define EMAC_PCS_AUTO_NEGOTIATION_COMPLETE (BIT(2)) -#define EMAC_PCS_AUTO_NEGOTIATION_COMPLETE_M (BIT(2)) -#define EMAC_PCS_AUTO_NEGOTIATION_COMPLETE_V 1 -#define EMAC_PCS_AUTO_NEGOTIATION_COMPLETE_S 2 -#define EMAC_PCS_LINK_STATUS_CHANGED (BIT(1)) -#define EMAC_PCS_LINK_STATUS_CHANGED_M (BIT(1)) -#define EMAC_PCS_LINK_STATUS_CHANGED_V 1 -#define EMAC_PCS_LINK_STATUS_CHANGED_S 1 -#define EMAC_INTERRUPT_STATUS (BIT(0)) -#define EMAC_INTERRUPT_STATUS_M (BIT(0)) -#define EMAC_INTERRUPT_STATUS_V 1 -#define EMAC_INTERRUPT_STATUS_S 0 - -#define EMAC_GMACINTERRUPTMASK_REG (REG_EMAC_BASE + 0x103C) -#define EMAC_LPI_INTERRUPT_MASK (BIT(10)) -#define EMAC_LPI_INTERRUPT_MASK_M (BIT(10)) -#define EMAC_LPI_INTERRUPT_MASK_V 1 -#define EMAC_LPI_INTERRUPT_MASK_S 10 -#define EMAC_TIMESTAMP_INTERRUPT_MASK (BIT(9)) -#define EMAC_TIMESTAMP_INTERRUPT_MASK_M (BIT(9)) -#define EMAC_TIMESTAMP_INTERRUPT_MASK_V 1 -#define EMAC_TIMESTAMP_INTERRUPT_MASK_S 9 -#define EMAC_PMT_INTERRUPT_MASK (BIT(3)) -#define EMAC_PMT_INTERRUPT_MASK_M (BIT(3)) -#define EMAC_PMT_INTERRUPT_MASK_V 1 -#define EMAC_PMT_INTERRUPT_MASK_S 3 -#define EMAC_PCS_AN_COMPLETION_INTERRUPT_MASK (BIT(2)) -#define EMAC_PCS_AN_COMPLETION_INTERRUPT_MASK_M (BIT(2)) -#define EMAC_PCS_AN_COMPLETION_INTERRUPT_MASK_V 1 -#define EMAC_PCS_AN_COMPLETION_INTERRUPT_MASK_S 2 -#define EMAC_PCS_LINK_STATUS_INTERRUPT_MASK (BIT(1)) -#define EMAC_PCS_LINK_STATUS_INTERRUPT_MASK_M (BIT(1)) -#define EMAC_PCS_LINK_STATUS_INTERRUPT_MASK_V 1 -#define EMAC_PCS_LINK_STATUS_INTERRUPT_MASK_S 1 -#define EMAC_INTERRUPT_MASK (BIT(0)) -#define EMAC_INTERRUPT_MASK_M (BIT(0)) -#define EMAC_INTERRUPT_MASK_V 1 -#define EMAC_INTERRUPT_MASK_S 0 - -#define EMAC_GMACADDR0HIGH_REG (REG_EMAC_BASE + 0x1040) -#define EMAC_ADDRESS_ENABLE0 (BIT(31)) -#define EMAC_ADDRESS_ENABLE0_M (BIT(31)) -#define EMAC_ADDRESS_ENABLE0_V 1 -#define EMAC_ADDRESS_ENABLE0_S 31 -#define EMAC_MAC_ADDRESS0_HI 0x0000FFFF -#define EMAC_MAC_ADDRESS0_HI_M (EMAC_MAC_ADDRESS0_HI_V << EMAC_MAC_ADDRESS0_HI_S) -#define EMAC_MAC_ADDRESS0_HI_V 0x0000FFFF -#define EMAC_MAC_ADDRESS0_HI_S 0 - -#define EMAC_GMACADDR0LOW_REG (REG_EMAC_BASE + 0x1044) -#define EMAC_MAC_ADDRESS0_LOW 0xFFFFFFFF -#define EMAC_MAC_ADDRESS0_LOW_M (EMAC_MAC_ADDRESS0_LOW_V << EMAC_MAC_ADDRESS0_LOW_S) -#define EMAC_MAC_ADDRESS0_LOW_V 0xFFFFFFFF -#define EMAC_MAC_ADDRESS0_LOW_S 0 - -#define EMAC_GMACADDR1HIGH_REG (REG_EMAC_BASE + 0x1048) -#define EMAC_ADDRESS_ENABLE1 (BIT(31)) -#define EMAC_ADDRESS_ENABLE1_M (BIT(31)) -#define EMAC_ADDRESS_ENABLE1_V 1 -#define EMAC_ADDRESS_ENABLE1_S 31 -#define EMAC_SOURCE_ADDRESS (BIT(30)) -#define EMAC_SOURCE_ADDRESS_M (BIT(30)) -#define EMAC_SOURCE_ADDRESS_V 1 -#define EMAC_SOURCE_ADDRESS_S 30 -#define EMAC_MASK_BYTE_CONTROL 0x0000003F -#define EMAC_MASK_BYTE_CONTROL_M (EMAC_MASK_BYTE_CONTROL_V << EMAC_MASK_BYTE_CONTROL_S) -#define EMAC_MASK_BYTE_CONTROL_V 0x0000003F -#define EMAC_MASK_BYTE_CONTROL_S 24 -#define EMAC_MAC_ADDRESS1_HI 0x0000FFFF -#define EMAC_MAC_ADDRESS1_HI_M (EMAC_MAC_ADDRESS1_HI_V << EMAC_MAC_ADDRESS1_HI_S) -#define EMAC_MAC_ADDRESS1_HI_V 0x0000FFFF -#define EMAC_MAC_ADDRESS1_HI_S 0 - -#define EMAC_GMACADDR1LOW_REG (REG_EMAC_BASE + 0x104C) -#define EMAC_MAC_ADDRESS1_LOW 0xFFFFFFFF -#define EMAC_MAC_ADDRESS1_LOW_M (EMAC_MAC_ADDRESS1_LOW_V << EMAC_MAC_ADDRESS1_LOW_S) -#define EMAC_MAC_ADDRESS1_LOW_V 0xFFFFFFFF -#define EMAC_MAC_ADDRESS1_LOW_S 0 - -#define EMAC_GMAC_AN_CONTROL_REG (REG_EMAC_BASE + 0x10C0) -#define EMAC_SGMII_RAL_CONTROL (BIT(18)) -#define EMAC_SGMII_RAL_CONTROL_M (BIT(18)) -#define EMAC_SGMII_RAL_CONTROL_V 1 -#define EMAC_SGMII_RAL_CONTROL_S 18 -#define EMAC_LOCK_REFERENCE (BIT(17)) -#define EMAC_LOCK_REFERENCE_M (BIT(17)) -#define EMAC_LOCK_REFERENCE_V 1 -#define EMAC_LOCK_REFERENCE_S 17 -#define EMAC_ENABLE_COMMA_DETECT (BIT(16)) -#define EMAC_ENABLE_COMMA_DETECT_M (BIT(16)) -#define EMAC_ENABLE_COMMA_DETECT_V 1 -#define EMAC_ENABLE_COMMA_DETECT_S 16 -#define EMAC_EXTERNAL_LOOPBACK_ENABLE (BIT(14)) -#define EMAC_EXTERNAL_LOOPBACK_ENABLE_M (BIT(14)) -#define EMAC_EXTERNAL_LOOPBACK_ENABLE_V 1 -#define EMAC_EXTERNAL_LOOPBACK_ENABLE_S 14 -#define EMAC_AUTO_NEGOTIATION_ENABLE (BIT(12)) -#define EMAC_AUTO_NEGOTIATION_ENABLE_M (BIT(12)) -#define EMAC_AUTO_NEGOTIATION_ENABLE_V 1 -#define EMAC_AUTO_NEGOTIATION_ENABLE_S 12 -#define EMAC_RESTART_AUTO_NEGOTIATION (BIT(9)) -#define EMAC_RESTART_AUTO_NEGOTIATION_M (BIT(9)) -#define EMAC_RESTART_AUTO_NEGOTIATION_V 1 -#define EMAC_RESTART_AUTO_NEGOTIATION_S 9 - -#define EMAC_GMAC_AN_STATUS_REG (REG_EMAC_BASE + 0x10C4) -#define EMAC_EXTENDED_STATUS (BIT(8)) -#define EMAC_EXTENDED_STATUS_M (BIT(8)) -#define EMAC_EXTENDED_STATUS_V 1 -#define EMAC_EXTENDED_STATUS_S 8 -#define EMAC_AUTO_NEGOTIATION_COMPLETE (BIT(5)) -#define EMAC_AUTO_NEGOTIATION_COMPLETE_M (BIT(5)) -#define EMAC_AUTO_NEGOTIATION_COMPLETE_V 1 -#define EMAC_AUTO_NEGOTIATION_COMPLETE_S 5 -#define EMAC_AUTO_NEGOTIATION_ABILITY (BIT(3)) -#define EMAC_AUTO_NEGOTIATION_ABILITY_M (BIT(3)) -#define EMAC_AUTO_NEGOTIATION_ABILITY_V 1 -#define EMAC_AUTO_NEGOTIATION_ABILITY_S 3 -#define EMAC_LINK_AN_STATUS (BIT(2)) -#define EMAC_LINK_AN_STATUS_M (BIT(2)) -#define EMAC_LINK_AN_STATUS_V 1 -#define EMAC_LINK_AN_STATUS_S 2 - -#define EMAC_GMAC_AUTO_NEGOTIATION_ADVERTISEMENT_REG (REG_EMAC_BASE + 0x10C8) -#define EMAC_ADV_NEXT_PAGE_SUPPORT (BIT(15)) -#define EMAC_ADV_NEXT_PAGE_SUPPORT_M (BIT(15)) -#define EMAC_ADV_NEXT_PAGE_SUPPORT_V 1 -#define EMAC_ADV_NEXT_PAGE_SUPPORT_S 15 -#define EMAC_ADV_REMOTE_FAULT_ENCODING 0x00000003 -#define EMAC_ADV_REMOTE_FAULT_ENCODING_M (EMAC_ADV_REMOTE_FAULT_ENCODING_V << EMAC_ADV_REMOTE_FAULT_ENCODING_S) -#define EMAC_ADV_REMOTE_FAULT_ENCODING_V 0x00000003 -#define EMAC_ADV_REMOTE_FAULT_ENCODING_S 12 -#define EMAC_ADV_PAUSE_ENCODING 0x00000003 -#define EMAC_ADV_PAUSE_ENCODING_M (EMAC_ADV_PAUSE_ENCODING_V << EMAC_ADV_PAUSE_ENCODING_S) -#define EMAC_ADV_PAUSE_ENCODING_V 0x00000003 -#define EMAC_ADV_PAUSE_ENCODING_S 7 -#define EMAC_ADV_HALF_DUPLEX (BIT(6)) -#define EMAC_ADV_HALF_DUPLEX_M (BIT(6)) -#define EMAC_ADV_HALF_DUPLEX_V 1 -#define EMAC_ADV_HALF_DUPLEX_S 6 -#define EMAC_ADV_FULL_DUPLEX (BIT(5)) -#define EMAC_ADV_FULL_DUPLEX_M (BIT(5)) -#define EMAC_ADV_FULL_DUPLEX_V 1 -#define EMAC_ADV_FULL_DUPLEX_S 5 - -#define EMAC_GMAC_AUTO_NEGOTIATION_LINK_PARTNER_ABILITY_REG (REG_EMAC_BASE + 0x10CC) -#define EMAC_LINK_NEXT_PAGE_SUPPORT (BIT(15)) -#define EMAC_LINK_NEXT_PAGE_SUPPORT_M (BIT(15)) -#define EMAC_LINK_NEXT_PAGE_SUPPORT_V 1 -#define EMAC_LINK_NEXT_PAGE_SUPPORT_S 15 -#define EMAC_LINK_ACKNOWLEDGE (BIT(14)) -#define EMAC_LINK_ACKNOWLEDGE_M (BIT(14)) -#define EMAC_LINK_ACKNOWLEDGE_V 1 -#define EMAC_LINK_ACKNOWLEDGE_S 14 -#define EMAC_LINK_REMOTE_FAULT_ENCODING 0x00000003 -#define EMAC_LINK_REMOTE_FAULT_ENCODING_M (EMAC_LINK_REMOTE_FAULT_ENCODING_V << EMAC_LINK_REMOTE_FAULT_ENCODING_S) -#define EMAC_LINK_REMOTE_FAULT_ENCODING_V 0x00000003 -#define EMAC_LINK_REMOTE_FAULT_ENCODING_S 12 -#define EMAC_LINK_PAUSE_ENCODING 0x00000003 -#define EMAC_LINK_PAUSE_ENCODING_M (EMAC_LINK_PAUSE_ENCODING_V << EMAC_LINK_PAUSE_ENCODING_S) -#define EMAC_LINK_PAUSE_ENCODING_V 0x00000003 -#define EMAC_LINK_PAUSE_ENCODING_S 7 -#define EMAC_LINK_HALF_DUPLEX (BIT(6)) -#define EMAC_LINK_HALF_DUPLEX_M (BIT(6)) -#define EMAC_LINK_HALF_DUPLEX_V 1 -#define EMAC_LINK_HALF_DUPLEX_S 6 -#define EMAC_LINK_FULL_DUPLEX (BIT(5)) -#define EMAC_LINK_FULL_DUPLEX_M (BIT(5)) -#define EMAC_LINK_FULL_DUPLEX_V 1 -#define EMAC_LINK_FULL_DUPLEX_S 5 - -#define EMAC_GMAC_AUTO_NEGOTIATION_EXPANSION_REG (REG_EMAC_BASE + 0x10D0) -#define EMAC_NEXT_PAGE_ABILITY (BIT(2)) -#define EMAC_NEXT_PAGE_ABILITY_M (BIT(2)) -#define EMAC_NEXT_PAGE_ABILITY_V 1 -#define EMAC_NEXT_PAGE_ABILITY_S 2 -#define EMAC_NEW_PAGE_RECEIVED (BIT(1)) -#define EMAC_NEW_PAGE_RECEIVED_M (BIT(1)) -#define EMAC_NEW_PAGE_RECEIVED_V 1 -#define EMAC_NEW_PAGE_RECEIVED_S 1 - -#define EMAC_GMAC_TBI_EXTENDED_STATUS_REG (REG_EMAC_BASE + 0x10D4) -#define EMAC_1000BASE_X_FULL_DUPLEX_CAPABLE (BIT(15)) -#define EMAC_1000BASE_X_FULL_DUPLEX_CAPABLE_M (BIT(15)) -#define EMAC_1000BASE_X_FULL_DUPLEX_CAPABLE_V 1 -#define EMAC_1000BASE_X_FULL_DUPLEX_CAPABLE_S 15 -#define EMAC_1000BASE_X_HALF_DUPLEX_CAPABLE (BIT(14)) -#define EMAC_1000BASE_X_HALF_DUPLEX_CAPABLE_M (BIT(14)) -#define EMAC_1000BASE_X_HALF_DUPLEX_CAPABLE_V 1 -#define EMAC_1000BASE_X_HALF_DUPLEX_CAPABLE_S 14 - -#define EMAC_GMAC_CONTROL_STATUS_REG (REG_EMAC_BASE + 0x10D8) -#define EMAC_SMIDRXS (BIT(16)) -#define EMAC_SMIDRXS_M (BIT(16)) -#define EMAC_SMIDRXS_V 1 -#define EMAC_SMIDRXS_S 16 -#define EMAC_FALSE_CARRIER_DETECTED (BIT(5)) -#define EMAC_FALSE_CARRIER_DETECTED_M (BIT(5)) -#define EMAC_FALSE_CARRIER_DETECTED_V 1 -#define EMAC_FALSE_CARRIER_DETECTED_S 5 -#define EMAC_JABBER_TIMEOUT (BIT(4)) -#define EMAC_JABBER_TIMEOUT_M (BIT(4)) -#define EMAC_JABBER_TIMEOUT_V 1 -#define EMAC_JABBER_TIMEOUT_S 4 -#define EMAC_LINK_STATUS (BIT(3)) -#define EMAC_LINK_STATUS_M (BIT(3)) -#define EMAC_LINK_STATUS_V 1 -#define EMAC_LINK_STATUS_S 3 -#define EMAC_LINK_SPEED 0x00000003 -#define EMAC_LINK_SPEED_M (EMAC_LINK_SPEED_V << EMAC_LINK_SPEED_S) -#define EMAC_LINK_SPEED_V 0x00000003 -#define EMAC_LINK_SPEED_S 1 -#define EMAC_LINK_MODE (BIT(0)) -#define EMAC_LINK_MODE_M (BIT(0)) -#define EMAC_LINK_MODE_V 1 -#define EMAC_LINK_MODE_S 0 - -#define EMAC_GMAC_WATCHDOG_TIMEOUT_REG (REG_EMAC_BASE + 0x10DC) -#define EMAC_PROGRAMMABLE_WATCHDOG_ENABLE (BIT(16)) -#define EMAC_PROGRAMMABLE_WATCHDOG_ENABLE_M (BIT(16)) -#define EMAC_PROGRAMMABLE_WATCHDOG_ENABLE_V 1 -#define EMAC_PROGRAMMABLE_WATCHDOG_ENABLE_S 16 -#define EMAC_WATCHDOG_TIMEOUT 0x00003FFF -#define EMAC_WATCHDOG_TIMEOUT_M (EMAC_WATCHDOG_TIMEOUT_V << EMAC_WATCHDOG_TIMEOUT_S) -#define EMAC_WATCHDOG_TIMEOUT_V 0x00003FFF -#define EMAC_WATCHDOG_TIMEOUT_S 0 - -#define EMAC_GMAC_GENERAL_PURPOSE_IO_REG (REG_EMAC_BASE + 0x10E0) -#define EMAC_GPI_TYPE 0x0000000F -#define EMAC_GPI_TYPE_M (EMAC_GPI_TYPE_V << EMAC_GPI_TYPE_S) -#define EMAC_GPI_TYPE_V 0x0000000F -#define EMAC_GPI_TYPE_S 24 -#define EMAC_GPI_INTERRUPT_ENABLE 0x0000000F -#define EMAC_GPI_INTERRUPT_ENABLE_M (EMAC_GPI_INTERRUPT_ENABLE_V << EMAC_GPI_INTERRUPT_ENABLE_S) -#define EMAC_GPI_INTERRUPT_ENABLE_V 0x0000000F -#define EMAC_GPI_INTERRUPT_ENABLE_S 16 -#define EMAC_GENERAL_PURPOSE_OUTPUT 0x0000000F -#define EMAC_GENERAL_PURPOSE_OUTPUT_M (EMAC_GENERAL_PURPOSE_OUTPUT_V << EMAC_GENERAL_PURPOSE_OUTPUT_S) -#define EMAC_GENERAL_PURPOSE_OUTPUT_V 0x0000000F -#define EMAC_GENERAL_PURPOSE_OUTPUT_S 8 -#define EMAC_GENERAL_PURPOSE_INPUT_STATUS 0x0000000F -#define EMAC_GENERAL_PURPOSE_INPUT_STATUS_M (EMAC_GENERAL_PURPOSE_INPUT_STATUS_V << EMAC_GENERAL_PURPOSE_INPUT_STATUS_S) -#define EMAC_GENERAL_PURPOSE_INPUT_STATUS_V 0x0000000F -#define EMAC_GENERAL_PURPOSE_INPUT_STATUS_S 0 - -#define EMAC_GMAC_LAYER3_LAYER4_CONTROL0_REG (REG_EMAC_BASE + 0x1400) -#define EMAC_LAYER4_DESTINATION_PORT_INVERSE_MATCH_ENABLE (BIT(21)) -#define EMAC_LAYER4_DESTINATION_PORT_INVERSE_MATCH_ENABLE_M (BIT(21)) -#define EMAC_LAYER4_DESTINATION_PORT_INVERSE_MATCH_ENABLE_V 1 -#define EMAC_LAYER4_DESTINATION_PORT_INVERSE_MATCH_ENABLE_S 21 -#define EMAC_LAYER4_DESTINATION_PORT_MATCH_ENABLE (BIT(20)) -#define EMAC_LAYER4_DESTINATION_PORT_MATCH_ENABLE_M (BIT(20)) -#define EMAC_LAYER4_DESTINATION_PORT_MATCH_ENABLE_V 1 -#define EMAC_LAYER4_DESTINATION_PORT_MATCH_ENABLE_S 20 -#define EMAC_LAYER4_SOURCE_PORT_INVERSE_MATCH_ENABLE (BIT(19)) -#define EMAC_LAYER4_SOURCE_PORT_INVERSE_MATCH_ENABLE_M (BIT(19)) -#define EMAC_LAYER4_SOURCE_PORT_INVERSE_MATCH_ENABLE_V 1 -#define EMAC_LAYER4_SOURCE_PORT_INVERSE_MATCH_ENABLE_S 19 -#define EMAC_LAYER4_SOURCE_PORT_MATCH_ENABLE (BIT(18)) -#define EMAC_LAYER4_SOURCE_PORT_MATCH_ENABLE_M (BIT(18)) -#define EMAC_LAYER4_SOURCE_PORT_MATCH_ENABLE_V 1 -#define EMAC_LAYER4_SOURCE_PORT_MATCH_ENABLE_S 18 -#define EMAC_LAYER4_PROTOCOL_ENABLE (BIT(16)) -#define EMAC_LAYER4_PROTOCOL_ENABLE_M (BIT(16)) -#define EMAC_LAYER4_PROTOCOL_ENABLE_V 1 -#define EMAC_LAYER4_PROTOCOL_ENABLE_S 16 -#define EMAC_LAYER3_IP_DA_HIGHER_BITS_MATCH 0x0000001F -#define EMAC_LAYER3_IP_DA_HIGHER_BITS_MATCH_M (EMAC_LAYER3_IP_DA_HIGHER_BITS_MATCH_V << EMAC_LAYER3_IP_DA_HIGHER_BITS_MATCH_S) -#define EMAC_LAYER3_IP_DA_HIGHER_BITS_MATCH_V 0x0000001F -#define EMAC_LAYER3_IP_DA_HIGHER_BITS_MATCH_S 11 -#define EMAC_LAYER3_IP_SA_HIGHER_BITS_MATCH 0x0000001F -#define EMAC_LAYER3_IP_SA_HIGHER_BITS_MATCH_M (EMAC_LAYER3_IP_SA_HIGHER_BITS_MATCH_V << EMAC_LAYER3_IP_SA_HIGHER_BITS_MATCH_S) -#define EMAC_LAYER3_IP_SA_HIGHER_BITS_MATCH_V 0x0000001F -#define EMAC_LAYER3_IP_SA_HIGHER_BITS_MATCH_S 6 -#define EMAC_LAYER3_IP_DA_INVERSE_MATCH_ENABLE (BIT(5)) -#define EMAC_LAYER3_IP_DA_INVERSE_MATCH_ENABLE_M (BIT(5)) -#define EMAC_LAYER3_IP_DA_INVERSE_MATCH_ENABLE_V 1 -#define EMAC_LAYER3_IP_DA_INVERSE_MATCH_ENABLE_S 5 -#define EMAC_LAYER3_IP_DA_MATCH_ENABLE (BIT(4)) -#define EMAC_LAYER3_IP_DA_MATCH_ENABLE_M (BIT(4)) -#define EMAC_LAYER3_IP_DA_MATCH_ENABLE_V 1 -#define EMAC_LAYER3_IP_DA_MATCH_ENABLE_S 4 -#define EMAC_LAYER3_IP_SA_INVERSE_MATCH_ENABLE (BIT(3)) -#define EMAC_LAYER3_IP_SA_INVERSE_MATCH_ENABLE_M (BIT(3)) -#define EMAC_LAYER3_IP_SA_INVERSE_MATCH_ENABLE_V 1 -#define EMAC_LAYER3_IP_SA_INVERSE_MATCH_ENABLE_S 3 -#define EMAC_LAYER3_IP_SA_MATCH_ENABLE (BIT(2)) -#define EMAC_LAYER3_IP_SA_MATCH_ENABLE_M (BIT(2)) -#define EMAC_LAYER3_IP_SA_MATCH_ENABLE_V 1 -#define EMAC_LAYER3_IP_SA_MATCH_ENABLE_S 2 -#define EMAC_LAYER3_PROTOCOL_ENABLE (BIT(0)) -#define EMAC_LAYER3_PROTOCOL_ENABLE_M (BIT(0)) -#define EMAC_LAYER3_PROTOCOL_ENABLE_V 1 -#define EMAC_LAYER3_PROTOCOL_ENABLE_S 0 - -#define EMAC_GMAC_LAYER4_ADDRESS0_REG (REG_EMAC_BASE + 0x1404) -#define EMAC_LAYER4_DESTINATION_PORT_NUMBER_FIELD 0x0000FFFF -#define EMAC_LAYER4_DESTINATION_PORT_NUMBER_FIELD_M (EMAC_LAYER4_DESTINATION_PORT_NUMBER_FIELD_V << EMAC_LAYER4_DESTINATION_PORT_NUMBER_FIELD_S) -#define EMAC_LAYER4_DESTINATION_PORT_NUMBER_FIELD_V 0x0000FFFF -#define EMAC_LAYER4_DESTINATION_PORT_NUMBER_FIELD_S 16 -#define EMAC_LAYER4_SOURCE_PORT_NUMBER_FIELD 0x0000FFFF -#define EMAC_LAYER4_SOURCE_PORT_NUMBER_FIELD_M (EMAC_LAYER4_SOURCE_PORT_NUMBER_FIELD_V << EMAC_LAYER4_SOURCE_PORT_NUMBER_FIELD_S) -#define EMAC_LAYER4_SOURCE_PORT_NUMBER_FIELD_V 0x0000FFFF -#define EMAC_LAYER4_SOURCE_PORT_NUMBER_FIELD_S 0 - -#define EMAC_GMAC_LAYER3_ADDRESS0_REG (REG_EMAC_BASE + 0x1410) -#define EMAC_LAYER3_ADDRESS0_FIELD 0xFFFFFFFF -#define EMAC_LAYER3_ADDRESS0_FIELD_M (EMAC_LAYER3_ADDRESS0_FIELD_V << EMAC_LAYER3_ADDRESS0_FIELD_S) -#define EMAC_LAYER3_ADDRESS0_FIELD_V 0xFFFFFFFF -#define EMAC_LAYER3_ADDRESS0_FIELD_S 0 - -#define EMAC_GMAC_LAYER3_ADDRESS1_REG (REG_EMAC_BASE + 0x1414) -#define EMAC_LAYER3_ADDRESS1_FIELD 0xFFFFFFFF -#define EMAC_LAYER3_ADDRESS1_FIELD_M (EMAC_LAYER3_ADDRESS1_FIELD_V << EMAC_LAYER3_ADDRESS1_FIELD_S) -#define EMAC_LAYER3_ADDRESS1_FIELD_V 0xFFFFFFFF -#define EMAC_LAYER3_ADDRESS1_FIELD_S 0 - -#define EMAC_GMAC_LAYER3_ADDRESS2_REG (REG_EMAC_BASE + 0x1418) -#define EMAC_LAYER3_ADDRESS2_FIELD 0xFFFFFFFF -#define EMAC_LAYER3_ADDRESS2_FIELD_M (EMAC_LAYER3_ADDRESS2_FIELD_V << EMAC_LAYER3_ADDRESS2_FIELD_S) -#define EMAC_LAYER3_ADDRESS2_FIELD_V 0xFFFFFFFF -#define EMAC_LAYER3_ADDRESS2_FIELD_S 0 - -#define EMAC_GMAC_LAYER3_ADDRESS3_REG (REG_EMAC_BASE + 0x141C) -#define EMAC_LAYER3_ADDRESS3_FIELD 0xFFFFFFFF -#define EMAC_LAYER3_ADDRESS3_FIELD_M (EMAC_LAYER3_ADDRESS3_FIELD_V << EMAC_LAYER3_ADDRESS3_FIELD_S) -#define EMAC_LAYER3_ADDRESS3_FIELD_V 0xFFFFFFFF -#define EMAC_LAYER3_ADDRESS3_FIELD_S 0 - -#define EMAC_GMAC_HASH_TABLE0_REG (REG_EMAC_BASE + 0x1500) -#define EMAC_FIRST32_BITS_HASH_TABLE 0xFFFFFFFF -#define EMAC_FIRST32_BITS_HASH_TABLE_M (EMAC_FIRST32_BITS_HASH_TABLE_V << EMAC_FIRST32_BITS_HASH_TABLE_S) -#define EMAC_FIRST32_BITS_HASH_TABLE_V 0xFFFFFFFF -#define EMAC_FIRST32_BITS_HASH_TABLE_S 0 - -#define EMAC_GMAC_VLAN_TAG_INCLUSION_REPLACEMENT_REG (REG_EMAC_BASE + 0x1584) -#define EMAC_VLAN_C_VLAN_S_VLAN (BIT(19)) -#define EMAC_VLAN_C_VLAN_S_VLAN_M (BIT(19)) -#define EMAC_VLAN_C_VLAN_S_VLAN_V 1 -#define EMAC_VLAN_C_VLAN_S_VLAN_S 19 -#define EMAC_VLAN_PRIORITY_CONTROL (BIT(18)) -#define EMAC_VLAN_PRIORITY_CONTROL_M (BIT(18)) -#define EMAC_VLAN_PRIORITY_CONTROL_V 1 -#define EMAC_VLAN_PRIORITY_CONTROL_S 18 -#define EMAC_VLAN_TAG_CONTROL_TRANSMIT_FRAMES 0x00000003 -#define EMAC_VLAN_TAG_CONTROL_TRANSMIT_FRAMES_M (EMAC_VLAN_TAG_CONTROL_TRANSMIT_FRAMES_V << EMAC_VLAN_TAG_CONTROL_TRANSMIT_FRAMES_S) -#define EMAC_VLAN_TAG_CONTROL_TRANSMIT_FRAMES_V 0x00000003 -#define EMAC_VLAN_TAG_CONTROL_TRANSMIT_FRAMES_S 16 -#define EMAC_VLAN_TAG_TRANSMIT_FRAMES 0x0000FFFF -#define EMAC_VLAN_TAG_TRANSMIT_FRAMES_M (EMAC_VLAN_TAG_TRANSMIT_FRAMES_V << EMAC_VLAN_TAG_TRANSMIT_FRAMES_S) -#define EMAC_VLAN_TAG_TRANSMIT_FRAMES_V 0x0000FFFF -#define EMAC_VLAN_TAG_TRANSMIT_FRAMES_S 0 - -#define EMAC_GMAC_VLAN_HASH_TABLE_REG (REG_EMAC_BASE + 0x1588) -#define EMAC_VLAN_HASH_TABLE 0x0000FFFF -#define EMAC_VLAN_HASH_TABLE_M (EMAC_VLAN_HASH_TABLE_V << EMAC_VLAN_HASH_TABLE_S) -#define EMAC_VLAN_HASH_TABLE_V 0x0000FFFF -#define EMAC_VLAN_HASH_TABLE_S 0 +#define EMAC_DMABUSMODE_REG (DR_REG_EMAC_BASE + 0x0000) +/* EMAC_DMAMIXEDBURST : R/W ;bitpos:[26] ;default: 1'h0 ; */ +/*description: When this bit is set high and the FIXED_BURST bit is low the + AHB master interface starts all bursts of a length more than 16 with INCR (undefined burst) whereas it reverts to fixed burst transfers (INCRx and SINGLE) for burst length of 16 and less.*/ +#define EMAC_DMAMIXEDBURST (BIT(26)) +#define EMAC_DMAMIXEDBURST_M (BIT(26)) +#define EMAC_DMAMIXEDBURST_V 0x1 +#define EMAC_DMAMIXEDBURST_S 26 +/* EMAC_DMAADDRALIBEA : R/W ;bitpos:[25] ;default: 1'h0 ; */ +/*description: When this bit is set high and the FIXED_BURST bit is 1 the AHB + interface generates all bursts aligned to the start address LS bits. If the FIXED_BURST bit is 0 the first burst (accessing the start address of data buffer) is not aligned but subsequent bursts are aligned to the address.*/ +#define EMAC_DMAADDRALIBEA (BIT(25)) +#define EMAC_DMAADDRALIBEA_M (BIT(25)) +#define EMAC_DMAADDRALIBEA_V 0x1 +#define EMAC_DMAADDRALIBEA_S 25 +/* EMAC_PBLX8_MODE : R/W ;bitpos:[24] ;default: 1'h0 ; */ +/*description: When set high this bit multiplies the programmed PBL value (Bits[22:17] + and Bits[13:8]) eight times. Therefore the DMA transfers the data in 8 16 32 64 128 and 256 beats depending on the PBL value.*/ +#define EMAC_PBLX8_MODE (BIT(24)) +#define EMAC_PBLX8_MODE_M (BIT(24)) +#define EMAC_PBLX8_MODE_V 0x1 +#define EMAC_PBLX8_MODE_S 24 +/* EMAC_USE_SEP_PBL : R/W ;bitpos:[23] ;default: 1'h0 ; */ +/*description: When set high this bit configures the Rx DMA to use the value + configured in Bits[22:17] as PBL. The PBL value in Bits[13:8] is applicable only to the Tx DMA operations. When reset to low the PBL value in Bits[13:8] is applicable for both DMA engines.*/ +#define EMAC_USE_SEP_PBL (BIT(23)) +#define EMAC_USE_SEP_PBL_M (BIT(23)) +#define EMAC_USE_SEP_PBL_V 0x1 +#define EMAC_USE_SEP_PBL_S 23 +/* EMAC_RX_DMA_PBL : R/W ;bitpos:[22:17] ;default: 6'h1 ; */ +/*description: This field indicates the maximum number of beats to be transferred + in one Rx DMA transaction. This is the maximum value that is used in a single block Read or Write.The Rx DMA always attempts to burst as specified in the RPBL(RX_DMA_PBL) bit each time it starts a burst transfer on the host bus. You can program RPBL with values of 1 2 4 8 16 and 32. Any other value results in undefined behavior. This field is valid and applicable only when USP(USE_SEP_PBL) is set high.*/ +#define EMAC_RX_DMA_PBL 0x0000003F +#define EMAC_RX_DMA_PBL_M ((EMAC_RX_DMA_PBL_V)<<(EMAC_RX_DMA_PBL_S)) +#define EMAC_RX_DMA_PBL_V 0x3F +#define EMAC_RX_DMA_PBL_S 17 +/* EMAC_FIXED_BURST : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: This bit controls whether the AHB master interface performs fixed + burst transfers or not. When set the AHB interface uses only SINGLE INCR4 INCR8 or INCR16 during start of the normal burst transfers. When reset the AHB interface uses SINGLE and INCR burst transfer Operations.*/ +#define EMAC_FIXED_BURST (BIT(16)) +#define EMAC_FIXED_BURST_M (BIT(16)) +#define EMAC_FIXED_BURST_V 0x1 +#define EMAC_FIXED_BURST_S 16 +/* EMAC_PRI_RATIO : R/W ;bitpos:[15:14] ;default: 2'h0 ; */ +/*description: These bits control the priority ratio in the weighted round-robin + arbitration between the Rx DMA and Tx DMA. These bits are valid only when Bit 1 (DA) is reset. The priority ratio Rx:Tx represented by each bit: 2'b00 -- 1: 1 2'b01 -- 2: 0 2'b10 -- 3: 1 2'b11 -- 4: 1*/ +#define EMAC_PRI_RATIO 0x00000003 +#define EMAC_PRI_RATIO_M ((EMAC_PRI_RATIO_V)<<(EMAC_PRI_RATIO_S)) +#define EMAC_PRI_RATIO_V 0x3 +#define EMAC_PRI_RATIO_S 14 +/* EMAC_PROG_BURST_LEN : R/W ;bitpos:[13:8] ;default: 6'h1 ; */ +/*description: These bits indicate the maximum number of beats to be transferred + in one DMA transaction. If the number of beats to be transferred is more than 32 then perform the following steps: 1. Set the PBLx8 mode 2. Set the PBL(PROG_BURST_LEN).*/ +#define EMAC_PROG_BURST_LEN 0x0000003F +#define EMAC_PROG_BURST_LEN_M ((EMAC_PROG_BURST_LEN_V)<<(EMAC_PROG_BURST_LEN_S)) +#define EMAC_PROG_BURST_LEN_V 0x3F +#define EMAC_PROG_BURST_LEN_S 8 +/* EMAC_ALT_DESC_SIZE : R/W ;bitpos:[7] ;default: 1'h0 ; */ +/*description: When set the size of the alternate descriptor increases to 32 bytes.*/ +#define EMAC_ALT_DESC_SIZE (BIT(7)) +#define EMAC_ALT_DESC_SIZE_M (BIT(7)) +#define EMAC_ALT_DESC_SIZE_V 0x1 +#define EMAC_ALT_DESC_SIZE_S 7 +/* EMAC_DESC_SKIP_LEN : R/W ;bitpos:[6:2] ;default: 5'h0 ; */ +/*description: This bit specifies the number of Word to skip between two unchained + descriptors.The address skipping starts from the end of current descriptor to the start of next descriptor. When the DSL(DESC_SKIP_LEN) value is equal to zero the descriptor table is taken as contiguous by the DMA in Ring mode.*/ +#define EMAC_DESC_SKIP_LEN 0x0000001F +#define EMAC_DESC_SKIP_LEN_M ((EMAC_DESC_SKIP_LEN_V)<<(EMAC_DESC_SKIP_LEN_S)) +#define EMAC_DESC_SKIP_LEN_V 0x1F +#define EMAC_DESC_SKIP_LEN_S 2 +/* EMAC_DMA_ARB_SCH : R/W ;bitpos:[1] ;default: 1'h0 ; */ +/*description: This bit specifies the arbitration scheme between the transmit + and receive paths.1'b0: weighted round-robin with RX:TX or TX:RX priority specified in PR (bit[15:14]). 1'b1 Fixed priority (Rx priority to Tx).*/ +#define EMAC_DMA_ARB_SCH (BIT(1)) +#define EMAC_DMA_ARB_SCH_M (BIT(1)) +#define EMAC_DMA_ARB_SCH_V 0x1 +#define EMAC_DMA_ARB_SCH_S 1 +/* EMAC_SW_RST : R_WS_SC ;bitpos:[0] ;default: 1'h1 ; */ +/*description: When this bit is set the MAC DMA Controller resets the logic + and all internal registers of the MAC. It is cleared automatically after the reset operation is complete in all of the ETH_MAC clock domains. Before reprogramming any register of the ETH_MAC you should read a zero (0) value in this bit.*/ +#define EMAC_SW_RST (BIT(0)) +#define EMAC_SW_RST_M (BIT(0)) +#define EMAC_SW_RST_V 0x1 +#define EMAC_SW_RST_S 0 + +#define EMAC_DMATXPOLLDEMAND_REG (DR_REG_EMAC_BASE + 0x0004) +/* EMAC_TRANS_POLL_DEMAND : RO_WT ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: When these bits are written with any value the DMA reads the + current descriptor to which the Register (Current Host Transmit Descriptor Register) is pointing. If that descriptor is not available (owned by the Host) the transmission returns to the suspend state and Bit[2] (TU) of Status Register is asserted. If the descriptor is available the transmission resumes.*/ +#define EMAC_TRANS_POLL_DEMAND 0xFFFFFFFF +#define EMAC_TRANS_POLL_DEMAND_M ((EMAC_TRANS_POLL_DEMAND_V)<<(EMAC_TRANS_POLL_DEMAND_S)) +#define EMAC_TRANS_POLL_DEMAND_V 0xFFFFFFFF +#define EMAC_TRANS_POLL_DEMAND_S 0 + +#define EMAC_DMARXPOLLDEMAND_REG (DR_REG_EMAC_BASE + 0x0008) +/* EMAC_RECV_POLL_DEMAND : RO_WT ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: When these bits are written with any value the DMA reads the + current descriptor to which the Current Host Receive Descriptor Register is pointing. If that descriptor is not available (owned by the Host) the reception returns to the Suspended state and Bit[7] (RU) of Status Register is asserted. If the descriptor is available the Rx DMA returns to the active state.*/ +#define EMAC_RECV_POLL_DEMAND 0xFFFFFFFF +#define EMAC_RECV_POLL_DEMAND_M ((EMAC_RECV_POLL_DEMAND_V)<<(EMAC_RECV_POLL_DEMAND_S)) +#define EMAC_RECV_POLL_DEMAND_V 0xFFFFFFFF +#define EMAC_RECV_POLL_DEMAND_S 0 + +#define EMAC_DMARXBASEADDR_REG (DR_REG_EMAC_BASE + 0x000C) +/* EMAC_START_RECV_LIST : R/W ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: This field contains the base address of the first descriptor + in the Receive Descriptor list. The LSB Bits[1:0] are ignored and internally taken as all-zero by the DMA. Therefore these LSB bits are read-only.*/ +#define EMAC_START_RECV_LIST 0xFFFFFFFF +#define EMAC_START_RECV_LIST_M ((EMAC_START_RECV_LIST_V)<<(EMAC_START_RECV_LIST_S)) +#define EMAC_START_RECV_LIST_V 0xFFFFFFFF +#define EMAC_START_RECV_LIST_S 0 + +#define EMAC_DMATXBASEADDR_REG (DR_REG_EMAC_BASE + 0x0010) +/* EMAC_START_TRANS_LIST : R/W ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: This field contains the base address of the first descriptor + in the Transmit Descriptor list. The LSB Bits[1:0] are ignored and are internally taken as all-zero by the DMA.Therefore these LSB bits are read-only.*/ +#define EMAC_START_TRANS_LIST 0xFFFFFFFF +#define EMAC_START_TRANS_LIST_M ((EMAC_START_TRANS_LIST_V)<<(EMAC_START_TRANS_LIST_S)) +#define EMAC_START_TRANS_LIST_V 0xFFFFFFFF +#define EMAC_START_TRANS_LIST_S 0 + +#define EMAC_DMASTATUS_REG (DR_REG_EMAC_BASE + 0x0014) +/* EMAC_TS_TRI_INT : RO ;bitpos:[29] ;default: 1'h0 ; */ +/*description: This bit indicates an interrupt event in the Timestamp Generator + block of the ETH_MAC.The software must read the corresponding registers in the ETH_MAC to get the exact cause of the interrupt and clear its source to reset this bit to 1'b0.*/ +#define EMAC_TS_TRI_INT (BIT(29)) +#define EMAC_TS_TRI_INT_M (BIT(29)) +#define EMAC_TS_TRI_INT_V 0x1 +#define EMAC_TS_TRI_INT_S 29 +/* EMAC_PMT_INT : RO ;bitpos:[28] ;default: 1'h0 ; */ +/*description: This bit indicates an interrupt event in the PMT module of the + ETH_MAC. The software must read the PMT Control and Status Register in the MAC to get the exact cause of interrupt and clear its source to reset this bit to 1'b0.*/ +#define EMAC_PMT_INT (BIT(28)) +#define EMAC_PMT_INT_M (BIT(28)) +#define EMAC_PMT_INT_V 0x1 +#define EMAC_PMT_INT_S 28 +/* EMAC_ERROR_BITS : RO ;bitpos:[25:23] ;default: 3'h0 ; */ +/*description: This field indicates the type of error that caused a Bus Error + for example error response on the AHB interface. This field is valid only when Bit[13] (FBI) is set. This field does not generate an interrupt. 3'b000: Error during Rx DMA Write Data Transfer. 3'b011: Error during Tx DMA Read Data Transfer. 3'b100: Error during Rx DMA Descriptor Write Access. 3'b101: Error during Tx DMA Descriptor Write Access. 3'b110: Error during Rx DMA Descriptor Read Access. 3'b111: Error during Tx DMA Descriptor Read Access.*/ +#define EMAC_ERROR_BITS 0x00000007 +#define EMAC_ERROR_BITS_M ((EMAC_ERROR_BITS_V)<<(EMAC_ERROR_BITS_S)) +#define EMAC_ERROR_BITS_V 0x7 +#define EMAC_ERROR_BITS_S 23 +/* EMAC_TRANS_PROC_STATE : RO ;bitpos:[22:20] ;default: 3'h0 ; */ +/*description: This field indicates the Transmit DMA FSM state. This field does + not generate an interrupt. 3'b000: Stopped. Reset or Stop Transmit Command issued. 3'b001: Running. Fetching Transmit Transfer Descriptor. 3'b010: Reserved for future use. 3'b011: Running. Waiting for TX packets. 3'b100: Suspended. Receive Descriptor Unavailable. 3'b101: Running. Closing Transmit Descriptor. 3'b110: TIME_STAMP write state. 3'b111: Running. Transferring the TX packets data from transmit buffer to host memory.*/ +#define EMAC_TRANS_PROC_STATE 0x00000007 +#define EMAC_TRANS_PROC_STATE_M ((EMAC_TRANS_PROC_STATE_V)<<(EMAC_TRANS_PROC_STATE_S)) +#define EMAC_TRANS_PROC_STATE_V 0x7 +#define EMAC_TRANS_PROC_STATE_S 20 +/* EMAC_RECV_PROC_STATE : RO ;bitpos:[19:17] ;default: 3'h0 ; */ +/*description: This field indicates the Receive DMA FSM state. This field does + not generate an interrupt. 3'b000: Stopped. Reset or Stop Receive Command issued. 3'b001: Running. Fetching Receive Transfer Descriptor. 3'b010: Reserved for future use. 3'b011: Running. Waiting for RX packets. 3'b100: Suspended. Receive Descriptor Unavailable. 3'b101: Running. Closing Receive Descriptor. 3'b110: TIME_STAMP write state. 3'b111: Running. Transferring the TX packets data from receive buffer to host memory.*/ +#define EMAC_RECV_PROC_STATE 0x00000007 +#define EMAC_RECV_PROC_STATE_M ((EMAC_RECV_PROC_STATE_V)<<(EMAC_RECV_PROC_STATE_S)) +#define EMAC_RECV_PROC_STATE_V 0x7 +#define EMAC_RECV_PROC_STATE_S 17 +/* EMAC_NORM_INT_SUMM : R_SS_WC ;bitpos:[16] ;default: 1'h0 ; */ +/*description: Normal Interrupt Summary bit value is the logical OR of the following + bits when the corresponding interrupt bits are enabled in Interrupt Enable Register: Bit[0]: Transmit Interrupt. Bit[2]: Transmit Buffer Unavailable. Bit[6]: Receive Interrupt. Bit[14]: Early Receive Interrupt. Only unmasked bits affect the Normal Interrupt Summary bit.This is a sticky bit and must be cleared (by writing 1 to this bit) each time a corresponding bit which causes NIS to be set is cleared.*/ +#define EMAC_NORM_INT_SUMM (BIT(16)) +#define EMAC_NORM_INT_SUMM_M (BIT(16)) +#define EMAC_NORM_INT_SUMM_V 0x1 +#define EMAC_NORM_INT_SUMM_S 16 +/* EMAC_ABN_INT_SUMM : R_SS_WC ;bitpos:[15] ;default: 1'h0 ; */ +/*description: Abnormal Interrupt Summary bit value is the logical OR of the + following when the corresponding interrupt bits are enabled in Interrupt Enable Register: Bit[1]: Transmit Process Stopped. Bit[3]: Transmit Jabber Timeout. Bit[4]: Receive FIFO Overflow. Bit[5]: Transmit Underflow. Bit[7]: Receive Buffer Unavailable. Bit[8]: Receive Process Stopped. Bit[9]: Receive Watchdog Timeout. Bit[10]: Early Transmit Interrupt. Bit[13]: Fatal Bus Error. Only unmasked bits affect the Abnormal Interrupt Summary bit. This is a sticky bit and must be cleared (by writing 1 to this bit) each time a corresponding bit which causes AIS to be set is cleared.*/ +#define EMAC_ABN_INT_SUMM (BIT(15)) +#define EMAC_ABN_INT_SUMM_M (BIT(15)) +#define EMAC_ABN_INT_SUMM_V 0x1 +#define EMAC_ABN_INT_SUMM_S 15 +/* EMAC_EARLY_RECV_INT : R_SS_WC ;bitpos:[14] ;default: 1'h0 ; */ +/*description: This bit indicates that the DMA filled the first data buffer + of the packet. This bit is cleared when the software writes 1 to this bit or when Bit[6] (RI) of this register is set (whichever occurs earlier).*/ +#define EMAC_EARLY_RECV_INT (BIT(14)) +#define EMAC_EARLY_RECV_INT_M (BIT(14)) +#define EMAC_EARLY_RECV_INT_V 0x1 +#define EMAC_EARLY_RECV_INT_S 14 +/* EMAC_FATAL_BUS_ERR_INT : R_SS_WC ;bitpos:[13] ;default: 1'h0 ; */ +/*description: This bit indicates that a bus error occurred as described in + Bits [25:23]. When this bit is set the corresponding DMA engine disables all of its bus accesses.*/ +#define EMAC_FATAL_BUS_ERR_INT (BIT(13)) +#define EMAC_FATAL_BUS_ERR_INT_M (BIT(13)) +#define EMAC_FATAL_BUS_ERR_INT_V 0x1 +#define EMAC_FATAL_BUS_ERR_INT_S 13 +/* EMAC_EARLY_TRANS_INT : R_SS_WC ;bitpos:[10] ;default: 1'h0 ; */ +/*description: This bit indicates that the frame to be transmitted is fully + transferred to the MTL Transmit FIFO.*/ +#define EMAC_EARLY_TRANS_INT (BIT(10)) +#define EMAC_EARLY_TRANS_INT_M (BIT(10)) +#define EMAC_EARLY_TRANS_INT_V 0x1 +#define EMAC_EARLY_TRANS_INT_S 10 +/* EMAC_RECV_WDT_TO : R_SS_WC ;bitpos:[9] ;default: 1'h0 ; */ +/*description: When set this bit indicates that the Receive Watchdog Timer + expired while receiving the current frame and the current frame is truncated after the watchdog timeout.*/ +#define EMAC_RECV_WDT_TO (BIT(9)) +#define EMAC_RECV_WDT_TO_M (BIT(9)) +#define EMAC_RECV_WDT_TO_V 0x1 +#define EMAC_RECV_WDT_TO_S 9 +/* EMAC_RECV_PROC_STOP : R_SS_WC ;bitpos:[8] ;default: 1'h0 ; */ +/*description: This bit is asserted when the Receive Process enters the Stopped state.*/ +#define EMAC_RECV_PROC_STOP (BIT(8)) +#define EMAC_RECV_PROC_STOP_M (BIT(8)) +#define EMAC_RECV_PROC_STOP_V 0x1 +#define EMAC_RECV_PROC_STOP_S 8 +/* EMAC_RECV_BUF_UNAVAIL : R_SS_WC ;bitpos:[7] ;default: 1'h0 ; */ +/*description: This bit indicates that the host owns the Next Descriptor in + the Receive List and the DMA cannot acquire it. The Receive Process is suspended. To resume processing Receive descriptors the host should change the ownership of the descriptor and issue a Receive Poll Demand command. If no Receive Poll Demand is issued the Receive Process resumes when the next recognized incoming frame is received. This bit is set only when the previous Receive Descriptor is owned by the DMA.*/ +#define EMAC_RECV_BUF_UNAVAIL (BIT(7)) +#define EMAC_RECV_BUF_UNAVAIL_M (BIT(7)) +#define EMAC_RECV_BUF_UNAVAIL_V 0x1 +#define EMAC_RECV_BUF_UNAVAIL_S 7 +/* EMAC_RECV_INT : R_SS_WC ;bitpos:[6] ;default: 1'h0 ; */ +/*description: This bit indicates that the frame reception is complete. When + reception is complete the Bit[31] of RDES1 (Disable Interrupt on Completion) is reset in the last Descriptor and the specific frame status information is updated in the descriptor. The reception remains in the Running state.*/ +#define EMAC_RECV_INT (BIT(6)) +#define EMAC_RECV_INT_M (BIT(6)) +#define EMAC_RECV_INT_V 0x1 +#define EMAC_RECV_INT_S 6 +/* EMAC_TRANS_UNDFLOW : R_SS_WC ;bitpos:[5] ;default: 1'h0 ; */ +/*description: This bit indicates that the Transmit Buffer had an Underflow + during frame transmission. Transmission is suspended and an Underflow Error TDES0[1] is set.*/ +#define EMAC_TRANS_UNDFLOW (BIT(5)) +#define EMAC_TRANS_UNDFLOW_M (BIT(5)) +#define EMAC_TRANS_UNDFLOW_V 0x1 +#define EMAC_TRANS_UNDFLOW_S 5 +/* EMAC_RECV_OVFLOW : R_SS_WC ;bitpos:[4] ;default: 1'h0 ; */ +/*description: This bit indicates that the Receive Buffer had an Overflow during + frame reception. If the partial frame is transferred to the application the overflow status is set in RDES0[11].*/ +#define EMAC_RECV_OVFLOW (BIT(4)) +#define EMAC_RECV_OVFLOW_M (BIT(4)) +#define EMAC_RECV_OVFLOW_V 0x1 +#define EMAC_RECV_OVFLOW_S 4 +/* EMAC_TRANS_JABBER_TO : R_SS_WC ;bitpos:[3] ;default: 1'h0 ; */ +/*description: This bit indicates that the Transmit Jabber Timer expired which + happens when the frame size exceeds 2 048 (10 240 bytes when the Jumbo frame is enabled). When the Jabber Timeout occurs the transmission process is aborted and placed in the Stopped state. This causes the Transmit Jabber Timeout TDES0[14] flag to assert.*/ +#define EMAC_TRANS_JABBER_TO (BIT(3)) +#define EMAC_TRANS_JABBER_TO_M (BIT(3)) +#define EMAC_TRANS_JABBER_TO_V 0x1 +#define EMAC_TRANS_JABBER_TO_S 3 +/* EMAC_TRANS_BUF_UNAVAIL : R_SS_WC ;bitpos:[2] ;default: 1'h0 ; */ +/*description: This bit indicates that the host owns the Next Descriptor in + the Transmit List and the DMA cannot acquire it. Transmission is suspended. Bits[22:20] explain the Transmit Process state transitions. To resume processing Transmit descriptors the host should change the ownership of the descriptor by setting TDES0[31] and then issue a Transmit Poll Demand Command.*/ +#define EMAC_TRANS_BUF_UNAVAIL (BIT(2)) +#define EMAC_TRANS_BUF_UNAVAIL_M (BIT(2)) +#define EMAC_TRANS_BUF_UNAVAIL_V 0x1 +#define EMAC_TRANS_BUF_UNAVAIL_S 2 +/* EMAC_TRANS_PROC_STOP : R_SS_WC ;bitpos:[1] ;default: 1'h0 ; */ +/*description: This bit is set when the transmission is stopped.*/ +#define EMAC_TRANS_PROC_STOP (BIT(1)) +#define EMAC_TRANS_PROC_STOP_M (BIT(1)) +#define EMAC_TRANS_PROC_STOP_V 0x1 +#define EMAC_TRANS_PROC_STOP_S 1 +/* EMAC_TRANS_INT : R_SS_WC ;bitpos:[0] ;default: 1'h0 ; */ +/*description: This bit indicates that the frame transmission is complete. When + transmission is complete Bit[31] (OWN) of TDES0 is reset and the specific frame status information is updated in the Descriptor.*/ +#define EMAC_TRANS_INT (BIT(0)) +#define EMAC_TRANS_INT_M (BIT(0)) +#define EMAC_TRANS_INT_V 0x1 +#define EMAC_TRANS_INT_S 0 + +#define EMAC_DMAOPERATION_MODE_REG (DR_REG_EMAC_BASE + 0x0018) +/* EMAC_DIS_DROP_TCPIP_ERR_FRAM : R/W ;bitpos:[26] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC does not drop the frames which + only have errors detected by the Receive Checksum engine.When this bit is reset all error frames are dropped if the Fwd_Err_Frame bit is reset.*/ +#define EMAC_DIS_DROP_TCPIP_ERR_FRAM (BIT(26)) +#define EMAC_DIS_DROP_TCPIP_ERR_FRAM_M (BIT(26)) +#define EMAC_DIS_DROP_TCPIP_ERR_FRAM_V 0x1 +#define EMAC_DIS_DROP_TCPIP_ERR_FRAM_S 26 +/* EMAC_RX_STORE_FORWARD : R/W ;bitpos:[25] ;default: 1'h0 ; */ +/*description: When this bit is set the MTL reads a frame from the Rx FIFO + only after the complete frame has been written to it.*/ +#define EMAC_RX_STORE_FORWARD (BIT(25)) +#define EMAC_RX_STORE_FORWARD_M (BIT(25)) +#define EMAC_RX_STORE_FORWARD_V 0x1 +#define EMAC_RX_STORE_FORWARD_S 25 +/* EMAC_DIS_FLUSH_RECV_FRAMES : R/W ;bitpos:[24] ;default: 1'h0 ; */ +/*description: When this bit is set the Rx DMA does not flush any frames because + of the unavailability of receive descriptors or buffers.*/ +#define EMAC_DIS_FLUSH_RECV_FRAMES (BIT(24)) +#define EMAC_DIS_FLUSH_RECV_FRAMES_M (BIT(24)) +#define EMAC_DIS_FLUSH_RECV_FRAMES_V 0x1 +#define EMAC_DIS_FLUSH_RECV_FRAMES_S 24 +/* EMAC_TX_STR_FWD : R/W ;bitpos:[21] ;default: 1'h0 ; */ +/*description: When this bit is set transmission starts when a full frame resides + in the MTL Transmit FIFO. When this bit is set the Tx_Thresh_Ctrl values specified in Tx_Thresh_Ctrl are ignored.*/ +#define EMAC_TX_STR_FWD (BIT(21)) +#define EMAC_TX_STR_FWD_M (BIT(21)) +#define EMAC_TX_STR_FWD_V 0x1 +#define EMAC_TX_STR_FWD_S 21 +/* EMAC_FLUSH_TX_FIFO : R_WS_SC ;bitpos:[20] ;default: 1'h0 ; */ +/*description: When this bit is set the transmit FIFO controller logic is reset + to its default values and thus all data in the Tx FIFO is lost or flushed. This bit is cleared internally when the flushing operation is complete.*/ +#define EMAC_FLUSH_TX_FIFO (BIT(20)) +#define EMAC_FLUSH_TX_FIFO_M (BIT(20)) +#define EMAC_FLUSH_TX_FIFO_V 0x1 +#define EMAC_FLUSH_TX_FIFO_S 20 +/* EMAC_TX_THRESH_CTRL : R/W ;bitpos:[16:14] ;default: 3'h0 ; */ +/*description: These bits control the threshold level of the MTL Transmit FIFO. + Transmission starts when the frame size within the MTL Transmit FIFO is larger than the threshold. In addition full frames with a length less than the threshold are also transmitted. These bits are used only when Tx_Str_fwd is reset. 3'b000: 64 3'b001: 128 3'b010: 192 3'b011: 256 3'b100: 40 3'b101: 32 3'b110: 24 3'b111: 16 .*/ +#define EMAC_TX_THRESH_CTRL 0x00000007 +#define EMAC_TX_THRESH_CTRL_M ((EMAC_TX_THRESH_CTRL_V)<<(EMAC_TX_THRESH_CTRL_S)) +#define EMAC_TX_THRESH_CTRL_V 0x7 +#define EMAC_TX_THRESH_CTRL_S 14 +/* EMAC_START_STOP_TRANSMISSION_COMMAND : R/W ;bitpos:[13] ;default: 1'h0 ; */ +/*description: When this bit is set transmission is placed in the Running state + and the DMA checks the Transmit List at the current position for a frame to be transmitted.When this bit is reset the transmission process is placed in the Stopped state after completing the transmission of the current frame.*/ +#define EMAC_START_STOP_TRANSMISSION_COMMAND (BIT(13)) +#define EMAC_START_STOP_TRANSMISSION_COMMAND_M (BIT(13)) +#define EMAC_START_STOP_TRANSMISSION_COMMAND_V 0x1 +#define EMAC_START_STOP_TRANSMISSION_COMMAND_S 13 +/* EMAC_FWD_ERR_FRAME : R/W ;bitpos:[7] ;default: 1'h0 ; */ +/*description: When this bit is reset the Rx FIFO drops frames with error status + (CRC error collision error giant frame watchdog timeout or overflow).*/ +#define EMAC_FWD_ERR_FRAME (BIT(7)) +#define EMAC_FWD_ERR_FRAME_M (BIT(7)) +#define EMAC_FWD_ERR_FRAME_V 0x1 +#define EMAC_FWD_ERR_FRAME_S 7 +/* EMAC_FWD_UNDER_GF : R/W ;bitpos:[6] ;default: 1'h0 ; */ +/*description: When set the Rx FIFO forwards Undersized frames (that is frames + with no Error and length less than 64 bytes) including pad-bytes and CRC.*/ +#define EMAC_FWD_UNDER_GF (BIT(6)) +#define EMAC_FWD_UNDER_GF_M (BIT(6)) +#define EMAC_FWD_UNDER_GF_V 0x1 +#define EMAC_FWD_UNDER_GF_S 6 +/* EMAC_DROP_GFRM : R/W ;bitpos:[5] ;default: 1'h0 ; */ +/*description: When set the MAC drops the received giant frames in the Rx FIFO + that is frames that are larger than the computed giant frame limit.*/ +#define EMAC_DROP_GFRM (BIT(5)) +#define EMAC_DROP_GFRM_M (BIT(5)) +#define EMAC_DROP_GFRM_V 0x1 +#define EMAC_DROP_GFRM_S 5 +/* EMAC_RX_THRESH_CTRL : R/W ;bitpos:[4:3] ;default: 2'h0 ; */ +/*description: These two bits control the threshold level of the MTL Receive + FIFO. Transfer (request) to DMA starts when the frame size within the MTL Receive FIFO is larger than the threshold. 2'b00: 64, 2'b01: 32, 2'b10: 96, 2'b11: 128 .*/ +#define EMAC_RX_THRESH_CTRL 0x00000003 +#define EMAC_RX_THRESH_CTRL_M ((EMAC_RX_THRESH_CTRL_V)<<(EMAC_RX_THRESH_CTRL_S)) +#define EMAC_RX_THRESH_CTRL_V 0x3 +#define EMAC_RX_THRESH_CTRL_S 3 +/* EMAC_OPT_SECOND_FRAME : R/W ;bitpos:[2] ;default: 1'h0 ; */ +/*description: When this bit is set it instructs the DMA to process the second + frame of the Transmit data even before the status for the first frame is obtained.*/ +#define EMAC_OPT_SECOND_FRAME (BIT(2)) +#define EMAC_OPT_SECOND_FRAME_M (BIT(2)) +#define EMAC_OPT_SECOND_FRAME_V 0x1 +#define EMAC_OPT_SECOND_FRAME_S 2 +/* EMAC_START_STOP_RX : R/W ;bitpos:[1] ;default: 1'h0 ; */ +/*description: When this bit is set the Receive process is placed in the Running + state. The DMA attempts to acquire the descriptor from the Receive list and processes the incoming frames.When this bit is cleared the Rx DMA operation is stopped after the transfer of the current frame.*/ +#define EMAC_START_STOP_RX (BIT(1)) +#define EMAC_START_STOP_RX_M (BIT(1)) +#define EMAC_START_STOP_RX_V 0x1 +#define EMAC_START_STOP_RX_S 1 + +#define EMAC_DMAIN_EN_REG (DR_REG_EMAC_BASE + 0x001C) +/* EMAC_DMAIN_NISE : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: When this bit is set normal interrupt summary is enabled. When + this bit is reset normal interrupt summary is disabled. This bit enables the following interrupts in Status Register: Bit[0]: Transmit Interrupt. Bit[2]: Transmit Buffer Unavailable. Bit[6]: Receive Interrupt. Bit[14]: Early Receive Interrupt.*/ +#define EMAC_DMAIN_NISE (BIT(16)) +#define EMAC_DMAIN_NISE_M (BIT(16)) +#define EMAC_DMAIN_NISE_V 0x1 +#define EMAC_DMAIN_NISE_S 16 +/* EMAC_DMAIN_AISE : R/W ;bitpos:[15] ;default: 1'h0 ; */ +/*description: When this bit is set abnormal interrupt summary is enabled. + When this bit is reset the abnormal interrupt summary is disabled. This bit enables the following interrupts in Status Register: Bit[1]: Transmit Process Stopped. Bit[3]: Transmit Jabber Timeout. Bit[4]: Receive Overflow. Bit[5]: Transmit Underflow. Bit[7]: Receive Buffer Unavailable. Bit[8]: Receive Process Stopped. Bit[9]: Receive Watchdog Timeout. Bit[10]: Early Transmit Interrupt. Bit[13]: Fatal Bus Error.*/ +#define EMAC_DMAIN_AISE (BIT(15)) +#define EMAC_DMAIN_AISE_M (BIT(15)) +#define EMAC_DMAIN_AISE_V 0x1 +#define EMAC_DMAIN_AISE_S 15 +/* EMAC_DMAIN_ERIE : R/W ;bitpos:[14] ;default: 1'h0 ; */ +/*description: When this bit is set with Normal Interrupt Summary Enable (Bit[16]) + the Early Receive Interrupt is enabled. When this bit is reset the Early Receive Interrupt is disabled.*/ +#define EMAC_DMAIN_ERIE (BIT(14)) +#define EMAC_DMAIN_ERIE_M (BIT(14)) +#define EMAC_DMAIN_ERIE_V 0x1 +#define EMAC_DMAIN_ERIE_S 14 +/* EMAC_DMAIN_FBEE : R/W ;bitpos:[13] ;default: 1'h0 ; */ +/*description: When this bit is set with Abnormal Interrupt Summary Enable (Bit[15]) + the Fatal Bus Error Interrupt is enabled. When this bit is reset the Fatal Bus Error Enable Interrupt is disabled.*/ +#define EMAC_DMAIN_FBEE (BIT(13)) +#define EMAC_DMAIN_FBEE_M (BIT(13)) +#define EMAC_DMAIN_FBEE_V 0x1 +#define EMAC_DMAIN_FBEE_S 13 +/* EMAC_DMAIN_ETIE : R/W ;bitpos:[10] ;default: 1'h0 ; */ +/*description: When this bit is set with an Abnormal Interrupt Summary Enable + (Bit[15]) the Early Transmit Interrupt is enabled. When this bit is reset the Early Transmit Interrupt is disabled.*/ +#define EMAC_DMAIN_ETIE (BIT(10)) +#define EMAC_DMAIN_ETIE_M (BIT(10)) +#define EMAC_DMAIN_ETIE_V 0x1 +#define EMAC_DMAIN_ETIE_S 10 +/* EMAC_DMAIN_RWTE : R/W ;bitpos:[9] ;default: 1'h0 ; */ +/*description: When this bit is set with Abnormal Interrupt Summary Enable (Bit[15]) + the Receive Watchdog Timeout Interrupt is enabled. When this bit is reset the Receive Watchdog Timeout Interrupt is disabled.*/ +#define EMAC_DMAIN_RWTE (BIT(9)) +#define EMAC_DMAIN_RWTE_M (BIT(9)) +#define EMAC_DMAIN_RWTE_V 0x1 +#define EMAC_DMAIN_RWTE_S 9 +/* EMAC_DMAIN_RSE : R/W ;bitpos:[8] ;default: 1'h0 ; */ +/*description: When this bit is set with Abnormal Interrupt Summary Enable (Bit[15]) + the Receive Stopped Interrupt is enabled. When this bit is reset the Receive Stopped Interrupt is disabled.*/ +#define EMAC_DMAIN_RSE (BIT(8)) +#define EMAC_DMAIN_RSE_M (BIT(8)) +#define EMAC_DMAIN_RSE_V 0x1 +#define EMAC_DMAIN_RSE_S 8 +/* EMAC_DMAIN_RBUE : R/W ;bitpos:[7] ;default: 1'h0 ; */ +/*description: When this bit is set with Abnormal Interrupt Summary Enable (Bit[15]) + the Receive Buffer Unavailable Interrupt is enabled. When this bit is reset the Receive Buffer Unavailable Interrupt is disabled.*/ +#define EMAC_DMAIN_RBUE (BIT(7)) +#define EMAC_DMAIN_RBUE_M (BIT(7)) +#define EMAC_DMAIN_RBUE_V 0x1 +#define EMAC_DMAIN_RBUE_S 7 +/* EMAC_DMAIN_RIE : R/W ;bitpos:[6] ;default: 1'h0 ; */ +/*description: When this bit is set with Normal Interrupt Summary Enable (Bit[16]) + the Receive Interrupt is enabled. When this bit is reset the Receive Interrupt is disabled.*/ +#define EMAC_DMAIN_RIE (BIT(6)) +#define EMAC_DMAIN_RIE_M (BIT(6)) +#define EMAC_DMAIN_RIE_V 0x1 +#define EMAC_DMAIN_RIE_S 6 +/* EMAC_DMAIN_UIE : R/W ;bitpos:[5] ;default: 1'h0 ; */ +/*description: When this bit is set with Abnormal Interrupt Summary Enable (Bit[15]) + the Transmit Underflow Interrupt is enabled. When this bit is reset the Underflow Interrupt is disabled.*/ +#define EMAC_DMAIN_UIE (BIT(5)) +#define EMAC_DMAIN_UIE_M (BIT(5)) +#define EMAC_DMAIN_UIE_V 0x1 +#define EMAC_DMAIN_UIE_S 5 +/* EMAC_DMAIN_OIE : R/W ;bitpos:[4] ;default: 1'h0 ; */ +/*description: When this bit is set with Abnormal Interrupt Summary Enable (Bit[15]) + the Receive Overflow Interrupt is enabled. When this bit is reset the Overflow Interrupt is disabled.*/ +#define EMAC_DMAIN_OIE (BIT(4)) +#define EMAC_DMAIN_OIE_M (BIT(4)) +#define EMAC_DMAIN_OIE_V 0x1 +#define EMAC_DMAIN_OIE_S 4 +/* EMAC_DMAIN_TJTE : R/W ;bitpos:[3] ;default: 1'h0 ; */ +/*description: When this bit is set with Abnormal Interrupt Summary Enable (Bit[15]) + the Transmit Jabber Timeout Interrupt is enabled. When this bit is reset the Transmit Jabber Timeout Interrupt is disabled.*/ +#define EMAC_DMAIN_TJTE (BIT(3)) +#define EMAC_DMAIN_TJTE_M (BIT(3)) +#define EMAC_DMAIN_TJTE_V 0x1 +#define EMAC_DMAIN_TJTE_S 3 +/* EMAC_DMAIN_TBUE : R/W ;bitpos:[2] ;default: 1'h0 ; */ +/*description: When this bit is set with Normal Interrupt Summary Enable (Bit + 16) the Transmit Buffer Unavailable Interrupt is enabled. When this bit is reset the Transmit Buffer Unavailable Interrupt is Disabled.*/ +#define EMAC_DMAIN_TBUE (BIT(2)) +#define EMAC_DMAIN_TBUE_M (BIT(2)) +#define EMAC_DMAIN_TBUE_V 0x1 +#define EMAC_DMAIN_TBUE_S 2 +/* EMAC_DMAIN_TSE : R/W ;bitpos:[1] ;default: 1'h0 ; */ +/*description: When this bit is set with Abnormal Interrupt Summary Enable (Bit[15]) + the Transmission Stopped Interrupt is enabled. When this bit is reset the Transmission Stopped Interrupt is disabled.*/ +#define EMAC_DMAIN_TSE (BIT(1)) +#define EMAC_DMAIN_TSE_M (BIT(1)) +#define EMAC_DMAIN_TSE_V 0x1 +#define EMAC_DMAIN_TSE_S 1 +/* EMAC_DMAIN_TIE : R/W ;bitpos:[0] ;default: 1'h0 ; */ +/*description: When this bit is set with Normal Interrupt Summary Enable (Bit[16]) + the Transmit Interrupt is enabled. When this bit is reset the Transmit Interrupt is disabled.*/ +#define EMAC_DMAIN_TIE (BIT(0)) +#define EMAC_DMAIN_TIE_M (BIT(0)) +#define EMAC_DMAIN_TIE_V 0x1 +#define EMAC_DMAIN_TIE_S 0 + +#define EMAC_DMAMISSEDFR_REG (DR_REG_EMAC_BASE + 0x0020) +/* EMAC_OVERFLOW_BFOC : R_SS_RC ;bitpos:[28] ;default: 1'h0 ; */ +/*description: This bit is set every time the Overflow Frame Counter (Bits[27:17]) + overflows that is the Rx FIFO overflows with the overflow frame counter at maximum value. In such a scenario the overflow frame counter is reset to all-zeros and this bit indicates that the rollover happened.*/ +#define EMAC_OVERFLOW_BFOC (BIT(28)) +#define EMAC_OVERFLOW_BFOC_M (BIT(28)) +#define EMAC_OVERFLOW_BFOC_V 0x1 +#define EMAC_OVERFLOW_BFOC_S 28 +/* EMAC_OVERFLOW_FC : R_SS_RC ;bitpos:[27:17] ;default: 11'h0 ; */ +/*description: This field indicates the number of frames missed by the application. + This counter is incremented each time the MTL FIFO overflows. The counter is cleared when this register is read.*/ +#define EMAC_OVERFLOW_FC 0x000007FF +#define EMAC_OVERFLOW_FC_M ((EMAC_OVERFLOW_FC_V)<<(EMAC_OVERFLOW_FC_S)) +#define EMAC_OVERFLOW_FC_V 0x7FF +#define EMAC_OVERFLOW_FC_S 17 +/* EMAC_OVERFLOW_BMFC : R_SS_RC ;bitpos:[16] ;default: 1'h0 ; */ +/*description: This bit is set every time Missed Frame Counter (Bits[15:0]) + overflows that is the DMA discards an incoming frame because of the Host Receive Buffer being unavailable with the missed frame counter at maximum value. In such a scenario the Missed frame counter is reset to all-zeros and this bit indicates that the rollover happened.*/ +#define EMAC_OVERFLOW_BMFC (BIT(16)) +#define EMAC_OVERFLOW_BMFC_M (BIT(16)) +#define EMAC_OVERFLOW_BMFC_V 0x1 +#define EMAC_OVERFLOW_BMFC_S 16 +/* EMAC_MISSED_FC : R_SS_RC ;bitpos:[15:0] ;default: 16'h0 ; */ +/*description: This field indicates the number of frames missed by the controller + because of the Host Receive Buffer being unavailable. This counter is incremented each time the DMA discards an incoming frame. The counter is cleared when this register is read.*/ +#define EMAC_MISSED_FC 0x0000FFFF +#define EMAC_MISSED_FC_M ((EMAC_MISSED_FC_V)<<(EMAC_MISSED_FC_S)) +#define EMAC_MISSED_FC_V 0xFFFF +#define EMAC_MISSED_FC_S 0 + +#define EMAC_DMARINTWDTIMER_REG (DR_REG_EMAC_BASE + 0x0024) +/* EMAC_RIWTC : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: This bit indicates the number of system clock cycles multiplied + by 256 for which the watchdog timer is set. The watchdog timer gets triggered with the programmed value after the Rx DMA completes the transfer of a frame for which the RI(RECV_INT) status bit is not set because of the setting in the corresponding descriptor RDES1[31]. When the watchdog timer runs out the RI bit is set and the timer is stopped. The watchdog timer is reset when the RI bit is set high because of automatic setting of RI as per RDES1[31] of any received frame.*/ +#define EMAC_RIWTC 0x000000FF +#define EMAC_RIWTC_M ((EMAC_RIWTC_V)<<(EMAC_RIWTC_S)) +#define EMAC_RIWTC_V 0xFF +#define EMAC_RIWTC_S 0 + +#define EMAC_DMATXCURRDESC_REG (DR_REG_EMAC_BASE + 0x0048) +/* EMAC_TRANS_DSCR_ADDR_PTR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: The address of the current receive descriptor list. Cleared on + Reset.Pointer updated by the DMA during operation.*/ +#define EMAC_TRANS_DSCR_ADDR_PTR 0xFFFFFFFF +#define EMAC_TRANS_DSCR_ADDR_PTR_M ((EMAC_TRANS_DSCR_ADDR_PTR_V)<<(EMAC_TRANS_DSCR_ADDR_PTR_S)) +#define EMAC_TRANS_DSCR_ADDR_PTR_V 0xFFFFFFFF +#define EMAC_TRANS_DSCR_ADDR_PTR_S 0 + +#define EMAC_DMARXCURRDESC_REG (DR_REG_EMAC_BASE + 0x004C) +/* EMAC_RECV_DSCR_ADDR_PTR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: The address of the current receive descriptor list. Cleared on + Reset.Pointer updated by the DMA during operation.*/ +#define EMAC_RECV_DSCR_ADDR_PTR 0xFFFFFFFF +#define EMAC_RECV_DSCR_ADDR_PTR_M ((EMAC_RECV_DSCR_ADDR_PTR_V)<<(EMAC_RECV_DSCR_ADDR_PTR_S)) +#define EMAC_RECV_DSCR_ADDR_PTR_V 0xFFFFFFFF +#define EMAC_RECV_DSCR_ADDR_PTR_S 0 + +#define EMAC_DMATXCURRADDR_BUF_REG (DR_REG_EMAC_BASE + 0x0050) +/* EMAC_TRANS_BUFF_ADDR_PTR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: The address of the current receive descriptor list. Cleared on + Reset.Pointer updated by the DMA during operation.*/ +#define EMAC_TRANS_BUFF_ADDR_PTR 0xFFFFFFFF +#define EMAC_TRANS_BUFF_ADDR_PTR_M ((EMAC_TRANS_BUFF_ADDR_PTR_V)<<(EMAC_TRANS_BUFF_ADDR_PTR_S)) +#define EMAC_TRANS_BUFF_ADDR_PTR_V 0xFFFFFFFF +#define EMAC_TRANS_BUFF_ADDR_PTR_S 0 + +#define EMAC_DMARXCURRADDR_BUF_REG (DR_REG_EMAC_BASE + 0x0054) +/* EMAC_RECV_BUFF_ADDR_PTR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: The address of the current receive descriptor list. Cleared on + Reset.Pointer updated by the DMA during operation.*/ +#define EMAC_RECV_BUFF_ADDR_PTR 0xFFFFFFFF +#define EMAC_RECV_BUFF_ADDR_PTR_M ((EMAC_RECV_BUFF_ADDR_PTR_V)<<(EMAC_RECV_BUFF_ADDR_PTR_S)) +#define EMAC_RECV_BUFF_ADDR_PTR_V 0xFFFFFFFF +#define EMAC_RECV_BUFF_ADDR_PTR_S 0 + +#define EMAC_GMACCONFIG_REG (DR_REG_EMAC_BASE + 0x1000) +/* EMAC_SAIRC : R/W ;bitpos:[30:28] ;default: 3'h0 ; */ +/*description: This field controls the source address insertion or replacement + for all transmitted frames.Bit[30] specifies which MAC Address register (0 or 1) is used for source address insertion or replacement based on the values of Bits [29:28]: 2'b0x: The input signals mti_sa_ctrl_i and ati_sa_ctrl_i control the SA field generation. 2'b10: If Bit[30] is set to 0 the MAC inserts the content of the MAC Address 0 registers in the SA field of all transmitted frames. If Bit[30] is set to 1 the MAC inserts the content of the MAC Address 1 registers in the SA field of all transmitted frames. 2'b11: If Bit[30] is set to 0 the MAC replaces the content of the MAC Address 0 registers in the SA field of all transmitted frames. If Bit[30] is set to 1 the MAC replaces the content of the MAC Address 1 registers in the SA field of all transmitted frames.*/ +#define EMAC_SAIRC 0x00000007 +#define EMAC_SAIRC_M ((EMAC_SAIRC_V)<<(EMAC_SAIRC_S)) +#define EMAC_SAIRC_V 0x7 +#define EMAC_SAIRC_S 28 +/* EMAC_ASS2KP : R/W ;bitpos:[27] ;default: 1'h0 ; */ +/*description: When set the MAC considers all frames with up to 2 000 bytes + length as normal packets.When Bit[20] (JE) is not set the MAC considers all received frames of size more than 2K bytes as Giant frames. When this bit is reset and Bit[20] (JE) is not set the MAC considers all received frames of size more than 1 518 bytes (1 522 bytes for tagged) as Giant frames. When Bit[20] is set setting this bit has no effect on Giant Frame status.*/ +#define EMAC_ASS2KP (BIT(27)) +#define EMAC_ASS2KP_M (BIT(27)) +#define EMAC_ASS2KP_V 0x1 +#define EMAC_ASS2KP_S 27 +/* EMAC_EMACWATCHDOG : R/W ;bitpos:[23] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC disables the watchdog timer on + the receiver. The MAC can receive frames of up to 16 383 bytes. When this bit is reset the MAC does not allow a receive frame which more than 2 048 bytes (10 240 if JE is set high) or the value programmed in Register (Watchdog Timeout Register). The MAC cuts off any bytes received after the watchdog limit number of bytes.*/ +#define EMAC_EMACWATCHDOG (BIT(23)) +#define EMAC_EMACWATCHDOG_M (BIT(23)) +#define EMAC_EMACWATCHDOG_V 0x1 +#define EMAC_EMACWATCHDOG_S 23 +/* EMAC_EMACJABBER : R/W ;bitpos:[22] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC disables the jabber timer on the + transmitter. The MAC can transfer frames of up to 16 383 bytes. When this bit is reset the MAC cuts off the transmitter if the application sends out more than 2 048 bytes of data (10 240 if JE is set high) during Transmission.*/ +#define EMAC_EMACJABBER (BIT(22)) +#define EMAC_EMACJABBER_M (BIT(22)) +#define EMAC_EMACJABBER_V 0x1 +#define EMAC_EMACJABBER_S 22 +/* EMAC_EMACJUMBOFRAME : R/W ;bitpos:[20] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC allows Jumbo frames of 9 018 bytes + (9 022 bytes for VLAN tagged frames) without reporting a giant frame error in the receive frame status.*/ +#define EMAC_EMACJUMBOFRAME (BIT(20)) +#define EMAC_EMACJUMBOFRAME_M (BIT(20)) +#define EMAC_EMACJUMBOFRAME_V 0x1 +#define EMAC_EMACJUMBOFRAME_S 20 +/* EMAC_EMACINTERFRAMEGAP : R/W ;bitpos:[19:17] ;default: 1'h0 ; */ +/*description: These bits control the minimum IFG between frames during transmission. + 3'b000: 96 bit times. 3'b001: 88 bit times. 3'b010: 80 bit times. 3'b111: 40 bit times. In the half-duplex mode the minimum IFG can be configured only for 64 bit times (IFG = 100). Lower values are not considered.*/ +#define EMAC_EMACINTERFRAMEGAP 0x00000007 +#define EMAC_EMACINTERFRAMEGAP_M ((EMAC_EMACINTERFRAMEGAP_V)<<(EMAC_EMACINTERFRAMEGAP_S)) +#define EMAC_EMACINTERFRAMEGAP_V 0x7 +#define EMAC_EMACINTERFRAMEGAP_S 17 +/* EMAC_EMACDISABLECRS : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: When set high this bit makes the MAC transmitter ignore the + MII CRS signal during frame transmission in the half-duplex mode. This request results in no errors generated because of Loss of Carrier or No Carrier during such transmission. When this bit is low the MAC transmitter generates such errors because of Carrier Sense and can even abort the transmissions.*/ +#define EMAC_EMACDISABLECRS (BIT(16)) +#define EMAC_EMACDISABLECRS_M (BIT(16)) +#define EMAC_EMACDISABLECRS_V 0x1 +#define EMAC_EMACDISABLECRS_S 16 +/* EMAC_EMACMII : R/W ;bitpos:[15] ;default: 1'h0 ; */ +/*description: This bit selects the Ethernet line speed. It should be set to + 1 for 10 or 100 Mbps operations.In 10 or 100 Mbps operations this bit along with FES(EMACFESPEED) bit it selects the exact linespeed. In the 10/100 Mbps-only operations the bit is always 1.*/ +#define EMAC_EMACMII (BIT(15)) +#define EMAC_EMACMII_M (BIT(15)) +#define EMAC_EMACMII_V 0x1 +#define EMAC_EMACMII_S 15 +/* EMAC_EMACFESPEED : R/W ;bitpos:[14] ;default: 1'h0 ; */ +/*description: This bit selects the speed in the MII RMII interface. 0: 10 Mbps. 1: 100 Mbps.*/ +#define EMAC_EMACFESPEED (BIT(14)) +#define EMAC_EMACFESPEED_M (BIT(14)) +#define EMAC_EMACFESPEED_V 0x1 +#define EMAC_EMACFESPEED_S 14 +/* EMAC_EMACRXOWN : R/W ;bitpos:[13] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC disables the reception of frames + when the TX_EN is asserted in the half-duplex mode. When this bit is reset the MAC receives all packets that are given by the PHY while transmitting. This bit is not applicable if the MAC is operating in the full duplex mode.*/ +#define EMAC_EMACRXOWN (BIT(13)) +#define EMAC_EMACRXOWN_M (BIT(13)) +#define EMAC_EMACRXOWN_V 0x1 +#define EMAC_EMACRXOWN_S 13 +/* EMAC_EMACLOOPBACK : R/W ;bitpos:[12] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC operates in the loopback mode MII. + The MII Receive clock input (CLK_RX) is required for the loopback to work properly because the transmit clock is not looped-back internally.*/ +#define EMAC_EMACLOOPBACK (BIT(12)) +#define EMAC_EMACLOOPBACK_M (BIT(12)) +#define EMAC_EMACLOOPBACK_V 0x1 +#define EMAC_EMACLOOPBACK_S 12 +/* EMAC_EMACDUPLEX : R/W ;bitpos:[11] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC operates in the full-duplex mode + where it can transmit and receive simultaneously. This bit is read only with default value of 1'b1 in the full-duplex-mode.*/ +#define EMAC_EMACDUPLEX (BIT(11)) +#define EMAC_EMACDUPLEX_M (BIT(11)) +#define EMAC_EMACDUPLEX_V 0x1 +#define EMAC_EMACDUPLEX_S 11 +/* EMAC_EMACRXIPCOFFLOAD : R/W ;bitpos:[10] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC calculates the 16-bit one's complement + of the one's complement sum of all received Ethernet frame payloads. It also checks whether the IPv4 Header checksum (assumed to be bytes 25/26 or 29/30 (VLAN-tagged) of the received Ethernet frame) is correct for the received frame and gives the status in the receive status word. The MAC also appends the 16-bit checksum calculated for the IP header datagram payload (bytes after the IPv4 header) and appends it to the Ethernet frame transferred to the application (when Type 2 COE is deselected). When this bit is reset this function is disabled.*/ +#define EMAC_EMACRXIPCOFFLOAD (BIT(10)) +#define EMAC_EMACRXIPCOFFLOAD_M (BIT(10)) +#define EMAC_EMACRXIPCOFFLOAD_V 0x1 +#define EMAC_EMACRXIPCOFFLOAD_S 10 +/* EMAC_EMACRETRY : R/W ;bitpos:[9] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC attempts only one transmission. + When a collision occurs on the MII interface the MAC ignores the current frame transmission and reports a Frame Abort with excessive collision error in the transmit frame status. When this bit is reset the MAC attempts retries based on the settings of the BL field (Bits [6:5]). This bit is applicable only in the half-duplex Mode.*/ +#define EMAC_EMACRETRY (BIT(9)) +#define EMAC_EMACRETRY_M (BIT(9)) +#define EMAC_EMACRETRY_V 0x1 +#define EMAC_EMACRETRY_S 9 +/* EMAC_EMACPADCRCSTRIP : R/W ;bitpos:[7] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC strips the Pad or FCS field on + the incoming frames only if the value of the length field is less than 1 536 bytes. All received frames with length field greater than or equal to 1 536 bytes are passed to the application without stripping the Pad or FCS field. When this bit is reset the MAC passes all incoming frames without modifying them to the Host.*/ +#define EMAC_EMACPADCRCSTRIP (BIT(7)) +#define EMAC_EMACPADCRCSTRIP_M (BIT(7)) +#define EMAC_EMACPADCRCSTRIP_V 0x1 +#define EMAC_EMACPADCRCSTRIP_S 7 +/* EMAC_EMACBACKOFFLIMIT : R/W ;bitpos:[6:5] ;default: 2'h0 ; */ +/*description: The Back-Off limit determines the random integer number (r) of + slot time delays (512 bit times for 10/100 Mbps) for which the MAC waits before rescheduling a transmission attempt during retries after a collision. This bit is applicable only in the half-duplex mode. 00: k= min (n 10). 01: k = min (n 8). 10: k = min (n 4). 11: k = min (n 1) n = retransmission attempt. The random integer r takes the value in the Range 0 ~ 2000.*/ +#define EMAC_EMACBACKOFFLIMIT 0x00000003 +#define EMAC_EMACBACKOFFLIMIT_M ((EMAC_EMACBACKOFFLIMIT_V)<<(EMAC_EMACBACKOFFLIMIT_S)) +#define EMAC_EMACBACKOFFLIMIT_V 0x3 +#define EMAC_EMACBACKOFFLIMIT_S 5 +/* EMAC_EMACDEFERRALCHECK : R/W ;bitpos:[4] ;default: 1'h0 ; */ +/*description: Deferral Check.*/ +#define EMAC_EMACDEFERRALCHECK (BIT(4)) +#define EMAC_EMACDEFERRALCHECK_M (BIT(4)) +#define EMAC_EMACDEFERRALCHECK_V 0x1 +#define EMAC_EMACDEFERRALCHECK_S 4 +/* EMAC_EMACTX : R/W ;bitpos:[3] ;default: 1'h0 ; */ +/*description: When this bit is set the transmit state machine of the MAC is + enabled for transmission on the MII. When this bit is reset the MAC transmit state machine is disabled after the completion of the transmission of the current frame and does not transmit any further frames.*/ +#define EMAC_EMACTX (BIT(3)) +#define EMAC_EMACTX_M (BIT(3)) +#define EMAC_EMACTX_V 0x1 +#define EMAC_EMACTX_S 3 +/* EMAC_EMACRX : R/W ;bitpos:[2] ;default: 1'h0 ; */ +/*description: When this bit is set the receiver state machine of the MAC is + enabled for receiving frames from the MII. When this bit is reset the MAC receive state machine is disabled after the completion of the reception of the current frame and does not receive any further frames from the MII.*/ +#define EMAC_EMACRX (BIT(2)) +#define EMAC_EMACRX_M (BIT(2)) +#define EMAC_EMACRX_V 0x1 +#define EMAC_EMACRX_S 2 +/* EMAC_PLTF : R/W ;bitpos:[1:0] ;default: 2'h0 ; */ +/*description: These bits control the number of preamble bytes that are added + to the beginning of every Transmit frame. The preamble reduction occurs only when the MAC is operating in the full-duplex mode.2'b00: 7 bytes of preamble. 2'b01: 5 bytes of preamble. 2'b10: 3 bytes of preamble.*/ +#define EMAC_PLTF 0x00000003 +#define EMAC_PLTF_M ((EMAC_PLTF_V)<<(EMAC_PLTF_S)) +#define EMAC_PLTF_V 0x3 +#define EMAC_PLTF_S 0 + +#define EMAC_GMACFF_REG (DR_REG_EMAC_BASE + 0x1004) +/* EMAC_RECEIVE_ALL : R/W ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC Receiver module passes all received + frames irrespective of whether they pass the address filter or not to the Application. The result of the SA or DA filtering is updated (pass or fail) in the corresponding bits in the Receive Status Word. When this bit is reset the Receiver module passes only those frames to the Application that pass the SA or DA address Filter.*/ +#define EMAC_RECEIVE_ALL (BIT(31)) +#define EMAC_RECEIVE_ALL_M (BIT(31)) +#define EMAC_RECEIVE_ALL_V 0x1 +#define EMAC_RECEIVE_ALL_S 31 +/* EMAC_SAFE : R/W ;bitpos:[9] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC compares the SA field of the received + frames with the values programmed in the enabled SA registers. If the comparison fails the MAC drops the frame. When this bit is reset the MAC forwards the received frame to the application with updated SAF bit of the Rx Status depending on the SA address comparison.*/ +#define EMAC_SAFE (BIT(9)) +#define EMAC_SAFE_M (BIT(9)) +#define EMAC_SAFE_V 0x1 +#define EMAC_SAFE_S 9 +/* EMAC_SAIF : R/W ;bitpos:[8] ;default: 1'h0 ; */ +/*description: When this bit is set the Address Check block operates in inverse + filtering mode for the SA address comparison. The frames whose SA matches the SA registers are marked as failing the SA Address filter. When this bit is reset frames whose SA does not match the SA registers are marked as failing the SA Address filter.*/ +#define EMAC_SAIF (BIT(8)) +#define EMAC_SAIF_M (BIT(8)) +#define EMAC_SAIF_V 0x1 +#define EMAC_SAIF_S 8 +/* EMAC_PCF : R/W ;bitpos:[7:6] ;default: 2'h0 ; */ +/*description: These bits control the forwarding of all control frames (including + unicast and multicast Pause frames). 2'b00: MAC filters all control frames from reaching the application. 2'b01: MAC forwards all control frames except Pause frames to application even if they fail the Address filter. 2'b10: MAC forwards all control frames to application even if they fail the Address Filter. 2'b11: MAC forwards control frames that pass the Address Filter.The following conditions should be true for the Pause frames processing: Condition 1: The MAC is in the full-duplex mode and flow control is enabled by setting Bit 2 (RFE) of Register (Flow Control Register) to 1. Condition 2: The destination address (DA) of the received frame matches the special multicast address or the MAC Address 0 when Bit 3 (UP) of the Register(Flow Control Register) is set. Condition 3: The Type field of the received frame is 0x8808 and the OPCODE field is 0x0001.*/ +#define EMAC_PCF 0x00000003 +#define EMAC_PCF_M ((EMAC_PCF_V)<<(EMAC_PCF_S)) +#define EMAC_PCF_V 0x3 +#define EMAC_PCF_S 6 +/* EMAC_DBF : R/W ;bitpos:[5] ;default: 1'h0 ; */ +/*description: When this bit is set the AFM(Address Filtering Module) module + blocks all incoming broadcast frames. In addition it overrides all other filter settings. When this bit is reset the AFM module passes all received broadcast Frames.*/ +#define EMAC_DBF (BIT(5)) +#define EMAC_DBF_M (BIT(5)) +#define EMAC_DBF_V 0x1 +#define EMAC_DBF_S 5 +/* EMAC_PAM : R/W ;bitpos:[4] ;default: 1'h0 ; */ +/*description: When set this bit indicates that all received frames with a + multicast destination address (first bit in the destination address field is '1') are passed.*/ +#define EMAC_PAM (BIT(4)) +#define EMAC_PAM_M (BIT(4)) +#define EMAC_PAM_V 0x1 +#define EMAC_PAM_S 4 +/* EMAC_DAIF : R/W ;bitpos:[3] ;default: 1'h0 ; */ +/*description: When this bit is set the Address Check block operates in inverse + filtering mode for the DA address comparison for both unicast and multicast frames. When reset normal filtering of frames is performed.*/ +#define EMAC_DAIF (BIT(3)) +#define EMAC_DAIF_M (BIT(3)) +#define EMAC_DAIF_V 0x1 +#define EMAC_DAIF_S 3 +/* EMAC_PMODE : R/W ;bitpos:[0] ;default: 1'h0 ; */ +/*description: When this bit is set the Address Filter module passes all incoming + frames irrespective of the destination or source address. The SA or DA Filter Fails status bits of the Receive Status Word are always cleared when PR(PRI_RATIO) is set.*/ +#define EMAC_PMODE (BIT(0)) +#define EMAC_PMODE_M (BIT(0)) +#define EMAC_PMODE_V 0x1 +#define EMAC_PMODE_S 0 + +#define EMAC_GMIIADDR_REG (DR_REG_EMAC_BASE + 0x1010) +/* EMAC_MIIDEV : R/W ;bitpos:[15:11] ;default: 6'h0 ; */ +/*description: This field indicates which of the 32 possible PHY devices are being accessed.*/ +#define EMAC_MIIDEV 0x0000001F +#define EMAC_MIIDEV_M ((EMAC_MIIDEV_V)<<(EMAC_MIIDEV_S)) +#define EMAC_MIIDEV_V 0x1F +#define EMAC_MIIDEV_S 11 +/* EMAC_MIIREG : R/W ;bitpos:[10:6] ;default: 5'h0 ; */ +/*description: These bits select the desired MII register in the selected PHY device.*/ +#define EMAC_MIIREG 0x0000001F +#define EMAC_MIIREG_M ((EMAC_MIIREG_V)<<(EMAC_MIIREG_S)) +#define EMAC_MIIREG_V 0x1F +#define EMAC_MIIREG_S 6 +/* EMAC_MIICSRCLK : R/W ;bitpos:[5:2] ;default: 5'h0 ; */ +/*description: CSR clock range: 1.0 MHz ~ 2.5 MHz. 4'b0000: When the APB clock + frequency is 80 MHz the MDC clock frequency is APB CLK/42 4'b0000: When the APB clock frequency is 40 MHz the MDC clock frequency is APB CLK/26.*/ +#define EMAC_MIICSRCLK 0x0000000F +#define EMAC_MIICSRCLK_M ((EMAC_MIICSRCLK_V)<<(EMAC_MIICSRCLK_S)) +#define EMAC_MIICSRCLK_V 0xF +#define EMAC_MIICSRCLK_S 2 +/* EMAC_MIIWRITE : R/W ;bitpos:[1] ;default: 1'h0 ; */ +/*description: When set this bit indicates to the PHY that this is a Write + operation using the MII Data register. If this bit is not set it indicates that this is a Read operation that is placing the data in the MII Data register.*/ +#define EMAC_MIIWRITE (BIT(1)) +#define EMAC_MIIWRITE_M (BIT(1)) +#define EMAC_MIIWRITE_V 0x1 +#define EMAC_MIIWRITE_S 1 +/* EMAC_MIIBUSY : R_WS_SC ;bitpos:[0] ;default: 1'h0 ; */ +/*description: This bit should read logic 0 before writing to PHY Addr Register + and PHY data Register.During a PHY register access the software sets this bit to 1'b1 to indicate that a Read or Write access is in progress. PHY data Register is invalid until this bit is cleared by the MAC. Therefore PHY data Register (MII Data) should be kept valid until the MAC clears this bit during a PHY Write operation. Similarly for a read operation the contents of Register 5 are not valid until this bit is cleared. The subsequent read or write operation should happen only after the previous operation is complete. Because there is no acknowledgment from the PHY to MAC after a read or write operation is completed there is no change in the functionality of this bit even when the PHY is not Present.*/ +#define EMAC_MIIBUSY (BIT(0)) +#define EMAC_MIIBUSY_M (BIT(0)) +#define EMAC_MIIBUSY_V 0x1 +#define EMAC_MIIBUSY_S 0 + +#define EMAC_MIIDATA_REG (DR_REG_EMAC_BASE + 0x1014) +/* EMAC_MII_DATA : R/W ;bitpos:[15:0] ;default: 16'h0 ; */ +/*description: This field contains the 16-bit data value read from the PHY after + a Management Read operation or the 16-bit data value to be written to the PHY before a Management Write operation.*/ +#define EMAC_MII_DATA 0x0000FFFF +#define EMAC_MII_DATA_M ((EMAC_MII_DATA_V)<<(EMAC_MII_DATA_S)) +#define EMAC_MII_DATA_V 0xFFFF +#define EMAC_MII_DATA_S 0 + +#define EMAC_GMACFC_REG (DR_REG_EMAC_BASE + 0x1018) +/* EMAC_PAUSE_TIME : R/W ;bitpos:[31:16] ;default: 16'h0 ; */ +/*description: This field holds the value to be used in the Pause Time field + in the transmit control frame. If the Pause Time bits is configured to be double-synchronized to the MII clock domain then consecutive writes to this register should be performed only after at least four clock cycles in the destination clock domain.*/ +#define EMAC_PAUSE_TIME 0x0000FFFF +#define EMAC_PAUSE_TIME_M ((EMAC_PAUSE_TIME_V)<<(EMAC_PAUSE_TIME_S)) +#define EMAC_PAUSE_TIME_V 0xFFFF +#define EMAC_PAUSE_TIME_S 16 +/* EMAC_DZPQ : R/W ;bitpos:[7] ;default: 1'h0 ; */ +/*description: When this bit is set it disables the automatic generation of + the Zero-Quanta Pause frames on the de-assertion of the flow-control signal from the FIFO layer. When this bit is reset normal operation with automatic Zero-Quanta Pause frame generation is enabled.*/ +#define EMAC_DZPQ (BIT(7)) +#define EMAC_DZPQ_M (BIT(7)) +#define EMAC_DZPQ_V 0x1 +#define EMAC_DZPQ_S 7 +/* EMAC_PLT : R/W ;bitpos:[5:4] ;default: 2'h0 ; */ +/*description: This field configures the threshold of the Pause timer automatic + retransmission of the Pause frame.The threshold values should be always less than the Pause Time configured in Bits[31:16]. For example if PT = 100H (256 slot-times) and PLT = 01 then a second Pause frame is automatically transmitted at 228 (256-28) slot times after the first Pause frame is transmitted. The following list provides the threshold values for different values: 2'b00: The threshold is Pause time minus 4 slot times (PT-4 slot times). 2'b01: The threshold is Pause time minus 28 slot times (PT-28 slot times). 2'b10: The threshold is Pause time minus 144 slot times (PT-144 slot times). 2'b11: The threshold is Pause time minus 256 slot times (PT-256 slot times). The slot time is defined as the time taken to transmit 512 bits (64 bytes) on the MII interface.*/ +#define EMAC_PLT 0x00000003 +#define EMAC_PLT_M ((EMAC_PLT_V)<<(EMAC_PLT_S)) +#define EMAC_PLT_V 0x3 +#define EMAC_PLT_S 4 +/* EMAC_UPFD : R/W ;bitpos:[3] ;default: 1'h0 ; */ +/*description: A pause frame is processed when it has the unique multicast address + specified in the IEEE Std 802.3. When this bit is set the MAC can also detect Pause frames with unicast address of the station. This unicast address should be as specified in the EMACADDR0 High Register and EMACADDR0 Low Register. When this bit is reset the MAC only detects Pause frames with unique multicast address.*/ +#define EMAC_UPFD (BIT(3)) +#define EMAC_UPFD_M (BIT(3)) +#define EMAC_UPFD_V 0x1 +#define EMAC_UPFD_S 3 +/* EMAC_RFCE : R/W ;bitpos:[2] ;default: 1'h0 ; */ +/*description: When this bit is set the MAC decodes the received Pause frame + and disables its transmitter for a specified (Pause) time. When this bit is reset the decode function of the Pause frame is disabled.*/ +#define EMAC_RFCE (BIT(2)) +#define EMAC_RFCE_M (BIT(2)) +#define EMAC_RFCE_V 0x1 +#define EMAC_RFCE_S 2 +/* EMAC_TFCE : R/W ;bitpos:[1] ;default: 1'h0 ; */ +/*description: In the full-duplex mode when this bit is set the MAC enables + the flow control operation to transmit Pause frames. When this bit is reset the flow control operation in the MAC is disabled and the MAC does not transmit any Pause frames. In the half-duplex mode when this bit is set the MAC enables the backpressure operation. When this bit is reset the backpressure feature is Disabled.*/ +#define EMAC_TFCE (BIT(1)) +#define EMAC_TFCE_M (BIT(1)) +#define EMAC_TFCE_V 0x1 +#define EMAC_TFCE_S 1 +/* EMAC_FCBBA : R_WS_SC(FCB)/R_W(BPA) ;bitpos:[0] ;default: 1'h0 ; */ +/*description: This bit initiates a Pause frame in the full-duplex mode and + activates the backpressure function in the half-duplex mode if the TFCE bit is set. In the full-duplex mode this bit should be read as 1'b0 before writing to the Flow Control register. To initiate a Pause frame the Application must set this bit to 1'b1. During a transfer of the Control Frame this bit continues to be set to signify that a frame transmission is in progress. After the completion of Pause frame transmission the MAC resets this bit to 1'b0. The Flow Control register should not be written to until this bit is cleared. In the half-duplex mode when this bit is set (and TFCE is set) then backpressure is asserted by the MAC. During backpressure when the MAC receives a new frame the transmitter starts sending a JAM pattern resulting in a collision. When the MAC is configured for the full-duplex mode the BPA(backpressure activate) is automatically disabled.*/ +#define EMAC_FCBBA (BIT(0)) +#define EMAC_FCBBA_M (BIT(0)) +#define EMAC_FCBBA_V 0x1 +#define EMAC_FCBBA_S 0 + +#define EMAC_DEBUG_REG (DR_REG_EMAC_BASE + 0x1024) +/* EMAC_MTLTSFFS : RO ;bitpos:[25] ;default: 1'h0 ; */ +/*description: When high this bit indicates that the MTL TxStatus FIFO is full. + Therefore the MTL cannot accept any more frames for transmission.*/ +#define EMAC_MTLTSFFS (BIT(25)) +#define EMAC_MTLTSFFS_M (BIT(25)) +#define EMAC_MTLTSFFS_V 0x1 +#define EMAC_MTLTSFFS_S 25 +/* EMAC_MTLTFNES : RO ;bitpos:[24] ;default: 1'h0 ; */ +/*description: When high this bit indicates that the MTL Tx FIFO is not empty + and some data is left for Transmission.*/ +#define EMAC_MTLTFNES (BIT(24)) +#define EMAC_MTLTFNES_M (BIT(24)) +#define EMAC_MTLTFNES_V 0x1 +#define EMAC_MTLTFNES_S 24 +/* EMAC_MTLTFWCS : RO ;bitpos:[22] ;default: 1'h0 ; */ +/*description: When high this bit indicates that the MTL Tx FIFO Write Controller + is active and is transferring data to the Tx FIFO.*/ +#define EMAC_MTLTFWCS (BIT(22)) +#define EMAC_MTLTFWCS_M (BIT(22)) +#define EMAC_MTLTFWCS_V 0x1 +#define EMAC_MTLTFWCS_S 22 +/* EMAC_MTLTFRCS : RO ;bitpos:[21:20] ;default: 2'h0 ; */ +/*description: This field indicates the state of the Tx FIFO Read Controller: + 2'b00: IDLE state. 2'b01: READ state (transferring data to the MAC transmitter). 2'b10: Waiting for TxStatus from the MAC transmitter. 2'b11: Writing the received TxStatus or flushing the Tx FIFO.*/ +#define EMAC_MTLTFRCS 0x00000003 +#define EMAC_MTLTFRCS_M ((EMAC_MTLTFRCS_V)<<(EMAC_MTLTFRCS_S)) +#define EMAC_MTLTFRCS_V 0x3 +#define EMAC_MTLTFRCS_S 20 +/* EMAC_MACTP : RO ;bitpos:[19] ;default: 1'h0 ; */ +/*description: When high this bit indicates that the MAC transmitter is in + the Pause condition (in the full-duplex-mode) and hence does not schedule any frame for transmission.*/ +#define EMAC_MACTP (BIT(19)) +#define EMAC_MACTP_M (BIT(19)) +#define EMAC_MACTP_V 0x1 +#define EMAC_MACTP_S 19 +/* EMAC_MACTFCS : RO ;bitpos:[18:17] ;default: 2'h0 ; */ +/*description: This field indicates the state of the MAC Transmit Frame Controller + module: 2'b00: IDLE state. 2'b01: Waiting for status of previous frame or IFG or backoff period to be over. 2'b10: Generating and transmitting a Pause frame (in the full-duplex mode). 2'b11: Transferring input frame for transmission.*/ +#define EMAC_MACTFCS 0x00000003 +#define EMAC_MACTFCS_M ((EMAC_MACTFCS_V)<<(EMAC_MACTFCS_S)) +#define EMAC_MACTFCS_V 0x3 +#define EMAC_MACTFCS_S 17 +/* EMAC_MACTPES : RO ;bitpos:[16] ;default: 1'h0 ; */ +/*description: When high this bit indicates that the MAC MII transmit protocol + engine is actively transmitting data and is not in the IDLE state.*/ +#define EMAC_MACTPES (BIT(16)) +#define EMAC_MACTPES_M (BIT(16)) +#define EMAC_MACTPES_V 0x1 +#define EMAC_MACTPES_S 16 +/* EMAC_MTLRFFLS : RO ;bitpos:[9:8] ;default: 2'h0 ; */ +/*description: This field gives the status of the fill-level of the Rx FIFO: + 2'b00: Rx FIFO Empty. 2'b01: Rx FIFO fill-level below flow-control deactivate threshold. 2'b10: Rx FIFO fill-level above flow-control activate threshold. 2'b11: Rx FIFO Full.*/ +#define EMAC_MTLRFFLS 0x00000003 +#define EMAC_MTLRFFLS_M ((EMAC_MTLRFFLS_V)<<(EMAC_MTLRFFLS_S)) +#define EMAC_MTLRFFLS_V 0x3 +#define EMAC_MTLRFFLS_S 8 +/* EMAC_MTLRFRCS : RO ;bitpos:[6:5] ;default: 2'h0 ; */ +/*description: This field gives the state of the Rx FIFO read Controller: 2'b00: + IDLE state.2'b01: Reading frame data.2'b10: Reading frame status (or timestamp).2'b11: Flushing the frame data and status.*/ +#define EMAC_MTLRFRCS 0x00000003 +#define EMAC_MTLRFRCS_M ((EMAC_MTLRFRCS_V)<<(EMAC_MTLRFRCS_S)) +#define EMAC_MTLRFRCS_V 0x3 +#define EMAC_MTLRFRCS_S 5 +/* EMAC_MTLRFWCAS : RO ;bitpos:[4] ;default: 1'h0 ; */ +/*description: When high this bit indicates that the MTL Rx FIFO Write Controller + is active and is transferring a received frame to the FIFO.*/ +#define EMAC_MTLRFWCAS (BIT(4)) +#define EMAC_MTLRFWCAS_M (BIT(4)) +#define EMAC_MTLRFWCAS_V 0x1 +#define EMAC_MTLRFWCAS_S 4 +/* EMAC_MACRFFCS : RO ;bitpos:[2:1] ;default: 2'h0 ; */ +/*description: When high this field indicates the active state of the FIFO + Read and Write controllers of the MAC Receive Frame Controller Module. MACRFFCS[1] represents the status of FIFO Read controller. MACRFFCS[0] represents the status of small FIFO Write controller.*/ +#define EMAC_MACRFFCS 0x00000003 +#define EMAC_MACRFFCS_M ((EMAC_MACRFFCS_V)<<(EMAC_MACRFFCS_S)) +#define EMAC_MACRFFCS_V 0x3 +#define EMAC_MACRFFCS_S 1 +/* EMAC_MACRPES : RO ;bitpos:[0] ;default: 1'h0 ; */ +/*description: When high this bit indicates that the MAC MII receive protocol + engine is actively receiving data and not in IDLE state.*/ +#define EMAC_MACRPES (BIT(0)) +#define EMAC_MACRPES_M (BIT(0)) +#define EMAC_MACRPES_V 0x1 +#define EMAC_MACRPES_S 0 + +#define EMAC_PMT_RWUFFR_REG (DR_REG_EMAC_BASE + 0x1028) +/* EMAC_WKUPPKTFILTER : R/W ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: The MSB (31st bit) must be zero.Bit j[30:0] is the byte mask. + If Bit 1/2/3/4 (byte number) of the byte mask is set the CRC block processes the Filter 0/1/2/3 Offset + j of the incoming packet(PWKPTR is 0/1/2/3).RWKPTR is 0:Filter 0 Byte Mask .RWKPTR is 1:Filter 1 Byte Mask RWKPTR is 2:Filter 2 Byte Mask RWKPTR is 3:Filter 3 Byte Mask RWKPTR is 4:Bit 3/11/19/27 specifies the address type defining the destination address type of the pattern.When the bit is set the pattern applies to only multicast packets*/ +#define EMAC_WKUPPKTFILTER 0xFFFFFFFF +#define EMAC_WKUPPKTFILTER_M ((EMAC_WKUPPKTFILTER_V)<<(EMAC_WKUPPKTFILTER_S)) +#define EMAC_WKUPPKTFILTER_V 0xFFFFFFFF +#define EMAC_WKUPPKTFILTER_S 0 + +#define EMAC_PMT_CSR_REG (DR_REG_EMAC_BASE + 0x102C) +/* EMAC_RWKFILTRST : R_WS_SC ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set it resets the RWKPTR register to 3’b000.*/ +#define EMAC_RWKFILTRST (BIT(31)) +#define EMAC_RWKFILTRST_M (BIT(31)) +#define EMAC_RWKFILTRST_V 0x1 +#define EMAC_RWKFILTRST_S 31 +/* EMAC_RWKPTR : RO ;bitpos:[28:24] ;default: 6'h0 ; */ +/*description: The maximum value of the pointer is 7 the detail information + please refer to PMT_RWUFFR.*/ +#define EMAC_RWKPTR 0x0000001F +#define EMAC_RWKPTR_M ((EMAC_RWKPTR_V)<<(EMAC_RWKPTR_S)) +#define EMAC_RWKPTR_V 0x1F +#define EMAC_RWKPTR_S 24 +/* EMAC_GLBLUCAST : R/W ;bitpos:[9] ;default: 1'h0 ; */ +/*description: When set enables any unicast packet filtered by the MAC (DAFilter) + address recognition to be a remote wake-up frame.*/ +#define EMAC_GLBLUCAST (BIT(9)) +#define EMAC_GLBLUCAST_M (BIT(9)) +#define EMAC_GLBLUCAST_V 0x1 +#define EMAC_GLBLUCAST_S 9 +/* EMAC_RWKPRCVD : R_SS_RC ;bitpos:[6] ;default: 1'h0 ; */ +/*description: When set this bit indicates the power management event is generated + because of the reception of a remote wake-up frame. This bit is cleared by a Read into this register.*/ +#define EMAC_RWKPRCVD (BIT(6)) +#define EMAC_RWKPRCVD_M (BIT(6)) +#define EMAC_RWKPRCVD_V 0x1 +#define EMAC_RWKPRCVD_S 6 +/* EMAC_MGKPRCVD : R_SS_RC ;bitpos:[5] ;default: 1'h0 ; */ +/*description: When set this bit indicates that the power management event + is generated because of the reception of a magic packet. This bit is cleared by a Read into this register.*/ +#define EMAC_MGKPRCVD (BIT(5)) +#define EMAC_MGKPRCVD_M (BIT(5)) +#define EMAC_MGKPRCVD_V 0x1 +#define EMAC_MGKPRCVD_S 5 +/* EMAC_RWKPKTEN : R/W ;bitpos:[2] ;default: 1'h0 ; */ +/*description: When set enables generation of a power management event because + of remote wake-up frame reception*/ +#define EMAC_RWKPKTEN (BIT(2)) +#define EMAC_RWKPKTEN_M (BIT(2)) +#define EMAC_RWKPKTEN_V 0x1 +#define EMAC_RWKPKTEN_S 2 +/* EMAC_MGKPKTEN : R/W ;bitpos:[1] ;default: 1'h0 ; */ +/*description: When set enables generation of a power management event because + of magic packet reception.*/ +#define EMAC_MGKPKTEN (BIT(1)) +#define EMAC_MGKPKTEN_M (BIT(1)) +#define EMAC_MGKPKTEN_V 0x1 +#define EMAC_MGKPKTEN_S 1 +/* EMAC_PWRDWN : R_WS_SC ;bitpos:[0] ;default: 1'h0 ; */ +/*description: When set the MAC receiver drops all received frames until it + receives the expected magic packet or remote wake-up frame.This bit must only be set when MGKPKTEN GLBLUCAST or RWKPKTEN bit is set high.*/ +#define EMAC_PWRDWN (BIT(0)) +#define EMAC_PWRDWN_M (BIT(0)) +#define EMAC_PWRDWN_V 0x1 +#define EMAC_PWRDWN_S 0 + +#define EMAC_GMACLPI_CRS_REG (DR_REG_EMAC_BASE + 0x1030) +/* EMAC_LPITXA : R/W ;bitpos:[19] ;default: 1'h0 ; */ +/*description: This bit controls the behavior of the MAC when it is entering + or coming out of the LPI mode on the transmit side.If the LPITXA and LPIEN bits are set to 1 the MAC enters the LPI mode only after all outstanding frames and pending frames have been transmitted. The MAC comes out of the LPI mode when the application sends any frame.When this bit is 0 the LPIEN bit directly controls behavior of the MAC when it is entering or coming out of the LPI mode.*/ +#define EMAC_LPITXA (BIT(19)) +#define EMAC_LPITXA_M (BIT(19)) +#define EMAC_LPITXA_V 0x1 +#define EMAC_LPITXA_S 19 +/* EMAC_PLS : R/W ;bitpos:[17] ;default: 1'h0 ; */ +/*description: This bit indicates the link status of the PHY.When set the link + is considered to be okay (up) and when reset the link is considered to be down.*/ +#define EMAC_PLS (BIT(17)) +#define EMAC_PLS_M (BIT(17)) +#define EMAC_PLS_V 0x1 +#define EMAC_PLS_S 17 +/* EMAC_LPIEN : R_W_SC ;bitpos:[16] ;default: 1'h0 ; */ +/*description: When set this bit instructs the MAC Transmitter to enter the + LPI state. When reset this bit instructs the MAC to exit the LPI state and resume normal transmission.This bit is cleared when the LPITXA bit is set and the MAC exits the LPI state because of the arrival of a new packet for transmission.*/ +#define EMAC_LPIEN (BIT(16)) +#define EMAC_LPIEN_M (BIT(16)) +#define EMAC_LPIEN_V 0x1 +#define EMAC_LPIEN_S 16 +/* EMAC_RLPIST : R/W ;bitpos:[9] ;default: 1'h0 ; */ +/*description: When set this bit indicates that the MAC is receiving the LPI + pattern on the MII interface.*/ +#define EMAC_RLPIST (BIT(9)) +#define EMAC_RLPIST_M (BIT(9)) +#define EMAC_RLPIST_V 0x1 +#define EMAC_RLPIST_S 9 +/* EMAC_TLPIST : R/W ;bitpos:[8] ;default: 1'h0 ; */ +/*description: When set this bit indicates that the MAC is transmitting the + LPI pattern on the MII interface.*/ +#define EMAC_TLPIST (BIT(8)) +#define EMAC_TLPIST_M (BIT(8)) +#define EMAC_TLPIST_V 0x1 +#define EMAC_TLPIST_S 8 +/* EMAC_RLPIEX : R_SS_RC ;bitpos:[3] ;default: 1'h0 ; */ +/*description: When set this bit indicates that the MAC Receiver has stopped + receiving the LPI pattern on the MII interface exited the LPI state and resumed the normal reception. This bit is cleared by a read into this register.*/ +#define EMAC_RLPIEX (BIT(3)) +#define EMAC_RLPIEX_M (BIT(3)) +#define EMAC_RLPIEX_V 0x1 +#define EMAC_RLPIEX_S 3 +/* EMAC_RLPIEN : R_SS_RC ;bitpos:[2] ;default: 1'h0 ; */ +/*description: When set this bit indicates that the MAC Receiver has received + an LPI pattern and entered the LPI state. This bit is cleared by a read into this register.*/ +#define EMAC_RLPIEN (BIT(2)) +#define EMAC_RLPIEN_M (BIT(2)) +#define EMAC_RLPIEN_V 0x1 +#define EMAC_RLPIEN_S 2 +/* EMAC_TLPIEX : R_SS_RC ;bitpos:[1] ;default: 1'h0 ; */ +/*description: When set this bit indicates that the MAC transmitter has exited + the LPI state after the user has cleared the LPIEN bit and the LPI_TW_Timer has expired.This bit is cleared by a read into this register.*/ +#define EMAC_TLPIEX (BIT(1)) +#define EMAC_TLPIEX_M (BIT(1)) +#define EMAC_TLPIEX_V 0x1 +#define EMAC_TLPIEX_S 1 +/* EMAC_TLPIEN : R_SS_RC ;bitpos:[0] ;default: 1'h0 ; */ +/*description: When set this bit indicates that the MAC Transmitter has entered + the LPI state because of the setting of the LPIEN bit. This bit is cleared by a read into this register.*/ +#define EMAC_TLPIEN (BIT(0)) +#define EMAC_TLPIEN_M (BIT(0)) +#define EMAC_TLPIEN_V 0x1 +#define EMAC_TLPIEN_S 0 + +#define EMAC_GMACLPITIMERSCONTROL_REG (DR_REG_EMAC_BASE + 0x1034) +/* EMAC_LPI_LS_TIMER : R/W ;bitpos:[25:16] ;default: 10'h3E8 ; */ +/*description: This field specifies the minimum time (in milliseconds) for which + the link status from the PHY should be up (OKAY) before the LPI pattern can be transmitted to the PHY. The MAC does not transmit the LPI pattern even when the LPIEN bit is set unless the LPI_LS_Timer reaches the programmed terminal count. The default value of the LPI_LS_Timer is 1000 (1 sec) as defined in the IEEE standard.*/ +#define EMAC_LPI_LS_TIMER 0x000003FF +#define EMAC_LPI_LS_TIMER_M ((EMAC_LPI_LS_TIMER_V)<<(EMAC_LPI_LS_TIMER_S)) +#define EMAC_LPI_LS_TIMER_V 0x3FF +#define EMAC_LPI_LS_TIMER_S 16 +/* EMAC_LPI_TW_TIMER : R/W ;bitpos:[15:0] ;default: 16'h0 ; */ +/*description: This field specifies the minimum time (in microseconds) for which + the MAC waits after it stops transmitting the LPI pattern to the PHY and before it resumes the normal transmission. The TLPIEX status bit is set after the expiry of this timer.*/ +#define EMAC_LPI_TW_TIMER 0x0000FFFF +#define EMAC_LPI_TW_TIMER_M ((EMAC_LPI_TW_TIMER_V)<<(EMAC_LPI_TW_TIMER_S)) +#define EMAC_LPI_TW_TIMER_V 0xFFFF +#define EMAC_LPI_TW_TIMER_S 0 + +#define EMAC_INTS_REG (DR_REG_EMAC_BASE + 0x1038) +/* EMAC_LPIIS : RO ;bitpos:[10] ;default: 1'h0 ; */ +/*description: When the Energy Efficient Ethernet feature is enabled this bit + is set for any LPI state entry or exit in the MAC Transmitter or Receiver. This bit is cleared on reading Bit[0] of Register (LPI Control and Status Register).*/ +#define EMAC_LPIIS (BIT(10)) +#define EMAC_LPIIS_M (BIT(10)) +#define EMAC_LPIIS_V 0x1 +#define EMAC_LPIIS_S 10 +/* EMAC_PMTINTS : RO ;bitpos:[3] ;default: 1'h0 ; */ +/*description: This bit is set when a magic packet or remote wake-up frame is + received in the power-down mode (see Bit[5] and Bit[6] in the PMT Control and Status Register). This bit is cleared when both Bits[6:5] are cleared because of a read operation to the PMT Control and Status register. This bit is valid only when you select the optional PMT module during core configuration.*/ +#define EMAC_PMTINTS (BIT(3)) +#define EMAC_PMTINTS_M (BIT(3)) +#define EMAC_PMTINTS_V 0x1 +#define EMAC_PMTINTS_S 3 + +#define EMAC_INTMASK_REG (DR_REG_EMAC_BASE + 0x103C) +/* EMAC_LPIINTMASK : R/W ;bitpos:[10] ;default: 1'h0 ; */ +/*description: When set this bit disables the assertion of the interrupt signal + because of the setting of the LPI Interrupt Status bit in Register (Interrupt Status Register).*/ +#define EMAC_LPIINTMASK (BIT(10)) +#define EMAC_LPIINTMASK_M (BIT(10)) +#define EMAC_LPIINTMASK_V 0x1 +#define EMAC_LPIINTMASK_S 10 +/* EMAC_PMTINTMASK : R/W ;bitpos:[3] ;default: 1'h0 ; */ +/*description: When set this bit disables the assertion of the interrupt signal + because of the setting of PMT Interrupt Status bit in Register (Interrupt Status Register).*/ +#define EMAC_PMTINTMASK (BIT(3)) +#define EMAC_PMTINTMASK_M (BIT(3)) +#define EMAC_PMTINTMASK_V 0x1 +#define EMAC_PMTINTMASK_S 3 + +#define EMAC_ADDR0HIGH_REG (DR_REG_EMAC_BASE + 0x1040) +/* EMAC_ADDRESS_ENABLE0 : RO ;bitpos:[31] ;default: 1'h0 ; */ +/*description: This bit is always set to 1.*/ +#define EMAC_ADDRESS_ENABLE0 (BIT(31)) +#define EMAC_ADDRESS_ENABLE0_M (BIT(31)) +#define EMAC_ADDRESS_ENABLE0_V 0x1 +#define EMAC_ADDRESS_ENABLE0_S 31 +/* EMAC_ADDRESS0_HI : R/W ;bitpos:[15:0] ;default: 16'hFFFF ; */ +/*description: This field contains the upper 16 bits (47:32) of the first 6-byte + MAC address.The MAC uses this field for filtering the received frames and inserting the MAC address in the Transmit Flow Control (Pause) Frames.*/ +#define EMAC_ADDRESS0_HI 0x0000FFFF +#define EMAC_ADDRESS0_HI_M ((EMAC_ADDRESS0_HI_V)<<(EMAC_ADDRESS0_HI_S)) +#define EMAC_ADDRESS0_HI_V 0xFFFF +#define EMAC_ADDRESS0_HI_S 0 + +#define EMAC_ADDR0LOW_REG (DR_REG_EMAC_BASE + 0x1044) +/* EMAC_MAC_ADDRESS0_LOW : R/W ;bitpos:[31:0] ;default: 32'hFFFFFFFF ; */ +/*description: This field contains the lower 32 bits of the first 6-byte MAC + address. This is used by the MAC for filtering the received frames and inserting the MAC address in the Transmit Flow Control (Pause) Frames.*/ +#define EMAC_MAC_ADDRESS0_LOW 0xFFFFFFFF +#define EMAC_MAC_ADDRESS0_LOW_M ((EMAC_MAC_ADDRESS0_LOW_V)<<(EMAC_MAC_ADDRESS0_LOW_S)) +#define EMAC_MAC_ADDRESS0_LOW_V 0xFFFFFFFF +#define EMAC_MAC_ADDRESS0_LOW_S 0 + +#define EMAC_ADDR1HIGH_REG (DR_REG_EMAC_BASE + 0x1048) +/* EMAC_ADDRESS_ENABLE1 : R/W ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set the address filter module uses the second + MAC address for perfect filtering. When this bit is reset the address filter module ignores the address for filtering.*/ +#define EMAC_ADDRESS_ENABLE1 (BIT(31)) +#define EMAC_ADDRESS_ENABLE1_M (BIT(31)) +#define EMAC_ADDRESS_ENABLE1_V 0x1 +#define EMAC_ADDRESS_ENABLE1_S 31 +/* EMAC_SOURCE_ADDRESS : R/W ;bitpos:[30] ;default: 1'h0 ; */ +/*description: When this bit is set the EMACADDR1[47:0] is used to compare + with the SA fields of the received frame. When this bit is reset the EMACADDR1[47:0] is used to compare with the DA fields of the received frame.*/ +#define EMAC_SOURCE_ADDRESS (BIT(30)) +#define EMAC_SOURCE_ADDRESS_M (BIT(30)) +#define EMAC_SOURCE_ADDRESS_V 0x1 +#define EMAC_SOURCE_ADDRESS_S 30 +/* EMAC_MASK_BYTE_CONTROL : R/W ;bitpos:[29:24] ;default: 6'h0 ; */ +/*description: These bits are mask control bits for comparison of each of the + EMACADDR1 bytes. When set high the MAC does not compare the corresponding byte of received DA or SA with the contents of EMACADDR1 registers. Each bit controls the masking of the bytes as follows: Bit[29]: EMACADDR1 High [15:8]. Bit[28]: EMACADDR1 High [7:0]. Bit[27]: EMACADDR1 Low [31:24]. Bit[24]: EMACADDR1 Low [7:0].You can filter a group of addresses (known as group address filtering) by masking one or more bytes of the address.*/ +#define EMAC_MASK_BYTE_CONTROL 0x0000003F +#define EMAC_MASK_BYTE_CONTROL_M ((EMAC_MASK_BYTE_CONTROL_V)<<(EMAC_MASK_BYTE_CONTROL_S)) +#define EMAC_MASK_BYTE_CONTROL_V 0x3F +#define EMAC_MASK_BYTE_CONTROL_S 24 +/* EMAC_MAC_ADDRESS1_HI : R/W ;bitpos:[15:0] ;default: 16'hFFFF ; */ +/*description: This field contains the upper 16 bits Bits[47:32] of the second + 6-byte MAC Address.*/ +#define EMAC_MAC_ADDRESS1_HI 0x0000FFFF +#define EMAC_MAC_ADDRESS1_HI_M ((EMAC_MAC_ADDRESS1_HI_V)<<(EMAC_MAC_ADDRESS1_HI_S)) +#define EMAC_MAC_ADDRESS1_HI_V 0xFFFF +#define EMAC_MAC_ADDRESS1_HI_S 0 + +#define EMAC_ADDR1LOW_REG (DR_REG_EMAC_BASE + 0x104C) +/* EMAC_MAC_ADDRESS1_LOW : R/W ;bitpos:[31:0] ;default: 32'hFFFFFFFF ; */ +/*description: This field contains the lower 32 bits of the second 6-byte MAC + address.The content of this field is undefined so the register needs to be configured after the initialization Process.*/ +#define EMAC_MAC_ADDRESS1_LOW 0xFFFFFFFF +#define EMAC_MAC_ADDRESS1_LOW_M ((EMAC_MAC_ADDRESS1_LOW_V)<<(EMAC_MAC_ADDRESS1_LOW_S)) +#define EMAC_MAC_ADDRESS1_LOW_V 0xFFFFFFFF +#define EMAC_MAC_ADDRESS1_LOW_S 0 + +#define EMAC_ADDR2HIGH_REG (DR_REG_EMAC_BASE + 0x1050) +/* EMAC_ADDRESS_ENABLE2 : R/W ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set the address filter module uses the third + MAC address for perfect filtering. When this bit is reset the address filter module ignores the address for filtering.*/ +#define EMAC_ADDRESS_ENABLE2 (BIT(31)) +#define EMAC_ADDRESS_ENABLE2_M (BIT(31)) +#define EMAC_ADDRESS_ENABLE2_V 0x1 +#define EMAC_ADDRESS_ENABLE2_S 31 +/* EMAC_SOURCE_ADDRESS2 : R/W ;bitpos:[30] ;default: 1'h0 ; */ +/*description: When this bit is set the EMACADDR2[47:0] is used to compare + with the SA fields of the received frame. When this bit is reset the EMACADDR2[47:0] is used to compare with the DA fields of the received frame.*/ +#define EMAC_SOURCE_ADDRESS2 (BIT(30)) +#define EMAC_SOURCE_ADDRESS2_M (BIT(30)) +#define EMAC_SOURCE_ADDRESS2_V 0x1 +#define EMAC_SOURCE_ADDRESS2_S 30 +/* EMAC_MASK_BYTE_CONTROL2 : R/W ;bitpos:[29:24] ;default: 6'h0 ; */ +/*description: These bits are mask control bits for comparison of each of the + EMACADDR2 bytes. When set high the MAC does not compare the corresponding byte of received DA or SA with the contents of EMACADDR2 registers. Each bit controls the masking of the bytes as follows: Bit[29]: EMACADDR2 High [15:8]. Bit[28]: EMACADDR2 High [7:0]. Bit[27]: EMACADDR2 Low [31:24]. Bit[24]: EMACADDR2 Low [7:0].You can filter a group of addresses (known as group address filtering) by masking one or more bytes of the address.*/ +#define EMAC_MASK_BYTE_CONTROL2 0x0000003F +#define EMAC_MASK_BYTE_CONTROL2_M ((EMAC_MASK_BYTE_CONTROL2_V)<<(EMAC_MASK_BYTE_CONTROL2_S)) +#define EMAC_MASK_BYTE_CONTROL2_V 0x3F +#define EMAC_MASK_BYTE_CONTROL2_S 24 +/* EMAC_MAC_ADDRESS2_HI : R/W ;bitpos:[15:0] ;default: 16'hFFFF ; */ +/*description: This field contains the upper 16 bits Bits[47:32] of the third + 6-byte MAC address.*/ +#define EMAC_MAC_ADDRESS2_HI 0x0000FFFF +#define EMAC_MAC_ADDRESS2_HI_M ((EMAC_MAC_ADDRESS2_HI_V)<<(EMAC_MAC_ADDRESS2_HI_S)) +#define EMAC_MAC_ADDRESS2_HI_V 0xFFFF +#define EMAC_MAC_ADDRESS2_HI_S 0 + +#define EMAC_ADDR2LOW_REG (DR_REG_EMAC_BASE + 0x1054) +/* EMAC_MAC_ADDRESS2_LOW : R/W ;bitpos:[31:0] ;default: 32'hFFFFFFFF ; */ +/*description: This field contains the lower 32 bits of the third 6-byte MAC + address. The content of this field is undefined so the register needs to be configured after the initialization process.*/ +#define EMAC_MAC_ADDRESS2_LOW 0xFFFFFFFF +#define EMAC_MAC_ADDRESS2_LOW_M ((EMAC_MAC_ADDRESS2_LOW_V)<<(EMAC_MAC_ADDRESS2_LOW_S)) +#define EMAC_MAC_ADDRESS2_LOW_V 0xFFFFFFFF +#define EMAC_MAC_ADDRESS2_LOW_S 0 + +#define EMAC_ADDR3HIGH_REG (DR_REG_EMAC_BASE + 0x1058) +/* EMAC_ADDRESS_ENABLE3 : R/W ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set the address filter module uses the fourth + MAC address for perfect filtering. When this bit is reset the address filter module ignores the address for filtering.*/ +#define EMAC_ADDRESS_ENABLE3 (BIT(31)) +#define EMAC_ADDRESS_ENABLE3_M (BIT(31)) +#define EMAC_ADDRESS_ENABLE3_V 0x1 +#define EMAC_ADDRESS_ENABLE3_S 31 +/* EMAC_SOURCE_ADDRESS3 : R/W ;bitpos:[30] ;default: 1'h0 ; */ +/*description: When this bit is set the EMACADDR3[47:0] is used to compare + with the SA fields of the received frame. When this bit is reset the EMACADDR3[47:0] is used to compare with the DA fields of the received frame.*/ +#define EMAC_SOURCE_ADDRESS3 (BIT(30)) +#define EMAC_SOURCE_ADDRESS3_M (BIT(30)) +#define EMAC_SOURCE_ADDRESS3_V 0x1 +#define EMAC_SOURCE_ADDRESS3_S 30 +/* EMAC_MASK_BYTE_CONTROL3 : R/W ;bitpos:[29:24] ;default: 6'h0 ; */ +/*description: These bits are mask control bits for comparison of each of the + EMACADDR3 bytes. When set high the MAC does not compare the corresponding byte of received DA or SA with the contents of EMACADDR3 registers. Each bit controls the masking of the bytes as follows: Bit[29]: EMACADDR3 High [15:8]. Bit[28]: EMACADDR3 High [7:0]. Bit[27]: EMACADDR3 Low [31:24]. Bit[24]: EMACADDR3 Low [7:0].You can filter a group of addresses (known as group address filtering) by masking one or more bytes of the address.*/ +#define EMAC_MASK_BYTE_CONTROL3 0x0000003F +#define EMAC_MASK_BYTE_CONTROL3_M ((EMAC_MASK_BYTE_CONTROL3_V)<<(EMAC_MASK_BYTE_CONTROL3_S)) +#define EMAC_MASK_BYTE_CONTROL3_V 0x3F +#define EMAC_MASK_BYTE_CONTROL3_S 24 +/* EMAC_MAC_ADDRESS3_HI : R/W ;bitpos:[15:0] ;default: 16'hFFFF ; */ +/*description: This field contains the upper 16 bits Bits[47:32] of the fourth + 6-byte MAC address.*/ +#define EMAC_MAC_ADDRESS3_HI 0x0000FFFF +#define EMAC_MAC_ADDRESS3_HI_M ((EMAC_MAC_ADDRESS3_HI_V)<<(EMAC_MAC_ADDRESS3_HI_S)) +#define EMAC_MAC_ADDRESS3_HI_V 0xFFFF +#define EMAC_MAC_ADDRESS3_HI_S 0 + +#define EMAC_ADDR3LOW_REG (DR_REG_EMAC_BASE + 0x105C) +/* EMAC_MAC_ADDRESS3_LOW : R/W ;bitpos:[31:0] ;default: 32'hFFFFFFFF ; */ +/*description: This field contains the lower 32 bits of the fourth 6-byte MAC + address.The content of this field is undefined so the register needs to be configured after the initialization Process.*/ +#define EMAC_MAC_ADDRESS3_LOW 0xFFFFFFFF +#define EMAC_MAC_ADDRESS3_LOW_M ((EMAC_MAC_ADDRESS3_LOW_V)<<(EMAC_MAC_ADDRESS3_LOW_S)) +#define EMAC_MAC_ADDRESS3_LOW_V 0xFFFFFFFF +#define EMAC_MAC_ADDRESS3_LOW_S 0 + +#define EMAC_ADDR4HIGH_REG (DR_REG_EMAC_BASE + 0x1060) +/* EMAC_ADDRESS_ENABLE4 : R/W ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set the address filter module uses the fifth + MAC address for perfect filtering. When this bit is reset the address filter module ignores the address for filtering.*/ +#define EMAC_ADDRESS_ENABLE4 (BIT(31)) +#define EMAC_ADDRESS_ENABLE4_M (BIT(31)) +#define EMAC_ADDRESS_ENABLE4_V 0x1 +#define EMAC_ADDRESS_ENABLE4_S 31 +/* EMAC_SOURCE_ADDRESS4 : R/W ;bitpos:[30] ;default: 1'h0 ; */ +/*description: When this bit is set the EMACADDR4[47:0] is used to compare + with the SA fields of the received frame. When this bit is reset the EMACADDR4[47:0] is used to compare with the DA fields of the received frame.*/ +#define EMAC_SOURCE_ADDRESS4 (BIT(30)) +#define EMAC_SOURCE_ADDRESS4_M (BIT(30)) +#define EMAC_SOURCE_ADDRESS4_V 0x1 +#define EMAC_SOURCE_ADDRESS4_S 30 +/* EMAC_MASK_BYTE_CONTROL4 : R/W ;bitpos:[29:24] ;default: 6'h0 ; */ +/*description: These bits are mask control bits for comparison of each of the + EMACADDR4 bytes. When set high the MAC does not compare the corresponding byte of received DA or SA with the contents of EMACADDR4 registers. Each bit controls the masking of the bytes as follows: Bit[29]: EMACADDR4 High [15:8]. Bit[28]: EMACADDR4 High [7:0]. Bit[27]: EMACADDR4 Low [31:24]. Bit[24]: EMACADDR4 Low [7:0].You can filter a group of addresses (known as group address filtering) by masking one or more bytes of the address.*/ +#define EMAC_MASK_BYTE_CONTROL4 0x0000003F +#define EMAC_MASK_BYTE_CONTROL4_M ((EMAC_MASK_BYTE_CONTROL4_V)<<(EMAC_MASK_BYTE_CONTROL4_S)) +#define EMAC_MASK_BYTE_CONTROL4_V 0x3F +#define EMAC_MASK_BYTE_CONTROL4_S 24 +/* EMAC_MAC_ADDRESS4_HI : R/W ;bitpos:[15:0] ;default: 16'hFFFF ; */ +/*description: This field contains the upper 16 bits Bits[47:32] of the fifth + 6-byte MAC address.*/ +#define EMAC_MAC_ADDRESS4_HI 0x0000FFFF +#define EMAC_MAC_ADDRESS4_HI_M ((EMAC_MAC_ADDRESS4_HI_V)<<(EMAC_MAC_ADDRESS4_HI_S)) +#define EMAC_MAC_ADDRESS4_HI_V 0xFFFF +#define EMAC_MAC_ADDRESS4_HI_S 0 + +#define EMAC_ADDR4LOW_REG (DR_REG_EMAC_BASE + 0x1064) +/* EMAC_MAC_ADDRESS4_LOW : R/W ;bitpos:[31:0] ;default: 32'hFFFFFFFF ; */ +/*description: This field contains the lower 32 bits of the fifth 6-byte MAC + address. The content of this field is undefined so the register needs to be configured after the initialization process.*/ +#define EMAC_MAC_ADDRESS4_LOW 0xFFFFFFFF +#define EMAC_MAC_ADDRESS4_LOW_M ((EMAC_MAC_ADDRESS4_LOW_V)<<(EMAC_MAC_ADDRESS4_LOW_S)) +#define EMAC_MAC_ADDRESS4_LOW_V 0xFFFFFFFF +#define EMAC_MAC_ADDRESS4_LOW_S 0 + +#define EMAC_ADDR5HIGH_REG (DR_REG_EMAC_BASE + 0x1068) +/* EMAC_ADDRESS_ENABLE5 : R/W ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set the address filter module uses the sixth + MAC address for perfect filtering. When this bit is reset the address filter module ignores the address for filtering.*/ +#define EMAC_ADDRESS_ENABLE5 (BIT(31)) +#define EMAC_ADDRESS_ENABLE5_M (BIT(31)) +#define EMAC_ADDRESS_ENABLE5_V 0x1 +#define EMAC_ADDRESS_ENABLE5_S 31 +/* EMAC_SOURCE_ADDRESS5 : R/W ;bitpos:[30] ;default: 1'h0 ; */ +/*description: When this bit is set the EMACADDR5[47:0] is used to compare + with the SA fields of the received frame. When this bit is reset the EMACADDR5[47:0] is used to compare with the DA fields of the received frame.*/ +#define EMAC_SOURCE_ADDRESS5 (BIT(30)) +#define EMAC_SOURCE_ADDRESS5_M (BIT(30)) +#define EMAC_SOURCE_ADDRESS5_V 0x1 +#define EMAC_SOURCE_ADDRESS5_S 30 +/* EMAC_MASK_BYTE_CONTROL5 : R/W ;bitpos:[29:24] ;default: 6'h0 ; */ +/*description: These bits are mask control bits for comparison of each of the + EMACADDR5 bytes. When set high the MAC does not compare the corresponding byte of received DA or SA with the contents of EMACADDR5 registers. Each bit controls the masking of the bytes as follows: Bit[29]: EMACADDR5 High [15:8]. Bit[28]: EMACADDR5 High [7:0]. Bit[27]: EMACADDR5 Low [31:24]. Bit[24]: EMACADDR5 Low [7:0].You can filter a group of addresses (known as group address filtering) by masking one or more bytes of the address.*/ +#define EMAC_MASK_BYTE_CONTROL5 0x0000003F +#define EMAC_MASK_BYTE_CONTROL5_M ((EMAC_MASK_BYTE_CONTROL5_V)<<(EMAC_MASK_BYTE_CONTROL5_S)) +#define EMAC_MASK_BYTE_CONTROL5_V 0x3F +#define EMAC_MASK_BYTE_CONTROL5_S 24 +/* EMAC_MAC_ADDRESS5_HI : R/W ;bitpos:[15:0] ;default: 16'hFFFF ; */ +/*description: This field contains the upper 16 bits Bits[47:32] of the sixth + 6-byte MAC address.*/ +#define EMAC_MAC_ADDRESS5_HI 0x0000FFFF +#define EMAC_MAC_ADDRESS5_HI_M ((EMAC_MAC_ADDRESS5_HI_V)<<(EMAC_MAC_ADDRESS5_HI_S)) +#define EMAC_MAC_ADDRESS5_HI_V 0xFFFF +#define EMAC_MAC_ADDRESS5_HI_S 0 + +#define EMAC_ADDR5LOW_REG (DR_REG_EMAC_BASE + 0x106C) +/* EMAC_MAC_ADDRESS5_LOW : R/W ;bitpos:[31:0] ;default: 32'hFFFFFFFF ; */ +/*description: This field contains the lower 32 bits of the sixth 6-byte MAC + address. The content of this field is undefined so the register needs to be configured after the initialization process.*/ +#define EMAC_MAC_ADDRESS5_LOW 0xFFFFFFFF +#define EMAC_MAC_ADDRESS5_LOW_M ((EMAC_MAC_ADDRESS5_LOW_V)<<(EMAC_MAC_ADDRESS5_LOW_S)) +#define EMAC_MAC_ADDRESS5_LOW_V 0xFFFFFFFF +#define EMAC_MAC_ADDRESS5_LOW_S 0 + +#define EMAC_ADDR6HIGH_REG (DR_REG_EMAC_BASE + 0x1070) +/* EMAC_ADDRESS_ENABLE6 : R/W ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set the address filter module uses the seventh + MAC address for perfect filtering. When this bit is reset the address filter module ignores the address for filtering.*/ +#define EMAC_ADDRESS_ENABLE6 (BIT(31)) +#define EMAC_ADDRESS_ENABLE6_M (BIT(31)) +#define EMAC_ADDRESS_ENABLE6_V 0x1 +#define EMAC_ADDRESS_ENABLE6_S 31 +/* EMAC_SOURCE_ADDRESS6 : R/W ;bitpos:[30] ;default: 1'h0 ; */ +/*description: When this bit is set the EMACADDR6[47:0] is used to compare + with the SA fields of the received frame. When this bit is reset the EMACADDR6[47:0] is used to compare with the DA fields of the received frame.*/ +#define EMAC_SOURCE_ADDRESS6 (BIT(30)) +#define EMAC_SOURCE_ADDRESS6_M (BIT(30)) +#define EMAC_SOURCE_ADDRESS6_V 0x1 +#define EMAC_SOURCE_ADDRESS6_S 30 +/* EMAC_MASK_BYTE_CONTROL6 : R/W ;bitpos:[29:24] ;default: 6'h0 ; */ +/*description: These bits are mask control bits for comparison of each of the + EMACADDR6 bytes. When set high the MAC does not compare the corresponding byte of received DA or SA with the contents of EMACADDR6 registers. Each bit controls the masking of the bytes as follows: Bit[29]: EMACADDR6 High [15:8]. Bit[28]: EMACADDR6 High [7:0]. Bit[27]: EMACADDR6 Low [31:24]. Bit[24]: EMACADDR6 Low [7:0].You can filter a group of addresses (known as group address filtering) by masking one or more bytes of the address.*/ +#define EMAC_MASK_BYTE_CONTROL6 0x0000003F +#define EMAC_MASK_BYTE_CONTROL6_M ((EMAC_MASK_BYTE_CONTROL6_V)<<(EMAC_MASK_BYTE_CONTROL6_S)) +#define EMAC_MASK_BYTE_CONTROL6_V 0x3F +#define EMAC_MASK_BYTE_CONTROL6_S 24 +/* EMAC_MAC_ADDRESS6_HI : R/W ;bitpos:[15:0] ;default: 16'hFFFF ; */ +/*description: This field contains the upper 16 bits Bits[47:32] of the seventh + 6-byte MAC Address.*/ +#define EMAC_MAC_ADDRESS6_HI 0x0000FFFF +#define EMAC_MAC_ADDRESS6_HI_M ((EMAC_MAC_ADDRESS6_HI_V)<<(EMAC_MAC_ADDRESS6_HI_S)) +#define EMAC_MAC_ADDRESS6_HI_V 0xFFFF +#define EMAC_MAC_ADDRESS6_HI_S 0 + +#define EMAC_ADDR6LOW_REG (DR_REG_EMAC_BASE + 0x1074) +/* EMAC_MAC_ADDRESS6_LOW : R/W ;bitpos:[31:0] ;default: 32'hFFFFFFFF ; */ +/*description: This field contains the lower 32 bits of the seventh 6-byte MAC + address.The content of this field is undefined so the register needs to be configured after the initialization Process.*/ +#define EMAC_MAC_ADDRESS6_LOW 0xFFFFFFFF +#define EMAC_MAC_ADDRESS6_LOW_M ((EMAC_MAC_ADDRESS6_LOW_V)<<(EMAC_MAC_ADDRESS6_LOW_S)) +#define EMAC_MAC_ADDRESS6_LOW_V 0xFFFFFFFF +#define EMAC_MAC_ADDRESS6_LOW_S 0 + +#define EMAC_ADDR7HIGH_REG (DR_REG_EMAC_BASE + 0x1078) +/* EMAC_ADDRESS_ENABLE7 : R/W ;bitpos:[31] ;default: 1'h0 ; */ +/*description: When this bit is set the address filter module uses the eighth + MAC address for perfect filtering. When this bit is reset the address filter module ignores the address for filtering.*/ +#define EMAC_ADDRESS_ENABLE7 (BIT(31)) +#define EMAC_ADDRESS_ENABLE7_M (BIT(31)) +#define EMAC_ADDRESS_ENABLE7_V 0x1 +#define EMAC_ADDRESS_ENABLE7_S 31 +/* EMAC_SOURCE_ADDRESS7 : R/W ;bitpos:[30] ;default: 1'h0 ; */ +/*description: When this bit is set the EMACADDR7[47:0] is used to compare + with the SA fields of the received frame. When this bit is reset the EMACADDR7[47:0] is used to compare with the DA fields of the received frame.*/ +#define EMAC_SOURCE_ADDRESS7 (BIT(30)) +#define EMAC_SOURCE_ADDRESS7_M (BIT(30)) +#define EMAC_SOURCE_ADDRESS7_V 0x1 +#define EMAC_SOURCE_ADDRESS7_S 30 +/* EMAC_MASK_BYTE_CONTROL7 : R/W ;bitpos:[29:24] ;default: 6'h0 ; */ +/*description: These bits are mask control bits for comparison of each of the + EMACADDR7 bytes. When set high the MAC does not compare the corresponding byte of received DA or SA with the contents of EMACADDR7 registers. Each bit controls the masking of the bytes as follows: Bit[29]: EMACADDR7 High [15:8]. Bit[28]: EMACADDR7 High [7:0]. Bit[27]: EMACADDR7 Low [31:24]. Bit[24]: EMACADDR7 Low [7:0].You can filter a group of addresses (known as group address filtering) by masking one or more bytes of the address.*/ +#define EMAC_MASK_BYTE_CONTROL7 0x0000003F +#define EMAC_MASK_BYTE_CONTROL7_M ((EMAC_MASK_BYTE_CONTROL7_V)<<(EMAC_MASK_BYTE_CONTROL7_S)) +#define EMAC_MASK_BYTE_CONTROL7_V 0x3F +#define EMAC_MASK_BYTE_CONTROL7_S 24 +/* EMAC_MAC_ADDRESS7_HI : R/W ;bitpos:[15:0] ;default: 16'hFFFF ; */ +/*description: This field contains the upper 16 bits Bits[47:32] of the eighth + 6-byte MAC Address.*/ +#define EMAC_MAC_ADDRESS7_HI 0x0000FFFF +#define EMAC_MAC_ADDRESS7_HI_M ((EMAC_MAC_ADDRESS7_HI_V)<<(EMAC_MAC_ADDRESS7_HI_S)) +#define EMAC_MAC_ADDRESS7_HI_V 0xFFFF +#define EMAC_MAC_ADDRESS7_HI_S 0 + +#define EMAC_ADDR7LOW_REG (DR_REG_EMAC_BASE + 0x107C) +/* EMAC_MAC_ADDRESS7_LOW : R/W ;bitpos:[31:0] ;default: 32'hFFFFFFFF ; */ +/*description: This field contains the lower 32 bits of the eighth 6-byte MAC + address.The content of this field is undefined so the register needs to be configured after the initialization Process.*/ +#define EMAC_MAC_ADDRESS7_LOW 0xFFFFFFFF +#define EMAC_MAC_ADDRESS7_LOW_M ((EMAC_MAC_ADDRESS7_LOW_V)<<(EMAC_MAC_ADDRESS7_LOW_S)) +#define EMAC_MAC_ADDRESS7_LOW_V 0xFFFFFFFF +#define EMAC_MAC_ADDRESS7_LOW_S 0 + +#define EMAC_CSTATUS_REG (DR_REG_EMAC_BASE + 0x10D8) +/* EMAC_JABBER_TIMEOUT : RO ;bitpos:[4] ;default: 1'h0 ; */ +/*description: This bit indicates whether there is jabber timeout error (1'b1) + in the received Frame.*/ +#define EMAC_JABBER_TIMEOUT (BIT(4)) +#define EMAC_JABBER_TIMEOUT_M (BIT(4)) +#define EMAC_JABBER_TIMEOUT_V 0x1 +#define EMAC_JABBER_TIMEOUT_S 4 +/* EMAC_LINK_SPEED : RO ;bitpos:[2:1] ;default: 1'h0 ; */ +/*description: This bit indicates the current speed of the link: 2'b00: 2.5 + MHz. 2'b01: 25 MHz. 2'b10: 125 MHz.*/ +#define EMAC_LINK_SPEED 0x00000003 +#define EMAC_LINK_SPEED_M ((EMAC_LINK_SPEED_V)<<(EMAC_LINK_SPEED_S)) +#define EMAC_LINK_SPEED_V 0x3 +#define EMAC_LINK_SPEED_S 1 +/* EMAC_LINK_MODE : RO ;bitpos:[0] ;default: 1'h0 ; */ +/*description: This bit indicates the current mode of operation of the link: + 1'b0: Half-duplex mode. 1'b1: Full-duplex mode.*/ +#define EMAC_LINK_MODE (BIT(0)) +#define EMAC_LINK_MODE_M (BIT(0)) +#define EMAC_LINK_MODE_V 0x1 +#define EMAC_LINK_MODE_S 0 + +#define EMAC_WDOGTO_REG (DR_REG_EMAC_BASE + 0x10DC) +/* EMAC_PWDOGEN : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: When this bit is set and Bit[23] (WD) of EMACCONFIG_REG is reset + the WTO field (Bits[13:0]) is used as watchdog timeout for a received frame. When this bit is cleared the watchdog timeout for a received frame is controlled by the setting of Bit[23] (WD) and Bit[20] (JE) in EMACCONFIG_REG.*/ +#define EMAC_PWDOGEN (BIT(16)) +#define EMAC_PWDOGEN_M (BIT(16)) +#define EMAC_PWDOGEN_V 0x1 +#define EMAC_PWDOGEN_S 16 +/* EMAC_WDOGTO : R/W ;bitpos:[13:0] ;default: 14'h0 ; */ +/*description: When Bit[16] (PWE) is set and Bit[23] (WD) of EMACCONFIG_REG + is reset this field is used as watchdog timeout for a received frame. If the length of a received frame exceeds the value of this field such frame is terminated and declared as an error frame.*/ +#define EMAC_WDOGTO 0x00003FFF +#define EMAC_WDOGTO_M ((EMAC_WDOGTO_V)<<(EMAC_WDOGTO_S)) +#define EMAC_WDOGTO_V 0x3FFF +#define EMAC_WDOGTO_S 0 #ifdef __cplusplus } #endif -#endif + + +#endif /*_SOC_EMAC_REG_H_ */ + diff --git a/tools/sdk/include/soc/soc/gpio_periph.h b/tools/sdk/include/soc/soc/gpio_periph.h new file mode 100644 index 00000000000..93b23f42772 --- /dev/null +++ b/tools/sdk/include/soc/soc/gpio_periph.h @@ -0,0 +1,35 @@ +// 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 _SOC_GPIO_PERIPH_H +#define _SOC_GPIO_PERIPH_H +#include "stdint.h" +#include "soc/gpio_pins.h" +#include "soc/io_mux_reg.h" +#include "soc/gpio_struct.h" +#include "soc/gpio_reg.h" +#include "soc/gpio_sig_map.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +extern const uint32_t GPIO_PIN_MUX_REG[GPIO_PIN_COUNT]; + +#ifdef __cplusplus +} +#endif + +#endif // _SOC_GPIO_PERIPH_H diff --git a/tools/sdk/include/soc/soc/gpio_pins.h b/tools/sdk/include/soc/soc/gpio_pins.h new file mode 100644 index 00000000000..6c2bfb7418f --- /dev/null +++ b/tools/sdk/include/soc/soc/gpio_pins.h @@ -0,0 +1,28 @@ +// 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 _GPIO_PINS_H +#define _GPIO_PINS_H +#ifdef __cplusplus +extern "C" +{ +#endif + +#define GPIO_PIN_COUNT 40 + +#ifdef __cplusplus +} +#endif + +#endif // _GPIO_PINS_H diff --git a/tools/sdk/include/soc/soc/hinf_reg.h b/tools/sdk/include/soc/soc/hinf_reg.h new file mode 100644 index 00000000000..aad357864eb --- /dev/null +++ b/tools/sdk/include/soc/soc/hinf_reg.h @@ -0,0 +1,248 @@ +// 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 _SOC_HINF_REG_H_ +#define _SOC_HINF_REG_H_ + + +#include "soc.h" +#define HINF_CFG_DATA0_REG (DR_REG_HINF_BASE + 0x0) +/* HINF_DEVICE_ID_FN1 : R/W ;bitpos:[31:16] ;default: 16'h2222 ; */ +/*description: */ +#define HINF_DEVICE_ID_FN1 0x0000FFFF +#define HINF_DEVICE_ID_FN1_M ((HINF_DEVICE_ID_FN1_V)<<(HINF_DEVICE_ID_FN1_S)) +#define HINF_DEVICE_ID_FN1_V 0xFFFF +#define HINF_DEVICE_ID_FN1_S 16 +/* HINF_USER_ID_FN1 : R/W ;bitpos:[15:0] ;default: 16'h6666 ; */ +/*description: */ +#define HINF_USER_ID_FN1 0x0000FFFF +#define HINF_USER_ID_FN1_M ((HINF_USER_ID_FN1_V)<<(HINF_USER_ID_FN1_S)) +#define HINF_USER_ID_FN1_V 0xFFFF +#define HINF_USER_ID_FN1_S 0 + +#define HINF_CFG_DATA1_REG (DR_REG_HINF_BASE + 0x4) +/* HINF_SDIO20_CONF1 : R/W ;bitpos:[31:29] ;default: 3'h0 ; */ +/*description: */ +#define HINF_SDIO20_CONF1 0x00000007 +#define HINF_SDIO20_CONF1_M ((HINF_SDIO20_CONF1_V)<<(HINF_SDIO20_CONF1_S)) +#define HINF_SDIO20_CONF1_V 0x7 +#define HINF_SDIO20_CONF1_S 29 +/* HINF_FUNC2_EPS : RO ;bitpos:[28] ;default: 1'b0 ; */ +/*description: */ +#define HINF_FUNC2_EPS (BIT(28)) +#define HINF_FUNC2_EPS_M (BIT(28)) +#define HINF_FUNC2_EPS_V 0x1 +#define HINF_FUNC2_EPS_S 28 +/* HINF_SDIO_VER : R/W ;bitpos:[27:16] ;default: 12'h111 ; */ +/*description: */ +#define HINF_SDIO_VER 0x00000FFF +#define HINF_SDIO_VER_M ((HINF_SDIO_VER_V)<<(HINF_SDIO_VER_S)) +#define HINF_SDIO_VER_V 0xFFF +#define HINF_SDIO_VER_S 16 +/* HINF_SDIO20_CONF0 : R/W ;bitpos:[15:12] ;default: 4'b0 ; */ +/*description: */ +#define HINF_SDIO20_CONF0 0x0000000F +#define HINF_SDIO20_CONF0_M ((HINF_SDIO20_CONF0_V)<<(HINF_SDIO20_CONF0_S)) +#define HINF_SDIO20_CONF0_V 0xF +#define HINF_SDIO20_CONF0_S 12 +/* HINF_IOENABLE1 : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HINF_IOENABLE1 (BIT(11)) +#define HINF_IOENABLE1_M (BIT(11)) +#define HINF_IOENABLE1_V 0x1 +#define HINF_IOENABLE1_S 11 +/* HINF_EMP : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HINF_EMP (BIT(10)) +#define HINF_EMP_M (BIT(10)) +#define HINF_EMP_V 0x1 +#define HINF_EMP_S 10 +/* HINF_FUNC1_EPS : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HINF_FUNC1_EPS (BIT(9)) +#define HINF_FUNC1_EPS_M (BIT(9)) +#define HINF_FUNC1_EPS_V 0x1 +#define HINF_FUNC1_EPS_S 9 +/* HINF_CD_DISABLE : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HINF_CD_DISABLE (BIT(8)) +#define HINF_CD_DISABLE_M (BIT(8)) +#define HINF_CD_DISABLE_V 0x1 +#define HINF_CD_DISABLE_S 8 +/* HINF_IOENABLE2 : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HINF_IOENABLE2 (BIT(7)) +#define HINF_IOENABLE2_M (BIT(7)) +#define HINF_IOENABLE2_V 0x1 +#define HINF_IOENABLE2_S 7 +/* HINF_SDIO_INT_MASK : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HINF_SDIO_INT_MASK (BIT(6)) +#define HINF_SDIO_INT_MASK_M (BIT(6)) +#define HINF_SDIO_INT_MASK_V 0x1 +#define HINF_SDIO_INT_MASK_S 6 +/* HINF_SDIO_IOREADY2 : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HINF_SDIO_IOREADY2 (BIT(5)) +#define HINF_SDIO_IOREADY2_M (BIT(5)) +#define HINF_SDIO_IOREADY2_V 0x1 +#define HINF_SDIO_IOREADY2_S 5 +/* HINF_SDIO_CD_ENABLE : R/W ;bitpos:[4] ;default: 1'b1 ; */ +/*description: */ +#define HINF_SDIO_CD_ENABLE (BIT(4)) +#define HINF_SDIO_CD_ENABLE_M (BIT(4)) +#define HINF_SDIO_CD_ENABLE_V 0x1 +#define HINF_SDIO_CD_ENABLE_S 4 +/* HINF_HIGHSPEED_MODE : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HINF_HIGHSPEED_MODE (BIT(3)) +#define HINF_HIGHSPEED_MODE_M (BIT(3)) +#define HINF_HIGHSPEED_MODE_V 0x1 +#define HINF_HIGHSPEED_MODE_S 3 +/* HINF_HIGHSPEED_ENABLE : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HINF_HIGHSPEED_ENABLE (BIT(2)) +#define HINF_HIGHSPEED_ENABLE_M (BIT(2)) +#define HINF_HIGHSPEED_ENABLE_V 0x1 +#define HINF_HIGHSPEED_ENABLE_S 2 +/* HINF_SDIO_IOREADY1 : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HINF_SDIO_IOREADY1 (BIT(1)) +#define HINF_SDIO_IOREADY1_M (BIT(1)) +#define HINF_SDIO_IOREADY1_V 0x1 +#define HINF_SDIO_IOREADY1_S 1 +/* HINF_SDIO_ENABLE : R/W ;bitpos:[0] ;default: 1'b1 ; */ +/*description: */ +#define HINF_SDIO_ENABLE (BIT(0)) +#define HINF_SDIO_ENABLE_M (BIT(0)) +#define HINF_SDIO_ENABLE_V 0x1 +#define HINF_SDIO_ENABLE_S 0 + +#define HINF_CFG_DATA7_REG (DR_REG_HINF_BASE + 0x1C) +/* HINF_SDIO_IOREADY0 : R/W ;bitpos:[17] ;default: 1'b1 ; */ +/*description: */ +#define HINF_SDIO_IOREADY0 (BIT(17)) +#define HINF_SDIO_IOREADY0_M (BIT(17)) +#define HINF_SDIO_IOREADY0_V 0x1 +#define HINF_SDIO_IOREADY0_S 17 +/* HINF_SDIO_RST : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HINF_SDIO_RST (BIT(16)) +#define HINF_SDIO_RST_M (BIT(16)) +#define HINF_SDIO_RST_V 0x1 +#define HINF_SDIO_RST_S 16 +/* HINF_CHIP_STATE : R/W ;bitpos:[15:8] ;default: 8'b0 ; */ +/*description: */ +#define HINF_CHIP_STATE 0x000000FF +#define HINF_CHIP_STATE_M ((HINF_CHIP_STATE_V)<<(HINF_CHIP_STATE_S)) +#define HINF_CHIP_STATE_V 0xFF +#define HINF_CHIP_STATE_S 8 +/* HINF_PIN_STATE : R/W ;bitpos:[7:0] ;default: 8'b0 ; */ +/*description: */ +#define HINF_PIN_STATE 0x000000FF +#define HINF_PIN_STATE_M ((HINF_PIN_STATE_V)<<(HINF_PIN_STATE_S)) +#define HINF_PIN_STATE_V 0xFF +#define HINF_PIN_STATE_S 0 + +#define HINF_CIS_CONF0_REG (DR_REG_HINF_BASE + 0x20) +/* HINF_CIS_CONF_W0 : R/W ;bitpos:[31:0] ;default: 32'hffffffff ; */ +/*description: */ +#define HINF_CIS_CONF_W0 0xFFFFFFFF +#define HINF_CIS_CONF_W0_M ((HINF_CIS_CONF_W0_V)<<(HINF_CIS_CONF_W0_S)) +#define HINF_CIS_CONF_W0_V 0xFFFFFFFF +#define HINF_CIS_CONF_W0_S 0 + +#define HINF_CIS_CONF1_REG (DR_REG_HINF_BASE + 0x24) +/* HINF_CIS_CONF_W1 : R/W ;bitpos:[31:0] ;default: 32'hffffffff ; */ +/*description: */ +#define HINF_CIS_CONF_W1 0xFFFFFFFF +#define HINF_CIS_CONF_W1_M ((HINF_CIS_CONF_W1_V)<<(HINF_CIS_CONF_W1_S)) +#define HINF_CIS_CONF_W1_V 0xFFFFFFFF +#define HINF_CIS_CONF_W1_S 0 + +#define HINF_CIS_CONF2_REG (DR_REG_HINF_BASE + 0x28) +/* HINF_CIS_CONF_W2 : R/W ;bitpos:[31:0] ;default: 32'hffffffff ; */ +/*description: */ +#define HINF_CIS_CONF_W2 0xFFFFFFFF +#define HINF_CIS_CONF_W2_M ((HINF_CIS_CONF_W2_V)<<(HINF_CIS_CONF_W2_S)) +#define HINF_CIS_CONF_W2_V 0xFFFFFFFF +#define HINF_CIS_CONF_W2_S 0 + +#define HINF_CIS_CONF3_REG (DR_REG_HINF_BASE + 0x2C) +/* HINF_CIS_CONF_W3 : R/W ;bitpos:[31:0] ;default: 32'hffffffff ; */ +/*description: */ +#define HINF_CIS_CONF_W3 0xFFFFFFFF +#define HINF_CIS_CONF_W3_M ((HINF_CIS_CONF_W3_V)<<(HINF_CIS_CONF_W3_S)) +#define HINF_CIS_CONF_W3_V 0xFFFFFFFF +#define HINF_CIS_CONF_W3_S 0 + +#define HINF_CIS_CONF4_REG (DR_REG_HINF_BASE + 0x30) +/* HINF_CIS_CONF_W4 : R/W ;bitpos:[31:0] ;default: 32'hffffffff ; */ +/*description: */ +#define HINF_CIS_CONF_W4 0xFFFFFFFF +#define HINF_CIS_CONF_W4_M ((HINF_CIS_CONF_W4_V)<<(HINF_CIS_CONF_W4_S)) +#define HINF_CIS_CONF_W4_V 0xFFFFFFFF +#define HINF_CIS_CONF_W4_S 0 + +#define HINF_CIS_CONF5_REG (DR_REG_HINF_BASE + 0x34) +/* HINF_CIS_CONF_W5 : R/W ;bitpos:[31:0] ;default: 32'hffffffff ; */ +/*description: */ +#define HINF_CIS_CONF_W5 0xFFFFFFFF +#define HINF_CIS_CONF_W5_M ((HINF_CIS_CONF_W5_V)<<(HINF_CIS_CONF_W5_S)) +#define HINF_CIS_CONF_W5_V 0xFFFFFFFF +#define HINF_CIS_CONF_W5_S 0 + +#define HINF_CIS_CONF6_REG (DR_REG_HINF_BASE + 0x38) +/* HINF_CIS_CONF_W6 : R/W ;bitpos:[31:0] ;default: 32'hffffffff ; */ +/*description: */ +#define HINF_CIS_CONF_W6 0xFFFFFFFF +#define HINF_CIS_CONF_W6_M ((HINF_CIS_CONF_W6_V)<<(HINF_CIS_CONF_W6_S)) +#define HINF_CIS_CONF_W6_V 0xFFFFFFFF +#define HINF_CIS_CONF_W6_S 0 + +#define HINF_CIS_CONF7_REG (DR_REG_HINF_BASE + 0x3C) +/* HINF_CIS_CONF_W7 : R/W ;bitpos:[31:0] ;default: 32'hffffffff ; */ +/*description: */ +#define HINF_CIS_CONF_W7 0xFFFFFFFF +#define HINF_CIS_CONF_W7_M ((HINF_CIS_CONF_W7_V)<<(HINF_CIS_CONF_W7_S)) +#define HINF_CIS_CONF_W7_V 0xFFFFFFFF +#define HINF_CIS_CONF_W7_S 0 + +#define HINF_CFG_DATA16_REG (DR_REG_HINF_BASE + 0x40) +/* HINF_DEVICE_ID_FN2 : R/W ;bitpos:[31:16] ;default: 16'h3333 ; */ +/*description: */ +#define HINF_DEVICE_ID_FN2 0x0000FFFF +#define HINF_DEVICE_ID_FN2_M ((HINF_DEVICE_ID_FN2_V)<<(HINF_DEVICE_ID_FN2_S)) +#define HINF_DEVICE_ID_FN2_V 0xFFFF +#define HINF_DEVICE_ID_FN2_S 16 +/* HINF_USER_ID_FN2 : R/W ;bitpos:[15:0] ;default: 16'h6666 ; */ +/*description: */ +#define HINF_USER_ID_FN2 0x0000FFFF +#define HINF_USER_ID_FN2_M ((HINF_USER_ID_FN2_V)<<(HINF_USER_ID_FN2_S)) +#define HINF_USER_ID_FN2_V 0xFFFF +#define HINF_USER_ID_FN2_S 0 + +#define HINF_DATE_REG (DR_REG_HINF_BASE + 0xFC) +/* HINF_SDIO_DATE : R/W ;bitpos:[31:0] ;default: 32'h15030200 ; */ +/*description: */ +#define HINF_SDIO_DATE 0xFFFFFFFF +#define HINF_SDIO_DATE_M ((HINF_SDIO_DATE_V)<<(HINF_SDIO_DATE_S)) +#define HINF_SDIO_DATE_V 0xFFFFFFFF +#define HINF_SDIO_DATE_S 0 + + + + +#endif /*_SOC_HINF_REG_H_ */ + + diff --git a/tools/sdk/include/soc/soc/hinf_struct.h b/tools/sdk/include/soc/soc/hinf_struct.h new file mode 100644 index 00000000000..1c2d9e3b784 --- /dev/null +++ b/tools/sdk/include/soc/soc/hinf_struct.h @@ -0,0 +1,134 @@ +// 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 _SOC_HINF_STRUCT_H_ +#define _SOC_HINF_STRUCT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef volatile struct { + union { + struct { + uint32_t user_id_fn1: 16; + uint32_t device_id_fn1:16; + }; + uint32_t val; + } cfg_data0; + union { + struct { + uint32_t sdio_enable: 1; + uint32_t sdio_ioready1: 1; + uint32_t highspeed_enable: 1; + uint32_t highspeed_mode: 1; + uint32_t sdio_cd_enable: 1; + uint32_t sdio_ioready2: 1; + uint32_t sdio_int_mask: 1; + uint32_t ioenable2: 1; + uint32_t cd_disable: 1; + uint32_t func1_eps: 1; + uint32_t emp: 1; + uint32_t ioenable1: 1; + uint32_t sdio20_conf0: 4; + uint32_t sdio_ver: 12; + uint32_t func2_eps: 1; + uint32_t sdio20_conf1: 3; + }; + uint32_t val; + } cfg_data1; + uint32_t reserved_8; + uint32_t reserved_c; + uint32_t reserved_10; + uint32_t reserved_14; + uint32_t reserved_18; + union { + struct { + uint32_t pin_state: 8; + uint32_t chip_state: 8; + uint32_t sdio_rst: 1; + uint32_t sdio_ioready0: 1; + uint32_t reserved18: 14; + }; + uint32_t val; + } cfg_data7; + uint32_t cis_conf0; /**/ + uint32_t cis_conf1; /**/ + uint32_t cis_conf2; /**/ + uint32_t cis_conf3; /**/ + uint32_t cis_conf4; /**/ + uint32_t cis_conf5; /**/ + uint32_t cis_conf6; /**/ + uint32_t cis_conf7; /**/ + union { + struct { + uint32_t user_id_fn2: 16; + uint32_t device_id_fn2:16; + }; + uint32_t val; + } cfg_data16; + uint32_t reserved_44; + uint32_t reserved_48; + uint32_t reserved_4c; + uint32_t reserved_50; + uint32_t reserved_54; + uint32_t reserved_58; + uint32_t reserved_5c; + uint32_t reserved_60; + uint32_t reserved_64; + uint32_t reserved_68; + uint32_t reserved_6c; + uint32_t reserved_70; + uint32_t reserved_74; + uint32_t reserved_78; + uint32_t reserved_7c; + uint32_t reserved_80; + uint32_t reserved_84; + uint32_t reserved_88; + uint32_t reserved_8c; + uint32_t reserved_90; + uint32_t reserved_94; + uint32_t reserved_98; + uint32_t reserved_9c; + uint32_t reserved_a0; + uint32_t reserved_a4; + uint32_t reserved_a8; + uint32_t reserved_ac; + uint32_t reserved_b0; + uint32_t reserved_b4; + uint32_t reserved_b8; + uint32_t reserved_bc; + uint32_t reserved_c0; + uint32_t reserved_c4; + uint32_t reserved_c8; + uint32_t reserved_cc; + uint32_t reserved_d0; + uint32_t reserved_d4; + uint32_t reserved_d8; + uint32_t reserved_dc; + uint32_t reserved_e0; + uint32_t reserved_e4; + uint32_t reserved_e8; + uint32_t reserved_ec; + uint32_t reserved_f0; + uint32_t reserved_f4; + uint32_t reserved_f8; + uint32_t date; /**/ +} hinf_dev_t; +extern hinf_dev_t HINF; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_HINF_STRUCT_H_ */ diff --git a/tools/sdk/include/soc/soc/host_reg.h b/tools/sdk/include/soc/soc/host_reg.h new file mode 100644 index 00000000000..ef556e21cdc --- /dev/null +++ b/tools/sdk/include/soc/soc/host_reg.h @@ -0,0 +1,3144 @@ +// 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 _SOC_HOST_REG_H_ +#define _SOC_HOST_REG_H_ + + +#include "soc.h" +#define HOST_SLCHOST_FUNC2_0_REG (DR_REG_SLCHOST_BASE + 0x10) +/* HOST_SLC_FUNC2_INT : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC_FUNC2_INT (BIT(24)) +#define HOST_SLC_FUNC2_INT_M (BIT(24)) +#define HOST_SLC_FUNC2_INT_V 0x1 +#define HOST_SLC_FUNC2_INT_S 24 + +#define HOST_SLCHOST_FUNC2_1_REG (DR_REG_SLCHOST_BASE + 0x14) +/* HOST_SLC_FUNC2_INT_EN : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC_FUNC2_INT_EN (BIT(0)) +#define HOST_SLC_FUNC2_INT_EN_M (BIT(0)) +#define HOST_SLC_FUNC2_INT_EN_V 0x1 +#define HOST_SLC_FUNC2_INT_EN_S 0 + +#define HOST_SLCHOST_FUNC2_2_REG (DR_REG_SLCHOST_BASE + 0x20) +/* HOST_SLC_FUNC1_MDSTAT : R/W ;bitpos:[0] ;default: 1'b1 ; */ +/*description: */ +#define HOST_SLC_FUNC1_MDSTAT (BIT(0)) +#define HOST_SLC_FUNC1_MDSTAT_M (BIT(0)) +#define HOST_SLC_FUNC1_MDSTAT_V 0x1 +#define HOST_SLC_FUNC1_MDSTAT_S 0 + +#define HOST_SLCHOST_GPIO_STATUS0_REG (DR_REG_SLCHOST_BASE + 0x34) +/* HOST_GPIO_SDIO_INT0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_INT0 0xFFFFFFFF +#define HOST_GPIO_SDIO_INT0_M ((HOST_GPIO_SDIO_INT0_V)<<(HOST_GPIO_SDIO_INT0_S)) +#define HOST_GPIO_SDIO_INT0_V 0xFFFFFFFF +#define HOST_GPIO_SDIO_INT0_S 0 + +#define HOST_SLCHOST_GPIO_STATUS1_REG (DR_REG_SLCHOST_BASE + 0x38) +/* HOST_GPIO_SDIO_INT1 : RO ;bitpos:[7:0] ;default: 8'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_INT1 0x000000FF +#define HOST_GPIO_SDIO_INT1_M ((HOST_GPIO_SDIO_INT1_V)<<(HOST_GPIO_SDIO_INT1_S)) +#define HOST_GPIO_SDIO_INT1_V 0xFF +#define HOST_GPIO_SDIO_INT1_S 0 + +#define HOST_SLCHOST_GPIO_IN0_REG (DR_REG_SLCHOST_BASE + 0x3C) +/* HOST_GPIO_SDIO_IN0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_IN0 0xFFFFFFFF +#define HOST_GPIO_SDIO_IN0_M ((HOST_GPIO_SDIO_IN0_V)<<(HOST_GPIO_SDIO_IN0_S)) +#define HOST_GPIO_SDIO_IN0_V 0xFFFFFFFF +#define HOST_GPIO_SDIO_IN0_S 0 + +#define HOST_SLCHOST_GPIO_IN1_REG (DR_REG_SLCHOST_BASE + 0x40) +/* HOST_GPIO_SDIO_IN1 : RO ;bitpos:[7:0] ;default: 8'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_IN1 0x000000FF +#define HOST_GPIO_SDIO_IN1_M ((HOST_GPIO_SDIO_IN1_V)<<(HOST_GPIO_SDIO_IN1_S)) +#define HOST_GPIO_SDIO_IN1_V 0xFF +#define HOST_GPIO_SDIO_IN1_S 0 + +#define HOST_SLC0HOST_TOKEN_RDATA_REG (DR_REG_SLCHOST_BASE + 0x44) +/* HOST_SLC0_RX_PF_EOF : RO ;bitpos:[31:28] ;default: 4'h0 ; */ +/*description: */ +#define HOST_SLC0_RX_PF_EOF 0x0000000F +#define HOST_SLC0_RX_PF_EOF_M ((HOST_SLC0_RX_PF_EOF_V)<<(HOST_SLC0_RX_PF_EOF_S)) +#define HOST_SLC0_RX_PF_EOF_V 0xF +#define HOST_SLC0_RX_PF_EOF_S 28 +/* HOST_HOSTSLC0_TOKEN1 : RO ;bitpos:[27:16] ;default: 12'h0 ; */ +/*description: */ +#define HOST_HOSTSLC0_TOKEN1 0x00000FFF +#define HOST_HOSTSLC0_TOKEN1_M ((HOST_HOSTSLC0_TOKEN1_V)<<(HOST_HOSTSLC0_TOKEN1_S)) +#define HOST_HOSTSLC0_TOKEN1_V 0xFFF +#define HOST_HOSTSLC0_TOKEN1_S 16 +/* HOST_SLC0_RX_PF_VALID : RO ;bitpos:[12] ;default: 4'h0 ; */ +/*description: */ +#define HOST_SLC0_RX_PF_VALID (BIT(12)) +#define HOST_SLC0_RX_PF_VALID_M (BIT(12)) +#define HOST_SLC0_RX_PF_VALID_V 0x1 +#define HOST_SLC0_RX_PF_VALID_S 12 +/* HOST_SLC0_TOKEN0 : RO ;bitpos:[11:0] ;default: 12'h0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0 0x00000FFF +#define HOST_SLC0_TOKEN0_M ((HOST_SLC0_TOKEN0_V)<<(HOST_SLC0_TOKEN0_S)) +#define HOST_SLC0_TOKEN0_V 0xFFF +#define HOST_SLC0_TOKEN0_S 0 + +#define HOST_SLC0_HOST_PF_REG (DR_REG_SLCHOST_BASE + 0x48) +/* HOST_SLC0_PF_DATA : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define HOST_SLC0_PF_DATA 0xFFFFFFFF +#define HOST_SLC0_PF_DATA_M ((HOST_SLC0_PF_DATA_V)<<(HOST_SLC0_PF_DATA_S)) +#define HOST_SLC0_PF_DATA_V 0xFFFFFFFF +#define HOST_SLC0_PF_DATA_S 0 + +#define HOST_SLC1_HOST_PF_REG (DR_REG_SLCHOST_BASE + 0x4C) +/* HOST_SLC1_PF_DATA : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define HOST_SLC1_PF_DATA 0xFFFFFFFF +#define HOST_SLC1_PF_DATA_M ((HOST_SLC1_PF_DATA_V)<<(HOST_SLC1_PF_DATA_S)) +#define HOST_SLC1_PF_DATA_V 0xFFFFFFFF +#define HOST_SLC1_PF_DATA_S 0 + +#define HOST_SLC0HOST_INT_RAW_REG (DR_REG_SLCHOST_BASE + 0x50) +/* HOST_GPIO_SDIO_INT_RAW : RO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_INT_RAW (BIT(25)) +#define HOST_GPIO_SDIO_INT_RAW_M (BIT(25)) +#define HOST_GPIO_SDIO_INT_RAW_V 0x1 +#define HOST_GPIO_SDIO_INT_RAW_S 25 +/* HOST_SLC0_HOST_RD_RETRY_INT_RAW : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_HOST_RD_RETRY_INT_RAW (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_RAW_M (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_RAW_V 0x1 +#define HOST_SLC0_HOST_RD_RETRY_INT_RAW_S 24 +/* HOST_SLC0_RX_NEW_PACKET_INT_RAW : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_NEW_PACKET_INT_RAW (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_RAW_M (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_RAW_V 0x1 +#define HOST_SLC0_RX_NEW_PACKET_INT_RAW_S 23 +/* HOST_SLC0_EXT_BIT3_INT_RAW : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT3_INT_RAW (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_RAW_M (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_RAW_V 0x1 +#define HOST_SLC0_EXT_BIT3_INT_RAW_S 22 +/* HOST_SLC0_EXT_BIT2_INT_RAW : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT2_INT_RAW (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_RAW_M (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_RAW_V 0x1 +#define HOST_SLC0_EXT_BIT2_INT_RAW_S 21 +/* HOST_SLC0_EXT_BIT1_INT_RAW : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT1_INT_RAW (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_RAW_M (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_RAW_V 0x1 +#define HOST_SLC0_EXT_BIT1_INT_RAW_S 20 +/* HOST_SLC0_EXT_BIT0_INT_RAW : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT0_INT_RAW (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_RAW_M (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_RAW_V 0x1 +#define HOST_SLC0_EXT_BIT0_INT_RAW_S 19 +/* HOST_SLC0_RX_PF_VALID_INT_RAW : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_PF_VALID_INT_RAW (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_RAW_M (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_RAW_V 0x1 +#define HOST_SLC0_RX_PF_VALID_INT_RAW_S 18 +/* HOST_SLC0_TX_OVF_INT_RAW : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TX_OVF_INT_RAW (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_RAW_M (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_RAW_V 0x1 +#define HOST_SLC0_TX_OVF_INT_RAW_S 17 +/* HOST_SLC0_RX_UDF_INT_RAW : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_UDF_INT_RAW (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_RAW_M (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_RAW_V 0x1 +#define HOST_SLC0_RX_UDF_INT_RAW_S 16 +/* HOST_SLC0HOST_TX_START_INT_RAW : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TX_START_INT_RAW (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_RAW_M (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_RAW_V 0x1 +#define HOST_SLC0HOST_TX_START_INT_RAW_S 15 +/* HOST_SLC0HOST_RX_START_INT_RAW : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_START_INT_RAW (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_RAW_M (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_RAW_V 0x1 +#define HOST_SLC0HOST_RX_START_INT_RAW_S 14 +/* HOST_SLC0HOST_RX_EOF_INT_RAW : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_EOF_INT_RAW (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_RAW_M (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_RAW_V 0x1 +#define HOST_SLC0HOST_RX_EOF_INT_RAW_S 13 +/* HOST_SLC0HOST_RX_SOF_INT_RAW : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_SOF_INT_RAW (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_RAW_M (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_RAW_V 0x1 +#define HOST_SLC0HOST_RX_SOF_INT_RAW_S 12 +/* HOST_SLC0_TOKEN1_0TO1_INT_RAW : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_0TO1_INT_RAW (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_RAW_M (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_RAW_V 0x1 +#define HOST_SLC0_TOKEN1_0TO1_INT_RAW_S 11 +/* HOST_SLC0_TOKEN0_0TO1_INT_RAW : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_0TO1_INT_RAW (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_RAW_M (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_RAW_V 0x1 +#define HOST_SLC0_TOKEN0_0TO1_INT_RAW_S 10 +/* HOST_SLC0_TOKEN1_1TO0_INT_RAW : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_1TO0_INT_RAW (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_RAW_M (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_RAW_V 0x1 +#define HOST_SLC0_TOKEN1_1TO0_INT_RAW_S 9 +/* HOST_SLC0_TOKEN0_1TO0_INT_RAW : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_1TO0_INT_RAW (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_RAW_M (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_RAW_V 0x1 +#define HOST_SLC0_TOKEN0_1TO0_INT_RAW_S 8 +/* HOST_SLC0_TOHOST_BIT7_INT_RAW : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT7_INT_RAW (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_RAW_M (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_RAW_V 0x1 +#define HOST_SLC0_TOHOST_BIT7_INT_RAW_S 7 +/* HOST_SLC0_TOHOST_BIT6_INT_RAW : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT6_INT_RAW (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_RAW_M (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_RAW_V 0x1 +#define HOST_SLC0_TOHOST_BIT6_INT_RAW_S 6 +/* HOST_SLC0_TOHOST_BIT5_INT_RAW : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT5_INT_RAW (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_RAW_M (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_RAW_V 0x1 +#define HOST_SLC0_TOHOST_BIT5_INT_RAW_S 5 +/* HOST_SLC0_TOHOST_BIT4_INT_RAW : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT4_INT_RAW (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_RAW_M (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_RAW_V 0x1 +#define HOST_SLC0_TOHOST_BIT4_INT_RAW_S 4 +/* HOST_SLC0_TOHOST_BIT3_INT_RAW : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT3_INT_RAW (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_RAW_M (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_RAW_V 0x1 +#define HOST_SLC0_TOHOST_BIT3_INT_RAW_S 3 +/* HOST_SLC0_TOHOST_BIT2_INT_RAW : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT2_INT_RAW (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_RAW_M (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_RAW_V 0x1 +#define HOST_SLC0_TOHOST_BIT2_INT_RAW_S 2 +/* HOST_SLC0_TOHOST_BIT1_INT_RAW : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT1_INT_RAW (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_RAW_M (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_RAW_V 0x1 +#define HOST_SLC0_TOHOST_BIT1_INT_RAW_S 1 +/* HOST_SLC0_TOHOST_BIT0_INT_RAW : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT0_INT_RAW (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_RAW_M (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_RAW_V 0x1 +#define HOST_SLC0_TOHOST_BIT0_INT_RAW_S 0 + +#define HOST_SLC1HOST_INT_RAW_REG (DR_REG_SLCHOST_BASE + 0x54) +/* HOST_SLC1_BT_RX_NEW_PACKET_INT_RAW : RO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_RAW (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_RAW_M (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_RAW_V 0x1 +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_RAW_S 25 +/* HOST_SLC1_HOST_RD_RETRY_INT_RAW : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_HOST_RD_RETRY_INT_RAW (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_RAW_M (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_RAW_V 0x1 +#define HOST_SLC1_HOST_RD_RETRY_INT_RAW_S 24 +/* HOST_SLC1_WIFI_RX_NEW_PACKET_INT_RAW : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_RAW (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_RAW_M (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_RAW_V 0x1 +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_RAW_S 23 +/* HOST_SLC1_EXT_BIT3_INT_RAW : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT3_INT_RAW (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_RAW_M (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_RAW_V 0x1 +#define HOST_SLC1_EXT_BIT3_INT_RAW_S 22 +/* HOST_SLC1_EXT_BIT2_INT_RAW : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT2_INT_RAW (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_RAW_M (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_RAW_V 0x1 +#define HOST_SLC1_EXT_BIT2_INT_RAW_S 21 +/* HOST_SLC1_EXT_BIT1_INT_RAW : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT1_INT_RAW (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_RAW_M (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_RAW_V 0x1 +#define HOST_SLC1_EXT_BIT1_INT_RAW_S 20 +/* HOST_SLC1_EXT_BIT0_INT_RAW : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT0_INT_RAW (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_RAW_M (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_RAW_V 0x1 +#define HOST_SLC1_EXT_BIT0_INT_RAW_S 19 +/* HOST_SLC1_RX_PF_VALID_INT_RAW : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_PF_VALID_INT_RAW (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_RAW_M (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_RAW_V 0x1 +#define HOST_SLC1_RX_PF_VALID_INT_RAW_S 18 +/* HOST_SLC1_TX_OVF_INT_RAW : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TX_OVF_INT_RAW (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_RAW_M (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_RAW_V 0x1 +#define HOST_SLC1_TX_OVF_INT_RAW_S 17 +/* HOST_SLC1_RX_UDF_INT_RAW : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_UDF_INT_RAW (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_RAW_M (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_RAW_V 0x1 +#define HOST_SLC1_RX_UDF_INT_RAW_S 16 +/* HOST_SLC1HOST_TX_START_INT_RAW : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TX_START_INT_RAW (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_RAW_M (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_RAW_V 0x1 +#define HOST_SLC1HOST_TX_START_INT_RAW_S 15 +/* HOST_SLC1HOST_RX_START_INT_RAW : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_START_INT_RAW (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_RAW_M (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_RAW_V 0x1 +#define HOST_SLC1HOST_RX_START_INT_RAW_S 14 +/* HOST_SLC1HOST_RX_EOF_INT_RAW : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_EOF_INT_RAW (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_RAW_M (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_RAW_V 0x1 +#define HOST_SLC1HOST_RX_EOF_INT_RAW_S 13 +/* HOST_SLC1HOST_RX_SOF_INT_RAW : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_SOF_INT_RAW (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_RAW_M (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_RAW_V 0x1 +#define HOST_SLC1HOST_RX_SOF_INT_RAW_S 12 +/* HOST_SLC1_TOKEN1_0TO1_INT_RAW : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_0TO1_INT_RAW (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_RAW_M (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_RAW_V 0x1 +#define HOST_SLC1_TOKEN1_0TO1_INT_RAW_S 11 +/* HOST_SLC1_TOKEN0_0TO1_INT_RAW : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_0TO1_INT_RAW (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_RAW_M (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_RAW_V 0x1 +#define HOST_SLC1_TOKEN0_0TO1_INT_RAW_S 10 +/* HOST_SLC1_TOKEN1_1TO0_INT_RAW : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_1TO0_INT_RAW (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_RAW_M (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_RAW_V 0x1 +#define HOST_SLC1_TOKEN1_1TO0_INT_RAW_S 9 +/* HOST_SLC1_TOKEN0_1TO0_INT_RAW : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_1TO0_INT_RAW (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_RAW_M (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_RAW_V 0x1 +#define HOST_SLC1_TOKEN0_1TO0_INT_RAW_S 8 +/* HOST_SLC1_TOHOST_BIT7_INT_RAW : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT7_INT_RAW (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_RAW_M (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_RAW_V 0x1 +#define HOST_SLC1_TOHOST_BIT7_INT_RAW_S 7 +/* HOST_SLC1_TOHOST_BIT6_INT_RAW : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT6_INT_RAW (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_RAW_M (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_RAW_V 0x1 +#define HOST_SLC1_TOHOST_BIT6_INT_RAW_S 6 +/* HOST_SLC1_TOHOST_BIT5_INT_RAW : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT5_INT_RAW (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_RAW_M (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_RAW_V 0x1 +#define HOST_SLC1_TOHOST_BIT5_INT_RAW_S 5 +/* HOST_SLC1_TOHOST_BIT4_INT_RAW : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT4_INT_RAW (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_RAW_M (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_RAW_V 0x1 +#define HOST_SLC1_TOHOST_BIT4_INT_RAW_S 4 +/* HOST_SLC1_TOHOST_BIT3_INT_RAW : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT3_INT_RAW (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_RAW_M (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_RAW_V 0x1 +#define HOST_SLC1_TOHOST_BIT3_INT_RAW_S 3 +/* HOST_SLC1_TOHOST_BIT2_INT_RAW : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT2_INT_RAW (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_RAW_M (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_RAW_V 0x1 +#define HOST_SLC1_TOHOST_BIT2_INT_RAW_S 2 +/* HOST_SLC1_TOHOST_BIT1_INT_RAW : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT1_INT_RAW (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_RAW_M (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_RAW_V 0x1 +#define HOST_SLC1_TOHOST_BIT1_INT_RAW_S 1 +/* HOST_SLC1_TOHOST_BIT0_INT_RAW : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT0_INT_RAW (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_RAW_M (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_RAW_V 0x1 +#define HOST_SLC1_TOHOST_BIT0_INT_RAW_S 0 + +#define HOST_SLC0HOST_INT_ST_REG (DR_REG_SLCHOST_BASE + 0x58) +/* HOST_GPIO_SDIO_INT_ST : RO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_INT_ST (BIT(25)) +#define HOST_GPIO_SDIO_INT_ST_M (BIT(25)) +#define HOST_GPIO_SDIO_INT_ST_V 0x1 +#define HOST_GPIO_SDIO_INT_ST_S 25 +/* HOST_SLC0_HOST_RD_RETRY_INT_ST : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_HOST_RD_RETRY_INT_ST (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_ST_M (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_ST_V 0x1 +#define HOST_SLC0_HOST_RD_RETRY_INT_ST_S 24 +/* HOST_SLC0_RX_NEW_PACKET_INT_ST : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_NEW_PACKET_INT_ST (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_ST_M (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_ST_V 0x1 +#define HOST_SLC0_RX_NEW_PACKET_INT_ST_S 23 +/* HOST_SLC0_EXT_BIT3_INT_ST : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT3_INT_ST (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_ST_M (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_ST_V 0x1 +#define HOST_SLC0_EXT_BIT3_INT_ST_S 22 +/* HOST_SLC0_EXT_BIT2_INT_ST : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT2_INT_ST (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_ST_M (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_ST_V 0x1 +#define HOST_SLC0_EXT_BIT2_INT_ST_S 21 +/* HOST_SLC0_EXT_BIT1_INT_ST : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT1_INT_ST (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_ST_M (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_ST_V 0x1 +#define HOST_SLC0_EXT_BIT1_INT_ST_S 20 +/* HOST_SLC0_EXT_BIT0_INT_ST : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT0_INT_ST (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_ST_M (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_ST_V 0x1 +#define HOST_SLC0_EXT_BIT0_INT_ST_S 19 +/* HOST_SLC0_RX_PF_VALID_INT_ST : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_PF_VALID_INT_ST (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_ST_M (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_ST_V 0x1 +#define HOST_SLC0_RX_PF_VALID_INT_ST_S 18 +/* HOST_SLC0_TX_OVF_INT_ST : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TX_OVF_INT_ST (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_ST_M (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_ST_V 0x1 +#define HOST_SLC0_TX_OVF_INT_ST_S 17 +/* HOST_SLC0_RX_UDF_INT_ST : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_UDF_INT_ST (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_ST_M (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_ST_V 0x1 +#define HOST_SLC0_RX_UDF_INT_ST_S 16 +/* HOST_SLC0HOST_TX_START_INT_ST : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TX_START_INT_ST (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_ST_M (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_ST_V 0x1 +#define HOST_SLC0HOST_TX_START_INT_ST_S 15 +/* HOST_SLC0HOST_RX_START_INT_ST : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_START_INT_ST (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_ST_M (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_ST_V 0x1 +#define HOST_SLC0HOST_RX_START_INT_ST_S 14 +/* HOST_SLC0HOST_RX_EOF_INT_ST : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_EOF_INT_ST (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_ST_M (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_ST_V 0x1 +#define HOST_SLC0HOST_RX_EOF_INT_ST_S 13 +/* HOST_SLC0HOST_RX_SOF_INT_ST : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_SOF_INT_ST (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_ST_M (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_ST_V 0x1 +#define HOST_SLC0HOST_RX_SOF_INT_ST_S 12 +/* HOST_SLC0_TOKEN1_0TO1_INT_ST : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_0TO1_INT_ST (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_ST_M (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_ST_V 0x1 +#define HOST_SLC0_TOKEN1_0TO1_INT_ST_S 11 +/* HOST_SLC0_TOKEN0_0TO1_INT_ST : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_0TO1_INT_ST (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_ST_M (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_ST_V 0x1 +#define HOST_SLC0_TOKEN0_0TO1_INT_ST_S 10 +/* HOST_SLC0_TOKEN1_1TO0_INT_ST : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_1TO0_INT_ST (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_ST_M (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_ST_V 0x1 +#define HOST_SLC0_TOKEN1_1TO0_INT_ST_S 9 +/* HOST_SLC0_TOKEN0_1TO0_INT_ST : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_1TO0_INT_ST (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_ST_M (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_ST_V 0x1 +#define HOST_SLC0_TOKEN0_1TO0_INT_ST_S 8 +/* HOST_SLC0_TOHOST_BIT7_INT_ST : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT7_INT_ST (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_ST_M (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_ST_V 0x1 +#define HOST_SLC0_TOHOST_BIT7_INT_ST_S 7 +/* HOST_SLC0_TOHOST_BIT6_INT_ST : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT6_INT_ST (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_ST_M (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_ST_V 0x1 +#define HOST_SLC0_TOHOST_BIT6_INT_ST_S 6 +/* HOST_SLC0_TOHOST_BIT5_INT_ST : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT5_INT_ST (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_ST_M (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_ST_V 0x1 +#define HOST_SLC0_TOHOST_BIT5_INT_ST_S 5 +/* HOST_SLC0_TOHOST_BIT4_INT_ST : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT4_INT_ST (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_ST_M (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_ST_V 0x1 +#define HOST_SLC0_TOHOST_BIT4_INT_ST_S 4 +/* HOST_SLC0_TOHOST_BIT3_INT_ST : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT3_INT_ST (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_ST_M (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_ST_V 0x1 +#define HOST_SLC0_TOHOST_BIT3_INT_ST_S 3 +/* HOST_SLC0_TOHOST_BIT2_INT_ST : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT2_INT_ST (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_ST_M (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_ST_V 0x1 +#define HOST_SLC0_TOHOST_BIT2_INT_ST_S 2 +/* HOST_SLC0_TOHOST_BIT1_INT_ST : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT1_INT_ST (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_ST_M (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_ST_V 0x1 +#define HOST_SLC0_TOHOST_BIT1_INT_ST_S 1 +/* HOST_SLC0_TOHOST_BIT0_INT_ST : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT0_INT_ST (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_ST_M (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_ST_V 0x1 +#define HOST_SLC0_TOHOST_BIT0_INT_ST_S 0 + +#define HOST_SLC1HOST_INT_ST_REG (DR_REG_SLCHOST_BASE + 0x5C) +/* HOST_SLC1_BT_RX_NEW_PACKET_INT_ST : RO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ST (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ST_M (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ST_V 0x1 +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ST_S 25 +/* HOST_SLC1_HOST_RD_RETRY_INT_ST : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_HOST_RD_RETRY_INT_ST (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_ST_M (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_ST_V 0x1 +#define HOST_SLC1_HOST_RD_RETRY_INT_ST_S 24 +/* HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ST : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ST (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ST_M (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ST_V 0x1 +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ST_S 23 +/* HOST_SLC1_EXT_BIT3_INT_ST : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT3_INT_ST (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_ST_M (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_ST_V 0x1 +#define HOST_SLC1_EXT_BIT3_INT_ST_S 22 +/* HOST_SLC1_EXT_BIT2_INT_ST : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT2_INT_ST (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_ST_M (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_ST_V 0x1 +#define HOST_SLC1_EXT_BIT2_INT_ST_S 21 +/* HOST_SLC1_EXT_BIT1_INT_ST : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT1_INT_ST (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_ST_M (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_ST_V 0x1 +#define HOST_SLC1_EXT_BIT1_INT_ST_S 20 +/* HOST_SLC1_EXT_BIT0_INT_ST : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT0_INT_ST (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_ST_M (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_ST_V 0x1 +#define HOST_SLC1_EXT_BIT0_INT_ST_S 19 +/* HOST_SLC1_RX_PF_VALID_INT_ST : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_PF_VALID_INT_ST (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_ST_M (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_ST_V 0x1 +#define HOST_SLC1_RX_PF_VALID_INT_ST_S 18 +/* HOST_SLC1_TX_OVF_INT_ST : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TX_OVF_INT_ST (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_ST_M (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_ST_V 0x1 +#define HOST_SLC1_TX_OVF_INT_ST_S 17 +/* HOST_SLC1_RX_UDF_INT_ST : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_UDF_INT_ST (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_ST_M (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_ST_V 0x1 +#define HOST_SLC1_RX_UDF_INT_ST_S 16 +/* HOST_SLC1HOST_TX_START_INT_ST : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TX_START_INT_ST (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_ST_M (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_ST_V 0x1 +#define HOST_SLC1HOST_TX_START_INT_ST_S 15 +/* HOST_SLC1HOST_RX_START_INT_ST : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_START_INT_ST (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_ST_M (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_ST_V 0x1 +#define HOST_SLC1HOST_RX_START_INT_ST_S 14 +/* HOST_SLC1HOST_RX_EOF_INT_ST : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_EOF_INT_ST (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_ST_M (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_ST_V 0x1 +#define HOST_SLC1HOST_RX_EOF_INT_ST_S 13 +/* HOST_SLC1HOST_RX_SOF_INT_ST : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_SOF_INT_ST (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_ST_M (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_ST_V 0x1 +#define HOST_SLC1HOST_RX_SOF_INT_ST_S 12 +/* HOST_SLC1_TOKEN1_0TO1_INT_ST : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_0TO1_INT_ST (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_ST_M (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_ST_V 0x1 +#define HOST_SLC1_TOKEN1_0TO1_INT_ST_S 11 +/* HOST_SLC1_TOKEN0_0TO1_INT_ST : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_0TO1_INT_ST (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_ST_M (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_ST_V 0x1 +#define HOST_SLC1_TOKEN0_0TO1_INT_ST_S 10 +/* HOST_SLC1_TOKEN1_1TO0_INT_ST : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_1TO0_INT_ST (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_ST_M (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_ST_V 0x1 +#define HOST_SLC1_TOKEN1_1TO0_INT_ST_S 9 +/* HOST_SLC1_TOKEN0_1TO0_INT_ST : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_1TO0_INT_ST (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_ST_M (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_ST_V 0x1 +#define HOST_SLC1_TOKEN0_1TO0_INT_ST_S 8 +/* HOST_SLC1_TOHOST_BIT7_INT_ST : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT7_INT_ST (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_ST_M (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_ST_V 0x1 +#define HOST_SLC1_TOHOST_BIT7_INT_ST_S 7 +/* HOST_SLC1_TOHOST_BIT6_INT_ST : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT6_INT_ST (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_ST_M (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_ST_V 0x1 +#define HOST_SLC1_TOHOST_BIT6_INT_ST_S 6 +/* HOST_SLC1_TOHOST_BIT5_INT_ST : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT5_INT_ST (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_ST_M (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_ST_V 0x1 +#define HOST_SLC1_TOHOST_BIT5_INT_ST_S 5 +/* HOST_SLC1_TOHOST_BIT4_INT_ST : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT4_INT_ST (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_ST_M (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_ST_V 0x1 +#define HOST_SLC1_TOHOST_BIT4_INT_ST_S 4 +/* HOST_SLC1_TOHOST_BIT3_INT_ST : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT3_INT_ST (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_ST_M (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_ST_V 0x1 +#define HOST_SLC1_TOHOST_BIT3_INT_ST_S 3 +/* HOST_SLC1_TOHOST_BIT2_INT_ST : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT2_INT_ST (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_ST_M (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_ST_V 0x1 +#define HOST_SLC1_TOHOST_BIT2_INT_ST_S 2 +/* HOST_SLC1_TOHOST_BIT1_INT_ST : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT1_INT_ST (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_ST_M (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_ST_V 0x1 +#define HOST_SLC1_TOHOST_BIT1_INT_ST_S 1 +/* HOST_SLC1_TOHOST_BIT0_INT_ST : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT0_INT_ST (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_ST_M (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_ST_V 0x1 +#define HOST_SLC1_TOHOST_BIT0_INT_ST_S 0 + +#define HOST_SLCHOST_PKT_LEN_REG (DR_REG_SLCHOST_BASE + 0x60) +/* HOST_HOSTSLC0_LEN_CHECK : RO ;bitpos:[31:20] ;default: 10'h0 ; */ +/*description: */ +#define HOST_HOSTSLC0_LEN_CHECK 0x00000FFF +#define HOST_HOSTSLC0_LEN_CHECK_M ((HOST_HOSTSLC0_LEN_CHECK_V)<<(HOST_HOSTSLC0_LEN_CHECK_S)) +#define HOST_HOSTSLC0_LEN_CHECK_V 0xFFF +#define HOST_HOSTSLC0_LEN_CHECK_S 20 +/* HOST_HOSTSLC0_LEN : RO ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define HOST_HOSTSLC0_LEN 0x000FFFFF +#define HOST_HOSTSLC0_LEN_M ((HOST_HOSTSLC0_LEN_V)<<(HOST_HOSTSLC0_LEN_S)) +#define HOST_HOSTSLC0_LEN_V 0xFFFFF +#define HOST_HOSTSLC0_LEN_S 0 + +#define HOST_SLCHOST_STATE_W0_REG (DR_REG_SLCHOST_BASE + 0x64) +/* HOST_SLCHOST_STATE3 : RO ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_STATE3 0x000000FF +#define HOST_SLCHOST_STATE3_M ((HOST_SLCHOST_STATE3_V)<<(HOST_SLCHOST_STATE3_S)) +#define HOST_SLCHOST_STATE3_V 0xFF +#define HOST_SLCHOST_STATE3_S 24 +/* HOST_SLCHOST_STATE2 : RO ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_STATE2 0x000000FF +#define HOST_SLCHOST_STATE2_M ((HOST_SLCHOST_STATE2_V)<<(HOST_SLCHOST_STATE2_S)) +#define HOST_SLCHOST_STATE2_V 0xFF +#define HOST_SLCHOST_STATE2_S 16 +/* HOST_SLCHOST_STATE1 : RO ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_STATE1 0x000000FF +#define HOST_SLCHOST_STATE1_M ((HOST_SLCHOST_STATE1_V)<<(HOST_SLCHOST_STATE1_S)) +#define HOST_SLCHOST_STATE1_V 0xFF +#define HOST_SLCHOST_STATE1_S 8 +/* HOST_SLCHOST_STATE0 : RO ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_STATE0 0x000000FF +#define HOST_SLCHOST_STATE0_M ((HOST_SLCHOST_STATE0_V)<<(HOST_SLCHOST_STATE0_S)) +#define HOST_SLCHOST_STATE0_V 0xFF +#define HOST_SLCHOST_STATE0_S 0 + +#define HOST_SLCHOST_STATE_W1_REG (DR_REG_SLCHOST_BASE + 0x68) +/* HOST_SLCHOST_STATE7 : RO ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_STATE7 0x000000FF +#define HOST_SLCHOST_STATE7_M ((HOST_SLCHOST_STATE7_V)<<(HOST_SLCHOST_STATE7_S)) +#define HOST_SLCHOST_STATE7_V 0xFF +#define HOST_SLCHOST_STATE7_S 24 +/* HOST_SLCHOST_STATE6 : RO ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_STATE6 0x000000FF +#define HOST_SLCHOST_STATE6_M ((HOST_SLCHOST_STATE6_V)<<(HOST_SLCHOST_STATE6_S)) +#define HOST_SLCHOST_STATE6_V 0xFF +#define HOST_SLCHOST_STATE6_S 16 +/* HOST_SLCHOST_STATE5 : RO ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_STATE5 0x000000FF +#define HOST_SLCHOST_STATE5_M ((HOST_SLCHOST_STATE5_V)<<(HOST_SLCHOST_STATE5_S)) +#define HOST_SLCHOST_STATE5_V 0xFF +#define HOST_SLCHOST_STATE5_S 8 +/* HOST_SLCHOST_STATE4 : RO ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_STATE4 0x000000FF +#define HOST_SLCHOST_STATE4_M ((HOST_SLCHOST_STATE4_V)<<(HOST_SLCHOST_STATE4_S)) +#define HOST_SLCHOST_STATE4_V 0xFF +#define HOST_SLCHOST_STATE4_S 0 + +#define HOST_SLCHOST_CONF_W_REG(pos) (HOST_SLCHOST_CONF_W0_REG+pos+(pos>23?4:0)+(pos>31?12:0)) + +#define HOST_SLCHOST_CONF_W0_REG (DR_REG_SLCHOST_BASE + 0x6C) +/* HOST_SLCHOST_CONF3 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF3 0x000000FF +#define HOST_SLCHOST_CONF3_M ((HOST_SLCHOST_CONF3_V)<<(HOST_SLCHOST_CONF3_S)) +#define HOST_SLCHOST_CONF3_V 0xFF +#define HOST_SLCHOST_CONF3_S 24 +/* HOST_SLCHOST_CONF2 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF2 0x000000FF +#define HOST_SLCHOST_CONF2_M ((HOST_SLCHOST_CONF2_V)<<(HOST_SLCHOST_CONF2_S)) +#define HOST_SLCHOST_CONF2_V 0xFF +#define HOST_SLCHOST_CONF2_S 16 +/* HOST_SLCHOST_CONF1 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF1 0x000000FF +#define HOST_SLCHOST_CONF1_M ((HOST_SLCHOST_CONF1_V)<<(HOST_SLCHOST_CONF1_S)) +#define HOST_SLCHOST_CONF1_V 0xFF +#define HOST_SLCHOST_CONF1_S 8 +/* HOST_SLCHOST_CONF0 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF0 0x000000FF +#define HOST_SLCHOST_CONF0_M ((HOST_SLCHOST_CONF0_V)<<(HOST_SLCHOST_CONF0_S)) +#define HOST_SLCHOST_CONF0_V 0xFF +#define HOST_SLCHOST_CONF0_S 0 + +#define HOST_SLCHOST_CONF_W1_REG (DR_REG_SLCHOST_BASE + 0x70) +/* HOST_SLCHOST_CONF7 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF7 0x000000FF +#define HOST_SLCHOST_CONF7_M ((HOST_SLCHOST_CONF7_V)<<(HOST_SLCHOST_CONF7_S)) +#define HOST_SLCHOST_CONF7_V 0xFF +#define HOST_SLCHOST_CONF7_S 24 +/* HOST_SLCHOST_CONF6 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF6 0x000000FF +#define HOST_SLCHOST_CONF6_M ((HOST_SLCHOST_CONF6_V)<<(HOST_SLCHOST_CONF6_S)) +#define HOST_SLCHOST_CONF6_V 0xFF +#define HOST_SLCHOST_CONF6_S 16 +/* HOST_SLCHOST_CONF5 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF5 0x000000FF +#define HOST_SLCHOST_CONF5_M ((HOST_SLCHOST_CONF5_V)<<(HOST_SLCHOST_CONF5_S)) +#define HOST_SLCHOST_CONF5_V 0xFF +#define HOST_SLCHOST_CONF5_S 8 +/* HOST_SLCHOST_CONF4 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF4 0x000000FF +#define HOST_SLCHOST_CONF4_M ((HOST_SLCHOST_CONF4_V)<<(HOST_SLCHOST_CONF4_S)) +#define HOST_SLCHOST_CONF4_V 0xFF +#define HOST_SLCHOST_CONF4_S 0 + +#define HOST_SLCHOST_CONF_W2_REG (DR_REG_SLCHOST_BASE + 0x74) +/* HOST_SLCHOST_CONF11 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF11 0x000000FF +#define HOST_SLCHOST_CONF11_M ((HOST_SLCHOST_CONF11_V)<<(HOST_SLCHOST_CONF11_S)) +#define HOST_SLCHOST_CONF11_V 0xFF +#define HOST_SLCHOST_CONF11_S 24 +/* HOST_SLCHOST_CONF10 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF10 0x000000FF +#define HOST_SLCHOST_CONF10_M ((HOST_SLCHOST_CONF10_V)<<(HOST_SLCHOST_CONF10_S)) +#define HOST_SLCHOST_CONF10_V 0xFF +#define HOST_SLCHOST_CONF10_S 16 +/* HOST_SLCHOST_CONF9 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF9 0x000000FF +#define HOST_SLCHOST_CONF9_M ((HOST_SLCHOST_CONF9_V)<<(HOST_SLCHOST_CONF9_S)) +#define HOST_SLCHOST_CONF9_V 0xFF +#define HOST_SLCHOST_CONF9_S 8 +/* HOST_SLCHOST_CONF8 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF8 0x000000FF +#define HOST_SLCHOST_CONF8_M ((HOST_SLCHOST_CONF8_V)<<(HOST_SLCHOST_CONF8_S)) +#define HOST_SLCHOST_CONF8_V 0xFF +#define HOST_SLCHOST_CONF8_S 0 + +#define HOST_SLCHOST_CONF_W3_REG (DR_REG_SLCHOST_BASE + 0x78) +/* HOST_SLCHOST_CONF15 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF15 0x000000FF +#define HOST_SLCHOST_CONF15_M ((HOST_SLCHOST_CONF15_V)<<(HOST_SLCHOST_CONF15_S)) +#define HOST_SLCHOST_CONF15_V 0xFF +#define HOST_SLCHOST_CONF15_S 24 +/* HOST_SLCHOST_CONF14 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF14 0x000000FF +#define HOST_SLCHOST_CONF14_M ((HOST_SLCHOST_CONF14_V)<<(HOST_SLCHOST_CONF14_S)) +#define HOST_SLCHOST_CONF14_V 0xFF +#define HOST_SLCHOST_CONF14_S 16 +/* HOST_SLCHOST_CONF13 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF13 0x000000FF +#define HOST_SLCHOST_CONF13_M ((HOST_SLCHOST_CONF13_V)<<(HOST_SLCHOST_CONF13_S)) +#define HOST_SLCHOST_CONF13_V 0xFF +#define HOST_SLCHOST_CONF13_S 8 +/* HOST_SLCHOST_CONF12 : R/W ;bitpos:[7:0] ;default: 8'hc0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF12 0x000000FF +#define HOST_SLCHOST_CONF12_M ((HOST_SLCHOST_CONF12_V)<<(HOST_SLCHOST_CONF12_S)) +#define HOST_SLCHOST_CONF12_V 0xFF +#define HOST_SLCHOST_CONF12_S 0 + +#define HOST_SLCHOST_CONF_W4_REG (DR_REG_SLCHOST_BASE + 0x7C) +/* HOST_SLCHOST_CONF19 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: Interrupt to target CPU*/ +#define HOST_SLCHOST_CONF19 0x000000FF +#define HOST_SLCHOST_CONF19_M ((HOST_SLCHOST_CONF19_V)<<(HOST_SLCHOST_CONF19_S)) +#define HOST_SLCHOST_CONF19_V 0xFF +#define HOST_SLCHOST_CONF19_S 24 +/* HOST_SLCHOST_CONF18 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF18 0x000000FF +#define HOST_SLCHOST_CONF18_M ((HOST_SLCHOST_CONF18_V)<<(HOST_SLCHOST_CONF18_S)) +#define HOST_SLCHOST_CONF18_V 0xFF +#define HOST_SLCHOST_CONF18_S 16 +/* HOST_SLCHOST_CONF17 : R/W ;bitpos:[15:8] ;default: 8'h1 ; */ +/*description: SLC timeout enable*/ +#define HOST_SLCHOST_CONF17 0x000000FF +#define HOST_SLCHOST_CONF17_M ((HOST_SLCHOST_CONF17_V)<<(HOST_SLCHOST_CONF17_S)) +#define HOST_SLCHOST_CONF17_V 0xFF +#define HOST_SLCHOST_CONF17_S 8 +/* HOST_SLCHOST_CONF16 : R/W ;bitpos:[7:0] ;default: 8'hFF ; */ +/*description: SLC timeout value*/ +#define HOST_SLCHOST_CONF16 0x000000FF +#define HOST_SLCHOST_CONF16_M ((HOST_SLCHOST_CONF16_V)<<(HOST_SLCHOST_CONF16_S)) +#define HOST_SLCHOST_CONF16_V 0xFF +#define HOST_SLCHOST_CONF16_S 0 + +#define HOST_SLCHOST_CONF_W5_REG (DR_REG_SLCHOST_BASE + 0x80) +/* HOST_SLCHOST_CONF23 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF23 0x000000FF +#define HOST_SLCHOST_CONF23_M ((HOST_SLCHOST_CONF23_V)<<(HOST_SLCHOST_CONF23_S)) +#define HOST_SLCHOST_CONF23_V 0xFF +#define HOST_SLCHOST_CONF23_S 24 +/* HOST_SLCHOST_CONF22 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF22 0x000000FF +#define HOST_SLCHOST_CONF22_M ((HOST_SLCHOST_CONF22_V)<<(HOST_SLCHOST_CONF22_S)) +#define HOST_SLCHOST_CONF22_V 0xFF +#define HOST_SLCHOST_CONF22_S 16 +/* HOST_SLCHOST_CONF21 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF21 0x000000FF +#define HOST_SLCHOST_CONF21_M ((HOST_SLCHOST_CONF21_V)<<(HOST_SLCHOST_CONF21_S)) +#define HOST_SLCHOST_CONF21_V 0xFF +#define HOST_SLCHOST_CONF21_S 8 +/* HOST_SLCHOST_CONF20 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF20 0x000000FF +#define HOST_SLCHOST_CONF20_M ((HOST_SLCHOST_CONF20_V)<<(HOST_SLCHOST_CONF20_S)) +#define HOST_SLCHOST_CONF20_V 0xFF +#define HOST_SLCHOST_CONF20_S 0 + +#define HOST_SLCHOST_WIN_CMD_REG (DR_REG_SLCHOST_BASE + 0x84) + +#define HOST_SLCHOST_CONF_W6_REG (DR_REG_SLCHOST_BASE + 0x88) +/* HOST_SLCHOST_CONF27 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF27 0x000000FF +#define HOST_SLCHOST_CONF27_M ((HOST_SLCHOST_CONF27_V)<<(HOST_SLCHOST_CONF27_S)) +#define HOST_SLCHOST_CONF27_V 0xFF +#define HOST_SLCHOST_CONF27_S 24 +/* HOST_SLCHOST_CONF26 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF26 0x000000FF +#define HOST_SLCHOST_CONF26_M ((HOST_SLCHOST_CONF26_V)<<(HOST_SLCHOST_CONF26_S)) +#define HOST_SLCHOST_CONF26_V 0xFF +#define HOST_SLCHOST_CONF26_S 16 +/* HOST_SLCHOST_CONF25 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF25 0x000000FF +#define HOST_SLCHOST_CONF25_M ((HOST_SLCHOST_CONF25_V)<<(HOST_SLCHOST_CONF25_S)) +#define HOST_SLCHOST_CONF25_V 0xFF +#define HOST_SLCHOST_CONF25_S 8 +/* HOST_SLCHOST_CONF24 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF24 0x000000FF +#define HOST_SLCHOST_CONF24_M ((HOST_SLCHOST_CONF24_V)<<(HOST_SLCHOST_CONF24_S)) +#define HOST_SLCHOST_CONF24_V 0xFF +#define HOST_SLCHOST_CONF24_S 0 + +#define HOST_SLCHOST_CONF_W7_REG (DR_REG_SLCHOST_BASE + 0x8C) +/* HOST_SLCHOST_CONF31 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF31 0x000000FF +#define HOST_SLCHOST_CONF31_M ((HOST_SLCHOST_CONF31_V)<<(HOST_SLCHOST_CONF31_S)) +#define HOST_SLCHOST_CONF31_V 0xFF +#define HOST_SLCHOST_CONF31_S 24 +/* HOST_SLCHOST_CONF30 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF30 0x000000FF +#define HOST_SLCHOST_CONF30_M ((HOST_SLCHOST_CONF30_V)<<(HOST_SLCHOST_CONF30_S)) +#define HOST_SLCHOST_CONF30_V 0xFF +#define HOST_SLCHOST_CONF30_S 16 +/* HOST_SLCHOST_CONF29 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF29 0x000000FF +#define HOST_SLCHOST_CONF29_M ((HOST_SLCHOST_CONF29_V)<<(HOST_SLCHOST_CONF29_S)) +#define HOST_SLCHOST_CONF29_V 0xFF +#define HOST_SLCHOST_CONF29_S 8 +/* HOST_SLCHOST_CONF28 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF28 0x000000FF +#define HOST_SLCHOST_CONF28_M ((HOST_SLCHOST_CONF28_V)<<(HOST_SLCHOST_CONF28_S)) +#define HOST_SLCHOST_CONF28_V 0xFF +#define HOST_SLCHOST_CONF28_S 0 + +#define HOST_SLCHOST_PKT_LEN0_REG (DR_REG_SLCHOST_BASE + 0x90) +/* HOST_HOSTSLC0_LEN0 : RO ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define HOST_HOSTSLC0_LEN0 0x000FFFFF +#define HOST_HOSTSLC0_LEN0_M ((HOST_HOSTSLC0_LEN0_V)<<(HOST_HOSTSLC0_LEN0_S)) +#define HOST_HOSTSLC0_LEN0_V 0xFFFFF +#define HOST_HOSTSLC0_LEN0_S 0 + +#define HOST_SLCHOST_PKT_LEN1_REG (DR_REG_SLCHOST_BASE + 0x94) +/* HOST_HOSTSLC0_LEN1 : RO ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define HOST_HOSTSLC0_LEN1 0x000FFFFF +#define HOST_HOSTSLC0_LEN1_M ((HOST_HOSTSLC0_LEN1_V)<<(HOST_HOSTSLC0_LEN1_S)) +#define HOST_HOSTSLC0_LEN1_V 0xFFFFF +#define HOST_HOSTSLC0_LEN1_S 0 + +#define HOST_SLCHOST_PKT_LEN2_REG (DR_REG_SLCHOST_BASE + 0x98) +/* HOST_HOSTSLC0_LEN2 : RO ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define HOST_HOSTSLC0_LEN2 0x000FFFFF +#define HOST_HOSTSLC0_LEN2_M ((HOST_HOSTSLC0_LEN2_V)<<(HOST_HOSTSLC0_LEN2_S)) +#define HOST_HOSTSLC0_LEN2_V 0xFFFFF +#define HOST_HOSTSLC0_LEN2_S 0 + +#define HOST_SLCHOST_CONF_W8_REG (DR_REG_SLCHOST_BASE + 0x9C) +/* HOST_SLCHOST_CONF35 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF35 0x000000FF +#define HOST_SLCHOST_CONF35_M ((HOST_SLCHOST_CONF35_V)<<(HOST_SLCHOST_CONF35_S)) +#define HOST_SLCHOST_CONF35_V 0xFF +#define HOST_SLCHOST_CONF35_S 24 +/* HOST_SLCHOST_CONF34 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF34 0x000000FF +#define HOST_SLCHOST_CONF34_M ((HOST_SLCHOST_CONF34_V)<<(HOST_SLCHOST_CONF34_S)) +#define HOST_SLCHOST_CONF34_V 0xFF +#define HOST_SLCHOST_CONF34_S 16 +/* HOST_SLCHOST_CONF33 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF33 0x000000FF +#define HOST_SLCHOST_CONF33_M ((HOST_SLCHOST_CONF33_V)<<(HOST_SLCHOST_CONF33_S)) +#define HOST_SLCHOST_CONF33_V 0xFF +#define HOST_SLCHOST_CONF33_S 8 +/* HOST_SLCHOST_CONF32 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF32 0x000000FF +#define HOST_SLCHOST_CONF32_M ((HOST_SLCHOST_CONF32_V)<<(HOST_SLCHOST_CONF32_S)) +#define HOST_SLCHOST_CONF32_V 0xFF +#define HOST_SLCHOST_CONF32_S 0 + +#define HOST_SLCHOST_CONF_W9_REG (DR_REG_SLCHOST_BASE + 0xA0) +/* HOST_SLCHOST_CONF39 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF39 0x000000FF +#define HOST_SLCHOST_CONF39_M ((HOST_SLCHOST_CONF39_V)<<(HOST_SLCHOST_CONF39_S)) +#define HOST_SLCHOST_CONF39_V 0xFF +#define HOST_SLCHOST_CONF39_S 24 +/* HOST_SLCHOST_CONF38 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF38 0x000000FF +#define HOST_SLCHOST_CONF38_M ((HOST_SLCHOST_CONF38_V)<<(HOST_SLCHOST_CONF38_S)) +#define HOST_SLCHOST_CONF38_V 0xFF +#define HOST_SLCHOST_CONF38_S 16 +/* HOST_SLCHOST_CONF37 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF37 0x000000FF +#define HOST_SLCHOST_CONF37_M ((HOST_SLCHOST_CONF37_V)<<(HOST_SLCHOST_CONF37_S)) +#define HOST_SLCHOST_CONF37_V 0xFF +#define HOST_SLCHOST_CONF37_S 8 +/* HOST_SLCHOST_CONF36 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF36 0x000000FF +#define HOST_SLCHOST_CONF36_M ((HOST_SLCHOST_CONF36_V)<<(HOST_SLCHOST_CONF36_S)) +#define HOST_SLCHOST_CONF36_V 0xFF +#define HOST_SLCHOST_CONF36_S 0 + +#define HOST_SLCHOST_CONF_W10_REG (DR_REG_SLCHOST_BASE + 0xA4) +/* HOST_SLCHOST_CONF43 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF43 0x000000FF +#define HOST_SLCHOST_CONF43_M ((HOST_SLCHOST_CONF43_V)<<(HOST_SLCHOST_CONF43_S)) +#define HOST_SLCHOST_CONF43_V 0xFF +#define HOST_SLCHOST_CONF43_S 24 +/* HOST_SLCHOST_CONF42 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF42 0x000000FF +#define HOST_SLCHOST_CONF42_M ((HOST_SLCHOST_CONF42_V)<<(HOST_SLCHOST_CONF42_S)) +#define HOST_SLCHOST_CONF42_V 0xFF +#define HOST_SLCHOST_CONF42_S 16 +/* HOST_SLCHOST_CONF41 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF41 0x000000FF +#define HOST_SLCHOST_CONF41_M ((HOST_SLCHOST_CONF41_V)<<(HOST_SLCHOST_CONF41_S)) +#define HOST_SLCHOST_CONF41_V 0xFF +#define HOST_SLCHOST_CONF41_S 8 +/* HOST_SLCHOST_CONF40 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF40 0x000000FF +#define HOST_SLCHOST_CONF40_M ((HOST_SLCHOST_CONF40_V)<<(HOST_SLCHOST_CONF40_S)) +#define HOST_SLCHOST_CONF40_V 0xFF +#define HOST_SLCHOST_CONF40_S 0 + +#define HOST_SLCHOST_CONF_W11_REG (DR_REG_SLCHOST_BASE + 0xA8) +/* HOST_SLCHOST_CONF47 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF47 0x000000FF +#define HOST_SLCHOST_CONF47_M ((HOST_SLCHOST_CONF47_V)<<(HOST_SLCHOST_CONF47_S)) +#define HOST_SLCHOST_CONF47_V 0xFF +#define HOST_SLCHOST_CONF47_S 24 +/* HOST_SLCHOST_CONF46 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF46 0x000000FF +#define HOST_SLCHOST_CONF46_M ((HOST_SLCHOST_CONF46_V)<<(HOST_SLCHOST_CONF46_S)) +#define HOST_SLCHOST_CONF46_V 0xFF +#define HOST_SLCHOST_CONF46_S 16 +/* HOST_SLCHOST_CONF45 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF45 0x000000FF +#define HOST_SLCHOST_CONF45_M ((HOST_SLCHOST_CONF45_V)<<(HOST_SLCHOST_CONF45_S)) +#define HOST_SLCHOST_CONF45_V 0xFF +#define HOST_SLCHOST_CONF45_S 8 +/* HOST_SLCHOST_CONF44 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF44 0x000000FF +#define HOST_SLCHOST_CONF44_M ((HOST_SLCHOST_CONF44_V)<<(HOST_SLCHOST_CONF44_S)) +#define HOST_SLCHOST_CONF44_V 0xFF +#define HOST_SLCHOST_CONF44_S 0 + +#define HOST_SLCHOST_CONF_W12_REG (DR_REG_SLCHOST_BASE + 0xAC) +/* HOST_SLCHOST_CONF51 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF51 0x000000FF +#define HOST_SLCHOST_CONF51_M ((HOST_SLCHOST_CONF51_V)<<(HOST_SLCHOST_CONF51_S)) +#define HOST_SLCHOST_CONF51_V 0xFF +#define HOST_SLCHOST_CONF51_S 24 +/* HOST_SLCHOST_CONF50 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF50 0x000000FF +#define HOST_SLCHOST_CONF50_M ((HOST_SLCHOST_CONF50_V)<<(HOST_SLCHOST_CONF50_S)) +#define HOST_SLCHOST_CONF50_V 0xFF +#define HOST_SLCHOST_CONF50_S 16 +/* HOST_SLCHOST_CONF49 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF49 0x000000FF +#define HOST_SLCHOST_CONF49_M ((HOST_SLCHOST_CONF49_V)<<(HOST_SLCHOST_CONF49_S)) +#define HOST_SLCHOST_CONF49_V 0xFF +#define HOST_SLCHOST_CONF49_S 8 +/* HOST_SLCHOST_CONF48 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF48 0x000000FF +#define HOST_SLCHOST_CONF48_M ((HOST_SLCHOST_CONF48_V)<<(HOST_SLCHOST_CONF48_S)) +#define HOST_SLCHOST_CONF48_V 0xFF +#define HOST_SLCHOST_CONF48_S 0 + +#define HOST_SLCHOST_CONF_W13_REG (DR_REG_SLCHOST_BASE + 0xB0) +/* HOST_SLCHOST_CONF55 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF55 0x000000FF +#define HOST_SLCHOST_CONF55_M ((HOST_SLCHOST_CONF55_V)<<(HOST_SLCHOST_CONF55_S)) +#define HOST_SLCHOST_CONF55_V 0xFF +#define HOST_SLCHOST_CONF55_S 24 +/* HOST_SLCHOST_CONF54 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF54 0x000000FF +#define HOST_SLCHOST_CONF54_M ((HOST_SLCHOST_CONF54_V)<<(HOST_SLCHOST_CONF54_S)) +#define HOST_SLCHOST_CONF54_V 0xFF +#define HOST_SLCHOST_CONF54_S 16 +/* HOST_SLCHOST_CONF53 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF53 0x000000FF +#define HOST_SLCHOST_CONF53_M ((HOST_SLCHOST_CONF53_V)<<(HOST_SLCHOST_CONF53_S)) +#define HOST_SLCHOST_CONF53_V 0xFF +#define HOST_SLCHOST_CONF53_S 8 +/* HOST_SLCHOST_CONF52 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF52 0x000000FF +#define HOST_SLCHOST_CONF52_M ((HOST_SLCHOST_CONF52_V)<<(HOST_SLCHOST_CONF52_S)) +#define HOST_SLCHOST_CONF52_V 0xFF +#define HOST_SLCHOST_CONF52_S 0 + +#define HOST_SLCHOST_CONF_W14_REG (DR_REG_SLCHOST_BASE + 0xB4) +/* HOST_SLCHOST_CONF59 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF59 0x000000FF +#define HOST_SLCHOST_CONF59_M ((HOST_SLCHOST_CONF59_V)<<(HOST_SLCHOST_CONF59_S)) +#define HOST_SLCHOST_CONF59_V 0xFF +#define HOST_SLCHOST_CONF59_S 24 +/* HOST_SLCHOST_CONF58 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF58 0x000000FF +#define HOST_SLCHOST_CONF58_M ((HOST_SLCHOST_CONF58_V)<<(HOST_SLCHOST_CONF58_S)) +#define HOST_SLCHOST_CONF58_V 0xFF +#define HOST_SLCHOST_CONF58_S 16 +/* HOST_SLCHOST_CONF57 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF57 0x000000FF +#define HOST_SLCHOST_CONF57_M ((HOST_SLCHOST_CONF57_V)<<(HOST_SLCHOST_CONF57_S)) +#define HOST_SLCHOST_CONF57_V 0xFF +#define HOST_SLCHOST_CONF57_S 8 +/* HOST_SLCHOST_CONF56 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF56 0x000000FF +#define HOST_SLCHOST_CONF56_M ((HOST_SLCHOST_CONF56_V)<<(HOST_SLCHOST_CONF56_S)) +#define HOST_SLCHOST_CONF56_V 0xFF +#define HOST_SLCHOST_CONF56_S 0 + +#define HOST_SLCHOST_CONF_W15_REG (DR_REG_SLCHOST_BASE + 0xB8) +/* HOST_SLCHOST_CONF63 : R/W ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF63 0x000000FF +#define HOST_SLCHOST_CONF63_M ((HOST_SLCHOST_CONF63_V)<<(HOST_SLCHOST_CONF63_S)) +#define HOST_SLCHOST_CONF63_V 0xFF +#define HOST_SLCHOST_CONF63_S 24 +/* HOST_SLCHOST_CONF62 : R/W ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF62 0x000000FF +#define HOST_SLCHOST_CONF62_M ((HOST_SLCHOST_CONF62_V)<<(HOST_SLCHOST_CONF62_S)) +#define HOST_SLCHOST_CONF62_V 0xFF +#define HOST_SLCHOST_CONF62_S 16 +/* HOST_SLCHOST_CONF61 : R/W ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF61 0x000000FF +#define HOST_SLCHOST_CONF61_M ((HOST_SLCHOST_CONF61_V)<<(HOST_SLCHOST_CONF61_S)) +#define HOST_SLCHOST_CONF61_V 0xFF +#define HOST_SLCHOST_CONF61_S 8 +/* HOST_SLCHOST_CONF60 : R/W ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define HOST_SLCHOST_CONF60 0x000000FF +#define HOST_SLCHOST_CONF60_M ((HOST_SLCHOST_CONF60_V)<<(HOST_SLCHOST_CONF60_S)) +#define HOST_SLCHOST_CONF60_V 0xFF +#define HOST_SLCHOST_CONF60_S 0 + +#define HOST_SLCHOST_CHECK_SUM0_REG (DR_REG_SLCHOST_BASE + 0xBC) +/* HOST_SLCHOST_CHECK_SUM0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define HOST_SLCHOST_CHECK_SUM0 0xFFFFFFFF +#define HOST_SLCHOST_CHECK_SUM0_M ((HOST_SLCHOST_CHECK_SUM0_V)<<(HOST_SLCHOST_CHECK_SUM0_S)) +#define HOST_SLCHOST_CHECK_SUM0_V 0xFFFFFFFF +#define HOST_SLCHOST_CHECK_SUM0_S 0 + +#define HOST_SLCHOST_CHECK_SUM1_REG (DR_REG_SLCHOST_BASE + 0xC0) +/* HOST_SLCHOST_CHECK_SUM1 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define HOST_SLCHOST_CHECK_SUM1 0xFFFFFFFF +#define HOST_SLCHOST_CHECK_SUM1_M ((HOST_SLCHOST_CHECK_SUM1_V)<<(HOST_SLCHOST_CHECK_SUM1_S)) +#define HOST_SLCHOST_CHECK_SUM1_V 0xFFFFFFFF +#define HOST_SLCHOST_CHECK_SUM1_S 0 + +#define HOST_SLC1HOST_TOKEN_RDATA_REG (DR_REG_SLCHOST_BASE + 0xC4) +/* HOST_SLC1_RX_PF_EOF : RO ;bitpos:[31:28] ;default: 4'h0 ; */ +/*description: */ +#define HOST_SLC1_RX_PF_EOF 0x0000000F +#define HOST_SLC1_RX_PF_EOF_M ((HOST_SLC1_RX_PF_EOF_V)<<(HOST_SLC1_RX_PF_EOF_S)) +#define HOST_SLC1_RX_PF_EOF_V 0xF +#define HOST_SLC1_RX_PF_EOF_S 28 +/* HOST_HOSTSLC1_TOKEN1 : RO ;bitpos:[27:16] ;default: 12'h0 ; */ +/*description: */ +#define HOST_HOSTSLC1_TOKEN1 0x00000FFF +#define HOST_HOSTSLC1_TOKEN1_M ((HOST_HOSTSLC1_TOKEN1_V)<<(HOST_HOSTSLC1_TOKEN1_S)) +#define HOST_HOSTSLC1_TOKEN1_V 0xFFF +#define HOST_HOSTSLC1_TOKEN1_S 16 +/* HOST_SLC1_RX_PF_VALID : RO ;bitpos:[12] ;default: 1'h0 ; */ +/*description: */ +#define HOST_SLC1_RX_PF_VALID (BIT(12)) +#define HOST_SLC1_RX_PF_VALID_M (BIT(12)) +#define HOST_SLC1_RX_PF_VALID_V 0x1 +#define HOST_SLC1_RX_PF_VALID_S 12 +/* HOST_SLC1_TOKEN0 : RO ;bitpos:[11:0] ;default: 12'h0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0 0x00000FFF +#define HOST_SLC1_TOKEN0_M ((HOST_SLC1_TOKEN0_V)<<(HOST_SLC1_TOKEN0_S)) +#define HOST_SLC1_TOKEN0_V 0xFFF +#define HOST_SLC1_TOKEN0_S 0 + +#define HOST_SLC0HOST_TOKEN_WDATA_REG (DR_REG_SLCHOST_BASE + 0xC8) +/* HOST_SLC0HOST_TOKEN1_WD : R/W ;bitpos:[27:16] ;default: 12'h0 ; */ +/*description: */ +#define HOST_SLC0HOST_TOKEN1_WD 0x00000FFF +#define HOST_SLC0HOST_TOKEN1_WD_M ((HOST_SLC0HOST_TOKEN1_WD_V)<<(HOST_SLC0HOST_TOKEN1_WD_S)) +#define HOST_SLC0HOST_TOKEN1_WD_V 0xFFF +#define HOST_SLC0HOST_TOKEN1_WD_S 16 +/* HOST_SLC0HOST_TOKEN0_WD : R/W ;bitpos:[11:0] ;default: 12'h0 ; */ +/*description: */ +#define HOST_SLC0HOST_TOKEN0_WD 0x00000FFF +#define HOST_SLC0HOST_TOKEN0_WD_M ((HOST_SLC0HOST_TOKEN0_WD_V)<<(HOST_SLC0HOST_TOKEN0_WD_S)) +#define HOST_SLC0HOST_TOKEN0_WD_V 0xFFF +#define HOST_SLC0HOST_TOKEN0_WD_S 0 + +#define HOST_SLC1HOST_TOKEN_WDATA_REG (DR_REG_SLCHOST_BASE + 0xCC) +/* HOST_SLC1HOST_TOKEN1_WD : R/W ;bitpos:[27:16] ;default: 12'h0 ; */ +/*description: */ +#define HOST_SLC1HOST_TOKEN1_WD 0x00000FFF +#define HOST_SLC1HOST_TOKEN1_WD_M ((HOST_SLC1HOST_TOKEN1_WD_V)<<(HOST_SLC1HOST_TOKEN1_WD_S)) +#define HOST_SLC1HOST_TOKEN1_WD_V 0xFFF +#define HOST_SLC1HOST_TOKEN1_WD_S 16 +/* HOST_SLC1HOST_TOKEN0_WD : R/W ;bitpos:[11:0] ;default: 12'h0 ; */ +/*description: */ +#define HOST_SLC1HOST_TOKEN0_WD 0x00000FFF +#define HOST_SLC1HOST_TOKEN0_WD_M ((HOST_SLC1HOST_TOKEN0_WD_V)<<(HOST_SLC1HOST_TOKEN0_WD_S)) +#define HOST_SLC1HOST_TOKEN0_WD_V 0xFFF +#define HOST_SLC1HOST_TOKEN0_WD_S 0 + +#define HOST_SLCHOST_TOKEN_CON_REG (DR_REG_SLCHOST_BASE + 0xD0) +/* HOST_SLC0HOST_LEN_WR : WO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_LEN_WR (BIT(8)) +#define HOST_SLC0HOST_LEN_WR_M (BIT(8)) +#define HOST_SLC0HOST_LEN_WR_V 0x1 +#define HOST_SLC0HOST_LEN_WR_S 8 +/* HOST_SLC1HOST_TOKEN1_WR : WO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TOKEN1_WR (BIT(7)) +#define HOST_SLC1HOST_TOKEN1_WR_M (BIT(7)) +#define HOST_SLC1HOST_TOKEN1_WR_V 0x1 +#define HOST_SLC1HOST_TOKEN1_WR_S 7 +/* HOST_SLC1HOST_TOKEN0_WR : WO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TOKEN0_WR (BIT(6)) +#define HOST_SLC1HOST_TOKEN0_WR_M (BIT(6)) +#define HOST_SLC1HOST_TOKEN0_WR_V 0x1 +#define HOST_SLC1HOST_TOKEN0_WR_S 6 +/* HOST_SLC1HOST_TOKEN1_DEC : WO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TOKEN1_DEC (BIT(5)) +#define HOST_SLC1HOST_TOKEN1_DEC_M (BIT(5)) +#define HOST_SLC1HOST_TOKEN1_DEC_V 0x1 +#define HOST_SLC1HOST_TOKEN1_DEC_S 5 +/* HOST_SLC1HOST_TOKEN0_DEC : WO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TOKEN0_DEC (BIT(4)) +#define HOST_SLC1HOST_TOKEN0_DEC_M (BIT(4)) +#define HOST_SLC1HOST_TOKEN0_DEC_V 0x1 +#define HOST_SLC1HOST_TOKEN0_DEC_S 4 +/* HOST_SLC0HOST_TOKEN1_WR : WO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TOKEN1_WR (BIT(3)) +#define HOST_SLC0HOST_TOKEN1_WR_M (BIT(3)) +#define HOST_SLC0HOST_TOKEN1_WR_V 0x1 +#define HOST_SLC0HOST_TOKEN1_WR_S 3 +/* HOST_SLC0HOST_TOKEN0_WR : WO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TOKEN0_WR (BIT(2)) +#define HOST_SLC0HOST_TOKEN0_WR_M (BIT(2)) +#define HOST_SLC0HOST_TOKEN0_WR_V 0x1 +#define HOST_SLC0HOST_TOKEN0_WR_S 2 +/* HOST_SLC0HOST_TOKEN1_DEC : WO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TOKEN1_DEC (BIT(1)) +#define HOST_SLC0HOST_TOKEN1_DEC_M (BIT(1)) +#define HOST_SLC0HOST_TOKEN1_DEC_V 0x1 +#define HOST_SLC0HOST_TOKEN1_DEC_S 1 +/* HOST_SLC0HOST_TOKEN0_DEC : WO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TOKEN0_DEC (BIT(0)) +#define HOST_SLC0HOST_TOKEN0_DEC_M (BIT(0)) +#define HOST_SLC0HOST_TOKEN0_DEC_V 0x1 +#define HOST_SLC0HOST_TOKEN0_DEC_S 0 + +#define HOST_SLC0HOST_INT_CLR_REG (DR_REG_SLCHOST_BASE + 0xD4) +/* HOST_GPIO_SDIO_INT_CLR : WO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_INT_CLR (BIT(25)) +#define HOST_GPIO_SDIO_INT_CLR_M (BIT(25)) +#define HOST_GPIO_SDIO_INT_CLR_V 0x1 +#define HOST_GPIO_SDIO_INT_CLR_S 25 +/* HOST_SLC0_HOST_RD_RETRY_INT_CLR : WO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_HOST_RD_RETRY_INT_CLR (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_CLR_M (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_CLR_V 0x1 +#define HOST_SLC0_HOST_RD_RETRY_INT_CLR_S 24 +/* HOST_SLC0_RX_NEW_PACKET_INT_CLR : WO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_NEW_PACKET_INT_CLR (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_CLR_M (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_CLR_V 0x1 +#define HOST_SLC0_RX_NEW_PACKET_INT_CLR_S 23 +/* HOST_SLC0_EXT_BIT3_INT_CLR : WO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT3_INT_CLR (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_CLR_M (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_CLR_V 0x1 +#define HOST_SLC0_EXT_BIT3_INT_CLR_S 22 +/* HOST_SLC0_EXT_BIT2_INT_CLR : WO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT2_INT_CLR (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_CLR_M (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_CLR_V 0x1 +#define HOST_SLC0_EXT_BIT2_INT_CLR_S 21 +/* HOST_SLC0_EXT_BIT1_INT_CLR : WO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT1_INT_CLR (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_CLR_M (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_CLR_V 0x1 +#define HOST_SLC0_EXT_BIT1_INT_CLR_S 20 +/* HOST_SLC0_EXT_BIT0_INT_CLR : WO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT0_INT_CLR (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_CLR_M (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_CLR_V 0x1 +#define HOST_SLC0_EXT_BIT0_INT_CLR_S 19 +/* HOST_SLC0_RX_PF_VALID_INT_CLR : WO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_PF_VALID_INT_CLR (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_CLR_M (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_CLR_V 0x1 +#define HOST_SLC0_RX_PF_VALID_INT_CLR_S 18 +/* HOST_SLC0_TX_OVF_INT_CLR : WO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TX_OVF_INT_CLR (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_CLR_M (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_CLR_V 0x1 +#define HOST_SLC0_TX_OVF_INT_CLR_S 17 +/* HOST_SLC0_RX_UDF_INT_CLR : WO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_UDF_INT_CLR (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_CLR_M (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_CLR_V 0x1 +#define HOST_SLC0_RX_UDF_INT_CLR_S 16 +/* HOST_SLC0HOST_TX_START_INT_CLR : WO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TX_START_INT_CLR (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_CLR_M (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_CLR_V 0x1 +#define HOST_SLC0HOST_TX_START_INT_CLR_S 15 +/* HOST_SLC0HOST_RX_START_INT_CLR : WO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_START_INT_CLR (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_CLR_M (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_CLR_V 0x1 +#define HOST_SLC0HOST_RX_START_INT_CLR_S 14 +/* HOST_SLC0HOST_RX_EOF_INT_CLR : WO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_EOF_INT_CLR (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_CLR_M (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_CLR_V 0x1 +#define HOST_SLC0HOST_RX_EOF_INT_CLR_S 13 +/* HOST_SLC0HOST_RX_SOF_INT_CLR : WO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_SOF_INT_CLR (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_CLR_M (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_CLR_V 0x1 +#define HOST_SLC0HOST_RX_SOF_INT_CLR_S 12 +/* HOST_SLC0_TOKEN1_0TO1_INT_CLR : WO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_0TO1_INT_CLR (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_CLR_M (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_CLR_V 0x1 +#define HOST_SLC0_TOKEN1_0TO1_INT_CLR_S 11 +/* HOST_SLC0_TOKEN0_0TO1_INT_CLR : WO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_0TO1_INT_CLR (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_CLR_M (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_CLR_V 0x1 +#define HOST_SLC0_TOKEN0_0TO1_INT_CLR_S 10 +/* HOST_SLC0_TOKEN1_1TO0_INT_CLR : WO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_1TO0_INT_CLR (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_CLR_M (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_CLR_V 0x1 +#define HOST_SLC0_TOKEN1_1TO0_INT_CLR_S 9 +/* HOST_SLC0_TOKEN0_1TO0_INT_CLR : WO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_1TO0_INT_CLR (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_CLR_M (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_CLR_V 0x1 +#define HOST_SLC0_TOKEN0_1TO0_INT_CLR_S 8 +/* HOST_SLC0_TOHOST_BIT7_INT_CLR : WO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT7_INT_CLR (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_CLR_M (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_CLR_V 0x1 +#define HOST_SLC0_TOHOST_BIT7_INT_CLR_S 7 +/* HOST_SLC0_TOHOST_BIT6_INT_CLR : WO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT6_INT_CLR (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_CLR_M (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_CLR_V 0x1 +#define HOST_SLC0_TOHOST_BIT6_INT_CLR_S 6 +/* HOST_SLC0_TOHOST_BIT5_INT_CLR : WO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT5_INT_CLR (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_CLR_M (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_CLR_V 0x1 +#define HOST_SLC0_TOHOST_BIT5_INT_CLR_S 5 +/* HOST_SLC0_TOHOST_BIT4_INT_CLR : WO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT4_INT_CLR (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_CLR_M (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_CLR_V 0x1 +#define HOST_SLC0_TOHOST_BIT4_INT_CLR_S 4 +/* HOST_SLC0_TOHOST_BIT3_INT_CLR : WO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT3_INT_CLR (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_CLR_M (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_CLR_V 0x1 +#define HOST_SLC0_TOHOST_BIT3_INT_CLR_S 3 +/* HOST_SLC0_TOHOST_BIT2_INT_CLR : WO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT2_INT_CLR (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_CLR_M (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_CLR_V 0x1 +#define HOST_SLC0_TOHOST_BIT2_INT_CLR_S 2 +/* HOST_SLC0_TOHOST_BIT1_INT_CLR : WO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT1_INT_CLR (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_CLR_M (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_CLR_V 0x1 +#define HOST_SLC0_TOHOST_BIT1_INT_CLR_S 1 +/* HOST_SLC0_TOHOST_BIT0_INT_CLR : WO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT0_INT_CLR (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_CLR_M (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_CLR_V 0x1 +#define HOST_SLC0_TOHOST_BIT0_INT_CLR_S 0 + +#define HOST_SLC1HOST_INT_CLR_REG (DR_REG_SLCHOST_BASE + 0xD8) +/* HOST_SLC1_BT_RX_NEW_PACKET_INT_CLR : WO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_CLR (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_CLR_M (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_CLR_V 0x1 +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_CLR_S 25 +/* HOST_SLC1_HOST_RD_RETRY_INT_CLR : WO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_HOST_RD_RETRY_INT_CLR (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_CLR_M (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_CLR_V 0x1 +#define HOST_SLC1_HOST_RD_RETRY_INT_CLR_S 24 +/* HOST_SLC1_WIFI_RX_NEW_PACKET_INT_CLR : WO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_CLR (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_CLR_M (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_CLR_V 0x1 +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_CLR_S 23 +/* HOST_SLC1_EXT_BIT3_INT_CLR : WO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT3_INT_CLR (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_CLR_M (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_CLR_V 0x1 +#define HOST_SLC1_EXT_BIT3_INT_CLR_S 22 +/* HOST_SLC1_EXT_BIT2_INT_CLR : WO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT2_INT_CLR (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_CLR_M (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_CLR_V 0x1 +#define HOST_SLC1_EXT_BIT2_INT_CLR_S 21 +/* HOST_SLC1_EXT_BIT1_INT_CLR : WO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT1_INT_CLR (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_CLR_M (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_CLR_V 0x1 +#define HOST_SLC1_EXT_BIT1_INT_CLR_S 20 +/* HOST_SLC1_EXT_BIT0_INT_CLR : WO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT0_INT_CLR (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_CLR_M (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_CLR_V 0x1 +#define HOST_SLC1_EXT_BIT0_INT_CLR_S 19 +/* HOST_SLC1_RX_PF_VALID_INT_CLR : WO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_PF_VALID_INT_CLR (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_CLR_M (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_CLR_V 0x1 +#define HOST_SLC1_RX_PF_VALID_INT_CLR_S 18 +/* HOST_SLC1_TX_OVF_INT_CLR : WO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TX_OVF_INT_CLR (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_CLR_M (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_CLR_V 0x1 +#define HOST_SLC1_TX_OVF_INT_CLR_S 17 +/* HOST_SLC1_RX_UDF_INT_CLR : WO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_UDF_INT_CLR (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_CLR_M (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_CLR_V 0x1 +#define HOST_SLC1_RX_UDF_INT_CLR_S 16 +/* HOST_SLC1HOST_TX_START_INT_CLR : WO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TX_START_INT_CLR (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_CLR_M (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_CLR_V 0x1 +#define HOST_SLC1HOST_TX_START_INT_CLR_S 15 +/* HOST_SLC1HOST_RX_START_INT_CLR : WO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_START_INT_CLR (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_CLR_M (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_CLR_V 0x1 +#define HOST_SLC1HOST_RX_START_INT_CLR_S 14 +/* HOST_SLC1HOST_RX_EOF_INT_CLR : WO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_EOF_INT_CLR (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_CLR_M (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_CLR_V 0x1 +#define HOST_SLC1HOST_RX_EOF_INT_CLR_S 13 +/* HOST_SLC1HOST_RX_SOF_INT_CLR : WO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_SOF_INT_CLR (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_CLR_M (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_CLR_V 0x1 +#define HOST_SLC1HOST_RX_SOF_INT_CLR_S 12 +/* HOST_SLC1_TOKEN1_0TO1_INT_CLR : WO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_0TO1_INT_CLR (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_CLR_M (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_CLR_V 0x1 +#define HOST_SLC1_TOKEN1_0TO1_INT_CLR_S 11 +/* HOST_SLC1_TOKEN0_0TO1_INT_CLR : WO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_0TO1_INT_CLR (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_CLR_M (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_CLR_V 0x1 +#define HOST_SLC1_TOKEN0_0TO1_INT_CLR_S 10 +/* HOST_SLC1_TOKEN1_1TO0_INT_CLR : WO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_1TO0_INT_CLR (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_CLR_M (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_CLR_V 0x1 +#define HOST_SLC1_TOKEN1_1TO0_INT_CLR_S 9 +/* HOST_SLC1_TOKEN0_1TO0_INT_CLR : WO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_1TO0_INT_CLR (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_CLR_M (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_CLR_V 0x1 +#define HOST_SLC1_TOKEN0_1TO0_INT_CLR_S 8 +/* HOST_SLC1_TOHOST_BIT7_INT_CLR : WO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT7_INT_CLR (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_CLR_M (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_CLR_V 0x1 +#define HOST_SLC1_TOHOST_BIT7_INT_CLR_S 7 +/* HOST_SLC1_TOHOST_BIT6_INT_CLR : WO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT6_INT_CLR (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_CLR_M (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_CLR_V 0x1 +#define HOST_SLC1_TOHOST_BIT6_INT_CLR_S 6 +/* HOST_SLC1_TOHOST_BIT5_INT_CLR : WO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT5_INT_CLR (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_CLR_M (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_CLR_V 0x1 +#define HOST_SLC1_TOHOST_BIT5_INT_CLR_S 5 +/* HOST_SLC1_TOHOST_BIT4_INT_CLR : WO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT4_INT_CLR (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_CLR_M (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_CLR_V 0x1 +#define HOST_SLC1_TOHOST_BIT4_INT_CLR_S 4 +/* HOST_SLC1_TOHOST_BIT3_INT_CLR : WO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT3_INT_CLR (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_CLR_M (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_CLR_V 0x1 +#define HOST_SLC1_TOHOST_BIT3_INT_CLR_S 3 +/* HOST_SLC1_TOHOST_BIT2_INT_CLR : WO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT2_INT_CLR (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_CLR_M (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_CLR_V 0x1 +#define HOST_SLC1_TOHOST_BIT2_INT_CLR_S 2 +/* HOST_SLC1_TOHOST_BIT1_INT_CLR : WO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT1_INT_CLR (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_CLR_M (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_CLR_V 0x1 +#define HOST_SLC1_TOHOST_BIT1_INT_CLR_S 1 +/* HOST_SLC1_TOHOST_BIT0_INT_CLR : WO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT0_INT_CLR (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_CLR_M (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_CLR_V 0x1 +#define HOST_SLC1_TOHOST_BIT0_INT_CLR_S 0 + +#define HOST_SLC0HOST_FUNC1_INT_ENA_REG (DR_REG_SLCHOST_BASE + 0xDC) +/* HOST_FN1_GPIO_SDIO_INT_ENA : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_GPIO_SDIO_INT_ENA (BIT(25)) +#define HOST_FN1_GPIO_SDIO_INT_ENA_M (BIT(25)) +#define HOST_FN1_GPIO_SDIO_INT_ENA_V 0x1 +#define HOST_FN1_GPIO_SDIO_INT_ENA_S 25 +/* HOST_FN1_SLC0_HOST_RD_RETRY_INT_ENA : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_HOST_RD_RETRY_INT_ENA (BIT(24)) +#define HOST_FN1_SLC0_HOST_RD_RETRY_INT_ENA_M (BIT(24)) +#define HOST_FN1_SLC0_HOST_RD_RETRY_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_HOST_RD_RETRY_INT_ENA_S 24 +/* HOST_FN1_SLC0_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_RX_NEW_PACKET_INT_ENA (BIT(23)) +#define HOST_FN1_SLC0_RX_NEW_PACKET_INT_ENA_M (BIT(23)) +#define HOST_FN1_SLC0_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_RX_NEW_PACKET_INT_ENA_S 23 +/* HOST_FN1_SLC0_EXT_BIT3_INT_ENA : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_EXT_BIT3_INT_ENA (BIT(22)) +#define HOST_FN1_SLC0_EXT_BIT3_INT_ENA_M (BIT(22)) +#define HOST_FN1_SLC0_EXT_BIT3_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_EXT_BIT3_INT_ENA_S 22 +/* HOST_FN1_SLC0_EXT_BIT2_INT_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_EXT_BIT2_INT_ENA (BIT(21)) +#define HOST_FN1_SLC0_EXT_BIT2_INT_ENA_M (BIT(21)) +#define HOST_FN1_SLC0_EXT_BIT2_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_EXT_BIT2_INT_ENA_S 21 +/* HOST_FN1_SLC0_EXT_BIT1_INT_ENA : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_EXT_BIT1_INT_ENA (BIT(20)) +#define HOST_FN1_SLC0_EXT_BIT1_INT_ENA_M (BIT(20)) +#define HOST_FN1_SLC0_EXT_BIT1_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_EXT_BIT1_INT_ENA_S 20 +/* HOST_FN1_SLC0_EXT_BIT0_INT_ENA : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_EXT_BIT0_INT_ENA (BIT(19)) +#define HOST_FN1_SLC0_EXT_BIT0_INT_ENA_M (BIT(19)) +#define HOST_FN1_SLC0_EXT_BIT0_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_EXT_BIT0_INT_ENA_S 19 +/* HOST_FN1_SLC0_RX_PF_VALID_INT_ENA : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_RX_PF_VALID_INT_ENA (BIT(18)) +#define HOST_FN1_SLC0_RX_PF_VALID_INT_ENA_M (BIT(18)) +#define HOST_FN1_SLC0_RX_PF_VALID_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_RX_PF_VALID_INT_ENA_S 18 +/* HOST_FN1_SLC0_TX_OVF_INT_ENA : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TX_OVF_INT_ENA (BIT(17)) +#define HOST_FN1_SLC0_TX_OVF_INT_ENA_M (BIT(17)) +#define HOST_FN1_SLC0_TX_OVF_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TX_OVF_INT_ENA_S 17 +/* HOST_FN1_SLC0_RX_UDF_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_RX_UDF_INT_ENA (BIT(16)) +#define HOST_FN1_SLC0_RX_UDF_INT_ENA_M (BIT(16)) +#define HOST_FN1_SLC0_RX_UDF_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_RX_UDF_INT_ENA_S 16 +/* HOST_FN1_SLC0HOST_TX_START_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0HOST_TX_START_INT_ENA (BIT(15)) +#define HOST_FN1_SLC0HOST_TX_START_INT_ENA_M (BIT(15)) +#define HOST_FN1_SLC0HOST_TX_START_INT_ENA_V 0x1 +#define HOST_FN1_SLC0HOST_TX_START_INT_ENA_S 15 +/* HOST_FN1_SLC0HOST_RX_START_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0HOST_RX_START_INT_ENA (BIT(14)) +#define HOST_FN1_SLC0HOST_RX_START_INT_ENA_M (BIT(14)) +#define HOST_FN1_SLC0HOST_RX_START_INT_ENA_V 0x1 +#define HOST_FN1_SLC0HOST_RX_START_INT_ENA_S 14 +/* HOST_FN1_SLC0HOST_RX_EOF_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0HOST_RX_EOF_INT_ENA (BIT(13)) +#define HOST_FN1_SLC0HOST_RX_EOF_INT_ENA_M (BIT(13)) +#define HOST_FN1_SLC0HOST_RX_EOF_INT_ENA_V 0x1 +#define HOST_FN1_SLC0HOST_RX_EOF_INT_ENA_S 13 +/* HOST_FN1_SLC0HOST_RX_SOF_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0HOST_RX_SOF_INT_ENA (BIT(12)) +#define HOST_FN1_SLC0HOST_RX_SOF_INT_ENA_M (BIT(12)) +#define HOST_FN1_SLC0HOST_RX_SOF_INT_ENA_V 0x1 +#define HOST_FN1_SLC0HOST_RX_SOF_INT_ENA_S 12 +/* HOST_FN1_SLC0_TOKEN1_0TO1_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOKEN1_0TO1_INT_ENA (BIT(11)) +#define HOST_FN1_SLC0_TOKEN1_0TO1_INT_ENA_M (BIT(11)) +#define HOST_FN1_SLC0_TOKEN1_0TO1_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOKEN1_0TO1_INT_ENA_S 11 +/* HOST_FN1_SLC0_TOKEN0_0TO1_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOKEN0_0TO1_INT_ENA (BIT(10)) +#define HOST_FN1_SLC0_TOKEN0_0TO1_INT_ENA_M (BIT(10)) +#define HOST_FN1_SLC0_TOKEN0_0TO1_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOKEN0_0TO1_INT_ENA_S 10 +/* HOST_FN1_SLC0_TOKEN1_1TO0_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOKEN1_1TO0_INT_ENA (BIT(9)) +#define HOST_FN1_SLC0_TOKEN1_1TO0_INT_ENA_M (BIT(9)) +#define HOST_FN1_SLC0_TOKEN1_1TO0_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOKEN1_1TO0_INT_ENA_S 9 +/* HOST_FN1_SLC0_TOKEN0_1TO0_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOKEN0_1TO0_INT_ENA (BIT(8)) +#define HOST_FN1_SLC0_TOKEN0_1TO0_INT_ENA_M (BIT(8)) +#define HOST_FN1_SLC0_TOKEN0_1TO0_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOKEN0_1TO0_INT_ENA_S 8 +/* HOST_FN1_SLC0_TOHOST_BIT7_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOHOST_BIT7_INT_ENA (BIT(7)) +#define HOST_FN1_SLC0_TOHOST_BIT7_INT_ENA_M (BIT(7)) +#define HOST_FN1_SLC0_TOHOST_BIT7_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOHOST_BIT7_INT_ENA_S 7 +/* HOST_FN1_SLC0_TOHOST_BIT6_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOHOST_BIT6_INT_ENA (BIT(6)) +#define HOST_FN1_SLC0_TOHOST_BIT6_INT_ENA_M (BIT(6)) +#define HOST_FN1_SLC0_TOHOST_BIT6_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOHOST_BIT6_INT_ENA_S 6 +/* HOST_FN1_SLC0_TOHOST_BIT5_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOHOST_BIT5_INT_ENA (BIT(5)) +#define HOST_FN1_SLC0_TOHOST_BIT5_INT_ENA_M (BIT(5)) +#define HOST_FN1_SLC0_TOHOST_BIT5_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOHOST_BIT5_INT_ENA_S 5 +/* HOST_FN1_SLC0_TOHOST_BIT4_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOHOST_BIT4_INT_ENA (BIT(4)) +#define HOST_FN1_SLC0_TOHOST_BIT4_INT_ENA_M (BIT(4)) +#define HOST_FN1_SLC0_TOHOST_BIT4_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOHOST_BIT4_INT_ENA_S 4 +/* HOST_FN1_SLC0_TOHOST_BIT3_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOHOST_BIT3_INT_ENA (BIT(3)) +#define HOST_FN1_SLC0_TOHOST_BIT3_INT_ENA_M (BIT(3)) +#define HOST_FN1_SLC0_TOHOST_BIT3_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOHOST_BIT3_INT_ENA_S 3 +/* HOST_FN1_SLC0_TOHOST_BIT2_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOHOST_BIT2_INT_ENA (BIT(2)) +#define HOST_FN1_SLC0_TOHOST_BIT2_INT_ENA_M (BIT(2)) +#define HOST_FN1_SLC0_TOHOST_BIT2_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOHOST_BIT2_INT_ENA_S 2 +/* HOST_FN1_SLC0_TOHOST_BIT1_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOHOST_BIT1_INT_ENA (BIT(1)) +#define HOST_FN1_SLC0_TOHOST_BIT1_INT_ENA_M (BIT(1)) +#define HOST_FN1_SLC0_TOHOST_BIT1_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOHOST_BIT1_INT_ENA_S 1 +/* HOST_FN1_SLC0_TOHOST_BIT0_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC0_TOHOST_BIT0_INT_ENA (BIT(0)) +#define HOST_FN1_SLC0_TOHOST_BIT0_INT_ENA_M (BIT(0)) +#define HOST_FN1_SLC0_TOHOST_BIT0_INT_ENA_V 0x1 +#define HOST_FN1_SLC0_TOHOST_BIT0_INT_ENA_S 0 + +#define HOST_SLC1HOST_FUNC1_INT_ENA_REG (DR_REG_SLCHOST_BASE + 0xE0) +/* HOST_FN1_SLC1_BT_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_BT_RX_NEW_PACKET_INT_ENA (BIT(25)) +#define HOST_FN1_SLC1_BT_RX_NEW_PACKET_INT_ENA_M (BIT(25)) +#define HOST_FN1_SLC1_BT_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_BT_RX_NEW_PACKET_INT_ENA_S 25 +/* HOST_FN1_SLC1_HOST_RD_RETRY_INT_ENA : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_HOST_RD_RETRY_INT_ENA (BIT(24)) +#define HOST_FN1_SLC1_HOST_RD_RETRY_INT_ENA_M (BIT(24)) +#define HOST_FN1_SLC1_HOST_RD_RETRY_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_HOST_RD_RETRY_INT_ENA_S 24 +/* HOST_FN1_SLC1_WIFI_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_WIFI_RX_NEW_PACKET_INT_ENA (BIT(23)) +#define HOST_FN1_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_M (BIT(23)) +#define HOST_FN1_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_S 23 +/* HOST_FN1_SLC1_EXT_BIT3_INT_ENA : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_EXT_BIT3_INT_ENA (BIT(22)) +#define HOST_FN1_SLC1_EXT_BIT3_INT_ENA_M (BIT(22)) +#define HOST_FN1_SLC1_EXT_BIT3_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_EXT_BIT3_INT_ENA_S 22 +/* HOST_FN1_SLC1_EXT_BIT2_INT_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_EXT_BIT2_INT_ENA (BIT(21)) +#define HOST_FN1_SLC1_EXT_BIT2_INT_ENA_M (BIT(21)) +#define HOST_FN1_SLC1_EXT_BIT2_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_EXT_BIT2_INT_ENA_S 21 +/* HOST_FN1_SLC1_EXT_BIT1_INT_ENA : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_EXT_BIT1_INT_ENA (BIT(20)) +#define HOST_FN1_SLC1_EXT_BIT1_INT_ENA_M (BIT(20)) +#define HOST_FN1_SLC1_EXT_BIT1_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_EXT_BIT1_INT_ENA_S 20 +/* HOST_FN1_SLC1_EXT_BIT0_INT_ENA : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_EXT_BIT0_INT_ENA (BIT(19)) +#define HOST_FN1_SLC1_EXT_BIT0_INT_ENA_M (BIT(19)) +#define HOST_FN1_SLC1_EXT_BIT0_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_EXT_BIT0_INT_ENA_S 19 +/* HOST_FN1_SLC1_RX_PF_VALID_INT_ENA : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_RX_PF_VALID_INT_ENA (BIT(18)) +#define HOST_FN1_SLC1_RX_PF_VALID_INT_ENA_M (BIT(18)) +#define HOST_FN1_SLC1_RX_PF_VALID_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_RX_PF_VALID_INT_ENA_S 18 +/* HOST_FN1_SLC1_TX_OVF_INT_ENA : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TX_OVF_INT_ENA (BIT(17)) +#define HOST_FN1_SLC1_TX_OVF_INT_ENA_M (BIT(17)) +#define HOST_FN1_SLC1_TX_OVF_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TX_OVF_INT_ENA_S 17 +/* HOST_FN1_SLC1_RX_UDF_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_RX_UDF_INT_ENA (BIT(16)) +#define HOST_FN1_SLC1_RX_UDF_INT_ENA_M (BIT(16)) +#define HOST_FN1_SLC1_RX_UDF_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_RX_UDF_INT_ENA_S 16 +/* HOST_FN1_SLC1HOST_TX_START_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1HOST_TX_START_INT_ENA (BIT(15)) +#define HOST_FN1_SLC1HOST_TX_START_INT_ENA_M (BIT(15)) +#define HOST_FN1_SLC1HOST_TX_START_INT_ENA_V 0x1 +#define HOST_FN1_SLC1HOST_TX_START_INT_ENA_S 15 +/* HOST_FN1_SLC1HOST_RX_START_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1HOST_RX_START_INT_ENA (BIT(14)) +#define HOST_FN1_SLC1HOST_RX_START_INT_ENA_M (BIT(14)) +#define HOST_FN1_SLC1HOST_RX_START_INT_ENA_V 0x1 +#define HOST_FN1_SLC1HOST_RX_START_INT_ENA_S 14 +/* HOST_FN1_SLC1HOST_RX_EOF_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1HOST_RX_EOF_INT_ENA (BIT(13)) +#define HOST_FN1_SLC1HOST_RX_EOF_INT_ENA_M (BIT(13)) +#define HOST_FN1_SLC1HOST_RX_EOF_INT_ENA_V 0x1 +#define HOST_FN1_SLC1HOST_RX_EOF_INT_ENA_S 13 +/* HOST_FN1_SLC1HOST_RX_SOF_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1HOST_RX_SOF_INT_ENA (BIT(12)) +#define HOST_FN1_SLC1HOST_RX_SOF_INT_ENA_M (BIT(12)) +#define HOST_FN1_SLC1HOST_RX_SOF_INT_ENA_V 0x1 +#define HOST_FN1_SLC1HOST_RX_SOF_INT_ENA_S 12 +/* HOST_FN1_SLC1_TOKEN1_0TO1_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOKEN1_0TO1_INT_ENA (BIT(11)) +#define HOST_FN1_SLC1_TOKEN1_0TO1_INT_ENA_M (BIT(11)) +#define HOST_FN1_SLC1_TOKEN1_0TO1_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOKEN1_0TO1_INT_ENA_S 11 +/* HOST_FN1_SLC1_TOKEN0_0TO1_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOKEN0_0TO1_INT_ENA (BIT(10)) +#define HOST_FN1_SLC1_TOKEN0_0TO1_INT_ENA_M (BIT(10)) +#define HOST_FN1_SLC1_TOKEN0_0TO1_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOKEN0_0TO1_INT_ENA_S 10 +/* HOST_FN1_SLC1_TOKEN1_1TO0_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOKEN1_1TO0_INT_ENA (BIT(9)) +#define HOST_FN1_SLC1_TOKEN1_1TO0_INT_ENA_M (BIT(9)) +#define HOST_FN1_SLC1_TOKEN1_1TO0_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOKEN1_1TO0_INT_ENA_S 9 +/* HOST_FN1_SLC1_TOKEN0_1TO0_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOKEN0_1TO0_INT_ENA (BIT(8)) +#define HOST_FN1_SLC1_TOKEN0_1TO0_INT_ENA_M (BIT(8)) +#define HOST_FN1_SLC1_TOKEN0_1TO0_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOKEN0_1TO0_INT_ENA_S 8 +/* HOST_FN1_SLC1_TOHOST_BIT7_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOHOST_BIT7_INT_ENA (BIT(7)) +#define HOST_FN1_SLC1_TOHOST_BIT7_INT_ENA_M (BIT(7)) +#define HOST_FN1_SLC1_TOHOST_BIT7_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOHOST_BIT7_INT_ENA_S 7 +/* HOST_FN1_SLC1_TOHOST_BIT6_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOHOST_BIT6_INT_ENA (BIT(6)) +#define HOST_FN1_SLC1_TOHOST_BIT6_INT_ENA_M (BIT(6)) +#define HOST_FN1_SLC1_TOHOST_BIT6_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOHOST_BIT6_INT_ENA_S 6 +/* HOST_FN1_SLC1_TOHOST_BIT5_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOHOST_BIT5_INT_ENA (BIT(5)) +#define HOST_FN1_SLC1_TOHOST_BIT5_INT_ENA_M (BIT(5)) +#define HOST_FN1_SLC1_TOHOST_BIT5_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOHOST_BIT5_INT_ENA_S 5 +/* HOST_FN1_SLC1_TOHOST_BIT4_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOHOST_BIT4_INT_ENA (BIT(4)) +#define HOST_FN1_SLC1_TOHOST_BIT4_INT_ENA_M (BIT(4)) +#define HOST_FN1_SLC1_TOHOST_BIT4_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOHOST_BIT4_INT_ENA_S 4 +/* HOST_FN1_SLC1_TOHOST_BIT3_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOHOST_BIT3_INT_ENA (BIT(3)) +#define HOST_FN1_SLC1_TOHOST_BIT3_INT_ENA_M (BIT(3)) +#define HOST_FN1_SLC1_TOHOST_BIT3_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOHOST_BIT3_INT_ENA_S 3 +/* HOST_FN1_SLC1_TOHOST_BIT2_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOHOST_BIT2_INT_ENA (BIT(2)) +#define HOST_FN1_SLC1_TOHOST_BIT2_INT_ENA_M (BIT(2)) +#define HOST_FN1_SLC1_TOHOST_BIT2_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOHOST_BIT2_INT_ENA_S 2 +/* HOST_FN1_SLC1_TOHOST_BIT1_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOHOST_BIT1_INT_ENA (BIT(1)) +#define HOST_FN1_SLC1_TOHOST_BIT1_INT_ENA_M (BIT(1)) +#define HOST_FN1_SLC1_TOHOST_BIT1_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOHOST_BIT1_INT_ENA_S 1 +/* HOST_FN1_SLC1_TOHOST_BIT0_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN1_SLC1_TOHOST_BIT0_INT_ENA (BIT(0)) +#define HOST_FN1_SLC1_TOHOST_BIT0_INT_ENA_M (BIT(0)) +#define HOST_FN1_SLC1_TOHOST_BIT0_INT_ENA_V 0x1 +#define HOST_FN1_SLC1_TOHOST_BIT0_INT_ENA_S 0 + +#define HOST_SLC0HOST_FUNC2_INT_ENA_REG (DR_REG_SLCHOST_BASE + 0xE4) +/* HOST_FN2_GPIO_SDIO_INT_ENA : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_GPIO_SDIO_INT_ENA (BIT(25)) +#define HOST_FN2_GPIO_SDIO_INT_ENA_M (BIT(25)) +#define HOST_FN2_GPIO_SDIO_INT_ENA_V 0x1 +#define HOST_FN2_GPIO_SDIO_INT_ENA_S 25 +/* HOST_FN2_SLC0_HOST_RD_RETRY_INT_ENA : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_HOST_RD_RETRY_INT_ENA (BIT(24)) +#define HOST_FN2_SLC0_HOST_RD_RETRY_INT_ENA_M (BIT(24)) +#define HOST_FN2_SLC0_HOST_RD_RETRY_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_HOST_RD_RETRY_INT_ENA_S 24 +/* HOST_FN2_SLC0_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_RX_NEW_PACKET_INT_ENA (BIT(23)) +#define HOST_FN2_SLC0_RX_NEW_PACKET_INT_ENA_M (BIT(23)) +#define HOST_FN2_SLC0_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_RX_NEW_PACKET_INT_ENA_S 23 +/* HOST_FN2_SLC0_EXT_BIT3_INT_ENA : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_EXT_BIT3_INT_ENA (BIT(22)) +#define HOST_FN2_SLC0_EXT_BIT3_INT_ENA_M (BIT(22)) +#define HOST_FN2_SLC0_EXT_BIT3_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_EXT_BIT3_INT_ENA_S 22 +/* HOST_FN2_SLC0_EXT_BIT2_INT_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_EXT_BIT2_INT_ENA (BIT(21)) +#define HOST_FN2_SLC0_EXT_BIT2_INT_ENA_M (BIT(21)) +#define HOST_FN2_SLC0_EXT_BIT2_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_EXT_BIT2_INT_ENA_S 21 +/* HOST_FN2_SLC0_EXT_BIT1_INT_ENA : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_EXT_BIT1_INT_ENA (BIT(20)) +#define HOST_FN2_SLC0_EXT_BIT1_INT_ENA_M (BIT(20)) +#define HOST_FN2_SLC0_EXT_BIT1_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_EXT_BIT1_INT_ENA_S 20 +/* HOST_FN2_SLC0_EXT_BIT0_INT_ENA : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_EXT_BIT0_INT_ENA (BIT(19)) +#define HOST_FN2_SLC0_EXT_BIT0_INT_ENA_M (BIT(19)) +#define HOST_FN2_SLC0_EXT_BIT0_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_EXT_BIT0_INT_ENA_S 19 +/* HOST_FN2_SLC0_RX_PF_VALID_INT_ENA : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_RX_PF_VALID_INT_ENA (BIT(18)) +#define HOST_FN2_SLC0_RX_PF_VALID_INT_ENA_M (BIT(18)) +#define HOST_FN2_SLC0_RX_PF_VALID_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_RX_PF_VALID_INT_ENA_S 18 +/* HOST_FN2_SLC0_TX_OVF_INT_ENA : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TX_OVF_INT_ENA (BIT(17)) +#define HOST_FN2_SLC0_TX_OVF_INT_ENA_M (BIT(17)) +#define HOST_FN2_SLC0_TX_OVF_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TX_OVF_INT_ENA_S 17 +/* HOST_FN2_SLC0_RX_UDF_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_RX_UDF_INT_ENA (BIT(16)) +#define HOST_FN2_SLC0_RX_UDF_INT_ENA_M (BIT(16)) +#define HOST_FN2_SLC0_RX_UDF_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_RX_UDF_INT_ENA_S 16 +/* HOST_FN2_SLC0HOST_TX_START_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0HOST_TX_START_INT_ENA (BIT(15)) +#define HOST_FN2_SLC0HOST_TX_START_INT_ENA_M (BIT(15)) +#define HOST_FN2_SLC0HOST_TX_START_INT_ENA_V 0x1 +#define HOST_FN2_SLC0HOST_TX_START_INT_ENA_S 15 +/* HOST_FN2_SLC0HOST_RX_START_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0HOST_RX_START_INT_ENA (BIT(14)) +#define HOST_FN2_SLC0HOST_RX_START_INT_ENA_M (BIT(14)) +#define HOST_FN2_SLC0HOST_RX_START_INT_ENA_V 0x1 +#define HOST_FN2_SLC0HOST_RX_START_INT_ENA_S 14 +/* HOST_FN2_SLC0HOST_RX_EOF_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0HOST_RX_EOF_INT_ENA (BIT(13)) +#define HOST_FN2_SLC0HOST_RX_EOF_INT_ENA_M (BIT(13)) +#define HOST_FN2_SLC0HOST_RX_EOF_INT_ENA_V 0x1 +#define HOST_FN2_SLC0HOST_RX_EOF_INT_ENA_S 13 +/* HOST_FN2_SLC0HOST_RX_SOF_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0HOST_RX_SOF_INT_ENA (BIT(12)) +#define HOST_FN2_SLC0HOST_RX_SOF_INT_ENA_M (BIT(12)) +#define HOST_FN2_SLC0HOST_RX_SOF_INT_ENA_V 0x1 +#define HOST_FN2_SLC0HOST_RX_SOF_INT_ENA_S 12 +/* HOST_FN2_SLC0_TOKEN1_0TO1_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOKEN1_0TO1_INT_ENA (BIT(11)) +#define HOST_FN2_SLC0_TOKEN1_0TO1_INT_ENA_M (BIT(11)) +#define HOST_FN2_SLC0_TOKEN1_0TO1_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOKEN1_0TO1_INT_ENA_S 11 +/* HOST_FN2_SLC0_TOKEN0_0TO1_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOKEN0_0TO1_INT_ENA (BIT(10)) +#define HOST_FN2_SLC0_TOKEN0_0TO1_INT_ENA_M (BIT(10)) +#define HOST_FN2_SLC0_TOKEN0_0TO1_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOKEN0_0TO1_INT_ENA_S 10 +/* HOST_FN2_SLC0_TOKEN1_1TO0_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOKEN1_1TO0_INT_ENA (BIT(9)) +#define HOST_FN2_SLC0_TOKEN1_1TO0_INT_ENA_M (BIT(9)) +#define HOST_FN2_SLC0_TOKEN1_1TO0_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOKEN1_1TO0_INT_ENA_S 9 +/* HOST_FN2_SLC0_TOKEN0_1TO0_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOKEN0_1TO0_INT_ENA (BIT(8)) +#define HOST_FN2_SLC0_TOKEN0_1TO0_INT_ENA_M (BIT(8)) +#define HOST_FN2_SLC0_TOKEN0_1TO0_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOKEN0_1TO0_INT_ENA_S 8 +/* HOST_FN2_SLC0_TOHOST_BIT7_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOHOST_BIT7_INT_ENA (BIT(7)) +#define HOST_FN2_SLC0_TOHOST_BIT7_INT_ENA_M (BIT(7)) +#define HOST_FN2_SLC0_TOHOST_BIT7_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOHOST_BIT7_INT_ENA_S 7 +/* HOST_FN2_SLC0_TOHOST_BIT6_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOHOST_BIT6_INT_ENA (BIT(6)) +#define HOST_FN2_SLC0_TOHOST_BIT6_INT_ENA_M (BIT(6)) +#define HOST_FN2_SLC0_TOHOST_BIT6_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOHOST_BIT6_INT_ENA_S 6 +/* HOST_FN2_SLC0_TOHOST_BIT5_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOHOST_BIT5_INT_ENA (BIT(5)) +#define HOST_FN2_SLC0_TOHOST_BIT5_INT_ENA_M (BIT(5)) +#define HOST_FN2_SLC0_TOHOST_BIT5_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOHOST_BIT5_INT_ENA_S 5 +/* HOST_FN2_SLC0_TOHOST_BIT4_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOHOST_BIT4_INT_ENA (BIT(4)) +#define HOST_FN2_SLC0_TOHOST_BIT4_INT_ENA_M (BIT(4)) +#define HOST_FN2_SLC0_TOHOST_BIT4_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOHOST_BIT4_INT_ENA_S 4 +/* HOST_FN2_SLC0_TOHOST_BIT3_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOHOST_BIT3_INT_ENA (BIT(3)) +#define HOST_FN2_SLC0_TOHOST_BIT3_INT_ENA_M (BIT(3)) +#define HOST_FN2_SLC0_TOHOST_BIT3_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOHOST_BIT3_INT_ENA_S 3 +/* HOST_FN2_SLC0_TOHOST_BIT2_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOHOST_BIT2_INT_ENA (BIT(2)) +#define HOST_FN2_SLC0_TOHOST_BIT2_INT_ENA_M (BIT(2)) +#define HOST_FN2_SLC0_TOHOST_BIT2_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOHOST_BIT2_INT_ENA_S 2 +/* HOST_FN2_SLC0_TOHOST_BIT1_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOHOST_BIT1_INT_ENA (BIT(1)) +#define HOST_FN2_SLC0_TOHOST_BIT1_INT_ENA_M (BIT(1)) +#define HOST_FN2_SLC0_TOHOST_BIT1_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOHOST_BIT1_INT_ENA_S 1 +/* HOST_FN2_SLC0_TOHOST_BIT0_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC0_TOHOST_BIT0_INT_ENA (BIT(0)) +#define HOST_FN2_SLC0_TOHOST_BIT0_INT_ENA_M (BIT(0)) +#define HOST_FN2_SLC0_TOHOST_BIT0_INT_ENA_V 0x1 +#define HOST_FN2_SLC0_TOHOST_BIT0_INT_ENA_S 0 + +#define HOST_SLC1HOST_FUNC2_INT_ENA_REG (DR_REG_SLCHOST_BASE + 0xE8) +/* HOST_FN2_SLC1_BT_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_BT_RX_NEW_PACKET_INT_ENA (BIT(25)) +#define HOST_FN2_SLC1_BT_RX_NEW_PACKET_INT_ENA_M (BIT(25)) +#define HOST_FN2_SLC1_BT_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_BT_RX_NEW_PACKET_INT_ENA_S 25 +/* HOST_FN2_SLC1_HOST_RD_RETRY_INT_ENA : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_HOST_RD_RETRY_INT_ENA (BIT(24)) +#define HOST_FN2_SLC1_HOST_RD_RETRY_INT_ENA_M (BIT(24)) +#define HOST_FN2_SLC1_HOST_RD_RETRY_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_HOST_RD_RETRY_INT_ENA_S 24 +/* HOST_FN2_SLC1_WIFI_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_WIFI_RX_NEW_PACKET_INT_ENA (BIT(23)) +#define HOST_FN2_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_M (BIT(23)) +#define HOST_FN2_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_S 23 +/* HOST_FN2_SLC1_EXT_BIT3_INT_ENA : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_EXT_BIT3_INT_ENA (BIT(22)) +#define HOST_FN2_SLC1_EXT_BIT3_INT_ENA_M (BIT(22)) +#define HOST_FN2_SLC1_EXT_BIT3_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_EXT_BIT3_INT_ENA_S 22 +/* HOST_FN2_SLC1_EXT_BIT2_INT_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_EXT_BIT2_INT_ENA (BIT(21)) +#define HOST_FN2_SLC1_EXT_BIT2_INT_ENA_M (BIT(21)) +#define HOST_FN2_SLC1_EXT_BIT2_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_EXT_BIT2_INT_ENA_S 21 +/* HOST_FN2_SLC1_EXT_BIT1_INT_ENA : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_EXT_BIT1_INT_ENA (BIT(20)) +#define HOST_FN2_SLC1_EXT_BIT1_INT_ENA_M (BIT(20)) +#define HOST_FN2_SLC1_EXT_BIT1_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_EXT_BIT1_INT_ENA_S 20 +/* HOST_FN2_SLC1_EXT_BIT0_INT_ENA : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_EXT_BIT0_INT_ENA (BIT(19)) +#define HOST_FN2_SLC1_EXT_BIT0_INT_ENA_M (BIT(19)) +#define HOST_FN2_SLC1_EXT_BIT0_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_EXT_BIT0_INT_ENA_S 19 +/* HOST_FN2_SLC1_RX_PF_VALID_INT_ENA : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_RX_PF_VALID_INT_ENA (BIT(18)) +#define HOST_FN2_SLC1_RX_PF_VALID_INT_ENA_M (BIT(18)) +#define HOST_FN2_SLC1_RX_PF_VALID_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_RX_PF_VALID_INT_ENA_S 18 +/* HOST_FN2_SLC1_TX_OVF_INT_ENA : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TX_OVF_INT_ENA (BIT(17)) +#define HOST_FN2_SLC1_TX_OVF_INT_ENA_M (BIT(17)) +#define HOST_FN2_SLC1_TX_OVF_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TX_OVF_INT_ENA_S 17 +/* HOST_FN2_SLC1_RX_UDF_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_RX_UDF_INT_ENA (BIT(16)) +#define HOST_FN2_SLC1_RX_UDF_INT_ENA_M (BIT(16)) +#define HOST_FN2_SLC1_RX_UDF_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_RX_UDF_INT_ENA_S 16 +/* HOST_FN2_SLC1HOST_TX_START_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1HOST_TX_START_INT_ENA (BIT(15)) +#define HOST_FN2_SLC1HOST_TX_START_INT_ENA_M (BIT(15)) +#define HOST_FN2_SLC1HOST_TX_START_INT_ENA_V 0x1 +#define HOST_FN2_SLC1HOST_TX_START_INT_ENA_S 15 +/* HOST_FN2_SLC1HOST_RX_START_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1HOST_RX_START_INT_ENA (BIT(14)) +#define HOST_FN2_SLC1HOST_RX_START_INT_ENA_M (BIT(14)) +#define HOST_FN2_SLC1HOST_RX_START_INT_ENA_V 0x1 +#define HOST_FN2_SLC1HOST_RX_START_INT_ENA_S 14 +/* HOST_FN2_SLC1HOST_RX_EOF_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1HOST_RX_EOF_INT_ENA (BIT(13)) +#define HOST_FN2_SLC1HOST_RX_EOF_INT_ENA_M (BIT(13)) +#define HOST_FN2_SLC1HOST_RX_EOF_INT_ENA_V 0x1 +#define HOST_FN2_SLC1HOST_RX_EOF_INT_ENA_S 13 +/* HOST_FN2_SLC1HOST_RX_SOF_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1HOST_RX_SOF_INT_ENA (BIT(12)) +#define HOST_FN2_SLC1HOST_RX_SOF_INT_ENA_M (BIT(12)) +#define HOST_FN2_SLC1HOST_RX_SOF_INT_ENA_V 0x1 +#define HOST_FN2_SLC1HOST_RX_SOF_INT_ENA_S 12 +/* HOST_FN2_SLC1_TOKEN1_0TO1_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOKEN1_0TO1_INT_ENA (BIT(11)) +#define HOST_FN2_SLC1_TOKEN1_0TO1_INT_ENA_M (BIT(11)) +#define HOST_FN2_SLC1_TOKEN1_0TO1_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOKEN1_0TO1_INT_ENA_S 11 +/* HOST_FN2_SLC1_TOKEN0_0TO1_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOKEN0_0TO1_INT_ENA (BIT(10)) +#define HOST_FN2_SLC1_TOKEN0_0TO1_INT_ENA_M (BIT(10)) +#define HOST_FN2_SLC1_TOKEN0_0TO1_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOKEN0_0TO1_INT_ENA_S 10 +/* HOST_FN2_SLC1_TOKEN1_1TO0_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOKEN1_1TO0_INT_ENA (BIT(9)) +#define HOST_FN2_SLC1_TOKEN1_1TO0_INT_ENA_M (BIT(9)) +#define HOST_FN2_SLC1_TOKEN1_1TO0_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOKEN1_1TO0_INT_ENA_S 9 +/* HOST_FN2_SLC1_TOKEN0_1TO0_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOKEN0_1TO0_INT_ENA (BIT(8)) +#define HOST_FN2_SLC1_TOKEN0_1TO0_INT_ENA_M (BIT(8)) +#define HOST_FN2_SLC1_TOKEN0_1TO0_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOKEN0_1TO0_INT_ENA_S 8 +/* HOST_FN2_SLC1_TOHOST_BIT7_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOHOST_BIT7_INT_ENA (BIT(7)) +#define HOST_FN2_SLC1_TOHOST_BIT7_INT_ENA_M (BIT(7)) +#define HOST_FN2_SLC1_TOHOST_BIT7_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOHOST_BIT7_INT_ENA_S 7 +/* HOST_FN2_SLC1_TOHOST_BIT6_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOHOST_BIT6_INT_ENA (BIT(6)) +#define HOST_FN2_SLC1_TOHOST_BIT6_INT_ENA_M (BIT(6)) +#define HOST_FN2_SLC1_TOHOST_BIT6_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOHOST_BIT6_INT_ENA_S 6 +/* HOST_FN2_SLC1_TOHOST_BIT5_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOHOST_BIT5_INT_ENA (BIT(5)) +#define HOST_FN2_SLC1_TOHOST_BIT5_INT_ENA_M (BIT(5)) +#define HOST_FN2_SLC1_TOHOST_BIT5_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOHOST_BIT5_INT_ENA_S 5 +/* HOST_FN2_SLC1_TOHOST_BIT4_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOHOST_BIT4_INT_ENA (BIT(4)) +#define HOST_FN2_SLC1_TOHOST_BIT4_INT_ENA_M (BIT(4)) +#define HOST_FN2_SLC1_TOHOST_BIT4_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOHOST_BIT4_INT_ENA_S 4 +/* HOST_FN2_SLC1_TOHOST_BIT3_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOHOST_BIT3_INT_ENA (BIT(3)) +#define HOST_FN2_SLC1_TOHOST_BIT3_INT_ENA_M (BIT(3)) +#define HOST_FN2_SLC1_TOHOST_BIT3_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOHOST_BIT3_INT_ENA_S 3 +/* HOST_FN2_SLC1_TOHOST_BIT2_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOHOST_BIT2_INT_ENA (BIT(2)) +#define HOST_FN2_SLC1_TOHOST_BIT2_INT_ENA_M (BIT(2)) +#define HOST_FN2_SLC1_TOHOST_BIT2_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOHOST_BIT2_INT_ENA_S 2 +/* HOST_FN2_SLC1_TOHOST_BIT1_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOHOST_BIT1_INT_ENA (BIT(1)) +#define HOST_FN2_SLC1_TOHOST_BIT1_INT_ENA_M (BIT(1)) +#define HOST_FN2_SLC1_TOHOST_BIT1_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOHOST_BIT1_INT_ENA_S 1 +/* HOST_FN2_SLC1_TOHOST_BIT0_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_FN2_SLC1_TOHOST_BIT0_INT_ENA (BIT(0)) +#define HOST_FN2_SLC1_TOHOST_BIT0_INT_ENA_M (BIT(0)) +#define HOST_FN2_SLC1_TOHOST_BIT0_INT_ENA_V 0x1 +#define HOST_FN2_SLC1_TOHOST_BIT0_INT_ENA_S 0 + +#define HOST_SLC0HOST_INT_ENA_REG (DR_REG_SLCHOST_BASE + 0xEC) +/* HOST_GPIO_SDIO_INT_ENA : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_INT_ENA (BIT(25)) +#define HOST_GPIO_SDIO_INT_ENA_M (BIT(25)) +#define HOST_GPIO_SDIO_INT_ENA_V 0x1 +#define HOST_GPIO_SDIO_INT_ENA_S 25 +/* HOST_SLC0_HOST_RD_RETRY_INT_ENA : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_HOST_RD_RETRY_INT_ENA (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_ENA_M (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_ENA_V 0x1 +#define HOST_SLC0_HOST_RD_RETRY_INT_ENA_S 24 +/* HOST_SLC0_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_NEW_PACKET_INT_ENA (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_ENA_M (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_SLC0_RX_NEW_PACKET_INT_ENA_S 23 +/* HOST_SLC0_EXT_BIT3_INT_ENA : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT3_INT_ENA (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_ENA_M (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_ENA_V 0x1 +#define HOST_SLC0_EXT_BIT3_INT_ENA_S 22 +/* HOST_SLC0_EXT_BIT2_INT_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT2_INT_ENA (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_ENA_M (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_ENA_V 0x1 +#define HOST_SLC0_EXT_BIT2_INT_ENA_S 21 +/* HOST_SLC0_EXT_BIT1_INT_ENA : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT1_INT_ENA (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_ENA_M (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_ENA_V 0x1 +#define HOST_SLC0_EXT_BIT1_INT_ENA_S 20 +/* HOST_SLC0_EXT_BIT0_INT_ENA : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT0_INT_ENA (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_ENA_M (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_ENA_V 0x1 +#define HOST_SLC0_EXT_BIT0_INT_ENA_S 19 +/* HOST_SLC0_RX_PF_VALID_INT_ENA : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_PF_VALID_INT_ENA (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_ENA_M (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_ENA_V 0x1 +#define HOST_SLC0_RX_PF_VALID_INT_ENA_S 18 +/* HOST_SLC0_TX_OVF_INT_ENA : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TX_OVF_INT_ENA (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_ENA_M (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_ENA_V 0x1 +#define HOST_SLC0_TX_OVF_INT_ENA_S 17 +/* HOST_SLC0_RX_UDF_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_UDF_INT_ENA (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_ENA_M (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_ENA_V 0x1 +#define HOST_SLC0_RX_UDF_INT_ENA_S 16 +/* HOST_SLC0HOST_TX_START_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TX_START_INT_ENA (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_ENA_M (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_ENA_V 0x1 +#define HOST_SLC0HOST_TX_START_INT_ENA_S 15 +/* HOST_SLC0HOST_RX_START_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_START_INT_ENA (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_ENA_M (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_ENA_V 0x1 +#define HOST_SLC0HOST_RX_START_INT_ENA_S 14 +/* HOST_SLC0HOST_RX_EOF_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_EOF_INT_ENA (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_ENA_M (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_ENA_V 0x1 +#define HOST_SLC0HOST_RX_EOF_INT_ENA_S 13 +/* HOST_SLC0HOST_RX_SOF_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_SOF_INT_ENA (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_ENA_M (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_ENA_V 0x1 +#define HOST_SLC0HOST_RX_SOF_INT_ENA_S 12 +/* HOST_SLC0_TOKEN1_0TO1_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_0TO1_INT_ENA (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_ENA_M (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_ENA_V 0x1 +#define HOST_SLC0_TOKEN1_0TO1_INT_ENA_S 11 +/* HOST_SLC0_TOKEN0_0TO1_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_0TO1_INT_ENA (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_ENA_M (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_ENA_V 0x1 +#define HOST_SLC0_TOKEN0_0TO1_INT_ENA_S 10 +/* HOST_SLC0_TOKEN1_1TO0_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_1TO0_INT_ENA (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_ENA_M (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_ENA_V 0x1 +#define HOST_SLC0_TOKEN1_1TO0_INT_ENA_S 9 +/* HOST_SLC0_TOKEN0_1TO0_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_1TO0_INT_ENA (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_ENA_M (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_ENA_V 0x1 +#define HOST_SLC0_TOKEN0_1TO0_INT_ENA_S 8 +/* HOST_SLC0_TOHOST_BIT7_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT7_INT_ENA (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_ENA_M (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_ENA_V 0x1 +#define HOST_SLC0_TOHOST_BIT7_INT_ENA_S 7 +/* HOST_SLC0_TOHOST_BIT6_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT6_INT_ENA (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_ENA_M (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_ENA_V 0x1 +#define HOST_SLC0_TOHOST_BIT6_INT_ENA_S 6 +/* HOST_SLC0_TOHOST_BIT5_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT5_INT_ENA (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_ENA_M (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_ENA_V 0x1 +#define HOST_SLC0_TOHOST_BIT5_INT_ENA_S 5 +/* HOST_SLC0_TOHOST_BIT4_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT4_INT_ENA (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_ENA_M (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_ENA_V 0x1 +#define HOST_SLC0_TOHOST_BIT4_INT_ENA_S 4 +/* HOST_SLC0_TOHOST_BIT3_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT3_INT_ENA (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_ENA_M (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_ENA_V 0x1 +#define HOST_SLC0_TOHOST_BIT3_INT_ENA_S 3 +/* HOST_SLC0_TOHOST_BIT2_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT2_INT_ENA (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_ENA_M (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_ENA_V 0x1 +#define HOST_SLC0_TOHOST_BIT2_INT_ENA_S 2 +/* HOST_SLC0_TOHOST_BIT1_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT1_INT_ENA (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_ENA_M (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_ENA_V 0x1 +#define HOST_SLC0_TOHOST_BIT1_INT_ENA_S 1 +/* HOST_SLC0_TOHOST_BIT0_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT0_INT_ENA (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_ENA_M (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_ENA_V 0x1 +#define HOST_SLC0_TOHOST_BIT0_INT_ENA_S 0 + +#define HOST_SLC1HOST_INT_ENA_REG (DR_REG_SLCHOST_BASE + 0xF0) +/* HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA_M (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA_S 25 +/* HOST_SLC1_HOST_RD_RETRY_INT_ENA : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_HOST_RD_RETRY_INT_ENA (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_ENA_M (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_ENA_V 0x1 +#define HOST_SLC1_HOST_RD_RETRY_INT_ENA_S 24 +/* HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_M (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_V 0x1 +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA_S 23 +/* HOST_SLC1_EXT_BIT3_INT_ENA : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT3_INT_ENA (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_ENA_M (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_ENA_V 0x1 +#define HOST_SLC1_EXT_BIT3_INT_ENA_S 22 +/* HOST_SLC1_EXT_BIT2_INT_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT2_INT_ENA (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_ENA_M (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_ENA_V 0x1 +#define HOST_SLC1_EXT_BIT2_INT_ENA_S 21 +/* HOST_SLC1_EXT_BIT1_INT_ENA : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT1_INT_ENA (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_ENA_M (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_ENA_V 0x1 +#define HOST_SLC1_EXT_BIT1_INT_ENA_S 20 +/* HOST_SLC1_EXT_BIT0_INT_ENA : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT0_INT_ENA (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_ENA_M (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_ENA_V 0x1 +#define HOST_SLC1_EXT_BIT0_INT_ENA_S 19 +/* HOST_SLC1_RX_PF_VALID_INT_ENA : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_PF_VALID_INT_ENA (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_ENA_M (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_ENA_V 0x1 +#define HOST_SLC1_RX_PF_VALID_INT_ENA_S 18 +/* HOST_SLC1_TX_OVF_INT_ENA : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TX_OVF_INT_ENA (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_ENA_M (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_ENA_V 0x1 +#define HOST_SLC1_TX_OVF_INT_ENA_S 17 +/* HOST_SLC1_RX_UDF_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_UDF_INT_ENA (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_ENA_M (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_ENA_V 0x1 +#define HOST_SLC1_RX_UDF_INT_ENA_S 16 +/* HOST_SLC1HOST_TX_START_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TX_START_INT_ENA (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_ENA_M (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_ENA_V 0x1 +#define HOST_SLC1HOST_TX_START_INT_ENA_S 15 +/* HOST_SLC1HOST_RX_START_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_START_INT_ENA (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_ENA_M (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_ENA_V 0x1 +#define HOST_SLC1HOST_RX_START_INT_ENA_S 14 +/* HOST_SLC1HOST_RX_EOF_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_EOF_INT_ENA (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_ENA_M (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_ENA_V 0x1 +#define HOST_SLC1HOST_RX_EOF_INT_ENA_S 13 +/* HOST_SLC1HOST_RX_SOF_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_SOF_INT_ENA (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_ENA_M (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_ENA_V 0x1 +#define HOST_SLC1HOST_RX_SOF_INT_ENA_S 12 +/* HOST_SLC1_TOKEN1_0TO1_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_0TO1_INT_ENA (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_ENA_M (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_ENA_V 0x1 +#define HOST_SLC1_TOKEN1_0TO1_INT_ENA_S 11 +/* HOST_SLC1_TOKEN0_0TO1_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_0TO1_INT_ENA (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_ENA_M (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_ENA_V 0x1 +#define HOST_SLC1_TOKEN0_0TO1_INT_ENA_S 10 +/* HOST_SLC1_TOKEN1_1TO0_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_1TO0_INT_ENA (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_ENA_M (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_ENA_V 0x1 +#define HOST_SLC1_TOKEN1_1TO0_INT_ENA_S 9 +/* HOST_SLC1_TOKEN0_1TO0_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_1TO0_INT_ENA (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_ENA_M (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_ENA_V 0x1 +#define HOST_SLC1_TOKEN0_1TO0_INT_ENA_S 8 +/* HOST_SLC1_TOHOST_BIT7_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT7_INT_ENA (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_ENA_M (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_ENA_V 0x1 +#define HOST_SLC1_TOHOST_BIT7_INT_ENA_S 7 +/* HOST_SLC1_TOHOST_BIT6_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT6_INT_ENA (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_ENA_M (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_ENA_V 0x1 +#define HOST_SLC1_TOHOST_BIT6_INT_ENA_S 6 +/* HOST_SLC1_TOHOST_BIT5_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT5_INT_ENA (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_ENA_M (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_ENA_V 0x1 +#define HOST_SLC1_TOHOST_BIT5_INT_ENA_S 5 +/* HOST_SLC1_TOHOST_BIT4_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT4_INT_ENA (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_ENA_M (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_ENA_V 0x1 +#define HOST_SLC1_TOHOST_BIT4_INT_ENA_S 4 +/* HOST_SLC1_TOHOST_BIT3_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT3_INT_ENA (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_ENA_M (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_ENA_V 0x1 +#define HOST_SLC1_TOHOST_BIT3_INT_ENA_S 3 +/* HOST_SLC1_TOHOST_BIT2_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT2_INT_ENA (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_ENA_M (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_ENA_V 0x1 +#define HOST_SLC1_TOHOST_BIT2_INT_ENA_S 2 +/* HOST_SLC1_TOHOST_BIT1_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT1_INT_ENA (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_ENA_M (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_ENA_V 0x1 +#define HOST_SLC1_TOHOST_BIT1_INT_ENA_S 1 +/* HOST_SLC1_TOHOST_BIT0_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT0_INT_ENA (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_ENA_M (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_ENA_V 0x1 +#define HOST_SLC1_TOHOST_BIT0_INT_ENA_S 0 + +#define HOST_SLC0HOST_RX_INFOR_REG (DR_REG_SLCHOST_BASE + 0xF4) +/* HOST_SLC0HOST_RX_INFOR : R/W ;bitpos:[19:0] ;default: 20'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_INFOR 0x000FFFFF +#define HOST_SLC0HOST_RX_INFOR_M ((HOST_SLC0HOST_RX_INFOR_V)<<(HOST_SLC0HOST_RX_INFOR_S)) +#define HOST_SLC0HOST_RX_INFOR_V 0xFFFFF +#define HOST_SLC0HOST_RX_INFOR_S 0 + +#define HOST_SLC1HOST_RX_INFOR_REG (DR_REG_SLCHOST_BASE + 0xF8) +/* HOST_SLC1HOST_RX_INFOR : R/W ;bitpos:[19:0] ;default: 20'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_INFOR 0x000FFFFF +#define HOST_SLC1HOST_RX_INFOR_M ((HOST_SLC1HOST_RX_INFOR_V)<<(HOST_SLC1HOST_RX_INFOR_S)) +#define HOST_SLC1HOST_RX_INFOR_V 0xFFFFF +#define HOST_SLC1HOST_RX_INFOR_S 0 + +#define HOST_SLC0HOST_LEN_WD_REG (DR_REG_SLCHOST_BASE + 0xFC) +/* HOST_SLC0HOST_LEN_WD : R/W ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_LEN_WD 0xFFFFFFFF +#define HOST_SLC0HOST_LEN_WD_M ((HOST_SLC0HOST_LEN_WD_V)<<(HOST_SLC0HOST_LEN_WD_S)) +#define HOST_SLC0HOST_LEN_WD_V 0xFFFFFFFF +#define HOST_SLC0HOST_LEN_WD_S 0 + +#define HOST_SLC_APBWIN_WDATA_REG (DR_REG_SLCHOST_BASE + 0x100) +/* HOST_SLC_APBWIN_WDATA : R/W ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define HOST_SLC_APBWIN_WDATA 0xFFFFFFFF +#define HOST_SLC_APBWIN_WDATA_M ((HOST_SLC_APBWIN_WDATA_V)<<(HOST_SLC_APBWIN_WDATA_S)) +#define HOST_SLC_APBWIN_WDATA_V 0xFFFFFFFF +#define HOST_SLC_APBWIN_WDATA_S 0 + +#define HOST_SLC_APBWIN_CONF_REG (DR_REG_SLCHOST_BASE + 0x104) +/* HOST_SLC_APBWIN_START : R/W ;bitpos:[29] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC_APBWIN_START (BIT(29)) +#define HOST_SLC_APBWIN_START_M (BIT(29)) +#define HOST_SLC_APBWIN_START_V 0x1 +#define HOST_SLC_APBWIN_START_S 29 +/* HOST_SLC_APBWIN_WR : R/W ;bitpos:[28] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC_APBWIN_WR (BIT(28)) +#define HOST_SLC_APBWIN_WR_M (BIT(28)) +#define HOST_SLC_APBWIN_WR_V 0x1 +#define HOST_SLC_APBWIN_WR_S 28 +/* HOST_SLC_APBWIN_ADDR : R/W ;bitpos:[27:0] ;default: 28'b0 ; */ +/*description: */ +#define HOST_SLC_APBWIN_ADDR 0x0FFFFFFF +#define HOST_SLC_APBWIN_ADDR_M ((HOST_SLC_APBWIN_ADDR_V)<<(HOST_SLC_APBWIN_ADDR_S)) +#define HOST_SLC_APBWIN_ADDR_V 0xFFFFFFF +#define HOST_SLC_APBWIN_ADDR_S 0 + +#define HOST_SLC_APBWIN_RDATA_REG (DR_REG_SLCHOST_BASE + 0x108) +/* HOST_SLC_APBWIN_RDATA : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define HOST_SLC_APBWIN_RDATA 0xFFFFFFFF +#define HOST_SLC_APBWIN_RDATA_M ((HOST_SLC_APBWIN_RDATA_V)<<(HOST_SLC_APBWIN_RDATA_S)) +#define HOST_SLC_APBWIN_RDATA_V 0xFFFFFFFF +#define HOST_SLC_APBWIN_RDATA_S 0 + +#define HOST_SLCHOST_RDCLR0_REG (DR_REG_SLCHOST_BASE + 0x10C) +/* HOST_SLCHOST_SLC0_BIT6_CLRADDR : R/W ;bitpos:[17:9] ;default: 9'h1e0 ; */ +/*description: */ +#define HOST_SLCHOST_SLC0_BIT6_CLRADDR 0x000001FF +#define HOST_SLCHOST_SLC0_BIT6_CLRADDR_M ((HOST_SLCHOST_SLC0_BIT6_CLRADDR_V)<<(HOST_SLCHOST_SLC0_BIT6_CLRADDR_S)) +#define HOST_SLCHOST_SLC0_BIT6_CLRADDR_V 0x1FF +#define HOST_SLCHOST_SLC0_BIT6_CLRADDR_S 9 +/* HOST_SLCHOST_SLC0_BIT7_CLRADDR : R/W ;bitpos:[8:0] ;default: 9'h44 ; */ +/*description: */ +#define HOST_SLCHOST_SLC0_BIT7_CLRADDR 0x000001FF +#define HOST_SLCHOST_SLC0_BIT7_CLRADDR_M ((HOST_SLCHOST_SLC0_BIT7_CLRADDR_V)<<(HOST_SLCHOST_SLC0_BIT7_CLRADDR_S)) +#define HOST_SLCHOST_SLC0_BIT7_CLRADDR_V 0x1FF +#define HOST_SLCHOST_SLC0_BIT7_CLRADDR_S 0 + +#define HOST_SLCHOST_RDCLR1_REG (DR_REG_SLCHOST_BASE + 0x110) +/* HOST_SLCHOST_SLC1_BIT6_CLRADDR : R/W ;bitpos:[17:9] ;default: 9'h1e0 ; */ +/*description: */ +#define HOST_SLCHOST_SLC1_BIT6_CLRADDR 0x000001FF +#define HOST_SLCHOST_SLC1_BIT6_CLRADDR_M ((HOST_SLCHOST_SLC1_BIT6_CLRADDR_V)<<(HOST_SLCHOST_SLC1_BIT6_CLRADDR_S)) +#define HOST_SLCHOST_SLC1_BIT6_CLRADDR_V 0x1FF +#define HOST_SLCHOST_SLC1_BIT6_CLRADDR_S 9 +/* HOST_SLCHOST_SLC1_BIT7_CLRADDR : R/W ;bitpos:[8:0] ;default: 9'h1e0 ; */ +/*description: */ +#define HOST_SLCHOST_SLC1_BIT7_CLRADDR 0x000001FF +#define HOST_SLCHOST_SLC1_BIT7_CLRADDR_M ((HOST_SLCHOST_SLC1_BIT7_CLRADDR_V)<<(HOST_SLCHOST_SLC1_BIT7_CLRADDR_S)) +#define HOST_SLCHOST_SLC1_BIT7_CLRADDR_V 0x1FF +#define HOST_SLCHOST_SLC1_BIT7_CLRADDR_S 0 + +#define HOST_SLC0HOST_INT_ENA1_REG (DR_REG_SLCHOST_BASE + 0x114) +/* HOST_GPIO_SDIO_INT_ENA1 : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_GPIO_SDIO_INT_ENA1 (BIT(25)) +#define HOST_GPIO_SDIO_INT_ENA1_M (BIT(25)) +#define HOST_GPIO_SDIO_INT_ENA1_V 0x1 +#define HOST_GPIO_SDIO_INT_ENA1_S 25 +/* HOST_SLC0_HOST_RD_RETRY_INT_ENA1 : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_HOST_RD_RETRY_INT_ENA1 (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_ENA1_M (BIT(24)) +#define HOST_SLC0_HOST_RD_RETRY_INT_ENA1_V 0x1 +#define HOST_SLC0_HOST_RD_RETRY_INT_ENA1_S 24 +/* HOST_SLC0_RX_NEW_PACKET_INT_ENA1 : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_NEW_PACKET_INT_ENA1 (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_ENA1_M (BIT(23)) +#define HOST_SLC0_RX_NEW_PACKET_INT_ENA1_V 0x1 +#define HOST_SLC0_RX_NEW_PACKET_INT_ENA1_S 23 +/* HOST_SLC0_EXT_BIT3_INT_ENA1 : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT3_INT_ENA1 (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_ENA1_M (BIT(22)) +#define HOST_SLC0_EXT_BIT3_INT_ENA1_V 0x1 +#define HOST_SLC0_EXT_BIT3_INT_ENA1_S 22 +/* HOST_SLC0_EXT_BIT2_INT_ENA1 : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT2_INT_ENA1 (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_ENA1_M (BIT(21)) +#define HOST_SLC0_EXT_BIT2_INT_ENA1_V 0x1 +#define HOST_SLC0_EXT_BIT2_INT_ENA1_S 21 +/* HOST_SLC0_EXT_BIT1_INT_ENA1 : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT1_INT_ENA1 (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_ENA1_M (BIT(20)) +#define HOST_SLC0_EXT_BIT1_INT_ENA1_V 0x1 +#define HOST_SLC0_EXT_BIT1_INT_ENA1_S 20 +/* HOST_SLC0_EXT_BIT0_INT_ENA1 : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_EXT_BIT0_INT_ENA1 (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_ENA1_M (BIT(19)) +#define HOST_SLC0_EXT_BIT0_INT_ENA1_V 0x1 +#define HOST_SLC0_EXT_BIT0_INT_ENA1_S 19 +/* HOST_SLC0_RX_PF_VALID_INT_ENA1 : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_PF_VALID_INT_ENA1 (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_ENA1_M (BIT(18)) +#define HOST_SLC0_RX_PF_VALID_INT_ENA1_V 0x1 +#define HOST_SLC0_RX_PF_VALID_INT_ENA1_S 18 +/* HOST_SLC0_TX_OVF_INT_ENA1 : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TX_OVF_INT_ENA1 (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_ENA1_M (BIT(17)) +#define HOST_SLC0_TX_OVF_INT_ENA1_V 0x1 +#define HOST_SLC0_TX_OVF_INT_ENA1_S 17 +/* HOST_SLC0_RX_UDF_INT_ENA1 : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_RX_UDF_INT_ENA1 (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_ENA1_M (BIT(16)) +#define HOST_SLC0_RX_UDF_INT_ENA1_V 0x1 +#define HOST_SLC0_RX_UDF_INT_ENA1_S 16 +/* HOST_SLC0HOST_TX_START_INT_ENA1 : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_TX_START_INT_ENA1 (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_ENA1_M (BIT(15)) +#define HOST_SLC0HOST_TX_START_INT_ENA1_V 0x1 +#define HOST_SLC0HOST_TX_START_INT_ENA1_S 15 +/* HOST_SLC0HOST_RX_START_INT_ENA1 : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_START_INT_ENA1 (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_ENA1_M (BIT(14)) +#define HOST_SLC0HOST_RX_START_INT_ENA1_V 0x1 +#define HOST_SLC0HOST_RX_START_INT_ENA1_S 14 +/* HOST_SLC0HOST_RX_EOF_INT_ENA1 : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_EOF_INT_ENA1 (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_ENA1_M (BIT(13)) +#define HOST_SLC0HOST_RX_EOF_INT_ENA1_V 0x1 +#define HOST_SLC0HOST_RX_EOF_INT_ENA1_S 13 +/* HOST_SLC0HOST_RX_SOF_INT_ENA1 : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0HOST_RX_SOF_INT_ENA1 (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_ENA1_M (BIT(12)) +#define HOST_SLC0HOST_RX_SOF_INT_ENA1_V 0x1 +#define HOST_SLC0HOST_RX_SOF_INT_ENA1_S 12 +/* HOST_SLC0_TOKEN1_0TO1_INT_ENA1 : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_0TO1_INT_ENA1 (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_ENA1_M (BIT(11)) +#define HOST_SLC0_TOKEN1_0TO1_INT_ENA1_V 0x1 +#define HOST_SLC0_TOKEN1_0TO1_INT_ENA1_S 11 +/* HOST_SLC0_TOKEN0_0TO1_INT_ENA1 : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_0TO1_INT_ENA1 (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_ENA1_M (BIT(10)) +#define HOST_SLC0_TOKEN0_0TO1_INT_ENA1_V 0x1 +#define HOST_SLC0_TOKEN0_0TO1_INT_ENA1_S 10 +/* HOST_SLC0_TOKEN1_1TO0_INT_ENA1 : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN1_1TO0_INT_ENA1 (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_ENA1_M (BIT(9)) +#define HOST_SLC0_TOKEN1_1TO0_INT_ENA1_V 0x1 +#define HOST_SLC0_TOKEN1_1TO0_INT_ENA1_S 9 +/* HOST_SLC0_TOKEN0_1TO0_INT_ENA1 : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOKEN0_1TO0_INT_ENA1 (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_ENA1_M (BIT(8)) +#define HOST_SLC0_TOKEN0_1TO0_INT_ENA1_V 0x1 +#define HOST_SLC0_TOKEN0_1TO0_INT_ENA1_S 8 +/* HOST_SLC0_TOHOST_BIT7_INT_ENA1 : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT7_INT_ENA1 (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_ENA1_M (BIT(7)) +#define HOST_SLC0_TOHOST_BIT7_INT_ENA1_V 0x1 +#define HOST_SLC0_TOHOST_BIT7_INT_ENA1_S 7 +/* HOST_SLC0_TOHOST_BIT6_INT_ENA1 : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT6_INT_ENA1 (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_ENA1_M (BIT(6)) +#define HOST_SLC0_TOHOST_BIT6_INT_ENA1_V 0x1 +#define HOST_SLC0_TOHOST_BIT6_INT_ENA1_S 6 +/* HOST_SLC0_TOHOST_BIT5_INT_ENA1 : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT5_INT_ENA1 (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_ENA1_M (BIT(5)) +#define HOST_SLC0_TOHOST_BIT5_INT_ENA1_V 0x1 +#define HOST_SLC0_TOHOST_BIT5_INT_ENA1_S 5 +/* HOST_SLC0_TOHOST_BIT4_INT_ENA1 : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT4_INT_ENA1 (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_ENA1_M (BIT(4)) +#define HOST_SLC0_TOHOST_BIT4_INT_ENA1_V 0x1 +#define HOST_SLC0_TOHOST_BIT4_INT_ENA1_S 4 +/* HOST_SLC0_TOHOST_BIT3_INT_ENA1 : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT3_INT_ENA1 (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_ENA1_M (BIT(3)) +#define HOST_SLC0_TOHOST_BIT3_INT_ENA1_V 0x1 +#define HOST_SLC0_TOHOST_BIT3_INT_ENA1_S 3 +/* HOST_SLC0_TOHOST_BIT2_INT_ENA1 : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT2_INT_ENA1 (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_ENA1_M (BIT(2)) +#define HOST_SLC0_TOHOST_BIT2_INT_ENA1_V 0x1 +#define HOST_SLC0_TOHOST_BIT2_INT_ENA1_S 2 +/* HOST_SLC0_TOHOST_BIT1_INT_ENA1 : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT1_INT_ENA1 (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_ENA1_M (BIT(1)) +#define HOST_SLC0_TOHOST_BIT1_INT_ENA1_V 0x1 +#define HOST_SLC0_TOHOST_BIT1_INT_ENA1_S 1 +/* HOST_SLC0_TOHOST_BIT0_INT_ENA1 : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC0_TOHOST_BIT0_INT_ENA1 (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_ENA1_M (BIT(0)) +#define HOST_SLC0_TOHOST_BIT0_INT_ENA1_V 0x1 +#define HOST_SLC0_TOHOST_BIT0_INT_ENA1_S 0 + +#define HOST_SLC1HOST_INT_ENA1_REG (DR_REG_SLCHOST_BASE + 0x118) +/* HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA1 : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA1 (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA1_M (BIT(25)) +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA1_V 0x1 +#define HOST_SLC1_BT_RX_NEW_PACKET_INT_ENA1_S 25 +/* HOST_SLC1_HOST_RD_RETRY_INT_ENA1 : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_HOST_RD_RETRY_INT_ENA1 (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_ENA1_M (BIT(24)) +#define HOST_SLC1_HOST_RD_RETRY_INT_ENA1_V 0x1 +#define HOST_SLC1_HOST_RD_RETRY_INT_ENA1_S 24 +/* HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA1 : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA1 (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA1_M (BIT(23)) +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA1_V 0x1 +#define HOST_SLC1_WIFI_RX_NEW_PACKET_INT_ENA1_S 23 +/* HOST_SLC1_EXT_BIT3_INT_ENA1 : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT3_INT_ENA1 (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_ENA1_M (BIT(22)) +#define HOST_SLC1_EXT_BIT3_INT_ENA1_V 0x1 +#define HOST_SLC1_EXT_BIT3_INT_ENA1_S 22 +/* HOST_SLC1_EXT_BIT2_INT_ENA1 : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT2_INT_ENA1 (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_ENA1_M (BIT(21)) +#define HOST_SLC1_EXT_BIT2_INT_ENA1_V 0x1 +#define HOST_SLC1_EXT_BIT2_INT_ENA1_S 21 +/* HOST_SLC1_EXT_BIT1_INT_ENA1 : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT1_INT_ENA1 (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_ENA1_M (BIT(20)) +#define HOST_SLC1_EXT_BIT1_INT_ENA1_V 0x1 +#define HOST_SLC1_EXT_BIT1_INT_ENA1_S 20 +/* HOST_SLC1_EXT_BIT0_INT_ENA1 : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_EXT_BIT0_INT_ENA1 (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_ENA1_M (BIT(19)) +#define HOST_SLC1_EXT_BIT0_INT_ENA1_V 0x1 +#define HOST_SLC1_EXT_BIT0_INT_ENA1_S 19 +/* HOST_SLC1_RX_PF_VALID_INT_ENA1 : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_PF_VALID_INT_ENA1 (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_ENA1_M (BIT(18)) +#define HOST_SLC1_RX_PF_VALID_INT_ENA1_V 0x1 +#define HOST_SLC1_RX_PF_VALID_INT_ENA1_S 18 +/* HOST_SLC1_TX_OVF_INT_ENA1 : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TX_OVF_INT_ENA1 (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_ENA1_M (BIT(17)) +#define HOST_SLC1_TX_OVF_INT_ENA1_V 0x1 +#define HOST_SLC1_TX_OVF_INT_ENA1_S 17 +/* HOST_SLC1_RX_UDF_INT_ENA1 : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_RX_UDF_INT_ENA1 (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_ENA1_M (BIT(16)) +#define HOST_SLC1_RX_UDF_INT_ENA1_V 0x1 +#define HOST_SLC1_RX_UDF_INT_ENA1_S 16 +/* HOST_SLC1HOST_TX_START_INT_ENA1 : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_TX_START_INT_ENA1 (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_ENA1_M (BIT(15)) +#define HOST_SLC1HOST_TX_START_INT_ENA1_V 0x1 +#define HOST_SLC1HOST_TX_START_INT_ENA1_S 15 +/* HOST_SLC1HOST_RX_START_INT_ENA1 : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_START_INT_ENA1 (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_ENA1_M (BIT(14)) +#define HOST_SLC1HOST_RX_START_INT_ENA1_V 0x1 +#define HOST_SLC1HOST_RX_START_INT_ENA1_S 14 +/* HOST_SLC1HOST_RX_EOF_INT_ENA1 : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_EOF_INT_ENA1 (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_ENA1_M (BIT(13)) +#define HOST_SLC1HOST_RX_EOF_INT_ENA1_V 0x1 +#define HOST_SLC1HOST_RX_EOF_INT_ENA1_S 13 +/* HOST_SLC1HOST_RX_SOF_INT_ENA1 : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1HOST_RX_SOF_INT_ENA1 (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_ENA1_M (BIT(12)) +#define HOST_SLC1HOST_RX_SOF_INT_ENA1_V 0x1 +#define HOST_SLC1HOST_RX_SOF_INT_ENA1_S 12 +/* HOST_SLC1_TOKEN1_0TO1_INT_ENA1 : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_0TO1_INT_ENA1 (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_ENA1_M (BIT(11)) +#define HOST_SLC1_TOKEN1_0TO1_INT_ENA1_V 0x1 +#define HOST_SLC1_TOKEN1_0TO1_INT_ENA1_S 11 +/* HOST_SLC1_TOKEN0_0TO1_INT_ENA1 : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_0TO1_INT_ENA1 (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_ENA1_M (BIT(10)) +#define HOST_SLC1_TOKEN0_0TO1_INT_ENA1_V 0x1 +#define HOST_SLC1_TOKEN0_0TO1_INT_ENA1_S 10 +/* HOST_SLC1_TOKEN1_1TO0_INT_ENA1 : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN1_1TO0_INT_ENA1 (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_ENA1_M (BIT(9)) +#define HOST_SLC1_TOKEN1_1TO0_INT_ENA1_V 0x1 +#define HOST_SLC1_TOKEN1_1TO0_INT_ENA1_S 9 +/* HOST_SLC1_TOKEN0_1TO0_INT_ENA1 : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOKEN0_1TO0_INT_ENA1 (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_ENA1_M (BIT(8)) +#define HOST_SLC1_TOKEN0_1TO0_INT_ENA1_V 0x1 +#define HOST_SLC1_TOKEN0_1TO0_INT_ENA1_S 8 +/* HOST_SLC1_TOHOST_BIT7_INT_ENA1 : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT7_INT_ENA1 (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_ENA1_M (BIT(7)) +#define HOST_SLC1_TOHOST_BIT7_INT_ENA1_V 0x1 +#define HOST_SLC1_TOHOST_BIT7_INT_ENA1_S 7 +/* HOST_SLC1_TOHOST_BIT6_INT_ENA1 : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT6_INT_ENA1 (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_ENA1_M (BIT(6)) +#define HOST_SLC1_TOHOST_BIT6_INT_ENA1_V 0x1 +#define HOST_SLC1_TOHOST_BIT6_INT_ENA1_S 6 +/* HOST_SLC1_TOHOST_BIT5_INT_ENA1 : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT5_INT_ENA1 (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_ENA1_M (BIT(5)) +#define HOST_SLC1_TOHOST_BIT5_INT_ENA1_V 0x1 +#define HOST_SLC1_TOHOST_BIT5_INT_ENA1_S 5 +/* HOST_SLC1_TOHOST_BIT4_INT_ENA1 : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT4_INT_ENA1 (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_ENA1_M (BIT(4)) +#define HOST_SLC1_TOHOST_BIT4_INT_ENA1_V 0x1 +#define HOST_SLC1_TOHOST_BIT4_INT_ENA1_S 4 +/* HOST_SLC1_TOHOST_BIT3_INT_ENA1 : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT3_INT_ENA1 (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_ENA1_M (BIT(3)) +#define HOST_SLC1_TOHOST_BIT3_INT_ENA1_V 0x1 +#define HOST_SLC1_TOHOST_BIT3_INT_ENA1_S 3 +/* HOST_SLC1_TOHOST_BIT2_INT_ENA1 : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT2_INT_ENA1 (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_ENA1_M (BIT(2)) +#define HOST_SLC1_TOHOST_BIT2_INT_ENA1_V 0x1 +#define HOST_SLC1_TOHOST_BIT2_INT_ENA1_S 2 +/* HOST_SLC1_TOHOST_BIT1_INT_ENA1 : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT1_INT_ENA1 (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_ENA1_M (BIT(1)) +#define HOST_SLC1_TOHOST_BIT1_INT_ENA1_V 0x1 +#define HOST_SLC1_TOHOST_BIT1_INT_ENA1_S 1 +/* HOST_SLC1_TOHOST_BIT0_INT_ENA1 : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SLC1_TOHOST_BIT0_INT_ENA1 (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_ENA1_M (BIT(0)) +#define HOST_SLC1_TOHOST_BIT0_INT_ENA1_V 0x1 +#define HOST_SLC1_TOHOST_BIT0_INT_ENA1_S 0 + +#define HOST_SLCHOSTDATE_REG (DR_REG_SLCHOST_BASE + 0x178) +/* HOST_SLCHOST_DATE : R/W ;bitpos:[31:0] ;default: 32'h16022500 ; */ +/*description: */ +#define HOST_SLCHOST_DATE 0xFFFFFFFF +#define HOST_SLCHOST_DATE_M ((HOST_SLCHOST_DATE_V)<<(HOST_SLCHOST_DATE_S)) +#define HOST_SLCHOST_DATE_V 0xFFFFFFFF +#define HOST_SLCHOST_DATE_S 0 + +#define HOST_SLCHOSTID_REG (DR_REG_SLCHOST_BASE + 0x17C) +/* HOST_SLCHOST_ID : R/W ;bitpos:[31:0] ;default: 32'h0600 ; */ +/*description: */ +#define HOST_SLCHOST_ID 0xFFFFFFFF +#define HOST_SLCHOST_ID_M ((HOST_SLCHOST_ID_V)<<(HOST_SLCHOST_ID_S)) +#define HOST_SLCHOST_ID_V 0xFFFFFFFF +#define HOST_SLCHOST_ID_S 0 + +#define HOST_SLCHOST_CONF_REG (DR_REG_SLCHOST_BASE + 0x1F0) +/* HOST_HSPEED_CON_EN : R/W ;bitpos:[27] ;default: 1'b0 ; */ +/*description: */ +#define HOST_HSPEED_CON_EN (BIT(27)) +#define HOST_HSPEED_CON_EN_M (BIT(27)) +#define HOST_HSPEED_CON_EN_V 0x1 +#define HOST_HSPEED_CON_EN_S 27 +/* HOST_SDIO_PAD_PULLUP : R/W ;bitpos:[26] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SDIO_PAD_PULLUP (BIT(26)) +#define HOST_SDIO_PAD_PULLUP_M (BIT(26)) +#define HOST_SDIO_PAD_PULLUP_V 0x1 +#define HOST_SDIO_PAD_PULLUP_S 26 +/* HOST_SDIO20_INT_DELAY : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define HOST_SDIO20_INT_DELAY (BIT(25)) +#define HOST_SDIO20_INT_DELAY_M (BIT(25)) +#define HOST_SDIO20_INT_DELAY_V 0x1 +#define HOST_SDIO20_INT_DELAY_S 25 +/* HOST_FRC_QUICK_IN : R/W ;bitpos:[24:20] ;default: 5'b0 ; */ +/*description: */ +#define HOST_FRC_QUICK_IN 0x0000001F +#define HOST_FRC_QUICK_IN_M ((HOST_FRC_QUICK_IN_V)<<(HOST_FRC_QUICK_IN_S)) +#define HOST_FRC_QUICK_IN_V 0x1F +#define HOST_FRC_QUICK_IN_S 20 +/* HOST_FRC_POS_SAMP : R/W ;bitpos:[19:15] ;default: 5'b0 ; */ +/*description: */ +#define HOST_FRC_POS_SAMP 0x0000001F +#define HOST_FRC_POS_SAMP_M ((HOST_FRC_POS_SAMP_V)<<(HOST_FRC_POS_SAMP_S)) +#define HOST_FRC_POS_SAMP_V 0x1F +#define HOST_FRC_POS_SAMP_S 15 +/* HOST_FRC_NEG_SAMP : R/W ;bitpos:[14:10] ;default: 5'b0 ; */ +/*description: */ +#define HOST_FRC_NEG_SAMP 0x0000001F +#define HOST_FRC_NEG_SAMP_M ((HOST_FRC_NEG_SAMP_V)<<(HOST_FRC_NEG_SAMP_S)) +#define HOST_FRC_NEG_SAMP_V 0x1F +#define HOST_FRC_NEG_SAMP_S 10 +/* HOST_FRC_SDIO20 : R/W ;bitpos:[9:5] ;default: 5'b0 ; */ +/*description: */ +#define HOST_FRC_SDIO20 0x0000001F +#define HOST_FRC_SDIO20_M ((HOST_FRC_SDIO20_V)<<(HOST_FRC_SDIO20_S)) +#define HOST_FRC_SDIO20_V 0x1F +#define HOST_FRC_SDIO20_S 5 +/* HOST_FRC_SDIO11 : R/W ;bitpos:[4:0] ;default: 5'b0 ; */ +/*description: */ +#define HOST_FRC_SDIO11 0x0000001F +#define HOST_FRC_SDIO11_M ((HOST_FRC_SDIO11_V)<<(HOST_FRC_SDIO11_S)) +#define HOST_FRC_SDIO11_V 0x1F +#define HOST_FRC_SDIO11_S 0 + +#define HOST_SLCHOST_INF_ST_REG (DR_REG_SLCHOST_BASE + 0x1F4) +/* HOST_SDIO_QUICK_IN : RO ;bitpos:[14:10] ;default: 5'b0 ; */ +/*description: */ +#define HOST_SDIO_QUICK_IN 0x0000001F +#define HOST_SDIO_QUICK_IN_M ((HOST_SDIO_QUICK_IN_V)<<(HOST_SDIO_QUICK_IN_S)) +#define HOST_SDIO_QUICK_IN_V 0x1F +#define HOST_SDIO_QUICK_IN_S 10 +/* HOST_SDIO_NEG_SAMP : RO ;bitpos:[9:5] ;default: 5'b0 ; */ +/*description: */ +#define HOST_SDIO_NEG_SAMP 0x0000001F +#define HOST_SDIO_NEG_SAMP_M ((HOST_SDIO_NEG_SAMP_V)<<(HOST_SDIO_NEG_SAMP_S)) +#define HOST_SDIO_NEG_SAMP_V 0x1F +#define HOST_SDIO_NEG_SAMP_S 5 +/* HOST_SDIO20_MODE : RO ;bitpos:[4:0] ;default: 5'b0 ; */ +/*description: */ +#define HOST_SDIO20_MODE 0x0000001F +#define HOST_SDIO20_MODE_M ((HOST_SDIO20_MODE_V)<<(HOST_SDIO20_MODE_S)) +#define HOST_SDIO20_MODE_V 0x1F +#define HOST_SDIO20_MODE_S 0 + + + + +#endif /*_SOC_HOST_REG_H_ */ + + diff --git a/tools/sdk/include/soc/soc/host_struct.h b/tools/sdk/include/soc/soc/host_struct.h new file mode 100644 index 00000000000..a86c2982db1 --- /dev/null +++ b/tools/sdk/include/soc/soc/host_struct.h @@ -0,0 +1,891 @@ +// 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 _SOC_HOST_STRUCT_H_ +#define _SOC_HOST_STRUCT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef volatile struct { + uint32_t reserved_0; + uint32_t reserved_4; + uint32_t reserved_8; + uint32_t reserved_c; + union { + struct { + uint32_t reserved0: 24; + uint32_t func2_int: 1; + uint32_t reserved25: 7; + }; + uint32_t val; + } func2_0; + union { + struct { + uint32_t func2_int_en: 1; + uint32_t reserved1: 31; + }; + uint32_t val; + } func2_1; + uint32_t reserved_18; + uint32_t reserved_1c; + union { + struct { + uint32_t func1_mdstat: 1; + uint32_t reserved1: 31; + }; + uint32_t val; + } func2_2; + uint32_t reserved_24; + uint32_t reserved_28; + uint32_t reserved_2c; + uint32_t reserved_30; + uint32_t gpio_status0; /**/ + union { + struct { + uint32_t sdio_int1: 8; + uint32_t reserved8: 24; + }; + uint32_t val; + } gpio_status1; + uint32_t gpio_in0; /**/ + union { + struct { + uint32_t sdio_in1: 8; + uint32_t reserved8: 24; + }; + uint32_t val; + } gpio_in1; + union { + struct { + uint32_t token0: 12; + uint32_t rx_pf_valid: 1; + uint32_t reserved13: 3; + uint32_t reg_token1: 12; + uint32_t rx_pf_eof: 4; + }; + uint32_t val; + } slc0_token_rdata; + uint32_t slc0_pf; /**/ + uint32_t slc1_pf; /**/ + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t gpio_sdio: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc0_int_raw; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t wifi_rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t bt_rx_new_packet: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc1_int_raw; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t gpio_sdio: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc0_int_st; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t wifi_rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t bt_rx_new_packet: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc1_int_st; + union { + struct { + uint32_t reg_slc0_len: 20; + uint32_t reg_slc0_len_check:12; + }; + uint32_t val; + } pkt_len; + union { + struct { + uint32_t state0: 8; + uint32_t state1: 8; + uint32_t state2: 8; + uint32_t state3: 8; + }; + uint32_t val; + } state_w0; + union { + struct { + uint32_t state4: 8; + uint32_t state5: 8; + uint32_t state6: 8; + uint32_t state7: 8; + }; + uint32_t val; + } state_w1; + union { + struct { + uint32_t conf0: 8; + uint32_t conf1: 8; + uint32_t conf2: 8; + uint32_t conf3: 8; + }; + uint32_t val; + } conf_w0; + union { + struct { + uint32_t conf4: 8; + uint32_t conf5: 8; + uint32_t conf6: 8; + uint32_t conf7: 8; + }; + uint32_t val; + } conf_w1; + union { + struct { + uint32_t conf8: 8; + uint32_t conf9: 8; + uint32_t conf10: 8; + uint32_t conf11: 8; + }; + uint32_t val; + } conf_w2; + union { + struct { + uint32_t conf12: 8; + uint32_t conf13: 8; + uint32_t conf14: 8; + uint32_t conf15: 8; + }; + uint32_t val; + } conf_w3; + union { + struct { + uint32_t conf16: 8; /*SLC timeout value*/ + uint32_t conf17: 8; /*SLC timeout enable*/ + uint32_t conf18: 8; + uint32_t conf19: 8; /*Interrupt to target CPU*/ + }; + uint32_t val; + } conf_w4; + union { + struct { + uint32_t conf20: 8; + uint32_t conf21: 8; + uint32_t conf22: 8; + uint32_t conf23: 8; + }; + uint32_t val; + } conf_w5; + uint32_t win_cmd; /**/ + union { + struct { + uint32_t conf24: 8; + uint32_t conf25: 8; + uint32_t conf26: 8; + uint32_t conf27: 8; + }; + uint32_t val; + } conf_w6; + union { + struct { + uint32_t conf28: 8; + uint32_t conf29: 8; + uint32_t conf30: 8; + uint32_t conf31: 8; + }; + uint32_t val; + } conf_w7; + union { + struct { + uint32_t reg_slc0_len0:20; + uint32_t reserved20: 12; + }; + uint32_t val; + } pkt_len0; + union { + struct { + uint32_t reg_slc0_len1:20; + uint32_t reserved20: 12; + }; + uint32_t val; + } pkt_len1; + union { + struct { + uint32_t reg_slc0_len2:20; + uint32_t reserved20: 12; + }; + uint32_t val; + } pkt_len2; + union { + struct { + uint32_t conf32: 8; + uint32_t conf33: 8; + uint32_t conf34: 8; + uint32_t conf35: 8; + }; + uint32_t val; + } conf_w8; + union { + struct { + uint32_t conf36: 8; + uint32_t conf37: 8; + uint32_t conf38: 8; + uint32_t conf39: 8; + }; + uint32_t val; + } conf_w9; + union { + struct { + uint32_t conf40: 8; + uint32_t conf41: 8; + uint32_t conf42: 8; + uint32_t conf43: 8; + }; + uint32_t val; + } conf_w10; + union { + struct { + uint32_t conf44: 8; + uint32_t conf45: 8; + uint32_t conf46: 8; + uint32_t conf47: 8; + }; + uint32_t val; + } conf_w11; + union { + struct { + uint32_t conf48: 8; + uint32_t conf49: 8; + uint32_t conf50: 8; + uint32_t conf51: 8; + }; + uint32_t val; + } conf_w12; + union { + struct { + uint32_t conf52: 8; + uint32_t conf53: 8; + uint32_t conf54: 8; + uint32_t conf55: 8; + }; + uint32_t val; + } conf_w13; + union { + struct { + uint32_t conf56: 8; + uint32_t conf57: 8; + uint32_t conf58: 8; + uint32_t conf59: 8; + }; + uint32_t val; + } conf_w14; + union { + struct { + uint32_t conf60: 8; + uint32_t conf61: 8; + uint32_t conf62: 8; + uint32_t conf63: 8; + }; + uint32_t val; + } conf_w15; + uint32_t check_sum0; /**/ + uint32_t check_sum1; /**/ + union { + struct { + uint32_t token0: 12; + uint32_t rx_pf_valid: 1; + uint32_t reserved13: 3; + uint32_t reg_token1: 12; + uint32_t rx_pf_eof: 4; + }; + uint32_t val; + } slc1_token_rdata; + union { + struct { + uint32_t token0_wd: 12; + uint32_t reserved12: 4; + uint32_t token1_wd: 12; + uint32_t reserved28: 4; + }; + uint32_t val; + } slc0_token_wdata; + union { + struct { + uint32_t token0_wd: 12; + uint32_t reserved12: 4; + uint32_t token1_wd: 12; + uint32_t reserved28: 4; + }; + uint32_t val; + } slc1_token_wdata; + union { + struct { + uint32_t slc0_token0_dec: 1; + uint32_t slc0_token1_dec: 1; + uint32_t slc0_token0_wr: 1; + uint32_t slc0_token1_wr: 1; + uint32_t slc1_token0_dec: 1; + uint32_t slc1_token1_dec: 1; + uint32_t slc1_token0_wr: 1; + uint32_t slc1_token1_wr: 1; + uint32_t slc0_len_wr: 1; + uint32_t reserved9: 23; + }; + uint32_t val; + } token_con; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t gpio_sdio: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc0_int_clr; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t wifi_rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t bt_rx_new_packet: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc1_int_clr; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t gpio_sdio: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc0_func1_int_ena; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t wifi_rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t bt_rx_new_packet: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc1_func1_int_ena; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t gpio_sdio: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc0_func2_int_ena; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t wifi_rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t bt_rx_new_packet: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc1_func2_int_ena; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t gpio_sdio: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc0_int_ena; + union { + struct { + uint32_t tohost_bit0: 1; + uint32_t tohost_bit1: 1; + uint32_t tohost_bit2: 1; + uint32_t tohost_bit3: 1; + uint32_t tohost_bit4: 1; + uint32_t tohost_bit5: 1; + uint32_t tohost_bit6: 1; + uint32_t tohost_bit7: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t token0_0to1: 1; + uint32_t token1_0to1: 1; + uint32_t rx_sof: 1; + uint32_t rx_eof: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t rx_pf_valid: 1; + uint32_t ext_bit0: 1; + uint32_t ext_bit1: 1; + uint32_t ext_bit2: 1; + uint32_t ext_bit3: 1; + uint32_t wifi_rx_new_packet: 1; + uint32_t rd_retry: 1; + uint32_t bt_rx_new_packet: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc1_int_ena; + union { + struct { + uint32_t infor: 20; + uint32_t reserved20: 12; + }; + uint32_t val; + } slc0_rx_infor; + union { + struct { + uint32_t infor: 20; + uint32_t reserved20: 12; + }; + uint32_t val; + } slc1_rx_infor; + uint32_t slc0_len_wd; /**/ + uint32_t apbwin_wdata; /**/ + union { + struct { + uint32_t addr: 28; + uint32_t wr: 1; + uint32_t start: 1; + uint32_t reserved30: 2; + }; + uint32_t val; + } apbwin_conf; + uint32_t apbwin_rdata; /**/ + union { + struct { + uint32_t bit7_clraddr: 9; + uint32_t bit6_clraddr: 9; + uint32_t reserved18: 14; + }; + uint32_t val; + } slc0_rdclr; + union { + struct { + uint32_t bit7_clraddr: 9; + uint32_t bit6_clraddr: 9; + uint32_t reserved18: 14; + }; + uint32_t val; + } slc1_rdclr; + union { + struct { + uint32_t tohost_bit01: 1; + uint32_t tohost_bit11: 1; + uint32_t tohost_bit21: 1; + uint32_t tohost_bit31: 1; + uint32_t tohost_bit41: 1; + uint32_t tohost_bit51: 1; + uint32_t tohost_bit61: 1; + uint32_t tohost_bit71: 1; + uint32_t token0_1to01: 1; + uint32_t token1_1to01: 1; + uint32_t token0_0to11: 1; + uint32_t token1_0to11: 1; + uint32_t rx_sof1: 1; + uint32_t rx_eof1: 1; + uint32_t rx_start1: 1; + uint32_t tx_start1: 1; + uint32_t rx_udf1: 1; + uint32_t tx_ovf1: 1; + uint32_t rx_pf_valid1: 1; + uint32_t ext_bit01: 1; + uint32_t ext_bit11: 1; + uint32_t ext_bit21: 1; + uint32_t ext_bit31: 1; + uint32_t rx_new_packet1: 1; + uint32_t rd_retry1: 1; + uint32_t gpio_sdio1: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc0_int_ena1; + union { + struct { + uint32_t tohost_bit01: 1; + uint32_t tohost_bit11: 1; + uint32_t tohost_bit21: 1; + uint32_t tohost_bit31: 1; + uint32_t tohost_bit41: 1; + uint32_t tohost_bit51: 1; + uint32_t tohost_bit61: 1; + uint32_t tohost_bit71: 1; + uint32_t token0_1to01: 1; + uint32_t token1_1to01: 1; + uint32_t token0_0to11: 1; + uint32_t token1_0to11: 1; + uint32_t rx_sof1: 1; + uint32_t rx_eof1: 1; + uint32_t rx_start1: 1; + uint32_t tx_start1: 1; + uint32_t rx_udf1: 1; + uint32_t tx_ovf1: 1; + uint32_t rx_pf_valid1: 1; + uint32_t ext_bit01: 1; + uint32_t ext_bit11: 1; + uint32_t ext_bit21: 1; + uint32_t ext_bit31: 1; + uint32_t wifi_rx_new_packet1: 1; + uint32_t rd_retry1: 1; + uint32_t bt_rx_new_packet1: 1; + uint32_t reserved26: 6; + }; + uint32_t val; + } slc1_int_ena1; + uint32_t reserved_11c; + uint32_t reserved_120; + uint32_t reserved_124; + uint32_t reserved_128; + uint32_t reserved_12c; + uint32_t reserved_130; + uint32_t reserved_134; + uint32_t reserved_138; + uint32_t reserved_13c; + uint32_t reserved_140; + uint32_t reserved_144; + uint32_t reserved_148; + uint32_t reserved_14c; + uint32_t reserved_150; + uint32_t reserved_154; + uint32_t reserved_158; + uint32_t reserved_15c; + uint32_t reserved_160; + uint32_t reserved_164; + uint32_t reserved_168; + uint32_t reserved_16c; + uint32_t reserved_170; + uint32_t reserved_174; + uint32_t date; /**/ + uint32_t id; /**/ + uint32_t reserved_180; + uint32_t reserved_184; + uint32_t reserved_188; + uint32_t reserved_18c; + uint32_t reserved_190; + uint32_t reserved_194; + uint32_t reserved_198; + uint32_t reserved_19c; + uint32_t reserved_1a0; + uint32_t reserved_1a4; + uint32_t reserved_1a8; + uint32_t reserved_1ac; + uint32_t reserved_1b0; + uint32_t reserved_1b4; + uint32_t reserved_1b8; + uint32_t reserved_1bc; + uint32_t reserved_1c0; + uint32_t reserved_1c4; + uint32_t reserved_1c8; + uint32_t reserved_1cc; + uint32_t reserved_1d0; + uint32_t reserved_1d4; + uint32_t reserved_1d8; + uint32_t reserved_1dc; + uint32_t reserved_1e0; + uint32_t reserved_1e4; + uint32_t reserved_1e8; + uint32_t reserved_1ec; + union { + struct { + uint32_t frc_sdio11: 5; + uint32_t frc_sdio20: 5; + uint32_t frc_neg_samp: 5; + uint32_t frc_pos_samp: 5; + uint32_t frc_quick_in: 5; + uint32_t sdio20_int_delay: 1; + uint32_t sdio_pad_pullup: 1; + uint32_t hspeed_con_en: 1; + uint32_t reserved28: 4; + }; + uint32_t val; + } conf; + union { + struct { + uint32_t sdio20_mode: 5; + uint32_t sdio_neg_samp: 5; + uint32_t sdio_quick_in: 5; + uint32_t reserved15: 17; + }; + uint32_t val; + } inf_st; +} host_dev_t; +extern host_dev_t HOST; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_HOST_STRUCT_H_ */ diff --git a/tools/sdk/include/soc/soc/io_mux_reg.h b/tools/sdk/include/soc/soc/io_mux_reg.h index 5516e59834c..25978b326ff 100644 --- a/tools/sdk/include/soc/soc/io_mux_reg.h +++ b/tools/sdk/include/soc/soc/io_mux_reg.h @@ -117,11 +117,17 @@ static inline void __attribute__ ((deprecated)) PIN_PULLDWN_EN(uint32_t PIN_NAME #define PIN_CTRL (DR_REG_IO_MUX_BASE +0x00) #define CLK_OUT3 0xf +#define CLK_OUT3_V CLK_OUT3 #define CLK_OUT3_S 8 +#define CLK_OUT3_M (CLK_OUT3_V << CLK_OUT3_S) #define CLK_OUT2 0xf +#define CLK_OUT2_V CLK_OUT2 #define CLK_OUT2_S 4 +#define CLK_OUT2_M (CLK_OUT2_V << CLK_OUT2_S) #define CLK_OUT1 0xf +#define CLK_OUT1_V CLK_OUT1 #define CLK_OUT1_S 0 +#define CLK_OUT1_M (CLK_OUT1_V << CLK_OUT1_S) #define PERIPHS_IO_MUX_GPIO0_U (DR_REG_IO_MUX_BASE +0x44) #define IO_MUX_GPIO0_REG PERIPHS_IO_MUX_GPIO0_U diff --git a/tools/sdk/include/soc/soc/periph_defs.h b/tools/sdk/include/soc/soc/periph_defs.h new file mode 100644 index 00000000000..c4ad589c9dd --- /dev/null +++ b/tools/sdk/include/soc/soc/periph_defs.h @@ -0,0 +1,64 @@ +// 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 _SOC_PERIPH_DEFS_H_ +#define _SOC_PERIPH_DEFS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + PERIPH_LEDC_MODULE = 0, + PERIPH_UART0_MODULE, + PERIPH_UART1_MODULE, + PERIPH_UART2_MODULE, + PERIPH_I2C0_MODULE, + PERIPH_I2C1_MODULE, + PERIPH_I2S0_MODULE, + PERIPH_I2S1_MODULE, + PERIPH_TIMG0_MODULE, + PERIPH_TIMG1_MODULE, + PERIPH_PWM0_MODULE, + PERIPH_PWM1_MODULE, + PERIPH_PWM2_MODULE, + PERIPH_PWM3_MODULE, + PERIPH_UHCI0_MODULE, + PERIPH_UHCI1_MODULE, + PERIPH_RMT_MODULE, + PERIPH_PCNT_MODULE, + PERIPH_SPI_MODULE, + PERIPH_HSPI_MODULE, + PERIPH_VSPI_MODULE, + PERIPH_SPI_DMA_MODULE, + PERIPH_SDMMC_MODULE, + PERIPH_SDIO_SLAVE_MODULE, + PERIPH_CAN_MODULE, + PERIPH_EMAC_MODULE, + PERIPH_RNG_MODULE, + PERIPH_WIFI_MODULE, + PERIPH_BT_MODULE, + PERIPH_WIFI_BT_COMMON_MODULE, + PERIPH_BT_BASEBAND_MODULE, + PERIPH_BT_LC_MODULE, + PERIPH_AES_MODULE, + PERIPH_SHA_MODULE, + PERIPH_RSA_MODULE, +} periph_module_t; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_PERIPH_DEFS_H_ */ diff --git a/tools/sdk/include/soc/soc/rmt_struct.h b/tools/sdk/include/soc/soc/rmt_struct.h index 68e244ad425..3fb254ad60b 100644 --- a/tools/sdk/include/soc/soc/rmt_struct.h +++ b/tools/sdk/include/soc/soc/rmt_struct.h @@ -19,7 +19,9 @@ extern "C" { #endif typedef volatile struct { - uint32_t data_ch[8]; /*The R/W ram address for channel0-7 by apb fifo access.*/ + uint32_t data_ch[8]; /*The R/W ram address for channel0-7 by apb fifo access. + Note that in some circumstances, data read from the FIFO may get lost. As RMT memory area accesses using the RMTMEM method do not have this issue + and provide all the functionality that the FIFO register has, it is encouraged to use that instead.*/ struct{ union { struct { @@ -39,7 +41,7 @@ typedef volatile struct { uint32_t rx_en: 1; /*Set this bit to enable receiving data for channel0-7.*/ uint32_t mem_wr_rst: 1; /*Set this bit to reset write ram address for channel0-7 by receiver access.*/ uint32_t mem_rd_rst: 1; /*Set this bit to reset read ram address for channel0-7 by transmitter access.*/ - uint32_t apb_mem_rst: 1; /*Set this bit to reset W/R ram address for channel0-7 by apb fifo access*/ + uint32_t apb_mem_rst: 1; /*Set this bit to reset W/R ram address for channel0-7 by apb fifo access (using fifo is discouraged, please see the note above at data_ch[] item)*/ uint32_t mem_owner: 1; /*This is the mark of channel0-7's ram usage right.1'b1:receiver uses the ram 0:transmitter uses the ram*/ uint32_t tx_conti_mode: 1; /*Set this bit to continue sending from the first data to the last data in channel0-7 again and again.*/ uint32_t rx_filter_en: 1; /*This is the receive filter enable bit for channel0-7.*/ @@ -54,7 +56,7 @@ typedef volatile struct { } conf1; } conf_ch[8]; uint32_t status_ch[8]; /*The status for channel0-7*/ - uint32_t apb_mem_addr_ch[8]; /*The ram relative address in channel0-7 by apb fifo access*/ + uint32_t apb_mem_addr_ch[8]; /*The ram relative address in channel0-7 by apb fifo access (using fifo is discouraged, please see the note above at data_ch[] item)*/ union { struct { uint32_t ch0_tx_end: 1; /*The interrupt raw bit for channel 0 turns to high level when the transmit process is done.*/ @@ -219,7 +221,7 @@ typedef volatile struct { } tx_lim_ch[8]; union { struct { - uint32_t fifo_mask: 1; /*Set this bit to disable apb fifo access*/ + uint32_t fifo_mask: 1; /*Set this bit to enable RMTMEM and disable apb fifo access (using fifo is discouraged, please see the note above at data_ch[] item)*/ uint32_t mem_tx_wrap_en: 1; /*when data need to be send is more than channel's mem can store then set this bit to enable reuse of mem this bit is used together with reg_rmt_tx_lim_chn.*/ uint32_t reserved2: 30; }; @@ -243,22 +245,11 @@ typedef struct { }; } rmt_item32_t; -typedef struct { - union { - struct { - uint16_t duration :15; - uint16_t level :1; - }; - uint16_t val; - }; -} rmt_item16_t; - //Allow access to RMT memory using RMTMEM.chan[0].data32[8] typedef volatile struct { struct { union { rmt_item32_t data32[64]; - rmt_item16_t data16[128]; }; } chan[8]; } rmt_mem_t; diff --git a/tools/sdk/include/soc/soc/rtc.h b/tools/sdk/include/soc/soc/rtc.h index ec9935fd57d..a528bdd15de 100644 --- a/tools/sdk/include/soc/soc/rtc.h +++ b/tools/sdk/include/soc/soc/rtc.h @@ -75,6 +75,26 @@ typedef enum { RTC_CPU_FREQ_2M = 4, //!< 2 MHz } rtc_cpu_freq_t; +/** + * @brief CPU clock source + */ +typedef enum { + RTC_CPU_FREQ_SRC_XTAL, //!< XTAL + RTC_CPU_FREQ_SRC_PLL, //!< PLL (480M or 320M) + RTC_CPU_FREQ_SRC_8M, //!< Internal 8M RTC oscillator + RTC_CPU_FREQ_SRC_APLL //!< APLL +} rtc_cpu_freq_src_t; + +/** + * @brief CPU clock configuration structure + */ +typedef struct { + rtc_cpu_freq_src_t source; //!< The clock from which CPU clock is derived + uint32_t source_freq_mhz; //!< Source clock frequency + uint32_t div; //!< Divider, freq_mhz = source_freq_mhz / div + uint32_t freq_mhz; //!< CPU clock frequency +} rtc_cpu_freq_config_t; + /** * @brief RTC SLOW_CLK frequency values */ @@ -108,13 +128,13 @@ typedef enum { * Initialization parameters for rtc_clk_init */ typedef struct { - rtc_xtal_freq_t xtal_freq : 8; //!< Main XTAL frequency - rtc_cpu_freq_t cpu_freq : 3; //!< CPU frequency to set - rtc_fast_freq_t fast_freq : 1; //!< RTC_FAST_CLK frequency to set - rtc_slow_freq_t slow_freq : 2; //!< RTC_SLOW_CLK frequency to set - uint32_t clk_8m_div : 3; //!< RTC 8M clock divider (division is by clk_8m_div+1, i.e. 0 means 8MHz frequency) - uint32_t slow_clk_dcap : 8; //!< RTC 150k clock adjustment parameter (higher value leads to lower frequency) - uint32_t clk_8m_dfreq : 8; //!< RTC 8m clock adjustment parameter (higher value leads to higher frequency) + rtc_xtal_freq_t xtal_freq : 8; //!< Main XTAL frequency + rtc_cpu_freq_t cpu_freq_mhz : 10; //!< CPU frequency to set, in MHz + rtc_fast_freq_t fast_freq : 1; //!< RTC_FAST_CLK frequency to set + rtc_slow_freq_t slow_freq : 2; //!< RTC_SLOW_CLK frequency to set + uint32_t clk_8m_div : 3; //!< RTC 8M clock divider (division is by clk_8m_div+1, i.e. 0 means 8MHz frequency) + uint32_t slow_clk_dcap : 8; //!< RTC 150k clock adjustment parameter (higher value leads to lower frequency) + uint32_t clk_8m_dfreq : 8; //!< RTC 8m clock adjustment parameter (higher value leads to higher frequency) } rtc_clk_config_t; /** @@ -122,7 +142,7 @@ typedef struct { */ #define RTC_CLK_CONFIG_DEFAULT() { \ .xtal_freq = RTC_XTAL_FREQ_AUTO, \ - .cpu_freq = RTC_CPU_FREQ_80M, \ + .cpu_freq_mhz = 80, \ .fast_freq = RTC_FAST_FREQ_8M, \ .slow_freq = RTC_SLOW_FREQ_RTC, \ .clk_8m_div = 0, \ @@ -173,6 +193,11 @@ void rtc_clk_xtal_freq_update(rtc_xtal_freq_t xtal_freq); */ void rtc_clk_32k_enable(bool en); +/** + * @brief Configure 32 kHz XTAL oscillator to accept external clock signal + */ +void rtc_clk_32k_enable_external(); + /** * @brief Get the state of 32k XTAL oscillator * @return true if 32k XTAL oscillator has been enabled @@ -281,6 +306,9 @@ rtc_fast_freq_t rtc_clk_fast_freq_get(); /** * @brief Switch CPU frequency * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_config_set instead. + * * If a PLL-derived frequency is requested (80, 160, 240 MHz), this function * will enable the PLL. Otherwise, PLL will be disabled. * Note: this function is not optimized for switching speed. It may take several @@ -288,11 +316,14 @@ rtc_fast_freq_t rtc_clk_fast_freq_get(); * * @param cpu_freq new CPU frequency */ -void rtc_clk_cpu_freq_set(rtc_cpu_freq_t cpu_freq); +void rtc_clk_cpu_freq_set(rtc_cpu_freq_t cpu_freq) __attribute__((deprecated)); /** * @brief Switch CPU frequency * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_set_config_fast instead. + * * This is a faster version of rtc_clk_cpu_freq_set, which can handle some of * the frequency switch paths (XTAL -> PLL, PLL -> XTAL). * When switching from PLL to XTAL, PLL is not disabled (unlike rtc_clk_cpu_freq_set). @@ -307,11 +338,14 @@ void rtc_clk_cpu_freq_set(rtc_cpu_freq_t cpu_freq); * * @param cpu_freq new CPU frequency */ -void rtc_clk_cpu_freq_set_fast(rtc_cpu_freq_t cpu_freq); +void rtc_clk_cpu_freq_set_fast(rtc_cpu_freq_t cpu_freq) __attribute__((deprecated)); /** * @brief Get the currently selected CPU frequency * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_get_config instead. + * * Although CPU can be clocked by APLL and RTC 8M sources, such support is not * exposed through this library. As such, this function will not return * meaningful values when these clock sources are configured (e.g. using direct @@ -320,22 +354,97 @@ void rtc_clk_cpu_freq_set_fast(rtc_cpu_freq_t cpu_freq); * * @return CPU frequency (one of rtc_cpu_freq_t values) */ -rtc_cpu_freq_t rtc_clk_cpu_freq_get(); +rtc_cpu_freq_t rtc_clk_cpu_freq_get() __attribute__((deprecated)); /** * @brief Get corresponding frequency value for rtc_cpu_freq_t enum value + * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_get/set_config instead. + * * @param cpu_freq CPU frequency, on of rtc_cpu_freq_t values * @return CPU frequency, in HZ */ -uint32_t rtc_clk_cpu_freq_value(rtc_cpu_freq_t cpu_freq); +uint32_t rtc_clk_cpu_freq_value(rtc_cpu_freq_t cpu_freq) __attribute__((deprecated)); /** * @brief Get rtc_cpu_freq_t enum value for given CPU frequency + * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_mhz_to_config instead. + * * @param cpu_freq_mhz CPU frequency, one of 80, 160, 240, 2, and XTAL frequency * @param[out] out_val output, rtc_cpu_freq_t value corresponding to the frequency * @return true if the given frequency value matches one of enum values */ - bool rtc_clk_cpu_freq_from_mhz(int cpu_freq_mhz, rtc_cpu_freq_t* out_val); + bool rtc_clk_cpu_freq_from_mhz(int cpu_freq_mhz, rtc_cpu_freq_t* out_val) __attribute__((deprecated)); + +/** + * @brief Get CPU frequency config corresponding to a rtc_cpu_freq_t value + * @param cpu_freq CPU frequency enumeration value + * @param[out] out_config Output, CPU frequency configuration structure + */ + void rtc_clk_cpu_freq_to_config(rtc_cpu_freq_t cpu_freq, rtc_cpu_freq_config_t* out_config); + + /** + * @brief Get CPU frequency config for a given frequency + * @param freq_mhz Frequency in MHz + * @param[out] out_config Output, CPU frequency configuration structure + * @return true if frequency can be obtained, false otherwise + */ + bool rtc_clk_cpu_freq_mhz_to_config(uint32_t freq_mhz, rtc_cpu_freq_config_t* out_config); + + /** + * @brief Switch CPU frequency + * + * This function sets CPU frequency according to the given configuration + * structure. It enables PLLs, if necessary. + * + * @note This function in not intended to be called by applications in FreeRTOS + * environment. This is because it does not adjust various timers based on the + * new CPU frequency. + * + * @param config CPU frequency configuration structure + */ + void rtc_clk_cpu_freq_set_config(const rtc_cpu_freq_config_t* config); + + /** + * @brief Switch CPU frequency (optimized for speed) + * + * This function is a faster equivalent of rtc_clk_cpu_freq_set_config. + * It works faster because it does not disable PLLs when switching from PLL to + * XTAL and does not enabled them when switching back. If PLL is not already + * enabled when this function is called to switch from XTAL to PLL frequency, + * or the PLL which is enabled is the wrong one, this function will fall back + * to calling rtc_clk_cpu_freq_set_config. + * + * Unlike rtc_clk_cpu_freq_set_config, this function relies on static data, + * so it is less safe to use it e.g. from a panic handler (when memory might + * be corrupted). + * + * @note This function in not intended to be called by applications in FreeRTOS + * environment. This is because it does not adjust various timers based on the + * new CPU frequency. + * + * @param config CPU frequency configuration structure + */ + void rtc_clk_cpu_freq_set_config_fast(const rtc_cpu_freq_config_t* config); + + /** + * @brief Get the currently used CPU frequency configuration + * @param[out] out_config Output, CPU frequency configuration structure + */ + void rtc_clk_cpu_freq_get_config(rtc_cpu_freq_config_t* out_config); + + /** + * @brief Switch CPU clock source to XTAL + * + * Short form for filling in rtc_cpu_freq_config_t structure and calling + * rtc_clk_cpu_freq_set_config when a switch to XTAL is needed. + * Assumes that XTAL frequency has been determined — don't call in startup code. + */ + void rtc_clk_cpu_freq_set_xtal(); + /** * @brief Store new APB frequency value into RTC_APB_FREQ_REG @@ -427,7 +536,6 @@ void rtc_clk_wait_for_slow_cycle(); * @brief sleep configuration for rtc_sleep_init function */ typedef struct { - uint32_t soc_clk_sel : 2; //!< SoC clock select, see RTC_CNTL_SOC_CLK_SEL uint32_t lslp_mem_inf_fpu : 1; //!< force normal voltage in sleep mode (digital domain memory) uint32_t rtc_mem_inf_fpu : 1; //!< force normal voltage in sleep mode (RTC memory) uint32_t rtc_mem_inf_follow_cpu : 1;//!< keep low voltage in sleep mode (even if ULP/touch is used) @@ -444,6 +552,7 @@ typedef struct { uint32_t rtc_dbias_slp : 3; //!< set bias for RTC domain, in sleep mode uint32_t lslp_meminf_pd : 1; //!< remove all peripheral force power up flags uint32_t vddsdio_pd_en : 1; //!< power down VDDSDIO regulator + uint32_t xtal_fpu : 1; //!< keep main XTAL powered up in sleep } rtc_sleep_config_t; /** @@ -455,7 +564,6 @@ typedef struct { * @param RTC_SLEEP_PD_x flags combined using bitwise OR */ #define RTC_SLEEP_CONFIG_DEFAULT(sleep_flags) { \ - .soc_clk_sel = RTC_CNTL_SOC_CLK_SEL_XTL, \ .lslp_mem_inf_fpu = 0, \ .rtc_mem_inf_fpu = 0, \ .rtc_mem_inf_follow_cpu = ((sleep_flags) & RTC_SLEEP_PD_RTC_MEM_FOLLOW_CPU) ? 1 : 0, \ @@ -468,10 +576,11 @@ typedef struct { .wdt_flashboot_mod_en = 0, \ .dig_dbias_wak = RTC_CNTL_DBIAS_1V10, \ .dig_dbias_slp = RTC_CNTL_DBIAS_0V90, \ - .rtc_dbias_wak = RTC_CNTL_DBIAS_0V90, \ + .rtc_dbias_wak = RTC_CNTL_DBIAS_1V10, \ .rtc_dbias_slp = RTC_CNTL_DBIAS_0V90, \ .lslp_meminf_pd = 1, \ .vddsdio_pd_en = ((sleep_flags) & RTC_SLEEP_PD_VDDSDIO) ? 1 : 0, \ + .xtal_fpu = ((sleep_flags) & RTC_SLEEP_PD_XTAL) ? 0 : 1 \ }; #define RTC_SLEEP_PD_DIG BIT(0) //!< Deep sleep (power down digital domain) @@ -480,6 +589,7 @@ typedef struct { #define RTC_SLEEP_PD_RTC_FAST_MEM BIT(3) //!< Power down RTC FAST memory #define RTC_SLEEP_PD_RTC_MEM_FOLLOW_CPU BIT(4) //!< RTC FAST and SLOW memories are automatically powered up and down along with the CPU #define RTC_SLEEP_PD_VDDSDIO BIT(5) //!< Power down VDDSDIO regulator +#define RTC_SLEEP_PD_XTAL BIT(6) //!< Power down main XTAL /** * @brief Prepare the chip to enter sleep mode @@ -577,13 +687,16 @@ typedef struct { */ void rtc_init(rtc_config_t cfg); +#define RTC_VDDSDIO_TIEH_1_8V 0 //!< TIEH field value for 1.8V VDDSDIO +#define RTC_VDDSDIO_TIEH_3_3V 1 //!< TIEH field value for 3.3V VDDSDIO + /** * Structure describing vddsdio configuration */ typedef struct { uint32_t force : 1; //!< If 1, use configuration from RTC registers; if 0, use EFUSE/bootstrapping pins. uint32_t enable : 1; //!< Enable VDDSDIO regulator - uint32_t tieh : 1; //!< Select VDDSDIO voltage: 1 — 1.8V, 0 — 3.3V + uint32_t tieh : 1; //!< Select VDDSDIO voltage. One of RTC_VDDSDIO_TIEH_1_8V, RTC_VDDSDIO_TIEH_3_3V uint32_t drefh : 2; //!< Tuning parameter for VDDSDIO regulator uint32_t drefm : 2; //!< Tuning parameter for VDDSDIO regulator uint32_t drefl : 2; //!< Tuning parameter for VDDSDIO regulator diff --git a/tools/sdk/include/soc/soc/rtc_cntl_reg.h b/tools/sdk/include/soc/soc/rtc_cntl_reg.h index d54a7dde7cf..090b3f7072c 100644 --- a/tools/sdk/include/soc/soc/rtc_cntl_reg.h +++ b/tools/sdk/include/soc/soc/rtc_cntl_reg.h @@ -1070,7 +1070,7 @@ #define RTC_CNTL_DBG_ATTEN_M ((RTC_CNTL_DBG_ATTEN_V)<<(RTC_CNTL_DBG_ATTEN_S)) #define RTC_CNTL_DBG_ATTEN_V 0x3 #define RTC_CNTL_DBG_ATTEN_S 24 - +#define RTC_CNTL_DBG_ATTEN_DEFAULT 3 #define RTC_CNTL_REG (DR_REG_RTCCNTL_BASE + 0x7c) /* RTC_CNTL_FORCE_PU : R/W ;bitpos:[31] ;default: 1'd1 ; */ /*description: RTC_REG force power up*/ diff --git a/tools/sdk/include/soc/soc/rtc_periph.h b/tools/sdk/include/soc/soc/rtc_periph.h new file mode 100644 index 00000000000..832186c3d8f --- /dev/null +++ b/tools/sdk/include/soc/soc/rtc_periph.h @@ -0,0 +1,62 @@ +// 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 _SOC_RTC_PERIPH_H +#define _SOC_RTC_PERIPH_H +#include +#include "soc/rtc_io_reg.h" +#include "soc/rtc_cntl_reg.h" +#include "soc/rtc_gpio_channel.h" +#include "soc/gpio_pins.h" +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * @brief Pin function information for a single GPIO pad's RTC functions. + * + * This is an internal function of the driver, and is not usually useful + * for external use. + */ +typedef struct { + uint32_t reg; /*!< Register of RTC pad, or 0 if not an RTC GPIO */ + uint32_t mux; /*!< Bit mask for selecting digital pad or RTC pad */ + uint32_t func; /*!< Shift of pad function (FUN_SEL) field */ + uint32_t ie; /*!< Mask of input enable */ + uint32_t pullup; /*!< Mask of pullup enable */ + uint32_t pulldown; /*!< Mask of pulldown enable */ + uint32_t slpsel; /*!< If slpsel bit is set, slpie will be used as pad input enabled signal in sleep mode */ + uint32_t slpie; /*!< Mask of input enable in sleep mode */ + uint32_t hold; /*!< Mask of hold enable */ + uint32_t hold_force;/*!< Mask of hold_force bit for RTC IO in RTC_CNTL_HOLD_FORCE_REG */ + uint32_t drv_v; /*!< Mask of drive capability */ + uint32_t drv_s; /*!< Offset of drive capability */ + int rtc_num; /*!< RTC IO number, or -1 if not an RTC GPIO */ +} rtc_gpio_desc_t; + +/** + * @brief Provides access to a constant table of RTC I/O pin + * function information. + * + * This is an internal function of the driver, and is not usually useful + * for external use. + */ +extern const rtc_gpio_desc_t rtc_gpio_desc[GPIO_PIN_COUNT]; + +#ifdef __cplusplus +} +#endif + +#endif // _SOC_RTC_PERIPH_H diff --git a/tools/sdk/include/soc/soc/rtc_wdt.h b/tools/sdk/include/soc/soc/rtc_wdt.h new file mode 100644 index 00000000000..bdaea942b4d --- /dev/null +++ b/tools/sdk/include/soc/soc/rtc_wdt.h @@ -0,0 +1,202 @@ +// 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 + */ + +#ifndef _SOC_RTC_WDT_H +#define _SOC_RTC_WDT_H + +#include +#include +#include "soc/rtc_cntl_reg.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(); + +/** + * @brief Set protect of rtc_wdt. + */ +void rtc_wdt_protect_on(); + +/** + * @brief Reset protect of rtc_wdt. + */ +void rtc_wdt_protect_off(); + +/** + * @brief Enable rtc_wdt. + */ +void rtc_wdt_enable(); + +/** + * @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(); + +/** + * @brief Disable rtc_wdt. + */ +void rtc_wdt_disable(); + +/** + * @brief Reset counter rtc_wdt. + * + * It returns to stage 0 and its expiry counter restarts from 0. + */ +void rtc_wdt_feed(); + +/** + * @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(); + +#ifdef __cplusplus +} +#endif + +#endif // _SOC_RTC_WDT_H diff --git a/tools/sdk/include/soc/soc/sdio_slave_periph.h b/tools/sdk/include/soc/soc/sdio_slave_periph.h new file mode 100644 index 00000000000..467104dcf4a --- /dev/null +++ b/tools/sdk/include/soc/soc/sdio_slave_periph.h @@ -0,0 +1,49 @@ +// 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 _SOC_SDIO_SLAVE_PERIPH_H_ +#define _SOC_SDIO_SLAVE_PERIPH_H_ + +#include +//include soc related (generated) definitions +#include "soc/sdio_slave_pins.h" +#include "soc/slc_reg.h" +#include "soc/slc_struct.h" +#include "soc/host_reg.h" +#include "soc/host_struct.h" +#include "soc/hinf_reg.h" +#include "soc/hinf_struct.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** pin and signal information of each slot */ +typedef struct { + uint32_t clk_gpio; + uint32_t cmd_gpio; + uint32_t d0_gpio; + uint32_t d1_gpio; + uint32_t d2_gpio; + uint32_t d3_gpio; + int func; +} sdio_slave_slot_info_t; + +extern const sdio_slave_slot_info_t sdio_slave_slot_info[]; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_SDIO_SLAVE_PERIPH_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/sdio_slave_pins.h b/tools/sdk/include/soc/soc/sdio_slave_pins.h new file mode 100644 index 00000000000..97c8bec07fd --- /dev/null +++ b/tools/sdk/include/soc/soc/sdio_slave_pins.h @@ -0,0 +1,34 @@ +// 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 _SOC_SDIO_SLAVE_PINS_H_ +#define _SOC_SDIO_SLAVE_PINS_H_ + +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_CLK 6 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_CMD 11 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D0 7 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D1 8 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D2 9 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D3 10 +#define SDIO_SLAVE_SLOT0_FUNC 0 + +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_CLK 14 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_CMD 15 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D0 2 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D1 4 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D2 12 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D3 13 +#define SDIO_SLAVE_SLOT1_FUNC 4 + +#endif /* _SOC_SDIO_SLAVE_PINS_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/sdmmc_periph.h b/tools/sdk/include/soc/soc/sdmmc_periph.h new file mode 100644 index 00000000000..79dfaf34abd --- /dev/null +++ b/tools/sdk/include/soc/soc/sdmmc_periph.h @@ -0,0 +1,53 @@ +// 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 _SOC_SDMMC_PERIPH_H_ +#define _SOC_SDMMC_PERIPH_H_ + +#include +//include soc related (generated) definitions +#include "soc/sdmmc_pins.h" +#include "soc/sdmmc_reg.h" +#include "soc/sdmmc_struct.h" +#include "soc/gpio_sig_map.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint8_t clk_gpio; + uint8_t cmd_gpio; + uint8_t d0_gpio; + uint8_t d1_gpio; + uint8_t d2_gpio; + uint8_t d3_gpio; + uint8_t d4_gpio; + uint8_t d5_gpio; + uint8_t d6_gpio; + uint8_t d7_gpio; + uint8_t card_detect; + uint8_t write_protect; + uint8_t card_int; + uint8_t width; +} sdmmc_slot_info_t; + +/** pin and signal information of each slot */ +extern const sdmmc_slot_info_t sdmmc_slot_info[]; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_SDMMC_PERIPH_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/sdmmc_pins.h b/tools/sdk/include/soc/soc/sdmmc_pins.h new file mode 100644 index 00000000000..c0b328239ad --- /dev/null +++ b/tools/sdk/include/soc/soc/sdmmc_pins.h @@ -0,0 +1,38 @@ +// 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 _SOC_SDMMC_PINS_H_ +#define _SOC_SDMMC_PINS_H_ + +#define SDMMC_SLOT0_IOMUX_PIN_NUM_CLK 6 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_CMD 11 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D0 7 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D1 8 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D2 9 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D3 10 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D4 16 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D5 17 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D6 5 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D7 18 +#define SDMMC_SLOT0_FUNC 0 + +#define SDMMC_SLOT1_IOMUX_PIN_NUM_CLK 14 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_CMD 15 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_D0 2 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_D1 4 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_D2 12 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_D3 13 +#define SDMMC_SLOT1_FUNC 4 + +#endif /* _SOC_SDMMC_PINS_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/sdmmc_reg.h b/tools/sdk/include/soc/soc/sdmmc_reg.h index d1b452d1d19..0e92f682244 100644 --- a/tools/sdk/include/soc/soc/sdmmc_reg.h +++ b/tools/sdk/include/soc/soc/sdmmc_reg.h @@ -66,9 +66,12 @@ #define SDMMC_CLOCK_REG (DR_REG_SDMMC_BASE + 0x800) +#define SDMMC_INTMASK_IO_SLOT1 BIT(17) +#define SDMMC_INTMASK_IO_SLOT0 BIT(16) #define SDMMC_INTMASK_EBE BIT(15) #define SDMMC_INTMASK_ACD BIT(14) #define SDMMC_INTMASK_SBE BIT(13) +#define SDMMC_INTMASK_BCI BIT(13) #define SDMMC_INTMASK_HLE BIT(12) #define SDMMC_INTMASK_FRUN BIT(11) #define SDMMC_INTMASK_HTO BIT(10) diff --git a/tools/sdk/include/soc/soc/sdmmc_struct.h b/tools/sdk/include/soc/soc/sdmmc_struct.h index 9f3625a3d93..6aa64b43cc3 100644 --- a/tools/sdk/include/soc/soc/sdmmc_struct.h +++ b/tools/sdk/include/soc/soc/sdmmc_struct.h @@ -255,7 +255,7 @@ typedef volatile struct { union { struct { - uint32_t cards: 2; ///< bit N reads 1 if card N is present + uint32_t cards: 2; ///< bit N reads 0 if card N is present uint32_t reserved: 30; }; uint32_t val; @@ -263,7 +263,7 @@ typedef volatile struct { union { struct { - uint32_t card0: 2; ///< bit N reads 1 if card N is write protected + uint32_t cards: 2; ///< bit N reads 1 if card N is write protected uint32_t reserved: 30; }; uint32_t val; @@ -283,7 +283,12 @@ typedef volatile struct { uint32_t usrid; ///< user ID uint32_t verid; ///< IP block version uint32_t hcon; ///< compile-time IP configuration - uint32_t uhs; ///< TBD + union { + struct { + uint32_t voltage: 16; ///< voltage control for slots; no-op on ESP32. + uint32_t ddr: 16; ///< bit N enables DDR mode for card N + }; + } uhs; ///< UHS related settings union { struct { @@ -348,7 +353,16 @@ typedef volatile struct { uint32_t bufaddrl; ///< unused uint32_t bufaddru; ///< unused uint32_t reserved_a8[22]; - uint32_t cardthrctl; + union { + struct { + uint32_t read_thr_en : 1; ///< initiate transfer only if FIFO has more space than the read threshold + uint32_t busy_clr_int_en : 1; ///< enable generation of busy clear interrupts + uint32_t write_thr_en : 1; ///< equivalent of read_thr_en for writes + uint32_t reserved1 : 13; + uint32_t card_threshold : 12; ///< threshold value for reads/writes, in bytes + }; + uint32_t val; + } cardthrctl; uint32_t back_end_power; uint32_t uhs_reg_ext; uint32_t emmc_ddr_reg; diff --git a/tools/sdk/include/soc/soc/slc_reg.h b/tools/sdk/include/soc/soc/slc_reg.h new file mode 100644 index 00000000000..3d4541cccbc --- /dev/null +++ b/tools/sdk/include/soc/soc/slc_reg.h @@ -0,0 +1,3244 @@ +// 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 _SOC_SLC_REG_H_ +#define _SOC_SLC_REG_H_ + + +#include "soc.h" +#define SLC_CONF0_REG (DR_REG_SLC_BASE + 0x0) +/* SLC_SLC1_TOKEN_SEL : R/W ;bitpos:[31] ;default: 1'h1 ; */ +/*description: */ +#define SLC_SLC1_TOKEN_SEL (BIT(31)) +#define SLC_SLC1_TOKEN_SEL_M (BIT(31)) +#define SLC_SLC1_TOKEN_SEL_V 0x1 +#define SLC_SLC1_TOKEN_SEL_S 31 +/* SLC_SLC1_TOKEN_AUTO_CLR : R/W ;bitpos:[30] ;default: 1'h1 ; */ +/*description: */ +#define SLC_SLC1_TOKEN_AUTO_CLR (BIT(30)) +#define SLC_SLC1_TOKEN_AUTO_CLR_M (BIT(30)) +#define SLC_SLC1_TOKEN_AUTO_CLR_V 0x1 +#define SLC_SLC1_TOKEN_AUTO_CLR_S 30 +/* SLC_SLC1_TXDATA_BURST_EN : R/W ;bitpos:[29] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_TXDATA_BURST_EN (BIT(29)) +#define SLC_SLC1_TXDATA_BURST_EN_M (BIT(29)) +#define SLC_SLC1_TXDATA_BURST_EN_V 0x1 +#define SLC_SLC1_TXDATA_BURST_EN_S 29 +/* SLC_SLC1_TXDSCR_BURST_EN : R/W ;bitpos:[28] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_TXDSCR_BURST_EN (BIT(28)) +#define SLC_SLC1_TXDSCR_BURST_EN_M (BIT(28)) +#define SLC_SLC1_TXDSCR_BURST_EN_V 0x1 +#define SLC_SLC1_TXDSCR_BURST_EN_S 28 +/* SLC_SLC1_TXLINK_AUTO_RET : R/W ;bitpos:[27] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_AUTO_RET (BIT(27)) +#define SLC_SLC1_TXLINK_AUTO_RET_M (BIT(27)) +#define SLC_SLC1_TXLINK_AUTO_RET_V 0x1 +#define SLC_SLC1_TXLINK_AUTO_RET_S 27 +/* SLC_SLC1_RXLINK_AUTO_RET : R/W ;bitpos:[26] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_AUTO_RET (BIT(26)) +#define SLC_SLC1_RXLINK_AUTO_RET_M (BIT(26)) +#define SLC_SLC1_RXLINK_AUTO_RET_V 0x1 +#define SLC_SLC1_RXLINK_AUTO_RET_S 26 +/* SLC_SLC1_RXDATA_BURST_EN : R/W ;bitpos:[25] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_RXDATA_BURST_EN (BIT(25)) +#define SLC_SLC1_RXDATA_BURST_EN_M (BIT(25)) +#define SLC_SLC1_RXDATA_BURST_EN_V 0x1 +#define SLC_SLC1_RXDATA_BURST_EN_S 25 +/* SLC_SLC1_RXDSCR_BURST_EN : R/W ;bitpos:[24] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_RXDSCR_BURST_EN (BIT(24)) +#define SLC_SLC1_RXDSCR_BURST_EN_M (BIT(24)) +#define SLC_SLC1_RXDSCR_BURST_EN_V 0x1 +#define SLC_SLC1_RXDSCR_BURST_EN_S 24 +/* SLC_SLC1_RX_NO_RESTART_CLR : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_NO_RESTART_CLR (BIT(23)) +#define SLC_SLC1_RX_NO_RESTART_CLR_M (BIT(23)) +#define SLC_SLC1_RX_NO_RESTART_CLR_V 0x1 +#define SLC_SLC1_RX_NO_RESTART_CLR_S 23 +/* SLC_SLC1_RX_AUTO_WRBACK : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_AUTO_WRBACK (BIT(22)) +#define SLC_SLC1_RX_AUTO_WRBACK_M (BIT(22)) +#define SLC_SLC1_RX_AUTO_WRBACK_V 0x1 +#define SLC_SLC1_RX_AUTO_WRBACK_S 22 +/* SLC_SLC1_RX_LOOP_TEST : R/W ;bitpos:[21] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_RX_LOOP_TEST (BIT(21)) +#define SLC_SLC1_RX_LOOP_TEST_M (BIT(21)) +#define SLC_SLC1_RX_LOOP_TEST_V 0x1 +#define SLC_SLC1_RX_LOOP_TEST_S 21 +/* SLC_SLC1_TX_LOOP_TEST : R/W ;bitpos:[20] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_TX_LOOP_TEST (BIT(20)) +#define SLC_SLC1_TX_LOOP_TEST_M (BIT(20)) +#define SLC_SLC1_TX_LOOP_TEST_V 0x1 +#define SLC_SLC1_TX_LOOP_TEST_S 20 +/* SLC_SLC1_WR_RETRY_MASK_EN : R/W ;bitpos:[19] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_WR_RETRY_MASK_EN (BIT(19)) +#define SLC_SLC1_WR_RETRY_MASK_EN_M (BIT(19)) +#define SLC_SLC1_WR_RETRY_MASK_EN_V 0x1 +#define SLC_SLC1_WR_RETRY_MASK_EN_S 19 +/* SLC_SLC0_WR_RETRY_MASK_EN : R/W ;bitpos:[18] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_WR_RETRY_MASK_EN (BIT(18)) +#define SLC_SLC0_WR_RETRY_MASK_EN_M (BIT(18)) +#define SLC_SLC0_WR_RETRY_MASK_EN_V 0x1 +#define SLC_SLC0_WR_RETRY_MASK_EN_S 18 +/* SLC_SLC1_RX_RST : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_RST (BIT(17)) +#define SLC_SLC1_RX_RST_M (BIT(17)) +#define SLC_SLC1_RX_RST_V 0x1 +#define SLC_SLC1_RX_RST_S 17 +/* SLC_SLC1_TX_RST : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC1_TX_RST (BIT(16)) +#define SLC_SLC1_TX_RST_M (BIT(16)) +#define SLC_SLC1_TX_RST_V 0x1 +#define SLC_SLC1_TX_RST_S 16 +/* SLC_SLC0_TOKEN_SEL : R/W ;bitpos:[15] ;default: 1'h1 ; */ +/*description: */ +#define SLC_SLC0_TOKEN_SEL (BIT(15)) +#define SLC_SLC0_TOKEN_SEL_M (BIT(15)) +#define SLC_SLC0_TOKEN_SEL_V 0x1 +#define SLC_SLC0_TOKEN_SEL_S 15 +/* SLC_SLC0_TOKEN_AUTO_CLR : R/W ;bitpos:[14] ;default: 1'h1 ; */ +/*description: */ +#define SLC_SLC0_TOKEN_AUTO_CLR (BIT(14)) +#define SLC_SLC0_TOKEN_AUTO_CLR_M (BIT(14)) +#define SLC_SLC0_TOKEN_AUTO_CLR_V 0x1 +#define SLC_SLC0_TOKEN_AUTO_CLR_S 14 +/* SLC_SLC0_TXDATA_BURST_EN : R/W ;bitpos:[13] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_TXDATA_BURST_EN (BIT(13)) +#define SLC_SLC0_TXDATA_BURST_EN_M (BIT(13)) +#define SLC_SLC0_TXDATA_BURST_EN_V 0x1 +#define SLC_SLC0_TXDATA_BURST_EN_S 13 +/* SLC_SLC0_TXDSCR_BURST_EN : R/W ;bitpos:[12] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_TXDSCR_BURST_EN (BIT(12)) +#define SLC_SLC0_TXDSCR_BURST_EN_M (BIT(12)) +#define SLC_SLC0_TXDSCR_BURST_EN_V 0x1 +#define SLC_SLC0_TXDSCR_BURST_EN_S 12 +/* SLC_SLC0_TXLINK_AUTO_RET : R/W ;bitpos:[11] ;default: 1'h1 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_AUTO_RET (BIT(11)) +#define SLC_SLC0_TXLINK_AUTO_RET_M (BIT(11)) +#define SLC_SLC0_TXLINK_AUTO_RET_V 0x1 +#define SLC_SLC0_TXLINK_AUTO_RET_S 11 +/* SLC_SLC0_RXLINK_AUTO_RET : R/W ;bitpos:[10] ;default: 1'h1 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_AUTO_RET (BIT(10)) +#define SLC_SLC0_RXLINK_AUTO_RET_M (BIT(10)) +#define SLC_SLC0_RXLINK_AUTO_RET_V 0x1 +#define SLC_SLC0_RXLINK_AUTO_RET_S 10 +/* SLC_SLC0_RXDATA_BURST_EN : R/W ;bitpos:[9] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_RXDATA_BURST_EN (BIT(9)) +#define SLC_SLC0_RXDATA_BURST_EN_M (BIT(9)) +#define SLC_SLC0_RXDATA_BURST_EN_V 0x1 +#define SLC_SLC0_RXDATA_BURST_EN_S 9 +/* SLC_SLC0_RXDSCR_BURST_EN : R/W ;bitpos:[8] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_RXDSCR_BURST_EN (BIT(8)) +#define SLC_SLC0_RXDSCR_BURST_EN_M (BIT(8)) +#define SLC_SLC0_RXDSCR_BURST_EN_V 0x1 +#define SLC_SLC0_RXDSCR_BURST_EN_S 8 +/* SLC_SLC0_RX_NO_RESTART_CLR : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_NO_RESTART_CLR (BIT(7)) +#define SLC_SLC0_RX_NO_RESTART_CLR_M (BIT(7)) +#define SLC_SLC0_RX_NO_RESTART_CLR_V 0x1 +#define SLC_SLC0_RX_NO_RESTART_CLR_S 7 +/* SLC_SLC0_RX_AUTO_WRBACK : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_AUTO_WRBACK (BIT(6)) +#define SLC_SLC0_RX_AUTO_WRBACK_M (BIT(6)) +#define SLC_SLC0_RX_AUTO_WRBACK_V 0x1 +#define SLC_SLC0_RX_AUTO_WRBACK_S 6 +/* SLC_SLC0_RX_LOOP_TEST : R/W ;bitpos:[5] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_RX_LOOP_TEST (BIT(5)) +#define SLC_SLC0_RX_LOOP_TEST_M (BIT(5)) +#define SLC_SLC0_RX_LOOP_TEST_V 0x1 +#define SLC_SLC0_RX_LOOP_TEST_S 5 +/* SLC_SLC0_TX_LOOP_TEST : R/W ;bitpos:[4] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_TX_LOOP_TEST (BIT(4)) +#define SLC_SLC0_TX_LOOP_TEST_M (BIT(4)) +#define SLC_SLC0_TX_LOOP_TEST_V 0x1 +#define SLC_SLC0_TX_LOOP_TEST_S 4 +/* SLC_AHBM_RST : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_AHBM_RST (BIT(3)) +#define SLC_AHBM_RST_M (BIT(3)) +#define SLC_AHBM_RST_V 0x1 +#define SLC_AHBM_RST_S 3 +/* SLC_AHBM_FIFO_RST : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_AHBM_FIFO_RST (BIT(2)) +#define SLC_AHBM_FIFO_RST_M (BIT(2)) +#define SLC_AHBM_FIFO_RST_V 0x1 +#define SLC_AHBM_FIFO_RST_S 2 +/* SLC_SLC0_RX_RST : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_RST (BIT(1)) +#define SLC_SLC0_RX_RST_M (BIT(1)) +#define SLC_SLC0_RX_RST_V 0x1 +#define SLC_SLC0_RX_RST_S 1 +/* SLC_SLC0_TX_RST : R/W ;bitpos:[0] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC0_TX_RST (BIT(0)) +#define SLC_SLC0_TX_RST_M (BIT(0)) +#define SLC_SLC0_TX_RST_V 0x1 +#define SLC_SLC0_TX_RST_S 0 + +#define SLC_0INT_RAW_REG (DR_REG_SLC_BASE + 0x4) +/* SLC_SLC0_RX_QUICK_EOF_INT_RAW : RO ;bitpos:[26] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_QUICK_EOF_INT_RAW (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_RAW_M (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_RAW_V 0x1 +#define SLC_SLC0_RX_QUICK_EOF_INT_RAW_S 26 +/* SLC_CMD_DTC_INT_RAW : RO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define SLC_CMD_DTC_INT_RAW (BIT(25)) +#define SLC_CMD_DTC_INT_RAW_M (BIT(25)) +#define SLC_CMD_DTC_INT_RAW_V 0x1 +#define SLC_CMD_DTC_INT_RAW_S 25 +/* SLC_SLC0_TX_ERR_EOF_INT_RAW : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_ERR_EOF_INT_RAW (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_RAW_M (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_RAW_V 0x1 +#define SLC_SLC0_TX_ERR_EOF_INT_RAW_S 24 +/* SLC_SLC0_WR_RETRY_DONE_INT_RAW : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_WR_RETRY_DONE_INT_RAW (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_RAW_M (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_RAW_V 0x1 +#define SLC_SLC0_WR_RETRY_DONE_INT_RAW_S 23 +/* SLC_SLC0_HOST_RD_ACK_INT_RAW : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_HOST_RD_ACK_INT_RAW (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_RAW_M (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_RAW_V 0x1 +#define SLC_SLC0_HOST_RD_ACK_INT_RAW_S 22 +/* SLC_SLC0_TX_DSCR_EMPTY_INT_RAW : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_EMPTY_INT_RAW (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_RAW_M (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_RAW_V 0x1 +#define SLC_SLC0_TX_DSCR_EMPTY_INT_RAW_S 21 +/* SLC_SLC0_RX_DSCR_ERR_INT_RAW : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DSCR_ERR_INT_RAW (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_RAW_M (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_RAW_V 0x1 +#define SLC_SLC0_RX_DSCR_ERR_INT_RAW_S 20 +/* SLC_SLC0_TX_DSCR_ERR_INT_RAW : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_ERR_INT_RAW (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_RAW_M (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_RAW_V 0x1 +#define SLC_SLC0_TX_DSCR_ERR_INT_RAW_S 19 +/* SLC_SLC0_TOHOST_INT_RAW : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOHOST_INT_RAW (BIT(18)) +#define SLC_SLC0_TOHOST_INT_RAW_M (BIT(18)) +#define SLC_SLC0_TOHOST_INT_RAW_V 0x1 +#define SLC_SLC0_TOHOST_INT_RAW_S 18 +/* SLC_SLC0_RX_EOF_INT_RAW : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_EOF_INT_RAW (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_RAW_M (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_RAW_V 0x1 +#define SLC_SLC0_RX_EOF_INT_RAW_S 17 +/* SLC_SLC0_RX_DONE_INT_RAW : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DONE_INT_RAW (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_RAW_M (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_RAW_V 0x1 +#define SLC_SLC0_RX_DONE_INT_RAW_S 16 +/* SLC_SLC0_TX_SUC_EOF_INT_RAW : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_SUC_EOF_INT_RAW (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_RAW_M (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_RAW_V 0x1 +#define SLC_SLC0_TX_SUC_EOF_INT_RAW_S 15 +/* SLC_SLC0_TX_DONE_INT_RAW : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DONE_INT_RAW (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_RAW_M (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_RAW_V 0x1 +#define SLC_SLC0_TX_DONE_INT_RAW_S 14 +/* SLC_SLC0_TOKEN1_1TO0_INT_RAW : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_1TO0_INT_RAW (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_RAW_M (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_RAW_V 0x1 +#define SLC_SLC0_TOKEN1_1TO0_INT_RAW_S 13 +/* SLC_SLC0_TOKEN0_1TO0_INT_RAW : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_1TO0_INT_RAW (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_RAW_M (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_RAW_V 0x1 +#define SLC_SLC0_TOKEN0_1TO0_INT_RAW_S 12 +/* SLC_SLC0_TX_OVF_INT_RAW : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_OVF_INT_RAW (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_RAW_M (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_RAW_V 0x1 +#define SLC_SLC0_TX_OVF_INT_RAW_S 11 +/* SLC_SLC0_RX_UDF_INT_RAW : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_UDF_INT_RAW (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_RAW_M (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_RAW_V 0x1 +#define SLC_SLC0_RX_UDF_INT_RAW_S 10 +/* SLC_SLC0_TX_START_INT_RAW : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_START_INT_RAW (BIT(9)) +#define SLC_SLC0_TX_START_INT_RAW_M (BIT(9)) +#define SLC_SLC0_TX_START_INT_RAW_V 0x1 +#define SLC_SLC0_TX_START_INT_RAW_S 9 +/* SLC_SLC0_RX_START_INT_RAW : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_START_INT_RAW (BIT(8)) +#define SLC_SLC0_RX_START_INT_RAW_M (BIT(8)) +#define SLC_SLC0_RX_START_INT_RAW_V 0x1 +#define SLC_SLC0_RX_START_INT_RAW_S 8 +/* SLC_FRHOST_BIT7_INT_RAW : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT7_INT_RAW (BIT(7)) +#define SLC_FRHOST_BIT7_INT_RAW_M (BIT(7)) +#define SLC_FRHOST_BIT7_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT7_INT_RAW_S 7 +/* SLC_FRHOST_BIT6_INT_RAW : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT6_INT_RAW (BIT(6)) +#define SLC_FRHOST_BIT6_INT_RAW_M (BIT(6)) +#define SLC_FRHOST_BIT6_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT6_INT_RAW_S 6 +/* SLC_FRHOST_BIT5_INT_RAW : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT5_INT_RAW (BIT(5)) +#define SLC_FRHOST_BIT5_INT_RAW_M (BIT(5)) +#define SLC_FRHOST_BIT5_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT5_INT_RAW_S 5 +/* SLC_FRHOST_BIT4_INT_RAW : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT4_INT_RAW (BIT(4)) +#define SLC_FRHOST_BIT4_INT_RAW_M (BIT(4)) +#define SLC_FRHOST_BIT4_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT4_INT_RAW_S 4 +/* SLC_FRHOST_BIT3_INT_RAW : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT3_INT_RAW (BIT(3)) +#define SLC_FRHOST_BIT3_INT_RAW_M (BIT(3)) +#define SLC_FRHOST_BIT3_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT3_INT_RAW_S 3 +/* SLC_FRHOST_BIT2_INT_RAW : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT2_INT_RAW (BIT(2)) +#define SLC_FRHOST_BIT2_INT_RAW_M (BIT(2)) +#define SLC_FRHOST_BIT2_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT2_INT_RAW_S 2 +/* SLC_FRHOST_BIT1_INT_RAW : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT1_INT_RAW (BIT(1)) +#define SLC_FRHOST_BIT1_INT_RAW_M (BIT(1)) +#define SLC_FRHOST_BIT1_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT1_INT_RAW_S 1 +/* SLC_FRHOST_BIT0_INT_RAW : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT0_INT_RAW (BIT(0)) +#define SLC_FRHOST_BIT0_INT_RAW_M (BIT(0)) +#define SLC_FRHOST_BIT0_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT0_INT_RAW_S 0 + +#define SLC_0INT_ST_REG (DR_REG_SLC_BASE + 0x8) +/* SLC_SLC0_RX_QUICK_EOF_INT_ST : RO ;bitpos:[26] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_QUICK_EOF_INT_ST (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_ST_M (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_ST_V 0x1 +#define SLC_SLC0_RX_QUICK_EOF_INT_ST_S 26 +/* SLC_CMD_DTC_INT_ST : RO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define SLC_CMD_DTC_INT_ST (BIT(25)) +#define SLC_CMD_DTC_INT_ST_M (BIT(25)) +#define SLC_CMD_DTC_INT_ST_V 0x1 +#define SLC_CMD_DTC_INT_ST_S 25 +/* SLC_SLC0_TX_ERR_EOF_INT_ST : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_ERR_EOF_INT_ST (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_ST_M (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_ST_V 0x1 +#define SLC_SLC0_TX_ERR_EOF_INT_ST_S 24 +/* SLC_SLC0_WR_RETRY_DONE_INT_ST : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_WR_RETRY_DONE_INT_ST (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_ST_M (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_ST_V 0x1 +#define SLC_SLC0_WR_RETRY_DONE_INT_ST_S 23 +/* SLC_SLC0_HOST_RD_ACK_INT_ST : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_HOST_RD_ACK_INT_ST (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_ST_M (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_ST_V 0x1 +#define SLC_SLC0_HOST_RD_ACK_INT_ST_S 22 +/* SLC_SLC0_TX_DSCR_EMPTY_INT_ST : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ST (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ST_M (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ST_V 0x1 +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ST_S 21 +/* SLC_SLC0_RX_DSCR_ERR_INT_ST : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DSCR_ERR_INT_ST (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_ST_M (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_ST_V 0x1 +#define SLC_SLC0_RX_DSCR_ERR_INT_ST_S 20 +/* SLC_SLC0_TX_DSCR_ERR_INT_ST : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_ERR_INT_ST (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_ST_M (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_ST_V 0x1 +#define SLC_SLC0_TX_DSCR_ERR_INT_ST_S 19 +/* SLC_SLC0_TOHOST_INT_ST : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOHOST_INT_ST (BIT(18)) +#define SLC_SLC0_TOHOST_INT_ST_M (BIT(18)) +#define SLC_SLC0_TOHOST_INT_ST_V 0x1 +#define SLC_SLC0_TOHOST_INT_ST_S 18 +/* SLC_SLC0_RX_EOF_INT_ST : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_EOF_INT_ST (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_ST_M (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_ST_V 0x1 +#define SLC_SLC0_RX_EOF_INT_ST_S 17 +/* SLC_SLC0_RX_DONE_INT_ST : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DONE_INT_ST (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_ST_M (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_ST_V 0x1 +#define SLC_SLC0_RX_DONE_INT_ST_S 16 +/* SLC_SLC0_TX_SUC_EOF_INT_ST : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_SUC_EOF_INT_ST (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_ST_M (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_ST_V 0x1 +#define SLC_SLC0_TX_SUC_EOF_INT_ST_S 15 +/* SLC_SLC0_TX_DONE_INT_ST : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DONE_INT_ST (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_ST_M (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_ST_V 0x1 +#define SLC_SLC0_TX_DONE_INT_ST_S 14 +/* SLC_SLC0_TOKEN1_1TO0_INT_ST : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_1TO0_INT_ST (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_ST_M (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_ST_V 0x1 +#define SLC_SLC0_TOKEN1_1TO0_INT_ST_S 13 +/* SLC_SLC0_TOKEN0_1TO0_INT_ST : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_1TO0_INT_ST (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_ST_M (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_ST_V 0x1 +#define SLC_SLC0_TOKEN0_1TO0_INT_ST_S 12 +/* SLC_SLC0_TX_OVF_INT_ST : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_OVF_INT_ST (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_ST_M (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_ST_V 0x1 +#define SLC_SLC0_TX_OVF_INT_ST_S 11 +/* SLC_SLC0_RX_UDF_INT_ST : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_UDF_INT_ST (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_ST_M (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_ST_V 0x1 +#define SLC_SLC0_RX_UDF_INT_ST_S 10 +/* SLC_SLC0_TX_START_INT_ST : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_START_INT_ST (BIT(9)) +#define SLC_SLC0_TX_START_INT_ST_M (BIT(9)) +#define SLC_SLC0_TX_START_INT_ST_V 0x1 +#define SLC_SLC0_TX_START_INT_ST_S 9 +/* SLC_SLC0_RX_START_INT_ST : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_START_INT_ST (BIT(8)) +#define SLC_SLC0_RX_START_INT_ST_M (BIT(8)) +#define SLC_SLC0_RX_START_INT_ST_V 0x1 +#define SLC_SLC0_RX_START_INT_ST_S 8 +/* SLC_FRHOST_BIT7_INT_ST : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT7_INT_ST (BIT(7)) +#define SLC_FRHOST_BIT7_INT_ST_M (BIT(7)) +#define SLC_FRHOST_BIT7_INT_ST_V 0x1 +#define SLC_FRHOST_BIT7_INT_ST_S 7 +/* SLC_FRHOST_BIT6_INT_ST : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT6_INT_ST (BIT(6)) +#define SLC_FRHOST_BIT6_INT_ST_M (BIT(6)) +#define SLC_FRHOST_BIT6_INT_ST_V 0x1 +#define SLC_FRHOST_BIT6_INT_ST_S 6 +/* SLC_FRHOST_BIT5_INT_ST : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT5_INT_ST (BIT(5)) +#define SLC_FRHOST_BIT5_INT_ST_M (BIT(5)) +#define SLC_FRHOST_BIT5_INT_ST_V 0x1 +#define SLC_FRHOST_BIT5_INT_ST_S 5 +/* SLC_FRHOST_BIT4_INT_ST : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT4_INT_ST (BIT(4)) +#define SLC_FRHOST_BIT4_INT_ST_M (BIT(4)) +#define SLC_FRHOST_BIT4_INT_ST_V 0x1 +#define SLC_FRHOST_BIT4_INT_ST_S 4 +/* SLC_FRHOST_BIT3_INT_ST : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT3_INT_ST (BIT(3)) +#define SLC_FRHOST_BIT3_INT_ST_M (BIT(3)) +#define SLC_FRHOST_BIT3_INT_ST_V 0x1 +#define SLC_FRHOST_BIT3_INT_ST_S 3 +/* SLC_FRHOST_BIT2_INT_ST : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT2_INT_ST (BIT(2)) +#define SLC_FRHOST_BIT2_INT_ST_M (BIT(2)) +#define SLC_FRHOST_BIT2_INT_ST_V 0x1 +#define SLC_FRHOST_BIT2_INT_ST_S 2 +/* SLC_FRHOST_BIT1_INT_ST : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT1_INT_ST (BIT(1)) +#define SLC_FRHOST_BIT1_INT_ST_M (BIT(1)) +#define SLC_FRHOST_BIT1_INT_ST_V 0x1 +#define SLC_FRHOST_BIT1_INT_ST_S 1 +/* SLC_FRHOST_BIT0_INT_ST : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT0_INT_ST (BIT(0)) +#define SLC_FRHOST_BIT0_INT_ST_M (BIT(0)) +#define SLC_FRHOST_BIT0_INT_ST_V 0x1 +#define SLC_FRHOST_BIT0_INT_ST_S 0 + +#define SLC_0INT_ENA_REG (DR_REG_SLC_BASE + 0xC) +/* SLC_SLC0_RX_QUICK_EOF_INT_ENA : R/W ;bitpos:[26] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_QUICK_EOF_INT_ENA (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_ENA_M (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_ENA_V 0x1 +#define SLC_SLC0_RX_QUICK_EOF_INT_ENA_S 26 +/* SLC_CMD_DTC_INT_ENA : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define SLC_CMD_DTC_INT_ENA (BIT(25)) +#define SLC_CMD_DTC_INT_ENA_M (BIT(25)) +#define SLC_CMD_DTC_INT_ENA_V 0x1 +#define SLC_CMD_DTC_INT_ENA_S 25 +/* SLC_SLC0_TX_ERR_EOF_INT_ENA : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_ERR_EOF_INT_ENA (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_ENA_M (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_ENA_V 0x1 +#define SLC_SLC0_TX_ERR_EOF_INT_ENA_S 24 +/* SLC_SLC0_WR_RETRY_DONE_INT_ENA : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_WR_RETRY_DONE_INT_ENA (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_ENA_M (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_ENA_V 0x1 +#define SLC_SLC0_WR_RETRY_DONE_INT_ENA_S 23 +/* SLC_SLC0_HOST_RD_ACK_INT_ENA : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_HOST_RD_ACK_INT_ENA (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_ENA_M (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_ENA_V 0x1 +#define SLC_SLC0_HOST_RD_ACK_INT_ENA_S 22 +/* SLC_SLC0_TX_DSCR_EMPTY_INT_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ENA (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ENA_M (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ENA_V 0x1 +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ENA_S 21 +/* SLC_SLC0_RX_DSCR_ERR_INT_ENA : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DSCR_ERR_INT_ENA (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_ENA_M (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_ENA_V 0x1 +#define SLC_SLC0_RX_DSCR_ERR_INT_ENA_S 20 +/* SLC_SLC0_TX_DSCR_ERR_INT_ENA : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_ERR_INT_ENA (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_ENA_M (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_ENA_V 0x1 +#define SLC_SLC0_TX_DSCR_ERR_INT_ENA_S 19 +/* SLC_SLC0_TOHOST_INT_ENA : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOHOST_INT_ENA (BIT(18)) +#define SLC_SLC0_TOHOST_INT_ENA_M (BIT(18)) +#define SLC_SLC0_TOHOST_INT_ENA_V 0x1 +#define SLC_SLC0_TOHOST_INT_ENA_S 18 +/* SLC_SLC0_RX_EOF_INT_ENA : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_EOF_INT_ENA (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_ENA_M (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_ENA_V 0x1 +#define SLC_SLC0_RX_EOF_INT_ENA_S 17 +/* SLC_SLC0_RX_DONE_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DONE_INT_ENA (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_ENA_M (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_ENA_V 0x1 +#define SLC_SLC0_RX_DONE_INT_ENA_S 16 +/* SLC_SLC0_TX_SUC_EOF_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_SUC_EOF_INT_ENA (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_ENA_M (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_ENA_V 0x1 +#define SLC_SLC0_TX_SUC_EOF_INT_ENA_S 15 +/* SLC_SLC0_TX_DONE_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DONE_INT_ENA (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_ENA_M (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_ENA_V 0x1 +#define SLC_SLC0_TX_DONE_INT_ENA_S 14 +/* SLC_SLC0_TOKEN1_1TO0_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_1TO0_INT_ENA (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_ENA_M (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_ENA_V 0x1 +#define SLC_SLC0_TOKEN1_1TO0_INT_ENA_S 13 +/* SLC_SLC0_TOKEN0_1TO0_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_1TO0_INT_ENA (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_ENA_M (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_ENA_V 0x1 +#define SLC_SLC0_TOKEN0_1TO0_INT_ENA_S 12 +/* SLC_SLC0_TX_OVF_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_OVF_INT_ENA (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_ENA_M (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_ENA_V 0x1 +#define SLC_SLC0_TX_OVF_INT_ENA_S 11 +/* SLC_SLC0_RX_UDF_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_UDF_INT_ENA (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_ENA_M (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_ENA_V 0x1 +#define SLC_SLC0_RX_UDF_INT_ENA_S 10 +/* SLC_SLC0_TX_START_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_START_INT_ENA (BIT(9)) +#define SLC_SLC0_TX_START_INT_ENA_M (BIT(9)) +#define SLC_SLC0_TX_START_INT_ENA_V 0x1 +#define SLC_SLC0_TX_START_INT_ENA_S 9 +/* SLC_SLC0_RX_START_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_START_INT_ENA (BIT(8)) +#define SLC_SLC0_RX_START_INT_ENA_M (BIT(8)) +#define SLC_SLC0_RX_START_INT_ENA_V 0x1 +#define SLC_SLC0_RX_START_INT_ENA_S 8 +/* SLC_FRHOST_BIT7_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT7_INT_ENA (BIT(7)) +#define SLC_FRHOST_BIT7_INT_ENA_M (BIT(7)) +#define SLC_FRHOST_BIT7_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT7_INT_ENA_S 7 +/* SLC_FRHOST_BIT6_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT6_INT_ENA (BIT(6)) +#define SLC_FRHOST_BIT6_INT_ENA_M (BIT(6)) +#define SLC_FRHOST_BIT6_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT6_INT_ENA_S 6 +/* SLC_FRHOST_BIT5_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT5_INT_ENA (BIT(5)) +#define SLC_FRHOST_BIT5_INT_ENA_M (BIT(5)) +#define SLC_FRHOST_BIT5_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT5_INT_ENA_S 5 +/* SLC_FRHOST_BIT4_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT4_INT_ENA (BIT(4)) +#define SLC_FRHOST_BIT4_INT_ENA_M (BIT(4)) +#define SLC_FRHOST_BIT4_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT4_INT_ENA_S 4 +/* SLC_FRHOST_BIT3_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT3_INT_ENA (BIT(3)) +#define SLC_FRHOST_BIT3_INT_ENA_M (BIT(3)) +#define SLC_FRHOST_BIT3_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT3_INT_ENA_S 3 +/* SLC_FRHOST_BIT2_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT2_INT_ENA (BIT(2)) +#define SLC_FRHOST_BIT2_INT_ENA_M (BIT(2)) +#define SLC_FRHOST_BIT2_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT2_INT_ENA_S 2 +/* SLC_FRHOST_BIT1_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT1_INT_ENA (BIT(1)) +#define SLC_FRHOST_BIT1_INT_ENA_M (BIT(1)) +#define SLC_FRHOST_BIT1_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT1_INT_ENA_S 1 +/* SLC_FRHOST_BIT0_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT0_INT_ENA (BIT(0)) +#define SLC_FRHOST_BIT0_INT_ENA_M (BIT(0)) +#define SLC_FRHOST_BIT0_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT0_INT_ENA_S 0 + +#define SLC_0INT_CLR_REG (DR_REG_SLC_BASE + 0x10) +/* SLC_SLC0_RX_QUICK_EOF_INT_CLR : WO ;bitpos:[26] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_QUICK_EOF_INT_CLR (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_CLR_M (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_CLR_V 0x1 +#define SLC_SLC0_RX_QUICK_EOF_INT_CLR_S 26 +/* SLC_CMD_DTC_INT_CLR : WO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define SLC_CMD_DTC_INT_CLR (BIT(25)) +#define SLC_CMD_DTC_INT_CLR_M (BIT(25)) +#define SLC_CMD_DTC_INT_CLR_V 0x1 +#define SLC_CMD_DTC_INT_CLR_S 25 +/* SLC_SLC0_TX_ERR_EOF_INT_CLR : WO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_ERR_EOF_INT_CLR (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_CLR_M (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_CLR_V 0x1 +#define SLC_SLC0_TX_ERR_EOF_INT_CLR_S 24 +/* SLC_SLC0_WR_RETRY_DONE_INT_CLR : WO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_WR_RETRY_DONE_INT_CLR (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_CLR_M (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_CLR_V 0x1 +#define SLC_SLC0_WR_RETRY_DONE_INT_CLR_S 23 +/* SLC_SLC0_HOST_RD_ACK_INT_CLR : WO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_HOST_RD_ACK_INT_CLR (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_CLR_M (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_CLR_V 0x1 +#define SLC_SLC0_HOST_RD_ACK_INT_CLR_S 22 +/* SLC_SLC0_TX_DSCR_EMPTY_INT_CLR : WO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_EMPTY_INT_CLR (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_CLR_M (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_CLR_V 0x1 +#define SLC_SLC0_TX_DSCR_EMPTY_INT_CLR_S 21 +/* SLC_SLC0_RX_DSCR_ERR_INT_CLR : WO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DSCR_ERR_INT_CLR (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_CLR_M (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_CLR_V 0x1 +#define SLC_SLC0_RX_DSCR_ERR_INT_CLR_S 20 +/* SLC_SLC0_TX_DSCR_ERR_INT_CLR : WO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_ERR_INT_CLR (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_CLR_M (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_CLR_V 0x1 +#define SLC_SLC0_TX_DSCR_ERR_INT_CLR_S 19 +/* SLC_SLC0_TOHOST_INT_CLR : WO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOHOST_INT_CLR (BIT(18)) +#define SLC_SLC0_TOHOST_INT_CLR_M (BIT(18)) +#define SLC_SLC0_TOHOST_INT_CLR_V 0x1 +#define SLC_SLC0_TOHOST_INT_CLR_S 18 +/* SLC_SLC0_RX_EOF_INT_CLR : WO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_EOF_INT_CLR (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_CLR_M (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_CLR_V 0x1 +#define SLC_SLC0_RX_EOF_INT_CLR_S 17 +/* SLC_SLC0_RX_DONE_INT_CLR : WO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DONE_INT_CLR (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_CLR_M (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_CLR_V 0x1 +#define SLC_SLC0_RX_DONE_INT_CLR_S 16 +/* SLC_SLC0_TX_SUC_EOF_INT_CLR : WO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_SUC_EOF_INT_CLR (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_CLR_M (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_CLR_V 0x1 +#define SLC_SLC0_TX_SUC_EOF_INT_CLR_S 15 +/* SLC_SLC0_TX_DONE_INT_CLR : WO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DONE_INT_CLR (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_CLR_M (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_CLR_V 0x1 +#define SLC_SLC0_TX_DONE_INT_CLR_S 14 +/* SLC_SLC0_TOKEN1_1TO0_INT_CLR : WO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_1TO0_INT_CLR (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_CLR_M (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_CLR_V 0x1 +#define SLC_SLC0_TOKEN1_1TO0_INT_CLR_S 13 +/* SLC_SLC0_TOKEN0_1TO0_INT_CLR : WO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_1TO0_INT_CLR (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_CLR_M (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_CLR_V 0x1 +#define SLC_SLC0_TOKEN0_1TO0_INT_CLR_S 12 +/* SLC_SLC0_TX_OVF_INT_CLR : WO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_OVF_INT_CLR (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_CLR_M (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_CLR_V 0x1 +#define SLC_SLC0_TX_OVF_INT_CLR_S 11 +/* SLC_SLC0_RX_UDF_INT_CLR : WO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_UDF_INT_CLR (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_CLR_M (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_CLR_V 0x1 +#define SLC_SLC0_RX_UDF_INT_CLR_S 10 +/* SLC_SLC0_TX_START_INT_CLR : WO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_START_INT_CLR (BIT(9)) +#define SLC_SLC0_TX_START_INT_CLR_M (BIT(9)) +#define SLC_SLC0_TX_START_INT_CLR_V 0x1 +#define SLC_SLC0_TX_START_INT_CLR_S 9 +/* SLC_SLC0_RX_START_INT_CLR : WO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_START_INT_CLR (BIT(8)) +#define SLC_SLC0_RX_START_INT_CLR_M (BIT(8)) +#define SLC_SLC0_RX_START_INT_CLR_V 0x1 +#define SLC_SLC0_RX_START_INT_CLR_S 8 +/* SLC_FRHOST_BIT7_INT_CLR : WO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT7_INT_CLR (BIT(7)) +#define SLC_FRHOST_BIT7_INT_CLR_M (BIT(7)) +#define SLC_FRHOST_BIT7_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT7_INT_CLR_S 7 +/* SLC_FRHOST_BIT6_INT_CLR : WO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT6_INT_CLR (BIT(6)) +#define SLC_FRHOST_BIT6_INT_CLR_M (BIT(6)) +#define SLC_FRHOST_BIT6_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT6_INT_CLR_S 6 +/* SLC_FRHOST_BIT5_INT_CLR : WO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT5_INT_CLR (BIT(5)) +#define SLC_FRHOST_BIT5_INT_CLR_M (BIT(5)) +#define SLC_FRHOST_BIT5_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT5_INT_CLR_S 5 +/* SLC_FRHOST_BIT4_INT_CLR : WO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT4_INT_CLR (BIT(4)) +#define SLC_FRHOST_BIT4_INT_CLR_M (BIT(4)) +#define SLC_FRHOST_BIT4_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT4_INT_CLR_S 4 +/* SLC_FRHOST_BIT3_INT_CLR : WO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT3_INT_CLR (BIT(3)) +#define SLC_FRHOST_BIT3_INT_CLR_M (BIT(3)) +#define SLC_FRHOST_BIT3_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT3_INT_CLR_S 3 +/* SLC_FRHOST_BIT2_INT_CLR : WO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT2_INT_CLR (BIT(2)) +#define SLC_FRHOST_BIT2_INT_CLR_M (BIT(2)) +#define SLC_FRHOST_BIT2_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT2_INT_CLR_S 2 +/* SLC_FRHOST_BIT1_INT_CLR : WO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT1_INT_CLR (BIT(1)) +#define SLC_FRHOST_BIT1_INT_CLR_M (BIT(1)) +#define SLC_FRHOST_BIT1_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT1_INT_CLR_S 1 +/* SLC_FRHOST_BIT0_INT_CLR : WO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT0_INT_CLR (BIT(0)) +#define SLC_FRHOST_BIT0_INT_CLR_M (BIT(0)) +#define SLC_FRHOST_BIT0_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT0_INT_CLR_S 0 + +#define SLC_1INT_RAW_REG (DR_REG_SLC_BASE + 0x14) +/* SLC_SLC1_TX_ERR_EOF_INT_RAW : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_ERR_EOF_INT_RAW (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_RAW_M (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_RAW_V 0x1 +#define SLC_SLC1_TX_ERR_EOF_INT_RAW_S 24 +/* SLC_SLC1_WR_RETRY_DONE_INT_RAW : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_WR_RETRY_DONE_INT_RAW (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_RAW_M (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_RAW_V 0x1 +#define SLC_SLC1_WR_RETRY_DONE_INT_RAW_S 23 +/* SLC_SLC1_HOST_RD_ACK_INT_RAW : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_HOST_RD_ACK_INT_RAW (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_RAW_M (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_RAW_V 0x1 +#define SLC_SLC1_HOST_RD_ACK_INT_RAW_S 22 +/* SLC_SLC1_TX_DSCR_EMPTY_INT_RAW : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_EMPTY_INT_RAW (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_RAW_M (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_RAW_V 0x1 +#define SLC_SLC1_TX_DSCR_EMPTY_INT_RAW_S 21 +/* SLC_SLC1_RX_DSCR_ERR_INT_RAW : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DSCR_ERR_INT_RAW (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_RAW_M (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_RAW_V 0x1 +#define SLC_SLC1_RX_DSCR_ERR_INT_RAW_S 20 +/* SLC_SLC1_TX_DSCR_ERR_INT_RAW : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_ERR_INT_RAW (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_RAW_M (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_RAW_V 0x1 +#define SLC_SLC1_TX_DSCR_ERR_INT_RAW_S 19 +/* SLC_SLC1_TOHOST_INT_RAW : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOHOST_INT_RAW (BIT(18)) +#define SLC_SLC1_TOHOST_INT_RAW_M (BIT(18)) +#define SLC_SLC1_TOHOST_INT_RAW_V 0x1 +#define SLC_SLC1_TOHOST_INT_RAW_S 18 +/* SLC_SLC1_RX_EOF_INT_RAW : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_EOF_INT_RAW (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_RAW_M (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_RAW_V 0x1 +#define SLC_SLC1_RX_EOF_INT_RAW_S 17 +/* SLC_SLC1_RX_DONE_INT_RAW : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DONE_INT_RAW (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_RAW_M (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_RAW_V 0x1 +#define SLC_SLC1_RX_DONE_INT_RAW_S 16 +/* SLC_SLC1_TX_SUC_EOF_INT_RAW : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_SUC_EOF_INT_RAW (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_RAW_M (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_RAW_V 0x1 +#define SLC_SLC1_TX_SUC_EOF_INT_RAW_S 15 +/* SLC_SLC1_TX_DONE_INT_RAW : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DONE_INT_RAW (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_RAW_M (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_RAW_V 0x1 +#define SLC_SLC1_TX_DONE_INT_RAW_S 14 +/* SLC_SLC1_TOKEN1_1TO0_INT_RAW : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_1TO0_INT_RAW (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_RAW_M (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_RAW_V 0x1 +#define SLC_SLC1_TOKEN1_1TO0_INT_RAW_S 13 +/* SLC_SLC1_TOKEN0_1TO0_INT_RAW : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_1TO0_INT_RAW (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_RAW_M (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_RAW_V 0x1 +#define SLC_SLC1_TOKEN0_1TO0_INT_RAW_S 12 +/* SLC_SLC1_TX_OVF_INT_RAW : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_OVF_INT_RAW (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_RAW_M (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_RAW_V 0x1 +#define SLC_SLC1_TX_OVF_INT_RAW_S 11 +/* SLC_SLC1_RX_UDF_INT_RAW : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_UDF_INT_RAW (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_RAW_M (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_RAW_V 0x1 +#define SLC_SLC1_RX_UDF_INT_RAW_S 10 +/* SLC_SLC1_TX_START_INT_RAW : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_START_INT_RAW (BIT(9)) +#define SLC_SLC1_TX_START_INT_RAW_M (BIT(9)) +#define SLC_SLC1_TX_START_INT_RAW_V 0x1 +#define SLC_SLC1_TX_START_INT_RAW_S 9 +/* SLC_SLC1_RX_START_INT_RAW : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_START_INT_RAW (BIT(8)) +#define SLC_SLC1_RX_START_INT_RAW_M (BIT(8)) +#define SLC_SLC1_RX_START_INT_RAW_V 0x1 +#define SLC_SLC1_RX_START_INT_RAW_S 8 +/* SLC_FRHOST_BIT15_INT_RAW : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT15_INT_RAW (BIT(7)) +#define SLC_FRHOST_BIT15_INT_RAW_M (BIT(7)) +#define SLC_FRHOST_BIT15_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT15_INT_RAW_S 7 +/* SLC_FRHOST_BIT14_INT_RAW : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT14_INT_RAW (BIT(6)) +#define SLC_FRHOST_BIT14_INT_RAW_M (BIT(6)) +#define SLC_FRHOST_BIT14_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT14_INT_RAW_S 6 +/* SLC_FRHOST_BIT13_INT_RAW : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT13_INT_RAW (BIT(5)) +#define SLC_FRHOST_BIT13_INT_RAW_M (BIT(5)) +#define SLC_FRHOST_BIT13_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT13_INT_RAW_S 5 +/* SLC_FRHOST_BIT12_INT_RAW : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT12_INT_RAW (BIT(4)) +#define SLC_FRHOST_BIT12_INT_RAW_M (BIT(4)) +#define SLC_FRHOST_BIT12_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT12_INT_RAW_S 4 +/* SLC_FRHOST_BIT11_INT_RAW : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT11_INT_RAW (BIT(3)) +#define SLC_FRHOST_BIT11_INT_RAW_M (BIT(3)) +#define SLC_FRHOST_BIT11_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT11_INT_RAW_S 3 +/* SLC_FRHOST_BIT10_INT_RAW : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT10_INT_RAW (BIT(2)) +#define SLC_FRHOST_BIT10_INT_RAW_M (BIT(2)) +#define SLC_FRHOST_BIT10_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT10_INT_RAW_S 2 +/* SLC_FRHOST_BIT9_INT_RAW : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT9_INT_RAW (BIT(1)) +#define SLC_FRHOST_BIT9_INT_RAW_M (BIT(1)) +#define SLC_FRHOST_BIT9_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT9_INT_RAW_S 1 +/* SLC_FRHOST_BIT8_INT_RAW : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT8_INT_RAW (BIT(0)) +#define SLC_FRHOST_BIT8_INT_RAW_M (BIT(0)) +#define SLC_FRHOST_BIT8_INT_RAW_V 0x1 +#define SLC_FRHOST_BIT8_INT_RAW_S 0 + +#define SLC_1INT_ST_REG (DR_REG_SLC_BASE + 0x18) +/* SLC_SLC1_TX_ERR_EOF_INT_ST : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_ERR_EOF_INT_ST (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_ST_M (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_ST_V 0x1 +#define SLC_SLC1_TX_ERR_EOF_INT_ST_S 24 +/* SLC_SLC1_WR_RETRY_DONE_INT_ST : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_WR_RETRY_DONE_INT_ST (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_ST_M (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_ST_V 0x1 +#define SLC_SLC1_WR_RETRY_DONE_INT_ST_S 23 +/* SLC_SLC1_HOST_RD_ACK_INT_ST : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_HOST_RD_ACK_INT_ST (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_ST_M (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_ST_V 0x1 +#define SLC_SLC1_HOST_RD_ACK_INT_ST_S 22 +/* SLC_SLC1_TX_DSCR_EMPTY_INT_ST : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ST (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ST_M (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ST_V 0x1 +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ST_S 21 +/* SLC_SLC1_RX_DSCR_ERR_INT_ST : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DSCR_ERR_INT_ST (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_ST_M (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_ST_V 0x1 +#define SLC_SLC1_RX_DSCR_ERR_INT_ST_S 20 +/* SLC_SLC1_TX_DSCR_ERR_INT_ST : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_ERR_INT_ST (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_ST_M (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_ST_V 0x1 +#define SLC_SLC1_TX_DSCR_ERR_INT_ST_S 19 +/* SLC_SLC1_TOHOST_INT_ST : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOHOST_INT_ST (BIT(18)) +#define SLC_SLC1_TOHOST_INT_ST_M (BIT(18)) +#define SLC_SLC1_TOHOST_INT_ST_V 0x1 +#define SLC_SLC1_TOHOST_INT_ST_S 18 +/* SLC_SLC1_RX_EOF_INT_ST : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_EOF_INT_ST (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_ST_M (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_ST_V 0x1 +#define SLC_SLC1_RX_EOF_INT_ST_S 17 +/* SLC_SLC1_RX_DONE_INT_ST : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DONE_INT_ST (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_ST_M (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_ST_V 0x1 +#define SLC_SLC1_RX_DONE_INT_ST_S 16 +/* SLC_SLC1_TX_SUC_EOF_INT_ST : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_SUC_EOF_INT_ST (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_ST_M (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_ST_V 0x1 +#define SLC_SLC1_TX_SUC_EOF_INT_ST_S 15 +/* SLC_SLC1_TX_DONE_INT_ST : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DONE_INT_ST (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_ST_M (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_ST_V 0x1 +#define SLC_SLC1_TX_DONE_INT_ST_S 14 +/* SLC_SLC1_TOKEN1_1TO0_INT_ST : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_1TO0_INT_ST (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_ST_M (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_ST_V 0x1 +#define SLC_SLC1_TOKEN1_1TO0_INT_ST_S 13 +/* SLC_SLC1_TOKEN0_1TO0_INT_ST : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_1TO0_INT_ST (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_ST_M (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_ST_V 0x1 +#define SLC_SLC1_TOKEN0_1TO0_INT_ST_S 12 +/* SLC_SLC1_TX_OVF_INT_ST : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_OVF_INT_ST (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_ST_M (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_ST_V 0x1 +#define SLC_SLC1_TX_OVF_INT_ST_S 11 +/* SLC_SLC1_RX_UDF_INT_ST : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_UDF_INT_ST (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_ST_M (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_ST_V 0x1 +#define SLC_SLC1_RX_UDF_INT_ST_S 10 +/* SLC_SLC1_TX_START_INT_ST : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_START_INT_ST (BIT(9)) +#define SLC_SLC1_TX_START_INT_ST_M (BIT(9)) +#define SLC_SLC1_TX_START_INT_ST_V 0x1 +#define SLC_SLC1_TX_START_INT_ST_S 9 +/* SLC_SLC1_RX_START_INT_ST : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_START_INT_ST (BIT(8)) +#define SLC_SLC1_RX_START_INT_ST_M (BIT(8)) +#define SLC_SLC1_RX_START_INT_ST_V 0x1 +#define SLC_SLC1_RX_START_INT_ST_S 8 +/* SLC_FRHOST_BIT15_INT_ST : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT15_INT_ST (BIT(7)) +#define SLC_FRHOST_BIT15_INT_ST_M (BIT(7)) +#define SLC_FRHOST_BIT15_INT_ST_V 0x1 +#define SLC_FRHOST_BIT15_INT_ST_S 7 +/* SLC_FRHOST_BIT14_INT_ST : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT14_INT_ST (BIT(6)) +#define SLC_FRHOST_BIT14_INT_ST_M (BIT(6)) +#define SLC_FRHOST_BIT14_INT_ST_V 0x1 +#define SLC_FRHOST_BIT14_INT_ST_S 6 +/* SLC_FRHOST_BIT13_INT_ST : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT13_INT_ST (BIT(5)) +#define SLC_FRHOST_BIT13_INT_ST_M (BIT(5)) +#define SLC_FRHOST_BIT13_INT_ST_V 0x1 +#define SLC_FRHOST_BIT13_INT_ST_S 5 +/* SLC_FRHOST_BIT12_INT_ST : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT12_INT_ST (BIT(4)) +#define SLC_FRHOST_BIT12_INT_ST_M (BIT(4)) +#define SLC_FRHOST_BIT12_INT_ST_V 0x1 +#define SLC_FRHOST_BIT12_INT_ST_S 4 +/* SLC_FRHOST_BIT11_INT_ST : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT11_INT_ST (BIT(3)) +#define SLC_FRHOST_BIT11_INT_ST_M (BIT(3)) +#define SLC_FRHOST_BIT11_INT_ST_V 0x1 +#define SLC_FRHOST_BIT11_INT_ST_S 3 +/* SLC_FRHOST_BIT10_INT_ST : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT10_INT_ST (BIT(2)) +#define SLC_FRHOST_BIT10_INT_ST_M (BIT(2)) +#define SLC_FRHOST_BIT10_INT_ST_V 0x1 +#define SLC_FRHOST_BIT10_INT_ST_S 2 +/* SLC_FRHOST_BIT9_INT_ST : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT9_INT_ST (BIT(1)) +#define SLC_FRHOST_BIT9_INT_ST_M (BIT(1)) +#define SLC_FRHOST_BIT9_INT_ST_V 0x1 +#define SLC_FRHOST_BIT9_INT_ST_S 1 +/* SLC_FRHOST_BIT8_INT_ST : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT8_INT_ST (BIT(0)) +#define SLC_FRHOST_BIT8_INT_ST_M (BIT(0)) +#define SLC_FRHOST_BIT8_INT_ST_V 0x1 +#define SLC_FRHOST_BIT8_INT_ST_S 0 + +#define SLC_1INT_ENA_REG (DR_REG_SLC_BASE + 0x1C) +/* SLC_SLC1_TX_ERR_EOF_INT_ENA : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_ERR_EOF_INT_ENA (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_ENA_M (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_ENA_V 0x1 +#define SLC_SLC1_TX_ERR_EOF_INT_ENA_S 24 +/* SLC_SLC1_WR_RETRY_DONE_INT_ENA : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_WR_RETRY_DONE_INT_ENA (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_ENA_M (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_ENA_V 0x1 +#define SLC_SLC1_WR_RETRY_DONE_INT_ENA_S 23 +/* SLC_SLC1_HOST_RD_ACK_INT_ENA : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_HOST_RD_ACK_INT_ENA (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_ENA_M (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_ENA_V 0x1 +#define SLC_SLC1_HOST_RD_ACK_INT_ENA_S 22 +/* SLC_SLC1_TX_DSCR_EMPTY_INT_ENA : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ENA (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ENA_M (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ENA_V 0x1 +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ENA_S 21 +/* SLC_SLC1_RX_DSCR_ERR_INT_ENA : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DSCR_ERR_INT_ENA (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_ENA_M (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_ENA_V 0x1 +#define SLC_SLC1_RX_DSCR_ERR_INT_ENA_S 20 +/* SLC_SLC1_TX_DSCR_ERR_INT_ENA : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_ERR_INT_ENA (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_ENA_M (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_ENA_V 0x1 +#define SLC_SLC1_TX_DSCR_ERR_INT_ENA_S 19 +/* SLC_SLC1_TOHOST_INT_ENA : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOHOST_INT_ENA (BIT(18)) +#define SLC_SLC1_TOHOST_INT_ENA_M (BIT(18)) +#define SLC_SLC1_TOHOST_INT_ENA_V 0x1 +#define SLC_SLC1_TOHOST_INT_ENA_S 18 +/* SLC_SLC1_RX_EOF_INT_ENA : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_EOF_INT_ENA (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_ENA_M (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_ENA_V 0x1 +#define SLC_SLC1_RX_EOF_INT_ENA_S 17 +/* SLC_SLC1_RX_DONE_INT_ENA : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DONE_INT_ENA (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_ENA_M (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_ENA_V 0x1 +#define SLC_SLC1_RX_DONE_INT_ENA_S 16 +/* SLC_SLC1_TX_SUC_EOF_INT_ENA : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_SUC_EOF_INT_ENA (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_ENA_M (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_ENA_V 0x1 +#define SLC_SLC1_TX_SUC_EOF_INT_ENA_S 15 +/* SLC_SLC1_TX_DONE_INT_ENA : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DONE_INT_ENA (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_ENA_M (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_ENA_V 0x1 +#define SLC_SLC1_TX_DONE_INT_ENA_S 14 +/* SLC_SLC1_TOKEN1_1TO0_INT_ENA : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_1TO0_INT_ENA (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_ENA_M (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_ENA_V 0x1 +#define SLC_SLC1_TOKEN1_1TO0_INT_ENA_S 13 +/* SLC_SLC1_TOKEN0_1TO0_INT_ENA : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_1TO0_INT_ENA (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_ENA_M (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_ENA_V 0x1 +#define SLC_SLC1_TOKEN0_1TO0_INT_ENA_S 12 +/* SLC_SLC1_TX_OVF_INT_ENA : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_OVF_INT_ENA (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_ENA_M (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_ENA_V 0x1 +#define SLC_SLC1_TX_OVF_INT_ENA_S 11 +/* SLC_SLC1_RX_UDF_INT_ENA : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_UDF_INT_ENA (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_ENA_M (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_ENA_V 0x1 +#define SLC_SLC1_RX_UDF_INT_ENA_S 10 +/* SLC_SLC1_TX_START_INT_ENA : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_START_INT_ENA (BIT(9)) +#define SLC_SLC1_TX_START_INT_ENA_M (BIT(9)) +#define SLC_SLC1_TX_START_INT_ENA_V 0x1 +#define SLC_SLC1_TX_START_INT_ENA_S 9 +/* SLC_SLC1_RX_START_INT_ENA : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_START_INT_ENA (BIT(8)) +#define SLC_SLC1_RX_START_INT_ENA_M (BIT(8)) +#define SLC_SLC1_RX_START_INT_ENA_V 0x1 +#define SLC_SLC1_RX_START_INT_ENA_S 8 +/* SLC_FRHOST_BIT15_INT_ENA : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT15_INT_ENA (BIT(7)) +#define SLC_FRHOST_BIT15_INT_ENA_M (BIT(7)) +#define SLC_FRHOST_BIT15_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT15_INT_ENA_S 7 +/* SLC_FRHOST_BIT14_INT_ENA : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT14_INT_ENA (BIT(6)) +#define SLC_FRHOST_BIT14_INT_ENA_M (BIT(6)) +#define SLC_FRHOST_BIT14_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT14_INT_ENA_S 6 +/* SLC_FRHOST_BIT13_INT_ENA : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT13_INT_ENA (BIT(5)) +#define SLC_FRHOST_BIT13_INT_ENA_M (BIT(5)) +#define SLC_FRHOST_BIT13_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT13_INT_ENA_S 5 +/* SLC_FRHOST_BIT12_INT_ENA : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT12_INT_ENA (BIT(4)) +#define SLC_FRHOST_BIT12_INT_ENA_M (BIT(4)) +#define SLC_FRHOST_BIT12_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT12_INT_ENA_S 4 +/* SLC_FRHOST_BIT11_INT_ENA : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT11_INT_ENA (BIT(3)) +#define SLC_FRHOST_BIT11_INT_ENA_M (BIT(3)) +#define SLC_FRHOST_BIT11_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT11_INT_ENA_S 3 +/* SLC_FRHOST_BIT10_INT_ENA : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT10_INT_ENA (BIT(2)) +#define SLC_FRHOST_BIT10_INT_ENA_M (BIT(2)) +#define SLC_FRHOST_BIT10_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT10_INT_ENA_S 2 +/* SLC_FRHOST_BIT9_INT_ENA : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT9_INT_ENA (BIT(1)) +#define SLC_FRHOST_BIT9_INT_ENA_M (BIT(1)) +#define SLC_FRHOST_BIT9_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT9_INT_ENA_S 1 +/* SLC_FRHOST_BIT8_INT_ENA : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT8_INT_ENA (BIT(0)) +#define SLC_FRHOST_BIT8_INT_ENA_M (BIT(0)) +#define SLC_FRHOST_BIT8_INT_ENA_V 0x1 +#define SLC_FRHOST_BIT8_INT_ENA_S 0 + +#define SLC_1INT_CLR_REG (DR_REG_SLC_BASE + 0x20) +/* SLC_SLC1_TX_ERR_EOF_INT_CLR : WO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_ERR_EOF_INT_CLR (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_CLR_M (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_CLR_V 0x1 +#define SLC_SLC1_TX_ERR_EOF_INT_CLR_S 24 +/* SLC_SLC1_WR_RETRY_DONE_INT_CLR : WO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_WR_RETRY_DONE_INT_CLR (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_CLR_M (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_CLR_V 0x1 +#define SLC_SLC1_WR_RETRY_DONE_INT_CLR_S 23 +/* SLC_SLC1_HOST_RD_ACK_INT_CLR : WO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_HOST_RD_ACK_INT_CLR (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_CLR_M (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_CLR_V 0x1 +#define SLC_SLC1_HOST_RD_ACK_INT_CLR_S 22 +/* SLC_SLC1_TX_DSCR_EMPTY_INT_CLR : WO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_EMPTY_INT_CLR (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_CLR_M (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_CLR_V 0x1 +#define SLC_SLC1_TX_DSCR_EMPTY_INT_CLR_S 21 +/* SLC_SLC1_RX_DSCR_ERR_INT_CLR : WO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DSCR_ERR_INT_CLR (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_CLR_M (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_CLR_V 0x1 +#define SLC_SLC1_RX_DSCR_ERR_INT_CLR_S 20 +/* SLC_SLC1_TX_DSCR_ERR_INT_CLR : WO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_ERR_INT_CLR (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_CLR_M (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_CLR_V 0x1 +#define SLC_SLC1_TX_DSCR_ERR_INT_CLR_S 19 +/* SLC_SLC1_TOHOST_INT_CLR : WO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOHOST_INT_CLR (BIT(18)) +#define SLC_SLC1_TOHOST_INT_CLR_M (BIT(18)) +#define SLC_SLC1_TOHOST_INT_CLR_V 0x1 +#define SLC_SLC1_TOHOST_INT_CLR_S 18 +/* SLC_SLC1_RX_EOF_INT_CLR : WO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_EOF_INT_CLR (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_CLR_M (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_CLR_V 0x1 +#define SLC_SLC1_RX_EOF_INT_CLR_S 17 +/* SLC_SLC1_RX_DONE_INT_CLR : WO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DONE_INT_CLR (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_CLR_M (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_CLR_V 0x1 +#define SLC_SLC1_RX_DONE_INT_CLR_S 16 +/* SLC_SLC1_TX_SUC_EOF_INT_CLR : WO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_SUC_EOF_INT_CLR (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_CLR_M (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_CLR_V 0x1 +#define SLC_SLC1_TX_SUC_EOF_INT_CLR_S 15 +/* SLC_SLC1_TX_DONE_INT_CLR : WO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DONE_INT_CLR (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_CLR_M (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_CLR_V 0x1 +#define SLC_SLC1_TX_DONE_INT_CLR_S 14 +/* SLC_SLC1_TOKEN1_1TO0_INT_CLR : WO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_1TO0_INT_CLR (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_CLR_M (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_CLR_V 0x1 +#define SLC_SLC1_TOKEN1_1TO0_INT_CLR_S 13 +/* SLC_SLC1_TOKEN0_1TO0_INT_CLR : WO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_1TO0_INT_CLR (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_CLR_M (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_CLR_V 0x1 +#define SLC_SLC1_TOKEN0_1TO0_INT_CLR_S 12 +/* SLC_SLC1_TX_OVF_INT_CLR : WO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_OVF_INT_CLR (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_CLR_M (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_CLR_V 0x1 +#define SLC_SLC1_TX_OVF_INT_CLR_S 11 +/* SLC_SLC1_RX_UDF_INT_CLR : WO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_UDF_INT_CLR (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_CLR_M (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_CLR_V 0x1 +#define SLC_SLC1_RX_UDF_INT_CLR_S 10 +/* SLC_SLC1_TX_START_INT_CLR : WO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_START_INT_CLR (BIT(9)) +#define SLC_SLC1_TX_START_INT_CLR_M (BIT(9)) +#define SLC_SLC1_TX_START_INT_CLR_V 0x1 +#define SLC_SLC1_TX_START_INT_CLR_S 9 +/* SLC_SLC1_RX_START_INT_CLR : WO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_START_INT_CLR (BIT(8)) +#define SLC_SLC1_RX_START_INT_CLR_M (BIT(8)) +#define SLC_SLC1_RX_START_INT_CLR_V 0x1 +#define SLC_SLC1_RX_START_INT_CLR_S 8 +/* SLC_FRHOST_BIT15_INT_CLR : WO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT15_INT_CLR (BIT(7)) +#define SLC_FRHOST_BIT15_INT_CLR_M (BIT(7)) +#define SLC_FRHOST_BIT15_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT15_INT_CLR_S 7 +/* SLC_FRHOST_BIT14_INT_CLR : WO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT14_INT_CLR (BIT(6)) +#define SLC_FRHOST_BIT14_INT_CLR_M (BIT(6)) +#define SLC_FRHOST_BIT14_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT14_INT_CLR_S 6 +/* SLC_FRHOST_BIT13_INT_CLR : WO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT13_INT_CLR (BIT(5)) +#define SLC_FRHOST_BIT13_INT_CLR_M (BIT(5)) +#define SLC_FRHOST_BIT13_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT13_INT_CLR_S 5 +/* SLC_FRHOST_BIT12_INT_CLR : WO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT12_INT_CLR (BIT(4)) +#define SLC_FRHOST_BIT12_INT_CLR_M (BIT(4)) +#define SLC_FRHOST_BIT12_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT12_INT_CLR_S 4 +/* SLC_FRHOST_BIT11_INT_CLR : WO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT11_INT_CLR (BIT(3)) +#define SLC_FRHOST_BIT11_INT_CLR_M (BIT(3)) +#define SLC_FRHOST_BIT11_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT11_INT_CLR_S 3 +/* SLC_FRHOST_BIT10_INT_CLR : WO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT10_INT_CLR (BIT(2)) +#define SLC_FRHOST_BIT10_INT_CLR_M (BIT(2)) +#define SLC_FRHOST_BIT10_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT10_INT_CLR_S 2 +/* SLC_FRHOST_BIT9_INT_CLR : WO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT9_INT_CLR (BIT(1)) +#define SLC_FRHOST_BIT9_INT_CLR_M (BIT(1)) +#define SLC_FRHOST_BIT9_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT9_INT_CLR_S 1 +/* SLC_FRHOST_BIT8_INT_CLR : WO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT8_INT_CLR (BIT(0)) +#define SLC_FRHOST_BIT8_INT_CLR_M (BIT(0)) +#define SLC_FRHOST_BIT8_INT_CLR_V 0x1 +#define SLC_FRHOST_BIT8_INT_CLR_S 0 + +#define SLC_RX_STATUS_REG (DR_REG_SLC_BASE + 0x24) +/* SLC_SLC1_RX_EMPTY : RO ;bitpos:[17] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_RX_EMPTY (BIT(17)) +#define SLC_SLC1_RX_EMPTY_M (BIT(17)) +#define SLC_SLC1_RX_EMPTY_V 0x1 +#define SLC_SLC1_RX_EMPTY_S 17 +/* SLC_SLC1_RX_FULL : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_FULL (BIT(16)) +#define SLC_SLC1_RX_FULL_M (BIT(16)) +#define SLC_SLC1_RX_FULL_V 0x1 +#define SLC_SLC1_RX_FULL_S 16 +/* SLC_SLC0_RX_EMPTY : RO ;bitpos:[1] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_RX_EMPTY (BIT(1)) +#define SLC_SLC0_RX_EMPTY_M (BIT(1)) +#define SLC_SLC0_RX_EMPTY_V 0x1 +#define SLC_SLC0_RX_EMPTY_S 1 +/* SLC_SLC0_RX_FULL : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_FULL (BIT(0)) +#define SLC_SLC0_RX_FULL_M (BIT(0)) +#define SLC_SLC0_RX_FULL_V 0x1 +#define SLC_SLC0_RX_FULL_S 0 + +#define SLC_0RXFIFO_PUSH_REG (DR_REG_SLC_BASE + 0x28) +/* SLC_SLC0_RXFIFO_PUSH : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC0_RXFIFO_PUSH (BIT(16)) +#define SLC_SLC0_RXFIFO_PUSH_M (BIT(16)) +#define SLC_SLC0_RXFIFO_PUSH_V 0x1 +#define SLC_SLC0_RXFIFO_PUSH_S 16 +/* SLC_SLC0_RXFIFO_WDATA : R/W ;bitpos:[8:0] ;default: 9'h0 ; */ +/*description: */ +#define SLC_SLC0_RXFIFO_WDATA 0x000001FF +#define SLC_SLC0_RXFIFO_WDATA_M ((SLC_SLC0_RXFIFO_WDATA_V)<<(SLC_SLC0_RXFIFO_WDATA_S)) +#define SLC_SLC0_RXFIFO_WDATA_V 0x1FF +#define SLC_SLC0_RXFIFO_WDATA_S 0 + +#define SLC_1RXFIFO_PUSH_REG (DR_REG_SLC_BASE + 0x2C) +/* SLC_SLC1_RXFIFO_PUSH : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC1_RXFIFO_PUSH (BIT(16)) +#define SLC_SLC1_RXFIFO_PUSH_M (BIT(16)) +#define SLC_SLC1_RXFIFO_PUSH_V 0x1 +#define SLC_SLC1_RXFIFO_PUSH_S 16 +/* SLC_SLC1_RXFIFO_WDATA : R/W ;bitpos:[8:0] ;default: 9'h0 ; */ +/*description: */ +#define SLC_SLC1_RXFIFO_WDATA 0x000001FF +#define SLC_SLC1_RXFIFO_WDATA_M ((SLC_SLC1_RXFIFO_WDATA_V)<<(SLC_SLC1_RXFIFO_WDATA_S)) +#define SLC_SLC1_RXFIFO_WDATA_V 0x1FF +#define SLC_SLC1_RXFIFO_WDATA_S 0 + +#define SLC_TX_STATUS_REG (DR_REG_SLC_BASE + 0x30) +/* SLC_SLC1_TX_EMPTY : RO ;bitpos:[17] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_TX_EMPTY (BIT(17)) +#define SLC_SLC1_TX_EMPTY_M (BIT(17)) +#define SLC_SLC1_TX_EMPTY_V 0x1 +#define SLC_SLC1_TX_EMPTY_S 17 +/* SLC_SLC1_TX_FULL : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_FULL (BIT(16)) +#define SLC_SLC1_TX_FULL_M (BIT(16)) +#define SLC_SLC1_TX_FULL_V 0x1 +#define SLC_SLC1_TX_FULL_S 16 +/* SLC_SLC0_TX_EMPTY : RO ;bitpos:[1] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_TX_EMPTY (BIT(1)) +#define SLC_SLC0_TX_EMPTY_M (BIT(1)) +#define SLC_SLC0_TX_EMPTY_V 0x1 +#define SLC_SLC0_TX_EMPTY_S 1 +/* SLC_SLC0_TX_FULL : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_FULL (BIT(0)) +#define SLC_SLC0_TX_FULL_M (BIT(0)) +#define SLC_SLC0_TX_FULL_V 0x1 +#define SLC_SLC0_TX_FULL_S 0 + +#define SLC_0TXFIFO_POP_REG (DR_REG_SLC_BASE + 0x34) +/* SLC_SLC0_TXFIFO_POP : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC0_TXFIFO_POP (BIT(16)) +#define SLC_SLC0_TXFIFO_POP_M (BIT(16)) +#define SLC_SLC0_TXFIFO_POP_V 0x1 +#define SLC_SLC0_TXFIFO_POP_S 16 +/* SLC_SLC0_TXFIFO_RDATA : RO ;bitpos:[10:0] ;default: 11'h0 ; */ +/*description: */ +#define SLC_SLC0_TXFIFO_RDATA 0x000007FF +#define SLC_SLC0_TXFIFO_RDATA_M ((SLC_SLC0_TXFIFO_RDATA_V)<<(SLC_SLC0_TXFIFO_RDATA_S)) +#define SLC_SLC0_TXFIFO_RDATA_V 0x7FF +#define SLC_SLC0_TXFIFO_RDATA_S 0 + +#define SLC_1TXFIFO_POP_REG (DR_REG_SLC_BASE + 0x38) +/* SLC_SLC1_TXFIFO_POP : R/W ;bitpos:[16] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC1_TXFIFO_POP (BIT(16)) +#define SLC_SLC1_TXFIFO_POP_M (BIT(16)) +#define SLC_SLC1_TXFIFO_POP_V 0x1 +#define SLC_SLC1_TXFIFO_POP_S 16 +/* SLC_SLC1_TXFIFO_RDATA : RO ;bitpos:[10:0] ;default: 11'h0 ; */ +/*description: */ +#define SLC_SLC1_TXFIFO_RDATA 0x000007FF +#define SLC_SLC1_TXFIFO_RDATA_M ((SLC_SLC1_TXFIFO_RDATA_V)<<(SLC_SLC1_TXFIFO_RDATA_S)) +#define SLC_SLC1_TXFIFO_RDATA_V 0x7FF +#define SLC_SLC1_TXFIFO_RDATA_S 0 + +#define SLC_0RX_LINK_REG (DR_REG_SLC_BASE + 0x3C) +/* SLC_SLC0_RXLINK_PARK : RO ;bitpos:[31] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_PARK (BIT(31)) +#define SLC_SLC0_RXLINK_PARK_M (BIT(31)) +#define SLC_SLC0_RXLINK_PARK_V 0x1 +#define SLC_SLC0_RXLINK_PARK_S 31 +/* SLC_SLC0_RXLINK_RESTART : R/W ;bitpos:[30] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_RESTART (BIT(30)) +#define SLC_SLC0_RXLINK_RESTART_M (BIT(30)) +#define SLC_SLC0_RXLINK_RESTART_V 0x1 +#define SLC_SLC0_RXLINK_RESTART_S 30 +/* SLC_SLC0_RXLINK_START : R/W ;bitpos:[29] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_START (BIT(29)) +#define SLC_SLC0_RXLINK_START_M (BIT(29)) +#define SLC_SLC0_RXLINK_START_V 0x1 +#define SLC_SLC0_RXLINK_START_S 29 +/* SLC_SLC0_RXLINK_STOP : R/W ;bitpos:[28] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_STOP (BIT(28)) +#define SLC_SLC0_RXLINK_STOP_M (BIT(28)) +#define SLC_SLC0_RXLINK_STOP_V 0x1 +#define SLC_SLC0_RXLINK_STOP_S 28 +/* SLC_SLC0_RXLINK_ADDR : R/W ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_ADDR 0x000FFFFF +#define SLC_SLC0_RXLINK_ADDR_M ((SLC_SLC0_RXLINK_ADDR_V)<<(SLC_SLC0_RXLINK_ADDR_S)) +#define SLC_SLC0_RXLINK_ADDR_V 0xFFFFF +#define SLC_SLC0_RXLINK_ADDR_S 0 + +#define SLC_0TX_LINK_REG (DR_REG_SLC_BASE + 0x40) +/* SLC_SLC0_TXLINK_PARK : RO ;bitpos:[31] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_PARK (BIT(31)) +#define SLC_SLC0_TXLINK_PARK_M (BIT(31)) +#define SLC_SLC0_TXLINK_PARK_V 0x1 +#define SLC_SLC0_TXLINK_PARK_S 31 +/* SLC_SLC0_TXLINK_RESTART : R/W ;bitpos:[30] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_RESTART (BIT(30)) +#define SLC_SLC0_TXLINK_RESTART_M (BIT(30)) +#define SLC_SLC0_TXLINK_RESTART_V 0x1 +#define SLC_SLC0_TXLINK_RESTART_S 30 +/* SLC_SLC0_TXLINK_START : R/W ;bitpos:[29] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_START (BIT(29)) +#define SLC_SLC0_TXLINK_START_M (BIT(29)) +#define SLC_SLC0_TXLINK_START_V 0x1 +#define SLC_SLC0_TXLINK_START_S 29 +/* SLC_SLC0_TXLINK_STOP : R/W ;bitpos:[28] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_STOP (BIT(28)) +#define SLC_SLC0_TXLINK_STOP_M (BIT(28)) +#define SLC_SLC0_TXLINK_STOP_V 0x1 +#define SLC_SLC0_TXLINK_STOP_S 28 +/* SLC_SLC0_TXLINK_ADDR : R/W ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_ADDR 0x000FFFFF +#define SLC_SLC0_TXLINK_ADDR_M ((SLC_SLC0_TXLINK_ADDR_V)<<(SLC_SLC0_TXLINK_ADDR_S)) +#define SLC_SLC0_TXLINK_ADDR_V 0xFFFFF +#define SLC_SLC0_TXLINK_ADDR_S 0 + +#define SLC_1RX_LINK_REG (DR_REG_SLC_BASE + 0x44) +/* SLC_SLC1_RXLINK_PARK : RO ;bitpos:[31] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_PARK (BIT(31)) +#define SLC_SLC1_RXLINK_PARK_M (BIT(31)) +#define SLC_SLC1_RXLINK_PARK_V 0x1 +#define SLC_SLC1_RXLINK_PARK_S 31 +/* SLC_SLC1_RXLINK_RESTART : R/W ;bitpos:[30] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_RESTART (BIT(30)) +#define SLC_SLC1_RXLINK_RESTART_M (BIT(30)) +#define SLC_SLC1_RXLINK_RESTART_V 0x1 +#define SLC_SLC1_RXLINK_RESTART_S 30 +/* SLC_SLC1_RXLINK_START : R/W ;bitpos:[29] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_START (BIT(29)) +#define SLC_SLC1_RXLINK_START_M (BIT(29)) +#define SLC_SLC1_RXLINK_START_V 0x1 +#define SLC_SLC1_RXLINK_START_S 29 +/* SLC_SLC1_RXLINK_STOP : R/W ;bitpos:[28] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_STOP (BIT(28)) +#define SLC_SLC1_RXLINK_STOP_M (BIT(28)) +#define SLC_SLC1_RXLINK_STOP_V 0x1 +#define SLC_SLC1_RXLINK_STOP_S 28 +/* SLC_SLC1_BT_PACKET : R/W ;bitpos:[20] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_BT_PACKET (BIT(20)) +#define SLC_SLC1_BT_PACKET_M (BIT(20)) +#define SLC_SLC1_BT_PACKET_V 0x1 +#define SLC_SLC1_BT_PACKET_S 20 +/* SLC_SLC1_RXLINK_ADDR : R/W ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_ADDR 0x000FFFFF +#define SLC_SLC1_RXLINK_ADDR_M ((SLC_SLC1_RXLINK_ADDR_V)<<(SLC_SLC1_RXLINK_ADDR_S)) +#define SLC_SLC1_RXLINK_ADDR_V 0xFFFFF +#define SLC_SLC1_RXLINK_ADDR_S 0 + +#define SLC_1TX_LINK_REG (DR_REG_SLC_BASE + 0x48) +/* SLC_SLC1_TXLINK_PARK : RO ;bitpos:[31] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_PARK (BIT(31)) +#define SLC_SLC1_TXLINK_PARK_M (BIT(31)) +#define SLC_SLC1_TXLINK_PARK_V 0x1 +#define SLC_SLC1_TXLINK_PARK_S 31 +/* SLC_SLC1_TXLINK_RESTART : R/W ;bitpos:[30] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_RESTART (BIT(30)) +#define SLC_SLC1_TXLINK_RESTART_M (BIT(30)) +#define SLC_SLC1_TXLINK_RESTART_V 0x1 +#define SLC_SLC1_TXLINK_RESTART_S 30 +/* SLC_SLC1_TXLINK_START : R/W ;bitpos:[29] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_START (BIT(29)) +#define SLC_SLC1_TXLINK_START_M (BIT(29)) +#define SLC_SLC1_TXLINK_START_V 0x1 +#define SLC_SLC1_TXLINK_START_S 29 +/* SLC_SLC1_TXLINK_STOP : R/W ;bitpos:[28] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_STOP (BIT(28)) +#define SLC_SLC1_TXLINK_STOP_M (BIT(28)) +#define SLC_SLC1_TXLINK_STOP_V 0x1 +#define SLC_SLC1_TXLINK_STOP_S 28 +/* SLC_SLC1_TXLINK_ADDR : R/W ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_ADDR 0x000FFFFF +#define SLC_SLC1_TXLINK_ADDR_M ((SLC_SLC1_TXLINK_ADDR_V)<<(SLC_SLC1_TXLINK_ADDR_S)) +#define SLC_SLC1_TXLINK_ADDR_V 0xFFFFF +#define SLC_SLC1_TXLINK_ADDR_S 0 + +#define SLC_INTVEC_TOHOST_REG (DR_REG_SLC_BASE + 0x4C) +/* SLC_SLC1_TOHOST_INTVEC : WO ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define SLC_SLC1_TOHOST_INTVEC 0x000000FF +#define SLC_SLC1_TOHOST_INTVEC_M ((SLC_SLC1_TOHOST_INTVEC_V)<<(SLC_SLC1_TOHOST_INTVEC_S)) +#define SLC_SLC1_TOHOST_INTVEC_V 0xFF +#define SLC_SLC1_TOHOST_INTVEC_S 16 +/* SLC_SLC0_TOHOST_INTVEC : WO ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define SLC_SLC0_TOHOST_INTVEC 0x000000FF +#define SLC_SLC0_TOHOST_INTVEC_M ((SLC_SLC0_TOHOST_INTVEC_V)<<(SLC_SLC0_TOHOST_INTVEC_S)) +#define SLC_SLC0_TOHOST_INTVEC_V 0xFF +#define SLC_SLC0_TOHOST_INTVEC_S 0 + +#define SLC_0TOKEN0_REG (DR_REG_SLC_BASE + 0x50) +/* SLC_SLC0_TOKEN0 : RO ;bitpos:[27:16] ;default: 12'h0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0 0x00000FFF +#define SLC_SLC0_TOKEN0_M ((SLC_SLC0_TOKEN0_V)<<(SLC_SLC0_TOKEN0_S)) +#define SLC_SLC0_TOKEN0_V 0xFFF +#define SLC_SLC0_TOKEN0_S 16 +/* SLC_SLC0_TOKEN0_INC_MORE : WO ;bitpos:[14] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_INC_MORE (BIT(14)) +#define SLC_SLC0_TOKEN0_INC_MORE_M (BIT(14)) +#define SLC_SLC0_TOKEN0_INC_MORE_V 0x1 +#define SLC_SLC0_TOKEN0_INC_MORE_S 14 +/* SLC_SLC0_TOKEN0_INC : WO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_INC (BIT(13)) +#define SLC_SLC0_TOKEN0_INC_M (BIT(13)) +#define SLC_SLC0_TOKEN0_INC_V 0x1 +#define SLC_SLC0_TOKEN0_INC_S 13 +/* SLC_SLC0_TOKEN0_WR : WO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_WR (BIT(12)) +#define SLC_SLC0_TOKEN0_WR_M (BIT(12)) +#define SLC_SLC0_TOKEN0_WR_V 0x1 +#define SLC_SLC0_TOKEN0_WR_S 12 +/* SLC_SLC0_TOKEN0_WDATA : WO ;bitpos:[11:0] ;default: 12'h0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_WDATA 0x00000FFF +#define SLC_SLC0_TOKEN0_WDATA_M ((SLC_SLC0_TOKEN0_WDATA_V)<<(SLC_SLC0_TOKEN0_WDATA_S)) +#define SLC_SLC0_TOKEN0_WDATA_V 0xFFF +#define SLC_SLC0_TOKEN0_WDATA_S 0 + +#define SLC_0TOKEN1_REG (DR_REG_SLC_BASE + 0x54) +/* SLC_SLC0_TOKEN1 : RO ;bitpos:[27:16] ;default: 12'h0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1 0x00000FFF +#define SLC_SLC0_TOKEN1_M ((SLC_SLC0_TOKEN1_V)<<(SLC_SLC0_TOKEN1_S)) +#define SLC_SLC0_TOKEN1_V 0xFFF +#define SLC_SLC0_TOKEN1_S 16 +/* SLC_SLC0_TOKEN1_INC_MORE : WO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_INC_MORE (BIT(14)) +#define SLC_SLC0_TOKEN1_INC_MORE_M (BIT(14)) +#define SLC_SLC0_TOKEN1_INC_MORE_V 0x1 +#define SLC_SLC0_TOKEN1_INC_MORE_S 14 +/* SLC_SLC0_TOKEN1_INC : WO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_INC (BIT(13)) +#define SLC_SLC0_TOKEN1_INC_M (BIT(13)) +#define SLC_SLC0_TOKEN1_INC_V 0x1 +#define SLC_SLC0_TOKEN1_INC_S 13 +/* SLC_SLC0_TOKEN1_WR : WO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_WR (BIT(12)) +#define SLC_SLC0_TOKEN1_WR_M (BIT(12)) +#define SLC_SLC0_TOKEN1_WR_V 0x1 +#define SLC_SLC0_TOKEN1_WR_S 12 +/* SLC_SLC0_TOKEN1_WDATA : WO ;bitpos:[11:0] ;default: 12'h0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_WDATA 0x00000FFF +#define SLC_SLC0_TOKEN1_WDATA_M ((SLC_SLC0_TOKEN1_WDATA_V)<<(SLC_SLC0_TOKEN1_WDATA_S)) +#define SLC_SLC0_TOKEN1_WDATA_V 0xFFF +#define SLC_SLC0_TOKEN1_WDATA_S 0 + +#define SLC_1TOKEN0_REG (DR_REG_SLC_BASE + 0x58) +/* SLC_SLC1_TOKEN0 : RO ;bitpos:[27:16] ;default: 12'h0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0 0x00000FFF +#define SLC_SLC1_TOKEN0_M ((SLC_SLC1_TOKEN0_V)<<(SLC_SLC1_TOKEN0_S)) +#define SLC_SLC1_TOKEN0_V 0xFFF +#define SLC_SLC1_TOKEN0_S 16 +/* SLC_SLC1_TOKEN0_INC_MORE : WO ;bitpos:[14] ;default: 1'h0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_INC_MORE (BIT(14)) +#define SLC_SLC1_TOKEN0_INC_MORE_M (BIT(14)) +#define SLC_SLC1_TOKEN0_INC_MORE_V 0x1 +#define SLC_SLC1_TOKEN0_INC_MORE_S 14 +/* SLC_SLC1_TOKEN0_INC : WO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_INC (BIT(13)) +#define SLC_SLC1_TOKEN0_INC_M (BIT(13)) +#define SLC_SLC1_TOKEN0_INC_V 0x1 +#define SLC_SLC1_TOKEN0_INC_S 13 +/* SLC_SLC1_TOKEN0_WR : WO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_WR (BIT(12)) +#define SLC_SLC1_TOKEN0_WR_M (BIT(12)) +#define SLC_SLC1_TOKEN0_WR_V 0x1 +#define SLC_SLC1_TOKEN0_WR_S 12 +/* SLC_SLC1_TOKEN0_WDATA : WO ;bitpos:[11:0] ;default: 12'h0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_WDATA 0x00000FFF +#define SLC_SLC1_TOKEN0_WDATA_M ((SLC_SLC1_TOKEN0_WDATA_V)<<(SLC_SLC1_TOKEN0_WDATA_S)) +#define SLC_SLC1_TOKEN0_WDATA_V 0xFFF +#define SLC_SLC1_TOKEN0_WDATA_S 0 + +#define SLC_1TOKEN1_REG (DR_REG_SLC_BASE + 0x5C) +/* SLC_SLC1_TOKEN1 : RO ;bitpos:[27:16] ;default: 12'h0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1 0x00000FFF +#define SLC_SLC1_TOKEN1_M ((SLC_SLC1_TOKEN1_V)<<(SLC_SLC1_TOKEN1_S)) +#define SLC_SLC1_TOKEN1_V 0xFFF +#define SLC_SLC1_TOKEN1_S 16 +/* SLC_SLC1_TOKEN1_INC_MORE : WO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_INC_MORE (BIT(14)) +#define SLC_SLC1_TOKEN1_INC_MORE_M (BIT(14)) +#define SLC_SLC1_TOKEN1_INC_MORE_V 0x1 +#define SLC_SLC1_TOKEN1_INC_MORE_S 14 +/* SLC_SLC1_TOKEN1_INC : WO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_INC (BIT(13)) +#define SLC_SLC1_TOKEN1_INC_M (BIT(13)) +#define SLC_SLC1_TOKEN1_INC_V 0x1 +#define SLC_SLC1_TOKEN1_INC_S 13 +/* SLC_SLC1_TOKEN1_WR : WO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_WR (BIT(12)) +#define SLC_SLC1_TOKEN1_WR_M (BIT(12)) +#define SLC_SLC1_TOKEN1_WR_V 0x1 +#define SLC_SLC1_TOKEN1_WR_S 12 +/* SLC_SLC1_TOKEN1_WDATA : WO ;bitpos:[11:0] ;default: 12'h0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_WDATA 0x00000FFF +#define SLC_SLC1_TOKEN1_WDATA_M ((SLC_SLC1_TOKEN1_WDATA_V)<<(SLC_SLC1_TOKEN1_WDATA_S)) +#define SLC_SLC1_TOKEN1_WDATA_V 0xFFF +#define SLC_SLC1_TOKEN1_WDATA_S 0 + +#define SLC_CONF1_REG (DR_REG_SLC_BASE + 0x60) +/* SLC_CLK_EN : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_CLK_EN (BIT(22)) +#define SLC_CLK_EN_M (BIT(22)) +#define SLC_CLK_EN_V 0x1 +#define SLC_CLK_EN_S 22 +/* SLC_SLC1_RX_STITCH_EN : R/W ;bitpos:[21] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_RX_STITCH_EN (BIT(21)) +#define SLC_SLC1_RX_STITCH_EN_M (BIT(21)) +#define SLC_SLC1_RX_STITCH_EN_V 0x1 +#define SLC_SLC1_RX_STITCH_EN_S 21 +/* SLC_SLC1_TX_STITCH_EN : R/W ;bitpos:[20] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_TX_STITCH_EN (BIT(20)) +#define SLC_SLC1_TX_STITCH_EN_M (BIT(20)) +#define SLC_SLC1_TX_STITCH_EN_V 0x1 +#define SLC_SLC1_TX_STITCH_EN_S 20 +/* SLC_HOST_INT_LEVEL_SEL : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_HOST_INT_LEVEL_SEL (BIT(19)) +#define SLC_HOST_INT_LEVEL_SEL_M (BIT(19)) +#define SLC_HOST_INT_LEVEL_SEL_V 0x1 +#define SLC_HOST_INT_LEVEL_SEL_S 19 +/* SLC_SLC1_RX_CHECK_SUM_EN : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_CHECK_SUM_EN (BIT(18)) +#define SLC_SLC1_RX_CHECK_SUM_EN_M (BIT(18)) +#define SLC_SLC1_RX_CHECK_SUM_EN_V 0x1 +#define SLC_SLC1_RX_CHECK_SUM_EN_S 18 +/* SLC_SLC1_TX_CHECK_SUM_EN : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_CHECK_SUM_EN (BIT(17)) +#define SLC_SLC1_TX_CHECK_SUM_EN_M (BIT(17)) +#define SLC_SLC1_TX_CHECK_SUM_EN_V 0x1 +#define SLC_SLC1_TX_CHECK_SUM_EN_S 17 +/* SLC_SLC1_CHECK_OWNER : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_CHECK_OWNER (BIT(16)) +#define SLC_SLC1_CHECK_OWNER_M (BIT(16)) +#define SLC_SLC1_CHECK_OWNER_V 0x1 +#define SLC_SLC1_CHECK_OWNER_S 16 +/* SLC_SLC0_RX_STITCH_EN : R/W ;bitpos:[6] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_RX_STITCH_EN (BIT(6)) +#define SLC_SLC0_RX_STITCH_EN_M (BIT(6)) +#define SLC_SLC0_RX_STITCH_EN_V 0x1 +#define SLC_SLC0_RX_STITCH_EN_S 6 +/* SLC_SLC0_TX_STITCH_EN : R/W ;bitpos:[5] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_TX_STITCH_EN (BIT(5)) +#define SLC_SLC0_TX_STITCH_EN_M (BIT(5)) +#define SLC_SLC0_TX_STITCH_EN_V 0x1 +#define SLC_SLC0_TX_STITCH_EN_S 5 +/* SLC_SLC0_LEN_AUTO_CLR : R/W ;bitpos:[4] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_LEN_AUTO_CLR (BIT(4)) +#define SLC_SLC0_LEN_AUTO_CLR_M (BIT(4)) +#define SLC_SLC0_LEN_AUTO_CLR_V 0x1 +#define SLC_SLC0_LEN_AUTO_CLR_S 4 +/* SLC_CMD_HOLD_EN : R/W ;bitpos:[3] ;default: 1'b1 ; */ +/*description: */ +#define SLC_CMD_HOLD_EN (BIT(3)) +#define SLC_CMD_HOLD_EN_M (BIT(3)) +#define SLC_CMD_HOLD_EN_V 0x1 +#define SLC_CMD_HOLD_EN_S 3 +/* SLC_SLC0_RX_CHECK_SUM_EN : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_CHECK_SUM_EN (BIT(2)) +#define SLC_SLC0_RX_CHECK_SUM_EN_M (BIT(2)) +#define SLC_SLC0_RX_CHECK_SUM_EN_V 0x1 +#define SLC_SLC0_RX_CHECK_SUM_EN_S 2 +/* SLC_SLC0_TX_CHECK_SUM_EN : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_CHECK_SUM_EN (BIT(1)) +#define SLC_SLC0_TX_CHECK_SUM_EN_M (BIT(1)) +#define SLC_SLC0_TX_CHECK_SUM_EN_V 0x1 +#define SLC_SLC0_TX_CHECK_SUM_EN_S 1 +/* SLC_SLC0_CHECK_OWNER : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_CHECK_OWNER (BIT(0)) +#define SLC_SLC0_CHECK_OWNER_M (BIT(0)) +#define SLC_SLC0_CHECK_OWNER_V 0x1 +#define SLC_SLC0_CHECK_OWNER_S 0 + +#define SLC_0_STATE0_REG (DR_REG_SLC_BASE + 0x64) +/* SLC_SLC0_STATE0 : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_STATE0 0xFFFFFFFF +#define SLC_SLC0_STATE0_M ((SLC_SLC0_STATE0_V)<<(SLC_SLC0_STATE0_S)) +#define SLC_SLC0_STATE0_V 0xFFFFFFFF +#define SLC_SLC0_STATE0_S 0 + +#define SLC_0_STATE1_REG (DR_REG_SLC_BASE + 0x68) +/* SLC_SLC0_STATE1 : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_STATE1 0xFFFFFFFF +#define SLC_SLC0_STATE1_M ((SLC_SLC0_STATE1_V)<<(SLC_SLC0_STATE1_S)) +#define SLC_SLC0_STATE1_V 0xFFFFFFFF +#define SLC_SLC0_STATE1_S 0 + +#define SLC_1_STATE0_REG (DR_REG_SLC_BASE + 0x6C) +/* SLC_SLC1_STATE0 : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC1_STATE0 0xFFFFFFFF +#define SLC_SLC1_STATE0_M ((SLC_SLC1_STATE0_V)<<(SLC_SLC1_STATE0_S)) +#define SLC_SLC1_STATE0_V 0xFFFFFFFF +#define SLC_SLC1_STATE0_S 0 + +#define SLC_1_STATE1_REG (DR_REG_SLC_BASE + 0x70) +/* SLC_SLC1_STATE1 : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC1_STATE1 0xFFFFFFFF +#define SLC_SLC1_STATE1_M ((SLC_SLC1_STATE1_V)<<(SLC_SLC1_STATE1_S)) +#define SLC_SLC1_STATE1_V 0xFFFFFFFF +#define SLC_SLC1_STATE1_S 0 + +#define SLC_BRIDGE_CONF_REG (DR_REG_SLC_BASE + 0x74) +/* SLC_TX_PUSH_IDLE_NUM : R/W ;bitpos:[31:16] ;default: 16'ha ; */ +/*description: */ +#define SLC_TX_PUSH_IDLE_NUM 0x0000FFFF +#define SLC_TX_PUSH_IDLE_NUM_M ((SLC_TX_PUSH_IDLE_NUM_V)<<(SLC_TX_PUSH_IDLE_NUM_S)) +#define SLC_TX_PUSH_IDLE_NUM_V 0xFFFF +#define SLC_TX_PUSH_IDLE_NUM_S 16 +/* SLC_SLC1_TX_DUMMY_MODE : R/W ;bitpos:[14] ;default: 1'h1 ; */ +/*description: */ +#define SLC_SLC1_TX_DUMMY_MODE (BIT(14)) +#define SLC_SLC1_TX_DUMMY_MODE_M (BIT(14)) +#define SLC_SLC1_TX_DUMMY_MODE_V 0x1 +#define SLC_SLC1_TX_DUMMY_MODE_S 14 +/* SLC_HDA_MAP_128K : R/W ;bitpos:[13] ;default: 1'h1 ; */ +/*description: */ +#define SLC_HDA_MAP_128K (BIT(13)) +#define SLC_HDA_MAP_128K_M (BIT(13)) +#define SLC_HDA_MAP_128K_V 0x1 +#define SLC_HDA_MAP_128K_S 13 +/* SLC_SLC0_TX_DUMMY_MODE : R/W ;bitpos:[12] ;default: 1'h1 ; */ +/*description: */ +#define SLC_SLC0_TX_DUMMY_MODE (BIT(12)) +#define SLC_SLC0_TX_DUMMY_MODE_M (BIT(12)) +#define SLC_SLC0_TX_DUMMY_MODE_V 0x1 +#define SLC_SLC0_TX_DUMMY_MODE_S 12 +/* SLC_FIFO_MAP_ENA : R/W ;bitpos:[11:8] ;default: 4'h7 ; */ +/*description: */ +#define SLC_FIFO_MAP_ENA 0x0000000F +#define SLC_FIFO_MAP_ENA_M ((SLC_FIFO_MAP_ENA_V)<<(SLC_FIFO_MAP_ENA_S)) +#define SLC_FIFO_MAP_ENA_V 0xF +#define SLC_FIFO_MAP_ENA_S 8 +/* SLC_TXEOF_ENA : R/W ;bitpos:[5:0] ;default: 6'h20 ; */ +/*description: */ +#define SLC_TXEOF_ENA 0x0000003F +#define SLC_TXEOF_ENA_M ((SLC_TXEOF_ENA_V)<<(SLC_TXEOF_ENA_S)) +#define SLC_TXEOF_ENA_V 0x3F +#define SLC_TXEOF_ENA_S 0 + +#define SLC_0_TO_EOF_DES_ADDR_REG (DR_REG_SLC_BASE + 0x78) +/* SLC_SLC0_TO_EOF_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_TO_EOF_DES_ADDR 0xFFFFFFFF +#define SLC_SLC0_TO_EOF_DES_ADDR_M ((SLC_SLC0_TO_EOF_DES_ADDR_V)<<(SLC_SLC0_TO_EOF_DES_ADDR_S)) +#define SLC_SLC0_TO_EOF_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_TO_EOF_DES_ADDR_S 0 + +#define SLC_0_TX_EOF_DES_ADDR_REG (DR_REG_SLC_BASE + 0x7C) +/* SLC_SLC0_TX_SUC_EOF_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_TX_SUC_EOF_DES_ADDR 0xFFFFFFFF +#define SLC_SLC0_TX_SUC_EOF_DES_ADDR_M ((SLC_SLC0_TX_SUC_EOF_DES_ADDR_V)<<(SLC_SLC0_TX_SUC_EOF_DES_ADDR_S)) +#define SLC_SLC0_TX_SUC_EOF_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_TX_SUC_EOF_DES_ADDR_S 0 + +#define SLC_0_TO_EOF_BFR_DES_ADDR_REG (DR_REG_SLC_BASE + 0x80) +/* SLC_SLC0_TO_EOF_BFR_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_TO_EOF_BFR_DES_ADDR 0xFFFFFFFF +#define SLC_SLC0_TO_EOF_BFR_DES_ADDR_M ((SLC_SLC0_TO_EOF_BFR_DES_ADDR_V)<<(SLC_SLC0_TO_EOF_BFR_DES_ADDR_S)) +#define SLC_SLC0_TO_EOF_BFR_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_TO_EOF_BFR_DES_ADDR_S 0 + +#define SLC_1_TO_EOF_DES_ADDR_REG (DR_REG_SLC_BASE + 0x84) +/* SLC_SLC1_TO_EOF_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC1_TO_EOF_DES_ADDR 0xFFFFFFFF +#define SLC_SLC1_TO_EOF_DES_ADDR_M ((SLC_SLC1_TO_EOF_DES_ADDR_V)<<(SLC_SLC1_TO_EOF_DES_ADDR_S)) +#define SLC_SLC1_TO_EOF_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC1_TO_EOF_DES_ADDR_S 0 + +#define SLC_1_TX_EOF_DES_ADDR_REG (DR_REG_SLC_BASE + 0x88) +/* SLC_SLC1_TX_SUC_EOF_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC1_TX_SUC_EOF_DES_ADDR 0xFFFFFFFF +#define SLC_SLC1_TX_SUC_EOF_DES_ADDR_M ((SLC_SLC1_TX_SUC_EOF_DES_ADDR_V)<<(SLC_SLC1_TX_SUC_EOF_DES_ADDR_S)) +#define SLC_SLC1_TX_SUC_EOF_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC1_TX_SUC_EOF_DES_ADDR_S 0 + +#define SLC_1_TO_EOF_BFR_DES_ADDR_REG (DR_REG_SLC_BASE + 0x8C) +/* SLC_SLC1_TO_EOF_BFR_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC1_TO_EOF_BFR_DES_ADDR 0xFFFFFFFF +#define SLC_SLC1_TO_EOF_BFR_DES_ADDR_M ((SLC_SLC1_TO_EOF_BFR_DES_ADDR_V)<<(SLC_SLC1_TO_EOF_BFR_DES_ADDR_S)) +#define SLC_SLC1_TO_EOF_BFR_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC1_TO_EOF_BFR_DES_ADDR_S 0 + +#define SLC_AHB_TEST_REG (DR_REG_SLC_BASE + 0x90) +/* SLC_AHB_TESTADDR : R/W ;bitpos:[5:4] ;default: 2'b0 ; */ +/*description: */ +#define SLC_AHB_TESTADDR 0x00000003 +#define SLC_AHB_TESTADDR_M ((SLC_AHB_TESTADDR_V)<<(SLC_AHB_TESTADDR_S)) +#define SLC_AHB_TESTADDR_V 0x3 +#define SLC_AHB_TESTADDR_S 4 +/* SLC_AHB_TESTMODE : R/W ;bitpos:[2:0] ;default: 3'b0 ; */ +/*description: */ +#define SLC_AHB_TESTMODE 0x00000007 +#define SLC_AHB_TESTMODE_M ((SLC_AHB_TESTMODE_V)<<(SLC_AHB_TESTMODE_S)) +#define SLC_AHB_TESTMODE_V 0x7 +#define SLC_AHB_TESTMODE_S 0 + +#define SLC_SDIO_ST_REG (DR_REG_SLC_BASE + 0x94) +/* SLC_FUNC2_ACC_STATE : RO ;bitpos:[28:24] ;default: 5'b0 ; */ +/*description: */ +#define SLC_FUNC2_ACC_STATE 0x0000001F +#define SLC_FUNC2_ACC_STATE_M ((SLC_FUNC2_ACC_STATE_V)<<(SLC_FUNC2_ACC_STATE_S)) +#define SLC_FUNC2_ACC_STATE_V 0x1F +#define SLC_FUNC2_ACC_STATE_S 24 +/* SLC_FUNC1_ACC_STATE : RO ;bitpos:[20:16] ;default: 5'b0 ; */ +/*description: */ +#define SLC_FUNC1_ACC_STATE 0x0000001F +#define SLC_FUNC1_ACC_STATE_M ((SLC_FUNC1_ACC_STATE_V)<<(SLC_FUNC1_ACC_STATE_S)) +#define SLC_FUNC1_ACC_STATE_V 0x1F +#define SLC_FUNC1_ACC_STATE_S 16 +/* SLC_BUS_ST : RO ;bitpos:[14:12] ;default: 3'b0 ; */ +/*description: */ +#define SLC_BUS_ST 0x00000007 +#define SLC_BUS_ST_M ((SLC_BUS_ST_V)<<(SLC_BUS_ST_S)) +#define SLC_BUS_ST_V 0x7 +#define SLC_BUS_ST_S 12 +/* SLC_SDIO_WAKEUP : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SDIO_WAKEUP (BIT(8)) +#define SLC_SDIO_WAKEUP_M (BIT(8)) +#define SLC_SDIO_WAKEUP_V 0x1 +#define SLC_SDIO_WAKEUP_S 8 +/* SLC_FUNC_ST : RO ;bitpos:[7:4] ;default: 4'b0 ; */ +/*description: */ +#define SLC_FUNC_ST 0x0000000F +#define SLC_FUNC_ST_M ((SLC_FUNC_ST_V)<<(SLC_FUNC_ST_S)) +#define SLC_FUNC_ST_V 0xF +#define SLC_FUNC_ST_S 4 +/* SLC_CMD_ST : RO ;bitpos:[2:0] ;default: 3'b0 ; */ +/*description: */ +#define SLC_CMD_ST 0x00000007 +#define SLC_CMD_ST_M ((SLC_CMD_ST_V)<<(SLC_CMD_ST_S)) +#define SLC_CMD_ST_V 0x7 +#define SLC_CMD_ST_S 0 + +#define SLC_RX_DSCR_CONF_REG (DR_REG_SLC_BASE + 0x98) +/* SLC_SLC1_RD_RETRY_THRESHOLD : R/W ;bitpos:[31:21] ;default: 11'h80 ; */ +/*description: */ +#define SLC_SLC1_RD_RETRY_THRESHOLD 0x000007FF +#define SLC_SLC1_RD_RETRY_THRESHOLD_M ((SLC_SLC1_RD_RETRY_THRESHOLD_V)<<(SLC_SLC1_RD_RETRY_THRESHOLD_S)) +#define SLC_SLC1_RD_RETRY_THRESHOLD_V 0x7FF +#define SLC_SLC1_RD_RETRY_THRESHOLD_S 21 +/* SLC_SLC1_RX_FILL_EN : R/W ;bitpos:[20] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_RX_FILL_EN (BIT(20)) +#define SLC_SLC1_RX_FILL_EN_M (BIT(20)) +#define SLC_SLC1_RX_FILL_EN_V 0x1 +#define SLC_SLC1_RX_FILL_EN_S 20 +/* SLC_SLC1_RX_EOF_MODE : R/W ;bitpos:[19] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_RX_EOF_MODE (BIT(19)) +#define SLC_SLC1_RX_EOF_MODE_M (BIT(19)) +#define SLC_SLC1_RX_EOF_MODE_V 0x1 +#define SLC_SLC1_RX_EOF_MODE_S 19 +/* SLC_SLC1_RX_FILL_MODE : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_FILL_MODE (BIT(18)) +#define SLC_SLC1_RX_FILL_MODE_M (BIT(18)) +#define SLC_SLC1_RX_FILL_MODE_V 0x1 +#define SLC_SLC1_RX_FILL_MODE_S 18 +/* SLC_SLC1_INFOR_NO_REPLACE : R/W ;bitpos:[17] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_INFOR_NO_REPLACE (BIT(17)) +#define SLC_SLC1_INFOR_NO_REPLACE_M (BIT(17)) +#define SLC_SLC1_INFOR_NO_REPLACE_V 0x1 +#define SLC_SLC1_INFOR_NO_REPLACE_S 17 +/* SLC_SLC1_TOKEN_NO_REPLACE : R/W ;bitpos:[16] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC1_TOKEN_NO_REPLACE (BIT(16)) +#define SLC_SLC1_TOKEN_NO_REPLACE_M (BIT(16)) +#define SLC_SLC1_TOKEN_NO_REPLACE_V 0x1 +#define SLC_SLC1_TOKEN_NO_REPLACE_S 16 +/* SLC_SLC0_RD_RETRY_THRESHOLD : R/W ;bitpos:[15:5] ;default: 11'h80 ; */ +/*description: */ +#define SLC_SLC0_RD_RETRY_THRESHOLD 0x000007FF +#define SLC_SLC0_RD_RETRY_THRESHOLD_M ((SLC_SLC0_RD_RETRY_THRESHOLD_V)<<(SLC_SLC0_RD_RETRY_THRESHOLD_S)) +#define SLC_SLC0_RD_RETRY_THRESHOLD_V 0x7FF +#define SLC_SLC0_RD_RETRY_THRESHOLD_S 5 +/* SLC_SLC0_RX_FILL_EN : R/W ;bitpos:[4] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_RX_FILL_EN (BIT(4)) +#define SLC_SLC0_RX_FILL_EN_M (BIT(4)) +#define SLC_SLC0_RX_FILL_EN_V 0x1 +#define SLC_SLC0_RX_FILL_EN_S 4 +/* SLC_SLC0_RX_EOF_MODE : R/W ;bitpos:[3] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_RX_EOF_MODE (BIT(3)) +#define SLC_SLC0_RX_EOF_MODE_M (BIT(3)) +#define SLC_SLC0_RX_EOF_MODE_V 0x1 +#define SLC_SLC0_RX_EOF_MODE_S 3 +/* SLC_SLC0_RX_FILL_MODE : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_FILL_MODE (BIT(2)) +#define SLC_SLC0_RX_FILL_MODE_M (BIT(2)) +#define SLC_SLC0_RX_FILL_MODE_V 0x1 +#define SLC_SLC0_RX_FILL_MODE_S 2 +/* SLC_SLC0_INFOR_NO_REPLACE : R/W ;bitpos:[1] ;default: 1'b1 ; */ +/*description: */ +#define SLC_SLC0_INFOR_NO_REPLACE (BIT(1)) +#define SLC_SLC0_INFOR_NO_REPLACE_M (BIT(1)) +#define SLC_SLC0_INFOR_NO_REPLACE_V 0x1 +#define SLC_SLC0_INFOR_NO_REPLACE_S 1 +/* SLC_SLC0_TOKEN_NO_REPLACE : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN_NO_REPLACE (BIT(0)) +#define SLC_SLC0_TOKEN_NO_REPLACE_M (BIT(0)) +#define SLC_SLC0_TOKEN_NO_REPLACE_V 0x1 +#define SLC_SLC0_TOKEN_NO_REPLACE_S 0 + +#define SLC_0_TXLINK_DSCR_REG (DR_REG_SLC_BASE + 0x9C) +/* SLC_SLC0_TXLINK_DSCR : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_DSCR 0xFFFFFFFF +#define SLC_SLC0_TXLINK_DSCR_M ((SLC_SLC0_TXLINK_DSCR_V)<<(SLC_SLC0_TXLINK_DSCR_S)) +#define SLC_SLC0_TXLINK_DSCR_V 0xFFFFFFFF +#define SLC_SLC0_TXLINK_DSCR_S 0 + +#define SLC_0_TXLINK_DSCR_BF0_REG (DR_REG_SLC_BASE + 0xA0) +/* SLC_SLC0_TXLINK_DSCR_BF0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_DSCR_BF0 0xFFFFFFFF +#define SLC_SLC0_TXLINK_DSCR_BF0_M ((SLC_SLC0_TXLINK_DSCR_BF0_V)<<(SLC_SLC0_TXLINK_DSCR_BF0_S)) +#define SLC_SLC0_TXLINK_DSCR_BF0_V 0xFFFFFFFF +#define SLC_SLC0_TXLINK_DSCR_BF0_S 0 + +#define SLC_0_TXLINK_DSCR_BF1_REG (DR_REG_SLC_BASE + 0xA4) +/* SLC_SLC0_TXLINK_DSCR_BF1 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_TXLINK_DSCR_BF1 0xFFFFFFFF +#define SLC_SLC0_TXLINK_DSCR_BF1_M ((SLC_SLC0_TXLINK_DSCR_BF1_V)<<(SLC_SLC0_TXLINK_DSCR_BF1_S)) +#define SLC_SLC0_TXLINK_DSCR_BF1_V 0xFFFFFFFF +#define SLC_SLC0_TXLINK_DSCR_BF1_S 0 + +#define SLC_0_RXLINK_DSCR_REG (DR_REG_SLC_BASE + 0xA8) +/* SLC_SLC0_RXLINK_DSCR : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_DSCR 0xFFFFFFFF +#define SLC_SLC0_RXLINK_DSCR_M ((SLC_SLC0_RXLINK_DSCR_V)<<(SLC_SLC0_RXLINK_DSCR_S)) +#define SLC_SLC0_RXLINK_DSCR_V 0xFFFFFFFF +#define SLC_SLC0_RXLINK_DSCR_S 0 + +#define SLC_0_RXLINK_DSCR_BF0_REG (DR_REG_SLC_BASE + 0xAC) +/* SLC_SLC0_RXLINK_DSCR_BF0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_DSCR_BF0 0xFFFFFFFF +#define SLC_SLC0_RXLINK_DSCR_BF0_M ((SLC_SLC0_RXLINK_DSCR_BF0_V)<<(SLC_SLC0_RXLINK_DSCR_BF0_S)) +#define SLC_SLC0_RXLINK_DSCR_BF0_V 0xFFFFFFFF +#define SLC_SLC0_RXLINK_DSCR_BF0_S 0 + +#define SLC_0_RXLINK_DSCR_BF1_REG (DR_REG_SLC_BASE + 0xB0) +/* SLC_SLC0_RXLINK_DSCR_BF1 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_RXLINK_DSCR_BF1 0xFFFFFFFF +#define SLC_SLC0_RXLINK_DSCR_BF1_M ((SLC_SLC0_RXLINK_DSCR_BF1_V)<<(SLC_SLC0_RXLINK_DSCR_BF1_S)) +#define SLC_SLC0_RXLINK_DSCR_BF1_V 0xFFFFFFFF +#define SLC_SLC0_RXLINK_DSCR_BF1_S 0 + +#define SLC_1_TXLINK_DSCR_REG (DR_REG_SLC_BASE + 0xB4) +/* SLC_SLC1_TXLINK_DSCR : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_DSCR 0xFFFFFFFF +#define SLC_SLC1_TXLINK_DSCR_M ((SLC_SLC1_TXLINK_DSCR_V)<<(SLC_SLC1_TXLINK_DSCR_S)) +#define SLC_SLC1_TXLINK_DSCR_V 0xFFFFFFFF +#define SLC_SLC1_TXLINK_DSCR_S 0 + +#define SLC_1_TXLINK_DSCR_BF0_REG (DR_REG_SLC_BASE + 0xB8) +/* SLC_SLC1_TXLINK_DSCR_BF0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_DSCR_BF0 0xFFFFFFFF +#define SLC_SLC1_TXLINK_DSCR_BF0_M ((SLC_SLC1_TXLINK_DSCR_BF0_V)<<(SLC_SLC1_TXLINK_DSCR_BF0_S)) +#define SLC_SLC1_TXLINK_DSCR_BF0_V 0xFFFFFFFF +#define SLC_SLC1_TXLINK_DSCR_BF0_S 0 + +#define SLC_1_TXLINK_DSCR_BF1_REG (DR_REG_SLC_BASE + 0xBC) +/* SLC_SLC1_TXLINK_DSCR_BF1 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC1_TXLINK_DSCR_BF1 0xFFFFFFFF +#define SLC_SLC1_TXLINK_DSCR_BF1_M ((SLC_SLC1_TXLINK_DSCR_BF1_V)<<(SLC_SLC1_TXLINK_DSCR_BF1_S)) +#define SLC_SLC1_TXLINK_DSCR_BF1_V 0xFFFFFFFF +#define SLC_SLC1_TXLINK_DSCR_BF1_S 0 + +#define SLC_1_RXLINK_DSCR_REG (DR_REG_SLC_BASE + 0xC0) +/* SLC_SLC1_RXLINK_DSCR : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_DSCR 0xFFFFFFFF +#define SLC_SLC1_RXLINK_DSCR_M ((SLC_SLC1_RXLINK_DSCR_V)<<(SLC_SLC1_RXLINK_DSCR_S)) +#define SLC_SLC1_RXLINK_DSCR_V 0xFFFFFFFF +#define SLC_SLC1_RXLINK_DSCR_S 0 + +#define SLC_1_RXLINK_DSCR_BF0_REG (DR_REG_SLC_BASE + 0xC4) +/* SLC_SLC1_RXLINK_DSCR_BF0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_DSCR_BF0 0xFFFFFFFF +#define SLC_SLC1_RXLINK_DSCR_BF0_M ((SLC_SLC1_RXLINK_DSCR_BF0_V)<<(SLC_SLC1_RXLINK_DSCR_BF0_S)) +#define SLC_SLC1_RXLINK_DSCR_BF0_V 0xFFFFFFFF +#define SLC_SLC1_RXLINK_DSCR_BF0_S 0 + +#define SLC_1_RXLINK_DSCR_BF1_REG (DR_REG_SLC_BASE + 0xC8) +/* SLC_SLC1_RXLINK_DSCR_BF1 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC1_RXLINK_DSCR_BF1 0xFFFFFFFF +#define SLC_SLC1_RXLINK_DSCR_BF1_M ((SLC_SLC1_RXLINK_DSCR_BF1_V)<<(SLC_SLC1_RXLINK_DSCR_BF1_S)) +#define SLC_SLC1_RXLINK_DSCR_BF1_V 0xFFFFFFFF +#define SLC_SLC1_RXLINK_DSCR_BF1_S 0 + +#define SLC_0_TX_ERREOF_DES_ADDR_REG (DR_REG_SLC_BASE + 0xCC) +/* SLC_SLC0_TX_ERR_EOF_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_TX_ERR_EOF_DES_ADDR 0xFFFFFFFF +#define SLC_SLC0_TX_ERR_EOF_DES_ADDR_M ((SLC_SLC0_TX_ERR_EOF_DES_ADDR_V)<<(SLC_SLC0_TX_ERR_EOF_DES_ADDR_S)) +#define SLC_SLC0_TX_ERR_EOF_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_TX_ERR_EOF_DES_ADDR_S 0 + +#define SLC_1_TX_ERREOF_DES_ADDR_REG (DR_REG_SLC_BASE + 0xD0) +/* SLC_SLC1_TX_ERR_EOF_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC1_TX_ERR_EOF_DES_ADDR 0xFFFFFFFF +#define SLC_SLC1_TX_ERR_EOF_DES_ADDR_M ((SLC_SLC1_TX_ERR_EOF_DES_ADDR_V)<<(SLC_SLC1_TX_ERR_EOF_DES_ADDR_S)) +#define SLC_SLC1_TX_ERR_EOF_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC1_TX_ERR_EOF_DES_ADDR_S 0 + +#define SLC_TOKEN_LAT_REG (DR_REG_SLC_BASE + 0xD4) +/* SLC_SLC1_TOKEN : RO ;bitpos:[27:16] ;default: 12'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN 0x00000FFF +#define SLC_SLC1_TOKEN_M ((SLC_SLC1_TOKEN_V)<<(SLC_SLC1_TOKEN_S)) +#define SLC_SLC1_TOKEN_V 0xFFF +#define SLC_SLC1_TOKEN_S 16 +/* SLC_SLC0_TOKEN : RO ;bitpos:[11:0] ;default: 12'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN 0x00000FFF +#define SLC_SLC0_TOKEN_M ((SLC_SLC0_TOKEN_V)<<(SLC_SLC0_TOKEN_S)) +#define SLC_SLC0_TOKEN_V 0xFFF +#define SLC_SLC0_TOKEN_S 0 + +#define SLC_TX_DSCR_CONF_REG (DR_REG_SLC_BASE + 0xD8) +/* SLC_WR_RETRY_THRESHOLD : R/W ;bitpos:[10:0] ;default: 11'h80 ; */ +/*description: */ +#define SLC_WR_RETRY_THRESHOLD 0x000007FF +#define SLC_WR_RETRY_THRESHOLD_M ((SLC_WR_RETRY_THRESHOLD_V)<<(SLC_WR_RETRY_THRESHOLD_S)) +#define SLC_WR_RETRY_THRESHOLD_V 0x7FF +#define SLC_WR_RETRY_THRESHOLD_S 0 + +#define SLC_CMD_INFOR0_REG (DR_REG_SLC_BASE + 0xDC) +/* SLC_CMD_CONTENT0 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_CMD_CONTENT0 0xFFFFFFFF +#define SLC_CMD_CONTENT0_M ((SLC_CMD_CONTENT0_V)<<(SLC_CMD_CONTENT0_S)) +#define SLC_CMD_CONTENT0_V 0xFFFFFFFF +#define SLC_CMD_CONTENT0_S 0 + +#define SLC_CMD_INFOR1_REG (DR_REG_SLC_BASE + 0xE0) +/* SLC_CMD_CONTENT1 : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_CMD_CONTENT1 0xFFFFFFFF +#define SLC_CMD_CONTENT1_M ((SLC_CMD_CONTENT1_V)<<(SLC_CMD_CONTENT1_S)) +#define SLC_CMD_CONTENT1_V 0xFFFFFFFF +#define SLC_CMD_CONTENT1_S 0 + +#define SLC_0_LEN_CONF_REG (DR_REG_SLC_BASE + 0xE4) +/* SLC_SLC0_TX_NEW_PKT_IND : RO ;bitpos:[28] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_NEW_PKT_IND (BIT(28)) +#define SLC_SLC0_TX_NEW_PKT_IND_M (BIT(28)) +#define SLC_SLC0_TX_NEW_PKT_IND_V 0x1 +#define SLC_SLC0_TX_NEW_PKT_IND_S 28 +/* SLC_SLC0_RX_NEW_PKT_IND : RO ;bitpos:[27] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_NEW_PKT_IND (BIT(27)) +#define SLC_SLC0_RX_NEW_PKT_IND_M (BIT(27)) +#define SLC_SLC0_RX_NEW_PKT_IND_V 0x1 +#define SLC_SLC0_RX_NEW_PKT_IND_S 27 +/* SLC_SLC0_TX_GET_USED_DSCR : WO ;bitpos:[26] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_GET_USED_DSCR (BIT(26)) +#define SLC_SLC0_TX_GET_USED_DSCR_M (BIT(26)) +#define SLC_SLC0_TX_GET_USED_DSCR_V 0x1 +#define SLC_SLC0_TX_GET_USED_DSCR_S 26 +/* SLC_SLC0_RX_GET_USED_DSCR : WO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_GET_USED_DSCR (BIT(25)) +#define SLC_SLC0_RX_GET_USED_DSCR_M (BIT(25)) +#define SLC_SLC0_RX_GET_USED_DSCR_V 0x1 +#define SLC_SLC0_RX_GET_USED_DSCR_S 25 +/* SLC_SLC0_TX_PACKET_LOAD_EN : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_PACKET_LOAD_EN (BIT(24)) +#define SLC_SLC0_TX_PACKET_LOAD_EN_M (BIT(24)) +#define SLC_SLC0_TX_PACKET_LOAD_EN_V 0x1 +#define SLC_SLC0_TX_PACKET_LOAD_EN_S 24 +/* SLC_SLC0_RX_PACKET_LOAD_EN : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_PACKET_LOAD_EN (BIT(23)) +#define SLC_SLC0_RX_PACKET_LOAD_EN_M (BIT(23)) +#define SLC_SLC0_RX_PACKET_LOAD_EN_V 0x1 +#define SLC_SLC0_RX_PACKET_LOAD_EN_S 23 +/* SLC_SLC0_LEN_INC_MORE : WO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_LEN_INC_MORE (BIT(22)) +#define SLC_SLC0_LEN_INC_MORE_M (BIT(22)) +#define SLC_SLC0_LEN_INC_MORE_V 0x1 +#define SLC_SLC0_LEN_INC_MORE_S 22 +/* SLC_SLC0_LEN_INC : WO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_LEN_INC (BIT(21)) +#define SLC_SLC0_LEN_INC_M (BIT(21)) +#define SLC_SLC0_LEN_INC_V 0x1 +#define SLC_SLC0_LEN_INC_S 21 +/* SLC_SLC0_LEN_WR : WO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_LEN_WR (BIT(20)) +#define SLC_SLC0_LEN_WR_M (BIT(20)) +#define SLC_SLC0_LEN_WR_V 0x1 +#define SLC_SLC0_LEN_WR_S 20 +/* SLC_SLC0_LEN_WDATA : WO ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define SLC_SLC0_LEN_WDATA 0x000FFFFF +#define SLC_SLC0_LEN_WDATA_M ((SLC_SLC0_LEN_WDATA_V)<<(SLC_SLC0_LEN_WDATA_S)) +#define SLC_SLC0_LEN_WDATA_V 0xFFFFF +#define SLC_SLC0_LEN_WDATA_S 0 + +#define SLC_0_LENGTH_REG (DR_REG_SLC_BASE + 0xE8) +/* SLC_SLC0_LEN : RO ;bitpos:[19:0] ;default: 20'h0 ; */ +/*description: */ +#define SLC_SLC0_LEN 0x000FFFFF +#define SLC_SLC0_LEN_M ((SLC_SLC0_LEN_V)<<(SLC_SLC0_LEN_S)) +#define SLC_SLC0_LEN_V 0xFFFFF +#define SLC_SLC0_LEN_S 0 + +#define SLC_0_TXPKT_H_DSCR_REG (DR_REG_SLC_BASE + 0xEC) +/* SLC_SLC0_TX_PKT_H_DSCR_ADDR : R/W ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_TX_PKT_H_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_TX_PKT_H_DSCR_ADDR_M ((SLC_SLC0_TX_PKT_H_DSCR_ADDR_V)<<(SLC_SLC0_TX_PKT_H_DSCR_ADDR_S)) +#define SLC_SLC0_TX_PKT_H_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_TX_PKT_H_DSCR_ADDR_S 0 + +#define SLC_0_TXPKT_E_DSCR_REG (DR_REG_SLC_BASE + 0xF0) +/* SLC_SLC0_TX_PKT_E_DSCR_ADDR : R/W ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_TX_PKT_E_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_TX_PKT_E_DSCR_ADDR_M ((SLC_SLC0_TX_PKT_E_DSCR_ADDR_V)<<(SLC_SLC0_TX_PKT_E_DSCR_ADDR_S)) +#define SLC_SLC0_TX_PKT_E_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_TX_PKT_E_DSCR_ADDR_S 0 + +#define SLC_0_RXPKT_H_DSCR_REG (DR_REG_SLC_BASE + 0xF4) +/* SLC_SLC0_RX_PKT_H_DSCR_ADDR : R/W ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_RX_PKT_H_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_RX_PKT_H_DSCR_ADDR_M ((SLC_SLC0_RX_PKT_H_DSCR_ADDR_V)<<(SLC_SLC0_RX_PKT_H_DSCR_ADDR_S)) +#define SLC_SLC0_RX_PKT_H_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_RX_PKT_H_DSCR_ADDR_S 0 + +#define SLC_0_RXPKT_E_DSCR_REG (DR_REG_SLC_BASE + 0xF8) +/* SLC_SLC0_RX_PKT_E_DSCR_ADDR : R/W ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_RX_PKT_E_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_RX_PKT_E_DSCR_ADDR_M ((SLC_SLC0_RX_PKT_E_DSCR_ADDR_V)<<(SLC_SLC0_RX_PKT_E_DSCR_ADDR_S)) +#define SLC_SLC0_RX_PKT_E_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_RX_PKT_E_DSCR_ADDR_S 0 + +#define SLC_0_TXPKTU_H_DSCR_REG (DR_REG_SLC_BASE + 0xFC) +/* SLC_SLC0_TX_PKT_START_DSCR_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_TX_PKT_START_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_TX_PKT_START_DSCR_ADDR_M ((SLC_SLC0_TX_PKT_START_DSCR_ADDR_V)<<(SLC_SLC0_TX_PKT_START_DSCR_ADDR_S)) +#define SLC_SLC0_TX_PKT_START_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_TX_PKT_START_DSCR_ADDR_S 0 + +#define SLC_0_TXPKTU_E_DSCR_REG (DR_REG_SLC_BASE + 0x100) +/* SLC_SLC0_TX_PKT_END_DSCR_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_TX_PKT_END_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_TX_PKT_END_DSCR_ADDR_M ((SLC_SLC0_TX_PKT_END_DSCR_ADDR_V)<<(SLC_SLC0_TX_PKT_END_DSCR_ADDR_S)) +#define SLC_SLC0_TX_PKT_END_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_TX_PKT_END_DSCR_ADDR_S 0 + +#define SLC_0_RXPKTU_H_DSCR_REG (DR_REG_SLC_BASE + 0x104) +/* SLC_SLC0_RX_PKT_START_DSCR_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_RX_PKT_START_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_RX_PKT_START_DSCR_ADDR_M ((SLC_SLC0_RX_PKT_START_DSCR_ADDR_V)<<(SLC_SLC0_RX_PKT_START_DSCR_ADDR_S)) +#define SLC_SLC0_RX_PKT_START_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_RX_PKT_START_DSCR_ADDR_S 0 + +#define SLC_0_RXPKTU_E_DSCR_REG (DR_REG_SLC_BASE + 0x108) +/* SLC_SLC0_RX_PKT_END_DSCR_ADDR : RO ;bitpos:[31:0] ;default: 32'h0 ; */ +/*description: */ +#define SLC_SLC0_RX_PKT_END_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_RX_PKT_END_DSCR_ADDR_M ((SLC_SLC0_RX_PKT_END_DSCR_ADDR_V)<<(SLC_SLC0_RX_PKT_END_DSCR_ADDR_S)) +#define SLC_SLC0_RX_PKT_END_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_RX_PKT_END_DSCR_ADDR_S 0 + +#define SLC_SEQ_POSITION_REG (DR_REG_SLC_BASE + 0x114) +/* SLC_SLC1_SEQ_POSITION : R/W ;bitpos:[15:8] ;default: 8'h5 ; */ +/*description: */ +#define SLC_SLC1_SEQ_POSITION 0x000000FF +#define SLC_SLC1_SEQ_POSITION_M ((SLC_SLC1_SEQ_POSITION_V)<<(SLC_SLC1_SEQ_POSITION_S)) +#define SLC_SLC1_SEQ_POSITION_V 0xFF +#define SLC_SLC1_SEQ_POSITION_S 8 +/* SLC_SLC0_SEQ_POSITION : R/W ;bitpos:[7:0] ;default: 8'h9 ; */ +/*description: */ +#define SLC_SLC0_SEQ_POSITION 0x000000FF +#define SLC_SLC0_SEQ_POSITION_M ((SLC_SLC0_SEQ_POSITION_V)<<(SLC_SLC0_SEQ_POSITION_S)) +#define SLC_SLC0_SEQ_POSITION_V 0xFF +#define SLC_SLC0_SEQ_POSITION_S 0 + +#define SLC_0_DSCR_REC_CONF_REG (DR_REG_SLC_BASE + 0x118) +/* SLC_SLC0_RX_DSCR_REC_LIM : R/W ;bitpos:[9:0] ;default: 10'h3ff ; */ +/*description: */ +#define SLC_SLC0_RX_DSCR_REC_LIM 0x000003FF +#define SLC_SLC0_RX_DSCR_REC_LIM_M ((SLC_SLC0_RX_DSCR_REC_LIM_V)<<(SLC_SLC0_RX_DSCR_REC_LIM_S)) +#define SLC_SLC0_RX_DSCR_REC_LIM_V 0x3FF +#define SLC_SLC0_RX_DSCR_REC_LIM_S 0 + +#define SLC_SDIO_CRC_ST0_REG (DR_REG_SLC_BASE + 0x11C) +/* SLC_DAT3_CRC_ERR_CNT : RO ;bitpos:[31:24] ;default: 8'h0 ; */ +/*description: */ +#define SLC_DAT3_CRC_ERR_CNT 0x000000FF +#define SLC_DAT3_CRC_ERR_CNT_M ((SLC_DAT3_CRC_ERR_CNT_V)<<(SLC_DAT3_CRC_ERR_CNT_S)) +#define SLC_DAT3_CRC_ERR_CNT_V 0xFF +#define SLC_DAT3_CRC_ERR_CNT_S 24 +/* SLC_DAT2_CRC_ERR_CNT : RO ;bitpos:[23:16] ;default: 8'h0 ; */ +/*description: */ +#define SLC_DAT2_CRC_ERR_CNT 0x000000FF +#define SLC_DAT2_CRC_ERR_CNT_M ((SLC_DAT2_CRC_ERR_CNT_V)<<(SLC_DAT2_CRC_ERR_CNT_S)) +#define SLC_DAT2_CRC_ERR_CNT_V 0xFF +#define SLC_DAT2_CRC_ERR_CNT_S 16 +/* SLC_DAT1_CRC_ERR_CNT : RO ;bitpos:[15:8] ;default: 8'h0 ; */ +/*description: */ +#define SLC_DAT1_CRC_ERR_CNT 0x000000FF +#define SLC_DAT1_CRC_ERR_CNT_M ((SLC_DAT1_CRC_ERR_CNT_V)<<(SLC_DAT1_CRC_ERR_CNT_S)) +#define SLC_DAT1_CRC_ERR_CNT_V 0xFF +#define SLC_DAT1_CRC_ERR_CNT_S 8 +/* SLC_DAT0_CRC_ERR_CNT : RO ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define SLC_DAT0_CRC_ERR_CNT 0x000000FF +#define SLC_DAT0_CRC_ERR_CNT_M ((SLC_DAT0_CRC_ERR_CNT_V)<<(SLC_DAT0_CRC_ERR_CNT_S)) +#define SLC_DAT0_CRC_ERR_CNT_V 0xFF +#define SLC_DAT0_CRC_ERR_CNT_S 0 + +#define SLC_SDIO_CRC_ST1_REG (DR_REG_SLC_BASE + 0x120) +/* SLC_ERR_CNT_CLR : R/W ;bitpos:[31] ;default: 1'b0 ; */ +/*description: */ +#define SLC_ERR_CNT_CLR (BIT(31)) +#define SLC_ERR_CNT_CLR_M (BIT(31)) +#define SLC_ERR_CNT_CLR_V 0x1 +#define SLC_ERR_CNT_CLR_S 31 +/* SLC_CMD_CRC_ERR_CNT : RO ;bitpos:[7:0] ;default: 8'h0 ; */ +/*description: */ +#define SLC_CMD_CRC_ERR_CNT 0x000000FF +#define SLC_CMD_CRC_ERR_CNT_M ((SLC_CMD_CRC_ERR_CNT_V)<<(SLC_CMD_CRC_ERR_CNT_S)) +#define SLC_CMD_CRC_ERR_CNT_V 0xFF +#define SLC_CMD_CRC_ERR_CNT_S 0 + +#define SLC_0_EOF_START_DES_REG (DR_REG_SLC_BASE + 0x124) +/* SLC_SLC0_EOF_START_DES_ADDR : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_EOF_START_DES_ADDR 0xFFFFFFFF +#define SLC_SLC0_EOF_START_DES_ADDR_M ((SLC_SLC0_EOF_START_DES_ADDR_V)<<(SLC_SLC0_EOF_START_DES_ADDR_S)) +#define SLC_SLC0_EOF_START_DES_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_EOF_START_DES_ADDR_S 0 + +#define SLC_0_PUSH_DSCR_ADDR_REG (DR_REG_SLC_BASE + 0x128) +/* SLC_SLC0_RX_PUSH_DSCR_ADDR : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_PUSH_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_RX_PUSH_DSCR_ADDR_M ((SLC_SLC0_RX_PUSH_DSCR_ADDR_V)<<(SLC_SLC0_RX_PUSH_DSCR_ADDR_S)) +#define SLC_SLC0_RX_PUSH_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_RX_PUSH_DSCR_ADDR_S 0 + +#define SLC_0_DONE_DSCR_ADDR_REG (DR_REG_SLC_BASE + 0x12C) +/* SLC_SLC0_RX_DONE_DSCR_ADDR : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DONE_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_RX_DONE_DSCR_ADDR_M ((SLC_SLC0_RX_DONE_DSCR_ADDR_V)<<(SLC_SLC0_RX_DONE_DSCR_ADDR_S)) +#define SLC_SLC0_RX_DONE_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_RX_DONE_DSCR_ADDR_S 0 + +#define SLC_0_SUB_START_DES_REG (DR_REG_SLC_BASE + 0x130) +/* SLC_SLC0_SUB_PAC_START_DSCR_ADDR : RO ;bitpos:[31:0] ;default: 32'b0 ; */ +/*description: */ +#define SLC_SLC0_SUB_PAC_START_DSCR_ADDR 0xFFFFFFFF +#define SLC_SLC0_SUB_PAC_START_DSCR_ADDR_M ((SLC_SLC0_SUB_PAC_START_DSCR_ADDR_V)<<(SLC_SLC0_SUB_PAC_START_DSCR_ADDR_S)) +#define SLC_SLC0_SUB_PAC_START_DSCR_ADDR_V 0xFFFFFFFF +#define SLC_SLC0_SUB_PAC_START_DSCR_ADDR_S 0 + +#define SLC_0_DSCR_CNT_REG (DR_REG_SLC_BASE + 0x134) +/* SLC_SLC0_RX_GET_EOF_OCC : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_GET_EOF_OCC (BIT(16)) +#define SLC_SLC0_RX_GET_EOF_OCC_M (BIT(16)) +#define SLC_SLC0_RX_GET_EOF_OCC_V 0x1 +#define SLC_SLC0_RX_GET_EOF_OCC_S 16 +/* SLC_SLC0_RX_DSCR_CNT_LAT : RO ;bitpos:[9:0] ;default: 10'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DSCR_CNT_LAT 0x000003FF +#define SLC_SLC0_RX_DSCR_CNT_LAT_M ((SLC_SLC0_RX_DSCR_CNT_LAT_V)<<(SLC_SLC0_RX_DSCR_CNT_LAT_S)) +#define SLC_SLC0_RX_DSCR_CNT_LAT_V 0x3FF +#define SLC_SLC0_RX_DSCR_CNT_LAT_S 0 + +#define SLC_0_LEN_LIM_CONF_REG (DR_REG_SLC_BASE + 0x138) +/* SLC_SLC0_LEN_LIM : R/W ;bitpos:[19:0] ;default: 20'h5400 ; */ +/*description: */ +#define SLC_SLC0_LEN_LIM 0x000FFFFF +#define SLC_SLC0_LEN_LIM_M ((SLC_SLC0_LEN_LIM_V)<<(SLC_SLC0_LEN_LIM_S)) +#define SLC_SLC0_LEN_LIM_V 0xFFFFF +#define SLC_SLC0_LEN_LIM_S 0 + +#define SLC_0INT_ST1_REG (DR_REG_SLC_BASE + 0x13C) +/* SLC_SLC0_RX_QUICK_EOF_INT_ST1 : RO ;bitpos:[26] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_QUICK_EOF_INT_ST1 (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_ST1_M (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_ST1_V 0x1 +#define SLC_SLC0_RX_QUICK_EOF_INT_ST1_S 26 +/* SLC_CMD_DTC_INT_ST1 : RO ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define SLC_CMD_DTC_INT_ST1 (BIT(25)) +#define SLC_CMD_DTC_INT_ST1_M (BIT(25)) +#define SLC_CMD_DTC_INT_ST1_V 0x1 +#define SLC_CMD_DTC_INT_ST1_S 25 +/* SLC_SLC0_TX_ERR_EOF_INT_ST1 : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_ERR_EOF_INT_ST1 (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_ST1_M (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_ST1_V 0x1 +#define SLC_SLC0_TX_ERR_EOF_INT_ST1_S 24 +/* SLC_SLC0_WR_RETRY_DONE_INT_ST1 : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_WR_RETRY_DONE_INT_ST1 (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_ST1_M (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_ST1_V 0x1 +#define SLC_SLC0_WR_RETRY_DONE_INT_ST1_S 23 +/* SLC_SLC0_HOST_RD_ACK_INT_ST1 : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_HOST_RD_ACK_INT_ST1 (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_ST1_M (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_ST1_V 0x1 +#define SLC_SLC0_HOST_RD_ACK_INT_ST1_S 22 +/* SLC_SLC0_TX_DSCR_EMPTY_INT_ST1 : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ST1 (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ST1_M (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ST1_V 0x1 +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ST1_S 21 +/* SLC_SLC0_RX_DSCR_ERR_INT_ST1 : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DSCR_ERR_INT_ST1 (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_ST1_M (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_ST1_V 0x1 +#define SLC_SLC0_RX_DSCR_ERR_INT_ST1_S 20 +/* SLC_SLC0_TX_DSCR_ERR_INT_ST1 : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_ERR_INT_ST1 (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_ST1_M (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_ST1_V 0x1 +#define SLC_SLC0_TX_DSCR_ERR_INT_ST1_S 19 +/* SLC_SLC0_TOHOST_INT_ST1 : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOHOST_INT_ST1 (BIT(18)) +#define SLC_SLC0_TOHOST_INT_ST1_M (BIT(18)) +#define SLC_SLC0_TOHOST_INT_ST1_V 0x1 +#define SLC_SLC0_TOHOST_INT_ST1_S 18 +/* SLC_SLC0_RX_EOF_INT_ST1 : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_EOF_INT_ST1 (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_ST1_M (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_ST1_V 0x1 +#define SLC_SLC0_RX_EOF_INT_ST1_S 17 +/* SLC_SLC0_RX_DONE_INT_ST1 : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DONE_INT_ST1 (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_ST1_M (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_ST1_V 0x1 +#define SLC_SLC0_RX_DONE_INT_ST1_S 16 +/* SLC_SLC0_TX_SUC_EOF_INT_ST1 : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_SUC_EOF_INT_ST1 (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_ST1_M (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_ST1_V 0x1 +#define SLC_SLC0_TX_SUC_EOF_INT_ST1_S 15 +/* SLC_SLC0_TX_DONE_INT_ST1 : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DONE_INT_ST1 (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_ST1_M (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_ST1_V 0x1 +#define SLC_SLC0_TX_DONE_INT_ST1_S 14 +/* SLC_SLC0_TOKEN1_1TO0_INT_ST1 : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_1TO0_INT_ST1 (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_ST1_M (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_ST1_V 0x1 +#define SLC_SLC0_TOKEN1_1TO0_INT_ST1_S 13 +/* SLC_SLC0_TOKEN0_1TO0_INT_ST1 : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_1TO0_INT_ST1 (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_ST1_M (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_ST1_V 0x1 +#define SLC_SLC0_TOKEN0_1TO0_INT_ST1_S 12 +/* SLC_SLC0_TX_OVF_INT_ST1 : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_OVF_INT_ST1 (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_ST1_M (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_ST1_V 0x1 +#define SLC_SLC0_TX_OVF_INT_ST1_S 11 +/* SLC_SLC0_RX_UDF_INT_ST1 : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_UDF_INT_ST1 (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_ST1_M (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_ST1_V 0x1 +#define SLC_SLC0_RX_UDF_INT_ST1_S 10 +/* SLC_SLC0_TX_START_INT_ST1 : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_START_INT_ST1 (BIT(9)) +#define SLC_SLC0_TX_START_INT_ST1_M (BIT(9)) +#define SLC_SLC0_TX_START_INT_ST1_V 0x1 +#define SLC_SLC0_TX_START_INT_ST1_S 9 +/* SLC_SLC0_RX_START_INT_ST1 : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_START_INT_ST1 (BIT(8)) +#define SLC_SLC0_RX_START_INT_ST1_M (BIT(8)) +#define SLC_SLC0_RX_START_INT_ST1_V 0x1 +#define SLC_SLC0_RX_START_INT_ST1_S 8 +/* SLC_FRHOST_BIT7_INT_ST1 : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT7_INT_ST1 (BIT(7)) +#define SLC_FRHOST_BIT7_INT_ST1_M (BIT(7)) +#define SLC_FRHOST_BIT7_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT7_INT_ST1_S 7 +/* SLC_FRHOST_BIT6_INT_ST1 : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT6_INT_ST1 (BIT(6)) +#define SLC_FRHOST_BIT6_INT_ST1_M (BIT(6)) +#define SLC_FRHOST_BIT6_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT6_INT_ST1_S 6 +/* SLC_FRHOST_BIT5_INT_ST1 : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT5_INT_ST1 (BIT(5)) +#define SLC_FRHOST_BIT5_INT_ST1_M (BIT(5)) +#define SLC_FRHOST_BIT5_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT5_INT_ST1_S 5 +/* SLC_FRHOST_BIT4_INT_ST1 : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT4_INT_ST1 (BIT(4)) +#define SLC_FRHOST_BIT4_INT_ST1_M (BIT(4)) +#define SLC_FRHOST_BIT4_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT4_INT_ST1_S 4 +/* SLC_FRHOST_BIT3_INT_ST1 : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT3_INT_ST1 (BIT(3)) +#define SLC_FRHOST_BIT3_INT_ST1_M (BIT(3)) +#define SLC_FRHOST_BIT3_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT3_INT_ST1_S 3 +/* SLC_FRHOST_BIT2_INT_ST1 : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT2_INT_ST1 (BIT(2)) +#define SLC_FRHOST_BIT2_INT_ST1_M (BIT(2)) +#define SLC_FRHOST_BIT2_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT2_INT_ST1_S 2 +/* SLC_FRHOST_BIT1_INT_ST1 : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT1_INT_ST1 (BIT(1)) +#define SLC_FRHOST_BIT1_INT_ST1_M (BIT(1)) +#define SLC_FRHOST_BIT1_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT1_INT_ST1_S 1 +/* SLC_FRHOST_BIT0_INT_ST1 : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT0_INT_ST1 (BIT(0)) +#define SLC_FRHOST_BIT0_INT_ST1_M (BIT(0)) +#define SLC_FRHOST_BIT0_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT0_INT_ST1_S 0 + +#define SLC_0INT_ENA1_REG (DR_REG_SLC_BASE + 0x140) +/* SLC_SLC0_RX_QUICK_EOF_INT_ENA1 : R/W ;bitpos:[26] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_QUICK_EOF_INT_ENA1 (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_ENA1_M (BIT(26)) +#define SLC_SLC0_RX_QUICK_EOF_INT_ENA1_V 0x1 +#define SLC_SLC0_RX_QUICK_EOF_INT_ENA1_S 26 +/* SLC_CMD_DTC_INT_ENA1 : R/W ;bitpos:[25] ;default: 1'b0 ; */ +/*description: */ +#define SLC_CMD_DTC_INT_ENA1 (BIT(25)) +#define SLC_CMD_DTC_INT_ENA1_M (BIT(25)) +#define SLC_CMD_DTC_INT_ENA1_V 0x1 +#define SLC_CMD_DTC_INT_ENA1_S 25 +/* SLC_SLC0_TX_ERR_EOF_INT_ENA1 : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_ERR_EOF_INT_ENA1 (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_ENA1_M (BIT(24)) +#define SLC_SLC0_TX_ERR_EOF_INT_ENA1_V 0x1 +#define SLC_SLC0_TX_ERR_EOF_INT_ENA1_S 24 +/* SLC_SLC0_WR_RETRY_DONE_INT_ENA1 : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_WR_RETRY_DONE_INT_ENA1 (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_ENA1_M (BIT(23)) +#define SLC_SLC0_WR_RETRY_DONE_INT_ENA1_V 0x1 +#define SLC_SLC0_WR_RETRY_DONE_INT_ENA1_S 23 +/* SLC_SLC0_HOST_RD_ACK_INT_ENA1 : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_HOST_RD_ACK_INT_ENA1 (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_ENA1_M (BIT(22)) +#define SLC_SLC0_HOST_RD_ACK_INT_ENA1_V 0x1 +#define SLC_SLC0_HOST_RD_ACK_INT_ENA1_S 22 +/* SLC_SLC0_TX_DSCR_EMPTY_INT_ENA1 : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ENA1 (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ENA1_M (BIT(21)) +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ENA1_V 0x1 +#define SLC_SLC0_TX_DSCR_EMPTY_INT_ENA1_S 21 +/* SLC_SLC0_RX_DSCR_ERR_INT_ENA1 : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DSCR_ERR_INT_ENA1 (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_ENA1_M (BIT(20)) +#define SLC_SLC0_RX_DSCR_ERR_INT_ENA1_V 0x1 +#define SLC_SLC0_RX_DSCR_ERR_INT_ENA1_S 20 +/* SLC_SLC0_TX_DSCR_ERR_INT_ENA1 : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DSCR_ERR_INT_ENA1 (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_ENA1_M (BIT(19)) +#define SLC_SLC0_TX_DSCR_ERR_INT_ENA1_V 0x1 +#define SLC_SLC0_TX_DSCR_ERR_INT_ENA1_S 19 +/* SLC_SLC0_TOHOST_INT_ENA1 : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOHOST_INT_ENA1 (BIT(18)) +#define SLC_SLC0_TOHOST_INT_ENA1_M (BIT(18)) +#define SLC_SLC0_TOHOST_INT_ENA1_V 0x1 +#define SLC_SLC0_TOHOST_INT_ENA1_S 18 +/* SLC_SLC0_RX_EOF_INT_ENA1 : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_EOF_INT_ENA1 (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_ENA1_M (BIT(17)) +#define SLC_SLC0_RX_EOF_INT_ENA1_V 0x1 +#define SLC_SLC0_RX_EOF_INT_ENA1_S 17 +/* SLC_SLC0_RX_DONE_INT_ENA1 : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_DONE_INT_ENA1 (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_ENA1_M (BIT(16)) +#define SLC_SLC0_RX_DONE_INT_ENA1_V 0x1 +#define SLC_SLC0_RX_DONE_INT_ENA1_S 16 +/* SLC_SLC0_TX_SUC_EOF_INT_ENA1 : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_SUC_EOF_INT_ENA1 (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_ENA1_M (BIT(15)) +#define SLC_SLC0_TX_SUC_EOF_INT_ENA1_V 0x1 +#define SLC_SLC0_TX_SUC_EOF_INT_ENA1_S 15 +/* SLC_SLC0_TX_DONE_INT_ENA1 : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_DONE_INT_ENA1 (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_ENA1_M (BIT(14)) +#define SLC_SLC0_TX_DONE_INT_ENA1_V 0x1 +#define SLC_SLC0_TX_DONE_INT_ENA1_S 14 +/* SLC_SLC0_TOKEN1_1TO0_INT_ENA1 : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN1_1TO0_INT_ENA1 (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_ENA1_M (BIT(13)) +#define SLC_SLC0_TOKEN1_1TO0_INT_ENA1_V 0x1 +#define SLC_SLC0_TOKEN1_1TO0_INT_ENA1_S 13 +/* SLC_SLC0_TOKEN0_1TO0_INT_ENA1 : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TOKEN0_1TO0_INT_ENA1 (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_ENA1_M (BIT(12)) +#define SLC_SLC0_TOKEN0_1TO0_INT_ENA1_V 0x1 +#define SLC_SLC0_TOKEN0_1TO0_INT_ENA1_S 12 +/* SLC_SLC0_TX_OVF_INT_ENA1 : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_OVF_INT_ENA1 (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_ENA1_M (BIT(11)) +#define SLC_SLC0_TX_OVF_INT_ENA1_V 0x1 +#define SLC_SLC0_TX_OVF_INT_ENA1_S 11 +/* SLC_SLC0_RX_UDF_INT_ENA1 : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_UDF_INT_ENA1 (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_ENA1_M (BIT(10)) +#define SLC_SLC0_RX_UDF_INT_ENA1_V 0x1 +#define SLC_SLC0_RX_UDF_INT_ENA1_S 10 +/* SLC_SLC0_TX_START_INT_ENA1 : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_TX_START_INT_ENA1 (BIT(9)) +#define SLC_SLC0_TX_START_INT_ENA1_M (BIT(9)) +#define SLC_SLC0_TX_START_INT_ENA1_V 0x1 +#define SLC_SLC0_TX_START_INT_ENA1_S 9 +/* SLC_SLC0_RX_START_INT_ENA1 : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC0_RX_START_INT_ENA1 (BIT(8)) +#define SLC_SLC0_RX_START_INT_ENA1_M (BIT(8)) +#define SLC_SLC0_RX_START_INT_ENA1_V 0x1 +#define SLC_SLC0_RX_START_INT_ENA1_S 8 +/* SLC_FRHOST_BIT7_INT_ENA1 : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT7_INT_ENA1 (BIT(7)) +#define SLC_FRHOST_BIT7_INT_ENA1_M (BIT(7)) +#define SLC_FRHOST_BIT7_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT7_INT_ENA1_S 7 +/* SLC_FRHOST_BIT6_INT_ENA1 : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT6_INT_ENA1 (BIT(6)) +#define SLC_FRHOST_BIT6_INT_ENA1_M (BIT(6)) +#define SLC_FRHOST_BIT6_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT6_INT_ENA1_S 6 +/* SLC_FRHOST_BIT5_INT_ENA1 : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT5_INT_ENA1 (BIT(5)) +#define SLC_FRHOST_BIT5_INT_ENA1_M (BIT(5)) +#define SLC_FRHOST_BIT5_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT5_INT_ENA1_S 5 +/* SLC_FRHOST_BIT4_INT_ENA1 : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT4_INT_ENA1 (BIT(4)) +#define SLC_FRHOST_BIT4_INT_ENA1_M (BIT(4)) +#define SLC_FRHOST_BIT4_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT4_INT_ENA1_S 4 +/* SLC_FRHOST_BIT3_INT_ENA1 : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT3_INT_ENA1 (BIT(3)) +#define SLC_FRHOST_BIT3_INT_ENA1_M (BIT(3)) +#define SLC_FRHOST_BIT3_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT3_INT_ENA1_S 3 +/* SLC_FRHOST_BIT2_INT_ENA1 : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT2_INT_ENA1 (BIT(2)) +#define SLC_FRHOST_BIT2_INT_ENA1_M (BIT(2)) +#define SLC_FRHOST_BIT2_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT2_INT_ENA1_S 2 +/* SLC_FRHOST_BIT1_INT_ENA1 : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT1_INT_ENA1 (BIT(1)) +#define SLC_FRHOST_BIT1_INT_ENA1_M (BIT(1)) +#define SLC_FRHOST_BIT1_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT1_INT_ENA1_S 1 +/* SLC_FRHOST_BIT0_INT_ENA1 : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT0_INT_ENA1 (BIT(0)) +#define SLC_FRHOST_BIT0_INT_ENA1_M (BIT(0)) +#define SLC_FRHOST_BIT0_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT0_INT_ENA1_S 0 + +#define SLC_1INT_ST1_REG (DR_REG_SLC_BASE + 0x144) +/* SLC_SLC1_TX_ERR_EOF_INT_ST1 : RO ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_ERR_EOF_INT_ST1 (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_ST1_M (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_ST1_V 0x1 +#define SLC_SLC1_TX_ERR_EOF_INT_ST1_S 24 +/* SLC_SLC1_WR_RETRY_DONE_INT_ST1 : RO ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_WR_RETRY_DONE_INT_ST1 (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_ST1_M (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_ST1_V 0x1 +#define SLC_SLC1_WR_RETRY_DONE_INT_ST1_S 23 +/* SLC_SLC1_HOST_RD_ACK_INT_ST1 : RO ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_HOST_RD_ACK_INT_ST1 (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_ST1_M (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_ST1_V 0x1 +#define SLC_SLC1_HOST_RD_ACK_INT_ST1_S 22 +/* SLC_SLC1_TX_DSCR_EMPTY_INT_ST1 : RO ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ST1 (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ST1_M (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ST1_V 0x1 +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ST1_S 21 +/* SLC_SLC1_RX_DSCR_ERR_INT_ST1 : RO ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DSCR_ERR_INT_ST1 (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_ST1_M (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_ST1_V 0x1 +#define SLC_SLC1_RX_DSCR_ERR_INT_ST1_S 20 +/* SLC_SLC1_TX_DSCR_ERR_INT_ST1 : RO ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_ERR_INT_ST1 (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_ST1_M (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_ST1_V 0x1 +#define SLC_SLC1_TX_DSCR_ERR_INT_ST1_S 19 +/* SLC_SLC1_TOHOST_INT_ST1 : RO ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOHOST_INT_ST1 (BIT(18)) +#define SLC_SLC1_TOHOST_INT_ST1_M (BIT(18)) +#define SLC_SLC1_TOHOST_INT_ST1_V 0x1 +#define SLC_SLC1_TOHOST_INT_ST1_S 18 +/* SLC_SLC1_RX_EOF_INT_ST1 : RO ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_EOF_INT_ST1 (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_ST1_M (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_ST1_V 0x1 +#define SLC_SLC1_RX_EOF_INT_ST1_S 17 +/* SLC_SLC1_RX_DONE_INT_ST1 : RO ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DONE_INT_ST1 (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_ST1_M (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_ST1_V 0x1 +#define SLC_SLC1_RX_DONE_INT_ST1_S 16 +/* SLC_SLC1_TX_SUC_EOF_INT_ST1 : RO ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_SUC_EOF_INT_ST1 (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_ST1_M (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_ST1_V 0x1 +#define SLC_SLC1_TX_SUC_EOF_INT_ST1_S 15 +/* SLC_SLC1_TX_DONE_INT_ST1 : RO ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DONE_INT_ST1 (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_ST1_M (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_ST1_V 0x1 +#define SLC_SLC1_TX_DONE_INT_ST1_S 14 +/* SLC_SLC1_TOKEN1_1TO0_INT_ST1 : RO ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_1TO0_INT_ST1 (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_ST1_M (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_ST1_V 0x1 +#define SLC_SLC1_TOKEN1_1TO0_INT_ST1_S 13 +/* SLC_SLC1_TOKEN0_1TO0_INT_ST1 : RO ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_1TO0_INT_ST1 (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_ST1_M (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_ST1_V 0x1 +#define SLC_SLC1_TOKEN0_1TO0_INT_ST1_S 12 +/* SLC_SLC1_TX_OVF_INT_ST1 : RO ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_OVF_INT_ST1 (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_ST1_M (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_ST1_V 0x1 +#define SLC_SLC1_TX_OVF_INT_ST1_S 11 +/* SLC_SLC1_RX_UDF_INT_ST1 : RO ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_UDF_INT_ST1 (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_ST1_M (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_ST1_V 0x1 +#define SLC_SLC1_RX_UDF_INT_ST1_S 10 +/* SLC_SLC1_TX_START_INT_ST1 : RO ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_START_INT_ST1 (BIT(9)) +#define SLC_SLC1_TX_START_INT_ST1_M (BIT(9)) +#define SLC_SLC1_TX_START_INT_ST1_V 0x1 +#define SLC_SLC1_TX_START_INT_ST1_S 9 +/* SLC_SLC1_RX_START_INT_ST1 : RO ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_START_INT_ST1 (BIT(8)) +#define SLC_SLC1_RX_START_INT_ST1_M (BIT(8)) +#define SLC_SLC1_RX_START_INT_ST1_V 0x1 +#define SLC_SLC1_RX_START_INT_ST1_S 8 +/* SLC_FRHOST_BIT15_INT_ST1 : RO ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT15_INT_ST1 (BIT(7)) +#define SLC_FRHOST_BIT15_INT_ST1_M (BIT(7)) +#define SLC_FRHOST_BIT15_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT15_INT_ST1_S 7 +/* SLC_FRHOST_BIT14_INT_ST1 : RO ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT14_INT_ST1 (BIT(6)) +#define SLC_FRHOST_BIT14_INT_ST1_M (BIT(6)) +#define SLC_FRHOST_BIT14_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT14_INT_ST1_S 6 +/* SLC_FRHOST_BIT13_INT_ST1 : RO ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT13_INT_ST1 (BIT(5)) +#define SLC_FRHOST_BIT13_INT_ST1_M (BIT(5)) +#define SLC_FRHOST_BIT13_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT13_INT_ST1_S 5 +/* SLC_FRHOST_BIT12_INT_ST1 : RO ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT12_INT_ST1 (BIT(4)) +#define SLC_FRHOST_BIT12_INT_ST1_M (BIT(4)) +#define SLC_FRHOST_BIT12_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT12_INT_ST1_S 4 +/* SLC_FRHOST_BIT11_INT_ST1 : RO ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT11_INT_ST1 (BIT(3)) +#define SLC_FRHOST_BIT11_INT_ST1_M (BIT(3)) +#define SLC_FRHOST_BIT11_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT11_INT_ST1_S 3 +/* SLC_FRHOST_BIT10_INT_ST1 : RO ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT10_INT_ST1 (BIT(2)) +#define SLC_FRHOST_BIT10_INT_ST1_M (BIT(2)) +#define SLC_FRHOST_BIT10_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT10_INT_ST1_S 2 +/* SLC_FRHOST_BIT9_INT_ST1 : RO ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT9_INT_ST1 (BIT(1)) +#define SLC_FRHOST_BIT9_INT_ST1_M (BIT(1)) +#define SLC_FRHOST_BIT9_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT9_INT_ST1_S 1 +/* SLC_FRHOST_BIT8_INT_ST1 : RO ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT8_INT_ST1 (BIT(0)) +#define SLC_FRHOST_BIT8_INT_ST1_M (BIT(0)) +#define SLC_FRHOST_BIT8_INT_ST1_V 0x1 +#define SLC_FRHOST_BIT8_INT_ST1_S 0 + +#define SLC_1INT_ENA1_REG (DR_REG_SLC_BASE + 0x148) +/* SLC_SLC1_TX_ERR_EOF_INT_ENA1 : R/W ;bitpos:[24] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_ERR_EOF_INT_ENA1 (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_ENA1_M (BIT(24)) +#define SLC_SLC1_TX_ERR_EOF_INT_ENA1_V 0x1 +#define SLC_SLC1_TX_ERR_EOF_INT_ENA1_S 24 +/* SLC_SLC1_WR_RETRY_DONE_INT_ENA1 : R/W ;bitpos:[23] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_WR_RETRY_DONE_INT_ENA1 (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_ENA1_M (BIT(23)) +#define SLC_SLC1_WR_RETRY_DONE_INT_ENA1_V 0x1 +#define SLC_SLC1_WR_RETRY_DONE_INT_ENA1_S 23 +/* SLC_SLC1_HOST_RD_ACK_INT_ENA1 : R/W ;bitpos:[22] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_HOST_RD_ACK_INT_ENA1 (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_ENA1_M (BIT(22)) +#define SLC_SLC1_HOST_RD_ACK_INT_ENA1_V 0x1 +#define SLC_SLC1_HOST_RD_ACK_INT_ENA1_S 22 +/* SLC_SLC1_TX_DSCR_EMPTY_INT_ENA1 : R/W ;bitpos:[21] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ENA1 (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ENA1_M (BIT(21)) +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ENA1_V 0x1 +#define SLC_SLC1_TX_DSCR_EMPTY_INT_ENA1_S 21 +/* SLC_SLC1_RX_DSCR_ERR_INT_ENA1 : R/W ;bitpos:[20] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DSCR_ERR_INT_ENA1 (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_ENA1_M (BIT(20)) +#define SLC_SLC1_RX_DSCR_ERR_INT_ENA1_V 0x1 +#define SLC_SLC1_RX_DSCR_ERR_INT_ENA1_S 20 +/* SLC_SLC1_TX_DSCR_ERR_INT_ENA1 : R/W ;bitpos:[19] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DSCR_ERR_INT_ENA1 (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_ENA1_M (BIT(19)) +#define SLC_SLC1_TX_DSCR_ERR_INT_ENA1_V 0x1 +#define SLC_SLC1_TX_DSCR_ERR_INT_ENA1_S 19 +/* SLC_SLC1_TOHOST_INT_ENA1 : R/W ;bitpos:[18] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOHOST_INT_ENA1 (BIT(18)) +#define SLC_SLC1_TOHOST_INT_ENA1_M (BIT(18)) +#define SLC_SLC1_TOHOST_INT_ENA1_V 0x1 +#define SLC_SLC1_TOHOST_INT_ENA1_S 18 +/* SLC_SLC1_RX_EOF_INT_ENA1 : R/W ;bitpos:[17] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_EOF_INT_ENA1 (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_ENA1_M (BIT(17)) +#define SLC_SLC1_RX_EOF_INT_ENA1_V 0x1 +#define SLC_SLC1_RX_EOF_INT_ENA1_S 17 +/* SLC_SLC1_RX_DONE_INT_ENA1 : R/W ;bitpos:[16] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_DONE_INT_ENA1 (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_ENA1_M (BIT(16)) +#define SLC_SLC1_RX_DONE_INT_ENA1_V 0x1 +#define SLC_SLC1_RX_DONE_INT_ENA1_S 16 +/* SLC_SLC1_TX_SUC_EOF_INT_ENA1 : R/W ;bitpos:[15] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_SUC_EOF_INT_ENA1 (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_ENA1_M (BIT(15)) +#define SLC_SLC1_TX_SUC_EOF_INT_ENA1_V 0x1 +#define SLC_SLC1_TX_SUC_EOF_INT_ENA1_S 15 +/* SLC_SLC1_TX_DONE_INT_ENA1 : R/W ;bitpos:[14] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_DONE_INT_ENA1 (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_ENA1_M (BIT(14)) +#define SLC_SLC1_TX_DONE_INT_ENA1_V 0x1 +#define SLC_SLC1_TX_DONE_INT_ENA1_S 14 +/* SLC_SLC1_TOKEN1_1TO0_INT_ENA1 : R/W ;bitpos:[13] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN1_1TO0_INT_ENA1 (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_ENA1_M (BIT(13)) +#define SLC_SLC1_TOKEN1_1TO0_INT_ENA1_V 0x1 +#define SLC_SLC1_TOKEN1_1TO0_INT_ENA1_S 13 +/* SLC_SLC1_TOKEN0_1TO0_INT_ENA1 : R/W ;bitpos:[12] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TOKEN0_1TO0_INT_ENA1 (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_ENA1_M (BIT(12)) +#define SLC_SLC1_TOKEN0_1TO0_INT_ENA1_V 0x1 +#define SLC_SLC1_TOKEN0_1TO0_INT_ENA1_S 12 +/* SLC_SLC1_TX_OVF_INT_ENA1 : R/W ;bitpos:[11] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_OVF_INT_ENA1 (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_ENA1_M (BIT(11)) +#define SLC_SLC1_TX_OVF_INT_ENA1_V 0x1 +#define SLC_SLC1_TX_OVF_INT_ENA1_S 11 +/* SLC_SLC1_RX_UDF_INT_ENA1 : R/W ;bitpos:[10] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_UDF_INT_ENA1 (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_ENA1_M (BIT(10)) +#define SLC_SLC1_RX_UDF_INT_ENA1_V 0x1 +#define SLC_SLC1_RX_UDF_INT_ENA1_S 10 +/* SLC_SLC1_TX_START_INT_ENA1 : R/W ;bitpos:[9] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_TX_START_INT_ENA1 (BIT(9)) +#define SLC_SLC1_TX_START_INT_ENA1_M (BIT(9)) +#define SLC_SLC1_TX_START_INT_ENA1_V 0x1 +#define SLC_SLC1_TX_START_INT_ENA1_S 9 +/* SLC_SLC1_RX_START_INT_ENA1 : R/W ;bitpos:[8] ;default: 1'b0 ; */ +/*description: */ +#define SLC_SLC1_RX_START_INT_ENA1 (BIT(8)) +#define SLC_SLC1_RX_START_INT_ENA1_M (BIT(8)) +#define SLC_SLC1_RX_START_INT_ENA1_V 0x1 +#define SLC_SLC1_RX_START_INT_ENA1_S 8 +/* SLC_FRHOST_BIT15_INT_ENA1 : R/W ;bitpos:[7] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT15_INT_ENA1 (BIT(7)) +#define SLC_FRHOST_BIT15_INT_ENA1_M (BIT(7)) +#define SLC_FRHOST_BIT15_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT15_INT_ENA1_S 7 +/* SLC_FRHOST_BIT14_INT_ENA1 : R/W ;bitpos:[6] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT14_INT_ENA1 (BIT(6)) +#define SLC_FRHOST_BIT14_INT_ENA1_M (BIT(6)) +#define SLC_FRHOST_BIT14_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT14_INT_ENA1_S 6 +/* SLC_FRHOST_BIT13_INT_ENA1 : R/W ;bitpos:[5] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT13_INT_ENA1 (BIT(5)) +#define SLC_FRHOST_BIT13_INT_ENA1_M (BIT(5)) +#define SLC_FRHOST_BIT13_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT13_INT_ENA1_S 5 +/* SLC_FRHOST_BIT12_INT_ENA1 : R/W ;bitpos:[4] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT12_INT_ENA1 (BIT(4)) +#define SLC_FRHOST_BIT12_INT_ENA1_M (BIT(4)) +#define SLC_FRHOST_BIT12_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT12_INT_ENA1_S 4 +/* SLC_FRHOST_BIT11_INT_ENA1 : R/W ;bitpos:[3] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT11_INT_ENA1 (BIT(3)) +#define SLC_FRHOST_BIT11_INT_ENA1_M (BIT(3)) +#define SLC_FRHOST_BIT11_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT11_INT_ENA1_S 3 +/* SLC_FRHOST_BIT10_INT_ENA1 : R/W ;bitpos:[2] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT10_INT_ENA1 (BIT(2)) +#define SLC_FRHOST_BIT10_INT_ENA1_M (BIT(2)) +#define SLC_FRHOST_BIT10_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT10_INT_ENA1_S 2 +/* SLC_FRHOST_BIT9_INT_ENA1 : R/W ;bitpos:[1] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT9_INT_ENA1 (BIT(1)) +#define SLC_FRHOST_BIT9_INT_ENA1_M (BIT(1)) +#define SLC_FRHOST_BIT9_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT9_INT_ENA1_S 1 +/* SLC_FRHOST_BIT8_INT_ENA1 : R/W ;bitpos:[0] ;default: 1'b0 ; */ +/*description: */ +#define SLC_FRHOST_BIT8_INT_ENA1 (BIT(0)) +#define SLC_FRHOST_BIT8_INT_ENA1_M (BIT(0)) +#define SLC_FRHOST_BIT8_INT_ENA1_V 0x1 +#define SLC_FRHOST_BIT8_INT_ENA1_S 0 + +#define SLC_DATE_REG (DR_REG_SLC_BASE + 0x1F8) +/* SLC_DATE : R/W ;bitpos:[31:0] ;default: 32'h16022500 ; */ +/*description: */ +#define SLC_DATE 0xFFFFFFFF +#define SLC_DATE_M ((SLC_DATE_V)<<(SLC_DATE_S)) +#define SLC_DATE_V 0xFFFFFFFF +#define SLC_DATE_S 0 + +#define SLC_ID_REG (DR_REG_SLC_BASE + 0x1FC) +/* SLC_ID : R/W ;bitpos:[31:0] ;default: 32'h0100 ; */ +/*description: */ +#define SLC_ID 0xFFFFFFFF +#define SLC_ID_M ((SLC_ID_V)<<(SLC_ID_S)) +#define SLC_ID_V 0xFFFFFFFF +#define SLC_ID_S 0 + + + + +#endif /*_SOC_SLC_REG_H_ */ + + diff --git a/tools/sdk/include/soc/soc/slc_struct.h b/tools/sdk/include/soc/soc/slc_struct.h new file mode 100644 index 00000000000..3d93ceef71d --- /dev/null +++ b/tools/sdk/include/soc/soc/slc_struct.h @@ -0,0 +1,858 @@ +// 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 _SOC_SLC_STRUCT_H_ +#define _SOC_SLC_STRUCT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef volatile struct { + union { + struct { + uint32_t slc0_tx_rst: 1; + uint32_t slc0_rx_rst: 1; + uint32_t ahbm_fifo_rst: 1; + uint32_t ahbm_rst: 1; + uint32_t slc0_tx_loop_test: 1; + uint32_t slc0_rx_loop_test: 1; + uint32_t slc0_rx_auto_wrback: 1; + uint32_t slc0_rx_no_restart_clr: 1; + uint32_t slc0_rxdscr_burst_en: 1; + uint32_t slc0_rxdata_burst_en: 1; + uint32_t slc0_rxlink_auto_ret: 1; + uint32_t slc0_txlink_auto_ret: 1; + uint32_t slc0_txdscr_burst_en: 1; + uint32_t slc0_txdata_burst_en: 1; + uint32_t slc0_token_auto_clr: 1; + uint32_t slc0_token_sel: 1; + uint32_t slc1_tx_rst: 1; + uint32_t slc1_rx_rst: 1; + uint32_t slc0_wr_retry_mask_en: 1; + uint32_t slc1_wr_retry_mask_en: 1; + uint32_t slc1_tx_loop_test: 1; + uint32_t slc1_rx_loop_test: 1; + uint32_t slc1_rx_auto_wrback: 1; + uint32_t slc1_rx_no_restart_clr: 1; + uint32_t slc1_rxdscr_burst_en: 1; + uint32_t slc1_rxdata_burst_en: 1; + uint32_t slc1_rxlink_auto_ret: 1; + uint32_t slc1_txlink_auto_ret: 1; + uint32_t slc1_txdscr_burst_en: 1; + uint32_t slc1_txdata_burst_en: 1; + uint32_t slc1_token_auto_clr: 1; + uint32_t slc1_token_sel: 1; + }; + uint32_t val; + } conf0; + union { + struct { + uint32_t frhost_bit0: 1; + uint32_t frhost_bit1: 1; + uint32_t frhost_bit2: 1; + uint32_t frhost_bit3: 1; + uint32_t frhost_bit4: 1; + uint32_t frhost_bit5: 1; + uint32_t frhost_bit6: 1; + uint32_t frhost_bit7: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t tx_done: 1; + uint32_t tx_suc_eof: 1; + uint32_t rx_done: 1; + uint32_t rx_eof: 1; + uint32_t tohost: 1; + uint32_t tx_dscr_err: 1; + uint32_t rx_dscr_err: 1; + uint32_t tx_dscr_empty: 1; + uint32_t host_rd_ack: 1; + uint32_t wr_retry_done: 1; + uint32_t tx_err_eof: 1; + uint32_t cmd_dtc: 1; + uint32_t rx_quick_eof: 1; + uint32_t reserved27: 5; + }; + uint32_t val; + } slc0_int_raw; + union { + struct { + uint32_t frhost_bit0: 1; + uint32_t frhost_bit1: 1; + uint32_t frhost_bit2: 1; + uint32_t frhost_bit3: 1; + uint32_t frhost_bit4: 1; + uint32_t frhost_bit5: 1; + uint32_t frhost_bit6: 1; + uint32_t frhost_bit7: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t tx_done: 1; + uint32_t tx_suc_eof: 1; + uint32_t rx_done: 1; + uint32_t rx_eof: 1; + uint32_t tohost: 1; + uint32_t tx_dscr_err: 1; + uint32_t rx_dscr_err: 1; + uint32_t tx_dscr_empty: 1; + uint32_t host_rd_ack: 1; + uint32_t wr_retry_done: 1; + uint32_t tx_err_eof: 1; + uint32_t cmd_dtc: 1; + uint32_t rx_quick_eof: 1; + uint32_t reserved27: 5; + }; + uint32_t val; + } slc0_int_st; + union { + struct { + uint32_t frhost_bit0: 1; + uint32_t frhost_bit1: 1; + uint32_t frhost_bit2: 1; + uint32_t frhost_bit3: 1; + uint32_t frhost_bit4: 1; + uint32_t frhost_bit5: 1; + uint32_t frhost_bit6: 1; + uint32_t frhost_bit7: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t tx_done: 1; + uint32_t tx_suc_eof: 1; + uint32_t rx_done: 1; + uint32_t rx_eof: 1; + uint32_t tohost: 1; + uint32_t tx_dscr_err: 1; + uint32_t rx_dscr_err: 1; + uint32_t tx_dscr_empty: 1; + uint32_t host_rd_ack: 1; + uint32_t wr_retry_done: 1; + uint32_t tx_err_eof: 1; + uint32_t cmd_dtc: 1; + uint32_t rx_quick_eof: 1; + uint32_t reserved27: 5; + }; + uint32_t val; + } slc0_int_ena; + union { + struct { + uint32_t frhost_bit0: 1; + uint32_t frhost_bit1: 1; + uint32_t frhost_bit2: 1; + uint32_t frhost_bit3: 1; + uint32_t frhost_bit4: 1; + uint32_t frhost_bit5: 1; + uint32_t frhost_bit6: 1; + uint32_t frhost_bit7: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t tx_done: 1; + uint32_t tx_suc_eof: 1; + uint32_t rx_done: 1; + uint32_t rx_eof: 1; + uint32_t tohost: 1; + uint32_t tx_dscr_err: 1; + uint32_t rx_dscr_err: 1; + uint32_t tx_dscr_empty: 1; + uint32_t host_rd_ack: 1; + uint32_t wr_retry_done: 1; + uint32_t tx_err_eof: 1; + uint32_t cmd_dtc: 1; + uint32_t rx_quick_eof: 1; + uint32_t reserved27: 5; + }; + uint32_t val; + } slc0_int_clr; + union { + struct { + uint32_t frhost_bit8: 1; + uint32_t frhost_bit9: 1; + uint32_t frhost_bit10: 1; + uint32_t frhost_bit11: 1; + uint32_t frhost_bit12: 1; + uint32_t frhost_bit13: 1; + uint32_t frhost_bit14: 1; + uint32_t frhost_bit15: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t tx_done: 1; + uint32_t tx_suc_eof: 1; + uint32_t rx_done: 1; + uint32_t rx_eof: 1; + uint32_t tohost: 1; + uint32_t tx_dscr_err: 1; + uint32_t rx_dscr_err: 1; + uint32_t tx_dscr_empty: 1; + uint32_t host_rd_ack: 1; + uint32_t wr_retry_done: 1; + uint32_t tx_err_eof: 1; + uint32_t reserved25: 7; + }; + uint32_t val; + } slc1_int_raw; + union { + struct { + uint32_t frhost_bit8: 1; + uint32_t frhost_bit9: 1; + uint32_t frhost_bit10: 1; + uint32_t frhost_bit11: 1; + uint32_t frhost_bit12: 1; + uint32_t frhost_bit13: 1; + uint32_t frhost_bit14: 1; + uint32_t frhost_bit15: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t tx_done: 1; + uint32_t tx_suc_eof: 1; + uint32_t rx_done: 1; + uint32_t rx_eof: 1; + uint32_t tohost: 1; + uint32_t tx_dscr_err: 1; + uint32_t rx_dscr_err: 1; + uint32_t tx_dscr_empty: 1; + uint32_t host_rd_ack: 1; + uint32_t wr_retry_done: 1; + uint32_t tx_err_eof: 1; + uint32_t reserved25: 7; + }; + uint32_t val; + } slc1_int_st; + union { + struct { + uint32_t frhost_bit8: 1; + uint32_t frhost_bit9: 1; + uint32_t frhost_bit10: 1; + uint32_t frhost_bit11: 1; + uint32_t frhost_bit12: 1; + uint32_t frhost_bit13: 1; + uint32_t frhost_bit14: 1; + uint32_t frhost_bit15: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t tx_done: 1; + uint32_t tx_suc_eof: 1; + uint32_t rx_done: 1; + uint32_t rx_eof: 1; + uint32_t tohost: 1; + uint32_t tx_dscr_err: 1; + uint32_t rx_dscr_err: 1; + uint32_t tx_dscr_empty: 1; + uint32_t host_rd_ack: 1; + uint32_t wr_retry_done: 1; + uint32_t tx_err_eof: 1; + uint32_t reserved25: 7; + }; + uint32_t val; + } slc1_int_ena; + union { + struct { + uint32_t frhost_bit8: 1; + uint32_t frhost_bit9: 1; + uint32_t frhost_bit10: 1; + uint32_t frhost_bit11: 1; + uint32_t frhost_bit12: 1; + uint32_t frhost_bit13: 1; + uint32_t frhost_bit14: 1; + uint32_t frhost_bit15: 1; + uint32_t rx_start: 1; + uint32_t tx_start: 1; + uint32_t rx_udf: 1; + uint32_t tx_ovf: 1; + uint32_t token0_1to0: 1; + uint32_t token1_1to0: 1; + uint32_t tx_done: 1; + uint32_t tx_suc_eof: 1; + uint32_t rx_done: 1; + uint32_t rx_eof: 1; + uint32_t tohost: 1; + uint32_t tx_dscr_err: 1; + uint32_t rx_dscr_err: 1; + uint32_t tx_dscr_empty: 1; + uint32_t host_rd_ack: 1; + uint32_t wr_retry_done: 1; + uint32_t tx_err_eof: 1; + uint32_t reserved25: 7; + }; + uint32_t val; + } slc1_int_clr; + union { + struct { + uint32_t slc0_rx_full: 1; + uint32_t slc0_rx_empty: 1; + uint32_t reserved2: 14; + uint32_t slc1_rx_full: 1; + uint32_t slc1_rx_empty: 1; + uint32_t reserved18:14; + }; + uint32_t val; + } rx_status; + union { + struct { + uint32_t rxfifo_wdata: 9; + uint32_t reserved9: 7; + uint32_t rxfifo_push: 1; + uint32_t reserved17: 15; + }; + uint32_t val; + } slc0_rxfifo_push; + union { + struct { + uint32_t rxfifo_wdata: 9; + uint32_t reserved9: 7; + uint32_t rxfifo_push: 1; + uint32_t reserved17: 15; + }; + uint32_t val; + } slc1_rxfifo_push; + union { + struct { + uint32_t slc0_tx_full: 1; + uint32_t slc0_tx_empty: 1; + uint32_t reserved2: 14; + uint32_t slc1_tx_full: 1; + uint32_t slc1_tx_empty: 1; + uint32_t reserved18:14; + }; + uint32_t val; + } tx_status; + union { + struct { + uint32_t txfifo_rdata: 11; + uint32_t reserved11: 5; + uint32_t txfifo_pop: 1; + uint32_t reserved17: 15; + }; + uint32_t val; + } slc0_txfifo_pop; + union { + struct { + uint32_t txfifo_rdata: 11; + uint32_t reserved11: 5; + uint32_t txfifo_pop: 1; + uint32_t reserved17: 15; + }; + uint32_t val; + } slc1_txfifo_pop; + union { + struct { + uint32_t addr: 20; + uint32_t reserved20: 8; + uint32_t stop: 1; + uint32_t start: 1; + uint32_t restart: 1; + uint32_t park: 1; + }; + uint32_t val; + } slc0_rx_link; + union { + struct { + uint32_t addr: 20; + uint32_t reserved20: 8; + uint32_t stop: 1; + uint32_t start: 1; + uint32_t restart: 1; + uint32_t park: 1; + }; + uint32_t val; + } slc0_tx_link; + union { + struct { + uint32_t addr: 20; + uint32_t bt_packet: 1; + uint32_t reserved21: 7; + uint32_t stop: 1; + uint32_t start: 1; + uint32_t restart: 1; + uint32_t park: 1; + }; + uint32_t val; + } slc1_rx_link; + union { + struct { + uint32_t addr: 20; + uint32_t reserved20: 8; + uint32_t stop: 1; + uint32_t start: 1; + uint32_t restart: 1; + uint32_t park: 1; + }; + uint32_t val; + } slc1_tx_link; + union { + struct { + uint32_t slc0_intvec: 8; + uint32_t reserved8: 8; + uint32_t slc1_intvec: 8; + uint32_t reserved24: 8; + }; + uint32_t val; + } intvec_tohost; + union { + struct { + uint32_t wdata: 12; + uint32_t wr: 1; + uint32_t inc: 1; + uint32_t inc_more: 1; + uint32_t reserved15: 1; + uint32_t token0: 12; + uint32_t reserved28: 4; + }; + uint32_t val; + } slc0_token0; + union { + struct { + uint32_t wdata: 12; + uint32_t wr: 1; + uint32_t inc: 1; + uint32_t inc_more: 1; + uint32_t reserved15: 1; + uint32_t token1: 12; + uint32_t reserved28: 4; + }; + uint32_t val; + } slc0_token1; + union { + struct { + uint32_t wdata: 12; + uint32_t wr: 1; + uint32_t inc: 1; + uint32_t inc_more: 1; + uint32_t reserved15: 1; + uint32_t token0: 12; + uint32_t reserved28: 4; + }; + uint32_t val; + } slc1_token0; + union { + struct { + uint32_t wdata: 12; + uint32_t wr: 1; + uint32_t inc: 1; + uint32_t inc_more: 1; + uint32_t reserved15: 1; + uint32_t token1: 12; + uint32_t reserved28: 4; + }; + uint32_t val; + } slc1_token1; + union { + struct { + uint32_t slc0_check_owner: 1; + uint32_t slc0_tx_check_sum_en: 1; + uint32_t slc0_rx_check_sum_en: 1; + uint32_t cmd_hold_en: 1; + uint32_t slc0_len_auto_clr: 1; + uint32_t slc0_tx_stitch_en: 1; + uint32_t slc0_rx_stitch_en: 1; + uint32_t reserved7: 9; + uint32_t slc1_check_owner: 1; + uint32_t slc1_tx_check_sum_en: 1; + uint32_t slc1_rx_check_sum_en: 1; + uint32_t host_int_level_sel: 1; + uint32_t slc1_tx_stitch_en: 1; + uint32_t slc1_rx_stitch_en: 1; + uint32_t clk_en: 1; + uint32_t reserved23: 9; + }; + uint32_t val; + } conf1; + uint32_t slc0_state0; /**/ + uint32_t slc0_state1; /**/ + uint32_t slc1_state0; /**/ + uint32_t slc1_state1; /**/ + union { + struct { + uint32_t txeof_ena: 6; + uint32_t reserved6: 2; + uint32_t fifo_map_ena: 4; + uint32_t slc0_tx_dummy_mode: 1; + uint32_t hda_map_128k: 1; + uint32_t slc1_tx_dummy_mode: 1; + uint32_t reserved15: 1; + uint32_t tx_push_idle_num:16; + }; + uint32_t val; + } bridge_conf; + uint32_t slc0_to_eof_des_addr; /**/ + uint32_t slc0_tx_eof_des_addr; /**/ + uint32_t slc0_to_eof_bfr_des_addr; /**/ + uint32_t slc1_to_eof_des_addr; /**/ + uint32_t slc1_tx_eof_des_addr; /**/ + uint32_t slc1_to_eof_bfr_des_addr; /**/ + union { + struct { + uint32_t mode: 3; + uint32_t reserved3: 1; + uint32_t addr: 2; + uint32_t reserved6: 26; + }; + uint32_t val; + } ahb_test; + union { + struct { + uint32_t cmd_st: 3; + uint32_t reserved3: 1; + uint32_t func_st: 4; + uint32_t sdio_wakeup: 1; + uint32_t reserved9: 3; + uint32_t bus_st: 3; + uint32_t reserved15: 1; + uint32_t func1_acc_state: 5; + uint32_t reserved21: 3; + uint32_t func2_acc_state: 5; + uint32_t reserved29: 3; + }; + uint32_t val; + } sdio_st; + union { + struct { + uint32_t slc0_token_no_replace: 1; + uint32_t slc0_infor_no_replace: 1; + uint32_t slc0_rx_fill_mode: 1; + uint32_t slc0_rx_eof_mode: 1; + uint32_t slc0_rx_fill_en: 1; + uint32_t slc0_rd_retry_threshold:11; + uint32_t slc1_token_no_replace: 1; + uint32_t slc1_infor_no_replace: 1; + uint32_t slc1_rx_fill_mode: 1; + uint32_t slc1_rx_eof_mode: 1; + uint32_t slc1_rx_fill_en: 1; + uint32_t slc1_rd_retry_threshold:11; + }; + uint32_t val; + } rx_dscr_conf; + uint32_t slc0_txlink_dscr; /**/ + uint32_t slc0_txlink_dscr_bf0; /**/ + uint32_t slc0_txlink_dscr_bf1; /**/ + uint32_t slc0_rxlink_dscr; /**/ + uint32_t slc0_rxlink_dscr_bf0; /**/ + uint32_t slc0_rxlink_dscr_bf1; /**/ + uint32_t slc1_txlink_dscr; /**/ + uint32_t slc1_txlink_dscr_bf0; /**/ + uint32_t slc1_txlink_dscr_bf1; /**/ + uint32_t slc1_rxlink_dscr; /**/ + uint32_t slc1_rxlink_dscr_bf0; /**/ + uint32_t slc1_rxlink_dscr_bf1; /**/ + uint32_t slc0_tx_erreof_des_addr; /**/ + uint32_t slc1_tx_erreof_des_addr; /**/ + union { + struct { + uint32_t slc0_token:12; + uint32_t reserved12: 4; + uint32_t slc1_token:12; + uint32_t reserved28: 4; + }; + uint32_t val; + } token_lat; + union { + struct { + uint32_t wr_retry_threshold:11; + uint32_t reserved11: 21; + }; + uint32_t val; + } tx_dscr_conf; + uint32_t cmd_infor0; /**/ + uint32_t cmd_infor1; /**/ + union { + struct { + uint32_t len_wdata: 20; + uint32_t len_wr: 1; + uint32_t len_inc: 1; + uint32_t len_inc_more: 1; + uint32_t rx_packet_load_en: 1; + uint32_t tx_packet_load_en: 1; + uint32_t rx_get_used_dscr: 1; + uint32_t tx_get_used_dscr: 1; + uint32_t rx_new_pkt_ind: 1; + uint32_t tx_new_pkt_ind: 1; + uint32_t reserved29: 3; + }; + uint32_t val; + } slc0_len_conf; + union { + struct { + uint32_t len: 20; + uint32_t reserved20:12; + }; + uint32_t val; + } slc0_length; + uint32_t slc0_txpkt_h_dscr; /**/ + uint32_t slc0_txpkt_e_dscr; /**/ + uint32_t slc0_rxpkt_h_dscr; /**/ + uint32_t slc0_rxpkt_e_dscr; /**/ + uint32_t slc0_txpktu_h_dscr; /**/ + uint32_t slc0_txpktu_e_dscr; /**/ + uint32_t slc0_rxpktu_h_dscr; /**/ + uint32_t slc0_rxpktu_e_dscr; /**/ + uint32_t reserved_10c; + uint32_t reserved_110; + union { + struct { + uint32_t slc0_position: 8; + uint32_t slc1_position: 8; + uint32_t reserved16: 16; + }; + uint32_t val; + } seq_position; + union { + struct { + uint32_t rx_dscr_rec_lim: 10; + uint32_t reserved10: 22; + }; + uint32_t val; + } slc0_dscr_rec_conf; + union { + struct { + uint32_t dat0_crc_err_cnt: 8; + uint32_t dat1_crc_err_cnt: 8; + uint32_t dat2_crc_err_cnt: 8; + uint32_t dat3_crc_err_cnt: 8; + }; + uint32_t val; + } sdio_crc_st0; + union { + struct { + uint32_t cmd_crc_err_cnt: 8; + uint32_t reserved8: 23; + uint32_t err_cnt_clr: 1; + }; + uint32_t val; + } sdio_crc_st1; + uint32_t slc0_eof_start_des; /**/ + uint32_t slc0_push_dscr_addr; /**/ + uint32_t slc0_done_dscr_addr; /**/ + uint32_t slc0_sub_start_des; /**/ + union { + struct { + uint32_t rx_dscr_cnt_lat: 10; + uint32_t reserved10: 6; + uint32_t rx_get_eof_occ: 1; + uint32_t reserved17: 15; + }; + uint32_t val; + } slc0_dscr_cnt; + union { + struct { + uint32_t len_lim: 20; + uint32_t reserved20:12; + }; + uint32_t val; + } slc0_len_lim_conf; + union { + struct { + uint32_t frhost_bit01: 1; + uint32_t frhost_bit11: 1; + uint32_t frhost_bit21: 1; + uint32_t frhost_bit31: 1; + uint32_t frhost_bit41: 1; + uint32_t frhost_bit51: 1; + uint32_t frhost_bit61: 1; + uint32_t frhost_bit71: 1; + uint32_t rx_start1: 1; + uint32_t tx_start1: 1; + uint32_t rx_udf1: 1; + uint32_t tx_ovf1: 1; + uint32_t token0_1to01: 1; + uint32_t token1_1to01: 1; + uint32_t tx_done1: 1; + uint32_t tx_suc_eof1: 1; + uint32_t rx_done1: 1; + uint32_t rx_eof1: 1; + uint32_t tohost1: 1; + uint32_t tx_dscr_err1: 1; + uint32_t rx_dscr_err1: 1; + uint32_t tx_dscr_empty1: 1; + uint32_t host_rd_ack1: 1; + uint32_t wr_retry_done1: 1; + uint32_t tx_err_eof1: 1; + uint32_t cmd_dtc1: 1; + uint32_t rx_quick_eof1: 1; + uint32_t reserved27: 5; + }; + uint32_t val; + } slc0_int_st1; + union { + struct { + uint32_t frhost_bit01: 1; + uint32_t frhost_bit11: 1; + uint32_t frhost_bit21: 1; + uint32_t frhost_bit31: 1; + uint32_t frhost_bit41: 1; + uint32_t frhost_bit51: 1; + uint32_t frhost_bit61: 1; + uint32_t frhost_bit71: 1; + uint32_t rx_start1: 1; + uint32_t tx_start1: 1; + uint32_t rx_udf1: 1; + uint32_t tx_ovf1: 1; + uint32_t token0_1to01: 1; + uint32_t token1_1to01: 1; + uint32_t tx_done1: 1; + uint32_t tx_suc_eof1: 1; + uint32_t rx_done1: 1; + uint32_t rx_eof1: 1; + uint32_t tohost1: 1; + uint32_t tx_dscr_err1: 1; + uint32_t rx_dscr_err1: 1; + uint32_t tx_dscr_empty1: 1; + uint32_t host_rd_ack1: 1; + uint32_t wr_retry_done1: 1; + uint32_t tx_err_eof1: 1; + uint32_t cmd_dtc1: 1; + uint32_t rx_quick_eof1: 1; + uint32_t reserved27: 5; + }; + uint32_t val; + } slc0_int_ena1; + union { + struct { + uint32_t frhost_bit81: 1; + uint32_t frhost_bit91: 1; + uint32_t frhost_bit101: 1; + uint32_t frhost_bit111: 1; + uint32_t frhost_bit121: 1; + uint32_t frhost_bit131: 1; + uint32_t frhost_bit141: 1; + uint32_t frhost_bit151: 1; + uint32_t rx_start1: 1; + uint32_t tx_start1: 1; + uint32_t rx_udf1: 1; + uint32_t tx_ovf1: 1; + uint32_t token0_1to01: 1; + uint32_t token1_1to01: 1; + uint32_t tx_done1: 1; + uint32_t tx_suc_eof1: 1; + uint32_t rx_done1: 1; + uint32_t rx_eof1: 1; + uint32_t tohost1: 1; + uint32_t tx_dscr_err1: 1; + uint32_t rx_dscr_err1: 1; + uint32_t tx_dscr_empty1: 1; + uint32_t host_rd_ack1: 1; + uint32_t wr_retry_done1: 1; + uint32_t tx_err_eof1: 1; + uint32_t reserved25: 7; + }; + uint32_t val; + } slc1_int_st1; + union { + struct { + uint32_t frhost_bit81: 1; + uint32_t frhost_bit91: 1; + uint32_t frhost_bit101: 1; + uint32_t frhost_bit111: 1; + uint32_t frhost_bit121: 1; + uint32_t frhost_bit131: 1; + uint32_t frhost_bit141: 1; + uint32_t frhost_bit151: 1; + uint32_t rx_start1: 1; + uint32_t tx_start1: 1; + uint32_t rx_udf1: 1; + uint32_t tx_ovf1: 1; + uint32_t token0_1to01: 1; + uint32_t token1_1to01: 1; + uint32_t tx_done1: 1; + uint32_t tx_suc_eof1: 1; + uint32_t rx_done1: 1; + uint32_t rx_eof1: 1; + uint32_t tohost1: 1; + uint32_t tx_dscr_err1: 1; + uint32_t rx_dscr_err1: 1; + uint32_t tx_dscr_empty1: 1; + uint32_t host_rd_ack1: 1; + uint32_t wr_retry_done1: 1; + uint32_t tx_err_eof1: 1; + uint32_t reserved25: 7; + }; + uint32_t val; + } slc1_int_ena1; + uint32_t reserved_14c; + uint32_t reserved_150; + uint32_t reserved_154; + uint32_t reserved_158; + uint32_t reserved_15c; + uint32_t reserved_160; + uint32_t reserved_164; + uint32_t reserved_168; + uint32_t reserved_16c; + uint32_t reserved_170; + uint32_t reserved_174; + uint32_t reserved_178; + uint32_t reserved_17c; + uint32_t reserved_180; + uint32_t reserved_184; + uint32_t reserved_188; + uint32_t reserved_18c; + uint32_t reserved_190; + uint32_t reserved_194; + uint32_t reserved_198; + uint32_t reserved_19c; + uint32_t reserved_1a0; + uint32_t reserved_1a4; + uint32_t reserved_1a8; + uint32_t reserved_1ac; + uint32_t reserved_1b0; + uint32_t reserved_1b4; + uint32_t reserved_1b8; + uint32_t reserved_1bc; + uint32_t reserved_1c0; + uint32_t reserved_1c4; + uint32_t reserved_1c8; + uint32_t reserved_1cc; + uint32_t reserved_1d0; + uint32_t reserved_1d4; + uint32_t reserved_1d8; + uint32_t reserved_1dc; + uint32_t reserved_1e0; + uint32_t reserved_1e4; + uint32_t reserved_1e8; + uint32_t reserved_1ec; + uint32_t reserved_1f0; + uint32_t reserved_1f4; + uint32_t date; /**/ + uint32_t id; /**/ +} slc_dev_t; +extern slc_dev_t SLC; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_SLC_STRUCT_H_ */ diff --git a/tools/sdk/include/soc/soc/soc.h b/tools/sdk/include/soc/soc/soc.h index 660abbdb3fc..d1d468303cc 100644 --- a/tools/sdk/include/soc/soc/soc.h +++ b/tools/sdk/include/soc/soc/soc.h @@ -59,16 +59,20 @@ #define APP_CPU_NUM (1) /* Overall memory map */ -#define SOC_IROM_LOW 0x400D0000 -#define SOC_IROM_HIGH 0x40400000 -#define SOC_DROM_LOW 0x3F400000 -#define SOC_DROM_HIGH 0x3F800000 -#define SOC_RTC_IRAM_LOW 0x400C0000 -#define SOC_RTC_IRAM_HIGH 0x400C2000 -#define SOC_RTC_DATA_LOW 0x50000000 -#define SOC_RTC_DATA_HIGH 0x50002000 -#define SOC_EXTRAM_DATA_LOW 0x3F800000 -#define SOC_EXTRAM_DATA_HIGH 0x3FC00000 +#define SOC_IROM_LOW 0x400D0000 +#define SOC_IROM_HIGH 0x40400000 +#define SOC_DROM_LOW 0x3F400000 +#define SOC_DROM_HIGH 0x3F800000 +#define SOC_DRAM_LOW 0x3FAE0000 +#define SOC_DRAM_HIGH 0x40000000 +#define SOC_RTC_IRAM_LOW 0x400C0000 +#define SOC_RTC_IRAM_HIGH 0x400C2000 +#define SOC_RTC_DATA_LOW 0x50000000 +#define SOC_RTC_DATA_HIGH 0x50002000 +#define SOC_EXTRAM_DATA_LOW 0x3F800000 +#define SOC_EXTRAM_DATA_HIGH 0x3FC00000 + +#define SOC_MAX_CONTIGUOUS_RAM_SIZE 0x400000 ///< Largest span of contiguous memory (DRAM or IRAM) in the address space #define DR_REG_DPORT_BASE 0x3ff00000 @@ -120,6 +124,7 @@ #define DR_REG_I2C1_EXT_BASE 0x3ff67000 #define DR_REG_SDMMC_BASE 0x3ff68000 #define DR_REG_EMAC_BASE 0x3ff69000 +#define DR_REG_CAN_BASE 0x3ff6B000 #define DR_REG_PWM1_BASE 0x3ff6C000 #define DR_REG_I2S1_BASE 0x3ff6D000 #define DR_REG_UART2_BASE 0x3ff6E000 @@ -129,10 +134,11 @@ //Registers Operation {{ #define ETS_UNCACHED_ADDR(addr) (addr) -#define ETS_CACHED_ADDR(addr) (addr) +#define ETS_CACHED_ADDR(addr) (addr) #ifndef __ASSEMBLER__ #define BIT(nr) (1UL << (nr)) +#define BIT64(nr) (1ULL << (nr)) #else #define BIT(nr) (1 << (nr)) #endif @@ -141,7 +147,7 @@ #define IS_DPORT_REG(_r) (((_r) >= DR_REG_DPORT_BASE) && (_r) <= DR_REG_DPORT_END) -#if !defined( BOOTLOADER_BUILD ) && !defined( CONFIG_FREERTOS_UNICORE ) && defined( ESP_PLATFORM ) +#if !defined( BOOTLOADER_BUILD ) && defined( CONFIG_ESP32_DPORT_WORKAROUND ) && defined( ESP_PLATFORM ) #define ASSERT_IF_DPORT_REG(_r, OP) TRY_STATIC_ASSERT(!IS_DPORT_REG(_r), (Cannot use OP for DPORT registers use DPORT_##OP)); #else #define ASSERT_IF_DPORT_REG(_r, OP) @@ -282,10 +288,18 @@ #define SOC_DROM_HIGH 0x3F800000 #define SOC_IROM_LOW 0x400D0000 #define SOC_IROM_HIGH 0x40400000 +#define SOC_IROM_MASK_LOW 0x40000000 +#define SOC_IROM_MASK_HIGH 0x40070000 +#define SOC_CACHE_PRO_LOW 0x40070000 +#define SOC_CACHE_PRO_HIGH 0x40078000 +#define SOC_CACHE_APP_LOW 0x40078000 +#define SOC_CACHE_APP_HIGH 0x40080000 #define SOC_IRAM_LOW 0x40080000 #define SOC_IRAM_HIGH 0x400A0000 #define SOC_RTC_IRAM_LOW 0x400C0000 #define SOC_RTC_IRAM_HIGH 0x400C2000 +#define SOC_RTC_DRAM_LOW 0x3FF80000 +#define SOC_RTC_DRAM_HIGH 0x3FF82000 #define SOC_RTC_DATA_LOW 0x50000000 #define SOC_RTC_DATA_HIGH 0x50002000 diff --git a/tools/sdk/include/soc/soc/soc_memory_layout.h b/tools/sdk/include/soc/soc/soc_memory_layout.h index 6273b1dbc32..fd7132cfa67 100644 --- a/tools/sdk/include/soc/soc/soc_memory_layout.h +++ b/tools/sdk/include/soc/soc/soc_memory_layout.h @@ -20,6 +20,38 @@ #include "sdkconfig.h" #include "esp_attr.h" +#ifdef CONFIG_BT_ENABLED + +#define SOC_MEM_BT_DATA_START 0x3ffae6e0 +#define SOC_MEM_BT_DATA_END 0x3ffaff10 +#define SOC_MEM_BT_EM_START 0x3ffb0000 +#define SOC_MEM_BT_EM_END 0x3ffb7cd8 +#define SOC_MEM_BT_EM_BTDM0_START 0x3ffb0000 +#define SOC_MEM_BT_EM_BTDM0_END 0x3ffb09a8 +#define SOC_MEM_BT_EM_BLE_START 0x3ffb09a8 +#define SOC_MEM_BT_EM_BLE_END 0x3ffb1ddc +#define SOC_MEM_BT_EM_BTDM1_START 0x3ffb1ddc +#define SOC_MEM_BT_EM_BTDM1_END 0x3ffb2730 +#define SOC_MEM_BT_EM_BREDR_START 0x3ffb2730 +#define SOC_MEM_BT_EM_BREDR_NO_SYNC_END 0x3ffb6388 //Not calculate with synchronize connection support +#define SOC_MEM_BT_EM_BREDR_END 0x3ffb7cd8 //Calculate with synchronize connection support +#define SOC_MEM_BT_EM_SYNC0_START 0x3ffb6388 +#define SOC_MEM_BT_EM_SYNC0_END 0x3ffb6bf8 +#define SOC_MEM_BT_EM_SYNC1_START 0x3ffb6bf8 +#define SOC_MEM_BT_EM_SYNC1_END 0x3ffb7468 +#define SOC_MEM_BT_EM_SYNC2_START 0x3ffb7468 +#define SOC_MEM_BT_EM_SYNC2_END 0x3ffb7cd8 +#define SOC_MEM_BT_BSS_START 0x3ffb8000 +#define SOC_MEM_BT_BSS_END 0x3ffb9a20 +#define SOC_MEM_BT_MISC_START 0x3ffbdb28 +#define SOC_MEM_BT_MISC_END 0x3ffbdb5c + +#define SOC_MEM_BT_EM_PER_SYNC_SIZE 0x870 + +#define SOC_MEM_BT_EM_BREDR_REAL_END (SOC_MEM_BT_EM_BREDR_NO_SYNC_END + CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF * SOC_MEM_BT_EM_PER_SYNC_SIZE) + +#endif //CONFIG_BT_ENABLED + #define SOC_MEMORY_TYPE_NO_PRIOS 3 /* Type descriptor holds a description for a particular type of memory on a particular SoC. @@ -57,8 +89,55 @@ typedef struct intptr_t end; } soc_reserved_region_t; -extern const soc_reserved_region_t soc_reserved_regions[]; -extern const size_t soc_reserved_region_count; +/* Use this macro to reserved a fixed region of RAM (hardcoded addresses) + * for a particular purpose. + * + * Usually used to mark out memory addresses needed for hardware or ROM code + * purposes. + * + * Don't call this macro from user code which can use normal C static allocation + * instead. + * + * @param START Start address to be reserved. + * @param END One after the address of the last byte to be reserved. (ie length of + * the reserved region is (END - START) in bytes. + * @param NAME Name for the reserved region. Must be a valid variable name, + * unique to this source file. + */ +#define SOC_RESERVE_MEMORY_REGION(START, END, NAME) \ + __attribute__((section(".reserved_memory_address"))) __attribute__((used)) \ + static soc_reserved_region_t reserved_region_##NAME = { START, END }; + +/* Return available memory regions for this SoC. Each available memory + * region is a contiguous piece of memory which is not being used by + * static data, used by ROM code, or reserved by a component using + * the SOC_RESERVE_MEMORY_REGION() macro. + * + * This result is soc_memory_regions[] minus all regions reserved + * via the SOC_RESERVE_MEMORY_REGION() macro (which may also split + * some regions up.) + * + * At startup, all available memory returned by this function is + * registered as heap space. + * + * @note OS-level startup function only, not recommended to call from + * app code. + * + * @param regions Pointer to an array for reading available regions into. + * Size of the array should be at least the result of + * soc_get_available_memory_region_max_count(). Entries in the array + * will be ordered by memory address. + * + * @return Number of entries copied to 'regions'. Will be no greater than + * the result of soc_get_available_memory_region_max_count(). + */ +size_t soc_get_available_memory_regions(soc_memory_region_t *regions); + +/* Return the maximum number of available memory regions which could be + * returned by soc_get_available_memory_regions(). Used to size the + * array passed to that function. + */ +size_t soc_get_available_memory_region_max_count(); inline static bool IRAM_ATTR esp_ptr_dma_capable(const void *p) { @@ -94,3 +173,27 @@ inline static bool IRAM_ATTR esp_ptr_internal(const void *p) { inline static bool IRAM_ATTR esp_ptr_external_ram(const void *p) { return ((intptr_t)p >= SOC_EXTRAM_DATA_LOW && (intptr_t)p < SOC_EXTRAM_DATA_HIGH); } + +inline static bool IRAM_ATTR esp_ptr_in_iram(const void *p) { +#ifndef CONFIG_FREERTOS_UNICORE + return ((intptr_t)p >= SOC_IRAM_LOW && (intptr_t)p < SOC_IRAM_HIGH); +#else + return ((intptr_t)p >= SOC_CACHE_APP_LOW && (intptr_t)p < SOC_IRAM_HIGH); +#endif +} + +inline static bool IRAM_ATTR esp_ptr_in_drom(const void *p) { + return ((intptr_t)p >= SOC_DROM_LOW && (intptr_t)p < SOC_DROM_HIGH); +} + +inline static bool IRAM_ATTR esp_ptr_in_dram(const void *p) { + return ((intptr_t)p >= SOC_DRAM_LOW && (intptr_t)p < SOC_DRAM_HIGH); +} + +inline static bool IRAM_ATTR esp_ptr_in_diram_dram(const void *p) { + return ((intptr_t)p >= SOC_DIRAM_DRAM_LOW && (intptr_t)p < SOC_DIRAM_DRAM_HIGH); +} + +inline static bool IRAM_ATTR esp_ptr_in_diram_iram(const void *p) { + return ((intptr_t)p >= SOC_DIRAM_IRAM_LOW && (intptr_t)p < SOC_DIRAM_IRAM_HIGH); +} diff --git a/tools/sdk/include/soc/soc/spi_periph.h b/tools/sdk/include/soc/soc/spi_periph.h new file mode 100644 index 00000000000..19b3f745125 --- /dev/null +++ b/tools/sdk/include/soc/soc/spi_periph.h @@ -0,0 +1,66 @@ +// 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 _SOC_SPI_PERIPH_H_ +#define _SOC_SPI_PERIPH_H_ + +#include +#include "soc/soc.h" +#include "soc/periph_defs.h" +//include soc related (generated) definitions +#include "soc/spi_pins.h" +#include "soc/spi_reg.h" +#include "soc/spi_struct.h" +#include "soc/gpio_sig_map.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* + Stores a bunch of per-spi-peripheral data. +*/ +typedef struct { + const uint8_t spiclk_out; //GPIO mux output signals + const uint8_t spiclk_in; + const uint8_t spid_out; + const uint8_t spiq_out; + const uint8_t spiwp_out; + const uint8_t spihd_out; + const uint8_t spid_in; //GPIO mux input signals + const uint8_t spiq_in; + const uint8_t spiwp_in; + const uint8_t spihd_in; + const uint8_t spics_out[3]; // /CS GPIO output mux signals + const uint8_t spics_in; + const uint8_t spiclk_iomux_pin; //IO pins of IO_MUX muxed signals + const uint8_t spid_iomux_pin; + const uint8_t spiq_iomux_pin; + const uint8_t spiwp_iomux_pin; + const uint8_t spihd_iomux_pin; + const uint8_t spics0_iomux_pin; + const uint8_t irq; //irq source for interrupt mux + const uint8_t irq_dma; //dma irq source for interrupt mux + const periph_module_t module; //peripheral module, for enabling clock etc + spi_dev_t *hw; //Pointer to the hardware registers +} spi_signal_conn_t; + +extern const spi_signal_conn_t spi_periph_signal[3]; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_SPI_PERIPH_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/spi_pins.h b/tools/sdk/include/soc/soc/spi_pins.h new file mode 100644 index 00000000000..eb7af858273 --- /dev/null +++ b/tools/sdk/include/soc/soc/spi_pins.h @@ -0,0 +1,39 @@ +// 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 _SOC_SPI_PINS_H_ +#define _SOC_SPI_PINS_H_ + +#define SPI_IOMUX_PIN_NUM_MISO 7 +#define SPI_IOMUX_PIN_NUM_MOSI 8 +#define SPI_IOMUX_PIN_NUM_CLK 6 +#define SPI_IOMUX_PIN_NUM_CS 11 +#define SPI_IOMUX_PIN_NUM_WP 10 +#define SPI_IOMUX_PIN_NUM_HD 9 + +#define HSPI_IOMUX_PIN_NUM_MISO 12 +#define HSPI_IOMUX_PIN_NUM_MOSI 13 +#define HSPI_IOMUX_PIN_NUM_CLK 14 +#define HSPI_IOMUX_PIN_NUM_CS 15 +#define HSPI_IOMUX_PIN_NUM_WP 2 +#define HSPI_IOMUX_PIN_NUM_HD 4 + +#define VSPI_IOMUX_PIN_NUM_MISO 19 +#define VSPI_IOMUX_PIN_NUM_MOSI 23 +#define VSPI_IOMUX_PIN_NUM_CLK 18 +#define VSPI_IOMUX_PIN_NUM_CS 5 +#define VSPI_IOMUX_PIN_NUM_WP 22 +#define VSPI_IOMUX_PIN_NUM_HD 21 + +#endif /* _SOC_SPI_PINS_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/spi_flash/esp_partition.h b/tools/sdk/include/spi_flash/esp_partition.h index f3d5a424af2..b1203696b84 100644 --- a/tools/sdk/include/spi_flash/esp_partition.h +++ b/tools/sdk/include/spi_flash/esp_partition.h @@ -70,6 +70,7 @@ typedef enum { ESP_PARTITION_SUBTYPE_DATA_PHY = 0x01, //!< PHY init data partition ESP_PARTITION_SUBTYPE_DATA_NVS = 0x02, //!< NVS partition ESP_PARTITION_SUBTYPE_DATA_COREDUMP = 0x03, //!< COREDUMP partition + ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS = 0x04, //!< Partition for NVS keys ESP_PARTITION_SUBTYPE_DATA_ESPHTTPD = 0x80, //!< ESPHTTPD partition ESP_PARTITION_SUBTYPE_DATA_FAT = 0x81, //!< FAT partition @@ -286,6 +287,37 @@ esp_err_t esp_partition_mmap(const esp_partition_t* partition, uint32_t offset, spi_flash_mmap_memory_t memory, const void** out_ptr, spi_flash_mmap_handle_t* out_handle); +/** + * @brief Get SHA-256 digest for required partition. + * + * 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] partition Pointer to info for partition containing app or data. (fields: address, size and type, are required to be filled). + * @param[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 esp_partition_get_sha256(const esp_partition_t *partition, uint8_t *sha_256); + +/** + * @brief Check for the identity of two partitions by SHA-256 digest. + * + * @param[in] partition_1 Pointer to info for partition 1 containing app or data. (fields: address, size and type, are required to be filled). + * @param[in] partition_2 Pointer to info for partition 2 containing app or data. (fields: address, size and type, are required to be filled). + * + * @return + * - True: In case of the two firmware is equal. + * - False: Otherwise + */ +bool esp_partition_check_identity(const esp_partition_t *partition_1, const esp_partition_t *partition_2); #ifdef __cplusplus } diff --git a/tools/sdk/include/spi_flash/esp_spi_flash.h b/tools/sdk/include/spi_flash/esp_spi_flash.h index 9caa47e4085..254e408959f 100644 --- a/tools/sdk/include/spi_flash/esp_spi_flash.h +++ b/tools/sdk/include/spi_flash/esp_spi_flash.h @@ -185,8 +185,8 @@ typedef uint32_t spi_flash_mmap_handle_t; * @param size Size of region to be mapped. This size will be rounded * up to a 64kB boundary * @param memory Address space where the region should be mapped (data or instruction) - * @param out_ptr Output, pointer to the mapped memory region - * @param out_handle Output, handle which should be used for spi_flash_munmap call + * @param[out] out_ptr Output, pointer to the mapped memory region + * @param[out] out_handle Output, handle which should be used for spi_flash_munmap call * * @return ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated */ @@ -204,14 +204,19 @@ esp_err_t spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t m * @param pages An array of numbers indicating the 64kB pages in flash to be mapped * contiguously into memory. These indicate the indexes of the 64kB pages, * not the byte-size addresses as used in other functions. - * @param pagecount Number of entries in the pages array + * Array must be located in internal memory. + * @param page_count Number of entries in the pages array * @param memory Address space where the region should be mapped (instruction or data) - * @param out_ptr Output, pointer to the mapped memory region - * @param out_handle Output, handle which should be used for spi_flash_munmap call + * @param[out] out_ptr Output, pointer to the mapped memory region + * @param[out] out_handle Output, handle which should be used for spi_flash_munmap call * - * @return ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if pages can not be allocated + * - ESP_ERR_INVALID_ARG if pagecount is zero or pages array is not in + * internal memory */ -esp_err_t spi_flash_mmap_pages(int *pages, size_t pagecount, spi_flash_mmap_memory_t memory, +esp_err_t spi_flash_mmap_pages(const int *pages, size_t page_count, spi_flash_mmap_memory_t memory, const void** out_ptr, spi_flash_mmap_handle_t* out_handle); @@ -239,15 +244,13 @@ void spi_flash_mmap_dump(); /** * @brief get free pages number which can be mmap * - * This function will return free page number of the mmu table which can mmap, - * when you want to call spi_flash_mmap to mmap an ranger of flash data to Dcache or Icache - * memmory region, maybe the size of MMU table will exceed,so if you are not sure the - * size need mmap is ok, can call the interface and watch how many MMU table page can be - * mmaped. + * This function will return number of free pages available in mmu table. This could be useful + * before calling actual spi_flash_mmap (maps flash range to DCache or ICache memory) to check + * if there is sufficient space available for mapping. * - * @param memory memmory type of MMU table free page + * @param memory memory type of MMU table free page * - * @return number of free pages which can be mmaped + * @return number of free pages which can be mmaped */ uint32_t spi_flash_mmap_get_free_pages(spi_flash_mmap_memory_t memory); @@ -310,6 +313,10 @@ typedef void (*spi_flash_op_lock_func_t)(void); * @brief SPI flash operation unlock function. */ typedef void (*spi_flash_op_unlock_func_t)(void); +/** + * @brief Function to protect SPI flash critical regions corruption. + */ +typedef bool (*spi_flash_is_safe_write_address_t)(size_t addr, size_t size); /** * Structure holding SPI flash access critical sections management functions. @@ -329,6 +336,9 @@ typedef void (*spi_flash_op_unlock_func_t)(void); * - 'op_unlock' unlocks access to flash API internal data. * These two functions are recursive and can be used around the outside of multiple calls to * 'start' & 'end', in order to create atomic multi-part flash operations. + * 3) When CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is disabled, flash writing/erasing + * API checks for addresses provided by user to avoid corruption of critical flash regions + * (bootloader, partition table, running application etc.). * * Different versions of the guarding functions should be used depending on the context of * execution (with or without functional OS). In normal conditions when flash API is called @@ -340,10 +350,13 @@ typedef void (*spi_flash_op_unlock_func_t)(void); * For example structure can be placed in DRAM and functions in IRAM sections. */ typedef struct { - spi_flash_guard_start_func_t start; /**< critical section start function. */ - spi_flash_guard_end_func_t end; /**< critical section end function. */ - spi_flash_op_lock_func_t op_lock; /**< flash access API lock function.*/ - spi_flash_op_unlock_func_t op_unlock; /**< flash access API unlock function.*/ + spi_flash_guard_start_func_t start; /**< critical section start function. */ + spi_flash_guard_end_func_t end; /**< critical section end function. */ + spi_flash_op_lock_func_t op_lock; /**< flash access API lock function.*/ + spi_flash_op_unlock_func_t op_unlock; /**< flash access API unlock function.*/ +#if !CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED + spi_flash_is_safe_write_address_t is_safe_write_address; /**< checks flash write addresses.*/ +#endif } spi_flash_guard_funcs_t; /** @@ -356,7 +369,6 @@ typedef struct { */ void spi_flash_guard_set(const spi_flash_guard_funcs_t* funcs); - /** * @brief Get the guard functions used for flash access * diff --git a/tools/sdk/include/spiffs/spiffs_config.h b/tools/sdk/include/spiffs/spiffs_config.h old mode 100755 new mode 100644 diff --git a/tools/sdk/include/tcp_transport/esp_transport.h b/tools/sdk/include/tcp_transport/esp_transport.h new file mode 100644 index 00000000000..e163a010cd9 --- /dev/null +++ b/tools/sdk/include/tcp_transport/esp_transport.h @@ -0,0 +1,304 @@ +// 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_TRANSPORT_H_ +#define _ESP_TRANSPORT_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct esp_transport_list_t* esp_transport_list_handle_t; +typedef struct esp_transport_item_t* esp_transport_handle_t; + +typedef int (*connect_func)(esp_transport_handle_t t, const char *host, int port, int timeout_ms); +typedef int (*io_func)(esp_transport_handle_t t, const char *buffer, int len, int timeout_ms); +typedef int (*io_read_func)(esp_transport_handle_t t, char *buffer, int len, int timeout_ms); +typedef int (*trans_func)(esp_transport_handle_t t); +typedef int (*poll_func)(esp_transport_handle_t t, int timeout_ms); +typedef int (*connect_async_func)(esp_transport_handle_t t, const char *host, int port, int timeout_ms); +typedef esp_transport_handle_t (*payload_transfer_func)(esp_transport_handle_t); + +/** + * @brief Create transport list + * + * @return A handle can hold all transports + */ +esp_transport_list_handle_t esp_transport_list_init(); + +/** + * @brief Cleanup and free all transports, include itself, + * this function will invoke esp_transport_destroy of every transport have added this the list + * + * @param[in] list The list + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_transport_list_destroy(esp_transport_list_handle_t list); + +/** + * @brief Add a transport to the list, and define a scheme to indentify this transport in the list + * + * @param[in] list The list + * @param[in] t The Transport + * @param[in] scheme The scheme + * + * @return + * - ESP_OK + */ +esp_err_t esp_transport_list_add(esp_transport_list_handle_t list, esp_transport_handle_t t, const char *scheme); + +/** + * @brief This function will remove all transport from the list, + * invoke esp_transport_destroy of every transport have added this the list + * + * @param[in] list The list + * + * @return + * - ESP_OK + * - ESP_ERR_INVALID_ARG + */ +esp_err_t esp_transport_list_clean(esp_transport_list_handle_t list); + +/** + * @brief Get the transport by scheme, which has been defined when calling function `esp_transport_list_add` + * + * @param[in] list The list + * @param[in] tag The tag + * + * @return The transport handle + */ +esp_transport_handle_t esp_transport_list_get_transport(esp_transport_list_handle_t list, const char *scheme); + +/** + * @brief Initialize a transport handle object + * + * @return The transport handle + */ +esp_transport_handle_t esp_transport_init(); + +/** + * @brief Cleanup and free memory the transport + * + * @param[in] t The transport handle + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_transport_destroy(esp_transport_handle_t t); + +/** + * @brief Get default port number used by this transport + * + * @param[in] t The transport handle + * + * @return the port number + */ +int esp_transport_get_default_port(esp_transport_handle_t t); + +/** + * @brief Set default port number that can be used by this transport + * + * @param[in] t The transport handle + * @param[in] port The port number + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_transport_set_default_port(esp_transport_handle_t t, int port); + +/** + * @brief Transport connection function, to make a connection to server + * + * @param t The transport handle + * @param[in] host Hostname + * @param[in] port Port + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - socket for will use by this transport + * - (-1) if there are any errors, should check errno + */ +int esp_transport_connect(esp_transport_handle_t t, const char *host, int port, int timeout_ms); + +/** + * @brief Non-blocking transport connection function, to make a connection to server + * + * @param t The transport handle + * @param[in] host Hostname + * @param[in] port Port + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - socket for will use by this transport + * - (-1) if there are any errors, should check errno + */ +int esp_transport_connect_async(esp_transport_handle_t t, const char *host, int port, int timeout_ms); + +/** + * @brief Transport read function + * + * @param t The transport handle + * @param buffer The buffer + * @param[in] len The length + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - Number of bytes was read + * - (-1) if there are any errors, should check errno + */ +int esp_transport_read(esp_transport_handle_t t, char *buffer, int len, int timeout_ms); + +/** + * @brief Poll the transport until readable or timeout + * + * @param[in] t The transport handle + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - 0 Timeout + * - (-1) If there are any errors, should check errno + * - other The transport can read + */ +int esp_transport_poll_read(esp_transport_handle_t t, int timeout_ms); + +/** + * @brief Transport write function + * + * @param t The transport handle + * @param buffer The buffer + * @param[in] len The length + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - Number of bytes was written + * - (-1) if there are any errors, should check errno + */ +int esp_transport_write(esp_transport_handle_t t, const char *buffer, int len, int timeout_ms); + +/** + * @brief Poll the transport until writeable or timeout + * + * @param[in] t The transport handle + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - 0 Timeout + * - (-1) If there are any errors, should check errno + * - other The transport can write + */ +int esp_transport_poll_write(esp_transport_handle_t t, int timeout_ms); + +/** + * @brief Transport close + * + * @param t The transport handle + * + * @return + * - 0 if ok + * - (-1) if there are any errors, should check errno + */ +int esp_transport_close(esp_transport_handle_t t); + +/** + * @brief Get user data context of this transport + * + * @param[in] t The transport handle + * + * @return The user data context + */ +void *esp_transport_get_context_data(esp_transport_handle_t t); + +/** + * @brief Get transport handle of underlying protocol + * which can access this protocol payload directly + * (used for receiving longer msg multiple times) + * + * @param[in] t The transport handle + * + * @return Payload transport handle + */ +esp_transport_handle_t esp_transport_get_payload_transport_handle(esp_transport_handle_t t); + +/** + * @brief Set the user context data for this transport + * + * @param[in] t The transport handle + * @param data The user data context + * + * @return + * - ESP_OK + */ +esp_err_t esp_transport_set_context_data(esp_transport_handle_t t, void *data); + +/** + * @brief Set transport functions for the transport handle + * + * @param[in] t The transport handle + * @param[in] _connect The connect function pointer + * @param[in] _read The read function pointer + * @param[in] _write The write function pointer + * @param[in] _close The close function pointer + * @param[in] _poll_read The poll read function pointer + * @param[in] _poll_write The poll write function pointer + * @param[in] _destroy The destroy function pointer + * + * @return + * - ESP_OK + */ +esp_err_t esp_transport_set_func(esp_transport_handle_t t, + connect_func _connect, + io_read_func _read, + io_func _write, + trans_func _close, + poll_func _poll_read, + poll_func _poll_write, + trans_func _destroy); + + +/** + * @brief Set transport functions for the transport handle + * + * @param[in] t The transport handle + * @param[in] _connect_async_func The connect_async function pointer + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_transport_set_async_connect_func(esp_transport_handle_t t, connect_async_func _connect_async_func); + +/** + * @brief Set parent transport function to the handle + * + * @param[in] t The transport handle + * @param[in] _parent_transport The underlying transport getter pointer + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_transport_set_parent_transport_func(esp_transport_handle_t t, payload_transfer_func _parent_transport); + +#ifdef __cplusplus +} +#endif +#endif /* _ESP_TRANSPORT_ */ diff --git a/tools/sdk/include/tcp_transport/esp_transport_ssl.h b/tools/sdk/include/tcp_transport/esp_transport_ssl.h new file mode 100644 index 00000000000..c42fd09353e --- /dev/null +++ b/tools/sdk/include/tcp_transport/esp_transport_ssl.h @@ -0,0 +1,76 @@ +// 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_TRANSPORT_SSL_H_ +#define _ESP_TRANSPORT_SSL_H_ + +#include "esp_transport.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Create new SSL transport, the transport handle must be release esp_transport_destroy callback + * + * @return the allocated esp_transport_handle_t, or NULL if the handle can not be allocated + */ +esp_transport_handle_t esp_transport_ssl_init(); + +/** + * @brief Set SSL certificate data (as PEM format). + * Note that, this function stores the pointer to data, rather than making a copy. + * So this data must remain valid until after the connection is cleaned up + * + * @param t ssl transport + * @param[in] data The pem data + * @param[in] len The length + */ +void esp_transport_ssl_set_cert_data(esp_transport_handle_t t, const char *data, int len); + +/** + * @brief Enable global CA store for SSL connection + * + * @param t ssl transport + */ +void esp_transport_ssl_enable_global_ca_store(esp_transport_handle_t t); + +/** + * @brief Set SSL client certificate data for mutual authentication (as PEM format). + * Note that, this function stores the pointer to data, rather than making a copy. + * So this data must remain valid until after the connection is cleaned up + * + * @param t ssl transport + * @param[in] data The pem data + * @param[in] len The length + */ +void esp_transport_ssl_set_client_cert_data(esp_transport_handle_t t, const char *data, int len); + +/** + * @brief Set SSL client key data for mutual authentication (as PEM format). + * Note that, this function stores the pointer to data, rather than making a copy. + * So this data must remain valid until after the connection is cleaned up + * + * @param t ssl transport + * @param[in] data The pem data + * @param[in] len The length + */ +void esp_transport_ssl_set_client_key_data(esp_transport_handle_t t, const char *data, int len); + +#ifdef __cplusplus +} +#endif +#endif /* _ESP_TRANSPORT_SSL_H_ */ + diff --git a/tools/sdk/include/tcp_transport/esp_transport_tcp.h b/tools/sdk/include/tcp_transport/esp_transport_tcp.h new file mode 100644 index 00000000000..57ad453309f --- /dev/null +++ b/tools/sdk/include/tcp_transport/esp_transport_tcp.h @@ -0,0 +1,36 @@ +// 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_TRANSPORT_TCP_H_ +#define _ESP_TRANSPORT_TCP_H_ + +#include "esp_transport.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Create TCP transport, the transport handle must be release esp_transport_destroy callback + * + * @return the allocated esp_transport_handle_t, or NULL if the handle can not be allocated + */ +esp_transport_handle_t esp_transport_tcp_init(); + + +#ifdef __cplusplus +} +#endif + +#endif /* _ESP_TRANSPORT_TCP_H_ */ diff --git a/tools/sdk/include/tcp_transport/esp_transport_utils.h b/tools/sdk/include/tcp_transport/esp_transport_utils.h new file mode 100644 index 00000000000..405b4f6b46e --- /dev/null +++ b/tools/sdk/include/tcp_transport/esp_transport_utils.h @@ -0,0 +1,40 @@ +// 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_TRANSPORT_UTILS_H_ +#define _ESP_TRANSPORT_UTILS_H_ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Convert milliseconds to timeval struct + * + * @param[in] timeout_ms The timeout milliseconds + * @param[out] tv Timeval struct + */ +void esp_transport_utils_ms_to_timeval(int timeout_ms, struct timeval *tv); + + +#define ESP_TRANSPORT_MEM_CHECK(TAG, a, action) if (!(a)) { \ + ESP_LOGE(TAG,"%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted"); \ + action; \ + } + +#ifdef __cplusplus +} +#endif +#endif /* _ESP_TRANSPORT_UTILS_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/tcp_transport/esp_transport_ws.h b/tools/sdk/include/tcp_transport/esp_transport_ws.h new file mode 100644 index 00000000000..582c5c7da28 --- /dev/null +++ b/tools/sdk/include/tcp_transport/esp_transport_ws.h @@ -0,0 +1,34 @@ +/* + * This file is subject to the terms and conditions defined in + * file 'LICENSE', which is part of this source code package. + * Tuan PM + */ + +#ifndef _ESP_TRANSPORT_WS_H_ +#define _ESP_TRANSPORT_WS_H_ + +#include "esp_transport.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Create web socket transport + * + * @return + * - transport + * - NULL + */ +esp_transport_handle_t esp_transport_ws_init(esp_transport_handle_t parent_handle); + +void esp_transport_ws_set_path(esp_transport_handle_t t, const char *path); + + + +#ifdef __cplusplus +} +#endif + +#endif /* _ESP_TRANSPORT_WS_H_ */ diff --git a/tools/sdk/include/tcpip_adapter/tcpip_adapter.h b/tools/sdk/include/tcpip_adapter/tcpip_adapter.h index 7ab31d1c12b..7d9e4ad8cd1 100644 --- a/tools/sdk/include/tcpip_adapter/tcpip_adapter.h +++ b/tools/sdk/include/tcpip_adapter/tcpip_adapter.h @@ -33,19 +33,17 @@ * get free station list APIs in application side. Other APIs are used in esp-idf internal, * otherwise the state maybe wrong. * - * TODO: ipv6 support will be added, use menuconfig to disable CONFIG_TCPIP_LWIP + * TODO: ipv6 support will be added */ #include #include "rom/queue.h" #include "esp_wifi_types.h" - -#define CONFIG_TCPIP_LWIP 1 -#define CONFIG_DHCP_STA_LIST 1 +#include "sdkconfig.h" #if CONFIG_TCPIP_LWIP #include "lwip/ip_addr.h" -#include "apps/dhcpserver.h" +#include "dhcpserver/dhcpserver.h" #ifdef __cplusplus extern "C" { @@ -81,7 +79,6 @@ typedef struct { typedef dhcps_lease_t tcpip_adapter_dhcps_lease_t; -#if CONFIG_DHCP_STA_LIST typedef struct { uint8_t mac[6]; ip4_addr_t ip; @@ -91,12 +88,10 @@ typedef struct { tcpip_adapter_sta_info_t sta[ESP_WIFI_MAX_CONN_NUM]; int num; } tcpip_adapter_sta_list_t; -#endif #endif -#define ESP_ERR_TCPIP_ADAPTER_BASE 0x5000 // TODO: move base address to esp_err.h - +#define ESP_ERR_TCPIP_ADAPTER_BASE 0x5000 #define ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS ESP_ERR_TCPIP_ADAPTER_BASE + 0x01 #define ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY ESP_ERR_TCPIP_ADAPTER_BASE + 0x02 #define ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED ESP_ERR_TCPIP_ADAPTER_BASE + 0x03 @@ -105,7 +100,6 @@ typedef struct { #define ESP_ERR_TCPIP_ADAPTER_NO_MEM ESP_ERR_TCPIP_ADAPTER_BASE + 0x06 #define ESP_ERR_TCPIP_ADAPTER_DHCP_NOT_STOPPED ESP_ERR_TCPIP_ADAPTER_BASE + 0x07 -/* TODO: add Ethernet interface */ typedef enum { TCPIP_ADAPTER_IF_STA = 0, /**< ESP32 station interface */ TCPIP_ADAPTER_IF_AP, /**< ESP32 soft-AP interface */ @@ -522,8 +516,17 @@ esp_err_t tcpip_adapter_dhcpc_start(tcpip_adapter_if_t tcpip_if); */ esp_err_t tcpip_adapter_dhcpc_stop(tcpip_adapter_if_t tcpip_if); - - +/** + * @brief Get data from ethernet interface + * + * This function should be installed by esp_eth_init, so Ethernet packets will be forward to TCPIP stack. + * + * @param[in] void *buffer: the received data point + * @param[in] uint16_t len: the received data length + * @param[in] void *eb: parameter + * + * @return ESP_OK + */ esp_err_t tcpip_adapter_eth_input(void *buffer, uint16_t len, void *eb); /** @@ -561,7 +564,7 @@ esp_err_t tcpip_adapter_ap_input(void *buffer, uint16_t len, void *eb); * * @return ESP_IF_WIFI_STA * ESP_IF_WIFI_AP - ESP_IF_ETH + * ESP_IF_ETH * ESP_IF_MAX */ esp_interface_t tcpip_adapter_get_esp_if(void *dev); @@ -615,6 +618,16 @@ esp_err_t tcpip_adapter_get_hostname(tcpip_adapter_if_t tcpip_if, const char **h */ esp_err_t tcpip_adapter_get_netif(tcpip_adapter_if_t tcpip_if, void ** netif); +/** + * @brief Test if supplied interface is up or down + * + * @param[in] tcpip_if: the interface which we will get the hostname + * + * @return true: tcpip_if is UP + * false: tcpip_if id DOWN + */ +bool tcpip_adapter_is_netif_up(tcpip_adapter_if_t tcpip_if); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/ulp/esp32/ulp.h b/tools/sdk/include/ulp/esp32/ulp.h index 64bfff8c459..6960ac97d84 100644 --- a/tools/sdk/include/ulp/esp32/ulp.h +++ b/tools/sdk/include/ulp/esp32/ulp.h @@ -17,11 +17,14 @@ #include #include #include "esp_err.h" +#include "soc/soc.h" #ifdef __cplusplus extern "C" { #endif +#define ULP_FSM_PREPARE_SLEEP_CYCLES 2 /*!< Cycles spent by FSM preparing ULP for sleep */ +#define ULP_FSM_WAKEUP_SLEEP_CYCLES 2 /*!< Cycles spent by FSM waking up ULP from sleep */ /** * @defgroup ulp_registers ULP coprocessor registers @@ -860,7 +863,7 @@ esp_err_t ulp_process_macros_and_load(uint32_t load_addr, const ulp_insn_t* prog * 3. TEXT_SIZE, size of .text section (2 bytes) * 4. DATA_SIZE, size of .data section (2 bytes) * 5. BSS_SIZE, size of .bss section (2 bytes) - * 6. (TEXT_OFFSET - 16) bytes of arbitrary data (will not be loaded into RTC memory) + * 6. (TEXT_OFFSET - 12) bytes of arbitrary data (will not be loaded into RTC memory) * 7. .text section * 8. .data section * @@ -897,6 +900,12 @@ esp_err_t ulp_run(uint32_t entry_point); * * @param period_index wakeup period setting number (0 - 4) * @param period_us wakeup period, us + * @note The ULP FSM requires two clock cycles to wakeup before being able to run the program. + * Then additional 16 cycles are reserved after wakeup waiting until the 8M clock is stable. + * The FSM also requires two more clock cycles to go to sleep after the program execution is halted. + * The minimum wakeup period that may be set up for the ULP + * is equal to the total number of cycles spent on the above internal tasks. + * For a default configuration of the ULP running at 150kHz it makes about 133us. * @return * - ESP_OK on success * - ESP_ERR_INVALID_ARG if period_index is out of range diff --git a/tools/sdk/include/vfs/esp_vfs.h b/tools/sdk/include/vfs/esp_vfs.h index ab645fccf68..7033b267655 100644 --- a/tools/sdk/include/vfs/esp_vfs.h +++ b/tools/sdk/include/vfs/esp_vfs.h @@ -1,4 +1,4 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// 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. @@ -18,16 +18,33 @@ #include #include #include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" #include "esp_err.h" #include #include #include +#include +#include +#include #include +#include +#include "sdkconfig.h" #ifdef __cplusplus extern "C" { #endif +#ifndef _SYS_TYPES_FD_SET +#error "VFS should be used with FD_SETSIZE and FD_SET from sys/types.h" +#endif + +/** + * Maximum number of (global) file descriptors. + */ +#define MAX_FDS FD_SETSIZE /* for compatibility with fd_set and select() */ + /** * Maximum length of path prefix (not including zero terminator) */ @@ -43,20 +60,10 @@ extern "C" { */ #define ESP_VFS_FLAG_CONTEXT_PTR 1 -/** - * Flag which indicates that the FD space of the VFS implementation should be made - * the same as the FD space in newlib. This means that the normal masking off - * of VFS-independent fd bits is ignored and the full user-facing fd is passed to - * the VFS implementation. - * - * Set the p_minimum_fd & p_maximum_fd pointers when registering the socket in - * order to know what range of FDs can be used with the registered VFS. - * - * This is mostly useful for LWIP which shares the socket FD space with - * socket-specific functions. - * +/* + * @brief VFS identificator used for esp_vfs_register_with_id() */ -#define ESP_VFS_FLAG_SHARED_FD_SPACE 2 +typedef int esp_vfs_id_t; /** * @brief VFS definition structure @@ -81,7 +88,7 @@ extern "C" { */ typedef struct { - int flags; /*!< ESP_VFS_FLAG_CONTEXT_PTR or ESP_VFS_FLAG_DEFAULT, plus optionally ESP_VFS_FLAG_SHARED_FD_SPACE */ + int flags; /*!< ESP_VFS_FLAG_CONTEXT_PTR or ESP_VFS_FLAG_DEFAULT */ union { ssize_t (*write_p)(void* p, int fd, const void * data, size_t size); ssize_t (*write)(int fd, const void * data, size_t size); @@ -166,6 +173,57 @@ typedef struct int (*fsync_p)(void* ctx, int fd); int (*fsync)(int fd); }; + union { + int (*access_p)(void* ctx, const char *path, int amode); + int (*access)(const char *path, int amode); + }; + union { + int (*truncate_p)(void* ctx, const char *path, off_t length); + int (*truncate)(const char *path, off_t length); + }; +#ifdef CONFIG_SUPPORT_TERMIOS + union { + int (*tcsetattr_p)(void *ctx, int fd, int optional_actions, const struct termios *p); + int (*tcsetattr)(int fd, int optional_actions, const struct termios *p); + }; + union { + int (*tcgetattr_p)(void *ctx, int fd, struct termios *p); + int (*tcgetattr)(int fd, struct termios *p); + }; + union { + int (*tcdrain_p)(void *ctx, int fd); + int (*tcdrain)(int fd); + }; + union { + int (*tcflush_p)(void *ctx, int fd, int select); + int (*tcflush)(int fd, int select); + }; + union { + int (*tcflow_p)(void *ctx, int fd, int action); + int (*tcflow)(int fd, int action); + }; + union { + pid_t (*tcgetsid_p)(void *ctx, int fd); + pid_t (*tcgetsid)(int fd); + }; + union { + int (*tcsendbreak_p)(void *ctx, int fd, int duration); + int (*tcsendbreak)(int fd, int duration); + }; +#endif // CONFIG_SUPPORT_TERMIOS + + /** start_select is called for setting up synchronous I/O multiplexing of the desired file descriptors in the given VFS */ + esp_err_t (*start_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, SemaphoreHandle_t *signal_sem); + /** socket select function for socket FDs with the functionality of POSIX select(); this should be set only for the socket VFS */ + int (*socket_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout); + /** called by VFS to interrupt the socket_select call when select is activated from a non-socket VFS driver; set only for the socket driver */ + void (*stop_socket_select)(); + /** stop_socket_select which can be called from ISR; set only for the socket driver */ + void (*stop_socket_select_isr)(BaseType_t *woken); + /** end_select is called to stop the I/O multiplexing and deinitialize the environment created by start_select for the given VFS */ + void* (*get_socket_select_semaphore)(); + /** get_socket_select_semaphore returns semaphore allocated in the socket driver; set only for the socket driver */ + void (*end_select)(); } esp_vfs_t; @@ -193,19 +251,38 @@ esp_err_t esp_vfs_register(const char* base_path, const esp_vfs_t* vfs, void* ct /** * Special case function for registering a VFS that uses a method other than - * open() to open new file descriptors. + * open() to open new file descriptors from the interval flags. - * @param p_max_fd If non-NULL, on success this variable is written with one higher than the maximum (global/user-facing) FD that this VFS will use. This is useful when ESP_VFS_FLAG_SHARED_FD_SPACE is set in vfs->flags. + * @param min_fd The smallest file descriptor this VFS will use. + * @param max_fd Upper boundary for file descriptors this VFS will use (the biggest file descriptor plus one). * * @return ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are - * registered. + * registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries + * are incorrect. + */ +esp_err_t esp_vfs_register_fd_range(const esp_vfs_t *vfs, void *ctx, int min_fd, int max_fd); + +/** + * Special case function for registering a VFS that uses a method other than + * open() to open new file descriptors. In comparison with + * esp_vfs_register_fd_range, this function doesn't pre-registers an interval + * of file descriptors. File descriptors can be registered later, by using + * esp_vfs_register_fd. + * + * @param vfs Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). + * @param ctx Pointer to context structure. Meaning is the same as for esp_vfs_register(). + * @param vfs_id Here will be written the VFS ID which can be passed to + * esp_vfs_register_fd for registering file descriptors. + * + * @return ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are + * registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries + * are incorrect. */ -esp_err_t esp_vfs_register_socket_space(const esp_vfs_t *vfs, void *ctx, int *p_min_fd, int *p_max_fd); +esp_err_t esp_vfs_register_with_id(const esp_vfs_t *vfs, void *ctx, esp_vfs_id_t *vfs_id); /** * Unregister a virtual filesystem for given path prefix @@ -216,6 +293,31 @@ esp_err_t esp_vfs_register_socket_space(const esp_vfs_t *vfs, void *ctx, int *p_ */ esp_err_t esp_vfs_unregister(const char* base_path); +/** + * Special function for registering another file descriptor for a VFS registered + * by esp_vfs_register_with_id. + * + * @param vfs_id VFS identificator returned by esp_vfs_register_with_id. + * @param fd The registered file descriptor will be written to this address. + * + * @return ESP_OK if the registration is successful, + * ESP_ERR_NO_MEM if too many file descriptors are registered, + * ESP_ERR_INVALID_ARG if the arguments are incorrect. + */ +esp_err_t esp_vfs_register_fd(esp_vfs_id_t vfs_id, int *fd); + +/** + * Special function for unregistering a file descriptor belonging to a VFS + * registered by esp_vfs_register_with_id. + * + * @param vfs_id VFS identificator returned by esp_vfs_register_with_id. + * @param fd File descriptor which should be unregistered. + * + * @return ESP_OK if the registration is successful, + * ESP_ERR_INVALID_ARG if the arguments are incorrect. + */ +esp_err_t esp_vfs_unregister_fd(esp_vfs_id_t vfs_id, int fd); + /** * These functions are to be used in newlib syscall table. They will be called by * newlib when it needs to use any of the syscalls. @@ -233,10 +335,71 @@ int esp_vfs_unlink(struct _reent *r, const char *path); int esp_vfs_rename(struct _reent *r, const char *src, const char *dst); /**@}*/ +/** + * @brief Synchronous I/O multiplexing which implements the functionality of POSIX select() for VFS + * @param nfds Specifies the range of descriptors which should be checked. + * The first nfds descriptors will be checked in each set. + * @param readfds If not NULL, then points to a descriptor set that on input + * specifies which descriptors should be checked for being + * ready to read, and on output indicates which descriptors + * are ready to read. + * @param writefds If not NULL, then points to a descriptor set that on input + * specifies which descriptors should be checked for being + * ready to write, and on output indicates which descriptors + * are ready to write. + * @param errorfds If not NULL, then points to a descriptor set that on input + * specifies which descriptors should be checked for error + * conditions, and on output indicates which descriptors + * have error conditions. + * @param timeout If not NULL, then points to timeval structure which + * specifies the time period after which the functions should + * time-out and return. If it is NULL, then the function will + * not time-out. + * + * @return The number of descriptors set in the descriptor sets, or -1 + * when an error (specified by errno) have occurred. + */ +int esp_vfs_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout); + +/** + * @brief Notification from a VFS driver about a read/write/error condition + * + * This function is called when the VFS driver detects a read/write/error + * condition as it was requested by the previous call to start_select. + * + * @param signal_sem semaphore handle which was passed to the driver by the start_select call + */ +void esp_vfs_select_triggered(SemaphoreHandle_t *signal_sem); + +/** + * @brief Notification from a VFS driver about a read/write/error condition (ISR version) + * + * This function is called when the VFS driver detects a read/write/error + * condition as it was requested by the previous call to start_select. + * + * @param signal_sem semaphore handle which was passed to the driver by the start_select call + * @param woken is set to pdTRUE if the function wakes up a task with higher priority + */ +void esp_vfs_select_triggered_isr(SemaphoreHandle_t *signal_sem, BaseType_t *woken); + +/** + * @brief Implements the VFS layer for synchronous I/O multiplexing by poll() + * + * The implementation is based on esp_vfs_select. The parameters and return values are compatible with POSIX poll(). + * + * @param fds Pointer to the array containing file descriptors and events poll() should consider. + * @param nfds Number of items in the array fds. + * @param timeout Poll() should wait at least timeout milliseconds. If the value is 0 then it should return + * immediately. If the value is -1 then it should wait (block) until the event occurs. + * + * @return A positive return value indicates the number of file descriptors that have been selected. The 0 + * return value indicates a timed-out poll. -1 is return on failure and errno is set accordingly. + * + */ +int esp_vfs_poll(struct pollfd *fds, nfds_t nfds, int timeout); #ifdef __cplusplus } // extern "C" #endif - #endif //__ESP_VFS_H__ diff --git a/tools/sdk/include/vfs/sys/ioctl.h b/tools/sdk/include/vfs/sys/ioctl.h index 95bad9818bb..90cbb47d663 100644 --- a/tools/sdk/include/vfs/sys/ioctl.h +++ b/tools/sdk/include/vfs/sys/ioctl.h @@ -14,5 +14,12 @@ #pragma once +#ifdef __cplusplus +extern "C" { +#endif + int ioctl(int fd, int request, ...); +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/wear_levelling/wear_levelling.h b/tools/sdk/include/wear_levelling/wear_levelling.h index 60f252e9caf..137b13f1d19 100644 --- a/tools/sdk/include/wear_levelling/wear_levelling.h +++ b/tools/sdk/include/wear_levelling/wear_levelling.h @@ -1,136 +1,136 @@ -// 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 _wear_levelling_H_ -#define _wear_levelling_H_ - -#include "esp_log.h" -#include "esp_partition.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** -* @brief wear levelling handle -*/ -typedef int32_t wl_handle_t; - -#define WL_INVALID_HANDLE -1 - -/** -* @brief Mount WL for defined partition -* -* @param partition that will be used for access -* @param out_handle handle of the WL instance -* -* @return -* - ESP_OK, if the allocation was successfully; -* - ESP_ERR_INVALID_ARG, if WL allocation was unsuccessful; -* - ESP_ERR_NO_MEM, if there was no memory to allocate WL components; -*/ -esp_err_t wl_mount(const esp_partition_t *partition, wl_handle_t *out_handle); - -/** -* @brief Unmount WL for defined partition -* -* @param handle WL partition handle -* -* @return -* - ESP_OK, if the operation completed successfully; -* - or one of error codes from lower-level flash driver. -*/ -esp_err_t wl_unmount(wl_handle_t handle); - -/** -* @brief Erase part of the WL storage -* -* @param handle WL handle that are related to the partition -* @param start_addr Address where erase operation should start. Must be aligned -* to the result of function wl_sector_size(...). -* @param size Size of the range which should be erased, in bytes. -* Must be divisible by result of function wl_sector_size(...).. -* -* @return -* - ESP_OK, if the range was erased successfully; -* - ESP_ERR_INVALID_ARG, if iterator or dst are NULL; -* - ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; -* - or one of error codes from lower-level flash driver. -*/ -esp_err_t wl_erase_range(wl_handle_t handle, size_t start_addr, size_t size); - -/** -* @brief Write data to the WL storage -* -* Before writing data to flash, corresponding region of flash needs to be erased. -* This can be done using wl_erase_range function. -* -* @param handle WL handle that are related to the partition -* @param dest_addr Address where the data should be written, relative to the -* beginning of the partition. -* @param src Pointer to the source buffer. Pointer must be non-NULL and -* buffer must be at least 'size' bytes long. -* @param size Size of data to be written, in bytes. -* -* @note Prior to writing to WL storage, make sure it has been erased with -* wl_erase_range call. -* -* @return -* - ESP_OK, if data was written successfully; -* - ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; -* - ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; -* - or one of error codes from lower-level flash driver. -*/ -esp_err_t wl_write(wl_handle_t handle, size_t dest_addr, const void *src, size_t size); - -/** -* @brief Read data from the WL storage -* -* @param handle WL module instance that was initialized before -* @param dest Pointer to the buffer where data should be stored. -* Pointer must be non-NULL and buffer must be at least 'size' bytes long. -* @param src_addr Address of the data to be read, relative to the -* beginning of the partition. -* @param size Size of data to be read, in bytes. -* -* @return -* - ESP_OK, if data was read successfully; -* - ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; -* - ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; -* - or one of error codes from lower-level flash driver. -*/ -esp_err_t wl_read(wl_handle_t handle, size_t src_addr, void *dest, size_t size); - -/** -* @brief Get size of the WL storage -* -* @param handle WL module handle that was initialized before -* @return usable size, in bytes -*/ -size_t wl_size(wl_handle_t handle); - -/** -* @brief Get sector size of the WL instance -* -* @param handle WL module handle that was initialized before -* @return sector size, in bytes -*/ -size_t wl_sector_size(wl_handle_t handle); - - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _wear_levelling_H_ +// 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 _wear_levelling_H_ +#define _wear_levelling_H_ + +#include "esp_log.h" +#include "esp_partition.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @brief wear levelling handle +*/ +typedef int32_t wl_handle_t; + +#define WL_INVALID_HANDLE -1 + +/** +* @brief Mount WL for defined partition +* +* @param partition that will be used for access +* @param out_handle handle of the WL instance +* +* @return +* - ESP_OK, if the allocation was successfully; +* - ESP_ERR_INVALID_ARG, if WL allocation was unsuccessful; +* - ESP_ERR_NO_MEM, if there was no memory to allocate WL components; +*/ +esp_err_t wl_mount(const esp_partition_t *partition, wl_handle_t *out_handle); + +/** +* @brief Unmount WL for defined partition +* +* @param handle WL partition handle +* +* @return +* - ESP_OK, if the operation completed successfully; +* - or one of error codes from lower-level flash driver. +*/ +esp_err_t wl_unmount(wl_handle_t handle); + +/** +* @brief Erase part of the WL storage +* +* @param handle WL handle that are related to the partition +* @param start_addr Address where erase operation should start. Must be aligned +* to the result of function wl_sector_size(...). +* @param size Size of the range which should be erased, in bytes. +* Must be divisible by result of function wl_sector_size(...).. +* +* @return +* - ESP_OK, if the range was erased successfully; +* - ESP_ERR_INVALID_ARG, if iterator or dst are NULL; +* - ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; +* - or one of error codes from lower-level flash driver. +*/ +esp_err_t wl_erase_range(wl_handle_t handle, size_t start_addr, size_t size); + +/** +* @brief Write data to the WL storage +* +* Before writing data to flash, corresponding region of flash needs to be erased. +* This can be done using wl_erase_range function. +* +* @param handle WL handle that are related to the partition +* @param dest_addr Address where the data should be written, relative to the +* beginning of the partition. +* @param src Pointer to the source buffer. Pointer must be non-NULL and +* buffer must be at least 'size' bytes long. +* @param size Size of data to be written, in bytes. +* +* @note Prior to writing to WL storage, make sure it has been erased with +* wl_erase_range call. +* +* @return +* - ESP_OK, if data was written successfully; +* - ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; +* - ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; +* - or one of error codes from lower-level flash driver. +*/ +esp_err_t wl_write(wl_handle_t handle, size_t dest_addr, const void *src, size_t size); + +/** +* @brief Read data from the WL storage +* +* @param handle WL module instance that was initialized before +* @param dest Pointer to the buffer where data should be stored. +* Pointer must be non-NULL and buffer must be at least 'size' bytes long. +* @param src_addr Address of the data to be read, relative to the +* beginning of the partition. +* @param size Size of data to be read, in bytes. +* +* @return +* - ESP_OK, if data was read successfully; +* - ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; +* - ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; +* - or one of error codes from lower-level flash driver. +*/ +esp_err_t wl_read(wl_handle_t handle, size_t src_addr, void *dest, size_t size); + +/** +* @brief Get size of the WL storage +* +* @param handle WL module handle that was initialized before +* @return usable size, in bytes +*/ +size_t wl_size(wl_handle_t handle); + +/** +* @brief Get sector size of the WL instance +* +* @param handle WL module handle that was initialized before +* @return sector size, in bytes +*/ +size_t wl_sector_size(wl_handle_t handle); + + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // _wear_levelling_H_ diff --git a/tools/sdk/include/wifi_provisioning/wifi_provisioning/wifi_config.h b/tools/sdk/include/wifi_provisioning/wifi_provisioning/wifi_config.h new file mode 100644 index 00000000000..2fa64448d49 --- /dev/null +++ b/tools/sdk/include/wifi_provisioning/wifi_provisioning/wifi_config.h @@ -0,0 +1,144 @@ +// 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 _WIFI_PROV_CONFIG_H_ +#define _WIFI_PROV_CONFIG_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief WiFi STA status for conveying back to the provisioning master + */ +typedef enum { + WIFI_PROV_STA_CONNECTING, + WIFI_PROV_STA_CONNECTED, + WIFI_PROV_STA_DISCONNECTED +} wifi_prov_sta_state_t; + +/** + * @brief WiFi STA connection fail reason + */ +typedef enum { + WIFI_PROV_STA_AUTH_ERROR, + WIFI_PROV_STA_AP_NOT_FOUND +} wifi_prov_sta_fail_reason_t; + +/** + * @brief WiFi STA connected status information + */ +typedef struct { + /** + * IP Address received by station + */ + char ip_addr[IP4ADDR_STRLEN_MAX]; + + char bssid[6]; /*!< BSSID of the AP to which connection was estalished */ + char ssid[33]; /*!< SSID of the to which connection was estalished */ + uint8_t channel; /*!< Channel of the AP */ + uint8_t auth_mode; /*!< Authorization mode of the AP */ +} wifi_prov_sta_conn_info_t; + +/** + * @brief WiFi status data to be sent in response to `get_status` request from master + */ +typedef struct { + wifi_prov_sta_state_t wifi_state; /*!< WiFi state of the station */ + union { + /** + * Reason for disconnection (valid only when `wifi_state` is `WIFI_STATION_DISCONNECTED`) + */ + wifi_prov_sta_fail_reason_t fail_reason; + + /** + * Connection information (valid only when `wifi_state` is `WIFI_STATION_CONNECTED`) + */ + wifi_prov_sta_conn_info_t conn_info; + }; +} wifi_prov_config_get_data_t; + +/** + * @brief WiFi config data received by slave during `set_config` request from master + */ +typedef struct { + char ssid[33]; /*!< SSID of the AP to which the slave is to be connected */ + char password[64]; /*!< Password of the AP */ + char bssid[6]; /*!< BSSID of the AP */ + uint8_t channel; /*!< Channel of the AP */ +} wifi_prov_config_set_data_t; + +/** + * @brief Type of context data passed to each get/set/apply handler + * function set in `wifi_prov_config_handlers` structure. + * + * This is passed as an opaque pointer, thereby allowing it be defined + * later in application code as per requirements. + */ +typedef struct wifi_prov_ctx wifi_prov_ctx_t; + +/** + * @brief Internal handlers for receiving and responding to protocomm + * requests from master + * + * This is to be passed as priv_data for protocomm request handler + * (refer to `wifi_prov_config_data_handler()`) when calling `protocomm_add_endpoint()`. + */ +typedef struct wifi_prov_config_handlers { + /** + * Handler function called when connection status + * of the slave (in WiFi station mode) is requested + */ + esp_err_t (*get_status_handler)(wifi_prov_config_get_data_t *resp_data, + wifi_prov_ctx_t **ctx); + + /** + * Handler function called when WiFi connection configuration + * (eg. AP SSID, password, etc.) of the slave (in WiFi station mode) + * is to be set to user provided values + */ + esp_err_t (*set_config_handler)(const wifi_prov_config_set_data_t *req_data, + wifi_prov_ctx_t **ctx); + + /** + * Handler function for applying the configuration that was set in + * `set_config_handler`. After applying the station may get connected to + * the AP or may fail to connect. The slave must be ready to convey the + * updated connection status information when `get_status_handler` is + * invoked again by the master. + */ + esp_err_t (*apply_config_handler)(wifi_prov_ctx_t **ctx); + + /** + * Context pointer to be passed to above handler functions upon invocation + */ + wifi_prov_ctx_t *ctx; +} wifi_prov_config_handlers_t; + +/** + * @brief Handler for receiving and responding to requests from master + * + * This is to be registered as the `wifi_config` endpoint handler + * (protocomm `protocomm_req_handler_t`) using `protocomm_add_endpoint()` + */ +esp_err_t wifi_prov_config_data_handler(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, + uint8_t **outbuf, ssize_t *outlen, void *priv_data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/wpa_supplicant/crypto/crypto.h b/tools/sdk/include/wpa_supplicant/crypto/crypto.h index b8877993df8..f6b7b2f2c49 100644 --- a/tools/sdk/include/wpa_supplicant/crypto/crypto.h +++ b/tools/sdk/include/wpa_supplicant/crypto/crypto.h @@ -27,6 +27,8 @@ #ifndef CRYPTO_H #define CRYPTO_H +#include "common.h" + /** * md4_vector - MD4 hash for data vector * @num_elem: Number of elements in the data vector @@ -604,4 +606,363 @@ int __must_check fast_crypto_mod_exp(const uint8_t *base, size_t base_len, int rc4_skip(const u8 *key, size_t keylen, size_t skip, u8 *data, size_t data_len); + +/** + * crypto_get_random - Generate cryptographically strong pseudy-random bytes + * @buf: Buffer for data + * @len: Number of bytes to generate + * Returns: 0 on success, -1 on failure + * + * If the PRNG does not have enough entropy to ensure unpredictable byte + * sequence, this functions must return -1. + */ +int crypto_get_random(void *buf, size_t len); + + +/** + * struct crypto_bignum - bignum + * + * Internal data structure for bignum implementation. The contents is specific + * to the used crypto library. + */ +struct crypto_bignum; + +/** + * crypto_bignum_init - Allocate memory for bignum + * Returns: Pointer to allocated bignum or %NULL on failure + */ +struct crypto_bignum * crypto_bignum_init(void); + +/** + * crypto_bignum_init_set - Allocate memory for bignum and set the value + * @buf: Buffer with unsigned binary value + * @len: Length of buf in octets + * Returns: Pointer to allocated bignum or %NULL on failure + */ +struct crypto_bignum * crypto_bignum_init_set(const u8 *buf, size_t len); + +/** + * crypto_bignum_deinit - Free bignum + * @n: Bignum from crypto_bignum_init() or crypto_bignum_init_set() + * @clear: Whether to clear the value from memory + */ +void crypto_bignum_deinit(struct crypto_bignum *n, int clear); + +/** + * crypto_bignum_to_bin - Set binary buffer to unsigned bignum + * @a: Bignum + * @buf: Buffer for the binary number + * @len: Length of @buf in octets + * @padlen: Length in octets to pad the result to or 0 to indicate no padding + * Returns: Number of octets written on success, -1 on failure + */ +int crypto_bignum_to_bin(const struct crypto_bignum *a, + u8 *buf, size_t buflen, size_t padlen); + +/** + * crypto_bignum_add - c = a + b + * @a: Bignum + * @b: Bignum + * @c: Bignum; used to store the result of a + b + * Returns: 0 on success, -1 on failure + */ +int crypto_bignum_add(const struct crypto_bignum *a, + const struct crypto_bignum *b, + struct crypto_bignum *c); + +/** + * crypto_bignum_mod - c = a % b + * @a: Bignum + * @b: Bignum + * @c: Bignum; used to store the result of a % b + * Returns: 0 on success, -1 on failure + */ +int crypto_bignum_mod(const struct crypto_bignum *a, + const struct crypto_bignum *b, + struct crypto_bignum *c); + +/** + * crypto_bignum_exptmod - Modular exponentiation: d = a^b (mod c) + * @a: Bignum; base + * @b: Bignum; exponent + * @c: Bignum; modulus + * @d: Bignum; used to store the result of a^b (mod c) + * Returns: 0 on success, -1 on failure + */ +int crypto_bignum_exptmod(const struct crypto_bignum *a, + const struct crypto_bignum *b, + const struct crypto_bignum *c, + struct crypto_bignum *d); + +/** + * crypto_bignum_inverse - Inverse a bignum so that a * c = 1 (mod b) + * @a: Bignum + * @b: Bignum + * @c: Bignum; used to store the result + * Returns: 0 on success, -1 on failure + */ +int crypto_bignum_inverse(const struct crypto_bignum *a, + const struct crypto_bignum *b, + struct crypto_bignum *c); + +/** + * crypto_bignum_sub - c = a - b + * @a: Bignum + * @b: Bignum + * @c: Bignum; used to store the result of a - b + * Returns: 0 on success, -1 on failure + */ +int crypto_bignum_sub(const struct crypto_bignum *a, + const struct crypto_bignum *b, + struct crypto_bignum *c); + +/** + * crypto_bignum_div - c = a / b + * @a: Bignum + * @b: Bignum + * @c: Bignum; used to store the result of a / b + * Returns: 0 on success, -1 on failure + */ +int crypto_bignum_div(const struct crypto_bignum *a, + const struct crypto_bignum *b, + struct crypto_bignum *c); + +/** + * crypto_bignum_mulmod - d = a * b (mod c) + * @a: Bignum + * @b: Bignum + * @c: Bignum + * @d: Bignum; used to store the result of (a * b) % c + * Returns: 0 on success, -1 on failure + */ +int crypto_bignum_mulmod(const struct crypto_bignum *a, + const struct crypto_bignum *b, + const struct crypto_bignum *c, + struct crypto_bignum *d); + +/** + * crypto_bignum_cmp - Compare two bignums + * @a: Bignum + * @b: Bignum + * Returns: -1 if a < b, 0 if a == b, or 1 if a > b + */ +int crypto_bignum_cmp(const struct crypto_bignum *a, + const struct crypto_bignum *b); + +/** + * crypto_bignum_bits - Get size of a bignum in bits + * @a: Bignum + * Returns: Number of bits in the bignum + */ +int crypto_bignum_bits(const struct crypto_bignum *a); + +/** + * crypto_bignum_is_zero - Is the given bignum zero + * @a: Bignum + * Returns: 1 if @a is zero or 0 if not + */ +int crypto_bignum_is_zero(const struct crypto_bignum *a); + +/** + * crypto_bignum_is_one - Is the given bignum one + * @a: Bignum + * Returns: 1 if @a is one or 0 if not + */ +int crypto_bignum_is_one(const struct crypto_bignum *a); + +/** + * crypto_bignum_legendre - Compute the Legendre symbol (a/p) + * @a: Bignum + * @p: Bignum + * Returns: Legendre symbol -1,0,1 on success; -2 on calculation failure + */ +int crypto_bignum_legendre(const struct crypto_bignum *a, + const struct crypto_bignum *p); + + +/** + * struct crypto_ec - Elliptic curve context + * + * Internal data structure for EC implementation. The contents is specific + * to the used crypto library. + */ +struct crypto_ec; + +/** + * crypto_ec_init - Initialize elliptic curve context + * @group: Identifying number for the ECC group (IANA "Group Description" + * attribute registrty for RFC 2409) + * Returns: Pointer to EC context or %NULL on failure + */ +struct crypto_ec * crypto_ec_init(int group); + +/** + * crypto_ec_deinit - Deinitialize elliptic curve context + * @e: EC context from crypto_ec_init() + */ +void crypto_ec_deinit(struct crypto_ec *e); + +/** + * crypto_ec_prime_len - Get length of the prime in octets + * @e: EC context from crypto_ec_init() + * Returns: Length of the prime defining the group + */ +size_t crypto_ec_prime_len(struct crypto_ec *e); + +/** + * crypto_ec_prime_len_bits - Get length of the prime in bits + * @e: EC context from crypto_ec_init() + * Returns: Length of the prime defining the group in bits + */ +size_t crypto_ec_prime_len_bits(struct crypto_ec *e); + +/** + * crypto_ec_get_prime - Get prime defining an EC group + * @e: EC context from crypto_ec_init() + * Returns: Prime (bignum) defining the group + */ +const struct crypto_bignum * crypto_ec_get_prime(struct crypto_ec *e); + +/** + * crypto_ec_get_order - Get order of an EC group + * @e: EC context from crypto_ec_init() + * Returns: Order (bignum) of the group + */ +const struct crypto_bignum * crypto_ec_get_order(struct crypto_ec *e); + +/** + * struct crypto_ec_point - Elliptic curve point + * + * Internal data structure for EC implementation to represent a point. The + * contents is specific to the used crypto library. + */ +struct crypto_ec_point; + +/** + * crypto_ec_point_init - Initialize data for an EC point + * @e: EC context from crypto_ec_init() + * Returns: Pointer to EC point data or %NULL on failure + */ +struct crypto_ec_point * crypto_ec_point_init(struct crypto_ec *e); + +/** + * crypto_ec_point_deinit - Deinitialize EC point data + * @p: EC point data from crypto_ec_point_init() + * @clear: Whether to clear the EC point value from memory + */ +void crypto_ec_point_deinit(struct crypto_ec_point *p, int clear); + +/** + * crypto_ec_point_to_bin - Write EC point value as binary data + * @e: EC context from crypto_ec_init() + * @p: EC point data from crypto_ec_point_init() + * @x: Buffer for writing the binary data for x coordinate or %NULL if not used + * @y: Buffer for writing the binary data for y coordinate or %NULL if not used + * Returns: 0 on success, -1 on failure + * + * This function can be used to write an EC point as binary data in a format + * that has the x and y coordinates in big endian byte order fields padded to + * the length of the prime defining the group. + */ +int crypto_ec_point_to_bin(struct crypto_ec *e, + const struct crypto_ec_point *point, u8 *x, u8 *y); + +/** + * crypto_ec_point_from_bin - Create EC point from binary data + * @e: EC context from crypto_ec_init() + * @val: Binary data to read the EC point from + * Returns: Pointer to EC point data or %NULL on failure + * + * This function readers x and y coordinates of the EC point from the provided + * buffer assuming the values are in big endian byte order with fields padded to + * the length of the prime defining the group. + */ +struct crypto_ec_point * crypto_ec_point_from_bin(struct crypto_ec *e, + const u8 *val); + +/** + * crypto_bignum_add - c = a + b + * @e: EC context from crypto_ec_init() + * @a: Bignum + * @b: Bignum + * @c: Bignum; used to store the result of a + b + * Returns: 0 on success, -1 on failure + */ +int crypto_ec_point_add(struct crypto_ec *e, const struct crypto_ec_point *a, + const struct crypto_ec_point *b, + struct crypto_ec_point *c); + +/** + * crypto_bignum_mul - res = b * p + * @e: EC context from crypto_ec_init() + * @p: EC point + * @b: Bignum + * @res: EC point; used to store the result of b * p + * Returns: 0 on success, -1 on failure + */ +int crypto_ec_point_mul(struct crypto_ec *e, const struct crypto_ec_point *p, + const struct crypto_bignum *b, + struct crypto_ec_point *res); + +/** + * crypto_ec_point_invert - Compute inverse of an EC point + * @e: EC context from crypto_ec_init() + * @p: EC point to invert (and result of the operation) + * Returns: 0 on success, -1 on failure + */ +int crypto_ec_point_invert(struct crypto_ec *e, struct crypto_ec_point *p); + +/** + * crypto_ec_point_solve_y_coord - Solve y coordinate for an x coordinate + * @e: EC context from crypto_ec_init() + * @p: EC point to use for the returning the result + * @x: x coordinate + * @y_bit: y-bit (0 or 1) for selecting the y value to use + * Returns: 0 on success, -1 on failure + */ +int crypto_ec_point_solve_y_coord(struct crypto_ec *e, + struct crypto_ec_point *p, + const struct crypto_bignum *x, int y_bit); + +/** + * crypto_ec_point_compute_y_sqr - Compute y^2 = x^3 + ax + b + * @e: EC context from crypto_ec_init() + * @x: x coordinate + * Returns: y^2 on success, %NULL failure + */ +struct crypto_bignum * +crypto_ec_point_compute_y_sqr(struct crypto_ec *e, + const struct crypto_bignum *x); + +/** + * crypto_ec_point_is_at_infinity - Check whether EC point is neutral element + * @e: EC context from crypto_ec_init() + * @p: EC point + * Returns: 1 if the specified EC point is the neutral element of the group or + * 0 if not + */ +int crypto_ec_point_is_at_infinity(struct crypto_ec *e, + const struct crypto_ec_point *p); + +/** + * crypto_ec_point_is_on_curve - Check whether EC point is on curve + * @e: EC context from crypto_ec_init() + * @p: EC point + * Returns: 1 if the specified EC point is on the curve or 0 if not + */ +int crypto_ec_point_is_on_curve(struct crypto_ec *e, + const struct crypto_ec_point *p); + +/** + * crypto_ec_point_cmp - Compare two EC points + * @e: EC context from crypto_ec_init() + * @a: EC point + * @b: EC point + * Returns: 0 on equal, non-zero otherwise + */ +int crypto_ec_point_cmp(const struct crypto_ec *e, + const struct crypto_ec_point *a, + const struct crypto_ec_point *b); + + #endif /* CRYPTO_H */ diff --git a/tools/sdk/include/wpa_supplicant/crypto/dh_group5.h b/tools/sdk/include/wpa_supplicant/crypto/dh_group5.h index 595f1114fe2..f92c1115d5e 100644 --- a/tools/sdk/include/wpa_supplicant/crypto/dh_group5.h +++ b/tools/sdk/include/wpa_supplicant/crypto/dh_group5.h @@ -15,6 +15,8 @@ #ifndef DH_GROUP5_H #define DH_GROUP5_H +#include "wpa/wpabuf.h" + void * dh5_init(struct wpabuf **priv, struct wpabuf **publ); struct wpabuf * dh5_derive_shared(void *ctx, const struct wpabuf *peer_public, const struct wpabuf *own_private); diff --git a/tools/sdk/include/wpa_supplicant/crypto/md5.h b/tools/sdk/include/wpa_supplicant/crypto/md5.h index 8952590782a..6de3a5b5f1b 100644 --- a/tools/sdk/include/wpa_supplicant/crypto/md5.h +++ b/tools/sdk/include/wpa_supplicant/crypto/md5.h @@ -17,16 +17,16 @@ #define MD5_MAC_LEN 16 -int hmac_md5_vector(const u8 *key, size_t key_len, size_t num_elem, - const u8 *addr[], const size_t *len, u8 *mac); -int hmac_md5(const u8 *key, size_t key_len, const u8 *data, size_t data_len, - u8 *mac); +int hmac_md5_vector(const uint8_t *key, size_t key_len, size_t num_elem, + const uint8_t *addr[], const size_t *len, uint8_t *mac); +int hmac_md5(const uint8_t *key, size_t key_len, const uint8_t *data, size_t data_len, + uint8_t *mac); #ifdef CONFIG_FIPS -int hmac_md5_vector_non_fips_allow(const u8 *key, size_t key_len, - size_t num_elem, const u8 *addr[], - const size_t *len, u8 *mac); -int hmac_md5_non_fips_allow(const u8 *key, size_t key_len, const u8 *data, - size_t data_len, u8 *mac); +int hmac_md5_vector_non_fips_allow(const uint8_t *key, size_t key_len, + size_t num_elem, const uint8_t *addr[], + const size_t *len, uint8_t *mac); +int hmac_md5_non_fips_allow(const uint8_t *key, size_t key_len, const uint8_t *data, + size_t data_len, uint8_t *mac); #else /* CONFIG_FIPS */ #define hmac_md5_vector_non_fips_allow hmac_md5_vector #define hmac_md5_non_fips_allow hmac_md5 diff --git a/tools/sdk/include/wpa_supplicant/crypto/sha1.h b/tools/sdk/include/wpa_supplicant/crypto/sha1.h index b3d186bdbc3..65e3958fc68 100644 --- a/tools/sdk/include/wpa_supplicant/crypto/sha1.h +++ b/tools/sdk/include/wpa_supplicant/crypto/sha1.h @@ -17,17 +17,17 @@ #define SHA1_MAC_LEN 20 -int hmac_sha1_vector(const u8 *key, size_t key_len, size_t num_elem, - const u8 *addr[], const size_t *len, u8 *mac); -int hmac_sha1(const u8 *key, size_t key_len, const u8 *data, size_t data_len, - u8 *mac); -int sha1_prf(const u8 *key, size_t key_len, const char *label, - const u8 *data, size_t data_len, u8 *buf, size_t buf_len); -int sha1_t_prf(const u8 *key, size_t key_len, const char *label, - const u8 *seed, size_t seed_len, u8 *buf, size_t buf_len); -//int __must_check tls_prf(const u8 *secret, size_t secret_len, -// const char *label, const u8 *seed, size_t seed_len, -// u8 *out, size_t outlen); +int hmac_sha1_vector(const uint8_t *key, size_t key_len, size_t num_elem, + const uint8_t *addr[], const size_t *len, uint8_t *mac); +int hmac_sha1(const uint8_t *key, size_t key_len, const uint8_t *data, size_t data_len, + uint8_t *mac); +int sha1_prf(const uint8_t *key, size_t key_len, const char *label, + const uint8_t *data, size_t data_len, uint8_t *buf, size_t buf_len); +int sha1_t_prf(const uint8_t *key, size_t key_len, const char *label, + const uint8_t *seed, size_t seed_len, uint8_t *buf, size_t buf_len); +//int __must_check tls_prf(const uint8_t *secret, size_t secret_len, +// const char *label, const uint8_t *seed, size_t seed_len, +// uint8_t *out, size_t outlen); int pbkdf2_sha1(const char *passphrase, const char *ssid, size_t ssid_len, - int iterations, u8 *buf, size_t buflen); + int iterations, uint8_t *buf, size_t buflen); #endif /* SHA1_H */ diff --git a/tools/sdk/include/wpa_supplicant/endian.h b/tools/sdk/include/wpa_supplicant/endian.h index 5e6a876fda3..1e2453f1645 100644 --- a/tools/sdk/include/wpa_supplicant/endian.h +++ b/tools/sdk/include/wpa_supplicant/endian.h @@ -29,6 +29,7 @@ #ifndef _ENDIAN_H_ #define _ENDIAN_H_ +#include #include "byteswap.h" #ifndef BIG_ENDIAN diff --git a/tools/sdk/include/wpa_supplicant/os.h b/tools/sdk/include/wpa_supplicant/os.h index e6da894e92b..0028c21e9cb 100644 --- a/tools/sdk/include/wpa_supplicant/os.h +++ b/tools/sdk/include/wpa_supplicant/os.h @@ -18,8 +18,9 @@ #include #include #include +#include "esp_err.h" #include "rom/ets_sys.h" -#include "lwip/mem.h" + typedef long os_time_t; /** @@ -201,6 +202,10 @@ char * os_readfile(const char *name, size_t *len); #define os_free(p) free((p)) #endif +#ifndef os_bzero +#define os_bzero(s, n) bzero(s, n) +#endif + #ifndef os_strdup #ifdef _MSC_VER @@ -265,7 +270,7 @@ char * ets_strdup(const char *s); #ifdef _MSC_VER #define os_snprintf _snprintf #else -#define os_snprintf vsnprintf +#define os_snprintf snprintf #endif #endif diff --git a/tools/sdk/include/wpa_supplicant/wpa/list.h b/tools/sdk/include/wpa_supplicant/wpa/list.h index c8dccee83dd..a67a04966c6 100644 --- a/tools/sdk/include/wpa_supplicant/wpa/list.h +++ b/tools/sdk/include/wpa_supplicant/wpa/list.h @@ -15,6 +15,8 @@ #ifndef LIST_H #define LIST_H +#include + /** * struct dl_list - Doubly-linked list */ diff --git a/tools/sdk/include/wpa_supplicant/wpa/wpa.h b/tools/sdk/include/wpa_supplicant/wpa/wpa.h index 2a1adfc5671..9d50bb1ba57 100644 --- a/tools/sdk/include/wpa_supplicant/wpa/wpa.h +++ b/tools/sdk/include/wpa_supplicant/wpa/wpa.h @@ -15,15 +15,11 @@ #ifndef WPA_H #define WPA_H -#include "c_types.h" -#include "os_type.h" +#include "rom/ets_sys.h" #include "common.h" -#include "ets_sys.h" #include "wpa/defs.h" #include "wpa/wpa_common.h" -//#include "net80211/ieee80211_var.h" -//#include "net80211/ieee80211_node.h" #define WPA_SM_STATE(_sm) ((_sm)->wpa_state) @@ -51,10 +47,6 @@ struct wpa_sm { u8 pmk[PMK_LEN]; size_t pmk_len; -// char *passphrase; //wlan password -// u8 *ssid; //wlan network name -// size_t ssid_len; - struct wpa_ptk ptk, tptk; int ptk_set, tptk_set; u8 snonce[WPA_NONCE_LEN]; @@ -64,8 +56,6 @@ struct wpa_sm { int rx_replay_counter_set; u8 request_counter[WPA_REPLAY_COUNTER_LEN]; -// void *network_ctx; - unsigned int pairwise_cipher; unsigned int group_cipher; unsigned int key_mgmt; @@ -74,7 +64,7 @@ struct wpa_sm { int rsn_enabled; /* Whether RSN is enabled in configuration */ int countermeasures; /*TKIP countermeasures state flag, 1:in countermeasures state*/ - os_timer_t cm_timer; + ETSTimer cm_timer; u8 *assoc_wpa_ie; /* Own WPA/RSN IE from (Re)AssocReq */ size_t assoc_wpa_ie_len; @@ -95,21 +85,17 @@ struct wpa_sm { struct install_key install_ptk; struct install_key install_gtk; int key_entry_valid; //present current avaliable entry for bssid, for pairkey:0,5,10,15,20, gtk: pairkey_no+i (i:1~4) - -// char *msg; //send eapol msg buff -// size_t msg_len; //msg length:6 + sizeof(eth) + data_len -// struct netif *ifp; struct pbuf *pb; void (* sendto) (struct pbuf *pb); - void (*config_assoc_ie) (uint8 proto, u8 *assoc_buf, u32 assoc_wpa_ie_len); - void (*install_ppkey) (enum wpa_alg alg, uint8 *addr, int key_idx, int set_tx, - uint8 *seq, size_t seq_len, uint8 *key, size_t key_len, int key_entry_valid); - void (*wpa_deauthenticate)(uint8 reason_code); + void (*config_assoc_ie) (u8 proto, u8 *assoc_buf, u32 assoc_wpa_ie_len); + void (*install_ppkey) (enum wpa_alg alg, u8 *addr, int key_idx, int set_tx, + u8 *seq, unsigned int seq_len, u8 *key, unsigned int key_len, int key_entry_valid); + void (*wpa_deauthenticate)(u8 reason_code); void (*wpa_neg_complete)(); struct wpa_gtk_data gd; //used for calllback save param - uint16 key_info; //used for txcallback param + u16 key_info; //used for txcallback param }; struct l2_ethhdr { @@ -185,9 +171,9 @@ struct l2_ethhdr { #define KEYENTRY_TABLE_MAP(key_entry_valid) ((key_entry_valid)%5) -void pp_michael_mic_failure(uint16 isunicast); - void wpa_sm_set_state(enum wpa_states state); +char * dup_binstr(const void *src, size_t len); + #endif /* WPA_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa/wpa_debug.h b/tools/sdk/include/wpa_supplicant/wpa/wpa_debug.h index b78a657e05c..10fe928c3eb 100644 --- a/tools/sdk/include/wpa_supplicant/wpa/wpa_debug.h +++ b/tools/sdk/include/wpa_supplicant/wpa/wpa_debug.h @@ -15,8 +15,22 @@ #ifndef WPA_DEBUG_H #define WPA_DEBUG_H +#include "wpabuf.h" +#include "esp_log.h" +#ifdef ESPRESSIF_USE + +#define TAG "wpa" + +#define MSG_ERROR ESP_LOG_ERROR +#define MSG_WARNING ESP_LOG_WARN +#define MSG_INFO ESP_LOG_INFO +#define MSG_DEBUG ESP_LOG_DEBUG +#define MSG_MSGDUMP ESP_LOG_VERBOSE + +#else enum { MSG_MSGDUMP, MSG_DEBUG, MSG_INFO, MSG_WARNING, MSG_ERROR }; +#endif /** EAP authentication completed successfully */ #define WPA_EVENT_EAP_SUCCESS "CTRL-EVENT-EAP-SUCCESS " @@ -44,8 +58,8 @@ void wpa_debug_print_timestamp(void); * * Note: New line '\n' is added to the end of the text when printing to stdout. */ -//#define DEBUG_PRINT -//#define MSG_PRINT +#define DEBUG_PRINT +#define MSG_PRINT /** * wpa_hexdump - conditional hex dump @@ -59,7 +73,7 @@ void wpa_debug_print_timestamp(void); * configuration. The contents of buf is printed out has hex dump. */ #ifdef DEBUG_PRINT -#define wpa_printf(level,fmt, args...) ets_printf(fmt,## args) +#define wpa_printf(level,fmt, args...) ESP_LOG_LEVEL_LOCAL(level, TAG, fmt, ##args) static inline void wpa_hexdump_ascii(int level, const char *title, const u8 *buf, size_t len) { diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap.h index e2cd2dd81d5..9e1c3efa94f 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap.h @@ -10,15 +10,45 @@ #define EAP_H #include "wpa/defs.h" -#include "eap/eap_defs.h" +#include "wpa2/eap_peer/eap_defs.h" struct eap_sm; struct eap_method_type { int vendor; - u32 method; + EapType method; }; +u8 *g_wpa_anonymous_identity; +int g_wpa_anonymous_identity_len; +u8 *g_wpa_username; +int g_wpa_username_len; +const u8 *g_wpa_client_cert; +int g_wpa_client_cert_len; +const u8 *g_wpa_private_key; +int g_wpa_private_key_len; +const u8 *g_wpa_private_key_passwd; +int g_wpa_private_key_passwd_len; + +const u8 *g_wpa_ca_cert; +int g_wpa_ca_cert_len; + +u8 *g_wpa_password; +int g_wpa_password_len; + +u8 *g_wpa_new_password; +int g_wpa_new_password_len; + const u8 * eap_get_eapKeyData(struct eap_sm *sm, size_t *len); +void eap_deinit_prev_method(struct eap_sm *sm, const char *txt); +struct wpabuf * eap_sm_build_nak(struct eap_sm *sm, EapType type, u8 id); +int eap_peer_blob_init(struct eap_sm *sm); +void eap_peer_blob_deinit(struct eap_sm *sm); +int eap_peer_config_init( + struct eap_sm *sm, u8 *private_key_passwd, + int private_key_passwd_len); +void eap_peer_config_deinit(struct eap_sm *sm); +void eap_sm_abort(struct eap_sm *sm); +int eap_peer_register_methods(void); #endif /* EAP_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_config.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_config.h index f35cbf43d76..f95dcda3a12 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_config.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_config.h @@ -26,6 +26,10 @@ struct eap_peer_config { */ size_t identity_len; + u8 *anonymous_identity; + + size_t anonymous_identity_len; + /** * password - Password string for EAP * @@ -139,8 +143,29 @@ struct eap_peer_config { */ u8 *private_key_passwd; + /** + * Phase 2 + */ + u8 *ca_cert2; + + u8 *ca_path2; + + u8 *client_cert2; + + u8 *private_key2; + + u8 *private_key2_password; + + /** + * eap_methods - Allowed EAP methods + */ + struct eap_method_type *eap_methods; + + char *phase1; + char *phase2; + /** * pin - PIN for USIM, GSM SIM, and smartcards * @@ -152,6 +177,10 @@ struct eap_peer_config { */ char *pin; + int mschapv2_retry; + u8 *new_password; + size_t new_password_len; + /** * fragment_size - Maximum EAP fragment size in bytes (default 1398) * @@ -204,7 +233,7 @@ struct wpa_config_blob { /** * data - Pointer to binary data */ - u8 *data; + const u8 *data; /** * len - Length of binary data diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_i.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_i.h index a4779d13f82..6adf5ec7e35 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_i.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_i.h @@ -13,6 +13,7 @@ #include "eap.h" #include "eap_common.h" #include "eap_config.h" +#include "esp_wpa2.h" /* RFC 4137 - EAP Peer state machine */ @@ -54,11 +55,55 @@ struct eap_method_ret { Boolean allowNotifications; }; +struct eap_sm; + +struct eap_method { + /** + * vendor -EAP Vendor-ID + */ + int vendor; + + /** + * method - EAP type number + */ + EapType method; + + /** + * name - Name of the method (e.g., "TLS") + */ + const char *name; + + struct eap_method *next; + + void * (*init)(struct eap_sm *sm); + void (*deinit)(struct eap_sm *sm, void *priv); + struct wpabuf * (*process)(struct eap_sm *sm, void *priv, + struct eap_method_ret *ret, + const struct wpabuf *reqData); + bool (*isKeyAvailable)(struct eap_sm *sm, void *priv); + u8 * (*getKey)(struct eap_sm *sm, void *priv, size_t *len); + int (*get_status)(struct eap_sm *sm, void *priv, char *buf, + size_t buflen, int verbose); + const u8 * (*get_identity)(struct eap_sm *sm, void *priv, size_t *len); + void (*free)(struct eap_method *method); + bool (*has_reauth_data)(struct eap_sm *sm, void *priv); + void (*deinit_for_reauth)(struct eap_sm *sm, void *priv); + void * (*init_for_reauth)(struct eap_sm *sm, void *priv); + u8 * (*getSessionId)(struct eap_sm *sm, void *priv, size_t *len); +}; + #define CLIENT_CERT_NAME "CLC" #define CA_CERT_NAME "CAC" #define PRIVATE_KEY_NAME "PVK" #define BLOB_NAME_LEN 3 -#define BLOB_NUM 2 +#define BLOB_NUM 3 + +enum SIG_WPA2 { + SIG_WPA2_START = 0, + SIG_WPA2_RX, + SIG_WPA2_TASK_DEL, + SIG_WPA2_MAX, +}; /** * struct eap_sm - EAP state machine data @@ -76,13 +121,29 @@ struct eap_sm { u8 current_identifier; u8 ownaddr[ETH_ALEN]; #ifdef USE_WPA2_TASK -#define SIG_WPA2_NUM 2 - u8 wpa2_sig_cnt[SIG_WPA2_NUM]; + u8 wpa2_sig_cnt[SIG_WPA2_MAX]; #endif u8 finish_state; + + int init_phase2; + bool peap_done; + + u8 *eapKeyData; + size_t eapKeyDataLen; + struct wpabuf *lastRespData; + const struct eap_method *m; }; +wpa2_crypto_funcs_t wpa2_crypto_funcs; + +const u8 * eap_get_config_identity(struct eap_sm *sm, size_t *len); +const u8 * eap_get_config_password(struct eap_sm *sm, size_t *len); +const u8 * eap_get_config_password2(struct eap_sm *sm, size_t *len, int *hash); +const u8 * eap_get_config_new_password(struct eap_sm *sm, size_t *len); struct eap_peer_config * eap_get_config(struct eap_sm *sm); const struct wpa_config_blob * eap_get_config_blob(struct eap_sm *sm, const char *name); +bool wifi_sta_get_enterprise_disable_time_check(void); + +struct wpabuf * eap_sm_build_identity_resp(struct eap_sm *sm, u8 id, int encrypted); #endif /* EAP_I_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_methods.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_methods.h new file mode 100644 index 00000000000..7d518dec2ce --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_methods.h @@ -0,0 +1,39 @@ +/* + * EAP peer: Method registration + * Copyright (c) 2004-2007, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef EAP_METHODS_H +#define EAP_METHODS_H + +#include "eap_defs.h" +#include "eap_config.h" + +const struct eap_method * eap_peer_get_eap_method(int vendor, EapType method); +const struct eap_method * eap_peer_get_methods(size_t *count); + +u32 eap_get_phase2_type(const char *name, int *vendor); +struct eap_method_type * eap_get_phase2_types(struct eap_peer_config *config, + size_t *count); + +struct eap_method * eap_peer_method_alloc(int verdor, EapType method, + const char *name); + +void eap_peer_method_free(struct eap_method *method); +int eap_peer_method_register(struct eap_method *method); + +void eap_peer_unregister_methods(void); + +//int eap_peer_md5_register(void); +int eap_peer_tls_register(void); +int eap_peer_peap_register(void); +int eap_peer_ttls_register(void); +int eap_peer_mschapv2_register(void); + +void eap_peer_unregister_methods(void); +int eap_peer_register_methods(void); + +#endif /* EAP_METHODS_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_peap_common.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_peap_common.h new file mode 100644 index 00000000000..7aad0dff781 --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_peap_common.h @@ -0,0 +1,16 @@ +/* + * EAP-PEAP common routines + * Copyright (c) 2008-2011, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef EAP_PEAP_COMMON_H +#define EAP_PEAP_COMMON_H + +int peap_prfplus(int version, const u8 *key, size_t key_len, + const char *label, const u8 *seed, size_t seed_len, + u8 *buf, size_t buf_len); + +#endif /* EAP_PEAP_COMMON_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_tlv_common.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_tlv_common.h new file mode 100644 index 00000000000..3286055ab7b --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_tlv_common.h @@ -0,0 +1,112 @@ +/* + * EAP-TLV definitions (draft-josefsson-pppext-eap-tls-eap-10.txt) + * Copyright (c) 2004-2008, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef EAP_TLV_COMMON_H +#define EAP_TLV_COMMON_H + +/* EAP-TLV TLVs (draft-josefsson-ppext-eap-tls-eap-10.txt) */ +#define EAP_TLV_RESULT_TLV 3 /* Acknowledged Result */ +#define EAP_TLV_NAK_TLV 4 +#define EAP_TLV_ERROR_CODE_TLV 5 +#define EAP_TLV_CONNECTION_BINDING_TLV 6 +#define EAP_TLV_VENDOR_SPECIFIC_TLV 7 +#define EAP_TLV_URI_TLV 8 +#define EAP_TLV_EAP_PAYLOAD_TLV 9 +#define EAP_TLV_INTERMEDIATE_RESULT_TLV 10 +#define EAP_TLV_PAC_TLV 11 /* RFC 5422, Section 4.2 */ +#define EAP_TLV_CRYPTO_BINDING_TLV 12 +#define EAP_TLV_CALLING_STATION_ID_TLV 13 +#define EAP_TLV_CALLED_STATION_ID_TLV 14 +#define EAP_TLV_NAS_PORT_TYPE_TLV 15 +#define EAP_TLV_SERVER_IDENTIFIER_TLV 16 +#define EAP_TLV_IDENTITY_TYPE_TLV 17 +#define EAP_TLV_SERVER_TRUSTED_ROOT_TLV 18 +#define EAP_TLV_REQUEST_ACTION_TLV 19 +#define EAP_TLV_PKCS7_TLV 20 + +#define EAP_TLV_RESULT_SUCCESS 1 +#define EAP_TLV_RESULT_FAILURE 2 + +#define EAP_TLV_TYPE_MANDATORY 0x8000 +#define EAP_TLV_TYPE_MASK 0x3fff + +#ifdef _MSC_VER +#pragma pack(push, 1) +#endif /* _MSC_VER */ + +struct eap_tlv_hdr { + be16 tlv_type; + be16 length; +} STRUCT_PACKED; + +struct eap_tlv_nak_tlv { + be16 tlv_type; + be16 length; + be32 vendor_id; + be16 nak_type; +} STRUCT_PACKED; + +struct eap_tlv_result_tlv { + be16 tlv_type; + be16 length; + be16 status; +} STRUCT_PACKED; + +/* RFC 4851, Section 4.2.7 - Intermediate-Result TLV */ +struct eap_tlv_intermediate_result_tlv { + be16 tlv_type; + be16 length; + be16 status; + /* Followed by optional TLVs */ +} STRUCT_PACKED; + +/* RFC 4851, Section 4.2.8 - Crypto-Binding TLV */ +struct eap_tlv_crypto_binding_tlv { + be16 tlv_type; + be16 length; + u8 reserved; + u8 version; + u8 received_version; + u8 subtype; + u8 nonce[32]; + u8 compound_mac[20]; +} STRUCT_PACKED; + +struct eap_tlv_pac_ack_tlv { + be16 tlv_type; + be16 length; + be16 pac_type; + be16 pac_len; + be16 result; +} STRUCT_PACKED; + +/* RFC 4851, Section 4.2.9 - Request-Action TLV */ +struct eap_tlv_request_action_tlv { + be16 tlv_type; + be16 length; + be16 action; +} STRUCT_PACKED; + +/* RFC 5422, Section 4.2.6 - PAC-Type TLV */ +struct eap_tlv_pac_type_tlv { + be16 tlv_type; /* PAC_TYPE_PAC_TYPE */ + be16 length; + be16 pac_type; +} STRUCT_PACKED; + +#ifdef _MSC_VER +#pragma pack(pop) +#endif /* _MSC_VER */ + +#define EAP_TLV_CRYPTO_BINDING_SUBTYPE_REQUEST 0 +#define EAP_TLV_CRYPTO_BINDING_SUBTYPE_RESPONSE 1 + +#define EAP_TLV_ACTION_PROCESS_TLV 1 +#define EAP_TLV_ACTION_NEGOTIATE_EAP 2 + +#endif /* EAP_TLV_COMMON_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_ttls.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_ttls.h new file mode 100644 index 00000000000..17901d42db1 --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_ttls.h @@ -0,0 +1,65 @@ +/* + * EAP server/peer: EAP-TTLS (RFC 5281) + * Copyright (c) 2004-2007, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef EAP_TTLS_H +#define EAP_TTLS_H + +struct ttls_avp { + be32 avp_code; + be32 avp_length; /* 8-bit flags, 24-bit length; + * length includes AVP header */ + /* optional 32-bit Vendor-ID */ + /* Data */ +}; + +struct ttls_avp_vendor { + be32 avp_code; + be32 avp_length; /* 8-bit flags, 24-bit length; + * length includes AVP header */ + be32 vendor_id; + /* Data */ +}; + +#define AVP_FLAGS_VENDOR 0x80 +#define AVP_FLAGS_MANDATORY 0x40 + +#define AVP_PAD(start, pos) \ +do { \ + int __pad; \ + __pad = (4 - (((pos) - (start)) & 3)) & 3; \ + os_memset((pos), 0, __pad); \ + pos += __pad; \ +} while (0) + + +/* RFC 2865 */ +#define RADIUS_ATTR_USER_NAME 1 +#define RADIUS_ATTR_USER_PASSWORD 2 +#define RADIUS_ATTR_CHAP_PASSWORD 3 +#define RADIUS_ATTR_REPLY_MESSAGE 18 +#define RADIUS_ATTR_CHAP_CHALLENGE 60 +#define RADIUS_ATTR_EAP_MESSAGE 79 + +/* RFC 2548 */ +#define RADIUS_VENDOR_ID_MICROSOFT 311 +#define RADIUS_ATTR_MS_CHAP_RESPONSE 1 +#define RADIUS_ATTR_MS_CHAP_ERROR 2 +#define RADIUS_ATTR_MS_CHAP_NT_ENC_PW 6 +#define RADIUS_ATTR_MS_CHAP_CHALLENGE 11 +#define RADIUS_ATTR_MS_CHAP2_RESPONSE 25 +#define RADIUS_ATTR_MS_CHAP2_SUCCESS 26 +#define RADIUS_ATTR_MS_CHAP2_CPW 27 + +#define EAP_TTLS_MSCHAPV2_CHALLENGE_LEN 16 +#define EAP_TTLS_MSCHAPV2_RESPONSE_LEN 50 +#define EAP_TTLS_MSCHAP_CHALLENGE_LEN 8 +#define EAP_TTLS_MSCHAP_RESPONSE_LEN 50 +#define EAP_TTLS_CHAP_CHALLENGE_LEN 16 +#define EAP_TTLS_CHAP_PASSWORD_LEN 16 + +#endif /* EAP_TTLS_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/mschapv2.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/mschapv2.h new file mode 100644 index 00000000000..ef750819ffe --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/mschapv2.h @@ -0,0 +1,24 @@ +/* + * MSCHAPV2 + */ + + +#ifndef MSCHAPV2_H +#define MSCHAPV2_H + +#define MSCHAPV2_CHAL_LEN 16 +#define MSCHAPV2_NT_RESPONSE_LEN 24 +#define MSCHAPV2_AUTH_RESPONSE_LEN 20 +#define MSCHAPV2_MASTER_KEY_LEN 16 + +const u8 * mschapv2_remove_domain(const u8 *username, size_t *len); +int mschapv2_derive_response(const u8 *username, size_t username_len, + const u8 *password, size_t password_len, + int pwhash, + const u8 *auth_challenge, + const u8 *peer_challenge, + u8 *nt_response, u8 *auth_response, + u8 *master_key); +int mschapv2_verify_auth_response(const u8 *auth_response, + const u8 *buf, size_t buf_len); +#endif /* MSCHAPV2_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/tls/libtommath.h b/tools/sdk/include/wpa_supplicant/wpa2/tls/libtommath.h index c0409b5e33f..9be311e86a6 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/tls/libtommath.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/tls/libtommath.h @@ -13,7 +13,6 @@ * If CONFIG_INTERNAL_LIBTOMMATH is defined, bignum.c includes this * libtommath.c file instead of using the external LibTomMath library. */ -#include "c_types.h" #include "os.h" #include "stdarg.h" @@ -193,7 +192,7 @@ static int mp_mul_d (mp_int * a, mp_digit b, mp_int * c); /* reverse an array, used for radix code */ -static void ICACHE_FLASH_ATTR +static void bn_reverse (unsigned char *s, int len) { int ix, iy; @@ -212,7 +211,7 @@ bn_reverse (unsigned char *s, int len) /* low level addition, based on HAC pp.594, Algorithm 14.7 */ -static int ICACHE_FLASH_ATTR +static int s_mp_add (mp_int * a, mp_int * b, mp_int * c) { mp_int *x; @@ -301,7 +300,7 @@ s_mp_add (mp_int * a, mp_int * b, mp_int * c) /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */ -static int ICACHE_FLASH_ATTR +static int s_mp_sub (mp_int * a, mp_int * b, mp_int * c) { int olduse, res, min, max; @@ -369,7 +368,7 @@ s_mp_sub (mp_int * a, mp_int * b, mp_int * c) /* init a new mp_int */ -static int ICACHE_FLASH_ATTR +static int mp_init (mp_int * a) { int i; @@ -396,7 +395,7 @@ mp_init (mp_int * a) /* clear one (frees) */ -static void ICACHE_FLASH_ATTR +static void mp_clear (mp_int * a) { int i; @@ -420,7 +419,7 @@ mp_clear (mp_int * a) /* high level addition (handles signs) */ -static int ICACHE_FLASH_ATTR +static int mp_add (mp_int * a, mp_int * b, mp_int * c) { int sa, sb, res; @@ -453,7 +452,7 @@ mp_add (mp_int * a, mp_int * b, mp_int * c) /* high level subtraction (handles signs) */ -static int ICACHE_FLASH_ATTR +static int mp_sub (mp_int * a, mp_int * b, mp_int * c) { int sa, sb, res; @@ -491,7 +490,7 @@ mp_sub (mp_int * a, mp_int * b, mp_int * c) /* high level multiplication (handles sign) */ -static int ICACHE_FLASH_ATTR +static int mp_mul (mp_int * a, mp_int * b, mp_int * c) { int res, neg; @@ -539,7 +538,7 @@ mp_mul (mp_int * a, mp_int * b, mp_int * c) /* d = a * b (mod c) */ -static int ICACHE_FLASH_ATTR +static int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d) { int res; @@ -560,7 +559,7 @@ mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d) /* c = a mod b, 0 <= c < b */ -static int ICACHE_FLASH_ATTR +static int mp_mod (mp_int * a, mp_int * b, mp_int * c) { mp_int t; @@ -592,10 +591,12 @@ mp_mod (mp_int * a, mp_int * b, mp_int * c) * embedded in the normal function but that wasted a lot of stack space * for nothing (since 99% of the time the Montgomery code would be called) */ -static int ICACHE_FLASH_ATTR +static int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y) { - int dr; +#if defined(BN_MP_DR_IS_MODULUS_C)||defined(BN_MP_REDUCE_IS_2K_C)||defined(BN_MP_EXPTMOD_FAST_C) + int dr = 0; +#endif /* modulus P must be positive */ if (P->sign == MP_NEG) { @@ -652,9 +653,6 @@ mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y) #ifdef BN_MP_DR_IS_MODULUS_C /* is it a DR modulus? */ dr = mp_dr_is_modulus(P); -#else - /* default to no */ - dr = 0; #endif #ifdef BN_MP_REDUCE_IS_2K_C @@ -685,7 +683,7 @@ mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y) /* compare two ints (signed)*/ -static int ICACHE_FLASH_ATTR +static int mp_cmp (mp_int * a, mp_int * b) { /* compare based on sign */ @@ -708,7 +706,7 @@ mp_cmp (mp_int * a, mp_int * b) /* compare a digit */ -static int ICACHE_FLASH_ATTR +static int mp_cmp_d(mp_int * a, mp_digit b) { /* compare based on sign */ @@ -734,7 +732,7 @@ mp_cmp_d(mp_int * a, mp_digit b) #ifndef LTM_NO_NEG_EXP /* hac 14.61, pp608 */ -static int ICACHE_FLASH_ATTR +static int mp_invmod (mp_int * a, mp_int * b, mp_int * c) { /* b cannot be negative */ @@ -764,7 +762,7 @@ mp_invmod (mp_int * a, mp_int * b, mp_int * c) /* get the size for an unsigned equivalent */ -static int ICACHE_FLASH_ATTR +static int mp_unsigned_bin_size (mp_int * a) { int size = mp_count_bits (a); @@ -774,7 +772,7 @@ mp_unsigned_bin_size (mp_int * a) #ifndef LTM_NO_NEG_EXP /* hac 14.61, pp608 */ -static int ICACHE_FLASH_ATTR +static int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c) { mp_int x, y, u, v, A, B, C, D; @@ -931,7 +929,7 @@ LBL_ERR:mp_clear_multi (&x, &y, &u, &v, &A, &B, &C, &D, NULL); /* compare maginitude of two ints (unsigned) */ -static int ICACHE_FLASH_ATTR +static int mp_cmp_mag (mp_int * a, mp_int * b) { int n; @@ -967,7 +965,7 @@ mp_cmp_mag (mp_int * a, mp_int * b) /* reads a unsigned char array, assumes the msb is stored first [big endian] */ -static int ICACHE_FLASH_ATTR +static int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c) { int res; @@ -1003,7 +1001,7 @@ mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c) /* store in unsigned [big endian] format */ -static int ICACHE_FLASH_ATTR +static int mp_to_unsigned_bin (mp_int * a, unsigned char *b) { int x, res; @@ -1032,7 +1030,7 @@ mp_to_unsigned_bin (mp_int * a, unsigned char *b) /* shift right by a certain bit count (store quotient in c, optional remainder in d) */ -static int ICACHE_FLASH_ATTR +static int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d) { mp_digit D, r, rr; @@ -1109,7 +1107,7 @@ mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d) } -static int ICACHE_FLASH_ATTR +static int mp_init_copy (mp_int * a, mp_int * b) { int res; @@ -1122,7 +1120,7 @@ mp_init_copy (mp_int * a, mp_int * b) /* set to zero */ -static void ICACHE_FLASH_ATTR +static void mp_zero (mp_int * a) { int n; @@ -1139,7 +1137,7 @@ mp_zero (mp_int * a) /* copy, b = a */ -static int ICACHE_FLASH_ATTR +static int mp_copy (mp_int * a, mp_int * b) { int res, n; @@ -1187,7 +1185,7 @@ mp_copy (mp_int * a, mp_int * b) /* shift right a certain amount of digits */ -static void ICACHE_FLASH_ATTR +static void mp_rshd (mp_int * a, int b) { int x; @@ -1242,7 +1240,7 @@ mp_rshd (mp_int * a, int b) /* swap the elements of two integers, for cases where you can't simply swap the * mp_int pointers around */ -static void ICACHE_FLASH_ATTR +static void mp_exch (mp_int * a, mp_int * b) { mp_int t; @@ -1260,7 +1258,7 @@ mp_exch (mp_int * a, mp_int * b) * Typically very fast. Also fixes the sign if there * are no more leading digits */ -static void ICACHE_FLASH_ATTR +static void mp_clamp (mp_int * a) { /* decrease used while the most significant digit is @@ -1278,7 +1276,7 @@ mp_clamp (mp_int * a) /* grow as required */ -static int ICACHE_FLASH_ATTR +static int mp_grow (mp_int * a, int size) { int i; @@ -1320,7 +1318,7 @@ mp_grow (mp_int * a, int size) * * Simple function copies the input and fixes the sign to positive */ -static int ICACHE_FLASH_ATTR +static int mp_abs (mp_int * a, mp_int * b) { int res; @@ -1341,7 +1339,7 @@ mp_abs (mp_int * a, mp_int * b) /* set to a digit */ -static void ICACHE_FLASH_ATTR +static void mp_set (mp_int * a, mp_digit b) { mp_zero (a); @@ -1352,7 +1350,7 @@ mp_set (mp_int * a, mp_digit b) #ifndef LTM_NO_NEG_EXP /* b = a/2 */ -static int ICACHE_FLASH_ATTR +static int mp_div_2(mp_int * a, mp_int * b) { int x, res, oldused; @@ -1402,7 +1400,7 @@ mp_div_2(mp_int * a, mp_int * b) /* shift left by a certain bit count */ -static int ICACHE_FLASH_ATTR +static int mp_mul_2d (mp_int * a, int b, mp_int * c) { mp_digit d; @@ -1468,7 +1466,7 @@ mp_mul_2d (mp_int * a, int b, mp_int * c) #ifdef BN_MP_INIT_MULTI_C -static int ICACHE_FLASH_ATTR +static int mp_init_multi(mp_int *mp, ...) { mp_err res = MP_OKAY; /* Assume ok until proven otherwise */ @@ -1508,7 +1506,7 @@ mp_init_multi(mp_int *mp, ...) #ifdef BN_MP_CLEAR_MULTI_C -static void ICACHE_FLASH_ATTR +static void mp_clear_multi(mp_int *mp, ...) { mp_int* next_mp = mp; @@ -1524,7 +1522,7 @@ mp_clear_multi(mp_int *mp, ...) /* shift left a certain amount of digits */ -static int ICACHE_FLASH_ATTR +static int mp_lshd (mp_int * a, int b) { int x, res; @@ -1572,7 +1570,7 @@ mp_lshd (mp_int * a, int b) /* returns the number of bits in an int */ -static int ICACHE_FLASH_ATTR +static int mp_count_bits (mp_int * a) { int r; @@ -1597,7 +1595,7 @@ mp_count_bits (mp_int * a) /* calc a value mod 2**b */ -static int ICACHE_FLASH_ATTR +static int mp_mod_2d (mp_int * a, int b, mp_int * c) { int x, res; @@ -1634,7 +1632,7 @@ mp_mod_2d (mp_int * a, int b, mp_int * c) #ifdef BN_MP_DIV_SMALL /* slower bit-bang division... also smaller */ -static int ICACHE_FLASH_ATTR +static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d) { mp_int ta, tb, tq, q; @@ -1717,7 +1715,7 @@ mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d) * The overall algorithm is as described as * 14.20 from HAC but fixed to treat these cases. */ -static int ICACHE_FLASH_ATTR +static int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d) { mp_int q, x, y, t1, t2; @@ -1910,7 +1908,7 @@ LBL_Q:mp_clear (&q); #define TAB_SIZE 256 #endif -static int ICACHE_FLASH_ATTR +static int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode) { mp_int M[TAB_SIZE], res, mu; @@ -2139,7 +2137,7 @@ LBL_MU:mp_clear (&mu); /* computes b = a*a */ -static int ICACHE_FLASH_ATTR +static int mp_sqr (mp_int * a, mp_int * b) { int res; @@ -2181,7 +2179,7 @@ if (a->used >= KARATSUBA_SQR_CUTOFF) { This differs from reduce_2k since "d" can be larger than a single digit. */ -static int ICACHE_FLASH_ATTR +static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d) { mp_int q; @@ -2220,7 +2218,7 @@ mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d) /* determines the setup value */ -static int ICACHE_FLASH_ATTR +static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d) { int res; @@ -2249,7 +2247,7 @@ mp_reduce_2k_setup_l(mp_int *a, mp_int *d) * Simple algorithm which zeroes the int, grows it then just sets one bit * as required. */ -static int ICACHE_FLASH_ATTR +static int mp_2expt (mp_int * a, int b) { int res; @@ -2275,7 +2273,7 @@ mp_2expt (mp_int * a, int b) /* pre-calculate the value required for Barrett reduction * For a given modulus "b" it calulates the value required in "a" */ -static int ICACHE_FLASH_ATTR +static int mp_reduce_setup (mp_int * a, mp_int * b) { int res; @@ -2291,7 +2289,7 @@ mp_reduce_setup (mp_int * a, mp_int * b) * precomputed via mp_reduce_setup. * From HAC pp.604 Algorithm 14.42 */ -static int ICACHE_FLASH_ATTR +static int mp_reduce (mp_int * x, mp_int * m, mp_int * mu) { mp_int q; @@ -2375,7 +2373,7 @@ mp_reduce (mp_int * x, mp_int * m, mp_int * mu) * HAC pp. 595, Algorithm 14.12 Modified so you can control how * many digits of output are created. */ -static int ICACHE_FLASH_ATTR +static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) { mp_int t; @@ -2458,7 +2456,7 @@ s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) * Based on Algorithm 14.12 on pp.595 of HAC. * */ -static int ICACHE_FLASH_ATTR +static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) { int olduse, res, pa, ix, iz; @@ -2531,7 +2529,7 @@ fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) /* init an mp_init for a given size */ -static int ICACHE_FLASH_ATTR +static int mp_init_size (mp_int * a, int size) { int x; @@ -2560,7 +2558,7 @@ mp_init_size (mp_int * a, int size) /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */ -static int ICACHE_FLASH_ATTR +static int s_mp_sqr (mp_int * a, mp_int * b) { mp_int t; @@ -2627,7 +2625,7 @@ s_mp_sqr (mp_int * a, mp_int * b) /* multiplies |a| * |b| and does not compute the lower digs digits * [meant to get the higher part of the product] */ -static int ICACHE_FLASH_ATTR +static int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs) { mp_int t; @@ -2687,7 +2685,7 @@ s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs) #ifdef BN_MP_MONTGOMERY_SETUP_C /* setups the montgomery reduction stuff */ -static int ICACHE_FLASH_ATTR +static int mp_montgomery_setup (mp_int * n, mp_digit * rho) { mp_digit x, b; @@ -2735,7 +2733,7 @@ mp_montgomery_setup (mp_int * n, mp_digit * rho) * * Based on Algorithm 14.32 on pp.601 of HAC. */ -int ICACHE_FLASH_ATTR +int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho) { int ix, res, olduse; @@ -2883,7 +2881,7 @@ fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho) #ifdef BN_MP_MUL_2_C /* b = a*2 */ -static int ICACHE_FLASH_ATTR +static int mp_mul_2(mp_int * a, mp_int * b) { int x, res, oldused; @@ -2953,7 +2951,7 @@ mp_mul_2(mp_int * a, mp_int * b) * The method is slightly modified to shift B unconditionally up to just under * the leading bit of b. This saves a lot of multiple precision shifting. */ -static int ICACHE_FLASH_ATTR +static int mp_montgomery_calc_normalization (mp_int * a, mp_int * b) { int x, bits, res; @@ -2997,7 +2995,7 @@ mp_montgomery_calc_normalization (mp_int * a, mp_int * b) * Uses Montgomery or Diminished Radix reduction [whichever appropriate] */ -static int ICACHE_FLASH_ATTR +static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode) { mp_int M[TAB_SIZE], res; @@ -3296,7 +3294,7 @@ LBL_RES:mp_clear (&res); After that loop you do the squares and add them in. */ -static int ICACHE_FLASH_ATTR +static int fast_s_mp_sqr (mp_int * a, mp_int * b) { int olduse, res, pa, ix, iz; @@ -3384,7 +3382,7 @@ fast_s_mp_sqr (mp_int * a, mp_int * b) #ifdef BN_MP_MUL_D_C /* multiply by a digit */ -static int ICACHE_FLASH_ATTR +static int mp_mul_d (mp_int * a, mp_digit b, mp_int * c) { mp_digit u, *tmpa, *tmpc; diff --git a/tools/sdk/include/wpa_supplicant/wpa2/utils/base64.h b/tools/sdk/include/wpa_supplicant/wpa2/utils/base64.h index 91eb8741985..aa21fd0fc1b 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/utils/base64.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/utils/base64.h @@ -9,9 +9,9 @@ #ifndef BASE64_H #define BASE64_H -unsigned char * _base64_encode(const unsigned char *src, size_t len, +unsigned char * base64_encode(const unsigned char *src, size_t len, size_t *out_len); -unsigned char * _base64_decode(const unsigned char *src, size_t len, +unsigned char * base64_decode(const unsigned char *src, size_t len, size_t *out_len); #endif /* BASE64_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/utils/ext_password.h b/tools/sdk/include/wpa_supplicant/wpa2/utils/ext_password.h index e3e46ea0843..dfe8e6f0e70 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/utils/ext_password.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/utils/ext_password.h @@ -23,10 +23,10 @@ void ext_password_free(struct wpabuf *pw); #else /* CONFIG_EXT_PASSWORD */ -#define ext_password_init(b, p) ((void *) 1) -#define ext_password_deinit(d) do { } while (0) -#define ext_password_get(d, n) (NULL) -#define ext_password_free(p) do { } while (0) +#define ext_password_init(b, p) +#define ext_password_deinit(d) +#define ext_password_get(d, n) +#define ext_password_free(p) #endif /* CONFIG_EXT_PASSWORD */ diff --git a/tools/sdk/include/wpa_supplicant/wps/utils/uuid.h b/tools/sdk/include/wpa_supplicant/wps/utils/uuid.h new file mode 100644 index 00000000000..5e860cbc593 --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wps/utils/uuid.h @@ -0,0 +1,18 @@ +/* + * Universally Unique IDentifier (UUID) + * Copyright (c) 2008, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef UUID_H +#define UUID_H + +#define UUID_LEN 16 + +int uuid_str2bin(const char *str, u8 *bin); +int uuid_bin2str(const u8 *bin, char *str, size_t max_len); +int is_nil_uuid(const u8 *uuid); + +#endif /* UUID_H */ diff --git a/tools/sdk/include/wpa_supplicant/wps/wps.h b/tools/sdk/include/wpa_supplicant/wps/wps.h new file mode 100644 index 00000000000..31092cbb836 --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wps/wps.h @@ -0,0 +1,1065 @@ +/* + * Wi-Fi Protected Setup + * Copyright (c) 2007-2012, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef WPS_H +#define WPS_H + +#include "rom/ets_sys.h" +#include "wps_defs.h" +#include "esp_wifi_types.h" + +/** + * enum wsc_op_code - EAP-WSC OP-Code values + */ +enum wsc_op_code { + WSC_UPnP = 0 /* No OP Code in UPnP transport */, + WSC_Start = 0x01, + WSC_ACK = 0x02, + WSC_NACK = 0x03, + WSC_MSG = 0x04, + WSC_Done = 0x05, + WSC_FRAG_ACK = 0x06 +}; + +struct wps_registrar; +//struct upnp_wps_device_sm; +struct wps_er; +struct wps_parse_attr; + +/** + * struct wps_credential - WPS Credential + * @ssid: SSID + * @ssid_len: Length of SSID + * @auth_type: Authentication Type (WPS_WIFI_AUTH_OPEN, .. flags) + * @encr_type: Encryption Type (WPS_ENCR_NONE, .. flags) + * @key_idx: Key index + * @key: Key + * @key_len: Key length in octets + * @mac_addr: MAC address of the Credential receiver + * @cred_attr: Unparsed Credential attribute data (used only in cred_cb()); + * this may be %NULL, if not used + * @cred_attr_len: Length of cred_attr in octets + * @ap_channel: AP channel + */ +struct wps_credential { + u8 ssid[32]; + size_t ssid_len; + u16 auth_type; + u16 encr_type; + u8 key_idx; + u8 key[64]; + size_t key_len; + u8 mac_addr[ETH_ALEN]; + const u8 *cred_attr; + size_t cred_attr_len; + u16 ap_channel; +}; + +#define WPS_DEV_TYPE_LEN 8 +#define WPS_DEV_TYPE_BUFSIZE 21 +#define WPS_SEC_DEV_TYPE_MAX_LEN 128 +/* maximum number of advertised WPS vendor extension attributes */ +#define MAX_WPS_VENDOR_EXTENSIONS 10 +/* maximum size of WPS Vendor extension attribute */ +#define WPS_MAX_VENDOR_EXT_LEN 1024 +/* maximum number of parsed WPS vendor extension attributes */ +#define MAX_WPS_PARSE_VENDOR_EXT 10 + +/** + * struct wps_device_data - WPS Device Data + * @mac_addr: Device MAC address + * @device_name: Device Name (0..32 octets encoded in UTF-8) + * @manufacturer: Manufacturer (0..64 octets encoded in UTF-8) + * @model_name: Model Name (0..32 octets encoded in UTF-8) + * @model_number: Model Number (0..32 octets encoded in UTF-8) + * @serial_number: Serial Number (0..32 octets encoded in UTF-8) + * @pri_dev_type: Primary Device Type + * @sec_dev_type: Array of secondary device types + * @num_sec_dev_type: Number of secondary device types + * @os_version: OS Version + * @rf_bands: RF bands (WPS_RF_24GHZ, WPS_RF_50GHZ flags) + * @p2p: Whether the device is a P2P device + */ +struct wps_device_data { + u8 mac_addr[ETH_ALEN]; + char *device_name; + char *manufacturer; + char *model_name; + char *model_number; + char *serial_number; + u8 pri_dev_type[WPS_DEV_TYPE_LEN]; +#define WPS_SEC_DEVICE_TYPES 5 + u8 sec_dev_type[WPS_SEC_DEVICE_TYPES][WPS_DEV_TYPE_LEN]; + u8 num_sec_dev_types; + u32 os_version; + u8 rf_bands; + u16 config_methods; + struct wpabuf *vendor_ext_m1; + struct wpabuf *vendor_ext[MAX_WPS_VENDOR_EXTENSIONS]; + + int p2p; +}; + +/** + * struct wps_config - WPS configuration for a single registration protocol run + */ +struct wps_config { + /** + * wps - Pointer to long term WPS context + */ + struct wps_context *wps; + + /** + * registrar - Whether this end is a Registrar + */ + int registrar; + + /** + * pin - Enrollee Device Password (%NULL for Registrar or PBC) + */ + const u8 *pin; + + /** + * pin_len - Length on pin in octets + */ + size_t pin_len; + + /** + * pbc - Whether this is protocol run uses PBC + */ + int pbc; + + /** + * assoc_wps_ie: (Re)AssocReq WPS IE (in AP; %NULL if not AP) + */ + const struct wpabuf *assoc_wps_ie; + + /** + * new_ap_settings - New AP settings (%NULL if not used) + * + * This parameter provides new AP settings when using a wireless + * stations as a Registrar to configure the AP. %NULL means that AP + * will not be reconfigured, i.e., the station will only learn the + * current AP settings by using AP PIN. + */ + const struct wps_credential *new_ap_settings; + + /** + * peer_addr: MAC address of the peer in AP; %NULL if not AP + */ + const u8 *peer_addr; + + /** + * use_psk_key - Use PSK format key in Credential + * + * Force PSK format to be used instead of ASCII passphrase when + * building Credential for an Enrollee. The PSK value is set in + * struct wpa_context::psk. + */ + int use_psk_key; + + /** + * dev_pw_id - Device Password ID for Enrollee when PIN is used + */ + u16 dev_pw_id; + + /** + * p2p_dev_addr - P2P Device Address from (Re)Association Request + * + * On AP/GO, this is set to the P2P Device Address of the associating + * P2P client if a P2P IE is included in the (Re)Association Request + * frame and the P2P Device Address is included. Otherwise, this is set + * to %NULL to indicate the station does not have a P2P Device Address. + */ + const u8 *p2p_dev_addr; + + /** + * pbc_in_m1 - Do not remove PushButton config method in M1 (AP) + * + * This can be used to enable a workaround to allow Windows 7 to use + * PBC with the AP. + */ + int pbc_in_m1; +}; + +/* Bssid of the discard AP which is discarded for not select reg or other reason */ +struct discard_ap_list_t{ + u8 bssid[6]; +}; + +//struct wps_data * wps_init(const struct wps_config *cfg); +struct wps_data * wps_init(void); + +//void wps_deinit(struct wps_data *data); +void wps_deinit(void); + +/** + * enum wps_process_res - WPS message processing result + */ +enum wps_process_res { + /** + * WPS_DONE - Processing done + */ + WPS_DONE, + + /** + * WPS_CONTINUE - Processing continues + */ + WPS_CONTINUE, + + /** + * WPS_FAILURE - Processing failed + */ + WPS_FAILURE, + + /** + * WPS_PENDING - Processing continues, but waiting for an external + * event (e.g., UPnP message from an external Registrar) + */ + WPS_PENDING, + WPS_IGNORE, /* snake, ignore the re-packge */ + + WPS_FRAGMENT /* Tim, send wsc fragment ack */ +}; +enum wps_process_res wps_process_msg(struct wps_data *wps, + enum wsc_op_code op_code, + const struct wpabuf *msg); + +struct wpabuf * wps_get_msg(struct wps_data *wps, enum wsc_op_code *op_code); + +int wps_is_selected_pbc_registrar(const struct wpabuf *msg, u8 *bssid); +int wps_is_selected_pin_registrar(const struct wpabuf *msg, u8 *bssid); +int wps_ap_priority_compar(const struct wpabuf *wps_a, + const struct wpabuf *wps_b); +int wps_is_addr_authorized(const struct wpabuf *msg, const u8 *addr, + int ver1_compat); +const u8 * wps_get_uuid_e(const struct wpabuf *msg); +int wps_is_20(const struct wpabuf *msg); + +struct wpabuf * wps_build_assoc_req_ie(enum wps_request_type req_type); +struct wpabuf * wps_build_assoc_resp_ie(void); +struct wpabuf * wps_build_probe_req_ie(u16 pw_id, struct wps_device_data *dev, + const u8 *uuid, + enum wps_request_type req_type, + unsigned int num_req_dev_types, + const u8 *req_dev_types); + + +/** + * struct wps_registrar_config - WPS Registrar configuration + */ +struct wps_registrar_config { + /** + * new_psk_cb - Callback for new PSK + * @ctx: Higher layer context data (cb_ctx) + * @mac_addr: MAC address of the Enrollee + * @psk: The new PSK + * @psk_len: The length of psk in octets + * Returns: 0 on success, -1 on failure + * + * This callback is called when a new per-device PSK is provisioned. + */ + int (*new_psk_cb)(void *ctx, const u8 *mac_addr, const u8 *psk, + size_t psk_len); + + /** + * set_ie_cb - Callback for WPS IE changes + * @ctx: Higher layer context data (cb_ctx) + * @beacon_ie: WPS IE for Beacon + * @probe_resp_ie: WPS IE for Probe Response + * Returns: 0 on success, -1 on failure + * + * This callback is called whenever the WPS IE in Beacon or Probe + * Response frames needs to be changed (AP only). Callee is responsible + * for freeing the buffers. + */ + int (*set_ie_cb)(void *ctx, struct wpabuf *beacon_ie, + struct wpabuf *probe_resp_ie); + + /** + * pin_needed_cb - Callback for requesting a PIN + * @ctx: Higher layer context data (cb_ctx) + * @uuid_e: UUID-E of the unknown Enrollee + * @dev: Device Data from the unknown Enrollee + * + * This callback is called whenever an unknown Enrollee requests to use + * PIN method and a matching PIN (Device Password) is not found in + * Registrar data. + */ + void (*pin_needed_cb)(void *ctx, const u8 *uuid_e, + const struct wps_device_data *dev); + + /** + * reg_success_cb - Callback for reporting successful registration + * @ctx: Higher layer context data (cb_ctx) + * @mac_addr: MAC address of the Enrollee + * @uuid_e: UUID-E of the Enrollee + * @dev_pw: Device Password (PIN) used during registration + * @dev_pw_len: Length of dev_pw in octets + * + * This callback is called whenever an Enrollee completes registration + * successfully. + */ + void (*reg_success_cb)(void *ctx, const u8 *mac_addr, + const u8 *uuid_e, const u8 *dev_pw, + size_t dev_pw_len); + + /** + * set_sel_reg_cb - Callback for reporting selected registrar changes + * @ctx: Higher layer context data (cb_ctx) + * @sel_reg: Whether the Registrar is selected + * @dev_passwd_id: Device Password ID to indicate with method or + * specific password the Registrar intends to use + * @sel_reg_config_methods: Bit field of active config methods + * + * This callback is called whenever the Selected Registrar state + * changes (e.g., a new PIN becomes available or PBC is invoked). This + * callback is only used by External Registrar implementation; + * set_ie_cb() is used by AP implementation in similar caes, but it + * provides the full WPS IE data instead of just the minimal Registrar + * state information. + */ + void (*set_sel_reg_cb)(void *ctx, int sel_reg, u16 dev_passwd_id, + u16 sel_reg_config_methods); + + /** + * enrollee_seen_cb - Callback for reporting Enrollee based on ProbeReq + * @ctx: Higher layer context data (cb_ctx) + * @addr: MAC address of the Enrollee + * @uuid_e: UUID of the Enrollee + * @pri_dev_type: Primary device type + * @config_methods: Config Methods + * @dev_password_id: Device Password ID + * @request_type: Request Type + * @dev_name: Device Name (if available) + */ + void (*enrollee_seen_cb)(void *ctx, const u8 *addr, const u8 *uuid_e, + const u8 *pri_dev_type, u16 config_methods, + u16 dev_password_id, u8 request_type, + const char *dev_name); + + /** + * cb_ctx: Higher layer context data for Registrar callbacks + */ + void *cb_ctx; + + /** + * skip_cred_build: Do not build credential + * + * This option can be used to disable internal code that builds + * Credential attribute into M8 based on the current network + * configuration and Enrollee capabilities. The extra_cred data will + * then be used as the Credential(s). + */ + int skip_cred_build; + + /** + * extra_cred: Additional Credential attribute(s) + * + * This optional data (set to %NULL to disable) can be used to add + * Credential attribute(s) for other networks into M8. If + * skip_cred_build is set, this will also override the automatically + * generated Credential attribute. + */ + const u8 *extra_cred; + + /** + * extra_cred_len: Length of extra_cred in octets + */ + size_t extra_cred_len; + + /** + * disable_auto_conf - Disable auto-configuration on first registration + * + * By default, the AP that is started in not configured state will + * generate a random PSK and move to configured state when the first + * registration protocol run is completed successfully. This option can + * be used to disable this functionality and leave it up to an external + * program to take care of configuration. This requires the extra_cred + * to be set with a suitable Credential and skip_cred_build being used. + */ + int disable_auto_conf; + + /** + * static_wep_only - Whether the BSS supports only static WEP + */ + int static_wep_only; + + /** + * dualband - Whether this is a concurrent dualband AP + */ + int dualband; +}; + + +/** + * enum wps_event - WPS event types + */ +enum wps_event { + /** + * WPS_EV_M2D - M2D received (Registrar did not know us) + */ + WPS_EV_M2D, + + /** + * WPS_EV_FAIL - Registration failed + */ + WPS_EV_FAIL, + + /** + * WPS_EV_SUCCESS - Registration succeeded + */ + WPS_EV_SUCCESS, + + /** + * WPS_EV_PWD_AUTH_FAIL - Password authentication failed + */ + WPS_EV_PWD_AUTH_FAIL, + + /** + * WPS_EV_PBC_OVERLAP - PBC session overlap detected + */ + WPS_EV_PBC_OVERLAP, + + /** + * WPS_EV_PBC_TIMEOUT - PBC walktime expired before protocol run start + */ + WPS_EV_PBC_TIMEOUT, + + /** + * WPS_EV_ER_AP_ADD - ER: AP added + */ + WPS_EV_ER_AP_ADD, + + /** + * WPS_EV_ER_AP_REMOVE - ER: AP removed + */ + WPS_EV_ER_AP_REMOVE, + + /** + * WPS_EV_ER_ENROLLEE_ADD - ER: Enrollee added + */ + WPS_EV_ER_ENROLLEE_ADD, + + /** + * WPS_EV_ER_ENROLLEE_REMOVE - ER: Enrollee removed + */ + WPS_EV_ER_ENROLLEE_REMOVE, + + /** + * WPS_EV_ER_AP_SETTINGS - ER: AP Settings learned + */ + WPS_EV_ER_AP_SETTINGS, + + /** + * WPS_EV_ER_SET_SELECTED_REGISTRAR - ER: SetSelectedRegistrar event + */ + WPS_EV_ER_SET_SELECTED_REGISTRAR, + + /** + * WPS_EV_AP_PIN_SUCCESS - External Registrar used correct AP PIN + */ + WPS_EV_AP_PIN_SUCCESS +}; + +/** + * union wps_event_data - WPS event data + */ +union wps_event_data { + /** + * struct wps_event_m2d - M2D event data + */ + struct wps_event_m2d { + u16 config_methods; + const u8 *manufacturer; + size_t manufacturer_len; + const u8 *model_name; + size_t model_name_len; + const u8 *model_number; + size_t model_number_len; + const u8 *serial_number; + size_t serial_number_len; + const u8 *dev_name; + size_t dev_name_len; + const u8 *primary_dev_type; /* 8 octets */ + u16 config_error; + u16 dev_password_id; + } m2d; + + /** + * struct wps_event_fail - Registration failure information + * @msg: enum wps_msg_type + */ + struct wps_event_fail { + int msg; + u16 config_error; + u16 error_indication; + } fail; + + struct wps_event_pwd_auth_fail { + int enrollee; + int part; + } pwd_auth_fail; + + struct wps_event_er_ap { + const u8 *uuid; + const u8 *mac_addr; + const char *friendly_name; + const char *manufacturer; + const char *manufacturer_url; + const char *model_description; + const char *model_name; + const char *model_number; + const char *model_url; + const char *serial_number; + const char *upc; + const u8 *pri_dev_type; + u8 wps_state; + } ap; + + struct wps_event_er_enrollee { + const u8 *uuid; + const u8 *mac_addr; + int m1_received; + u16 config_methods; + u16 dev_passwd_id; + const u8 *pri_dev_type; + const char *dev_name; + const char *manufacturer; + const char *model_name; + const char *model_number; + const char *serial_number; + } enrollee; + + struct wps_event_er_ap_settings { + const u8 *uuid; + const struct wps_credential *cred; + } ap_settings; + + struct wps_event_er_set_selected_registrar { + const u8 *uuid; + int sel_reg; + u16 dev_passwd_id; + u16 sel_reg_config_methods; + enum { + WPS_ER_SET_SEL_REG_START, + WPS_ER_SET_SEL_REG_DONE, + WPS_ER_SET_SEL_REG_FAILED + } state; + } set_sel_reg; +}; +#ifdef CONFIG_WPS_UPNP +/** + * struct upnp_pending_message - Pending PutWLANResponse messages + * @next: Pointer to next pending message or %NULL + * @addr: NewWLANEventMAC + * @msg: NewMessage + * @type: Message Type + */ +struct upnp_pending_message { + struct upnp_pending_message *next; + u8 addr[ETH_ALEN]; + struct wpabuf *msg; + enum wps_msg_type type; +}; +void wps_free_pending_msgs(struct upnp_pending_message *msgs); +#endif +/** + * struct wps_context - Long term WPS context data + * + * This data is stored at the higher layer Authenticator or Supplicant data + * structures and it is maintained over multiple registration protocol runs. + */ +struct wps_context { + /** + * ap - Whether the local end is an access point + */ + int ap; + + /** + * registrar - Pointer to WPS registrar data from wps_registrar_init() + */ + struct wps_registrar *registrar; + + /** + * wps_state - Current WPS state + */ + enum wps_state wps_state; + + /** + * ap_setup_locked - Whether AP setup is locked (only used at AP) + */ + int ap_setup_locked; + + /** + * uuid - Own UUID + */ + u8 uuid[16]; + + /** + * ssid - SSID + * + * This SSID is used by the Registrar to fill in information for + * Credentials. In addition, AP uses it when acting as an Enrollee to + * notify Registrar of the current configuration. + */ + u8 ssid[32]; + + /** + * ssid_len - Length of ssid in octets + */ + size_t ssid_len; + + /** + * dev - Own WPS device data + */ + struct wps_device_data dev; + + /** + * dh_ctx - Context data for Diffie-Hellman operation + */ + void *dh_ctx; + + /** + * dh_privkey - Diffie-Hellman private key + */ + struct wpabuf *dh_privkey; + + /** + * dh_pubkey_oob - Diffie-Hellman public key + */ + struct wpabuf *dh_pubkey; + + /** + * config_methods - Enabled configuration methods + * + * Bit field of WPS_CONFIG_* + */ + u16 config_methods; + + /** + * encr_types - Enabled encryption types (bit field of WPS_ENCR_*) + */ + u16 encr_types; + + /** + * auth_types - Authentication types (bit field of WPS_AUTH_*) + */ + u16 auth_types; + + /** + * network_key - The current Network Key (PSK) or %NULL to generate new + * + * If %NULL, Registrar will generate per-device PSK. In addition, AP + * uses this when acting as an Enrollee to notify Registrar of the + * current configuration. + * + * When using WPA/WPA2-Person, this key can be either the ASCII + * passphrase (8..63 characters) or the 32-octet PSK (64 hex + * characters). When this is set to the ASCII passphrase, the PSK can + * be provided in the psk buffer and used per-Enrollee to control which + * key type is included in the Credential (e.g., to reduce calculation + * need on low-powered devices by provisioning PSK while still allowing + * other devices to get the passphrase). + */ + u8 *network_key; + + /** + * network_key_len - Length of network_key in octets + */ + size_t network_key_len; + + /** + * psk - The current network PSK + * + * This optional value can be used to provide the current PSK if + * network_key is set to the ASCII passphrase. + */ + u8 psk[32]; + + /** + * psk_set - Whether psk value is set + */ + int psk_set; + + /** + * ap_settings - AP Settings override for M7 (only used at AP) + * + * If %NULL, AP Settings attributes will be generated based on the + * current network configuration. + */ + u8 *ap_settings; + + /** + * ap_settings_len - Length of ap_settings in octets + */ + size_t ap_settings_len; + + /** + * friendly_name - Friendly Name (required for UPnP) + */ + char *friendly_name; + + /** + * manufacturer_url - Manufacturer URL (optional for UPnP) + */ + char *manufacturer_url; + + /** + * model_description - Model Description (recommended for UPnP) + */ + char *model_description; + + /** + * model_url - Model URL (optional for UPnP) + */ + char *model_url; + + /** + * upc - Universal Product Code (optional for UPnP) + */ + char *upc; + + /** + * cred_cb - Callback to notify that new Credentials were received + * @ctx: Higher layer context data (cb_ctx) + * @cred: The received Credential + * Return: 0 on success, -1 on failure + */ + int (*cred_cb)(void *ctx, const struct wps_credential *cred); + + /** + * event_cb - Event callback (state information about progress) + * @ctx: Higher layer context data (cb_ctx) + * @event: Event type + * @data: Event data + */ + void (*event_cb)(void *ctx, enum wps_event event, + union wps_event_data *data); + + /** + * cb_ctx: Higher layer context data for callbacks + */ + void *cb_ctx; + + //struct upnp_wps_device_sm *wps_upnp; + + /* Pending messages from UPnP PutWLANResponse */ + //struct upnp_pending_message *upnp_msgs; +#ifdef CONFIG_WPS_NFC + + u16 ap_nfc_dev_pw_id; + struct wpabuf *ap_nfc_dh_pubkey; + struct wpabuf *ap_nfc_dh_privkey; + struct wpabuf *ap_nfc_dev_pw; +#endif +}; + +struct wps_registrar * +wps_registrar_init(struct wps_context *wps, + const struct wps_registrar_config *cfg); +void wps_registrar_deinit(struct wps_registrar *reg); +#ifdef CONFIG_WPS_PIN + +int wps_registrar_add_pin(struct wps_registrar *reg, const u8 *addr, + const u8 *uuid, const u8 *pin, size_t pin_len, + int timeout); +int wps_registrar_invalidate_pin(struct wps_registrar *reg, const u8 *uuid); +int wps_registrar_unlock_pin(struct wps_registrar *reg, const u8 *uuid); +#endif +int wps_registrar_wps_cancel(struct wps_registrar *reg); + +int wps_registrar_button_pushed(struct wps_registrar *reg, + const u8 *p2p_dev_addr); +void wps_registrar_complete(struct wps_registrar *registrar, const u8 *uuid_e, + const u8 *dev_pw, size_t dev_pw_len); +void wps_registrar_probe_req_rx(struct wps_registrar *reg, const u8 *addr, + const struct wpabuf *wps_data, + int p2p_wildcard); +int wps_registrar_update_ie(struct wps_registrar *reg); +int wps_registrar_get_info(struct wps_registrar *reg, const u8 *addr, + char *buf, size_t buflen); +int wps_registrar_config_ap(struct wps_registrar *reg, + struct wps_credential *cred); +#ifdef CONFIG_WPS_NFC + +int wps_registrar_add_nfc_pw_token(struct wps_registrar *reg, + const u8 *pubkey_hash, u16 pw_id, + const u8 *dev_pw, size_t dev_pw_len); +int wps_registrar_add_nfc_password_token(struct wps_registrar *reg, + const u8 *oob_dev_pw, + size_t oob_dev_pw_len); +#endif +int wps_build_credential_wrap(struct wpabuf *msg, + const struct wps_credential *cred); +#ifdef CONFIG_WPS_PIN + +unsigned int wps_pin_checksum(unsigned int pin); +unsigned int wps_pin_valid(unsigned int pin); +int wps_pin_str_valid(const char *pin); +#endif +unsigned int wps_generate_pin(void); + +#ifdef CONFIG_WPS_OOB + +struct wpabuf * wps_get_oob_cred(struct wps_context *wps); +int wps_oob_use_cred(struct wps_context *wps, struct wps_parse_attr *attr); +#endif +int wps_attr_text(struct wpabuf *data, char *buf, char *end); + +struct wps_er * wps_er_init(struct wps_context *wps, const char *ifname, + const char *filter); +void wps_er_refresh(struct wps_er *er); +void wps_er_deinit(struct wps_er *er, void (*cb)(void *ctx), void *ctx); +void wps_er_set_sel_reg(struct wps_er *er, int sel_reg, u16 dev_passwd_id, + u16 sel_reg_config_methods); +int wps_er_pbc(struct wps_er *er, const u8 *uuid); +int wps_er_learn(struct wps_er *er, const u8 *uuid, const u8 *pin, + size_t pin_len); +int wps_er_set_config(struct wps_er *er, const u8 *uuid, + const struct wps_credential *cred); +int wps_er_config(struct wps_er *er, const u8 *uuid, const u8 *pin, + size_t pin_len, const struct wps_credential *cred); +#ifdef CONFIG_WPS_NFC + +struct wpabuf * wps_er_nfc_config_token(struct wps_er *er, const u8 *uuid); + +#endif + +int wps_dev_type_str2bin(const char *str, u8 dev_type[WPS_DEV_TYPE_LEN]); +char * wps_dev_type_bin2str(const u8 dev_type[WPS_DEV_TYPE_LEN], char *buf, + size_t buf_len); +void uuid_gen_mac_addr(const u8 *mac_addr, u8 *uuid); +u16 wps_config_methods_str2bin(const char *str); + +#ifdef CONFIG_WPS_NFC + +struct wpabuf * wps_build_nfc_pw_token(u16 dev_pw_id, + const struct wpabuf *pubkey, + const struct wpabuf *dev_pw); +struct wpabuf * wps_nfc_token_gen(int ndef, int *id, struct wpabuf **pubkey, + struct wpabuf **privkey, + struct wpabuf **dev_pw); +#endif + +/* ndef.c */ +struct wpabuf * ndef_parse_wifi(const struct wpabuf *buf); +struct wpabuf * ndef_build_wifi(const struct wpabuf *buf); +struct wpabuf * ndef_build_wifi_hr(void); + +#ifdef CONFIG_WPS_STRICT +int wps_validate_beacon(const struct wpabuf *wps_ie); +int wps_validate_beacon_probe_resp(const struct wpabuf *wps_ie, int probe, + const u8 *addr); +int wps_validate_probe_req(const struct wpabuf *wps_ie, const u8 *addr); +int wps_validate_assoc_req(const struct wpabuf *wps_ie); +int wps_validate_assoc_resp(const struct wpabuf *wps_ie); +int wps_validate_m1(const struct wpabuf *tlvs); +int wps_validate_m2(const struct wpabuf *tlvs); +int wps_validate_m2d(const struct wpabuf *tlvs); +int wps_validate_m3(const struct wpabuf *tlvs); +int wps_validate_m4(const struct wpabuf *tlvs); +int wps_validate_m4_encr(const struct wpabuf *tlvs, int wps2); +int wps_validate_m5(const struct wpabuf *tlvs); +int wps_validate_m5_encr(const struct wpabuf *tlvs, int wps2); +int wps_validate_m6(const struct wpabuf *tlvs); +int wps_validate_m6_encr(const struct wpabuf *tlvs, int wps2); +int wps_validate_m7(const struct wpabuf *tlvs); +int wps_validate_m7_encr(const struct wpabuf *tlvs, int ap, int wps2); +int wps_validate_m8(const struct wpabuf *tlvs); +int wps_validate_m8_encr(const struct wpabuf *tlvs, int ap, int wps2); +int wps_validate_wsc_ack(const struct wpabuf *tlvs); +int wps_validate_wsc_nack(const struct wpabuf *tlvs); +int wps_validate_wsc_done(const struct wpabuf *tlvs); +int wps_validate_upnp_set_selected_registrar(const struct wpabuf *tlvs); +#else /* CONFIG_WPS_STRICT */ +static inline int wps_validate_beacon(const struct wpabuf *wps_ie){ + return 0; +} + +static inline int wps_validate_beacon_probe_resp(const struct wpabuf *wps_ie, + int probe, const u8 *addr) +{ + return 0; +} + +static inline int wps_validate_probe_req(const struct wpabuf *wps_ie, + const u8 *addr) +{ + return 0; +} + +static inline int wps_validate_assoc_req(const struct wpabuf *wps_ie) +{ + return 0; +} + +static inline int wps_validate_assoc_resp(const struct wpabuf *wps_ie) +{ + return 0; +} + +static inline int wps_validate_m1(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m2(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m2d(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m3(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m4(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m4_encr(const struct wpabuf *tlvs, int wps2) +{ + return 0; +} + +static inline int wps_validate_m5(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m5_encr(const struct wpabuf *tlvs, int wps2) +{ + return 0; +} + +static inline int wps_validate_m6(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m6_encr(const struct wpabuf *tlvs, int wps2) +{ + return 0; +} + +static inline int wps_validate_m7(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m7_encr(const struct wpabuf *tlvs, int ap, + int wps2) +{ + return 0; +} + +static inline int wps_validate_m8(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_m8_encr(const struct wpabuf *tlvs, int ap, + int wps2) +{ + return 0; +} + +static inline int wps_validate_wsc_ack(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_wsc_nack(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_wsc_done(const struct wpabuf *tlvs) +{ + return 0; +} + +static inline int wps_validate_upnp_set_selected_registrar( + const struct wpabuf *tlvs) +{ + return 0; +} +#endif /* CONFIG_WPS_STRICT */ + +enum wps_cb_status { + WPS_CB_ST_SUCCESS = 0, + WPS_CB_ST_FAILED, + WPS_CB_ST_TIMEOUT, + WPS_CB_ST_WEP, + WPS_CB_ST_SCAN_ERR, +}; + +typedef void (*wps_st_cb_t)(int status); + +#ifdef USE_WPS_TASK +#define SIG_WPS_START 2 +#define SIG_WPS_RX 3 +#define SIG_WPS_NUM 9 +#endif + +#define WPS_EAP_EXT_VENDOR_TYPE "WFA-SimpleConfig-Enrollee-1-0" +#define WPS_OUTBUF_SIZE 500 +struct wps_sm { + struct wps_config *wps_cfg; + struct wps_context *wps_ctx; + struct wps_data *wps; + char identity[32]; + u8 identity_len; + u8 ownaddr[ETH_ALEN]; + u8 bssid[ETH_ALEN]; + u8 ssid[32]; + u8 ssid_len; + struct wps_device_data *dev; + u8 uuid[16]; + u8 eapol_version; + char key[64]; + u8 key_len; + ETSTimer wps_timeout_timer; + ETSTimer wps_msg_timeout_timer; + ETSTimer wps_scan_timer; + ETSTimer wps_success_cb_timer; + ETSTimer wps_eapol_start_timer; + wps_st_cb_t st_cb; + u8 current_identifier; + bool is_wps_scan; + u8 channel; + u8 scan_cnt; +#ifdef USE_WPS_TASK + u8 wps_sig_cnt[SIG_WPS_NUM]; +#endif + u8 discover_ssid_cnt; + bool ignore_sel_reg; + struct discard_ap_list_t dis_ap_list[WPS_MAX_DIS_AP_NUM]; + u8 discard_ap_cnt; + wifi_sta_config_t config; +}; + +#define IEEE80211_CAPINFO_PRIVACY 0x0010 + +struct wps_sm *wps_sm_get(void); +int wps_ssid_save(u8 *ssid, u8 ssid_len); +int wps_key_save(char *key, u8 key_len); +int wps_station_wps_register_cb(wps_st_cb_t cb); +int wps_station_wps_unregister_cb(void); +int wps_start_pending(void); +int wps_sm_rx_eapol(u8 *src_addr, u8 *buf, u32 len); + +int wps_dev_deinit(struct wps_device_data *dev); +#endif /* WPS_H */ diff --git a/tools/sdk/include/wpa_supplicant/wps/wps_attr_parse.h b/tools/sdk/include/wpa_supplicant/wps/wps_attr_parse.h new file mode 100644 index 00000000000..86061aea062 --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wps/wps_attr_parse.h @@ -0,0 +1,108 @@ +/* + * Wi-Fi Protected Setup - attribute parsing + * Copyright (c) 2008-2012, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef WPS_ATTR_PARSE_H +#define WPS_ATTR_PARSE_H + +#include "wps/wps.h" + +struct wps_parse_attr { + /* fixed length fields */ + const u8 *version; /* 1 octet */ + const u8 *version2; /* 1 octet */ + const u8 *msg_type; /* 1 octet */ + const u8 *enrollee_nonce; /* WPS_NONCE_LEN (16) octets */ + const u8 *registrar_nonce; /* WPS_NONCE_LEN (16) octets */ + const u8 *uuid_r; /* WPS_UUID_LEN (16) octets */ + const u8 *uuid_e; /* WPS_UUID_LEN (16) octets */ + const u8 *auth_type_flags; /* 2 octets */ + const u8 *encr_type_flags; /* 2 octets */ + const u8 *conn_type_flags; /* 1 octet */ + const u8 *config_methods; /* 2 octets */ + const u8 *sel_reg_config_methods; /* 2 octets */ + const u8 *primary_dev_type; /* 8 octets */ + const u8 *rf_bands; /* 1 octet */ + const u8 *assoc_state; /* 2 octets */ + const u8 *config_error; /* 2 octets */ + const u8 *dev_password_id; /* 2 octets */ + const u8 *os_version; /* 4 octets */ + const u8 *wps_state; /* 1 octet */ + const u8 *authenticator; /* WPS_AUTHENTICATOR_LEN (8) octets */ + const u8 *r_hash1; /* WPS_HASH_LEN (32) octets */ + const u8 *r_hash2; /* WPS_HASH_LEN (32) octets */ + const u8 *e_hash1; /* WPS_HASH_LEN (32) octets */ + const u8 *e_hash2; /* WPS_HASH_LEN (32) octets */ + const u8 *r_snonce1; /* WPS_SECRET_NONCE_LEN (16) octets */ + const u8 *r_snonce2; /* WPS_SECRET_NONCE_LEN (16) octets */ + const u8 *e_snonce1; /* WPS_SECRET_NONCE_LEN (16) octets */ + const u8 *e_snonce2; /* WPS_SECRET_NONCE_LEN (16) octets */ + const u8 *key_wrap_auth; /* WPS_KWA_LEN (8) octets */ + const u8 *auth_type; /* 2 octets */ + const u8 *encr_type; /* 2 octets */ + const u8 *network_idx; /* 1 octet */ + const u8 *network_key_idx; /* 1 octet */ + const u8 *mac_addr; /* ETH_ALEN (6) octets */ + const u8 *key_prov_auto; /* 1 octet (Bool) */ + const u8 *dot1x_enabled; /* 1 octet (Bool) */ + const u8 *selected_registrar; /* 1 octet (Bool) */ + const u8 *request_type; /* 1 octet */ + const u8 *response_type; /* 1 octet */ + const u8 *ap_setup_locked; /* 1 octet */ + const u8 *settings_delay_time; /* 1 octet */ + const u8 *network_key_shareable; /* 1 octet (Bool) */ + const u8 *request_to_enroll; /* 1 octet (Bool) */ + const u8 *ap_channel; /* 2 octets */ + + /* variable length fields */ + const u8 *manufacturer; + size_t manufacturer_len; + const u8 *model_name; + size_t model_name_len; + const u8 *model_number; + size_t model_number_len; + const u8 *serial_number; + size_t serial_number_len; + const u8 *dev_name; + size_t dev_name_len; + const u8 *public_key; + size_t public_key_len; + const u8 *encr_settings; + size_t encr_settings_len; + const u8 *ssid; /* <= 32 octets */ + size_t ssid_len; + const u8 *network_key; /* <= 64 octets */ + size_t network_key_len; + const u8 *eap_type; /* <= 8 octets */ + size_t eap_type_len; + const u8 *eap_identity; /* <= 64 octets */ + size_t eap_identity_len; + const u8 *authorized_macs; /* <= 30 octets */ + size_t authorized_macs_len; + const u8 *sec_dev_type_list; /* <= 128 octets */ + size_t sec_dev_type_list_len; + const u8 *oob_dev_password; /* 38..54 octets */ + size_t oob_dev_password_len; + + /* attributes that can occur multiple times */ +#define MAX_CRED_COUNT 10 + const u8 *cred[MAX_CRED_COUNT]; + size_t cred_len[MAX_CRED_COUNT]; + size_t num_cred; + +#define MAX_REQ_DEV_TYPE_COUNT 10 + const u8 *req_dev_type[MAX_REQ_DEV_TYPE_COUNT]; + size_t num_req_dev_type; + + const u8 *vendor_ext[MAX_WPS_PARSE_VENDOR_EXT]; + size_t vendor_ext_len[MAX_WPS_PARSE_VENDOR_EXT]; + size_t num_vendor_ext; +}; + +int wps_parse_msg(const struct wpabuf *msg, struct wps_parse_attr *attr); + +#endif /* WPS_ATTR_PARSE_H */ diff --git a/tools/sdk/include/wpa_supplicant/wps/wps_defs.h b/tools/sdk/include/wpa_supplicant/wps/wps_defs.h new file mode 100644 index 00000000000..d100202da6e --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wps/wps_defs.h @@ -0,0 +1,342 @@ +/* + * Wi-Fi Protected Setup - message definitions + * Copyright (c) 2008, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef WPS_DEFS_H +#define WPS_DEFS_H + +#ifdef CONFIG_WPS_TESTING + +extern int wps_version_number; +extern int wps_testing_dummy_cred; +#define WPS_VERSION wps_version_number + +#else /* CONFIG_WPS_TESTING */ + +#ifdef CONFIG_WPS2 +#define WPS_VERSION 0x20 +#else /* CONFIG_WPS2 */ +#define WPS_VERSION 0x10 +#endif /* CONFIG_WPS2 */ + +#endif /* CONFIG_WPS_TESTING */ + +#define CONFIG_WPS_STRICT + +/* Diffie-Hellman 1536-bit MODP Group; RFC 3526, Group 5 */ +#define WPS_DH_GROUP 5 + +#define WPS_UUID_LEN 16 +#define WPS_NONCE_LEN 16 +#define WPS_AUTHENTICATOR_LEN 8 +#define WPS_AUTHKEY_LEN 32 +#define WPS_KEYWRAPKEY_LEN 16 +#define WPS_EMSK_LEN 32 +#define WPS_PSK_LEN 16 +#define WPS_SECRET_NONCE_LEN 16 +#define WPS_HASH_LEN 32 +#define WPS_KWA_LEN 8 +#define WPS_MGMTAUTHKEY_LEN 32 +#define WPS_MGMTENCKEY_LEN 16 +#define WPS_MGMT_KEY_ID_LEN 16 +#define WPS_OOB_DEVICE_PASSWORD_MIN_LEN 16 +#define WPS_OOB_DEVICE_PASSWORD_LEN 32 +#define WPS_OOB_PUBKEY_HASH_LEN 20 + +/* Attribute Types */ +enum wps_attribute { + ATTR_AP_CHANNEL = 0x1001, + ATTR_ASSOC_STATE = 0x1002, + ATTR_AUTH_TYPE = 0x1003, + ATTR_AUTH_TYPE_FLAGS = 0x1004, + ATTR_AUTHENTICATOR = 0x1005, + ATTR_CONFIG_METHODS = 0x1008, + ATTR_CONFIG_ERROR = 0x1009, + ATTR_CONFIRM_URL4 = 0x100a, + ATTR_CONFIRM_URL6 = 0x100b, + ATTR_CONN_TYPE = 0x100c, + ATTR_CONN_TYPE_FLAGS = 0x100d, + ATTR_CRED = 0x100e, + ATTR_ENCR_TYPE = 0x100f, + ATTR_ENCR_TYPE_FLAGS = 0x1010, + ATTR_DEV_NAME = 0x1011, + ATTR_DEV_PASSWORD_ID = 0x1012, + ATTR_E_HASH1 = 0x1014, + ATTR_E_HASH2 = 0x1015, + ATTR_E_SNONCE1 = 0x1016, + ATTR_E_SNONCE2 = 0x1017, + ATTR_ENCR_SETTINGS = 0x1018, + ATTR_ENROLLEE_NONCE = 0x101a, + ATTR_FEATURE_ID = 0x101b, + ATTR_IDENTITY = 0x101c, + ATTR_IDENTITY_PROOF = 0x101d, + ATTR_KEY_WRAP_AUTH = 0x101e, + ATTR_KEY_ID = 0x101f, + ATTR_MAC_ADDR = 0x1020, + ATTR_MANUFACTURER = 0x1021, + ATTR_MSG_TYPE = 0x1022, + ATTR_MODEL_NAME = 0x1023, + ATTR_MODEL_NUMBER = 0x1024, + ATTR_NETWORK_INDEX = 0x1026, + ATTR_NETWORK_KEY = 0x1027, + ATTR_NETWORK_KEY_INDEX = 0x1028, + ATTR_NEW_DEVICE_NAME = 0x1029, + ATTR_NEW_PASSWORD = 0x102a, + ATTR_OOB_DEVICE_PASSWORD = 0x102c, + ATTR_OS_VERSION = 0x102d, + ATTR_POWER_LEVEL = 0x102f, + ATTR_PSK_CURRENT = 0x1030, + ATTR_PSK_MAX = 0x1031, + ATTR_PUBLIC_KEY = 0x1032, + ATTR_RADIO_ENABLE = 0x1033, + ATTR_REBOOT = 0x1034, + ATTR_REGISTRAR_CURRENT = 0x1035, + ATTR_REGISTRAR_ESTABLISHED = 0x1036, + ATTR_REGISTRAR_LIST = 0x1037, + ATTR_REGISTRAR_MAX = 0x1038, + ATTR_REGISTRAR_NONCE = 0x1039, + ATTR_REQUEST_TYPE = 0x103a, + ATTR_RESPONSE_TYPE = 0x103b, + ATTR_RF_BANDS = 0x103c, + ATTR_R_HASH1 = 0x103d, + ATTR_R_HASH2 = 0x103e, + ATTR_R_SNONCE1 = 0x103f, + ATTR_R_SNONCE2 = 0x1040, + ATTR_SELECTED_REGISTRAR = 0x1041, + ATTR_SERIAL_NUMBER = 0x1042, + ATTR_WPS_STATE = 0x1044, + ATTR_SSID = 0x1045, + ATTR_TOTAL_NETWORKS = 0x1046, + ATTR_UUID_E = 0x1047, + ATTR_UUID_R = 0x1048, + ATTR_VENDOR_EXT = 0x1049, + ATTR_VERSION = 0x104a, + ATTR_X509_CERT_REQ = 0x104b, + ATTR_X509_CERT = 0x104c, + ATTR_EAP_IDENTITY = 0x104d, + ATTR_MSG_COUNTER = 0x104e, + ATTR_PUBKEY_HASH = 0x104f, + ATTR_REKEY_KEY = 0x1050, + ATTR_KEY_LIFETIME = 0x1051, + ATTR_PERMITTED_CFG_METHODS = 0x1052, + ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053, + ATTR_PRIMARY_DEV_TYPE = 0x1054, + ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055, + ATTR_PORTABLE_DEV = 0x1056, + ATTR_AP_SETUP_LOCKED = 0x1057, + ATTR_APPLICATION_EXT = 0x1058, + ATTR_EAP_TYPE = 0x1059, + ATTR_IV = 0x1060, + ATTR_KEY_PROVIDED_AUTO = 0x1061, + ATTR_802_1X_ENABLED = 0x1062, + ATTR_APPSESSIONKEY = 0x1063, + ATTR_WEPTRANSMITKEY = 0x1064, + ATTR_REQUESTED_DEV_TYPE = 0x106a, + ATTR_EXTENSIBILITY_TEST = 0x10fa /* _NOT_ defined in the spec */ +}; + +#define WPS_VENDOR_ID_WFA 14122 + +/* WFA Vendor Extension subelements */ +enum { + WFA_ELEM_VERSION2 = 0x00, + WFA_ELEM_AUTHORIZEDMACS = 0x01, + WFA_ELEM_NETWORK_KEY_SHAREABLE = 0x02, + WFA_ELEM_REQUEST_TO_ENROLL = 0x03, + WFA_ELEM_SETTINGS_DELAY_TIME = 0x04 +}; + +/* Device Password ID */ +enum wps_dev_password_id { + DEV_PW_DEFAULT = 0x0000, + DEV_PW_USER_SPECIFIED = 0x0001, + DEV_PW_MACHINE_SPECIFIED = 0x0002, + DEV_PW_REKEY = 0x0003, + DEV_PW_PUSHBUTTON = 0x0004, + DEV_PW_REGISTRAR_SPECIFIED = 0x0005 +}; + +/* WPS message flag */ +enum wps_msg_flag { + WPS_MSG_FLAG_MORE = 0x01, + WPS_MSG_FLAG_LEN = 0x02 +}; + +/* Message Type */ +enum wps_msg_type { + WPS_Beacon = 0x01, + WPS_ProbeRequest = 0x02, + WPS_ProbeResponse = 0x03, + WPS_M1 = 0x04, + WPS_M2 = 0x05, + WPS_M2D = 0x06, + WPS_M3 = 0x07, + WPS_M4 = 0x08, + WPS_M5 = 0x09, + WPS_M6 = 0x0a, + WPS_M7 = 0x0b, + WPS_M8 = 0x0c, + WPS_WSC_ACK = 0x0d, + WPS_WSC_NACK = 0x0e, + WPS_WSC_DONE = 0x0f +}; + +/* Authentication Type Flags */ +#define WPS_WIFI_AUTH_OPEN 0x0001 +#define WPS_AUTH_WPAPSK 0x0002 +#define WPS_AUTH_SHARED 0x0004 +#define WPS_AUTH_WPA 0x0008 +#define WPS_AUTH_WPA2 0x0010 +#define WPS_AUTH_WPA2PSK 0x0020 +#define WPS_AUTH_TYPES (WPS_WIFI_AUTH_OPEN | WPS_AUTH_WPAPSK | WPS_AUTH_SHARED | \ + WPS_AUTH_WPA | WPS_AUTH_WPA2 | WPS_AUTH_WPA2PSK) + +/* Encryption Type Flags */ +#define WPS_ENCR_NONE 0x0001 +#define WPS_ENCR_WEP 0x0002 +#define WPS_ENCR_TKIP 0x0004 +#define WPS_ENCR_AES 0x0008 +#define WPS_ENCR_TYPES (WPS_ENCR_NONE | WPS_ENCR_WEP | WPS_ENCR_TKIP | \ + WPS_ENCR_AES) + +/* Configuration Error */ +enum wps_config_error { + WPS_CFG_NO_ERROR = 0, + WPS_CFG_OOB_IFACE_READ_ERROR = 1, + WPS_CFG_DECRYPTION_CRC_FAILURE = 2, + WPS_CFG_24_CHAN_NOT_SUPPORTED = 3, + WPS_CFG_50_CHAN_NOT_SUPPORTED = 4, + WPS_CFG_SIGNAL_TOO_WEAK = 5, + WPS_CFG_NETWORK_AUTH_FAILURE = 6, + WPS_CFG_NETWORK_ASSOC_FAILURE = 7, + WPS_CFG_NO_DHCP_RESPONSE = 8, + WPS_CFG_FAILED_DHCP_CONFIG = 9, + WPS_CFG_IP_ADDR_CONFLICT = 10, + WPS_CFG_NO_CONN_TO_REGISTRAR = 11, + WPS_CFG_MULTIPLE_PBC_DETECTED = 12, + WPS_CFG_ROGUE_SUSPECTED = 13, + WPS_CFG_DEVICE_BUSY = 14, + WPS_CFG_SETUP_LOCKED = 15, + WPS_CFG_MSG_TIMEOUT = 16, + WPS_CFG_REG_SESS_TIMEOUT = 17, + WPS_CFG_DEV_PASSWORD_AUTH_FAILURE = 18 +}; + +/* Vendor specific Error Indication for WPS event messages */ +enum wps_error_indication { + WPS_EI_NO_ERROR, + WPS_EI_SECURITY_TKIP_ONLY_PROHIBITED, + WPS_EI_SECURITY_WEP_PROHIBITED, + NUM_WPS_EI_VALUES +}; + +/* RF Bands */ +#define WPS_RF_24GHZ 0x01 +#define WPS_RF_50GHZ 0x02 + +/* Config Methods */ +#define WPS_CONFIG_USBA 0x0001 +#define WPS_CONFIG_ETHERNET 0x0002 +#define WPS_CONFIG_LABEL 0x0004 +#define WPS_CONFIG_DISPLAY 0x0008 +#define WPS_CONFIG_EXT_NFC_TOKEN 0x0010 +#define WPS_CONFIG_INT_NFC_TOKEN 0x0020 +#define WPS_CONFIG_NFC_INTERFACE 0x0040 +#define WPS_CONFIG_PUSHBUTTON 0x0080 +#define WPS_CONFIG_KEYPAD 0x0100 +#ifdef CONFIG_WPS2 +#define WPS_CONFIG_VIRT_PUSHBUTTON 0x0280 +#define WPS_CONFIG_PHY_PUSHBUTTON 0x0480 +#define WPS_CONFIG_VIRT_DISPLAY 0x2008 +#define WPS_CONFIG_PHY_DISPLAY 0x4008 +#endif /* CONFIG_WPS2 */ + +/* Connection Type Flags */ +#define WPS_CONN_ESS 0x01 +#define WPS_CONN_IBSS 0x02 + +/* Wi-Fi Protected Setup State */ +enum wps_state { + WPS_STATE_NOT_CONFIGURED = 1, + WPS_STATE_CONFIGURED = 2 +}; + +/* Association State */ +enum wps_assoc_state { + WPS_ASSOC_NOT_ASSOC = 0, + WPS_ASSOC_CONN_SUCCESS = 1, + WPS_ASSOC_CFG_FAILURE = 2, + WPS_ASSOC_FAILURE = 3, + WPS_ASSOC_IP_FAILURE = 4 +}; + + +#define WPS_DEV_OUI_WFA 0x0050f204 + +enum wps_dev_categ { + WPS_DEV_COMPUTER = 1, + WPS_DEV_INPUT = 2, + WPS_DEV_PRINTER = 3, + WPS_DEV_CAMERA = 4, + WPS_DEV_STORAGE = 5, + WPS_DEV_NETWORK_INFRA = 6, + WPS_DEV_DISPLAY = 7, + WPS_DEV_MULTIMEDIA = 8, + WPS_DEV_GAMING = 9, + WPS_DEV_PHONE = 10 +}; + +enum wps_dev_subcateg { + WPS_DEV_COMPUTER_PC = 1, + WPS_DEV_COMPUTER_SERVER = 2, + WPS_DEV_COMPUTER_MEDIA_CENTER = 3, + WPS_DEV_PRINTER_PRINTER = 1, + WPS_DEV_PRINTER_SCANNER = 2, + WPS_DEV_CAMERA_DIGITAL_STILL_CAMERA = 1, + WPS_DEV_STORAGE_NAS = 1, + WPS_DEV_NETWORK_INFRA_AP = 1, + WPS_DEV_NETWORK_INFRA_ROUTER = 2, + WPS_DEV_NETWORK_INFRA_SWITCH = 3, + WPS_DEV_DISPLAY_TV = 1, + WPS_DEV_DISPLAY_PICTURE_FRAME = 2, + WPS_DEV_DISPLAY_PROJECTOR = 3, + WPS_DEV_MULTIMEDIA_DAR = 1, + WPS_DEV_MULTIMEDIA_PVR = 2, + WPS_DEV_MULTIMEDIA_MCX = 3, + WPS_DEV_GAMING_XBOX = 1, + WPS_DEV_GAMING_XBOX360 = 2, + WPS_DEV_GAMING_PLAYSTATION = 3, + WPS_DEV_PHONE_WINDOWS_MOBILE = 1 +}; + + +/* Request Type */ +enum wps_request_type { + WPS_REQ_ENROLLEE_INFO = 0, + WPS_REQ_ENROLLEE = 1, + WPS_REQ_REGISTRAR = 2, + WPS_REQ_WLAN_MANAGER_REGISTRAR = 3 +}; + +/* Response Type */ +enum wps_response_type { + WPS_RESP_ENROLLEE_INFO = 0, + WPS_RESP_ENROLLEE = 1, + WPS_RESP_REGISTRAR = 2, + WPS_RESP_AP = 3 +}; + +/* Walk Time for push button configuration (in seconds) */ +#define WPS_PBC_WALK_TIME 120 + +#define WPS_MAX_AUTHORIZED_MACS 5 + +#define WPS_IGNORE_SEL_REG_MAX_CNT 4 + +#define WPS_MAX_DIS_AP_NUM 10 + +#endif /* WPS_DEFS_H */ diff --git a/tools/sdk/include/wpa_supplicant/wps/wps_dev_attr.h b/tools/sdk/include/wpa_supplicant/wps/wps_dev_attr.h new file mode 100644 index 00000000000..200c9c45adc --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wps/wps_dev_attr.h @@ -0,0 +1,39 @@ +/* + * Wi-Fi Protected Setup - device attributes + * Copyright (c) 2008, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef WPS_DEV_ATTR_H +#define WPS_DEV_ATTR_H + +struct wps_parse_attr; + +int wps_build_manufacturer(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_model_name(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_model_number(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_dev_name(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_device_attrs(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_os_version(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_vendor_ext_m1(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_rf_bands(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_primary_dev_type(struct wps_device_data *dev, + struct wpabuf *msg); +int wps_build_secondary_dev_type(struct wps_device_data *dev, + struct wpabuf *msg); +int wps_build_dev_name(struct wps_device_data *dev, struct wpabuf *msg); +int wps_process_device_attrs(struct wps_device_data *dev, + struct wps_parse_attr *attr); +int wps_process_os_version(struct wps_device_data *dev, const u8 *ver); +int wps_process_rf_bands(struct wps_device_data *dev, const u8 *bands); +void wps_device_data_dup(struct wps_device_data *dst, + const struct wps_device_data *src); +void wps_device_data_free(struct wps_device_data *dev); +int wps_build_vendor_ext(struct wps_device_data *dev, struct wpabuf *msg); +int wps_build_req_dev_type(struct wps_device_data *dev, struct wpabuf *msg, + unsigned int num_req_dev_types, + const u8 *req_dev_types); + +#endif /* WPS_DEV_ATTR_H */ diff --git a/tools/sdk/include/wpa_supplicant/wps/wps_i.h b/tools/sdk/include/wpa_supplicant/wps/wps_i.h new file mode 100644 index 00000000000..c20d5ef917c --- /dev/null +++ b/tools/sdk/include/wpa_supplicant/wps/wps_i.h @@ -0,0 +1,217 @@ +/* + * Wi-Fi Protected Setup - internal definitions + * Copyright (c) 2008-2012, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef WPS_I_H +#define WPS_I_H + +#include "wps.h" +#include "wps_attr_parse.h" +#include "esp_wifi_crypto_types.h" + +#ifdef CONFIG_WPS_NFC +struct wps_nfc_pw_token; +#endif +/** + * struct wps_data - WPS registration protocol data + * + * This data is stored at the EAP-WSC server/peer method and it is kept for a + * single registration protocol run. + */ +struct wps_data { + /** + * wps - Pointer to long term WPS context + */ + struct wps_context *wps; + + /** + * registrar - Whether this end is a Registrar + */ + int registrar; + + /** + * er - Whether the local end is an external registrar + */ + int er; + + enum { + /* Enrollee states */ + SEND_M1, RECV_M2, SEND_M3, RECV_M4, SEND_M5, RECV_M6, SEND_M7, + RECV_M8, RECEIVED_M2D, WPS_MSG_DONE, RECV_ACK, WPS_FINISHED, + SEND_WSC_NACK, + + /* Registrar states */ + RECV_M1, SEND_M2, RECV_M3, SEND_M4, RECV_M5, SEND_M6, + RECV_M7, SEND_M8, RECV_DONE, SEND_M2D, RECV_M2D_ACK + } state; + + u8 uuid_e[WPS_UUID_LEN]; + u8 uuid_r[WPS_UUID_LEN]; + u8 mac_addr_e[ETH_ALEN]; + u8 nonce_e[WPS_NONCE_LEN]; + u8 nonce_r[WPS_NONCE_LEN]; + u8 psk1[WPS_PSK_LEN]; + u8 psk2[WPS_PSK_LEN]; + u8 snonce[2 * WPS_SECRET_NONCE_LEN]; + u8 peer_hash1[WPS_HASH_LEN]; + u8 peer_hash2[WPS_HASH_LEN]; + + struct wpabuf *dh_privkey; + struct wpabuf *dh_pubkey_e; + struct wpabuf *dh_pubkey_r; + u8 authkey[WPS_AUTHKEY_LEN]; + u8 keywrapkey[WPS_KEYWRAPKEY_LEN]; + u8 emsk[WPS_EMSK_LEN]; + + struct wpabuf *last_msg; + + u8 *dev_password; + size_t dev_password_len; + u16 dev_pw_id; + int pbc; + + /** + * request_type - Request Type attribute from (Re)AssocReq + */ + u8 request_type; + + /** + * encr_type - Available encryption types + */ + u16 encr_type; + + /** + * auth_type - Available authentication types + */ + u16 auth_type; + + u8 *new_psk; + size_t new_psk_len; + + int wps_pin_revealed; + struct wps_credential cred; + + struct wps_device_data peer_dev; + + /** + * config_error - Configuration Error value to be used in NACK + */ + u16 config_error; + u16 error_indication; + + int ext_reg; + int int_reg; + + struct wps_credential *new_ap_settings; + + void *dh_ctx; + + void (*ap_settings_cb)(void *ctx, const struct wps_credential *cred); + void *ap_settings_cb_ctx; + + struct wps_credential *use_cred; + + int use_psk_key; + u8 p2p_dev_addr[ETH_ALEN]; /* P2P Device Address of the client or + * 00:00:00:00:00:00 if not a P2p client */ + int pbc_in_m1; +#ifdef CONFIG_WPS_NFC + struct wps_nfc_pw_token *nfc_pw_token; +#endif +}; + +wps_crypto_funcs_t wps_crypto_funcs; + +/* wps_common.c */ +void wps_kdf(const u8 *key, const u8 *label_prefix, size_t label_prefix_len, + const char *label, u8 *res, size_t res_len); +int wps_derive_keys(struct wps_data *wps); +void wps_derive_psk(struct wps_data *wps, const u8 *dev_passwd, + size_t dev_passwd_len); +struct wpabuf * wps_decrypt_encr_settings(struct wps_data *wps, const u8 *encr, + size_t encr_len); +void wps_fail_event(struct wps_context *wps, enum wps_msg_type msg, + u16 config_error, u16 error_indication); +void wps_success_event(struct wps_context *wps); +void wps_pwd_auth_fail_event(struct wps_context *wps, int enrollee, int part); +void wps_pbc_overlap_event(struct wps_context *wps); +void wps_pbc_timeout_event(struct wps_context *wps); + +struct wpabuf * wps_build_wsc_ack(struct wps_data *wps); +struct wpabuf * wps_build_wsc_nack(struct wps_data *wps); + +typedef enum wps_calc_key_mode { + WPS_CALC_KEY_NORMAL = 0, + WPS_CALC_KEY_NO_CALC, + WPS_CALC_KEY_PRE_CALC, + WPS_CALC_KEY_MAX, +} wps_key_mode_t; + +/* wps_attr_build.c */ +int wps_build_public_key(struct wps_data *wps, struct wpabuf *msg, wps_key_mode_t mode); +int wps_build_req_type(struct wpabuf *msg, enum wps_request_type type); +int wps_build_resp_type(struct wpabuf *msg, enum wps_response_type type); +int wps_build_config_methods(struct wpabuf *msg, u16 methods); +int wps_build_uuid_e(struct wpabuf *msg, const u8 *uuid); +int wps_build_dev_password_id(struct wpabuf *msg, u16 id); +int wps_build_config_error(struct wpabuf *msg, u16 err); +int wps_build_authenticator(struct wps_data *wps, struct wpabuf *msg); +int wps_build_key_wrap_auth(struct wps_data *wps, struct wpabuf *msg); +int wps_build_encr_settings(struct wps_data *wps, struct wpabuf *msg, + struct wpabuf *plain); +int wps_build_version(struct wpabuf *msg); +int wps_build_wfa_ext(struct wpabuf *msg, int req_to_enroll, + const u8 *auth_macs, size_t auth_macs_count); +int wps_build_msg_type(struct wpabuf *msg, enum wps_msg_type msg_type); +int wps_build_enrollee_nonce(struct wps_data *wps, struct wpabuf *msg); +int wps_build_registrar_nonce(struct wps_data *wps, struct wpabuf *msg); +int wps_build_auth_type_flags(struct wps_data *wps, struct wpabuf *msg); +int wps_build_encr_type_flags(struct wps_data *wps, struct wpabuf *msg); +int wps_build_conn_type_flags(struct wps_data *wps, struct wpabuf *msg); +int wps_build_assoc_state(struct wps_data *wps, struct wpabuf *msg); +int wps_build_oob_dev_pw(struct wpabuf *msg, u16 dev_pw_id, + const struct wpabuf *pubkey, const u8 *dev_pw, + size_t dev_pw_len); +struct wpabuf * wps_ie_encapsulate(struct wpabuf *data); + +/* wps_attr_process.c */ +int wps_process_authenticator(struct wps_data *wps, const u8 *authenticator, + const struct wpabuf *msg); +int wps_process_key_wrap_auth(struct wps_data *wps, struct wpabuf *msg, + const u8 *key_wrap_auth); +int wps_process_cred(struct wps_parse_attr *attr, + struct wps_credential *cred); +int wps_process_ap_settings(struct wps_parse_attr *attr, + struct wps_credential *cred); + +/* wps_enrollee.c */ +struct wpabuf * wps_enrollee_get_msg(struct wps_data *wps, + enum wsc_op_code *op_code); +enum wps_process_res wps_enrollee_process_msg(struct wps_data *wps, + enum wsc_op_code op_code, + const struct wpabuf *msg); + +/* wps_registrar.c */ +struct wpabuf * wps_registrar_get_msg(struct wps_data *wps, + enum wsc_op_code *op_code); +enum wps_process_res wps_registrar_process_msg(struct wps_data *wps, + enum wsc_op_code op_code, + const struct wpabuf *msg); +int wps_build_cred(struct wps_data *wps, struct wpabuf *msg); +int wps_device_store(struct wps_registrar *reg, + struct wps_device_data *dev, const u8 *uuid); +void wps_registrar_selected_registrar_changed(struct wps_registrar *reg); +const u8 * wps_authorized_macs(struct wps_registrar *reg, size_t *count); +int wps_registrar_pbc_overlap(struct wps_registrar *reg, + const u8 *addr, const u8 *uuid_e); +#ifdef CONFIG_WPS_NFC + +void wps_registrar_remove_nfc_pw_token(struct wps_registrar *reg, + struct wps_nfc_pw_token *token); +#endif + +#endif /* WPS_I_H */ diff --git a/tools/sdk/ld/esp32.common.ld b/tools/sdk/ld/esp32.common.ld index c6a92356c8f..179b1abdc21 100644 --- a/tools/sdk/ld/esp32.common.ld +++ b/tools/sdk/ld/esp32.common.ld @@ -10,34 +10,109 @@ SECTIONS { . = ALIGN(4); *(.rtc.literal .rtc.text) - *rtc_wake_stub*.o(.literal .text .literal.* .text.*) - } >rtc_iram_seg + *rtc_wake_stub*.*(.literal .text .literal.* .text.*) + _rtc_text_end = ABSOLUTE(.); + } > rtc_iram_seg + + /* + This section is required to skip rtc.text area because rtc_iram_seg and + rtc_data_seg are reflect the same address space on different buses. + */ + .rtc.dummy : + { + _rtc_dummy_start = ABSOLUTE(.); + _rtc_fast_start = ABSOLUTE(.); + . = SIZEOF(.rtc.text); + _rtc_dummy_end = ABSOLUTE(.); + } > rtc_data_seg + + /* This section located in RTC FAST Memory area. + It holds data marked with RTC_FAST_ATTR attribute. + See the file "esp_attr.h" for more information. + */ + .rtc.force_fast : + { + . = ALIGN(4); + _rtc_force_fast_start = ABSOLUTE(.); + *(.rtc.force_fast .rtc.force_fast.*) + . = ALIGN(4) ; + _rtc_force_fast_end = ABSOLUTE(.); + } > rtc_data_seg - /* RTC slow memory holds RTC wake stub + /* RTC data section holds RTC wake stub data/rodata, including from any source file - named rtc_wake_stub*.c + named rtc_wake_stub*.c and the data marked with + RTC_DATA_ATTR, RTC_RODATA_ATTR attributes. + The memory location of the data is dependent on + CONFIG_ESP32_RTCDATA_IN_FAST_MEM option. */ .rtc.data : { _rtc_data_start = ABSOLUTE(.); *(.rtc.data) *(.rtc.rodata) - *rtc_wake_stub*.o(.data .rodata .data.* .rodata.* .bss .bss.*) + *rtc_wake_stub*.*(.data .rodata .data.* .rodata.* .bss .bss.*) _rtc_data_end = ABSOLUTE(.); - } > rtc_slow_seg + } > rtc_data_location /* RTC bss, from any source file named rtc_wake_stub*.c */ .rtc.bss (NOLOAD) : { _rtc_bss_start = ABSOLUTE(.); - *rtc_wake_stub*.o(.bss .bss.*) - *rtc_wake_stub*.o(COMMON) + *rtc_wake_stub*.*(.bss .bss.*) + *rtc_wake_stub*.*(COMMON) + *(.rtc.bss) _rtc_bss_end = ABSOLUTE(.); + } > rtc_data_location + + /* This section holds data that should not be initialized at power up + and will be retained during deep sleep. + User data marked with RTC_NOINIT_ATTR will be placed + into this section. See the file "esp_attr.h" for more information. + The memory location of the data is dependent on + CONFIG_ESP32_RTCDATA_IN_FAST_MEM option. + */ + .rtc_noinit (NOLOAD): + { + . = ALIGN(4); + _rtc_noinit_start = ABSOLUTE(.); + *(.rtc_noinit .rtc_noinit.*) + . = ALIGN(4) ; + _rtc_noinit_end = ABSOLUTE(.); + } > rtc_data_location + + /* This section located in RTC SLOW Memory area. + It holds data marked with RTC_SLOW_ATTR attribute. + See the file "esp_attr.h" for more information. + */ + .rtc.force_slow : + { + . = ALIGN(4); + _rtc_force_slow_start = ABSOLUTE(.); + *(.rtc.force_slow .rtc.force_slow.*) + . = ALIGN(4) ; + _rtc_force_slow_end = ABSOLUTE(.); } > rtc_slow_seg + /* Get size of rtc slow data based on rtc_data_location alias */ + _rtc_slow_length = (ORIGIN(rtc_slow_seg) == ORIGIN(rtc_data_location)) + ? (_rtc_force_slow_end - _rtc_data_start) + : (_rtc_force_slow_end - _rtc_force_slow_start); + + _rtc_fast_length = (ORIGIN(rtc_slow_seg) == ORIGIN(rtc_data_location)) + ? (_rtc_force_fast_end - _rtc_fast_start) + : (_rtc_noinit_end - _rtc_fast_start); + + ASSERT((_rtc_slow_length <= LENGTH(rtc_slow_seg)), + "RTC_SLOW segment data does not fit.") + + ASSERT((_rtc_fast_length <= LENGTH(rtc_data_seg)), + "RTC_FAST segment data does not fit.") + /* Send .iram0 code to iram */ .iram0.vectors : { + _iram_start = ABSOLUTE(.); /* Vectors go to IRAM */ _init_start = ABSOLUTE(.); /* Vectors according to builds/RF-2015.2-win32/esp108_v1_2_s5_512int_2/config.html */ @@ -71,10 +146,6 @@ SECTIONS *(.init.literal) *(.init) _init_end = ABSOLUTE(.); - - /* This goes here, not at top of linker script, so addr2line finds it last, - and uses it in preference to the first symbol in IRAM */ - _iram_start = ABSOLUTE(0); } > iram0_0_seg .iram0.text : @@ -82,26 +153,41 @@ SECTIONS /* Code marked as runnning out of IRAM */ _iram_text_start = ABSOLUTE(.); *(.iram1 .iram1.*) + *libesp_ringbuf.a:(.literal .text .literal.* .text.*) *libfreertos.a:(.literal .text .literal.* .text.*) - *libheap.a:multi_heap.o(.literal .text .literal.* .text.*) - *libheap.a:multi_heap_poisoning.o(.literal .text .literal.* .text.*) - *libesp32.a:panic.o(.literal .text .literal.* .text.*) - *libesp32.a:core_dump.o(.literal .text .literal.* .text.*) + *libheap.a:multi_heap.*(.literal .text .literal.* .text.*) + *libheap.a:multi_heap_poisoning.*(.literal .text .literal.* .text.*) + *libesp32.a:panic.*(.literal .text .literal.* .text.*) + *libesp32.a:core_dump.*(.literal .text .literal.* .text.*) + INCLUDE wifi_iram.ld *libapp_trace.a:(.literal .text .literal.* .text.*) - *libxtensa-debug-module.a:eri.o(.literal .text .literal.* .text.*) + *libxtensa-debug-module.a:eri.*(.literal .text .literal.* .text.*) *librtc.a:(.literal .text .literal.* .text.*) - *libsoc.a:(.literal .text .literal.* .text.*) + *libsoc.a:rtc_*.*(.literal .text .literal.* .text.*) + *libsoc.a:cpu_util.*(.literal .text .literal.* .text.*) *libhal.a:(.literal .text .literal.* .text.*) - *libgcc.a:lib2funcs.o(.literal .text .literal.* .text.*) - *libspi_flash.a:spi_flash_rom_patch.o(.literal .text .literal.* .text.*) + *libgcc.a:lib2funcs.*(.literal .text .literal.* .text.*) + *libspi_flash.a:spi_flash_rom_patch.*(.literal .text .literal.* .text.*) *libgcov.a:(.literal .text .literal.* .text.*) INCLUDE esp32.spiram.rom-functions-iram.ld _iram_text_end = ABSOLUTE(.); + _iram_end = ABSOLUTE(.); } > iram0_0_seg + ASSERT(((_iram_text_end - ORIGIN(iram0_0_seg)) <= LENGTH(iram0_0_seg)), + "IRAM0 segment data does not fit.") + .dram0.data : { _data_start = ABSOLUTE(.); + _bt_data_start = ABSOLUTE(.); + *libbt.a:(.data .data.*) + . = ALIGN (4); + _bt_data_end = ABSOLUTE(.); + _btdm_data_start = ABSOLUTE(.); + *libbtdm_app.a:(.data .data.*) + . = ALIGN (4); + _btdm_data_end = ABSOLUTE(.); *(.data) *(.data.*) *(.gnu.linkonce.d.*) @@ -114,23 +200,46 @@ SECTIONS *(.gnu.linkonce.s2.*) *(.jcr) *(.dram1 .dram1.*) - *libesp32.a:panic.o(.rodata .rodata.*) + *libesp32.a:panic.*(.rodata .rodata.*) *libphy.a:(.rodata .rodata.*) - *libsoc.a:rtc_clk.o(.rodata .rodata.*) + *libsoc.a:rtc_clk.*(.rodata .rodata.*) *libapp_trace.a:(.rodata .rodata.*) *libgcov.a:(.rodata .rodata.*) - *libheap.a:multi_heap.o(.rodata .rodata.*) - *libheap.a:multi_heap_poisoning.o(.rodata .rodata.*) + *libheap.a:multi_heap.*(.rodata .rodata.*) + *libheap.a:multi_heap_poisoning.*(.rodata .rodata.*) INCLUDE esp32.spiram.rom-functions-dram.ld _data_end = ABSOLUTE(.); . = ALIGN(4); - } >dram0_0_seg + } > dram0_0_seg + + /*This section holds data that should not be initialized at power up. + The section located in Internal SRAM memory region. The macro _NOINIT + can be used as attribute to place data into this section. + See the esp_attr.h file for more information. + */ + .noinit (NOLOAD): + { + . = ALIGN(4); + _noinit_start = ABSOLUTE(.); + *(.noinit .noinit.*) + . = ALIGN(4) ; + _noinit_end = ABSOLUTE(.); + } > dram0_0_seg /* Shared RAM */ .dram0.bss (NOLOAD) : { . = ALIGN (8); _bss_start = ABSOLUTE(.); + *(.ext_ram.bss*) + _bt_bss_start = ABSOLUTE(.); + *libbt.a:(.bss .bss.* COMMON) + . = ALIGN (4); + _bt_bss_end = ABSOLUTE(.); + _btdm_bss_start = ABSOLUTE(.); + *libbtdm_app.a:(.bss .bss.* COMMON) + . = ALIGN (4); + _btdm_bss_end = ABSOLUTE(.); *(.dynsbss) *(.sbss) *(.sbss.*) @@ -147,9 +256,13 @@ SECTIONS *(COMMON) . = ALIGN (8); _bss_end = ABSOLUTE(.); + /* The heap starts right after end of this section */ _heap_start = ABSOLUTE(.); - } >dram0_0_seg + } > dram0_0_seg + ASSERT(((_bss_end - ORIGIN(dram0_0_seg)) <= LENGTH(dram0_0_seg)), + "DRAM segment data does not fit.") + .flash.rodata : { _rodata_start = ABSOLUTE(.); @@ -169,13 +282,13 @@ SECTIONS . = (. + 7) & ~ 3; /* C++ constructor and destructor tables, properly ordered: */ __init_array_start = ABSOLUTE(.); - KEEP (*crtbegin.o(.ctors)) - KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*crtbegin.*(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.*) .ctors)) KEEP (*(SORT(.ctors.*))) KEEP (*(.ctors)) __init_array_end = ABSOLUTE(.); - KEEP (*crtbegin.o(.dtors)) - KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*crtbegin.*(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.*) .dtors)) KEEP (*(SORT(.dtors.*))) KEEP (*(.dtors)) /* C++ exception handlers table: */ @@ -186,6 +299,11 @@ SECTIONS *(.xt_except_desc_end) *(.dynamic) *(.gnu.version_d) + /* Addresses of memory regions reserved via + SOC_RESERVE_MEMORY_REGION() */ + soc_reserved_memory_region_start = ABSOLUTE(.); + KEEP (*(.reserved_memory_address)) + soc_reserved_memory_region_end = ABSOLUTE(.); _rodata_end = ABSOLUTE(.); /* Literals are also RO data. */ _lit4_start = ABSOLUTE(.); @@ -209,6 +327,7 @@ SECTIONS _text_start = ABSOLUTE(.); *(.literal .text .literal.* .text.* .stub .gnu.warning .gnu.linkonce.literal.* .gnu.linkonce.t.*.literal .gnu.linkonce.t.*) *(.irom0.text) /* catch stray ICACHE_RODATA_ATTR */ + *(.wifi0iram .wifi0iram.*) /* catch stray WIFI_IRAM_ATTR */ *(.fini.literal) *(.fini) *(.gnu.version) diff --git a/tools/sdk/ld/esp32.extram.bss.ld b/tools/sdk/ld/esp32.extram.bss.ld new file mode 100644 index 00000000000..582f6eb6ea2 --- /dev/null +++ b/tools/sdk/ld/esp32.extram.bss.ld @@ -0,0 +1,18 @@ +/* This section is only included if CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY + is set, to link some sections to BSS in PSRAM */ + +SECTIONS +{ + /* external memory bss, from any global variable with EXT_RAM_ATTR attribute*/ + .ext_ram.bss (NOLOAD) : + { + _ext_ram_bss_start = ABSOLUTE(.); + *(.ext_ram.bss*) + *libnet80211.a:(.dynsbss .sbss .sbss.* .gnu.linkonce.sb.* .scommon .sbss2.* .gnu.linkonce.sb2.* .dynbss .bss .bss.* .share.mem .gnu.linkonce.b.* COMMON) + *libpp.a:(.dynsbss .sbss .sbss.* .gnu.linkonce.sb.* .scommon .sbss2.* .gnu.linkonce.sb2.* .dynbss .bss .bss.* .share.mem .gnu.linkonce.b.* COMMON) + *liblwip.a:(.dynsbss .sbss .sbss.* .gnu.linkonce.sb.* .scommon .sbss2.* .gnu.linkonce.sb2.* .dynbss .bss .bss.* .share.mem .gnu.linkonce.b.* COMMON) + *libbt.a:(EXCLUDE_FILE (libbtdm_app.a) .dynsbss .sbss .sbss.* .gnu.linkonce.sb.* .scommon .sbss2.* .gnu.linkonce.sb2.* .dynbss .bss .bss.* .share.mem .gnu.linkonce.b.* COMMON) + . = ALIGN(4); + _ext_ram_bss_end = ABSOLUTE(.); + } > extern_ram_seg +} diff --git a/tools/sdk/ld/esp32.ld b/tools/sdk/ld/esp32.ld index ee41f747931..fd02e0d2108 100644 --- a/tools/sdk/ld/esp32.ld +++ b/tools/sdk/ld/esp32.ld @@ -61,6 +61,9 @@ MEMORY /* RTC fast memory (executable). Persists over deep sleep. */ rtc_iram_seg(RWX) : org = 0x400C0000, len = 0x2000 + + /* RTC fast memory (same block as above), viewed from data bus */ + rtc_data_seg(RW) : org = 0x3ff80000, len = 0x2000 /* RTC slow memory (data accessible). Persists over deep sleep. @@ -68,7 +71,22 @@ MEMORY */ rtc_slow_seg(RW) : org = 0x50000000 + CONFIG_ULP_COPROC_RESERVE_MEM, len = 0x1000 - CONFIG_ULP_COPROC_RESERVE_MEM + + /* external memory ,including data and text */ + extern_ram_seg(RWX) : org = 0x3F800000, + len = 0x400000 } /* Heap ends at top of dram0_0_seg */ _heap_end = 0x40000000 - CONFIG_TRACEMEM_RESERVE_DRAM; + +_data_seg_org = ORIGIN(rtc_data_seg); + +/* The lines below define location alias for .rtc.data section based on Kconfig option. + When the option is not defined then use slow memory segment + else the data will be placed in fast memory segment */ +#ifndef CONFIG_ESP32_RTCDATA_IN_FAST_MEM +REGION_ALIAS("rtc_data_location", rtc_slow_seg ); +#else +REGION_ALIAS("rtc_data_location", rtc_data_seg ); +#endif diff --git a/tools/sdk/ld/esp32.peripherals.ld b/tools/sdk/ld/esp32.peripherals.ld index 621fedea13d..2dce0e0fcf7 100644 --- a/tools/sdk/ld/esp32.peripherals.ld +++ b/tools/sdk/ld/esp32.peripherals.ld @@ -6,14 +6,17 @@ PROVIDE ( SIGMADELTA = 0x3ff44f00 ); PROVIDE ( RTCCNTL = 0x3ff48000 ); PROVIDE ( RTCIO = 0x3ff48400 ); PROVIDE ( SENS = 0x3ff48800 ); +PROVIDE ( HINF = 0x3ff4B000 ); PROVIDE ( UHCI1 = 0x3ff4C000 ); PROVIDE ( I2S0 = 0x3ff4F000 ); PROVIDE ( UART1 = 0x3ff50000 ); PROVIDE ( I2C0 = 0x3ff53000 ); PROVIDE ( UHCI0 = 0x3ff54000 ); +PROVIDE ( HOST = 0x3ff55000 ); PROVIDE ( RMT = 0x3ff56000 ); PROVIDE ( RMTMEM = 0x3ff56800 ); PROVIDE ( PCNT = 0x3ff57000 ); +PROVIDE ( SLC = 0x3ff58000 ); PROVIDE ( LEDC = 0x3ff59000 ); PROVIDE ( MCPWM0 = 0x3ff5E000 ); PROVIDE ( TIMERG0 = 0x3ff5F000 ); @@ -23,6 +26,7 @@ PROVIDE ( SPI3 = 0x3ff65000 ); PROVIDE ( SYSCON = 0x3ff66000 ); PROVIDE ( I2C1 = 0x3ff67000 ); PROVIDE ( SDMMC = 0x3ff68000 ); +PROVIDE ( CAN = 0x3ff6B000 ); PROVIDE ( MCPWM1 = 0x3ff6C000 ); PROVIDE ( I2S1 = 0x3ff6D000 ); PROVIDE ( UART2 = 0x3ff6E000 ); diff --git a/tools/sdk/ld/esp32.rom.ld b/tools/sdk/ld/esp32.rom.ld index c1c1df0884e..c1e3e94bcb2 100644 --- a/tools/sdk/ld/esp32.rom.ld +++ b/tools/sdk/ld/esp32.rom.ld @@ -3,33 +3,17 @@ ESP32 ROM address table Generated for ROM with MD5sum: ab8282ae908fe9e7a63fb2a4ac2df013 ../../rom_image/prorom.elf */ -PROVIDE ( abort = 0x4000bba4 ); -PROVIDE ( __absvdi2 = 0x4006387c ); -PROVIDE ( __absvsi2 = 0x40063868 ); PROVIDE ( Add2SelfBigHex256 = 0x40015b7c ); PROVIDE ( AddBigHex256 = 0x40015b28 ); PROVIDE ( AddBigHexModP256 = 0x40015c98 ); -PROVIDE ( __adddf3 = 0x40002590 ); PROVIDE ( AddP256 = 0x40015c74 ); PROVIDE ( AddPdiv2_256 = 0x40015ce0 ); -PROVIDE ( __addsf3 = 0x400020e8 ); -PROVIDE ( __addvdi3 = 0x40002cbc ); -PROVIDE ( __addvsi3 = 0x40002c98 ); -PROVIDE ( aes_128_cbc_decrypt = 0x4005cc7c ); -PROVIDE ( aes_128_cbc_encrypt = 0x4005cc18 ); -PROVIDE ( aes_unwrap = 0x4005ccf0 ); PROVIDE ( app_gpio_arg = 0x3ffe003c ); PROVIDE ( app_gpio_handler = 0x3ffe0040 ); -PROVIDE ( __ashldi3 = 0x4000c818 ); -PROVIDE ( __ashrdi3 = 0x4000c830 ); -PROVIDE ( base64_decode = 0x4005ced8 ); -PROVIDE ( base64_encode = 0x4005cdbc ); PROVIDE ( BasePoint_x_256 = 0x3ff97488 ); PROVIDE ( BasePoint_y_256 = 0x3ff97468 ); PROVIDE ( bigHexInversion256 = 0x400168f0 ); PROVIDE ( bigHexP256 = 0x3ff973bc ); -PROVIDE ( __bswapdi2 = 0x400649c4 ); -PROVIDE ( __bswapsi2 = 0x4006499c ); PROVIDE ( btdm_r_ble_bt_handler_tab_p_get = 0x40019b0c ); PROVIDE ( btdm_r_btdm_option_data_p_get = 0x40010004 ); PROVIDE ( btdm_r_btdm_rom_version_get = 0x40010078 ); @@ -50,14 +34,8 @@ PROVIDE ( cache_sram_mmu_set_rom = 0x400097f4 ); /* This is static function, but can be used, not generated by script*/ PROVIDE ( calc_rtc_memory_crc = 0x40008170 ); PROVIDE ( calloc = 0x4000bee4 ); -PROVIDE ( _calloc_r = 0x4000bbf8 ); PROVIDE ( __clear_cache = 0x40063860 ); PROVIDE ( _close_r = 0x4000bd3c ); -PROVIDE ( __clrsbdi2 = 0x40064a38 ); -PROVIDE ( __clrsbsi2 = 0x40064a20 ); -PROVIDE ( __clzdi2 = 0x4000ca50 ); -PROVIDE ( __clzsi2 = 0x4000c7e8 ); -PROVIDE ( __cmpdi2 = 0x40063820 ); PROVIDE ( co_default_bdaddr = 0x3ffae704 ); PROVIDE ( co_null_bdaddr = 0x3ffb80e0 ); PROVIDE ( co_sca2ppm = 0x3ff971e8 ); @@ -69,8 +47,6 @@ PROVIDE ( crc8_be = 0x4005d114 ); PROVIDE ( crc8_le = 0x4005d0e0 ); PROVIDE ( _ctype_ = 0x3ff96354 ); PROVIDE ( __ctype_ptr__ = 0x3ff96350 ); -PROVIDE ( __ctzdi2 = 0x4000ca64 ); -PROVIDE ( __ctzsi2 = 0x4000c7f0 ); PROVIDE ( _data_end_rom = 0x4000d5c8 ); PROVIDE ( _data_end_btdm_rom = 0x4000d4f8 ); PROVIDE ( _data_start_rom = 0x4000d4f8 ); @@ -81,6 +57,7 @@ PROVIDE ( _bss_start_btdm = 0x3ffb8000); PROVIDE ( _bss_end_btdm = 0x3ffbff70); PROVIDE ( _daylight = 0x3ffae0a4 ); PROVIDE ( dbg_default_handler = 0x3ff97218 ); +PROVIDE ( dbg_default_state = 0x3ff97220 ); PROVIDE ( dbg_state = 0x3ffb8d5d ); PROVIDE ( DebugE256PublicKey_x = 0x3ff97428 ); PROVIDE ( DebugE256PublicKey_y = 0x3ff97408 ); @@ -103,60 +80,28 @@ PROVIDE ( dh_group2_generator = 0x3ff9ada2 ); PROVIDE ( dh_group2_prime = 0x3ff9ad22 ); PROVIDE ( dh_group5_generator = 0x3ff9ad21 ); PROVIDE ( dh_group5_prime = 0x3ff9ac61 ); -PROVIDE ( __divdc3 = 0x40064460 ); -PROVIDE ( __divdf3 = 0x40002954 ); -PROVIDE ( __divdi3 = 0x4000ca84 ); -PROVIDE ( __divsc3 = 0x40064200 ); -PROVIDE ( __divsf3 = 0x4000234c ); -PROVIDE ( __divsi3 = 0x4000c7b8 ); PROVIDE ( g_rom_spiflash_dummy_len_plus = 0x3ffae290 ); PROVIDE ( ecc_env = 0x3ffb8d60 ); PROVIDE ( ecc_Jacobian_InfinityPoint256 = 0x3ff972e8 ); PROVIDE ( em_buf_env = 0x3ffb8d74 ); PROVIDE ( environ = 0x3ffae0b4 ); -PROVIDE ( __eqdf2 = 0x400636a8 ); -PROVIDE ( __eqsf2 = 0x40063374 ); PROVIDE ( esp_crc8 = 0x4005d144 ); PROVIDE ( _etext = 0x4000d66c ); PROVIDE ( ets_readySet_ = 0x3ffe01f0 ); PROVIDE ( ets_startup_callback = 0x3ffe0404 ); +PROVIDE ( rwip_coex_cfg = 0x3ff9914c ); +PROVIDE ( rwip_priority = 0x3ff99159 ); PROVIDE ( exc_cause_table = 0x3ff991d0 ); PROVIDE ( _exit_r = 0x4000bd28 ); -PROVIDE ( __extendsfdf2 = 0x40002c34 ); -PROVIDE ( __ffsdi2 = 0x4000ca2c ); -PROVIDE ( __ffssi2 = 0x4000c804 ); -PROVIDE ( __fixdfdi = 0x40002ac4 ); -PROVIDE ( __fixdfsi = 0x40002a78 ); -PROVIDE ( __fixsfdi = 0x4000244c ); -PROVIDE ( __fixsfsi = 0x4000240c ); -PROVIDE ( __fixunsdfsi = 0x40002b30 ); -PROVIDE ( __fixunssfdi = 0x40002504 ); -PROVIDE ( __fixunssfsi = 0x400024ac ); -PROVIDE ( __floatdidf = 0x4000c988 ); -PROVIDE ( __floatdisf = 0x4000c8c0 ); -PROVIDE ( __floatsidf = 0x4000c944 ); -PROVIDE ( __floatsisf = 0x4000c870 ); -PROVIDE ( __floatundidf = 0x4000c978 ); -PROVIDE ( __floatundisf = 0x4000c8b0 ); -PROVIDE ( __floatunsidf = 0x4000c938 ); -PROVIDE ( __floatunsisf = 0x4000c864 ); PROVIDE ( free = 0x4000beb8 ); -PROVIDE ( _free_r = 0x4000bbcc ); PROVIDE ( _fstat_r = 0x4000bccc ); PROVIDE ( __gcc_bcmp = 0x40064a70 ); -PROVIDE ( __gedf2 = 0x40063768 ); -PROVIDE ( __gesf2 = 0x4006340c ); -PROVIDE ( _getpid_r = 0x4000bcfc ); -PROVIDE ( __getreent = 0x4000be8c ); -PROVIDE ( _gettimeofday_r = 0x4000bc58 ); PROVIDE ( GF_Jacobian_Point_Addition256 = 0x400163a4 ); PROVIDE ( GF_Jacobian_Point_Double256 = 0x40016260 ); PROVIDE ( GF_Point_Jacobian_To_Affine256 = 0x40016b0c ); PROVIDE ( _global_impure_ptr = 0x3ffae0b0 ); PROVIDE ( g_phyFuns_instance = 0x3ffae0c4 ); PROVIDE ( g_rom_flashchip = 0x3ffae270 ); -PROVIDE ( __gtdf2 = 0x400636dc ); -PROVIDE ( __gtsf2 = 0x400633a0 ); PROVIDE ( gTxMsg = 0x3ffe0050 ); PROVIDE ( hci_cmd_desc_root_tab = 0x3ff976d4 ); PROVIDE ( hci_cmd_desc_tab_ctrl_bb = 0x3ff97b70 ); @@ -169,20 +114,14 @@ PROVIDE ( hci_cmd_desc_tab_testing = 0x3ff97a98 ); PROVIDE ( hci_cmd_desc_tab_vs = 0x3ff97714 ); PROVIDE ( hci_command_handler = 0x4004c928 ); PROVIDE ( hci_env = 0x3ffb9350 ); +PROVIDE ( rwip_env = 0x3ffb8bcc ); PROVIDE ( hci_evt_dbg_desc_tab = 0x3ff9750c ); PROVIDE ( hci_evt_desc_tab = 0x3ff9751c ); PROVIDE ( hci_evt_le_desc_tab = 0x3ff974b4 ); PROVIDE ( hci_fc_env = 0x3ffb9340 ); -PROVIDE ( hmac_md5 = 0x4005d264 ); -PROVIDE ( hmac_md5_vector = 0x4005d17c ); -PROVIDE ( hmac_sha1 = 0x40060acc ); -PROVIDE ( hmac_sha1_vector = 0x400609e4 ); -PROVIDE ( hmac_sha256 = 0x40060d58 ); -PROVIDE ( hmac_sha256_vector = 0x40060c84 ); PROVIDE ( jd_decomp = 0x400613e8 ); PROVIDE ( jd_prepare = 0x40060fa8 ); PROVIDE ( ke_env = 0x3ffb93cc ); -PROVIDE ( _kill_r = 0x4000bd10 ); PROVIDE ( lb_default_handler = 0x3ff982b8 ); PROVIDE ( lb_default_state_tab_p_get = 0x4001c198 ); PROVIDE ( lb_env = 0x3ffb9424 ); @@ -201,8 +140,6 @@ PROVIDE ( ld_env = 0x3ffb9510 ); PROVIDE ( ld_pcm_settings_dft = 0x3ff98a0c ); PROVIDE ( ld_sched_params = 0x3ffb96c0 ); PROVIDE ( ld_sync_train_channels = 0x3ff98a3c ); -PROVIDE ( __ledf2 = 0x40063704 ); -PROVIDE ( __lesf2 = 0x400633c0 ); PROVIDE ( _link_r = 0x4000bc9c ); PROVIDE ( llc_default_handler = 0x3ff98b3c ); PROVIDE ( llc_default_state_tab_p_get = 0x40046058 ); @@ -225,6 +162,7 @@ PROVIDE ( lld_evt_elt_wait_get = 0x400468e4 ); PROVIDE ( lld_evt_get_next_free_slot = 0x4004692c ); PROVIDE ( lld_pdu_adv_pk_desc_tab = 0x3ff98c70 ); PROVIDE ( lld_pdu_llcp_pk_desc_tab = 0x3ff98b68 ); +PROVIDE ( lld_pdu_tx_flush_list = 0x4004a760 ); PROVIDE ( lld_pdu_pack = 0x4004ab14 ); PROVIDE ( LLM_AA_CT1 = 0x3ff98d8a ); PROVIDE ( LLM_AA_CT2 = 0x3ff98d88 ); @@ -246,64 +184,23 @@ PROVIDE ( lm_n_page_tab = 0x3ff990e8 ); PROVIDE ( lmp_desc_tab = 0x3ff96e6c ); PROVIDE ( lmp_ext_desc_tab = 0x3ff96d9c ); PROVIDE ( lm_state = 0x3ffb9a1c ); -PROVIDE ( _lock_acquire_recursive = 0x4000be28 ); -PROVIDE ( _lock_close = 0x4000bdec ); -PROVIDE ( _lock_close_recursive = 0x4000be00 ); -PROVIDE ( _lock_init = 0x4000bdc4 ); -PROVIDE ( _lock_init_recursive = 0x4000bdd8 ); -PROVIDE ( _lock_release_recursive = 0x4000be78 ); -PROVIDE ( _lock_try_acquire = 0x4000be3c ); -PROVIDE ( _lock_try_acquire_recursive = 0x4000be50 ); PROVIDE ( _lseek_r = 0x4000bd8c ); -PROVIDE ( __lshrdi3 = 0x4000c84c ); -PROVIDE ( __ltdf2 = 0x40063790 ); -PROVIDE ( __ltsf2 = 0x4006342c ); PROVIDE ( malloc = 0x4000bea0 ); -PROVIDE ( _malloc_r = 0x4000bbb4 ); PROVIDE ( maxSecretKey_256 = 0x3ff97448 ); PROVIDE ( __mb_cur_max = 0x3ff96530 ); -PROVIDE ( MD5Final = 0x4005db1c ); -PROVIDE ( MD5Init = 0x4005da7c ); -PROVIDE ( MD5Update = 0x4005da9c ); -PROVIDE ( md5_vector = 0x4005db80 ); PROVIDE ( mmu_init = 0x400095a4 ); -PROVIDE ( __moddi3 = 0x4000cd4c ); -PROVIDE ( __modsi3 = 0x4000c7c0 ); PROVIDE ( __month_lengths = 0x3ff9609c ); -PROVIDE ( __muldc3 = 0x40063bf4 ); -PROVIDE ( __muldf3 = 0x4006358c ); -PROVIDE ( __muldi3 = 0x4000c9fc ); -PROVIDE ( __mulsc3 = 0x40063934 ); -PROVIDE ( __mulsf3 = 0x400632c8 ); -PROVIDE ( __mulsi3 = 0x4000c7b0 ); PROVIDE ( MultiplyBigHexByUint32_256 = 0x40016214 ); PROVIDE ( MultiplyBigHexModP256 = 0x400160b8 ); PROVIDE ( MultiplyByU32ModP256 = 0x40015fdc ); PROVIDE ( multofup = 0x4000ab8c ); -PROVIDE ( __mulvdi3 = 0x40002d78 ); -PROVIDE ( __mulvsi3 = 0x40002d60 ); PROVIDE ( mz_adler32 = 0x4005edbc ); PROVIDE ( mz_crc32 = 0x4005ee88 ); PROVIDE ( mz_free = 0x4005eed4 ); -PROVIDE ( __nedf2 = 0x400636a8 ); -PROVIDE ( __negdf2 = 0x400634a0 ); -PROVIDE ( __negdi2 = 0x4000ca14 ); -PROVIDE ( __negsf2 = 0x400020c0 ); -PROVIDE ( __negvdi2 = 0x40002e98 ); -PROVIDE ( __negvsi2 = 0x40002e78 ); -PROVIDE ( __nesf2 = 0x40063374 ); PROVIDE ( notEqual256 = 0x40015b04 ); -PROVIDE ( __nsau_data = 0x3ff96544 ); PROVIDE ( one_bits = 0x3ff971f8 ); PROVIDE ( _open_r = 0x4000bd54 ); -PROVIDE ( __paritysi2 = 0x40002f3c ); -PROVIDE ( pbkdf2_sha1 = 0x40060ba4 ); PROVIDE ( phy_get_romfuncs = 0x40004100 ); -PROVIDE ( __popcountdi2 = 0x40002ef8 ); -PROVIDE ( __popcountsi2 = 0x40002ed0 ); -PROVIDE ( __popcount_tab = 0x3ff96544 ); -PROVIDE ( __powidf2 = 0x400638d4 ); -PROVIDE ( __powisf2 = 0x4006389c ); PROVIDE ( _Pri_4_HandlerAddress = 0x3ffe0648 ); PROVIDE ( _Pri_5_HandlerAddress = 0x3ffe064c ); PROVIDE ( r_btdm_option_data = 0x3ffae6e0 ); @@ -320,7 +217,6 @@ PROVIDE ( r_bt_util_buf_sync_rx_alloc = 0x40010468 ); PROVIDE ( r_bt_util_buf_sync_rx_free = 0x4001049c ); PROVIDE ( r_bt_util_buf_sync_tx_alloc = 0x400103ec ); PROVIDE ( r_bt_util_buf_sync_tx_free = 0x40010428 ); -PROVIDE ( rc4_skip = 0x40060928 ); PROVIDE ( r_co_bdaddr_compare = 0x40014324 ); PROVIDE ( r_co_bytes_to_string = 0x400142e4 ); PROVIDE ( r_co_list_check_size_available = 0x400142c4 ); @@ -347,6 +243,9 @@ PROVIDE ( r_E1 = 0x400108e8 ); PROVIDE ( r_E21 = 0x40010968 ); PROVIDE ( r_E22 = 0x400109b4 ); PROVIDE ( r_E3 = 0x40010a58 ); +PROVIDE ( lm_n192_mod_mul = 0x40011dc0 ); +PROVIDE ( lm_n192_mod_add = 0x40011e9c ); +PROVIDE ( lm_n192_mod_sub = 0x40011eec ); PROVIDE ( r_ea_alarm_clear = 0x40015ab4 ); PROVIDE ( r_ea_alarm_set = 0x40015a10 ); PROVIDE ( _read_r = 0x4000bda8 ); @@ -364,7 +263,6 @@ PROVIDE ( r_ea_interval_remove = 0x40015590 ); PROVIDE ( ea_conflict_check = 0x40014e9c ); PROVIDE ( ea_prog_timer = 0x40014f88 ); PROVIDE ( realloc = 0x4000becc ); -PROVIDE ( _realloc_r = 0x4000bbe0 ); PROVIDE ( r_ea_offset_req = 0x40015748 ); PROVIDE ( r_ea_sleep_check = 0x40015928 ); PROVIDE ( r_ea_sw_isr = 0x40015724 ); @@ -376,6 +274,7 @@ PROVIDE ( r_ecc_gen_new_public_key = 0x400170c0 ); PROVIDE ( r_ecc_gen_new_secret_key = 0x400170e4 ); PROVIDE ( r_ecc_get_debug_Keys = 0x40017224 ); PROVIDE ( r_ecc_init = 0x40016dbc ); +PROVIDE ( ecc_point_multiplication_uint8_256 = 0x40016804); PROVIDE ( RecvBuff = 0x3ffe009c ); PROVIDE ( r_em_buf_init = 0x4001729c ); PROVIDE ( r_em_buf_rx_buff_addr_get = 0x400173e8 ); @@ -674,6 +573,14 @@ PROVIDE ( r_lc_util_get_offset_clke = 0x4002f538 ); PROVIDE ( r_lc_util_get_offset_clkn = 0x4002f51c ); PROVIDE ( r_lc_util_set_loc_trans_coll = 0x4002f500 ); PROVIDE ( r_lc_version = 0x40020a30 ); +PROVIDE ( lc_set_encap_pdu_data_p192 = 0x4002e4c8 ); +PROVIDE ( lc_set_encap_pdu_data_p256 = 0x4002e454 ); +PROVIDE ( lm_get_auth_method = 0x40023420); +PROVIDE ( lmp_accepted_ext_handler = 0x40027290 ); +PROVIDE ( lmp_not_accepted_ext_handler = 0x40029c54 ); +PROVIDE ( lmp_clk_adj_handler = 0x40027468 ); +PROVIDE ( lmp_clk_adj_ack_handler = 0x400274f4 ); +PROVIDE ( lm_get_auth_method = 0x40023420); PROVIDE ( lmp_accepted_ext_handler = 0x40027290 ); PROVIDE ( lmp_not_accepted_ext_handler = 0x40029c54 ); PROVIDE ( lmp_clk_adj_handler = 0x40027468 ); @@ -761,7 +668,19 @@ PROVIDE ( lmp_io_cap_req_handler = 0x4002c7a4 ); PROVIDE ( ld_acl_tx_packet_type_select = 0x4002fb40 ); PROVIDE ( ld_acl_sched = 0x40033268 ); PROVIDE ( ld_acl_sniff_sched = 0x4003340c ); +PROVIDE ( ld_acl_rx = 0x4003274c ); +PROVIDE ( ld_acl_tx = 0x4002ffdc ); +PROVIDE ( ld_acl_rx_sync = 0x4002fbec ); +PROVIDE ( ld_acl_rx_sync2 = 0x4002fd8c ); +PROVIDE ( ld_acl_rx_no_sync = 0x4002fe78 ); +PROVIDE ( ld_acl_clk_isr = 0x40030cf8 ); +PROVIDE ( ld_sco_modify = 0x40031778 ); PROVIDE ( lm_cmd_cmp_send = 0x40051838 ); +PROVIDE ( ld_sco_frm_cbk = 0x400349dc ); +PROVIDE ( ld_acl_sniff_frm_cbk = 0x4003482c ); +PROVIDE ( ld_inq_end = 0x4003ab48 ); +PROVIDE ( ld_inq_sched = 0x4003aba4 ); +PROVIDE ( ld_inq_frm_cbk = 0x4003ae4c ); PROVIDE ( r_ld_acl_active_hop_types_get = 0x40036e10 ); PROVIDE ( r_ld_acl_afh_confirm = 0x40036d40 ); PROVIDE ( r_ld_acl_afh_prepare = 0x40036c84 ); @@ -1371,14 +1290,9 @@ PROVIDE ( rwip_priority = 0x3ff99159 ); PROVIDE ( rwip_rf = 0x3ffbdb28 ); PROVIDE ( rwip_rf_p_get = 0x400558f4 ); PROVIDE ( r_XorKey = 0x400112c0 ); -PROVIDE ( _sbrk_r = 0x4000bce4 ); PROVIDE ( __sf_fake_stderr = 0x3ff96458 ); PROVIDE ( __sf_fake_stdin = 0x3ff96498 ); PROVIDE ( __sf_fake_stdout = 0x3ff96478 ); -PROVIDE ( sha1_prf = 0x40060ae8 ); -PROVIDE ( sha1_vector = 0x40060b64 ); -PROVIDE ( sha256_prf = 0x40060d70 ); -PROVIDE ( sha256_vector = 0x40060e08 ); PROVIDE ( sha_blk_bits = 0x3ff99290 ); PROVIDE ( sha_blk_bits_bytes = 0x3ff99288 ); PROVIDE ( sha_blk_hash_bytes = 0x3ff9928c ); @@ -1417,15 +1331,11 @@ PROVIDE ( _start = 0x40000704 ); PROVIDE ( start_tb_console = 0x4005a980 ); PROVIDE ( _stat_r = 0x4000bcb4 ); PROVIDE ( _stext = 0x40000560 ); -PROVIDE ( __subdf3 = 0x400026e4 ); -PROVIDE ( __subsf3 = 0x400021d0 ); PROVIDE ( SubtractBigHex256 = 0x40015bcc ); PROVIDE ( SubtractBigHexMod256 = 0x40015e8c ); PROVIDE ( SubtractBigHexUint32_256 = 0x40015f8c ); PROVIDE ( SubtractFromSelfBigHex256 = 0x40015c20 ); PROVIDE ( SubtractFromSelfBigHexSign256 = 0x40015dc8 ); -PROVIDE ( __subvdi3 = 0x40002d20 ); -PROVIDE ( __subvsi3 = 0x40002cf8 ); PROVIDE ( sw_to_hw = 0x3ffb8d40 ); PROVIDE ( syscall_table_ptr_app = 0x3ffae020 ); PROVIDE ( syscall_table_ptr_pro = 0x3ffae024 ); @@ -1438,25 +1348,13 @@ PROVIDE ( tdefl_get_prev_return_status = 0x400608d0 ); PROVIDE ( tdefl_init = 0x40060810 ); PROVIDE ( tdefl_write_image_to_png_file_in_memory = 0x4006091c ); PROVIDE ( tdefl_write_image_to_png_file_in_memory_ex = 0x40060910 ); -PROVIDE ( _times_r = 0x4000bc40 ); PROVIDE ( _timezone = 0x3ffae0a0 ); PROVIDE ( tinfl_decompress = 0x4005ef30 ); PROVIDE ( tinfl_decompress_mem_to_callback = 0x40060090 ); PROVIDE ( tinfl_decompress_mem_to_mem = 0x40060050 ); -PROVIDE ( __truncdfsf2 = 0x40002b90 ); PROVIDE ( _tzname = 0x3ffae030 ); PROVIDE ( UartDev = 0x3ffe019c ); -PROVIDE ( __ucmpdi2 = 0x40063840 ); -PROVIDE ( __udivdi3 = 0x4000cff8 ); -PROVIDE ( __udivmoddi4 = 0x40064ab0 ); -PROVIDE ( __udivsi3 = 0x4000c7c8 ); -PROVIDE ( __udiv_w_sdiv = 0x40064aa8 ); -PROVIDE ( __umoddi3 = 0x4000d280 ); -PROVIDE ( __umodsi3 = 0x4000c7d0 ); -PROVIDE ( __umulsidi3 = 0x4000c7d8 ); PROVIDE ( _unlink_r = 0x4000bc84 ); -PROVIDE ( __unorddf2 = 0x400637f4 ); -PROVIDE ( __unordsf2 = 0x40063478 ); PROVIDE ( user_code_start = 0x3ffe0400 ); PROVIDE ( veryBigHexP256 = 0x3ff9736c ); PROVIDE ( __wctomb = 0x3ff96540 ); @@ -1484,8 +1382,8 @@ PROVIDE ( esp_rom_spiflash_attach = 0x40062a6c ); PROVIDE ( esp_rom_spiflash_config_clk = 0x40062bc8 ); PROVIDE ( g_rom_spiflash_chip = 0x3ffae270 ); -/* -These functions are xtos-related (or call xtos-related functions) and do not play well +/* +These functions are xtos-related (or call xtos-related functions) and do not play well with multicore FreeRTOS. Where needed, we provide alternatives that are multicore compatible. These functions also use a chunk of static RAM, by not using them we can allocate that RAM for general use. @@ -1582,7 +1480,6 @@ PROVIDE ( uart_tx_flush = 0x40009258 ); PROVIDE ( uart_tx_one_char = 0x40009200 ); PROVIDE ( uart_tx_one_char2 = 0x4000922c ); PROVIDE ( uart_tx_switch = 0x40009028 ); -PROVIDE ( uart_tx_wait_idle = 0x40009278 ); /* @@ -1649,8 +1546,6 @@ PROVIDE ( ets_efuse_read_op = 0x40008600 ); PROVIDE ( ets_intr_lock = 0x400067b0 ); PROVIDE ( ets_intr_unlock = 0x400067c4 ); PROVIDE ( ets_isr_attach = 0x400067ec ); -PROVIDE ( ets_isr_mask = 0x400067fc ); -PROVIDE ( ets_isr_unmask = 0x40006808 ); PROVIDE ( ets_waiti0 = 0x400067d8 ); PROVIDE ( intr_matrix_set = 0x4000681c ); PROVIDE ( check_pos = 0x400068b8 ); @@ -1690,19 +1585,14 @@ PROVIDE ( ets_delay_us = 0x40008534 ); PROVIDE ( ets_get_cpu_frequency = 0x4000855c ); PROVIDE ( ets_get_detected_xtal_freq = 0x40008588 ); PROVIDE ( ets_get_xtal_scale = 0x4000856c ); -PROVIDE ( ets_timer_arm = 0x40008368 ); -PROVIDE ( ets_timer_arm_us = 0x400083ac ); -PROVIDE ( ets_timer_disarm = 0x400083ec ); -PROVIDE ( ets_timer_done = 0x40008428 ); -PROVIDE ( ets_timer_handler_isr = 0x40008454 ); -PROVIDE ( ets_timer_init = 0x400084e8 ); -PROVIDE ( ets_timer_setfn = 0x40008350 ); PROVIDE ( ets_update_cpu_frequency_rom = 0x40008550 ); /* Updates g_ticks_per_us on the current CPU only; not on the other core */ /* Following are static data, but can be used, not generated by script <<<<< btdm data */ PROVIDE ( hci_tl_env = 0x3ffb8154 ); PROVIDE ( ld_acl_env = 0x3ffb8258 ); PROVIDE ( ea_env = 0x3ffb80ec ); +PROVIDE ( lc_sco_data_path_config = 0x3ffb81f8 ); +PROVIDE ( lc_sco_env = 0x3ffb81fc ); PROVIDE ( ld_active_ch_map = 0x3ffb8334 ); PROVIDE ( ld_bcst_acl_env = 0x3ffb8274 ); PROVIDE ( ld_csb_rx_env = 0x3ffb8278 ); diff --git a/tools/sdk/ld/esp32.rom.libgcc.ld b/tools/sdk/ld/esp32.rom.libgcc.ld new file mode 100644 index 00000000000..51448b33272 --- /dev/null +++ b/tools/sdk/ld/esp32.rom.libgcc.ld @@ -0,0 +1,91 @@ +__absvdi2 = 0x4006387c; +__absvsi2 = 0x40063868; +__adddf3 = 0x40002590; +__addsf3 = 0x400020e8; +__addvdi3 = 0x40002cbc; +__addvsi3 = 0x40002c98; +__ashldi3 = 0x4000c818; +__ashrdi3 = 0x4000c830; +__bswapdi2 = 0x40064b08; +__bswapsi2 = 0x40064ae0; +__clrsbdi2 = 0x40064b7c; +__clrsbsi2 = 0x40064b64; +__clzdi2 = 0x4000ca50; +__clzsi2 = 0x4000c7e8; +__cmpdi2 = 0x40063820; +__ctzdi2 = 0x4000ca64; +__ctzsi2 = 0x4000c7f0; +__divdc3 = 0x400645a4; +__divdf3 = 0x40002954; +__divdi3 = 0x4000ca84; +__divsc3 = 0x4006429c; +__divsf3 = 0x4000234c; +__divsi3 = 0x4000c7b8; +__eqdf2 = 0x400636a8; +__eqsf2 = 0x40063374; +__extendsfdf2 = 0x40002c34; +__ffsdi2 = 0x4000ca2c; +__ffssi2 = 0x4000c804; +__fixdfdi = 0x40002ac4; +__fixdfsi = 0x40002a78; +__fixsfdi = 0x4000244c; +__fixsfsi = 0x4000240c; +__fixunsdfsi = 0x40002b30; +__fixunssfdi = 0x40002504; +__fixunssfsi = 0x400024ac; +__floatdidf = 0x4000c988; +__floatdisf = 0x4000c8c0; +__floatsidf = 0x4000c944; +__floatsisf = 0x4000c870; +__floatundidf = 0x4000c978; +__floatundisf = 0x4000c8b0; +__floatunsidf = 0x4000c938; +__floatunsisf = 0x4000c864; +__gedf2 = 0x40063768; +__gesf2 = 0x4006340c; +__gtdf2 = 0x400636dc; +__gtsf2 = 0x400633a0; +__ledf2 = 0x40063704; +__lesf2 = 0x400633c0; +__lshrdi3 = 0x4000c84c; +__ltdf2 = 0x40063790; +__ltsf2 = 0x4006342c; +__moddi3 = 0x4000cd4c; +__modsi3 = 0x4000c7c0; +__muldc3 = 0x40063c90; +__muldf3 = 0x4006358c; +__muldi3 = 0x4000c9fc; +__mulsc3 = 0x40063944; +__mulsf3 = 0x400632c8; +__mulsi3 = 0x4000c7b0; +__mulvdi3 = 0x40002d78; +__mulvsi3 = 0x40002d60; +__nedf2 = 0x400636a8; +__negdf2 = 0x400634a0; +__negdi2 = 0x4000ca14; +__negsf2 = 0x400020c0; +__negvdi2 = 0x40002e98; +__negvsi2 = 0x40002e78; +__nesf2 = 0x40063374; +__nsau_data = 0x3ff96544; +__paritysi2 = 0x40002f3c; +__popcount_tab = 0x3ff96544; +__popcountdi2 = 0x40002ef8; +__popcountsi2 = 0x40002ed0; +__powidf2 = 0x400638e4; +__powisf2 = 0x4006389c; +__subdf3 = 0x400026e4; +__subsf3 = 0x400021d0; +__subvdi3 = 0x40002d20; +__subvsi3 = 0x40002cf8; +__truncdfsf2 = 0x40002b90; +__ucmpdi2 = 0x40063840; +__udiv_w_sdiv = 0x40064bec; +__udivdi3 = 0x4000cff8; +__udivmoddi4 = 0x40064bf4; +__udivsi3 = 0x4000c7c8; +__umoddi3 = 0x4000d280; +__umodsi3 = 0x4000c7d0; +__umulsidi3 = 0x4000c7d8; +__unorddf2 = 0x400637f4; +__unordsf2 = 0x40063478; diff --git a/tools/sdk/ld/esp32.rom.redefined.ld b/tools/sdk/ld/esp32.rom.redefined.ld new file mode 100644 index 00000000000..c229640a20e --- /dev/null +++ b/tools/sdk/ld/esp32.rom.redefined.ld @@ -0,0 +1,60 @@ +/* + ROM Functions defined in this file are not used in ESP-IDF as is, + and different definitions for functions with the same names are provided. + This file is not used when linking ESP-IDF and is intended for reference only +*/ + +PROVIDE ( abort = 0x4000bba4 ); +PROVIDE ( aes_128_cbc_decrypt = 0x4005cc7c ); +PROVIDE ( aes_128_cbc_encrypt = 0x4005cc18 ); +PROVIDE ( aes_unwrap = 0x4005ccf0 ); +PROVIDE ( base64_decode = 0x4005ced8 ); +PROVIDE ( base64_encode = 0x4005cdbc ); +PROVIDE ( ets_isr_mask = 0x400067fc ); +PROVIDE ( ets_isr_unmask = 0x40006808 ); +PROVIDE ( ets_timer_arm = 0x40008368 ); +PROVIDE ( ets_timer_arm_us = 0x400083ac ); +PROVIDE ( ets_timer_disarm = 0x400083ec ); +PROVIDE ( ets_timer_done = 0x40008428 ); +PROVIDE ( ets_timer_init = 0x400084e8 ); +PROVIDE ( ets_timer_handler_isr = 0x40008454 ); +PROVIDE ( ets_timer_setfn = 0x40008350 ); +PROVIDE ( _free_r = 0x4000bbcc ); +PROVIDE ( _getpid_r = 0x4000bcfc ); +PROVIDE ( __getreent = 0x4000be8c ); +PROVIDE ( _gettimeofday_r = 0x4000bc58 ); +PROVIDE ( hmac_md5 = 0x4005d264 ); +PROVIDE ( hmac_md5_vector = 0x4005d17c ); +PROVIDE ( hmac_sha1 = 0x40060acc ); +PROVIDE ( hmac_sha1_vector = 0x400609e4 ); +PROVIDE ( hmac_sha256 = 0x40060d58 ); +PROVIDE ( hmac_sha256_vector = 0x40060c84 ); +PROVIDE ( _kill_r = 0x4000bd10 ); +PROVIDE ( _lock_acquire = 0x4000be14 ); +PROVIDE ( _lock_acquire_recursive = 0x4000be28 ); +PROVIDE ( _lock_close = 0x4000bdec ); +PROVIDE ( _lock_close_recursive = 0x4000be00 ); +PROVIDE ( _lock_init = 0x4000bdc4 ); +PROVIDE ( _lock_init_recursive = 0x4000bdd8 ); +PROVIDE ( _lock_release = 0x4000be64 ); +PROVIDE ( _lock_release_recursive = 0x4000be78 ); +PROVIDE ( _lock_try_acquire = 0x4000be3c ); +PROVIDE ( _lock_try_acquire_recursive = 0x4000be50 ); +PROVIDE ( _malloc_r = 0x4000bbb4 ); +PROVIDE ( MD5Final = 0x4005db1c ); +PROVIDE ( MD5Init = 0x4005da7c ); +PROVIDE ( MD5Update = 0x4005da9c ); +PROVIDE ( md5_vector = 0x4005db80 ); +PROVIDE ( pbkdf2_sha1 = 0x40060ba4 ); +PROVIDE ( rc4_skip = 0x40060928 ); +PROVIDE ( _raise_r = 0x4000bc70 ); +PROVIDE ( _realloc_r = 0x4000bbe0 ); +PROVIDE ( _sbrk_r = 0x4000bce4 ); +PROVIDE ( sha1_prf = 0x40060ae8 ); +PROVIDE ( sha1_vector = 0x40060b64 ); +PROVIDE ( sha256_prf = 0x40060d70 ); +PROVIDE ( sha256_vector = 0x40060e08 ); +PROVIDE ( _system_r = 0x4000bc10 ); +PROVIDE ( _times_r = 0x4000bc40 ); +PROVIDE ( uart_tx_wait_idle = 0x40009278 ); + diff --git a/tools/sdk/ld/esp32.rom.spiram_incompatible_fns.ld b/tools/sdk/ld/esp32.rom.spiram_incompatible_fns.ld index e4899b6616d..17a38d35573 100644 --- a/tools/sdk/ld/esp32.rom.spiram_incompatible_fns.ld +++ b/tools/sdk/ld/esp32.rom.spiram_incompatible_fns.ld @@ -64,8 +64,6 @@ PROVIDE ( __locale_mb_cur_max = 0x40059548 ); PROVIDE ( __locale_msgcharset = 0x40059550 ); PROVIDE ( localtime = 0x400595dc ); PROVIDE ( localtime_r = 0x400595fc ); -PROVIDE ( _lock_acquire = 0x4000be14 ); -PROVIDE ( _lock_release = 0x4000be64 ); PROVIDE ( longjmp = 0x400562cc ); PROVIDE ( memccpy = 0x4000c220 ); PROVIDE ( memchr = 0x4000c244 ); @@ -77,7 +75,6 @@ PROVIDE ( memset = 0x4000c44c ); PROVIDE ( mktime = 0x4005a5e8 ); PROVIDE ( open = 0x4000178c ); PROVIDE ( qsort = 0x40056424 ); -PROVIDE ( _raise_r = 0x4000bc70 ); PROVIDE ( rand = 0x40001058 ); PROVIDE ( rand_r = 0x400010d4 ); PROVIDE ( read = 0x400017dc ); @@ -145,7 +142,6 @@ PROVIDE ( __swbuf = 0x40058cb4 ); PROVIDE ( __swbuf_r = 0x40058bec ); PROVIDE ( __swrite = 0x40001150 ); PROVIDE ( __swsetup_r = 0x40058cc8 ); -PROVIDE ( _system_r = 0x4000bc10 ); PROVIDE ( time = 0x40001844 ); PROVIDE ( __time_load_locale = 0x4000183c ); PROVIDE ( times = 0x40001808 ); diff --git a/tools/sdk/ld/esp32.spiram.rom-functions-dram.ld b/tools/sdk/ld/esp32.spiram.rom-functions-dram.ld index da59bc09c4e..205d9471f82 100644 --- a/tools/sdk/ld/esp32.spiram.rom-functions-dram.ld +++ b/tools/sdk/ld/esp32.spiram.rom-functions-dram.ld @@ -8,136 +8,136 @@ This file is responsible for placing the rodata segment in DRAM. */ - *lib_a-utoa.o(.rodata .rodata.*) - *lib_a-longjmp.o(.rodata .rodata.*) - *lib_a-setjmp.o(.rodata .rodata.*) - *lib_a-abs.o(.rodata .rodata.*) - *lib_a-div.o(.rodata .rodata.*) - *lib_a-labs.o(.rodata .rodata.*) - *lib_a-ldiv.o(.rodata .rodata.*) - *lib_a-quorem.o(.rodata .rodata.*) - *lib_a-qsort.o(.rodata .rodata.*) - *lib_a-utoa.o(.rodata .rodata.*) - *lib_a-itoa.o(.rodata .rodata.*) - *lib_a-atoi.o(.rodata .rodata.*) - *lib_a-atol.o(.rodata .rodata.*) - *lib_a-strtol.o(.rodata .rodata.*) - *lib_a-strtoul.o(.rodata .rodata.*) - *lib_a-wcrtomb.o(.rodata .rodata.*) - *lib_a-fvwrite.o(.rodata .rodata.*) - *lib_a-wbuf.o(.rodata .rodata.*) - *lib_a-wsetup.o(.rodata .rodata.*) - *lib_a-fputwc.o(.rodata .rodata.*) - *lib_a-wctomb_r.o(.rodata .rodata.*) - *lib_a-ungetc.o(.rodata .rodata.*) - *lib_a-makebuf.o(.rodata .rodata.*) - *lib_a-fflush.o(.rodata .rodata.*) - *lib_a-refill.o(.rodata .rodata.*) - *lib_a-s_fpclassify.o(.rodata .rodata.*) - *lib_a-locale.o(.rodata .rodata.*) - *lib_a-asctime.o(.rodata .rodata.*) - *lib_a-ctime.o(.rodata .rodata.*) - *lib_a-ctime_r.o(.rodata .rodata.*) - *lib_a-lcltime.o(.rodata .rodata.*) - *lib_a-lcltime_r.o(.rodata .rodata.*) - *lib_a-gmtime.o(.rodata .rodata.*) - *lib_a-gmtime_r.o(.rodata .rodata.*) - *lib_a-strftime.o(.rodata .rodata.*) - *lib_a-mktime.o(.rodata .rodata.*) - *lib_a-syswrite.o(.rodata .rodata.*) - *lib_a-tzset_r.o(.rodata .rodata.*) - *lib_a-tzset.o(.rodata .rodata.*) - *lib_a-toupper.o(.rodata .rodata.*) - *lib_a-tolower.o(.rodata .rodata.*) - *lib_a-toascii.o(.rodata .rodata.*) - *lib_a-systimes.o(.rodata .rodata.*) - *lib_a-time.o(.rodata .rodata.*) - *lib_a-bsd_qsort_r.o(.rodata .rodata.*) - *lib_a-qsort_r.o(.rodata .rodata.*) - *lib_a-gettzinfo.o(.rodata .rodata.*) - *lib_a-strupr.o(.rodata .rodata.*) - *lib_a-asctime_r.o(.rodata .rodata.*) - *lib_a-bzero.o(.rodata .rodata.*) - *lib_a-close.o(.rodata .rodata.*) - *lib_a-creat.o(.rodata .rodata.*) - *lib_a-environ.o(.rodata .rodata.*) - *lib_a-fclose.o(.rodata .rodata.*) - *lib_a-isalnum.o(.rodata .rodata.*) - *lib_a-isalpha.o(.rodata .rodata.*) - *lib_a-isascii.o(.rodata .rodata.*) - *lib_a-isblank.o(.rodata .rodata.*) - *lib_a-iscntrl.o(.rodata .rodata.*) - *lib_a-isdigit.o(.rodata .rodata.*) - *lib_a-isgraph.o(.rodata .rodata.*) - *lib_a-islower.o(.rodata .rodata.*) - *lib_a-isprint.o(.rodata .rodata.*) - *lib_a-ispunct.o(.rodata .rodata.*) - *lib_a-isspace.o(.rodata .rodata.*) - *lib_a-isupper.o(.rodata .rodata.*) - *lib_a-memccpy.o(.rodata .rodata.*) - *lib_a-memchr.o(.rodata .rodata.*) - *lib_a-memcmp.o(.rodata .rodata.*) - *lib_a-memcpy.o(.rodata .rodata.*) - *lib_a-memmove.o(.rodata .rodata.*) - *lib_a-memrchr.o(.rodata .rodata.*) - *lib_a-memset.o(.rodata .rodata.*) - *lib_a-open.o(.rodata .rodata.*) - *lib_a-rand.o(.rodata .rodata.*) - *lib_a-rand_r.o(.rodata .rodata.*) - *lib_a-read.o(.rodata .rodata.*) - *lib_a-rshift.o(.rodata .rodata.*) - *lib_a-sbrk.o(.rodata .rodata.*) - *lib_a-srand.o(.rodata .rodata.*) - *lib_a-strcasecmp.o(.rodata .rodata.*) - *lib_a-strcasestr.o(.rodata .rodata.*) - *lib_a-strcat.o(.rodata .rodata.*) - *lib_a-strchr.o(.rodata .rodata.*) - *lib_a-strcmp.o(.rodata .rodata.*) - *lib_a-strcoll.o(.rodata .rodata.*) - *lib_a-strcpy.o(.rodata .rodata.*) - *lib_a-strcspn.o(.rodata .rodata.*) - *lib_a-strdup.o(.rodata .rodata.*) - *lib_a-strlcat.o(.rodata .rodata.*) - *lib_a-strlcpy.o(.rodata .rodata.*) - *lib_a-strlen.o(.rodata .rodata.*) - *lib_a-strlwr.o(.rodata .rodata.*) - *lib_a-strncasecmp.o(.rodata .rodata.*) - *lib_a-strncat.o(.rodata .rodata.*) - *lib_a-strncmp.o(.rodata .rodata.*) - *lib_a-strncpy.o(.rodata .rodata.*) - *lib_a-strndup.o(.rodata .rodata.*) - *lib_a-strnlen.o(.rodata .rodata.*) - *lib_a-strrchr.o(.rodata .rodata.*) - *lib_a-strsep.o(.rodata .rodata.*) - *lib_a-strspn.o(.rodata .rodata.*) - *lib_a-strstr.o(.rodata .rodata.*) - *lib_a-strtok_r.o(.rodata .rodata.*) - *lib_a-strupr.o(.rodata .rodata.*) - *lib_a-stdio.o(.rodata .rodata.*) - *lib_a-syssbrk.o(.rodata .rodata.*) - *lib_a-sysclose.o(.rodata .rodata.*) - *lib_a-sysopen.o(.rodata .rodata.*) - *creat.o(.rodata .rodata.*) - *lib_a-sysread.o(.rodata .rodata.*) - *lib_a-syswrite.o(.rodata .rodata.*) - *lib_a-impure.o(.rodata .rodata.*) - *lib_a-tzvars.o(.rodata .rodata.*) - *lib_a-sf_nan.o(.rodata .rodata.*) - *lib_a-tzcalc_limits.o(.rodata .rodata.*) - *lib_a-month_lengths.o(.rodata .rodata.*) - *lib_a-timelocal.o(.rodata .rodata.*) - *lib_a-findfp.o(.rodata .rodata.*) - *lock.o(.rodata .rodata.*) - *lib_a-getenv_r.o(.rodata .rodata.*) - *isatty.o(.rodata .rodata.*) - *lib_a-fwalk.o(.rodata .rodata.*) - *lib_a-getenv_r.o(.rodata .rodata.*) - *lib_a-tzlock.o(.rodata .rodata.*) - *lib_a-ctype_.o(.rodata .rodata.*) - *lib_a-sccl.o(.rodata .rodata.*) - *lib_a-strptime.o(.rodata .rodata.*) - *lib_a-envlock.o(.rodata .rodata.*) - *lib_a-raise.o(.rodata .rodata.*) - *lib_a-strdup_r.o(.rodata .rodata.*) - *lib_a-system.o(.rodata .rodata.*) - *lib_a-strndup_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-utoa.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-longjmp.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-setjmp.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-abs.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-div.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-labs.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-ldiv.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-quorem.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-qsort.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-utoa.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-itoa.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-atoi.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-atol.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strtol.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strtoul.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-wcrtomb.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-fvwrite.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-wbuf.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-wsetup.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-fputwc.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-wctomb_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-ungetc.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-makebuf.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-fflush.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-refill.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-s_fpclassify.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-locale.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-asctime.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-ctime.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-ctime_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-lcltime.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-lcltime_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-gmtime.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-gmtime_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strftime.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-mktime.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-syswrite.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-tzset_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-tzset.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-toupper.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-tolower.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-toascii.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-systimes.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-time.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-bsd_qsort_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-qsort_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-gettzinfo.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strupr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-asctime_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-bzero.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-close.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-creat.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-environ.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-fclose.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isalnum.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isalpha.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isascii.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isblank.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-iscntrl.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isdigit.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isgraph.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-islower.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isprint.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-ispunct.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isspace.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-isupper.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-memccpy.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-memchr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-memcmp.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-memcpy.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-memmove.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-memrchr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-memset.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-open.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-rand.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-rand_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-read.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-rshift.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-sbrk.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-srand.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strcasecmp.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strcasestr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strcat.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strchr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strcmp.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strcoll.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strcpy.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strcspn.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strdup.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strlcat.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strlcpy.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strlen.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strlwr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strncasecmp.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strncat.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strncmp.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strncpy.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strndup.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strnlen.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strrchr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strsep.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strspn.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strstr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strtok_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strupr.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-stdio.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-syssbrk.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-sysclose.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-sysopen.o(.rodata .rodata.*) + *libc-psram-workaround.a:*creat.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-sysread.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-syswrite.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-impure.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-tzvars.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-sf_nan.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-tzcalc_limits.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-month_lengths.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-timelocal.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-findfp.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lock.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-getenv_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*isatty.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-fwalk.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-getenv_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-tzlock.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-ctype_.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-sccl.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strptime.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-envlock.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-raise.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strdup_r.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-system.o(.rodata .rodata.*) + *libc-psram-workaround.a:*lib_a-strndup_r.o(.rodata .rodata.*) diff --git a/tools/sdk/ld/esp32.spiram.rom-functions-iram.ld b/tools/sdk/ld/esp32.spiram.rom-functions-iram.ld index 6f97fb6b15e..d3a264da194 100644 --- a/tools/sdk/ld/esp32.spiram.rom-functions-iram.ld +++ b/tools/sdk/ld/esp32.spiram.rom-functions-iram.ld @@ -9,136 +9,132 @@ */ - *lib_a-utoa.o(.literal .text .literal.* .text.*) - *lib_a-longjmp.o(.literal .text .literal.* .text.*) - *lib_a-setjmp.o(.literal .text .literal.* .text.*) - *lib_a-abs.o(.literal .text .literal.* .text.*) - *lib_a-div.o(.literal .text .literal.* .text.*) - *lib_a-labs.o(.literal .text .literal.* .text.*) - *lib_a-ldiv.o(.literal .text .literal.* .text.*) - *lib_a-quorem.o(.literal .text .literal.* .text.*) - *lib_a-qsort.o(.literal .text .literal.* .text.*) - *lib_a-utoa.o(.literal .text .literal.* .text.*) - *lib_a-itoa.o(.literal .text .literal.* .text.*) - *lib_a-atoi.o(.literal .text .literal.* .text.*) - *lib_a-atol.o(.literal .text .literal.* .text.*) - *lib_a-strtol.o(.literal .text .literal.* .text.*) - *lib_a-strtoul.o(.literal .text .literal.* .text.*) - *lib_a-wcrtomb.o(.literal .text .literal.* .text.*) - *lib_a-fvwrite.o(.literal .text .literal.* .text.*) - *lib_a-wbuf.o(.literal .text .literal.* .text.*) - *lib_a-wsetup.o(.literal .text .literal.* .text.*) - *lib_a-fputwc.o(.literal .text .literal.* .text.*) - *lib_a-wctomb_r.o(.literal .text .literal.* .text.*) - *lib_a-ungetc.o(.literal .text .literal.* .text.*) - *lib_a-makebuf.o(.literal .text .literal.* .text.*) - *lib_a-fflush.o(.literal .text .literal.* .text.*) - *lib_a-refill.o(.literal .text .literal.* .text.*) - *lib_a-s_fpclassify.o(.literal .text .literal.* .text.*) - *lib_a-locale.o(.literal .text .literal.* .text.*) - *lib_a-asctime.o(.literal .text .literal.* .text.*) - *lib_a-ctime.o(.literal .text .literal.* .text.*) - *lib_a-ctime_r.o(.literal .text .literal.* .text.*) - *lib_a-lcltime.o(.literal .text .literal.* .text.*) - *lib_a-lcltime_r.o(.literal .text .literal.* .text.*) - *lib_a-gmtime.o(.literal .text .literal.* .text.*) - *lib_a-gmtime_r.o(.literal .text .literal.* .text.*) - *lib_a-strftime.o(.literal .text .literal.* .text.*) - *lib_a-mktime.o(.literal .text .literal.* .text.*) - *lib_a-syswrite.o(.literal .text .literal.* .text.*) - *lib_a-tzset_r.o(.literal .text .literal.* .text.*) - *lib_a-tzset.o(.literal .text .literal.* .text.*) - *lib_a-toupper.o(.literal .text .literal.* .text.*) - *lib_a-tolower.o(.literal .text .literal.* .text.*) - *lib_a-toascii.o(.literal .text .literal.* .text.*) - *lib_a-systimes.o(.literal .text .literal.* .text.*) - *lib_a-time.o(.literal .text .literal.* .text.*) - *lib_a-bsd_qsort_r.o(.literal .text .literal.* .text.*) - *lib_a-qsort_r.o(.literal .text .literal.* .text.*) - *lib_a-gettzinfo.o(.literal .text .literal.* .text.*) - *lib_a-strupr.o(.literal .text .literal.* .text.*) - *lib_a-asctime_r.o(.literal .text .literal.* .text.*) - *lib_a-bzero.o(.literal .text .literal.* .text.*) - *lib_a-close.o(.literal .text .literal.* .text.*) - *lib_a-creat.o(.literal .text .literal.* .text.*) - *lib_a-environ.o(.literal .text .literal.* .text.*) - *lib_a-fclose.o(.literal .text .literal.* .text.*) - *lib_a-isalnum.o(.literal .text .literal.* .text.*) - *lib_a-isalpha.o(.literal .text .literal.* .text.*) - *lib_a-isascii.o(.literal .text .literal.* .text.*) - *lib_a-isblank.o(.literal .text .literal.* .text.*) - *lib_a-iscntrl.o(.literal .text .literal.* .text.*) - *lib_a-isdigit.o(.literal .text .literal.* .text.*) - *lib_a-isgraph.o(.literal .text .literal.* .text.*) - *lib_a-islower.o(.literal .text .literal.* .text.*) - *lib_a-isprint.o(.literal .text .literal.* .text.*) - *lib_a-ispunct.o(.literal .text .literal.* .text.*) - *lib_a-isspace.o(.literal .text .literal.* .text.*) - *lib_a-isupper.o(.literal .text .literal.* .text.*) - *lib_a-memccpy.o(.literal .text .literal.* .text.*) - *lib_a-memchr.o(.literal .text .literal.* .text.*) - *lib_a-memcmp.o(.literal .text .literal.* .text.*) - *lib_a-memcpy.o(.literal .text .literal.* .text.*) - *lib_a-memmove.o(.literal .text .literal.* .text.*) - *lib_a-memrchr.o(.literal .text .literal.* .text.*) - *lib_a-memset.o(.literal .text .literal.* .text.*) - *lib_a-open.o(.literal .text .literal.* .text.*) - *lib_a-rand.o(.literal .text .literal.* .text.*) - *lib_a-rand_r.o(.literal .text .literal.* .text.*) - *lib_a-read.o(.literal .text .literal.* .text.*) - *lib_a-rshift.o(.literal .text .literal.* .text.*) - *lib_a-sbrk.o(.literal .text .literal.* .text.*) - *lib_a-srand.o(.literal .text .literal.* .text.*) - *lib_a-strcasecmp.o(.literal .text .literal.* .text.*) - *lib_a-strcasestr.o(.literal .text .literal.* .text.*) - *lib_a-strcat.o(.literal .text .literal.* .text.*) - *lib_a-strchr.o(.literal .text .literal.* .text.*) - *lib_a-strcmp.o(.literal .text .literal.* .text.*) - *lib_a-strcoll.o(.literal .text .literal.* .text.*) - *lib_a-strcpy.o(.literal .text .literal.* .text.*) - *lib_a-strcspn.o(.literal .text .literal.* .text.*) - *lib_a-strdup.o(.literal .text .literal.* .text.*) - *lib_a-strlcat.o(.literal .text .literal.* .text.*) - *lib_a-strlcpy.o(.literal .text .literal.* .text.*) - *lib_a-strlen.o(.literal .text .literal.* .text.*) - *lib_a-strlwr.o(.literal .text .literal.* .text.*) - *lib_a-strncasecmp.o(.literal .text .literal.* .text.*) - *lib_a-strncat.o(.literal .text .literal.* .text.*) - *lib_a-strncmp.o(.literal .text .literal.* .text.*) - *lib_a-strncpy.o(.literal .text .literal.* .text.*) - *lib_a-strndup.o(.literal .text .literal.* .text.*) - *lib_a-strnlen.o(.literal .text .literal.* .text.*) - *lib_a-strrchr.o(.literal .text .literal.* .text.*) - *lib_a-strsep.o(.literal .text .literal.* .text.*) - *lib_a-strspn.o(.literal .text .literal.* .text.*) - *lib_a-strstr.o(.literal .text .literal.* .text.*) - *lib_a-strtok_r.o(.literal .text .literal.* .text.*) - *lib_a-strupr.o(.literal .text .literal.* .text.*) - *lib_a-stdio.o(.literal .text .literal.* .text.*) - *lib_a-syssbrk.o(.literal .text .literal.* .text.*) - *lib_a-sysclose.o(.literal .text .literal.* .text.*) - *lib_a-sysopen.o(.literal .text .literal.* .text.*) - *creat.o(.literal .text .literal.* .text.*) - *lib_a-sysread.o(.literal .text .literal.* .text.*) - *lib_a-syswrite.o(.literal .text .literal.* .text.*) - *lib_a-impure.o(.literal .text .literal.* .text.*) - *lib_a-tzvars.o(.literal .text .literal.* .text.*) - *lib_a-sf_nan.o(.literal .text .literal.* .text.*) - *lib_a-tzcalc_limits.o(.literal .text .literal.* .text.*) - *lib_a-month_lengths.o(.literal .text .literal.* .text.*) - *lib_a-timelocal.o(.literal .text .literal.* .text.*) - *lib_a-findfp.o(.literal .text .literal.* .text.*) - *lock.o(.literal .text .literal.* .text.*) - *lib_a-getenv_r.o(.literal .text .literal.* .text.*) - *isatty.o(.literal .text .literal.* .text.*) - *lib_a-fwalk.o(.literal .text .literal.* .text.*) - *lib_a-getenv_r.o(.literal .text .literal.* .text.*) - *lib_a-tzlock.o(.literal .text .literal.* .text.*) - *lib_a-ctype_.o(.literal .text .literal.* .text.*) - *lib_a-sccl.o(.literal .text .literal.* .text.*) - *lib_a-strptime.o(.literal .text .literal.* .text.*) - *lib_a-envlock.o(.literal .text .literal.* .text.*) - *lib_a-raise.o(.literal .text .literal.* .text.*) - *lib_a-strdup_r.o(.literal .text .literal.* .text.*) - *lib_a-system.o(.literal .text .literal.* .text.*) - *lib_a-strndup_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-utoa.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-longjmp.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-setjmp.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-abs.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-div.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-labs.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-ldiv.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-quorem.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-utoa.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-itoa.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-atoi.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-atol.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strtol.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strtoul.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-wcrtomb.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-fvwrite.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-wbuf.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-wsetup.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-fputwc.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-wctomb_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-ungetc.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-makebuf.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-fflush.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-refill.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-s_fpclassify.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-asctime.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-ctime.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-ctime_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-lcltime.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-lcltime_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-gmtime.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-gmtime_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strftime.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-mktime.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-syswrite.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-tzset_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-tzset.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-toupper.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-tolower.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-toascii.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-systimes.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-time.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-gettzinfo.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strupr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-asctime_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-bzero.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-close.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-creat.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-environ.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-fclose.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isalnum.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isalpha.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isascii.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isblank.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-iscntrl.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isdigit.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isgraph.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-islower.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isprint.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-ispunct.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isspace.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-isupper.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-memccpy.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-memchr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-memcmp.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-memcpy.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-memmove.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-memrchr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-memset.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-open.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-rand.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-rand_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-read.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-rshift.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-sbrk.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-srand.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strcasecmp.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strcasestr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strcat.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strchr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strcmp.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strcoll.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strcpy.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strcspn.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strdup.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strlcat.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strlcpy.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strlen.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strlwr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strncasecmp.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strncat.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strncmp.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strncpy.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strndup.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strnlen.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strrchr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strsep.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strspn.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strstr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strtok_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strupr.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-stdio.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-syssbrk.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-sysclose.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-sysopen.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*creat.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-sysread.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-syswrite.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-impure.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-tzvars.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-sf_nan.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-tzcalc_limits.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-month_lengths.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-timelocal.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-findfp.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lock.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-getenv_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*isatty.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-fwalk.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-getenv_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-tzlock.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-ctype_.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-sccl.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strptime.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-envlock.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-raise.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strdup_r.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-system.o(.literal .text .literal.* .text.*) + *libc-psram-workaround.a:*lib_a-strndup_r.o(.literal .text .literal.* .text.*) diff --git a/tools/sdk/ld/esp32_out.ld b/tools/sdk/ld/esp32_out.ld index f82b39fcad9..c644ae712a1 100644 --- a/tools/sdk/ld/esp32_out.ld +++ b/tools/sdk/ld/esp32_out.ld @@ -45,20 +45,30 @@ MEMORY in heap at runtime. However due to static ROM memory usage at this 176KB mark, the additional static memory temporarily cannot be used. */ - dram0_0_seg (RW) : org = 0x3FFB0000 + 0x10000, - len = 0x2c200 - 0x10000 + dram0_0_seg (RW) : org = 0x3FFB0000 + 0xdb5c, + len = 0x2c200 - 0xdb5c /* Flash mapped constant data */ drom0_0_seg (R) : org = 0x3F400018, len = 0x400000-0x18 /* (See iram0_2_seg for meaning of 0x18 offset in the above.) */ /* RTC fast memory (executable). Persists over deep sleep. */ rtc_iram_seg(RWX) : org = 0x400C0000, len = 0x2000 + /* RTC fast memory (same block as above), viewed from data bus */ + rtc_data_seg(RW) : org = 0x3ff80000, len = 0x2000 /* RTC slow memory (data accessible). Persists over deep sleep. Start of RTC slow memory is reserved for ULP co-processor code + data, if enabled. */ rtc_slow_seg(RW) : org = 0x50000000 + 512, len = 0x1000 - 512 + /* external memory ,including data and text */ + extern_ram_seg(RWX) : org = 0x3F800000, + len = 0x400000 } /* Heap ends at top of dram0_0_seg */ _heap_end = 0x40000000 - 0x0; +_data_seg_org = ORIGIN(rtc_data_seg); +/* The lines below define location alias for .rtc.data section based on Kconfig option. + When the option is not defined then use slow memory segment + else the data will be placed in fast memory segment */ +REGION_ALIAS("rtc_data_location", rtc_slow_seg ); diff --git a/tools/sdk/ld/wifi_iram.ld b/tools/sdk/ld/wifi_iram.ld new file mode 100644 index 00000000000..f8cd6dbebf1 --- /dev/null +++ b/tools/sdk/ld/wifi_iram.ld @@ -0,0 +1,4 @@ +/* Link WiFi library .wifi0iram sections to IRAM + if this snippet is included */ +*libnet80211.a:( .wifi0iram .wifi0iram.*) +*libpp.a:( .wifi0iram .wifi0iram.*) diff --git a/tools/sdk/lib/libapp_trace.a b/tools/sdk/lib/libapp_trace.a index 8c43cda6262..4857b5afedf 100644 Binary files a/tools/sdk/lib/libapp_trace.a and b/tools/sdk/lib/libapp_trace.a differ diff --git a/tools/sdk/lib/libapp_update.a b/tools/sdk/lib/libapp_update.a index d632804c487..9ead7d8c63c 100644 Binary files a/tools/sdk/lib/libapp_update.a and b/tools/sdk/lib/libapp_update.a differ diff --git a/tools/sdk/lib/libasio.a b/tools/sdk/lib/libasio.a new file mode 100644 index 00000000000..857fbae184a Binary files /dev/null and b/tools/sdk/lib/libasio.a differ diff --git a/tools/sdk/lib/libbootloader_support.a b/tools/sdk/lib/libbootloader_support.a index c8bba3b6e5e..465f3e83efc 100644 Binary files a/tools/sdk/lib/libbootloader_support.a and b/tools/sdk/lib/libbootloader_support.a differ diff --git a/tools/sdk/lib/libbt.a b/tools/sdk/lib/libbt.a index e322bcd3870..4f0ffdefc7e 100644 Binary files a/tools/sdk/lib/libbt.a and b/tools/sdk/lib/libbt.a differ diff --git a/tools/sdk/lib/libbtdm_app.a b/tools/sdk/lib/libbtdm_app.a old mode 100755 new mode 100644 index 10b2a07b5ee..b4d1fcfbe67 Binary files a/tools/sdk/lib/libbtdm_app.a and b/tools/sdk/lib/libbtdm_app.a differ diff --git a/tools/sdk/lib/libcoap.a b/tools/sdk/lib/libcoap.a index f5c70b96a2f..854b45b8587 100644 Binary files a/tools/sdk/lib/libcoap.a and b/tools/sdk/lib/libcoap.a differ diff --git a/tools/sdk/lib/libcoexist.a b/tools/sdk/lib/libcoexist.a index 79f982b753f..87f22e299ce 100644 Binary files a/tools/sdk/lib/libcoexist.a and b/tools/sdk/lib/libcoexist.a differ diff --git a/tools/sdk/lib/libconsole.a b/tools/sdk/lib/libconsole.a index aca2c9708e8..cb2986480ea 100644 Binary files a/tools/sdk/lib/libconsole.a and b/tools/sdk/lib/libconsole.a differ diff --git a/tools/sdk/lib/libcore.a b/tools/sdk/lib/libcore.a index a53bda08875..7e5ece4ae0a 100644 Binary files a/tools/sdk/lib/libcore.a and b/tools/sdk/lib/libcore.a differ diff --git a/tools/sdk/lib/libcxx.a b/tools/sdk/lib/libcxx.a index 3c891c89cd0..1389afedb3e 100644 Binary files a/tools/sdk/lib/libcxx.a and b/tools/sdk/lib/libcxx.a differ diff --git a/tools/sdk/lib/libdl_lib.a b/tools/sdk/lib/libdl_lib.a new file mode 100644 index 00000000000..9a186595d35 Binary files /dev/null and b/tools/sdk/lib/libdl_lib.a differ diff --git a/tools/sdk/lib/libdriver.a b/tools/sdk/lib/libdriver.a index 20f78957237..278349e0369 100644 Binary files a/tools/sdk/lib/libdriver.a and b/tools/sdk/lib/libdriver.a differ diff --git a/tools/sdk/lib/libesp-tls.a b/tools/sdk/lib/libesp-tls.a new file mode 100644 index 00000000000..9cc139c78ab Binary files /dev/null and b/tools/sdk/lib/libesp-tls.a differ diff --git a/tools/sdk/lib/libesp32-camera.a b/tools/sdk/lib/libesp32-camera.a new file mode 100644 index 00000000000..1c0179837bc Binary files /dev/null and b/tools/sdk/lib/libesp32-camera.a differ diff --git a/tools/sdk/lib/libesp32.a b/tools/sdk/lib/libesp32.a index f153efa5c5f..240c82e4e22 100644 Binary files a/tools/sdk/lib/libesp32.a and b/tools/sdk/lib/libesp32.a differ diff --git a/tools/sdk/lib/libesp_adc_cal.a b/tools/sdk/lib/libesp_adc_cal.a index de02653cf4d..b55ca617858 100644 Binary files a/tools/sdk/lib/libesp_adc_cal.a and b/tools/sdk/lib/libesp_adc_cal.a differ diff --git a/tools/sdk/lib/libesp_event.a b/tools/sdk/lib/libesp_event.a new file mode 100644 index 00000000000..60ca34ef7b0 Binary files /dev/null and b/tools/sdk/lib/libesp_event.a differ diff --git a/tools/sdk/lib/libesp_http_client.a b/tools/sdk/lib/libesp_http_client.a new file mode 100644 index 00000000000..a3f1ba83be8 Binary files /dev/null and b/tools/sdk/lib/libesp_http_client.a differ diff --git a/tools/sdk/lib/libesp_http_server.a b/tools/sdk/lib/libesp_http_server.a new file mode 100644 index 00000000000..6637f05562f Binary files /dev/null and b/tools/sdk/lib/libesp_http_server.a differ diff --git a/tools/sdk/lib/libesp_https_ota.a b/tools/sdk/lib/libesp_https_ota.a new file mode 100644 index 00000000000..3df5593397d Binary files /dev/null and b/tools/sdk/lib/libesp_https_ota.a differ diff --git a/tools/sdk/lib/libesp_ringbuf.a b/tools/sdk/lib/libesp_ringbuf.a new file mode 100644 index 00000000000..41d5e52285e Binary files /dev/null and b/tools/sdk/lib/libesp_ringbuf.a differ diff --git a/tools/sdk/lib/libespnow.a b/tools/sdk/lib/libespnow.a index 63159396934..39078d7cb93 100644 Binary files a/tools/sdk/lib/libespnow.a and b/tools/sdk/lib/libespnow.a differ diff --git a/tools/sdk/lib/libethernet.a b/tools/sdk/lib/libethernet.a index 93a62f75589..4c41f923816 100644 Binary files a/tools/sdk/lib/libethernet.a and b/tools/sdk/lib/libethernet.a differ diff --git a/tools/sdk/lib/libexpat.a b/tools/sdk/lib/libexpat.a index 9fdb077ab79..419c8c37270 100644 Binary files a/tools/sdk/lib/libexpat.a and b/tools/sdk/lib/libexpat.a differ diff --git a/tools/sdk/lib/libface_detection.a b/tools/sdk/lib/libface_detection.a new file mode 100644 index 00000000000..b5d9868e456 Binary files /dev/null and b/tools/sdk/lib/libface_detection.a differ diff --git a/tools/sdk/lib/libface_recognition.a b/tools/sdk/lib/libface_recognition.a new file mode 100644 index 00000000000..b5f4486e729 Binary files /dev/null and b/tools/sdk/lib/libface_recognition.a differ diff --git a/tools/sdk/lib/libfatfs.a b/tools/sdk/lib/libfatfs.a index 83d05ceecab..7a5f329ec63 100644 Binary files a/tools/sdk/lib/libfatfs.a and b/tools/sdk/lib/libfatfs.a differ diff --git a/tools/sdk/lib/libfb_gfx.a b/tools/sdk/lib/libfb_gfx.a new file mode 100644 index 00000000000..a2967139948 Binary files /dev/null and b/tools/sdk/lib/libfb_gfx.a differ diff --git a/tools/sdk/lib/libfd.a b/tools/sdk/lib/libfd.a new file mode 100644 index 00000000000..38ccff621f3 Binary files /dev/null and b/tools/sdk/lib/libfd.a differ diff --git a/tools/sdk/lib/libfr.a b/tools/sdk/lib/libfr.a new file mode 100644 index 00000000000..7ba16b25495 Binary files /dev/null and b/tools/sdk/lib/libfr.a differ diff --git a/tools/sdk/lib/libfreemodbus.a b/tools/sdk/lib/libfreemodbus.a new file mode 100644 index 00000000000..d64373bc699 Binary files /dev/null and b/tools/sdk/lib/libfreemodbus.a differ diff --git a/tools/sdk/lib/libfreertos.a b/tools/sdk/lib/libfreertos.a index d3776131751..1eed10babc2 100644 Binary files a/tools/sdk/lib/libfreertos.a and b/tools/sdk/lib/libfreertos.a differ diff --git a/tools/sdk/lib/libheap.a b/tools/sdk/lib/libheap.a index 0a08bfc242c..56e829a4bb4 100644 Binary files a/tools/sdk/lib/libheap.a and b/tools/sdk/lib/libheap.a differ diff --git a/tools/sdk/lib/libimage_util.a b/tools/sdk/lib/libimage_util.a new file mode 100644 index 00000000000..a8a38c9346c Binary files /dev/null and b/tools/sdk/lib/libimage_util.a differ diff --git a/tools/sdk/lib/libjsmn.a b/tools/sdk/lib/libjsmn.a index 73063f97f2f..c86b126d392 100644 Binary files a/tools/sdk/lib/libjsmn.a and b/tools/sdk/lib/libjsmn.a differ diff --git a/tools/sdk/lib/libjson.a b/tools/sdk/lib/libjson.a index b12648d8c28..cd0768f7352 100644 Binary files a/tools/sdk/lib/libjson.a and b/tools/sdk/lib/libjson.a differ diff --git a/tools/sdk/lib/liblibsodium.a b/tools/sdk/lib/liblibsodium.a new file mode 100644 index 00000000000..f26b48d8f88 Binary files /dev/null and b/tools/sdk/lib/liblibsodium.a differ diff --git a/tools/sdk/lib/liblog.a b/tools/sdk/lib/liblog.a index fe3b04dc91e..9e689004b2d 100644 Binary files a/tools/sdk/lib/liblog.a and b/tools/sdk/lib/liblog.a differ diff --git a/tools/sdk/lib/liblwip.a b/tools/sdk/lib/liblwip.a index 82d25a51ee3..7b5d5bf5987 100644 Binary files a/tools/sdk/lib/liblwip.a and b/tools/sdk/lib/liblwip.a differ diff --git a/tools/sdk/lib/libmbedtls.a b/tools/sdk/lib/libmbedtls.a index 267b744fa1d..45929d70ac3 100644 Binary files a/tools/sdk/lib/libmbedtls.a and b/tools/sdk/lib/libmbedtls.a differ diff --git a/tools/sdk/lib/libmdns.a b/tools/sdk/lib/libmdns.a index 8ee4b2aea1b..8e4482766d0 100644 Binary files a/tools/sdk/lib/libmdns.a and b/tools/sdk/lib/libmdns.a differ diff --git a/tools/sdk/lib/libmesh.a b/tools/sdk/lib/libmesh.a index 4025450f1a2..326bb0bfcc1 100644 Binary files a/tools/sdk/lib/libmesh.a and b/tools/sdk/lib/libmesh.a differ diff --git a/tools/sdk/lib/libmicro-ecc.a b/tools/sdk/lib/libmicro-ecc.a index 9971df7edb0..3d3e108fed8 100644 Binary files a/tools/sdk/lib/libmicro-ecc.a and b/tools/sdk/lib/libmicro-ecc.a differ diff --git a/tools/sdk/lib/libmqtt.a b/tools/sdk/lib/libmqtt.a new file mode 100644 index 00000000000..18fd9420709 Binary files /dev/null and b/tools/sdk/lib/libmqtt.a differ diff --git a/tools/sdk/lib/libnet80211.a b/tools/sdk/lib/libnet80211.a index 9c5b41c2533..3effa68be48 100644 Binary files a/tools/sdk/lib/libnet80211.a and b/tools/sdk/lib/libnet80211.a differ diff --git a/tools/sdk/lib/libnewlib.a b/tools/sdk/lib/libnewlib.a index f8b8fb20a73..640e1500160 100644 Binary files a/tools/sdk/lib/libnewlib.a and b/tools/sdk/lib/libnewlib.a differ diff --git a/tools/sdk/lib/libnghttp.a b/tools/sdk/lib/libnghttp.a index 4e35ba2f0ce..8ce8eb813fd 100644 Binary files a/tools/sdk/lib/libnghttp.a and b/tools/sdk/lib/libnghttp.a differ diff --git a/tools/sdk/lib/libnvs_flash.a b/tools/sdk/lib/libnvs_flash.a index a872304a439..f2189ae77bb 100644 Binary files a/tools/sdk/lib/libnvs_flash.a and b/tools/sdk/lib/libnvs_flash.a differ diff --git a/tools/sdk/lib/libopenssl.a b/tools/sdk/lib/libopenssl.a index d4acb357df5..935ee46a97f 100644 Binary files a/tools/sdk/lib/libopenssl.a and b/tools/sdk/lib/libopenssl.a differ diff --git a/tools/sdk/lib/libphy.a b/tools/sdk/lib/libphy.a index df8225423fb..83ccef7e85e 100644 Binary files a/tools/sdk/lib/libphy.a and b/tools/sdk/lib/libphy.a differ diff --git a/tools/sdk/lib/libpp.a b/tools/sdk/lib/libpp.a index f0d59497fd6..6354cba8ebc 100644 Binary files a/tools/sdk/lib/libpp.a and b/tools/sdk/lib/libpp.a differ diff --git a/tools/sdk/lib/libprotobuf-c.a b/tools/sdk/lib/libprotobuf-c.a new file mode 100644 index 00000000000..777e595da5d Binary files /dev/null and b/tools/sdk/lib/libprotobuf-c.a differ diff --git a/tools/sdk/lib/libprotocomm.a b/tools/sdk/lib/libprotocomm.a new file mode 100644 index 00000000000..a2d802e3967 Binary files /dev/null and b/tools/sdk/lib/libprotocomm.a differ diff --git a/tools/sdk/lib/libpthread.a b/tools/sdk/lib/libpthread.a index 9aa172a4397..6fba7a72a96 100644 Binary files a/tools/sdk/lib/libpthread.a and b/tools/sdk/lib/libpthread.a differ diff --git a/tools/sdk/lib/librtc.a b/tools/sdk/lib/librtc.a old mode 100755 new mode 100644 index 3f019f58f6d..3b3370a36a5 Binary files a/tools/sdk/lib/librtc.a and b/tools/sdk/lib/librtc.a differ diff --git a/tools/sdk/lib/libsdmmc.a b/tools/sdk/lib/libsdmmc.a index e6be972d9b9..4141d2688e0 100644 Binary files a/tools/sdk/lib/libsdmmc.a and b/tools/sdk/lib/libsdmmc.a differ diff --git a/tools/sdk/lib/libsmartconfig.a b/tools/sdk/lib/libsmartconfig.a index 67aec8d4836..04e2cb834c9 100644 Binary files a/tools/sdk/lib/libsmartconfig.a and b/tools/sdk/lib/libsmartconfig.a differ diff --git a/tools/sdk/lib/libsmartconfig_ack.a b/tools/sdk/lib/libsmartconfig_ack.a new file mode 100644 index 00000000000..ef0430902a8 Binary files /dev/null and b/tools/sdk/lib/libsmartconfig_ack.a differ diff --git a/tools/sdk/lib/libsoc.a b/tools/sdk/lib/libsoc.a index 68128b52867..6dffcda805e 100644 Binary files a/tools/sdk/lib/libsoc.a and b/tools/sdk/lib/libsoc.a differ diff --git a/tools/sdk/lib/libspi_flash.a b/tools/sdk/lib/libspi_flash.a index a2e04471d75..c8ae07321eb 100644 Binary files a/tools/sdk/lib/libspi_flash.a and b/tools/sdk/lib/libspi_flash.a differ diff --git a/tools/sdk/lib/libspiffs.a b/tools/sdk/lib/libspiffs.a index e4397309a78..441ee6cdad0 100644 Binary files a/tools/sdk/lib/libspiffs.a and b/tools/sdk/lib/libspiffs.a differ diff --git a/tools/sdk/lib/libtcp_transport.a b/tools/sdk/lib/libtcp_transport.a new file mode 100644 index 00000000000..1a46d0147a7 Binary files /dev/null and b/tools/sdk/lib/libtcp_transport.a differ diff --git a/tools/sdk/lib/libtcpip_adapter.a b/tools/sdk/lib/libtcpip_adapter.a index 0208c985688..653e79b5b7e 100644 Binary files a/tools/sdk/lib/libtcpip_adapter.a and b/tools/sdk/lib/libtcpip_adapter.a differ diff --git a/tools/sdk/lib/libulp.a b/tools/sdk/lib/libulp.a index 96705189db7..c5c875fa529 100644 Binary files a/tools/sdk/lib/libulp.a and b/tools/sdk/lib/libulp.a differ diff --git a/tools/sdk/lib/libvfs.a b/tools/sdk/lib/libvfs.a index 53b6c12d42c..6c29a20e660 100644 Binary files a/tools/sdk/lib/libvfs.a and b/tools/sdk/lib/libvfs.a differ diff --git a/tools/sdk/lib/libwear_levelling.a b/tools/sdk/lib/libwear_levelling.a index 6953e4fbec4..75c615a1bf6 100644 Binary files a/tools/sdk/lib/libwear_levelling.a and b/tools/sdk/lib/libwear_levelling.a differ diff --git a/tools/sdk/lib/libwifi_provisioning.a b/tools/sdk/lib/libwifi_provisioning.a new file mode 100644 index 00000000000..cccbbb0f7cf Binary files /dev/null and b/tools/sdk/lib/libwifi_provisioning.a differ diff --git a/tools/sdk/lib/libwpa.a b/tools/sdk/lib/libwpa.a index 7fa1105c077..ac1a36fdd4d 100644 Binary files a/tools/sdk/lib/libwpa.a and b/tools/sdk/lib/libwpa.a differ diff --git a/tools/sdk/lib/libwpa2.a b/tools/sdk/lib/libwpa2.a index 29e9277d9a1..4ba731fe950 100644 Binary files a/tools/sdk/lib/libwpa2.a and b/tools/sdk/lib/libwpa2.a differ diff --git a/tools/sdk/lib/libwpa_supplicant.a b/tools/sdk/lib/libwpa_supplicant.a index d61cebc9ad8..15535d887ec 100644 Binary files a/tools/sdk/lib/libwpa_supplicant.a and b/tools/sdk/lib/libwpa_supplicant.a differ diff --git a/tools/sdk/lib/libwps.a b/tools/sdk/lib/libwps.a index 4d153055242..139e9e1b2fe 100644 Binary files a/tools/sdk/lib/libwps.a and b/tools/sdk/lib/libwps.a differ diff --git a/tools/sdk/lib/libxtensa-debug-module.a b/tools/sdk/lib/libxtensa-debug-module.a index aac19ab1ae9..6b32ff1dce0 100644 Binary files a/tools/sdk/lib/libxtensa-debug-module.a and b/tools/sdk/lib/libxtensa-debug-module.a differ diff --git a/tools/sdk/sdkconfig b/tools/sdk/sdkconfig index b2ca2f61adb..08e8142f7a4 100644 --- a/tools/sdk/sdkconfig +++ b/tools/sdk/sdkconfig @@ -2,6 +2,7 @@ # Automatically generated file; DO NOT EDIT. # Espressif IoT Development Framework Configuration # +CONFIG_IDF_FIRMWARE_CHIP_ID=0x0000 # # SDK tool configuration @@ -10,6 +11,46 @@ CONFIG_TOOLPREFIX="xtensa-esp32-elf-" CONFIG_PYTHON="python" CONFIG_MAKE_WARN_UNDEFINED_VARIABLES=y +# +# Arduino Configuration +# +CONFIG_ENABLE_ARDUINO_DEPENDS=y +CONFIG_AUTOSTART_ARDUINO=y +CONFIG_ARDUINO_RUN_CORE0= +CONFIG_ARDUINO_RUN_CORE1=y +CONFIG_ARDUINO_RUN_NO_AFFINITY= +CONFIG_ARDUINO_RUNNING_CORE=1 +CONFIG_ARDUINO_EVENT_RUN_CORE0= +CONFIG_ARDUINO_EVENT_RUN_CORE1=y +CONFIG_ARDUINO_EVENT_RUN_NO_AFFINITY= +CONFIG_ARDUINO_EVENT_RUNNING_CORE=1 +CONFIG_ARDUINO_UDP_RUN_CORE0= +CONFIG_ARDUINO_UDP_RUN_CORE1=y +CONFIG_ARDUINO_UDP_RUN_NO_AFFINITY= +CONFIG_ARDUINO_UDP_RUNNING_CORE=1 +CONFIG_DISABLE_HAL_LOCKS= + +# +# Debug Log Configuration +# +CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_NONE= +CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_ERROR=y +CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_WARN= +CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_INFO= +CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_DEBUG= +CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_VERBOSE= +CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL=1 +CONFIG_ARDUHAL_LOG_COLORS= +CONFIG_ARDUHAL_ESP_LOG=y +CONFIG_ARDUHAL_PARTITION_SCHEME_DEFAULT=y +CONFIG_ARDUHAL_PARTITION_SCHEME_MINIMAL= +CONFIG_ARDUHAL_PARTITION_SCHEME_NO_OTA= +CONFIG_ARDUHAL_PARTITION_SCHEME_HUGE_APP= +CONFIG_ARDUHAL_PARTITION_SCHEME_MIN_SPIFFS= +CONFIG_ARDUHAL_PARTITION_SCHEME="default" +CONFIG_AUTOCONNECT_WIFI= +CONFIG_ARDUINO_SELECTIVE_COMPILATION= + # # Bootloader config # @@ -22,10 +63,16 @@ CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE= CONFIG_LOG_BOOTLOADER_LEVEL=0 CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_8V= CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V=y +CONFIG_BOOTLOADER_FACTORY_RESET= +CONFIG_BOOTLOADER_APP_TEST= +CONFIG_BOOTLOADER_WDT_ENABLE=y +CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE= +CONFIG_BOOTLOADER_WDT_TIME_MS=9000 # # Security features # +CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT= CONFIG_SECURE_BOOT_ENABLED= CONFIG_FLASH_ENCRYPTION_ENABLED= @@ -81,9 +128,8 @@ CONFIG_PARTITION_TABLE_SINGLE_APP=y CONFIG_PARTITION_TABLE_TWO_OTA= CONFIG_PARTITION_TABLE_CUSTOM= CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" -CONFIG_PARTITION_TABLE_CUSTOM_APP_BIN_OFFSET=0x10000 CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv" -CONFIG_APP_OFFSET=0x10000 +CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y # @@ -101,6 +147,8 @@ CONFIG_STACK_CHECK_NORM=y CONFIG_STACK_CHECK_STRONG= CONFIG_STACK_CHECK_ALL= CONFIG_STACK_CHECK=y +CONFIG_WARN_WRITE_STRINGS=y +CONFIG_DISABLE_GCC8_WARNINGS= # # Component config @@ -113,42 +161,51 @@ CONFIG_ESP32_APPTRACE_DEST_TRAX= CONFIG_ESP32_APPTRACE_DEST_NONE=y CONFIG_ESP32_APPTRACE_ENABLE= CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y - -# -# FreeRTOS SystemView Tracing -# - -# -# Arduino Configuration -# -CONFIG_ENABLE_ARDUINO_DEPENDS=y -CONFIG_AUTOSTART_ARDUINO=y -CONFIG_DISABLE_HAL_LOCKS= - -# -# Debug Log Configuration -# -CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_NONE= -CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_ERROR=y -CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_WARN= -CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_INFO= -CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_DEBUG= -CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_VERBOSE= -CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL=1 -CONFIG_ARDUHAL_LOG_COLORS= -CONFIG_ARDUHAL_ESP_LOG=y -CONFIG_AUTOCONNECT_WIFI= CONFIG_AWS_IOT_SDK= # # Bluetooth # CONFIG_BT_ENABLED=y + +# +# Bluetooth controller +# +CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY= +CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY= +CONFIG_BTDM_CONTROLLER_MODE_BTDM=y +CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN=3 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN=2 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN=0 +CONFIG_BTDM_CONTROLLER_BR_EDR_SCO_DATA_PATH_HCI= +CONFIG_BTDM_CONTROLLER_BR_EDR_SCO_DATA_PATH_PCM=y +CONFIG_BTDM_CONTROLLER_BR_EDR_SCO_DATA_PATH_EFF=1 +CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF=3 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_EFF=2 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF=0 CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_0=y CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_1= CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE=0 CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI=y CONFIG_BTDM_CONTROLLER_HCI_MODE_UART_H4= + +# +# MODEM SLEEP Options +# +CONFIG_BTDM_CONTROLLER_MODEM_SLEEP=y +CONFIG_BTDM_MODEM_SLEEP_MODE_ORIG=y +CONFIG_BTDM_MODEM_SLEEP_MODE_EVED= +CONFIG_BTDM_LPCLK_SEL_MAIN_XTAL=y +CONFIG_BLE_SCAN_DUPLICATE=y +CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR=y +CONFIG_SCAN_DUPLICATE_BY_ADV_DATA= +CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR= +CONFIG_SCAN_DUPLICATE_TYPE=0 +CONFIG_DUPLICATE_SCAN_CACHE_SIZE=20 +CONFIG_BLE_MESH_SCAN_DUPLICATE_EN= +CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_SUPPORTED=y +CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_NUM=100 +CONFIG_BLE_ADV_REPORT_DISCARD_THRSHOLD=20 CONFIG_BLUEDROID_ENABLED=y CONFIG_BLUEDROID_PINNED_TO_CORE_0=y CONFIG_BLUEDROID_PINNED_TO_CORE_1= @@ -157,19 +214,34 @@ CONFIG_BTC_TASK_STACK_SIZE=8192 CONFIG_BLUEDROID_MEM_DEBUG= CONFIG_CLASSIC_BT_ENABLED=y CONFIG_A2DP_ENABLE=y -CONFIG_A2DP_SINK_ENABLE=y -CONFIG_A2DP_SRC_ENABLE= CONFIG_A2DP_SINK_TASK_STACK_SIZE=2048 +CONFIG_A2DP_SOURCE_TASK_STACK_SIZE=2048 CONFIG_BT_SPP_ENABLED=y +CONFIG_HFP_ENABLE=y +CONFIG_HFP_CLIENT_ENABLE=y +CONFIG_HFP_AUDIO_DATA_PATH_PCM=y +CONFIG_HFP_AUDIO_DATA_PATH_HCI= CONFIG_GATTS_ENABLE=y +CONFIG_GATTS_SEND_SERVICE_CHANGE_MANUAL= +CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO=y +CONFIG_GATTS_SEND_SERVICE_CHANGE_MODE=0 CONFIG_GATTC_ENABLE=y +CONFIG_GATTC_CACHE_NVS_FLASH= CONFIG_BLE_SMP_ENABLE=y -CONFIG_BT_STACK_NO_LOG= +CONFIG_SMP_SLAVE_CON_PARAMS_UPD_ENABLE= +CONFIG_BT_STACK_NO_LOG=y CONFIG_BT_ACL_CONNECTIONS=4 -CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST= +CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST=y CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY=y +CONFIG_BLE_HOST_QUEUE_CONGESTION_CHECK= CONFIG_SMP_ENABLE=y -CONFIG_BT_RESERVE_DRAM=0x10000 +CONFIG_BLE_ACTIVE_SCAN_REPORT_ADV_SCAN_RSP_INDIVIDUALLY= +CONFIG_BLE_ESTABLISH_LINK_CONNECTION_TIMEOUT=30 +CONFIG_BT_RESERVE_DRAM=0xdb5c + +# +# Driver configurations +# # # ADC configuration @@ -177,14 +249,77 @@ CONFIG_BT_RESERVE_DRAM=0x10000 CONFIG_ADC_FORCE_XPD_FSM= CONFIG_ADC2_DISABLE_DAC=y +# +# SPI configuration +# +CONFIG_SPI_MASTER_IN_IRAM= +CONFIG_SPI_MASTER_ISR_IN_IRAM=y +CONFIG_SPI_SLAVE_IN_IRAM= +CONFIG_SPI_SLAVE_ISR_IN_IRAM=y +CONFIG_C_IMPL= +CONFIG_XTENSA_IMPL=y + +# +# ESP-FACE Configuration +# +CONFIG_MTMN_LITE_QUANT=y +CONFIG_MTMN_LITE_FLOAT= +CONFIG_MTMN_HEAVY_QUANT= +CONFIG_FRMN1_QUANT=y +CONFIG_FRMN2_QUANT= +CONFIG_FRMN2P_QUANT= +CONFIG_FRMN2C_QUANT= + # # ESP32-specific # +CONFIG_ESP32_REV_MIN_0=y +CONFIG_ESP32_REV_MIN_1= +CONFIG_ESP32_REV_MIN_2= +CONFIG_ESP32_REV_MIN_3= +CONFIG_ESP32_REV_MIN=0 +CONFIG_ESP32_DPORT_WORKAROUND=y CONFIG_ESP32_DEFAULT_CPU_FREQ_80= CONFIG_ESP32_DEFAULT_CPU_FREQ_160= CONFIG_ESP32_DEFAULT_CPU_FREQ_240=y CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ=240 -CONFIG_SPIRAM_SUPPORT= +CONFIG_SPIRAM_SUPPORT=y + +# +# SPI RAM config +# +CONFIG_SPIRAM_BOOT_INIT= +CONFIG_SPIRAM_USE_MEMMAP= +CONFIG_SPIRAM_USE_CAPS_ALLOC=y +CONFIG_SPIRAM_USE_MALLOC= +CONFIG_SPIRAM_TYPE_AUTO=y +CONFIG_SPIRAM_TYPE_ESPPSRAM32= +CONFIG_SPIRAM_TYPE_ESPPSRAM64= +CONFIG_SPIRAM_SIZE=-1 +CONFIG_SPIRAM_SPEED_40M=y +CONFIG_SPIRAM_CACHE_WORKAROUND=y +CONFIG_SPIRAM_BANKSWITCH_ENABLE=y +CONFIG_SPIRAM_BANKSWITCH_RESERVE=8 +CONFIG_WIFI_LWIP_ALLOCATION_FROM_SPIRAM_FIRST= +CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY= + +# +# PSRAM clock and cs IO for ESP32-DOWD +# +CONFIG_D0WD_PSRAM_CLK_IO=17 +CONFIG_D0WD_PSRAM_CS_IO=16 + +# +# PSRAM clock and cs IO for ESP32-D2WD +# +CONFIG_D2WD_PSRAM_CLK_IO=9 +CONFIG_D2WD_PSRAM_CS_IO=10 + +# +# PSRAM clock and cs IO for ESP32-PICO +# +CONFIG_PICO_PSRAM_CS_IO=10 +CONFIG_SPIRAM_SPIWP_SD3_PIN=7 CONFIG_MEMMAP_TRACEMEM= CONFIG_MEMMAP_TRACEMEM_TWOBANKS= CONFIG_ESP32_TRAX= @@ -220,11 +355,12 @@ CONFIG_ESP32_PANIC_PRINT_REBOOT=y CONFIG_ESP32_PANIC_SILENT_REBOOT= CONFIG_ESP32_PANIC_GDBSTUB= CONFIG_ESP32_DEBUG_OCDAWARE=y +CONFIG_ESP32_DEBUG_STUBS_ENABLE=y CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=300 CONFIG_INT_WDT_CHECK_CPU1=y CONFIG_TASK_WDT=y -CONFIG_TASK_WDT_PANIC= +CONFIG_TASK_WDT_PANIC=y CONFIG_TASK_WDT_TIMEOUT_S=5 CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1= @@ -238,14 +374,16 @@ CONFIG_BROWNOUT_DET_LVL_SEL_5= CONFIG_BROWNOUT_DET_LVL_SEL_6= CONFIG_BROWNOUT_DET_LVL_SEL_7= CONFIG_BROWNOUT_DET_LVL=0 +CONFIG_REDUCE_PHY_TX_POWER=y CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1=y CONFIG_ESP32_TIME_SYSCALL_USE_RTC= CONFIG_ESP32_TIME_SYSCALL_USE_FRC1= CONFIG_ESP32_TIME_SYSCALL_USE_NONE= CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_RC=y CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_CRYSTAL= +CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_OSC= +CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_8MD256= CONFIG_ESP32_RTC_CLK_CAL_CYCLES=1024 -CONFIG_ESP32_RTC_XTAL_BOOTSTRAP_CYCLES=100 CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY=2000 CONFIG_ESP32_XTAL_FREQ_40= CONFIG_ESP32_XTAL_FREQ_26= @@ -255,6 +393,7 @@ CONFIG_DISABLE_BASIC_ROM_CONSOLE= CONFIG_ESP_TIMER_PROFILING= CONFIG_COMPATIBLE_PRE_V2_1_BOOTLOADERS= CONFIG_ESP_ERR_TO_NAME_LOOKUP=y +CONFIG_ESP32_DPORT_DIS_INTERRUPT_LVL=5 # # Wi-Fi @@ -264,15 +403,23 @@ CONFIG_SW_COEXIST_PREFERENCE_WIFI= CONFIG_SW_COEXIST_PREFERENCE_BT= CONFIG_SW_COEXIST_PREFERENCE_BALANCE=y CONFIG_SW_COEXIST_PREFERENCE_VALUE=2 -CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 -CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=0 +CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=16 +CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 CONFIG_ESP32_WIFI_STATIC_TX_BUFFER= CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER=y CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=1 CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 +CONFIG_ESP32_WIFI_CSI_ENABLED= CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y CONFIG_ESP32_WIFI_TX_BA_WIN=6 +CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y +CONFIG_ESP32_WIFI_RX_BA_WIN=16 CONFIG_ESP32_WIFI_NVS_ENABLED=y +CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0=y +CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1= +CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752 +CONFIG_ESP32_WIFI_IRAM_OPT=y +CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32 # # PHY @@ -287,6 +434,17 @@ CONFIG_ESP32_PHY_MAX_TX_POWER=20 # CONFIG_PM_ENABLE= +# +# Camera configuration +# +CONFIG_OV2640_SUPPORT=y +CONFIG_OV7725_SUPPORT=y +CONFIG_OV3660_SUPPORT=y +CONFIG_SCCB_HARDWARE_I2C=y +CONFIG_CAMERA_CORE0= +CONFIG_CAMERA_CORE1=y +CONFIG_CAMERA_NO_AFFINITY= + # # ADC-Calibration # @@ -294,13 +452,33 @@ CONFIG_ADC_CAL_EFUSE_TP_ENABLE=y CONFIG_ADC_CAL_EFUSE_VREF_ENABLE=y CONFIG_ADC_CAL_LUT_ENABLE=y +# +# Event Loop Library +# +CONFIG_EVENT_LOOP_PROFILING= + +# +# ESP HTTP client +# +CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y + +# +# HTTP Server +# +CONFIG_HTTPD_MAX_REQ_HDR_LEN=512 +CONFIG_HTTPD_MAX_URI_LEN=512 +CONFIG_HTTPD_PURGE_BUF_LEN=32 +CONFIG_HTTPD_LOG_PURGE_DATA= + # # Ethernet # CONFIG_DMA_RX_BUF_NUM=10 CONFIG_DMA_TX_BUF_NUM=10 CONFIG_EMAC_L2_TO_L3_RX_BUF_MODE=y +CONFIG_EMAC_CHECK_LINK_PERIOD_MS=2000 CONFIG_EMAC_TASK_PRIORITY=20 +CONFIG_EMAC_TASK_STACK_SIZE=3072 # # FAT Filesystem support @@ -339,10 +517,27 @@ CONFIG_FATFS_FS_LOCK=0 CONFIG_FATFS_TIMEOUT_MS=10000 CONFIG_FATFS_PER_FILE_CACHE=y +# +# Modbus configuration +# +CONFIG_MB_QUEUE_LENGTH=20 +CONFIG_MB_SERIAL_TASK_STACK_SIZE=2048 +CONFIG_MB_SERIAL_BUF_SIZE=256 +CONFIG_MB_SERIAL_TASK_PRIO=10 +CONFIG_MB_CONTROLLER_SLAVE_ID_SUPPORT= +CONFIG_MB_CONTROLLER_NOTIFY_TIMEOUT=20 +CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE=20 +CONFIG_MB_CONTROLLER_STACK_SIZE=4096 +CONFIG_MB_EVENT_QUEUE_TIMEOUT=20 +CONFIG_MB_TIMER_PORT_ENABLED=y +CONFIG_MB_TIMER_GROUP=0 +CONFIG_MB_TIMER_INDEX=0 + # # FreeRTOS # CONFIG_FREERTOS_UNICORE= +CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_CORETIMER_0=y CONFIG_FREERTOS_CORETIMER_1= CONFIG_FREERTOS_HZ=1000 @@ -368,6 +563,7 @@ CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0 CONFIG_FREERTOS_USE_TRACE_FACILITY= CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS= CONFIG_FREERTOS_DEBUG_INTERNALS= +CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y # # Heap memory debugging @@ -401,6 +597,7 @@ CONFIG_LOG_COLORS= CONFIG_L2_TO_L3_COPY= CONFIG_LWIP_IRAM_OPTIMIZATION= CONFIG_LWIP_MAX_SOCKETS=10 +CONFIG_USE_ONLY_LWIP_SELECT= CONFIG_LWIP_SO_REUSE=y CONFIG_LWIP_SO_REUSE_RXTOALL=y CONFIG_LWIP_SO_RCVBUF=y @@ -409,8 +606,11 @@ CONFIG_LWIP_IP_FRAG= CONFIG_LWIP_IP_REASSEMBLY= CONFIG_LWIP_STATS= CONFIG_LWIP_ETHARP_TRUST_IP_MAC=y +CONFIG_ESP_GRATUITOUS_ARP=y +CONFIG_GARP_TMR_INTERVAL=60 CONFIG_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK= +CONFIG_LWIP_DHCP_RESTORE_LAST_IP=y # # DHCP server @@ -434,6 +634,7 @@ CONFIG_TCP_SND_BUF_DEFAULT=5744 CONFIG_TCP_WND_DEFAULT=5744 CONFIG_TCP_RECVMBOX_SIZE=6 CONFIG_TCP_QUEUE_OOSEQ=y +CONFIG_ESP_TCP_KEEP_CONNECTION_WHEN_IP_CHANGES= CONFIG_TCP_OVERSIZE_MSS=y CONFIG_TCP_OVERSIZE_QUARTER_MSS= CONFIG_TCP_OVERSIZE_DISABLE= @@ -444,7 +645,16 @@ CONFIG_TCP_OVERSIZE_DISABLE= CONFIG_LWIP_MAX_UDP_PCBS=16 CONFIG_UDP_RECVMBOX_SIZE=6 CONFIG_TCPIP_TASK_STACK_SIZE=2560 -CONFIG_PPP_SUPPORT= +CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY= +CONFIG_TCPIP_TASK_AFFINITY_CPU0=y +CONFIG_TCPIP_TASK_AFFINITY_CPU1= +CONFIG_TCPIP_TASK_AFFINITY=0x0 +CONFIG_PPP_SUPPORT=y +CONFIG_PPP_PAP_SUPPORT=y +CONFIG_PPP_CHAP_SUPPORT=y +CONFIG_PPP_MSCHAP_SUPPORT=y +CONFIG_PPP_MPPE_SUPPORT=y +CONFIG_PPP_DEBUG_ON= # # ICMP @@ -460,7 +670,12 @@ CONFIG_LWIP_MAX_RAW_PCBS=16 # # mbedTLS # +CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y +CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC= +CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC= +CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC= CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN=16384 +CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN= CONFIG_MBEDTLS_DEBUG= CONFIG_MBEDTLS_HARDWARE_AES=y CONFIG_MBEDTLS_HARDWARE_MPI= @@ -478,7 +693,11 @@ CONFIG_MBEDTLS_TLS_ENABLED=y # # TLS Key Exchange Methods # -CONFIG_MBEDTLS_PSK_MODES= +CONFIG_MBEDTLS_PSK_MODES=y +CONFIG_MBEDTLS_KEY_EXCHANGE_PSK=y +CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_PSK=y +CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_PSK=y +CONFIG_MBEDTLS_KEY_EXCHANGE_RSA_PSK=y CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y @@ -534,6 +753,26 @@ CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y CONFIG_MBEDTLS_ECP_NIST_OPTIM=y +# +# mDNS +# +CONFIG_MDNS_MAX_SERVICES=10 + +# +# ESP-MQTT Configurations +# +CONFIG_MQTT_PROTOCOL_311=y +CONFIG_MQTT_TRANSPORT_SSL=y +CONFIG_MQTT_TRANSPORT_WEBSOCKET=y +CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y +CONFIG_MQTT_USE_CUSTOM_CONFIG= +CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED= +CONFIG_MQTT_CUSTOM_OUTBOX= + +# +# NVS +# + # # OpenSSL # @@ -546,6 +785,7 @@ CONFIG_OPENSSL_ASSERT_EXIT= # CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=2048 +CONFIG_PTHREAD_STACK_MIN=768 # # SPI Flash driver @@ -556,6 +796,7 @@ CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS= CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED= +CONFIG_SPI_FLASH_YIELD_DURING_ERASE= # # SPIFFS Configuration @@ -589,9 +830,16 @@ CONFIG_SPIFFS_CHECK_DBG= CONFIG_SPIFFS_TEST_VISUALISATION= # -# tcpip adapter +# TCP/IP Adapter # CONFIG_IP_LOST_TIMER_INTERVAL=120 +CONFIG_TCPIP_LWIP=y + +# +# Virtual file system +# +CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y +CONFIG_SUPPORT_TERMIOS=y # # Wear Levelling diff --git a/variants/alksesp32/pins_arduino.h b/variants/alksesp32/pins_arduino.h new file mode 100644 index 00000000000..31a237198fe --- /dev/null +++ b/variants/alksesp32/pins_arduino.h @@ -0,0 +1,85 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +#define ALKSESP32 // tell library to not map pins again + +static const uint8_t LED_BUILTIN = 23; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t D0 = 40; +static const uint8_t D1 = 41; +static const uint8_t D2 = 15; +static const uint8_t D3 = 2; +static const uint8_t D4 = 0; +static const uint8_t D5 = 4; +static const uint8_t D6 = 16; +static const uint8_t D7 = 17; +static const uint8_t D8 = 5; +static const uint8_t D9 = 18; +static const uint8_t D10 = 19; +static const uint8_t D11 = 21; +static const uint8_t D12 = 22; +static const uint8_t D13 = 23; + +static const uint8_t A0 = 32; +static const uint8_t A1 = 33; +static const uint8_t A2 = 25; +static const uint8_t A3 = 26; +static const uint8_t A4 = 27; +static const uint8_t A5 = 14; +static const uint8_t A6 = 12; +static const uint8_t A7 = 15; + +static const uint8_t L_R = 22; +static const uint8_t L_G = 17; +static const uint8_t L_Y = 23; +static const uint8_t L_B = 5; +static const uint8_t L_RGB_R = 4; +static const uint8_t L_RGB_G = 21; +static const uint8_t L_RGB_B = 16; + +static const uint8_t SW1 = 15; +static const uint8_t SW2 = 2; +static const uint8_t SW3 = 0; + +static const uint8_t POT1 = 32; +static const uint8_t POT2 = 33; + +static const uint8_t PIEZO1 = 19; +static const uint8_t PIEZO2 = 18; + +static const uint8_t PHOTO = 25; + +static const uint8_t DHT_PIN = 26; + +static const uint8_t S1 = 4; +static const uint8_t S2 = 16; +static const uint8_t S3 = 18; +static const uint8_t S4 = 19; +static const uint8_t S5 = 21; + +static const uint8_t SDA = 27; +static const uint8_t SCL = 14; + +static const uint8_t SS = 19; +static const uint8_t MOSI = 21; +static const uint8_t MISO = 22; +static const uint8_t SCK = 23; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/bpi-bit/pins_arduino.h b/variants/bpi-bit/pins_arduino.h new file mode 100644 index 00000000000..2a317a9abf9 --- /dev/null +++ b/variants/bpi-bit/pins_arduino.h @@ -0,0 +1,62 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p) < 20) ? (esp32_adc2gpio[(p)]) : -1) +#define digitalPinToInterrupt(p) (((p) < 40) ? (p) : -1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t BUZZER = 25; + +static const uint8_t BUTTON_A = 35; +static const uint8_t BUTTON_B = 27; + +static const uint8_t RGB_LED = 4; + +static const uint8_t LIGHT_SENSOR1 = 36; +static const uint8_t LIGHT_SENSOR2 = 39; + +static const uint8_t TEMPERATURE_SENSOR = 34; + +static const uint8_t MPU9250_INT = 0; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t P0 = 25; +static const uint8_t P1 = 32; +static const uint8_t P2 = 33; +static const uint8_t P3 = 13; +static const uint8_t P4 = 15; +static const uint8_t P5 = 35; +static const uint8_t P6 = 12; +static const uint8_t P7 = 14; +static const uint8_t P8 = 16; +static const uint8_t P9 = 17; +static const uint8_t P10 = 26; +static const uint8_t P11 = 27; +static const uint8_t P12 = 2; +static const uint8_t P13 = 18; +static const uint8_t P14 = 19; +static const uint8_t P15 = 23; +static const uint8_t P16 = 5; +static const uint8_t P19 = 22; +static const uint8_t P20 = 21; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/d-duino-32/pins_arduino.h b/variants/d-duino-32/pins_arduino.h new file mode 100644 index 00000000000..19a1eb91a16 --- /dev/null +++ b/variants/d-duino-32/pins_arduino.h @@ -0,0 +1,64 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 5; +static const uint8_t SCL = 4; + +static const uint8_t SS = 15; +static const uint8_t MOSI = 13; +static const uint8_t MISO = 12; +static const uint8_t SCK = 14; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +// Wemos Grove Shield +static const uint8_t D1 = 5; +static const uint8_t D2 = 4; +static const uint8_t D3 = 0; +static const uint8_t D4 = 2; +static const uint8_t D5 = 14; +static const uint8_t D6 = 12; +static const uint8_t D7 = 13; +static const uint8_t D8 = 15; +static const uint8_t D9 = 3; +static const uint8_t D10 = 1; + +// OLed +static const uint8_t OLED_SCL = SCL; +static const uint8_t OLED_SDA = SDA; + +#endif /* Pins_Arduino_h */ diff --git a/variants/d1_mini32/pins_arduino.h b/variants/d1_mini32/pins_arduino.h new file mode 100644 index 00000000000..757adf14149 --- /dev/null +++ b/variants/d1_mini32/pins_arduino.h @@ -0,0 +1,33 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include +#include <../d32/d32_core.h> + +static const uint8_t LED_BUILTIN = 2; +#define BUILTIN_LED LED_BUILTIN // backward compatibility +static const uint8_t _VBAT = 35; // battery voltage + +#define PIN_WIRE_SDA SDA // backward compatibility +#define PIN_WIRE_SCL SCL // backward compatibility + +static const uint8_t D0 = 26; +static const uint8_t D1 = 22; +static const uint8_t D2 = 21; +static const uint8_t D3 = 17; +static const uint8_t D4 = 16; +static const uint8_t D5 = 18; +static const uint8_t D6 = 19; +static const uint8_t D7 = 23; +static const uint8_t D8 = 5; +static const uint8_t RXD = 3; +static const uint8_t TXD = 1; + +#define PIN_SPI_SS SS // backward compatibility +#define PIN_SPI_MOSI MOSI // backward compatibility +#define PIN_SPI_MISO MISO // backward compatibility +#define PIN_SPI_SCK SCK // backward compatibility + +#define PIN_A0 A0 // backward compatibility + +#endif /* Pins_Arduino_h */ diff --git a/variants/d32/d32_core.h b/variants/d32/d32_core.h new file mode 100644 index 00000000000..787d08c2006 --- /dev/null +++ b/variants/d32/d32_core.h @@ -0,0 +1,54 @@ +#ifndef _D32_CORE_H_ +#define _D32_CORE_H_ + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif \ No newline at end of file diff --git a/variants/d32/pins_arduino.h b/variants/d32/pins_arduino.h new file mode 100644 index 00000000000..065cef91ea8 --- /dev/null +++ b/variants/d32/pins_arduino.h @@ -0,0 +1,11 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include +#include + +static const uint8_t LED_BUILTIN = 5; +#define BUILTIN_LED LED_BUILTIN // backward compatibility +static const uint8_t _VBAT = 35; // battery voltage + +#endif /* Pins_Arduino_h */ diff --git a/variants/d32_pro/pins_arduino.h b/variants/d32_pro/pins_arduino.h new file mode 100644 index 00000000000..3be2efcaa9a --- /dev/null +++ b/variants/d32_pro/pins_arduino.h @@ -0,0 +1,21 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include +#include <../d32/d32_core.h> + +static const uint8_t LED_BUILTIN = 5; +#define BUILTIN_LED LED_BUILTIN // backward compatibility +static const uint8_t _VBAT = 35; // battery voltage + + +#define TF_CS 4 // TF (Micro SD Card) CS pin +#define TS_CS 12 // Touch Screen CS pin +#define TFT_CS 14 // TFT CS pin +#define TFT_LED 32 // TFT backlight control pin +#define TFT_RST 33 // TFT reset pin +#define TFT_DC 27 // TFT DC pin + +#define SS TF_CS + +#endif /* Pins_Arduino_h */ diff --git a/variants/esp32-devkit-lipo/pins_arduino.h b/variants/esp32-devkit-lipo/pins_arduino.h new file mode 100644 index 00000000000..a405e764c6a --- /dev/null +++ b/variants/esp32-devkit-lipo/pins_arduino.h @@ -0,0 +1,62 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +#define TX1 33 // Ext1 pin 8 +#define RX1 25 // Ext1 pin 9 + +#define TX2 19 // Ext2 pin 8 +#define RX2 18 // Ext2 pin 9 + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/esp32-evb/pins_arduino.h b/variants/esp32-evb/pins_arduino.h index 1153c77c8fd..15fa98e2496 100644 --- a/variants/esp32-evb/pins_arduino.h +++ b/variants/esp32-evb/pins_arduino.h @@ -17,6 +17,9 @@ static const uint8_t KEY_BUILTIN = 34; static const uint8_t TX = 1; static const uint8_t RX = 3; +#define TX1 4 +#define RX1 36 + static const uint8_t SDA = 13; static const uint8_t SCL = 16; diff --git a/variants/esp32-gateway/pins_arduino.h b/variants/esp32-gateway/pins_arduino.h index 19c21ec9f46..fda309271fb 100644 --- a/variants/esp32-gateway/pins_arduino.h +++ b/variants/esp32-gateway/pins_arduino.h @@ -11,11 +11,24 @@ #define digitalPinToInterrupt(p) (((p)<40)?(p):-1) #define digitalPinHasPWM(p) (p < 34) +#if ARDUINO_ESP32_GATEWAY >= 'D' +#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT +#define ETH_PHY_POWER 5 +#endif + static const uint8_t LED_BUILTIN = 33; #define BUILTIN_LED LED_BUILTIN // backward compatibility static const uint8_t KEY_BUILTIN = 34; +static const uint8_t SCL = 16; // This is extention pin 11 +static const uint8_t SDA = 32; // This is extention pin 13 + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + static const uint8_t TX = 1; static const uint8_t RX = 3; @@ -26,4 +39,8 @@ static const uint8_t A7 = 35; static const uint8_t T9 = 32; +#if ARDUINO_ESP32_GATEWAY >= 'F' +#define BOARD_HAS_1BIT_SDMMC +#endif + #endif /* Pins_Arduino_h */ diff --git a/variants/esp32-poe-iso/pins_arduino.h b/variants/esp32-poe-iso/pins_arduino.h new file mode 100644 index 00000000000..1ab04a7578b --- /dev/null +++ b/variants/esp32-poe-iso/pins_arduino.h @@ -0,0 +1,38 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT +#define ETH_PHY_POWER 12 + +static const uint8_t KEY_BUILTIN = 34; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +#define TX1 4 +#define RX1 36 + +#define TX2 33 // ext2 pin 5 +#define RX2 35 // ext2 pin 3 + +static const uint8_t SDA = 13; +static const uint8_t SCL = 16; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 2; +static const uint8_t MISO = 15; +static const uint8_t SCK = 14; + +#define BOARD_HAS_1BIT_SDMMC + +#endif /* Pins_Arduino_h */ diff --git a/variants/esp32-poe/pins_arduino.h b/variants/esp32-poe/pins_arduino.h new file mode 100644 index 00000000000..1ab04a7578b --- /dev/null +++ b/variants/esp32-poe/pins_arduino.h @@ -0,0 +1,38 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT +#define ETH_PHY_POWER 12 + +static const uint8_t KEY_BUILTIN = 34; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +#define TX1 4 +#define RX1 36 + +#define TX2 33 // ext2 pin 5 +#define RX2 35 // ext2 pin 3 + +static const uint8_t SDA = 13; +static const uint8_t SCL = 16; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 2; +static const uint8_t MISO = 15; +static const uint8_t SCK = 14; + +#define BOARD_HAS_1BIT_SDMMC + +#endif /* Pins_Arduino_h */ diff --git a/variants/feather_esp32/pins_arduino.h b/variants/feather_esp32/pins_arduino.h index f952a83ef07..a94befc322e 100644 --- a/variants/feather_esp32/pins_arduino.h +++ b/variants/feather_esp32/pins_arduino.h @@ -17,10 +17,13 @@ static const uint8_t LED_BUILTIN = 13; static const uint8_t TX = 17; static const uint8_t RX = 16; +#define TX1 TX +#define RX1 RX + static const uint8_t SDA = 23; static const uint8_t SCL = 22; -static const uint8_t SS = 2; +static const uint8_t SS = 33; static const uint8_t MOSI = 18; static const uint8_t MISO = 19; static const uint8_t SCK = 5; diff --git a/variants/fm-devkit/pins_arduino.h b/variants/fm-devkit/pins_arduino.h new file mode 100644 index 00000000000..2302dd9f67e --- /dev/null +++ b/variants/fm-devkit/pins_arduino.h @@ -0,0 +1,53 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +// IO +static const uint8_t LED_BUILTIN = 5; +static const uint8_t SW1 = 4; +static const uint8_t SW2 = 18; +static const uint8_t SW3 = 19; +static const uint8_t SW4 = 21; + +//I2S DAC +static const uint8_t I2S_MCLK = 2; // CLOCK must be an integer multiplier of SCLK +static const uint8_t I2S_LRCLK = 25; // LRCLK +static const uint8_t I2S_SCLK = 26; // SCLK - Fs (44100 Hz) +static const uint8_t I2S_DOUT = 22; // DATA + +//GPIO +static const uint8_t D0 = 34; // GPI - Input Only +static const uint8_t D1 = 35; // GPI - Input Only +static const uint8_t D2 = 32; // GPO - Output Only +static const uint8_t D3 = 33; // GPO - Output Only +static const uint8_t D4 = 27; +static const uint8_t D5 = 14; +static const uint8_t D6 = 12; +static const uint8_t D7 = 13; +static const uint8_t D8 = 15; +static const uint8_t D9 = 23; +static const uint8_t D10 = 0; + +// I2C BUS, 2k2 hardware pull-ups +static const uint8_t SDA = 16; +static const uint8_t SCL = 17; + +// SPI - unused but you can create your own definition in your sketch +static const int8_t SCK = -1; +static const int8_t MISO = -1; +static const int8_t MOSI = -1; +static const int8_t SS = -1; + +#endif /* Pins_Arduino_h */ diff --git a/variants/frog32/pins_arduino.h b/variants/frog32/pins_arduino.h new file mode 100644 index 00000000000..d50715e5c91 --- /dev/null +++ b/variants/frog32/pins_arduino.h @@ -0,0 +1,56 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/gpy/pins_arduino.h b/variants/gpy/pins_arduino.h new file mode 100644 index 00000000000..affd7f5571f --- /dev/null +++ b/variants/gpy/pins_arduino.h @@ -0,0 +1,74 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 18 + +#define analogInputToDigitalPin(p) (((p)<40)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +// Sequans Monarch LTE Cat M1/NB1 modem +// NOTE: The Pycom pinout as well as spec sheet block diagram / pin details +// incorrectly list the LTE pins. The correct pins are defined in the source and CSV +// at https://github.com/pycom/pycom-micropython-sigfox/tree/master/esp32/boards/GPY. +#define LTE_CTS 18 // GPIO18 - Sequans modem CTS +#define LTE_RTS 19 // GPIO19 - Sequans modem RTS (pull low to communicate) +#define LTE_RX 23 // GPIO23 - Sequans modem RX +#define LTE_TX 5 // GPIO5 - Sequans modem TX +#define LTE_WAKE 27 // GPIO27 - Sequans modem wake-up interrupt +#define LTE_BAUD 921600 + +static const uint8_t LED_BUILTIN = 0; // ->2812 RGB !!! +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +#define ANT_SELECT 21 // GPIO21 - WiFi external / internal antenna switch + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 12; +static const uint8_t SCL = 13; + +static const uint8_t SS = 17; +static const uint8_t MOSI = 22; +static const uint8_t MISO = 37; +static const uint8_t SCK = 13; + +static const uint8_t A0 = 36; +static const uint8_t A1 = 37; +static const uint8_t A2 = 38; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/heltec_wifi_kit_32/pins_arduino.h b/variants/heltec_wifi_kit_32/pins_arduino.h index e22d01e8905..c17574a46f5 100644 --- a/variants/heltec_wifi_kit_32/pins_arduino.h +++ b/variants/heltec_wifi_kit_32/pins_arduino.h @@ -1,64 +1,74 @@ -#ifndef Pins_Arduino_h -#define Pins_Arduino_h - -#include - -#define EXTERNAL_NUM_INTERRUPTS 16 -#define NUM_DIGITAL_PINS 40 -#define NUM_ANALOG_INPUTS 16 - -#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) -#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) -#define digitalPinHasPWM(p) (p < 34) - -static const uint8_t LED_BUILTIN = 25; -#define BUILTIN_LED LED_BUILTIN // backward compatibility - -static const uint8_t KEY_BUILTIN = 0; - -static const uint8_t TX = 1; -static const uint8_t RX = 3; - -static const uint8_t SDA = 21; -static const uint8_t SCL = 22; - -static const uint8_t SS = 5; -static const uint8_t MOSI = 23; -static const uint8_t MISO = 19; -static const uint8_t SCK = 18; - -static const uint8_t A0 = 36; -static const uint8_t A1 = 37; -static const uint8_t A2 = 38; -static const uint8_t A3 = 39; -static const uint8_t A4 = 32; -static const uint8_t A5 = 33; -static const uint8_t A6 = 34; -static const uint8_t A7 = 35; - -static const uint8_t A10 = 4; -static const uint8_t A11 = 0; -static const uint8_t A12 = 2; -static const uint8_t A13 = 15; -static const uint8_t A14 = 13; -static const uint8_t A15 = 12; -static const uint8_t A16 = 14; -static const uint8_t A17 = 27; -static const uint8_t A18 = 25; -static const uint8_t A19 = 26; - -static const uint8_t T0 = 4; -static const uint8_t T1 = 0; -static const uint8_t T2 = 2; -static const uint8_t T3 = 15; -static const uint8_t T4 = 13; -static const uint8_t T5 = 12; -static const uint8_t T6 = 14; -static const uint8_t T7 = 27; -static const uint8_t T8 = 33; -static const uint8_t T9 = 32; - -static const uint8_t DAC1 = 25; -static const uint8_t DAC2 = 26; - -#endif /* Pins_Arduino_h */ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define WIFI_Kit_32 true +#define DISPLAY_HEIGHT 64 +#define DISPLAY_WIDTH 128 + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 25; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t KEY_BUILTIN = 0; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t A0 = 36; +static const uint8_t A1 = 37; +static const uint8_t A2 = 38; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; + +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t Vext = 21; +static const uint8_t LED = 25; +static const uint8_t RST_OLED = 16; +static const uint8_t SCL_OLED = 15; +static const uint8_t SDA_OLED = 4; + +#endif /* Pins_Arduino_h */ diff --git a/variants/heltec_wifi_lora_32/pins_arduino.h b/variants/heltec_wifi_lora_32/pins_arduino.h index 8f21df4fb0c..b8f466ec703 100644 --- a/variants/heltec_wifi_lora_32/pins_arduino.h +++ b/variants/heltec_wifi_lora_32/pins_arduino.h @@ -1,64 +1,76 @@ -#ifndef Pins_Arduino_h -#define Pins_Arduino_h - -#include - -#define EXTERNAL_NUM_INTERRUPTS 16 -#define NUM_DIGITAL_PINS 40 -#define NUM_ANALOG_INPUTS 16 - -#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) -#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) -#define digitalPinHasPWM(p) (p < 34) - -static const uint8_t LED_BUILTIN = 25; -#define BUILTIN_LED LED_BUILTIN // backward compatibility - -static const uint8_t KEY_BUILTIN = 0; - -static const uint8_t TX = 1; -static const uint8_t RX = 3; - -static const uint8_t SDA = 21; -static const uint8_t SCL = 22; - -static const uint8_t SS = 18; -static const uint8_t MOSI = 27; -static const uint8_t MISO = 19; -static const uint8_t SCK = 5; - -static const uint8_t A0 = 36; -static const uint8_t A1 = 37; -static const uint8_t A2 = 38; -static const uint8_t A3 = 39; -static const uint8_t A4 = 32; -static const uint8_t A5 = 33; -static const uint8_t A6 = 34; -static const uint8_t A7 = 35; - -static const uint8_t A10 = 4; -static const uint8_t A11 = 0; -static const uint8_t A12 = 2; -static const uint8_t A13 = 15; -static const uint8_t A14 = 13; -static const uint8_t A15 = 12; -static const uint8_t A16 = 14; -static const uint8_t A17 = 27; -static const uint8_t A18 = 25; -static const uint8_t A19 = 26; - -static const uint8_t T0 = 4; -static const uint8_t T1 = 0; -static const uint8_t T2 = 2; -static const uint8_t T3 = 15; -static const uint8_t T4 = 13; -static const uint8_t T5 = 12; -static const uint8_t T6 = 14; -static const uint8_t T7 = 27; -static const uint8_t T8 = 32; -static const uint8_t T9 = 33; - -static const uint8_t DAC1 = 26; -static const uint8_t DAC2 = 25; - -#endif /* Pins_Arduino_h */ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define WIFI_LoRa_32 +#define DISPLAY_HEIGHT 64 +#define DISPLAY_WIDTH 128 + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 25; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t KEY_BUILTIN = 0; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 18; +static const uint8_t MOSI = 27; +static const uint8_t MISO = 19; +static const uint8_t SCK = 5; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t Vext = 21; +static const uint8_t LED = 25; +static const uint8_t RST_OLED = 16; +static const uint8_t SCL_OLED = 15; +static const uint8_t SDA_OLED = 4; +static const uint8_t RST_LoRa = 14; +static const uint8_t DIO0 = 26; +static const uint8_t DIO1 = 33; +static const uint8_t DIO2 = 32; + + +#endif /* Pins_Arduino_h */ diff --git a/variants/heltec_wifi_lora_32_V2/pins_arduino.h b/variants/heltec_wifi_lora_32_V2/pins_arduino.h new file mode 100644 index 00000000000..1881f02f89d --- /dev/null +++ b/variants/heltec_wifi_lora_32_V2/pins_arduino.h @@ -0,0 +1,76 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define WIFI_LoRa_32_V2 +#define DISPLAY_HEIGHT 64 +#define DISPLAY_WIDTH 128 + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 25; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t KEY_BUILTIN = 0; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 18; +static const uint8_t MOSI = 27; +static const uint8_t MISO = 19; +static const uint8_t SCK = 5; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t Vext = 21; +static const uint8_t LED = 25; +static const uint8_t RST_OLED = 16; +static const uint8_t SCL_OLED = 15; +static const uint8_t SDA_OLED = 4; +static const uint8_t RST_LoRa = 14; +static const uint8_t DIO0 = 26; +static const uint8_t DIO1 = 35; +static const uint8_t DIO2 = 34; + + +#endif /* Pins_Arduino_h */ diff --git a/variants/heltec_wireless_stick/pins_arduino.h b/variants/heltec_wireless_stick/pins_arduino.h new file mode 100644 index 00000000000..5dd199781b9 --- /dev/null +++ b/variants/heltec_wireless_stick/pins_arduino.h @@ -0,0 +1,75 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define Wireless_Stick +#define DISPLAY_HEIGHT 32 +#define DISPLAY_WIDTH 64 + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 25; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t KEY_BUILTIN = 0; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 18; +static const uint8_t MOSI = 27; +static const uint8_t MISO = 19; +static const uint8_t SCK = 5; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t Vext = 21; +static const uint8_t LED = 25; +static const uint8_t RST_OLED = 16; +static const uint8_t SCL_OLED = 15; +static const uint8_t SDA_OLED = 4; +static const uint8_t RST_LoRa = 14; +static const uint8_t DIO0 = 26; +static const uint8_t DIO1 = 35; +static const uint8_t DIO2 = 34; + +#endif /* Pins_Arduino_h */ diff --git a/variants/lopy/pins_arduino.h b/variants/lopy/pins_arduino.h new file mode 100644 index 00000000000..9336576654c --- /dev/null +++ b/variants/lopy/pins_arduino.h @@ -0,0 +1,74 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 18 + +#define analogInputToDigitalPin(p) (((p)<40)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +// SPI LoRa Radio +#define LORA_SCK 5 // GPIO5 - SX1276 SCK +#define LORA_MISO 19 // GPIO19 - SX1276 MISO +#define LORA_MOSI 27 // GPIO27 - SX1276 MOSI +#define LORA_CS 17 // GPIO17 - SX1276 CS +#define LORA_RST 18 // GPIO18 - SX1276 RST +#define LORA_IRQ 23 // GPIO23 - SX1276 IO0 +#define LORA_IO0 LORA_IRQ // alias +#define LORA_IO1 LORA_IRQ // tied by diode to IO0 +#define LORA_IO2 LORA_IRQ // tied by diode to IO0 + +static const uint8_t LED_BUILTIN = 0; // ->2812 RGB !!! +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +#define ANT_SELECT 16 // GPIO16 - External Antenna Switch + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 12; +static const uint8_t SCL = 13; + +static const uint8_t SS = 17; +static const uint8_t MOSI = 22; +static const uint8_t MISO = 37; +static const uint8_t SCK = 13; + +static const uint8_t A0 = 36; +static const uint8_t A1 = 37; +static const uint8_t A2 = 38; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/lopy4/pins_arduino.h b/variants/lopy4/pins_arduino.h new file mode 100644 index 00000000000..70f933ced93 --- /dev/null +++ b/variants/lopy4/pins_arduino.h @@ -0,0 +1,74 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 18 + +#define analogInputToDigitalPin(p) (((p)<40)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +// SPI LoRa Radio +#define LORA_SCK 5 // GPIO5 - SX1276 SCK +#define LORA_MISO 19 // GPIO19 - SX1276 MISO +#define LORA_MOSI 27 // GPIO27 - SX1276 MOSI +#define LORA_CS 18 // GPIO18 - SX1276 CS +#define LORA_IRQ 23 // GPIO23 - SX1276 IO0 +#define LORA_IO0 LORA_IRQ // alias +#define LORA_IO1 LORA_IRQ // tied by diode to IO0 +#define LORA_IO2 LORA_IRQ // tied by diode to IO0 +#define LORA_RST NOT_A_PIN + +static const uint8_t LED_BUILTIN = 0; // ->2812 RGB !!! +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +#define ANT_SELECT 21 // GPIO21 - External Antenna Switch + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 12; +static const uint8_t SCL = 13; + +static const uint8_t SS = 18; +static const uint8_t MOSI = 22; +static const uint8_t MISO = 37; +static const uint8_t SCK = 13; + +static const uint8_t A0 = 36; +static const uint8_t A1 = 37; +static const uint8_t A2 = 38; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/m5stack_fire/pins_arduino.h b/variants/m5stack_fire/pins_arduino.h new file mode 100644 index 00000000000..5912a1c35c6 --- /dev/null +++ b/variants/m5stack_fire/pins_arduino.h @@ -0,0 +1,52 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 20 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t G23 = 23; +static const uint8_t G19 = 19; +static const uint8_t G18 = 18; +static const uint8_t G3 = 3; +static const uint8_t G16 = 16; +static const uint8_t G21 = 21; +static const uint8_t G2 = 2; +static const uint8_t G12 = 12; +static const uint8_t G15 = 15; +static const uint8_t G35 = 35; +static const uint8_t G36 = 36; +static const uint8_t G25 = 25; +static const uint8_t G26 = 26; +static const uint8_t G1 = 1; +static const uint8_t G17 = 17; +static const uint8_t G22 = 22; +static const uint8_t G5 = 5; +static const uint8_t G13 = 13; +static const uint8_t G0 = 0; +static const uint8_t G34 = 34; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t ADC1 = 35; +static const uint8_t ADC2 = 36; + +#endif /* Pins_Arduino_h */ diff --git a/variants/m5stick_c/pins_arduino.h b/variants/m5stick_c/pins_arduino.h new file mode 100644 index 00000000000..048d9b5e50b --- /dev/null +++ b/variants/m5stick_c/pins_arduino.h @@ -0,0 +1,41 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 32; +static const uint8_t SCL = 33; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 15; +static const uint8_t MISO = 36; +static const uint8_t SCK = 13; + +static const uint8_t G9 = 9; +static const uint8_t G10 = 10; +static const uint8_t G37 = 37; +static const uint8_t G39 = 39; +static const uint8_t G32 = 32; +static const uint8_t G33 = 33; +static const uint8_t G26 = 26; +static const uint8_t G36 = 36; +static const uint8_t G0 = 0; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t ADC1 = 35; +static const uint8_t ADC2 = 36; + +#endif /* Pins_Arduino_h */ diff --git a/variants/magicbit/pins_arduino.h b/variants/magicbit/pins_arduino.h new file mode 100644 index 00000000000..3073ade6100 --- /dev/null +++ b/variants/magicbit/pins_arduino.h @@ -0,0 +1,71 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t BUZZER = 25; +static const uint8_t RED_LED = 27; +static const uint8_t YELLOW_LED = 18; +static const uint8_t GREEN_LED = 16; +static const uint8_t BLUE_LED = 17; +static const uint8_t LDR = 36; +static const uint8_t POT = 39; +static const uint8_t RIGHT_PUTTON = 34; +static const uint8_t LEFT_BUTTON = 35; +static const uint8_t MOTOR1A = 27; +static const uint8_t MOTOR1B = 18; +static const uint8_t MOTOR2A = 16; +static const uint8_t MOTOR2B = 17; +static const uint8_t LED_BUILTIN=16; + +#endif /* Pins_Arduino_h */ diff --git a/variants/odroid_esp32/pins_arduino.h b/variants/odroid_esp32/pins_arduino.h new file mode 100644 index 00000000000..301a5c82631 --- /dev/null +++ b/variants/odroid_esp32/pins_arduino.h @@ -0,0 +1,34 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 2; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 15; +static const uint8_t SCL = 4; + +static const uint8_t SS = 22; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t ADC1 = 35; +static const uint8_t ADC2 = 36; + +#endif /* Pins_Arduino_h */ diff --git a/variants/oroca_edubot/pins_arduino.h b/variants/oroca_edubot/pins_arduino.h new file mode 100644 index 00000000000..7ffe17763f0 --- /dev/null +++ b/variants/oroca_edubot/pins_arduino.h @@ -0,0 +1,62 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 13; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t TX = 17; +static const uint8_t RX = 16; + +static const uint8_t SDA = 23; +static const uint8_t SCL = 22; + +static const uint8_t SS = 2; +static const uint8_t MOSI = 18; +static const uint8_t MISO = 19; +static const uint8_t SCK = 5; + + +static const uint8_t A0 = 34; +static const uint8_t A1 = 39; +static const uint8_t A2 = 36; +static const uint8_t A3 = 33; + +static const uint8_t D0 = 4; +static const uint8_t D1 = 16; +static const uint8_t D2 = 17; +static const uint8_t D3 = 22; +static const uint8_t D4 = 23; +static const uint8_t D5 = 5; +static const uint8_t D6 = 18; +static const uint8_t D7 = 19; +static const uint8_t D8 = 33; + +// vbat measure +static const uint8_t VBAT = 35; + + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/sparkfun_lora_gateway_1-channel/pins_arduino.h b/variants/sparkfun_lora_gateway_1-channel/pins_arduino.h new file mode 100755 index 00000000000..0d45940f576 --- /dev/null +++ b/variants/sparkfun_lora_gateway_1-channel/pins_arduino.h @@ -0,0 +1,58 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const int LED_BUILTIN = 17; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 16; +static const uint8_t MOSI = 13; +static const uint8_t MISO = 12; +static const uint8_t SCK = 14; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/t-beam/pins_arduino.h b/variants/t-beam/pins_arduino.h new file mode 100644 index 00000000000..977b6b26734 --- /dev/null +++ b/variants/t-beam/pins_arduino.h @@ -0,0 +1,65 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 20 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +// SPI LoRa Radio +#define LORA_SCK 5 // GPIO5 - SX1276 SCK +#define LORA_MISO 19 // GPIO19 - SX1276 MISO +#define LORA_MOSI 27 // GPIO27 - SX1276 MOSI +#define LORA_CS 18 // GPIO18 - SX1276 CS +#define LORA_RST 23 // GPIO23 - SX1276 RST +#define LORA_IRQ 26 // GPIO26 - SX1276 IO0 +#define LORA_IO0 LORA_IRQ // alias +#define LORA_IO1 33 // GPIO33 - SX1276 IO1 -> wired on pcb AND connected to header pin LORA1 +#define LORA_IO2 32 // GPIO32 - SX1276 IO2 -> wired on pcb AND connected to header pin LORA2 + +static const uint8_t KEY_BUILTIN = 39; + +static const uint8_t LED_BUILTIN = 14; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 18; +static const uint8_t MOSI = 27; +static const uint8_t MISO = 19; +static const uint8_t SCK = 5; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; + +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A14 = 13; +static const uint8_t A16 = 14; +static const uint8_t A18 = 25; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T4 = 13; +static const uint8_t T6 = 14; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; + +#endif /* Pins_Arduino_h */ diff --git a/variants/tinypico/pins_arduino.h b/variants/tinypico/pins_arduino.h new file mode 100644 index 00000000000..617cd9bf92c --- /dev/null +++ b/variants/tinypico/pins_arduino.h @@ -0,0 +1,60 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +static const uint8_t APA_POWER = 13; +static const uint8_t APA_DATA = 2; +static const uint8_t APA_CLK = 12; + +#endif /* Pins_Arduino_h */ diff --git a/variants/ttgo-lora32-v1/pins_arduino.h b/variants/ttgo-lora32-v1/pins_arduino.h new file mode 100644 index 00000000000..11cd3d101e2 --- /dev/null +++ b/variants/ttgo-lora32-v1/pins_arduino.h @@ -0,0 +1,77 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +// I2C OLED Display works with SSD1306 driver +#define OLED_SDA 4 +#define OLED_SCL 15 +#define OLED_RST 16 + +// SPI LoRa Radio +#define LORA_SCK 5 // GPIO5 - SX1276 SCK +#define LORA_MISO 19 // GPIO19 - SX1276 MISO +#define LORA_MOSI 27 // GPIO27 - SX1276 MOSI +#define LORA_CS 18 // GPIO18 - SX1276 CS +#define LORA_RST 14 // GPIO14 - SX1276 RST +#define LORA_IRQ 26 // GPIO26 - SX1276 IRQ (interrupt request) + +static const uint8_t LED_BUILTIN = 2; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t KEY_BUILTIN = 0; + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 18; +static const uint8_t MOSI = 27; +static const uint8_t MISO = 19; +static const uint8_t SCK = 5; + +static const uint8_t A0 = 36; +static const uint8_t A1 = 37; +static const uint8_t A2 = 38; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; + +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/ttgo-t1/pins_arduino.h b/variants/ttgo-t1/pins_arduino.h new file mode 100644 index 00000000000..f68e5fd977f --- /dev/null +++ b/variants/ttgo-t1/pins_arduino.h @@ -0,0 +1,62 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t LED_BUILTIN = 22; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t SDA = 21; +// Despite the many diagrams from TTGO showing SCL on pin 22, due to the on-board LED +// also on this pin it is better to shift to 23 instead to avoid issues. +static const uint8_t SCL = 23; + +// These are the settings used for the on-board SD card slot +static const uint8_t SS = 13; +static const uint8_t MOSI = 15; +static const uint8_t MISO = 2; +static const uint8_t SCK = 14; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/turta_iot_node/pins_arduino.h b/variants/turta_iot_node/pins_arduino.h new file mode 100644 index 00000000000..81292ffac11 --- /dev/null +++ b/variants/turta_iot_node/pins_arduino.h @@ -0,0 +1,73 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 20 +#define NUM_DIGITAL_PINS 21 +#define NUM_ANALOG_INPUTS 9 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +// LED +static const uint8_t LED_BUILTIN = 13; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +// UART +static const uint8_t TX = 10; +static const uint8_t RX = 9; + +// I2C +static const uint8_t SDA = 23; +static const uint8_t SCL = 22; + +// SPI +static const uint8_t SS = 21; +static const uint8_t MOSI = 18; +static const uint8_t MISO = 19; +static const uint8_t SCK = 5; + +// Analog Inputs +static const uint8_t A0 = 4; +static const uint8_t A1 = 25; +static const uint8_t A2 = 26; +static const uint8_t A3 = 27; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A8 = 38; + +// Right side +static const uint8_t T0 = 4; +static const uint8_t T1 = 25; +static const uint8_t T2 = 26; +static const uint8_t T3 = 27; +static const uint8_t T4 = 32; +static const uint8_t T5 = 33; +static const uint8_t T6 = 34; +static const uint8_t T7 = 35; + +// Left side +static const uint8_t T8 = 22; +static const uint8_t T9 = 23; +static const uint8_t T10 = 10; +static const uint8_t T11 = 9; +static const uint8_t T12 = 21; +static const uint8_t T13 = 5; +static const uint8_t T14 = 18; +static const uint8_t T15 = 19; + +// Module +static const uint8_t T16 = 37; +static const uint8_t T17 = 14; +static const uint8_t T18 = 2; +static const uint8_t T19 = 38; + +// DAC +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/twatch/pins_arduino.h b/variants/twatch/pins_arduino.h new file mode 100644 index 00000000000..44570b72693 --- /dev/null +++ b/variants/twatch/pins_arduino.h @@ -0,0 +1,43 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 20 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +// touch screen +#define TP_SDA 14 +#define TP_SCL 15 +#define TP_INT 38 + +// Interrupt IO port +#define RTC_INT 37 +#define APX20X_INT 35 +#define BMA42X_INT1 39 +#define BMA42X_INT2 4 + +//Serial1 Already assigned to GPS LORA +#define TX1 33 +#define RX1 34 + +static const uint8_t KEY_BUILTIN = 36; + +// Already assigned to BMA423 PCF8563 and external extensions +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; +// SPI has been configured as an SD card slot and must be removed when downloading +static const uint8_t SS = 13; +static const uint8_t MOSI = 15; +static const uint8_t MISO = 2; +static const uint8_t SCK = 14; +// Externally programmable IO +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/vintlabsdevkitv1/pins_arduino.h b/variants/vintlabsdevkitv1/pins_arduino.h new file mode 100644 index 00000000000..e9cdd317b10 --- /dev/null +++ b/variants/vintlabsdevkitv1/pins_arduino.h @@ -0,0 +1,69 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 2; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +// PWM Driver pins for PWM Driver board +static const uint8_t PWM0 = 12; +static const uint8_t PWM1 = 13; +static const uint8_t PWM2 = 14; +static const uint8_t PWM3 = 15; +static const uint8_t PWM4 = 16; +static const uint8_t PWM5 = 17; +static const uint8_t PWM6 = 18; +static const uint8_t PWM7 = 19; + +#endif /* Pins_Arduino_h */ diff --git a/variants/wesp32/pins_arduino.h b/variants/wesp32/pins_arduino.h new file mode 100644 index 00000000000..c3790504155 --- /dev/null +++ b/variants/wesp32/pins_arduino.h @@ -0,0 +1,49 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +#define TX1 12 +#define RX1 13 +#define TX2 33 +#define RX2 39 + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SCL = 4; +static const uint8_t SDA = 15; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 32; +static const uint8_t SCK = 18; + +static const uint8_t A0 = 36; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; + +static const uint8_t T0 = 4; +static const uint8_t T2 = 2; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +#define ETH_PHY_ADDR 0 +#define ETH_PHY_POWER -1 +#define ETH_PHY_MDC 16 +#define ETH_PHY_MDIO 17 +#define ETH_PHY_TYPE ETH_PHY_LAN8720 +#define ETH_CLK_MODE ETH_CLOCK_GPIO0_IN + +#endif /* Pins_Arduino_h */ diff --git a/variants/wipy3/pins_arduino.h b/variants/wipy3/pins_arduino.h new file mode 100644 index 00000000000..cfee21dc83f --- /dev/null +++ b/variants/wipy3/pins_arduino.h @@ -0,0 +1,63 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 18 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 0; // ->2812 RGB !!! +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +#define ANT_SELECT 21 // GPIO21 - External Antenna Switch + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 12; +static const uint8_t SCL = 13; + +static const uint8_t SS = 2; +static const uint8_t MOSI = 22; +static const uint8_t MISO = 37; +static const uint8_t SCK = 13; + +static const uint8_t A0 = 36; +static const uint8_t A1 = 37; +static const uint8_t A2 = 38; +static const uint8_t A3 = 39; +static const uint8_t A4 = 32; +static const uint8_t A5 = 33; +static const uint8_t A6 = 34; +static const uint8_t A7 = 35; +static const uint8_t A10 = 4; +static const uint8_t A11 = 0; +static const uint8_t A12 = 2; +static const uint8_t A13 = 15; +static const uint8_t A14 = 13; +static const uint8_t A15 = 12; +static const uint8_t A16 = 14; +static const uint8_t A17 = 27; +static const uint8_t A18 = 25; +static const uint8_t A19 = 26; + +static const uint8_t T0 = 4; +static const uint8_t T1 = 0; +static const uint8_t T2 = 2; +static const uint8_t T3 = 15; +static const uint8_t T4 = 13; +static const uint8_t T5 = 12; +static const uint8_t T6 = 14; +static const uint8_t T7 = 27; +static const uint8_t T8 = 33; +static const uint8_t T9 = 32; + +static const uint8_t DAC1 = 25; +static const uint8_t DAC2 = 26; + +#endif /* Pins_Arduino_h */ diff --git a/variants/xinabox/pins_arduino.h b/variants/xinabox/pins_arduino.h new file mode 100644 index 00000000000..2cb41b91eb3 --- /dev/null +++ b/variants/xinabox/pins_arduino.h @@ -0,0 +1,28 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include + +#define EXTERNAL_NUM_INTERRUPTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 + +#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) +#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) +#define digitalPinHasPWM(p) (p < 34) + +static const uint8_t LED_BUILTIN = 27; +#define BUILTIN_LED LED_BUILTIN // backward compatibility + +static const uint8_t TX = 1; +static const uint8_t RX = 3; + +static const uint8_t SDA = 21; +static const uint8_t SCL = 22; + +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; + +#endif /* Pins_Arduino_h */